DO NOT MERGE ANYWHERE make /data/misc/bluetooth owner to be bluetooth am: 2e06a0ff6e  -s ours
am: 3c31204e68  -s ours

Change-Id: I251108805c58aabdd41f31a015a6760ea36878e0
diff --git a/.clang-format b/.clang-format
new file mode 120000
index 0000000..9b45e0a
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1 @@
+.clang-format-4
\ No newline at end of file
diff --git a/.clang-format-2 b/.clang-format-2
new file mode 100644
index 0000000..aab4665
--- /dev/null
+++ b/.clang-format-2
@@ -0,0 +1,9 @@
+BasedOnStyle: Google
+ColumnLimit: 100
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 2
+PointerAlignment: Left
+TabWidth: 2
+UseTab: Never
+PenaltyExcessCharacter: 32
diff --git a/.clang-format-4 b/.clang-format-4
new file mode 100644
index 0000000..1497447
--- /dev/null
+++ b/.clang-format-4
@@ -0,0 +1,10 @@
+BasedOnStyle: Google
+AccessModifierOffset: -2
+ColumnLimit: 100
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 4
+PointerAlignment: Left
+TabWidth: 4
+UseTab: Never
+PenaltyExcessCharacter: 32
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..c6f6251
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,6 @@
+filegroup {
+    name: "android_filesystem_config_header",
+    srcs: ["include/private/android_filesystem_config.h"],
+}
+
+subdirs = ["*"]
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 5d335b5..5b5eff4 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -56,4 +56,7 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/lmkd_intermediates/import_includes)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libsysutils_intermediates/import_includes)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/grep $(PRODUCT_OUT)/system/bin/toolbox)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/hw/gatekeeper.$(TARGET_DEVICE).so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib64/hw/gatekeeper.$(TARGET_DEVICE).so)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/vendor)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/init.rc)
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
new file mode 100644
index 0000000..c8dbf77
--- /dev/null
+++ b/PREUPLOAD.cfg
@@ -0,0 +1,5 @@
+[Builtin Hooks]
+clang_format = true
+
+[Builtin Hooks Options]
+clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
diff --git a/adb/.clang-format b/adb/.clang-format
deleted file mode 100644
index fc4eb1b..0000000
--- a/adb/.clang-format
+++ /dev/null
@@ -1,13 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-AccessModifierOffset: -2
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/adb/.clang-format b/adb/.clang-format
new file mode 120000
index 0000000..1af4f51
--- /dev/null
+++ b/adb/.clang-format
@@ -0,0 +1 @@
+../.clang-format-4
\ No newline at end of file
diff --git a/adb/Android.mk b/adb/Android.mk
index 8f56d74..e841205 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -18,11 +18,9 @@
     -DADB_REVISION='"$(adb_version)"' \
 
 ADB_COMMON_linux_CFLAGS := \
-    -std=c++14 \
     -Wexit-time-destructors \
 
 ADB_COMMON_darwin_CFLAGS := \
-    -std=c++14 \
     -Wexit-time-destructors \
 
 # Define windows.h and tchar.h Unicode preprocessor symbols so that
@@ -45,21 +43,24 @@
 # get enough of adb in here that we no longer need minadb. https://b/17626262
 LIBADB_SRC_FILES := \
     adb.cpp \
-    adb_auth.cpp \
     adb_io.cpp \
     adb_listeners.cpp \
     adb_trace.cpp \
     adb_utils.cpp \
     fdevent.cpp \
     sockets.cpp \
+    socket_spec.cpp \
+    sysdeps/errno.cpp \
     transport.cpp \
     transport_local.cpp \
     transport_usb.cpp \
 
 LIBADB_TEST_SRCS := \
     adb_io_test.cpp \
+    adb_listeners_test.cpp \
     adb_utils_test.cpp \
     fdevent_test.cpp \
+    socket_spec_test.cpp \
     socket_test.cpp \
     sysdeps_test.cpp \
     sysdeps/stat_test.cpp \
@@ -79,38 +80,57 @@
     $(ADB_COMMON_windows_CFLAGS) \
 
 LIBADB_darwin_SRC_FILES := \
-    get_my_path_darwin.cpp \
     sysdeps_unix.cpp \
-    usb_osx.cpp \
+    client/usb_dispatch.cpp \
+    client/usb_libusb.cpp \
+    client/usb_osx.cpp \
 
 LIBADB_linux_SRC_FILES := \
-    get_my_path_linux.cpp \
     sysdeps_unix.cpp \
-    usb_linux.cpp \
+    client/usb_dispatch.cpp \
+    client/usb_libusb.cpp \
+    client/usb_linux.cpp \
 
 LIBADB_windows_SRC_FILES := \
     sysdeps_win32.cpp \
+    sysdeps/win32/errno.cpp \
     sysdeps/win32/stat.cpp \
-    usb_windows.cpp \
+    client/usb_windows.cpp \
 
 LIBADB_TEST_windows_SRCS := \
+    sysdeps/win32/errno_test.cpp \
     sysdeps_win32_test.cpp \
 
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
+LOCAL_MODULE := libadbd_usb
+LOCAL_CFLAGS := $(LIBADB_CFLAGS) -DADB_HOST=0
+LOCAL_SRC_FILES := daemon/usb.cpp
+
+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 libbase
+
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
 LOCAL_MODULE := libadbd
 LOCAL_CFLAGS := $(LIBADB_CFLAGS) -DADB_HOST=0
 LOCAL_SRC_FILES := \
     $(LIBADB_SRC_FILES) \
-    adb_auth_client.cpp \
+    adbd_auth.cpp \
     jdwp_service.cpp \
-    usb_linux_client.cpp \
 
 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 := libbase
+LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase
+
+LOCAL_WHOLE_STATIC_LIBRARIES := libadbd_usb
 
 include $(BUILD_STATIC_LIBRARY)
 
@@ -124,6 +144,7 @@
 LOCAL_SRC_FILES := \
     $(LIBADB_SRC_FILES) \
     adb_auth_host.cpp \
+    transport_mdns.cpp \
 
 LOCAL_SRC_FILES_darwin := $(LIBADB_darwin_SRC_FILES)
 LOCAL_SRC_FILES_linux := $(LIBADB_linux_SRC_FILES)
@@ -133,7 +154,9 @@
 
 # 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_static libbase
+LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase libmdnssd
+LOCAL_STATIC_LIBRARIES_linux := libusb
+LOCAL_STATIC_LIBRARIES_darwin := libusb
 
 LOCAL_C_INCLUDES_windows := development/host/windows/usb/api/
 LOCAL_MULTILIB := first
@@ -153,7 +176,7 @@
     shell_service_test.cpp \
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
-LOCAL_STATIC_LIBRARIES := libadbd
+LOCAL_STATIC_LIBRARIES := libadbd libcrypto_utils libcrypto libusb libmdnssd
 LOCAL_SHARED_LIBRARIES := liblog libbase libcutils
 include $(BUILD_NATIVE_TEST)
 
@@ -197,15 +220,20 @@
 LOCAL_SHARED_LIBRARIES := libbase
 LOCAL_STATIC_LIBRARIES := \
     libadb \
-    libcrypto_static \
+    libcrypto_utils \
+    libcrypto \
     libcutils \
     libdiagnose_usb \
-    libgmock_host \
+    libmdnssd \
+    libgmock_host
+
+LOCAL_STATIC_LIBRARIES_linux := libusb
+LOCAL_STATIC_LIBRARIES_darwin := libusb
 
 # Set entrypoint to wmain from sysdeps_win32.cpp instead of main
 LOCAL_LDFLAGS_windows := -municode
 LOCAL_LDLIBS_linux := -lrt -ldl -lpthread
-LOCAL_LDLIBS_darwin := -framework CoreFoundation -framework IOKit
+LOCAL_LDLIBS_darwin := -framework CoreFoundation -framework IOKit -lobjc
 LOCAL_LDLIBS_windows := -lws2_32 -luserenv
 LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
 
@@ -213,31 +241,13 @@
 
 include $(BUILD_HOST_NATIVE_TEST)
 
-# adb device tracker (used by ddms) test tool
-# =========================================================
-
-ifeq ($(HOST_OS),linux)
-include $(CLEAR_VARS)
-LOCAL_MODULE := adb_device_tracker_test
-LOCAL_CFLAGS := -DADB_HOST=1 $(LIBADB_CFLAGS)
-LOCAL_CFLAGS_windows := $(LIBADB_windows_CFLAGS)
-LOCAL_CFLAGS_linux := $(LIBADB_linux_CFLAGS)
-LOCAL_CFLAGS_darwin := $(LIBADB_darwin_CFLAGS)
-LOCAL_SRC_FILES := test_track_devices.cpp
-LOCAL_SANITIZE := $(adb_host_sanitize)
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_STATIC_LIBRARIES := libadb libcrypto_static libcutils
-LOCAL_LDLIBS += -lrt -ldl -lpthread
-include $(BUILD_HOST_EXECUTABLE)
-endif
-
 # adb host tool
 # =========================================================
 include $(CLEAR_VARS)
 
 LOCAL_LDLIBS_linux := -lrt -ldl -lpthread
 
-LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
+LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon -lobjc
 
 # Use wmain instead of main
 LOCAL_LDFLAGS_windows := -municode
@@ -279,14 +289,19 @@
 LOCAL_STATIC_LIBRARIES := \
     libadb \
     libbase \
-    libcrypto_static \
+    libcrypto_utils \
+    libcrypto \
     libdiagnose_usb \
     liblog \
+    libmdnssd
 
 # Don't use libcutils on Windows.
 LOCAL_STATIC_LIBRARIES_darwin := libcutils
 LOCAL_STATIC_LIBRARIES_linux := libcutils
 
+LOCAL_STATIC_LIBRARIES_darwin += libusb
+LOCAL_STATIC_LIBRARIES_linux += libusb
+
 LOCAL_CXX_STL := libc++_static
 
 # Don't add anything here, we don't want additional shared dependencies
@@ -312,6 +327,7 @@
 
 LOCAL_SRC_FILES := \
     daemon/main.cpp \
+    daemon/mdns.cpp \
     services.cpp \
     file_sync_service.cpp \
     framebuffer_service.cpp \
@@ -339,23 +355,28 @@
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN)
 LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED)
-LOCAL_C_INCLUDES += system/extras/ext4_utils
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
+LOCAL_STRIP_MODULE := keep_symbols
 LOCAL_STATIC_LIBRARIES := \
     libadbd \
     libbase \
+    libbootloader_message \
     libfs_mgr \
     libfec \
     libfec_rs \
     libselinux \
     liblog \
-    libmincrypt \
-    libext4_utils_static \
+    libext4_utils \
     libsquashfs_utils \
     libcutils \
     libbase \
-    libcrypto_static \
-    libminijail
+    libcrypto_utils \
+    libcrypto \
+    libminijail \
+    libmdnssd \
+    libdebuggerd_handler \
 
 include $(BUILD_EXECUTABLE)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/adb/NOTICE b/adb/NOTICE
index 9ffcc08..ff47c95 100644
--- a/adb/NOTICE
+++ b/adb/NOTICE
@@ -189,3 +189,63 @@
 
    END OF TERMS AND CONDITIONS
 
+------------------------------------------------------------
+libwinpthread license:
+------------------------------------------------------------
+Copyright (c) 2011 mingw-w64 project
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+/*
+ * Parts of this library are derived by:
+ *
+ * Posix Threads library for Microsoft Windows
+ *
+ * Use at own risk, there is no implied warranty to this code.
+ * It uses undocumented features of Microsoft Windows that can change
+ * at any time in the future.
+ *
+ * (C) 2010 Lockless Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of Lockless Inc. nor the names of its contributors may be
+ *    used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
diff --git a/adb/adb.cpp b/adb/adb.cpp
index e0c0503..577e9b9 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -30,13 +30,17 @@
 #include <sys/time.h>
 #include <time.h>
 
+#include <chrono>
 #include <string>
+#include <thread>
 #include <vector>
 
 #include <android-base/errors.h>
+#include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/macros.h>
 #include <android-base/parsenetaddress.h>
+#include <android-base/quick_exit.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 
@@ -46,12 +50,11 @@
 #include "adb_utils.h"
 #include "transport.h"
 
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
-
 #if !ADB_HOST
-#include <cutils/properties.h>
 #include <sys/capability.h>
 #include <sys/mount.h>
+#include <android-base/properties.h>
+using namespace std::chrono_literals;
 #endif
 
 std::string adb_version() {
@@ -65,21 +68,46 @@
 void fatal(const char *fmt, ...) {
     va_list ap;
     va_start(ap, fmt);
-    fprintf(stderr, "error: ");
-    vfprintf(stderr, fmt, ap);
-    fprintf(stderr, "\n");
+    char buf[1024];
+    vsnprintf(buf, sizeof(buf), fmt, ap);
+
+#if ADB_HOST
+    fprintf(stderr, "error: %s\n", buf);
+#else
+    LOG(ERROR) << "error: " << buf;
+#endif
+
     va_end(ap);
-    exit(-1);
+    abort();
 }
 
 void fatal_errno(const char* fmt, ...) {
+    int err = errno;
     va_list ap;
     va_start(ap, fmt);
-    fprintf(stderr, "error: %s: ", strerror(errno));
-    vfprintf(stderr, fmt, ap);
-    fprintf(stderr, "\n");
+    char buf[1024];
+    vsnprintf(buf, sizeof(buf), fmt, ap);
+
+#if ADB_HOST
+    fprintf(stderr, "error: %s: %s\n", buf, strerror(err));
+#else
+    LOG(ERROR) << "error: " << buf << ": " << strerror(err);
+#endif
+
     va_end(ap);
-    exit(-1);
+    abort();
+}
+
+uint32_t calculate_apacket_checksum(const apacket* p) {
+    const unsigned char* x = reinterpret_cast<const unsigned char*>(p->data);
+    uint32_t sum = 0;
+    size_t count = p->msg.data_length;
+
+    while (count-- > 0) {
+        sum += *x++;
+    }
+
+    return sum;
 }
 
 apacket* get_apacket(void)
@@ -188,11 +216,9 @@
         "ro.product.device",
     };
 
-    for (const auto& prop_name : cnxn_props) {
-        char value[PROPERTY_VALUE_MAX];
-        property_get(prop_name, value, "");
-        connection_properties.push_back(
-            android::base::StringPrintf("%s=%s", prop_name, value));
+    for (const auto& prop : cnxn_props) {
+        std::string value = std::string(prop) + "=" + android::base::GetProperty(prop, "");
+        connection_properties.push_back(value);
     }
 #endif
 
@@ -316,8 +342,6 @@
 
 void handle_packet(apacket *p, atransport *t)
 {
-    asocket *s;
-
     D("handle_packet() %c%c%c%c", ((char*) (&(p->msg.command)))[0],
             ((char*) (&(p->msg.command)))[1],
             ((char*) (&(p->msg.command)))[2],
@@ -326,7 +350,7 @@
 
     switch(p->msg.command){
     case A_SYNC:
-        if(p->msg.arg0){
+        if (p->msg.arg0){
             send_packet(p, t);
 #if ADB_HOST
             send_connect(t);
@@ -343,26 +367,31 @@
         break;
 
     case A_AUTH:
-        if (p->msg.arg0 == ADB_AUTH_TOKEN) {
-            t->connection_state = kCsUnauthorized;
-            t->key = adb_auth_nextkey(t->key);
-            if (t->key) {
+        switch (p->msg.arg0) {
+#if ADB_HOST
+            case ADB_AUTH_TOKEN:
+                t->connection_state = kCsUnauthorized;
                 send_auth_response(p->data, p->msg.data_length, t);
-            } else {
-                /* No more private keys to try, send the public key */
-                send_auth_publickey(t);
-            }
-        } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
-            if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
-                adb_auth_verified(t);
-                t->failed_auth_attempts = 0;
-            } else {
-                if (t->failed_auth_attempts++ > 10)
-                    adb_sleep_ms(1000);
-                send_auth_request(t);
-            }
-        } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
-            adb_auth_confirm_key(p->data, p->msg.data_length, t);
+                break;
+#else
+            case ADB_AUTH_SIGNATURE:
+                if (adbd_auth_verify(t->token, sizeof(t->token), p->data, p->msg.data_length)) {
+                    adbd_auth_verified(t);
+                    t->failed_auth_attempts = 0;
+                } else {
+                    if (t->failed_auth_attempts++ > 256) std::this_thread::sleep_for(1s);
+                    send_auth_request(t);
+                }
+                break;
+
+            case ADB_AUTH_RSAPUBLICKEY:
+                adbd_auth_confirm_key(p->data, p->msg.data_length, t);
+                break;
+#endif
+            default:
+                t->connection_state = kCsOffline;
+                handle_offline(t);
+                break;
         }
         break;
 
@@ -370,8 +399,8 @@
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
             char *name = (char*) p->data;
             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
-            s = create_local_service_socket(name, t);
-            if(s == 0) {
+            asocket* s = create_local_service_socket(name, t);
+            if (s == nullptr) {
                 send_close(0, p->msg.arg0, t);
             } else {
                 s->peer = create_remote_socket(p->msg.arg0, t);
@@ -384,7 +413,8 @@
 
     case A_OKAY: /* READY(local-id, remote-id, "") */
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, 0))) {
+            asocket* s = find_local_socket(p->msg.arg1, 0);
+            if (s) {
                 if(s->peer == 0) {
                     /* On first READY message, create the connection. */
                     s->peer = create_remote_socket(p->msg.arg0, t);
@@ -408,7 +438,8 @@
 
     case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
         if (t->online && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
+            asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
+            if (s) {
                 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
                  * a failed OPEN only. However, due to a bug in previous ADB
                  * versions, CLOSE(0, remote-id, "") was also used for normal
@@ -431,11 +462,12 @@
 
     case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
+            asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
+            if (s) {
                 unsigned rid = p->msg.arg0;
                 p->len = p->msg.data_length;
 
-                if(s->enqueue(s, p) == 0) {
+                if (s->enqueue(s, p) == 0) {
                     D("Enqueue the socket");
                     send_ready(s->id, rid, t);
                 }
@@ -605,8 +637,7 @@
 
 #endif
 
-int launch_server(int server_port)
-{
+int launch_server(const std::string& socket_spec) {
 #if defined(_WIN32)
     /* we need to start the server in the background                    */
     /* we create a PIPE that will be used to wait for the server's "OK" */
@@ -709,9 +740,8 @@
     }
 
     WCHAR   args[64];
-    snwprintf(args, arraysize(args),
-              L"adb -P %d fork-server server --reply-fd %d", server_port,
-              ack_write_as_int);
+    snwprintf(args, arraysize(args), L"adb -L %s fork-server server --reply-fd %d",
+              socket_spec.c_str(), ack_write_as_int);
 
     PROCESS_INFORMATION   pinfo;
     ZeroMemory(&pinfo, sizeof(pinfo));
@@ -838,30 +868,29 @@
         return -1;
     }
 #else /* !defined(_WIN32) */
-    char    path[PATH_MAX];
-    int     fd[2];
-
     // set up a pipe so the child can tell us when it is ready.
     // fd[0] will be parent's end, and the child will write on fd[1]
+    int fd[2];
     if (pipe(fd)) {
         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
         return -1;
     }
-    get_my_path(path, PATH_MAX);
+
+    std::string path = android::base::GetExecutablePath();
+
     pid_t pid = fork();
-    if(pid < 0) return -1;
+    if (pid < 0) return -1;
 
     if (pid == 0) {
         // child side of the fork
 
         adb_close(fd[0]);
 
-        char str_port[30];
-        snprintf(str_port, sizeof(str_port), "%d", server_port);
         char reply_fd[30];
         snprintf(reply_fd, sizeof(reply_fd), "%d", fd[1]);
         // child process
-        int result = execl(path, "adb", "-P", str_port, "fork-server", "server", "--reply-fd", reply_fd, NULL);
+        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);
     } else  {
@@ -954,18 +983,25 @@
 
         std::string error;
         InstallStatus r;
+        int resolved_tcp_port = 0;
         if (kill_forward) {
             r = remove_listener(pieces[0].c_str(), transport);
         } else {
-            r = install_listener(pieces[0], pieces[1].c_str(), transport,
-                                 no_rebind, &error);
+            r = install_listener(pieces[0], pieces[1].c_str(), transport, no_rebind,
+                                 &resolved_tcp_port, &error);
         }
         if (r == INSTALL_STATUS_OK) {
 #if ADB_HOST
-            /* On the host: 1st OKAY is connect, 2nd OKAY is status */
+            // On the host: 1st OKAY is connect, 2nd OKAY is status.
             SendOkay(reply_fd);
 #endif
             SendOkay(reply_fd);
+
+            // If a TCP port was resolved, send the actual port number back.
+            if (resolved_tcp_port != 0) {
+                SendProtocolString(reply_fd, android::base::StringPrintf("%d", resolved_tcp_port));
+            }
+
             return 1;
         }
 
@@ -1012,7 +1048,7 @@
         // may not read the OKAY sent above.
         adb_shutdown(reply_fd);
 
-        exit(0);
+        android::base::quick_exit(0);
     }
 
 #if ADB_HOST
@@ -1057,6 +1093,31 @@
         return 1;
     }
 
+    if (!strcmp(service, "reconnect-offline")) {
+        std::string response;
+        close_usb_devices([&response](const atransport* transport) {
+            switch (transport->connection_state) {
+                case kCsOffline:
+                case kCsUnauthorized:
+                    response += "reconnecting ";
+                    if (transport->serial) {
+                        response += transport->serial;
+                    } else {
+                        response += "<unknown>";
+                    }
+                    response += "\n";
+                    return true;
+                default:
+                    return false;
+            }
+        });
+        if (!response.empty()) {
+            response.resize(response.size() - 1);
+        }
+        SendOkay(reply_fd, response);
+        return 0;
+    }
+
     if (!strcmp(service, "features")) {
         std::string error;
         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
@@ -1068,6 +1129,18 @@
         return 0;
     }
 
+#if ADB_HOST
+    if (!strcmp(service, "host-features")) {
+        FeatureSet features = supported_features();
+        // Abuse features to report libusb status.
+        if (should_use_libusb()) {
+            features.insert(kFeatureLibusb);
+        }
+        SendOkay(reply_fd, FeatureSetToString(features));
+        return 0;
+    }
+#endif
+
     // remove TCP transport
     if (!strncmp(service, "disconnect:", 11)) {
         const std::string address(service + 11);
diff --git a/adb/adb.h b/adb/adb.h
index b1d9896..aea5fb8 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -18,6 +18,7 @@
 #define __ADB_H
 
 #include <limits.h>
+#include <stdint.h>
 #include <sys/types.h>
 
 #include <string>
@@ -27,11 +28,14 @@
 #include "adb_trace.h"
 #include "fdevent.h"
 #include "socket.h"
+#include "usb.h"
 
 constexpr size_t MAX_PAYLOAD_V1 = 4 * 1024;
 constexpr size_t MAX_PAYLOAD_V2 = 256 * 1024;
 constexpr size_t MAX_PAYLOAD = MAX_PAYLOAD_V2;
 
+constexpr size_t LINUX_MAX_SOCKET_SIZE = 4194304;
+
 #define A_SYNC 0x434e5953
 #define A_CNXN 0x4e584e43
 #define A_OPEN 0x4e45504f
@@ -50,31 +54,32 @@
 std::string adb_version();
 
 // Increment this when we want to force users to start a new adb server.
-#define ADB_SERVER_VERSION 36
+#define ADB_SERVER_VERSION 39
 
 class atransport;
-struct usb_handle;
 
 struct amessage {
-    unsigned command;       /* command identifier constant      */
-    unsigned arg0;          /* first argument                   */
-    unsigned arg1;          /* second argument                  */
-    unsigned data_length;   /* length of payload (0 is allowed) */
-    unsigned data_check;    /* checksum of data payload         */
-    unsigned magic;         /* command ^ 0xffffffff             */
+    uint32_t command;     /* command identifier constant      */
+    uint32_t arg0;        /* first argument                   */
+    uint32_t arg1;        /* second argument                  */
+    uint32_t data_length; /* length of payload (0 is allowed) */
+    uint32_t data_check;  /* checksum of data payload         */
+    uint32_t magic;       /* command ^ 0xffffffff             */
 };
 
 struct apacket
 {
     apacket *next;
 
-    unsigned len;
-    unsigned char *ptr;
+    size_t len;
+    char* ptr;
 
     amessage msg;
-    unsigned char data[MAX_PAYLOAD];
+    char data[MAX_PAYLOAD];
 };
 
+uint32_t calculate_apacket_checksum(const apacket* packet);
+
 /* the adisconnect structure is used to record a callback that
 ** will be called whenever a transport is disconnected (e.g. by the user)
 ** this should be used to cleanup objects that depend on the
@@ -116,29 +121,6 @@
     kCsUnauthorized,
 };
 
-/* A listener is an entity which binds to a local port
-** and, upon receiving a connection on that port, creates
-** an asocket to connect the new local connection to a
-** specific remote service.
-**
-** TODO: some listeners read from the new connection to
-** determine what exact service to connect to on the far
-** side.
-*/
-struct alistener
-{
-    alistener *next;
-    alistener *prev;
-
-    fdevent fde;
-    int fd;
-
-    char *local_name;
-    char *connect_to;
-    atransport *transport;
-    adisconnect  disconnect;
-};
-
 
 void print_packet(const char *label, apacket *p);
 
@@ -149,9 +131,8 @@
 
 void handle_packet(apacket *p, atransport *t);
 
-void get_my_path(char *s, size_t maxLen);
-int launch_server(int server_port);
-int adb_server_main(int is_daemon, int server_port, int ack_reply_fd);
+int launch_server(const std::string& socket_spec);
+int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply_fd);
 
 /* initialize a transport object's func pointers and state */
 #if ADB_HOST
@@ -213,21 +194,9 @@
 
 
 void local_init(int port);
-void local_connect(int port);
+bool local_connect(int port);
 int  local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error);
 
-// USB host/client interface.
-void usb_init();
-int usb_write(usb_handle *h, const void *data, int len);
-int usb_read(usb_handle *h, void *data, int len);
-int usb_close(usb_handle *h);
-void usb_kick(usb_handle *h);
-
-// USB device detection.
-#if ADB_HOST
-int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol);
-#endif
-
 ConnectionState connection_state(atransport *t);
 
 extern const char* adb_device_banner;
@@ -239,8 +208,6 @@
 #define CHUNK_SIZE (64*1024)
 
 #if !ADB_HOST
-#define USB_ADB_PATH     "/dev/android_adb"
-
 #define USB_FFS_ADB_PATH  "/dev/usb-ffs/adb/"
 #define USB_FFS_ADB_EP(x) USB_FFS_ADB_PATH#x
 
diff --git a/adb/adb_auth.cpp b/adb/adb_auth.cpp
deleted file mode 100644
index 1ffab09..0000000
--- a/adb/adb_auth.cpp
+++ /dev/null
@@ -1,95 +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.
- */
-
-#define TRACE_TAG ADB
-
-#include "sysdeps.h"
-#include "adb_auth.h"
-
-#include <errno.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "adb.h"
-#include "transport.h"
-
-bool auth_required = true;
-
-void send_auth_request(atransport *t)
-{
-    D("Calling send_auth_request");
-    apacket *p;
-    int ret;
-
-    ret = adb_auth_generate_token(t->token, sizeof(t->token));
-    if (ret != sizeof(t->token)) {
-        D("Error generating token ret=%d", ret);
-        return;
-    }
-
-    p = get_apacket();
-    memcpy(p->data, t->token, ret);
-    p->msg.command = A_AUTH;
-    p->msg.arg0 = ADB_AUTH_TOKEN;
-    p->msg.data_length = ret;
-    send_packet(p, t);
-}
-
-void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
-{
-    D("Calling send_auth_response");
-    apacket *p = get_apacket();
-    int ret;
-
-    ret = adb_auth_sign(t->key, token, token_size, p->data);
-    if (!ret) {
-        D("Error signing the token");
-        put_apacket(p);
-        return;
-    }
-
-    p->msg.command = A_AUTH;
-    p->msg.arg0 = ADB_AUTH_SIGNATURE;
-    p->msg.data_length = ret;
-    send_packet(p, t);
-}
-
-void send_auth_publickey(atransport *t)
-{
-    D("Calling send_auth_publickey");
-    apacket *p = get_apacket();
-    int ret;
-
-    ret = adb_auth_get_userkey(p->data, MAX_PAYLOAD_V1);
-    if (!ret) {
-        D("Failed to get user public key");
-        put_apacket(p);
-        return;
-    }
-
-    p->msg.command = A_AUTH;
-    p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
-    p->msg.data_length = ret;
-    send_packet(p, t);
-}
-
-void adb_auth_verified(atransport *t)
-{
-    handle_online(t);
-    send_connect(t);
-}
diff --git a/adb/adb_auth.h b/adb/adb_auth.h
index a13604a..a6f224f 100644
--- a/adb/adb_auth.h
+++ b/adb/adb_auth.h
@@ -19,14 +19,10 @@
 
 #include "adb.h"
 
-extern bool auth_required;
+#include <deque>
+#include <memory>
 
-int adb_auth_keygen(const char* filename);
-void adb_auth_verified(atransport *t);
-
-void send_auth_request(atransport *t);
-void send_auth_response(uint8_t *token, size_t token_size, atransport *t);
-void send_auth_publickey(atransport *t);
+#include <openssl/rsa.h>
 
 /* AUTH packets first argument */
 /* Request */
@@ -37,30 +33,26 @@
 
 #if ADB_HOST
 
-void adb_auth_init(void);
-int adb_auth_sign(void *key, const unsigned char* token, size_t token_size,
-                  unsigned char* sig);
-void *adb_auth_nextkey(void *current);
-int adb_auth_get_userkey(unsigned char *data, size_t len);
+void adb_auth_init();
 
-static inline int adb_auth_generate_token(void *token, size_t token_size) { return 0; }
-static inline int adb_auth_verify(void *token, void *sig, int siglen) { return 0; }
-static inline void adb_auth_confirm_key(unsigned char *data, size_t len, atransport *t) { }
+int adb_auth_keygen(const char* filename);
+std::string adb_auth_get_userkey();
+std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys();
+
+void send_auth_response(const char* token, size_t token_size, atransport* t);
 
 #else // !ADB_HOST
 
-static inline int adb_auth_sign(void* key, const unsigned char* token,
-                                size_t token_size, unsigned char* sig) {
-    return 0;
-}
-static inline void *adb_auth_nextkey(void *current) { return NULL; }
-static inline int adb_auth_get_userkey(unsigned char *data, size_t len) { return 0; }
+extern bool auth_required;
 
 void adbd_auth_init(void);
+void adbd_auth_verified(atransport *t);
+
 void adbd_cloexec_auth_socket();
-int adb_auth_generate_token(void *token, size_t token_size);
-int adb_auth_verify(uint8_t* token, uint8_t* sig, int siglen);
-void adb_auth_confirm_key(unsigned char *data, size_t len, atransport *t);
+bool adbd_auth_verify(const char* token, size_t token_size, const char* sig, int sig_len);
+void adbd_auth_confirm_key(const char* data, size_t len, atransport* t);
+
+void send_auth_request(atransport *t);
 
 #endif // ADB_HOST
 
diff --git a/adb/adb_auth_client.cpp b/adb/adb_auth_client.cpp
deleted file mode 100644
index 128c3df..0000000
--- a/adb/adb_auth_client.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define TRACE_TAG AUTH
-
-#include "sysdeps.h"
-#include "adb_auth.h"
-
-#include <resolv.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "cutils/list.h"
-#include "cutils/sockets.h"
-#include "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-
-#include "adb.h"
-#include "fdevent.h"
-#include "transport.h"
-
-struct adb_public_key {
-    struct listnode node;
-    RSAPublicKey key;
-};
-
-static const char *key_paths[] = {
-    "/adb_keys",
-    "/data/misc/adb/adb_keys",
-    NULL
-};
-
-static fdevent listener_fde;
-static fdevent framework_fde;
-static int framework_fd = -1;
-
-static void usb_disconnected(void* unused, atransport* t);
-static struct adisconnect usb_disconnect = { usb_disconnected, nullptr};
-static atransport* usb_transport;
-static bool needs_retry = false;
-
-static void read_keys(const char *file, struct listnode *list)
-{
-    FILE *f;
-    char buf[MAX_PAYLOAD_V1];
-    char *sep;
-    int ret;
-
-    f = fopen(file, "re");
-    if (!f) {
-        D("Can't open '%s'", file);
-        return;
-    }
-
-    while (fgets(buf, sizeof(buf), f)) {
-        /* Allocate 4 extra bytes to decode the base64 data in-place */
-        auto key = reinterpret_cast<adb_public_key*>(
-            calloc(1, sizeof(adb_public_key) + 4));
-        if (key == nullptr) {
-            D("Can't malloc key");
-            break;
-        }
-
-        sep = strpbrk(buf, " \t");
-        if (sep)
-            *sep = '\0';
-
-        ret = __b64_pton(buf, (u_char *)&key->key, sizeof(key->key) + 4);
-        if (ret != sizeof(key->key)) {
-            D("%s: Invalid base64 data ret=%d", file, ret);
-            free(key);
-            continue;
-        }
-
-        if (key->key.len != RSANUMWORDS) {
-            D("%s: Invalid key len %d", file, key->key.len);
-            free(key);
-            continue;
-        }
-
-        list_add_tail(list, &key->node);
-    }
-
-    fclose(f);
-}
-
-static void free_keys(struct listnode *list)
-{
-    struct listnode *item;
-
-    while (!list_empty(list)) {
-        item = list_head(list);
-        list_remove(item);
-        free(node_to_item(item, struct adb_public_key, node));
-    }
-}
-
-static void load_keys(struct listnode *list)
-{
-    const char* path;
-    const char** paths = key_paths;
-    struct stat buf;
-
-    list_init(list);
-
-    while ((path = *paths++)) {
-        if (!stat(path, &buf)) {
-            D("Loading keys from '%s'", path);
-            read_keys(path, list);
-        }
-    }
-}
-
-int adb_auth_generate_token(void *token, size_t token_size)
-{
-    FILE *f;
-    int ret;
-
-    f = fopen("/dev/urandom", "re");
-    if (!f)
-        return 0;
-
-    ret = fread(token, token_size, 1, f);
-
-    fclose(f);
-    return ret * token_size;
-}
-
-int adb_auth_verify(uint8_t* token, uint8_t* sig, int siglen)
-{
-    struct listnode *item;
-    struct listnode key_list;
-    int ret = 0;
-
-    if (siglen != RSANUMBYTES)
-        return 0;
-
-    load_keys(&key_list);
-
-    list_for_each(item, &key_list) {
-        adb_public_key* key = node_to_item(item, struct adb_public_key, node);
-        ret = RSA_verify(&key->key, sig, siglen, token, SHA_DIGEST_SIZE);
-        if (ret)
-            break;
-    }
-
-    free_keys(&key_list);
-
-    return ret;
-}
-
-static void usb_disconnected(void* unused, atransport* t) {
-    D("USB disconnect");
-    usb_transport = NULL;
-    needs_retry = false;
-}
-
-static void framework_disconnected() {
-    D("Framework disconnect");
-    fdevent_remove(&framework_fde);
-    framework_fd = -1;
-}
-
-static void adb_auth_event(int fd, unsigned events, void*) {
-    char response[2];
-    int ret;
-
-    if (events & FDE_READ) {
-        ret = unix_read(fd, response, sizeof(response));
-        if (ret <= 0) {
-            framework_disconnected();
-        } else if (ret == 2 && response[0] == 'O' && response[1] == 'K') {
-            if (usb_transport) {
-                adb_auth_verified(usb_transport);
-            }
-        }
-    }
-}
-
-void adb_auth_confirm_key(unsigned char *key, size_t len, atransport *t)
-{
-    char msg[MAX_PAYLOAD_V1];
-    int ret;
-
-    if (!usb_transport) {
-        usb_transport = t;
-        t->AddDisconnect(&usb_disconnect);
-    }
-
-    if (framework_fd < 0) {
-        D("Client not connected");
-        needs_retry = true;
-        return;
-    }
-
-    if (key[len - 1] != '\0') {
-        D("Key must be a null-terminated string");
-        return;
-    }
-
-    ret = snprintf(msg, sizeof(msg), "PK%s", key);
-    if (ret >= (signed)sizeof(msg)) {
-        D("Key too long. ret=%d", ret);
-        return;
-    }
-    D("Sending '%s'", msg);
-
-    ret = unix_write(framework_fd, msg, ret);
-    if (ret < 0) {
-        D("Failed to write PK, errno=%d", errno);
-        return;
-    }
-}
-
-static void adb_auth_listener(int fd, unsigned events, void* data) {
-    sockaddr_storage addr;
-    socklen_t alen;
-    int s;
-
-    alen = sizeof(addr);
-
-    s = adb_socket_accept(fd, reinterpret_cast<sockaddr*>(&addr), &alen);
-    if (s < 0) {
-        D("Failed to accept: errno=%d", errno);
-        return;
-    }
-
-    if (framework_fd >= 0) {
-        LOG(WARNING) << "adb received framework auth socket connection again";
-        framework_disconnected();
-    }
-
-    framework_fd = s;
-    fdevent_install(&framework_fde, framework_fd, adb_auth_event, nullptr);
-    fdevent_add(&framework_fde, FDE_READ);
-
-    if (needs_retry) {
-        needs_retry = false;
-        send_auth_request(usb_transport);
-    }
-}
-
-void adbd_cloexec_auth_socket() {
-    int fd = android_get_control_socket("adbd");
-    if (fd == -1) {
-        D("Failed to get adbd socket");
-        return;
-    }
-    fcntl(fd, F_SETFD, FD_CLOEXEC);
-}
-
-void adbd_auth_init(void) {
-    int fd = android_get_control_socket("adbd");
-    if (fd == -1) {
-        D("Failed to get adbd socket");
-        return;
-    }
-
-    if (listen(fd, 4) == -1) {
-        D("Failed to listen on '%d'", fd);
-        return;
-    }
-
-    fdevent_install(&listener_fde, fd, adb_auth_listener, NULL);
-    fdevent_add(&listener_fde, FDE_READ);
-}
diff --git a/adb/adb_auth_host.cpp b/adb/adb_auth_host.cpp
index 7b6671d..365bf77 100644
--- a/adb/adb_auth_host.cpp
+++ b/adb/adb_auth_host.cpp
@@ -16,211 +16,107 @@
 
 #define TRACE_TAG AUTH
 
-#include "sysdeps.h"
-#include "adb_auth.h"
-#include "adb_utils.h"
-
+#include <dirent.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#if defined(__linux__)
+#include <sys/inotify.h>
+#endif
 
-#include "adb.h"
-
-/* HACK: we need the RSAPublicKey struct
- * but RSA_verify conflits with openssl */
-#define RSA_verify RSA_verify_mincrypt
-#include "mincrypt/rsa.h"
-#undef RSA_verify
+#include <map>
+#include <mutex>
+#include <set>
+#include <string>
 
 #include <android-base/errors.h>
+#include <android-base/file.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <cutils/list.h>
-
+#include <crypto_utils/android_pubkey.h>
+#include <openssl/base64.h>
 #include <openssl/evp.h>
 #include <openssl/objects.h>
 #include <openssl/pem.h>
 #include <openssl/rsa.h>
 #include <openssl/sha.h>
 
-#if defined(OPENSSL_IS_BORINGSSL)
-#include <openssl/base64.h>
+#include "adb.h"
+#include "adb_auth.h"
+#include "adb_utils.h"
+#include "sysdeps.h"
+#include "transport.h"
+
+static std::mutex& g_keys_mutex = *new std::mutex;
+static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
+    *new std::map<std::string, std::shared_ptr<RSA>>;
+static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
+
+static std::string get_user_info() {
+    LOG(INFO) << "get_user_info...";
+
+    std::string hostname;
+    if (getenv("HOSTNAME")) hostname = getenv("HOSTNAME");
+#if !defined(_WIN32)
+    char buf[64];
+    if (hostname.empty() && gethostname(buf, sizeof(buf)) != -1) hostname = buf;
 #endif
+    if (hostname.empty()) hostname = "unknown";
 
-#define ANDROID_PATH   ".android"
-#define ADB_KEY_FILE   "adbkey"
-
-struct adb_private_key {
-    struct listnode node;
-    RSA *rsa;
-};
-
-static struct listnode key_list;
-
-
-/* Convert OpenSSL RSA private key to android pre-computed RSAPublicKey format */
-static int RSA_to_RSAPublicKey(RSA *rsa, RSAPublicKey *pkey)
-{
-    int ret = 1;
-    unsigned int i;
-
-    BN_CTX* ctx = BN_CTX_new();
-    BIGNUM* r32 = BN_new();
-    BIGNUM* rr = BN_new();
-    BIGNUM* r = BN_new();
-    BIGNUM* rem = BN_new();
-    BIGNUM* n = BN_new();
-    BIGNUM* n0inv = BN_new();
-
-    if (RSA_size(rsa) != RSANUMBYTES) {
-        ret = 0;
-        goto out;
-    }
-
-    BN_set_bit(r32, 32);
-    BN_copy(n, rsa->n);
-    BN_set_bit(r, RSANUMWORDS * 32);
-    BN_mod_sqr(rr, r, n, ctx);
-    BN_div(NULL, rem, n, r32, ctx);
-    BN_mod_inverse(n0inv, rem, r32, ctx);
-
-    pkey->len = RSANUMWORDS;
-    pkey->n0inv = 0 - BN_get_word(n0inv);
-    for (i = 0; i < RSANUMWORDS; i++) {
-        BN_div(rr, rem, rr, r32, ctx);
-        pkey->rr[i] = BN_get_word(rem);
-        BN_div(n, rem, n, r32, ctx);
-        pkey->n[i] = BN_get_word(rem);
-    }
-    pkey->exponent = BN_get_word(rsa->e);
-
-out:
-    BN_free(n0inv);
-    BN_free(n);
-    BN_free(rem);
-    BN_free(r);
-    BN_free(rr);
-    BN_free(r32);
-    BN_CTX_free(ctx);
-
-    return ret;
-}
-
-static void get_user_info(char *buf, size_t len)
-{
-    char hostname[1024], username[1024];
-    int ret = -1;
-
-    if (getenv("HOSTNAME") != NULL) {
-        strncpy(hostname, getenv("HOSTNAME"), sizeof(hostname));
-        hostname[sizeof(hostname)-1] = '\0';
-        ret = 0;
-    }
-
-#ifndef _WIN32
-    if (ret < 0)
-        ret = gethostname(hostname, sizeof(hostname));
-#endif
-    if (ret < 0)
-        strcpy(hostname, "unknown");
-
-    ret = -1;
-
-    if (getenv("LOGNAME") != NULL) {
-        strncpy(username, getenv("LOGNAME"), sizeof(username));
-        username[sizeof(username)-1] = '\0';
-        ret = 0;
-    }
-
+    std::string username;
+    if (getenv("LOGNAME")) username = getenv("LOGNAME");
 #if !defined _WIN32 && !defined ADB_HOST_ON_TARGET
-    if (ret < 0)
-        ret = getlogin_r(username, sizeof(username));
+    if (username.empty() && getlogin()) username = getlogin();
 #endif
-    if (ret < 0)
-        strcpy(username, "unknown");
+    if (username.empty()) hostname = "unknown";
 
-    ret = snprintf(buf, len, " %s@%s", username, hostname);
-    if (ret >= (signed)len)
-        buf[len - 1] = '\0';
+    return " " + username + "@" + hostname;
 }
 
-static int write_public_keyfile(RSA *private_key, const char *private_key_path)
-{
-    RSAPublicKey pkey;
-    FILE *outfile = NULL;
-    char path[PATH_MAX], info[MAX_PAYLOAD_V1];
-    uint8_t* encoded = nullptr;
-    size_t encoded_length;
-    int ret = 0;
+static bool write_public_keyfile(RSA* private_key, const std::string& private_key_path) {
+    LOG(INFO) << "write_public_keyfile...";
 
-    if (snprintf(path, sizeof(path), "%s.pub", private_key_path) >=
-        (int)sizeof(path)) {
-        D("Path too long while writing public key");
-        return 0;
+    uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
+    if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) {
+        LOG(ERROR) << "Failed to convert to public key";
+        return false;
     }
 
-    if (!RSA_to_RSAPublicKey(private_key, &pkey)) {
-        D("Failed to convert to publickey");
-        return 0;
+    size_t expected_length;
+    if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
+        LOG(ERROR) << "Public key too large to base64 encode";
+        return false;
     }
 
-    outfile = fopen(path, "w");
-    if (!outfile) {
-        D("Failed to open '%s'", path);
-        return 0;
+    std::string content;
+    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();
+
+    std::string path(private_key_path + ".pub");
+    if (!android::base::WriteStringToFile(content, path)) {
+        PLOG(ERROR) << "Failed to write public key to '" << path << "'";
+        return false;
     }
 
-    D("Writing public key to '%s'", path);
-
-#if defined(OPENSSL_IS_BORINGSSL)
-    if (!EVP_EncodedLength(&encoded_length, sizeof(pkey))) {
-        D("Public key too large to base64 encode");
-        goto out;
-    }
-#else
-    /* While we switch from OpenSSL to BoringSSL we have to implement
-     * |EVP_EncodedLength| here. */
-    encoded_length = 1 + ((sizeof(pkey) + 2) / 3 * 4);
-#endif
-
-    encoded = new uint8_t[encoded_length];
-    if (encoded == nullptr) {
-        D("Allocation failure");
-        goto out;
-    }
-
-    encoded_length = EVP_EncodeBlock(encoded, (uint8_t*) &pkey, sizeof(pkey));
-    get_user_info(info, sizeof(info));
-
-    if (fwrite(encoded, encoded_length, 1, outfile) != 1 ||
-        fwrite(info, strlen(info), 1, outfile) != 1) {
-        D("Write error while writing public key");
-        goto out;
-    }
-
-    ret = 1;
-
- out:
-    if (outfile != NULL) {
-        fclose(outfile);
-    }
-    delete[] encoded;
-    return ret;
+    return true;
 }
 
-static int generate_key(const char *file)
-{
-    EVP_PKEY* pkey = EVP_PKEY_new();
-    BIGNUM* exponent = BN_new();
-    RSA* rsa = RSA_new();
+static int generate_key(const std::string& file) {
+    LOG(INFO) << "generate_key(" << file << ")...";
+
     mode_t old_mask;
     FILE *f = NULL;
     int ret = 0;
 
-    D("generate_key '%s'", file);
-
+    EVP_PKEY* pkey = EVP_PKEY_new();
+    BIGNUM* exponent = BN_new();
+    RSA* rsa = RSA_new();
     if (!pkey || !exponent || !rsa) {
-        D("Failed to allocate key");
+        LOG(ERROR) << "Failed to allocate key";
         goto out;
     }
 
@@ -230,9 +126,9 @@
 
     old_mask = umask(077);
 
-    f = fopen(file, "w");
+    f = fopen(file.c_str(), "w");
     if (!f) {
-        D("Failed to open '%s'", file);
+        PLOG(ERROR) << "Failed to open " << file;
         umask(old_mask);
         goto out;
     }
@@ -252,110 +148,166 @@
     ret = 1;
 
 out:
-    if (f)
-        fclose(f);
+    if (f) fclose(f);
     EVP_PKEY_free(pkey);
     RSA_free(rsa);
     BN_free(exponent);
     return ret;
 }
 
-static int read_key(const char *file, struct listnode *list)
-{
-    D("read_key '%s'", file);
+static std::string hash_key(RSA* key) {
+    unsigned char* pubkey = nullptr;
+    int len = i2d_RSA_PUBKEY(key, &pubkey);
+    if (len < 0) {
+        LOG(ERROR) << "failed to encode RSA public key";
+        return std::string();
+    }
 
-    FILE* fp = fopen(file, "r");
+    std::string result;
+    result.resize(SHA256_DIGEST_LENGTH);
+    SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
+    OPENSSL_free(pubkey);
+    return result;
+}
+
+static bool read_key_file(const std::string& file) {
+    LOG(INFO) << "read_key_file '" << file << "'...";
+
+    std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
     if (!fp) {
-        D("Failed to open '%s': %s", file, strerror(errno));
-        return 0;
+        PLOG(ERROR) << "Failed to open '" << file << "'";
+        return false;
     }
 
-    adb_private_key* key = new adb_private_key;
-    key->rsa = RSA_new();
-
-    if (!PEM_read_RSAPrivateKey(fp, &key->rsa, NULL, NULL)) {
-        D("Failed to read key");
-        fclose(fp);
-        RSA_free(key->rsa);
-        delete key;
-        return 0;
+    RSA* key = RSA_new();
+    if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
+        LOG(ERROR) << "Failed to read key";
+        RSA_free(key);
+        return false;
     }
 
-    fclose(fp);
-    list_add_tail(list, &key->node);
-    return 1;
+    std::lock_guard<std::mutex> lock(g_keys_mutex);
+    std::string fingerprint = hash_key(key);
+    if (g_keys.find(fingerprint) != g_keys.end()) {
+        LOG(INFO) << "ignoring already-loaded key: " << file;
+        RSA_free(key);
+    } else {
+        g_keys[fingerprint] = std::shared_ptr<RSA>(key, RSA_free);
+    }
+
+    return true;
 }
 
-static int get_user_keyfilepath(char *filename, size_t len)
-{
-    const std::string home = adb_get_homedir_path(true);
-    D("home '%s'", home.c_str());
+static bool read_keys(const std::string& path, bool allow_dir = true) {
+    LOG(INFO) << "read_keys '" << path << "'...";
 
-    const std::string android_dir =
-            android::base::StringPrintf("%s%c%s", home.c_str(),
-                                        OS_PATH_SEPARATOR, ANDROID_PATH);
+    struct stat st;
+    if (stat(path.c_str(), &st) != 0) {
+        PLOG(ERROR) << "failed to stat '" << path << "'";
+        return false;
+    }
 
-    struct stat buf;
-    if (stat(android_dir.c_str(), &buf)) {
-        if (adb_mkdir(android_dir.c_str(), 0750) < 0) {
-            D("Cannot mkdir '%s'", android_dir.c_str());
-            return -1;
+    if (S_ISREG(st.st_mode)) {
+        return read_key_file(path);
+    } else if (S_ISDIR(st.st_mode)) {
+        if (!allow_dir) {
+            // inotify isn't recursive. It would break expectations to load keys in nested
+            // directories but not monitor them for new keys.
+            LOG(WARNING) << "refusing to recurse into directory '" << path << "'";
+            return false;
         }
+
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
+        if (!dir) {
+            PLOG(ERROR) << "failed to open directory '" << path << "'";
+            return false;
+        }
+
+        bool result = false;
+        while (struct dirent* dent = readdir(dir.get())) {
+            std::string name = dent->d_name;
+
+            // We can't use dent->d_type here because it's not available on Windows.
+            if (name == "." || name == "..") {
+                continue;
+            }
+
+            if (!android::base::EndsWith(name, ".adb_key")) {
+                LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'";
+                continue;
+            }
+
+            result |= read_key_file((path + OS_PATH_SEPARATOR + name));
+        }
+        return result;
     }
 
-    return snprintf(filename, len, "%s%c%s",
-                    android_dir.c_str(), OS_PATH_SEPARATOR, ADB_KEY_FILE);
+    LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
+    return false;
 }
 
-static int get_user_key(struct listnode *list)
-{
-    struct stat buf;
-    char path[PATH_MAX];
-    int ret;
+static std::string get_user_key_path() {
+    return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
+}
 
-    ret = get_user_keyfilepath(path, sizeof(path));
-    if (ret < 0 || ret >= (signed)sizeof(path)) {
-        D("Error getting user key filename");
-        return 0;
+static bool get_user_key() {
+    std::string path = get_user_key_path();
+    if (path.empty()) {
+        PLOG(ERROR) << "Error getting user key filename";
+        return false;
     }
 
-    D("user key '%s'", path);
-
-    if (stat(path, &buf) == -1) {
+    struct stat buf;
+    if (stat(path.c_str(), &buf) == -1) {
+        LOG(INFO) << "User key '" << path << "' does not exist...";
         if (!generate_key(path)) {
-            D("Failed to generate new key");
-            return 0;
+            LOG(ERROR) << "Failed to generate new key";
+            return false;
         }
     }
 
-    return read_key(path, list);
+    return read_key_file(path);
 }
 
-static void get_vendor_keys(struct listnode* key_list) {
+static std::set<std::string> get_vendor_keys() {
     const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
     if (adb_keys_path == nullptr) {
-        return;
+        return std::set<std::string>();
     }
 
+    std::set<std::string> result;
     for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
-        if (!read_key(path.c_str(), key_list)) {
-            D("Failed to read '%s'", path.c_str());
-        }
+        result.emplace(path);
     }
+    return result;
 }
 
-int adb_auth_sign(void *node, const unsigned char* token, size_t token_size,
-                  unsigned char* sig)
-{
-    unsigned int len;
-    struct adb_private_key *key = node_to_item(node, struct adb_private_key, node);
+std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
+    std::deque<std::shared_ptr<RSA>> result;
 
+    // Copy all the currently known keys.
+    std::lock_guard<std::mutex> lock(g_keys_mutex);
+    for (const auto& it : g_keys) {
+        result.push_back(it.second);
+    }
+
+    // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
+    // but try using the public key" (the empty deque could otherwise mean this _or_
+    // that this function hasn't been called yet to request the keys).
+    result.push_back(nullptr);
+
+    return result;
+}
+
+static int adb_auth_sign(RSA* key, const char* token, size_t token_size, char* sig) {
     if (token_size != TOKEN_SIZE) {
         D("Unexpected token size %zd", token_size);
         return 0;
     }
 
-    if (!RSA_sign(NID_sha1, token, token_size, sig, &len, key->rsa)) {
+    unsigned int len;
+    if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
+                  reinterpret_cast<uint8_t*>(sig), &len, key)) {
         return 0;
     }
 
@@ -363,80 +315,167 @@
     return (int)len;
 }
 
-void *adb_auth_nextkey(void *current)
-{
-    struct listnode *item;
-
-    if (list_empty(&key_list))
-        return NULL;
-
-    if (!current)
-        return list_head(&key_list);
-
-    list_for_each(item, &key_list) {
-        if (item == current) {
-            /* current is the last item, we tried all the keys */
-            if (item->next == &key_list)
-                return NULL;
-            return item->next;
-        }
+std::string adb_auth_get_userkey() {
+    std::string path = get_user_key_path();
+    if (path.empty()) {
+        PLOG(ERROR) << "Error getting user key filename";
+        return "";
     }
+    path += ".pub";
 
-    return NULL;
-}
-
-int adb_auth_get_userkey(unsigned char *data, size_t len)
-{
-    char path[PATH_MAX];
-    int ret = get_user_keyfilepath(path, sizeof(path) - 4);
-    if (ret < 0 || ret >= (signed)(sizeof(path) - 4)) {
-        D("Error getting user key filename");
-        return 0;
+    std::string content;
+    if (!android::base::ReadFileToString(path, &content)) {
+        PLOG(ERROR) << "Can't load '" << path << "'";
+        return "";
     }
-    strcat(path, ".pub");
-
-    // TODO(danalbert): ReadFileToString
-    // Note that on Windows, load_file() does not do CR/LF translation, but
-    // ReadFileToString() uses the C Runtime which uses CR/LF translation by
-    // default (by is overridable with _setmode()).
-    unsigned size;
-    char* file_data = reinterpret_cast<char*>(load_file(path, &size));
-    if (file_data == nullptr) {
-        D("Can't load '%s'", path);
-        return 0;
-    }
-
-    if (len < (size_t)(size + 1)) {
-        D("%s: Content too large ret=%d", path, size);
-        free(file_data);
-        return 0;
-    }
-
-    memcpy(data, file_data, size);
-    free(file_data);
-    file_data = nullptr;
-    data[size] = '\0';
-
-    return size + 1;
+    return content;
 }
 
 int adb_auth_keygen(const char* filename) {
     return (generate_key(filename) == 0);
 }
 
-void adb_auth_init(void)
-{
-    int ret;
-
-    D("adb_auth_init");
-
-    list_init(&key_list);
-
-    ret = get_user_key(&key_list);
-    if (!ret) {
-        D("Failed to get user key");
+#if defined(__linux__)
+static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
+    LOG(INFO) << "adb_auth_inotify_update called";
+    if (!(fd_event & FDE_READ)) {
         return;
     }
 
-    get_vendor_keys(&key_list);
+    char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
+    while (true) {
+        ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
+        if (rc == -1) {
+            if (errno == EAGAIN) {
+                LOG(INFO) << "done reading inotify fd";
+                break;
+            }
+            PLOG(FATAL) << "read of inotify event failed";
+        }
+
+        // The read potentially returned multiple events.
+        char* start = buf;
+        char* end = buf + rc;
+
+        while (start < end) {
+            inotify_event* event = reinterpret_cast<inotify_event*>(start);
+            auto root_it = g_monitored_paths.find(event->wd);
+            if (root_it == g_monitored_paths.end()) {
+                LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
+            }
+
+            std::string path = root_it->second;
+            if (event->len > 0) {
+                path += '/';
+                path += event->name;
+            }
+
+            if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
+                if (event->mask & IN_ISDIR) {
+                    LOG(INFO) << "ignoring new directory at '" << path << "'";
+                } else {
+                    LOG(INFO) << "observed new file at '" << path << "'";
+                    read_keys(path, false);
+                }
+            } else {
+                LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
+                             << event->mask;
+            }
+
+            start += sizeof(struct inotify_event) + event->len;
+        }
+    }
+}
+
+static void adb_auth_inotify_init(const std::set<std::string>& paths) {
+    LOG(INFO) << "adb_auth_inotify_init...";
+
+    int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
+    if (infd < 0) {
+        PLOG(ERROR) << "failed to create inotify fd";
+        return;
+    }
+
+    for (const std::string& path : paths) {
+        int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
+        if (wd < 0) {
+            PLOG(ERROR) << "failed to inotify_add_watch on path '" << path;
+            continue;
+        }
+
+        g_monitored_paths[wd] = path;
+        LOG(INFO) << "watch descriptor " << wd << " registered for " << path;
+    }
+
+    fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
+    fdevent_add(event, FDE_READ);
+}
+#endif
+
+void adb_auth_init() {
+    LOG(INFO) << "adb_auth_init...";
+
+    if (!get_user_key()) {
+        LOG(ERROR) << "Failed to get user key";
+        return;
+    }
+
+    const auto& key_paths = get_vendor_keys();
+
+#if defined(__linux__)
+    adb_auth_inotify_init(key_paths);
+#endif
+
+    for (const std::string& path : key_paths) {
+        read_keys(path.c_str());
+    }
+}
+
+static void send_auth_publickey(atransport* t) {
+    LOG(INFO) << "Calling send_auth_publickey";
+
+    std::string key = adb_auth_get_userkey();
+    if (key.empty()) {
+        D("Failed to get user public key");
+        return;
+    }
+
+    if (key.size() >= MAX_PAYLOAD_V1) {
+        D("User public key too large (%zu B)", key.size());
+        return;
+    }
+
+    apacket* p = get_apacket();
+    memcpy(p->data, key.c_str(), key.size() + 1);
+
+    p->msg.command = A_AUTH;
+    p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
+
+    // adbd expects a null-terminated string.
+    p->msg.data_length = key.size() + 1;
+    send_packet(p, t);
+}
+
+void send_auth_response(const char* token, size_t token_size, atransport* t) {
+    std::shared_ptr<RSA> key = t->NextKey();
+    if (key == nullptr) {
+        // No more private keys to try, send the public key.
+        send_auth_publickey(t);
+        return;
+    }
+
+    LOG(INFO) << "Calling send_auth_response";
+    apacket* p = get_apacket();
+
+    int ret = adb_auth_sign(key.get(), token, token_size, p->data);
+    if (!ret) {
+        D("Error signing the token");
+        put_apacket(p);
+        return;
+    }
+
+    p->msg.command = A_AUTH;
+    p->msg.arg0 = ADB_AUTH_SIGNATURE;
+    p->msg.data_length = ret;
+    send_packet(p, t);
 }
diff --git a/adb/adb_client.cpp b/adb/adb_client.cpp
index a27dd47..ef52189 100644
--- a/adb/adb_client.cpp
+++ b/adb/adb_client.cpp
@@ -29,6 +29,7 @@
 #include <sys/types.h>
 
 #include <string>
+#include <thread>
 #include <vector>
 
 #include <android-base/stringprintf.h>
@@ -37,36 +38,24 @@
 
 #include "adb_io.h"
 #include "adb_utils.h"
+#include "socket_spec.h"
+#include "sysdeps/chrono.h"
 
 static TransportType __adb_transport = kTransportAny;
 static const char* __adb_serial = NULL;
 
-static int __adb_server_port = DEFAULT_ADB_PORT;
-static const char* __adb_server_name = NULL;
+static const char* __adb_server_socket_spec;
 
-void adb_set_transport(TransportType type, const char* serial)
-{
+void adb_set_transport(TransportType type, const char* serial) {
     __adb_transport = type;
     __adb_serial = serial;
 }
 
-void adb_get_transport(TransportType* type, const char** serial) {
-    if (type) {
-        *type = __adb_transport;
+void adb_set_socket_spec(const char* socket_spec) {
+    if (__adb_server_socket_spec) {
+        LOG(FATAL) << "attempted to reinitialize adb_server_socket_spec " << socket_spec << " (was " << __adb_server_socket_spec << ")";
     }
-    if (serial) {
-        *serial = __adb_serial;
-    }
-}
-
-void adb_set_tcp_specifics(int server_port)
-{
-    __adb_server_port = server_port;
-}
-
-void adb_set_tcp_name(const char* hostname)
-{
-    __adb_server_name = hostname;
+    __adb_server_socket_spec = socket_spec;
 }
 
 static int switch_socket_transport(int fd, std::string* error) {
@@ -139,23 +128,12 @@
         return -1;
     }
 
-    int fd;
     std::string reason;
-    if (__adb_server_name) {
-        fd = network_connect(__adb_server_name, __adb_server_port, SOCK_STREAM, 0, &reason);
-        if (fd == -1) {
-            *error = android::base::StringPrintf("can't connect to %s:%d: %s",
-                                                 __adb_server_name, __adb_server_port,
-                                                 reason.c_str());
-            return -2;
-        }
-    } else {
-        fd = network_loopback_client(__adb_server_port, SOCK_STREAM, &reason);
-        if (fd == -1) {
-            *error = android::base::StringPrintf("cannot connect to daemon: %s",
-                                                 reason.c_str());
-            return -2;
-        }
+    int fd = socket_spec_connect(__adb_server_socket_spec, &reason);
+    if (fd < 0) {
+        *error = android::base::StringPrintf("cannot connect to daemon at %s: %s",
+                                             __adb_server_socket_spec, reason.c_str());
+        return -2;
     }
 
     if ((memcmp(&service[0],"host",4) != 0 || service == "host:reconnect") &&
@@ -185,15 +163,14 @@
     int fd = _adb_connect("host:version", error);
 
     D("adb_connect: service %s", service.c_str());
-    if (fd == -2 && __adb_server_name) {
+    if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) {
         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 on port %d *\n",
-                __adb_server_port);
+        fprintf(stdout, "* daemon not running. starting it now at %s *\n", __adb_server_socket_spec);
     start_server:
-        if (launch_server(__adb_server_port)) {
+        if (launch_server(__adb_server_socket_spec)) {
             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()
@@ -203,8 +180,8 @@
         } else {
             fprintf(stdout,"* daemon started successfully *\n");
         }
-        /* give the server some time to start properly and detect devices */
-        adb_sleep_ms(3000);
+        // Give the server some time to start properly and detect devices.
+        std::this_thread::sleep_for(3s);
         // fall through to _adb_connect
     } else {
         // If a server is already running, check its version matches.
@@ -249,7 +226,7 @@
             }
 
             /* XXX can we better detect its death? */
-            adb_sleep_ms(2000);
+            std::this_thread::sleep_for(2s);
             goto start_server;
         }
     }
diff --git a/adb/adb_client.h b/adb/adb_client.h
index 9f9eb1f..d07c1e9 100644
--- a/adb/adb_client.h
+++ b/adb/adb_client.h
@@ -40,14 +40,9 @@
 // Set the preferred transport to connect to.
 void adb_set_transport(TransportType type, const char* _Nullable serial);
 
-// Get the preferred transport to connect to.
-void adb_get_transport(TransportType* _Nullable type, const char* _Nullable* _Nullable serial);
-
-// Set TCP specifics of the transport to use.
-void adb_set_tcp_specifics(int server_port);
-
-// Set TCP Hostname of the transport to use.
-void adb_set_tcp_name(const char* _Nullable hostname);
+// Set the socket specification for the adb server.
+// This function can only be called once, and the argument must live to the end of the process.
+void adb_set_socket_spec(const char* _Nonnull socket_spec);
 
 // Send commands to the current emulator instance. Will fail if there is not
 // exactly one emulator connected (or if you use -s <serial> with a <serial>
diff --git a/adb/adb_io.cpp b/adb/adb_io.cpp
index ae16834..ca8729e 100644
--- a/adb/adb_io.cpp
+++ b/adb/adb_io.cpp
@@ -20,6 +20,8 @@
 
 #include <unistd.h>
 
+#include <thread>
+
 #include <android-base/stringprintf.h>
 
 #include "adb.h"
@@ -104,7 +106,7 @@
         if (r == -1) {
             D("writex: fd=%d error %d: %s", fd, errno, strerror(errno));
             if (errno == EAGAIN) {
-                adb_sleep_ms(1); // just yield some cpu time
+                std::this_thread::yield();
                 continue;
             } else if (errno == EPIPE) {
                 D("writex: fd=%d disconnected", fd);
diff --git a/adb/adb_io_test.cpp b/adb/adb_io_test.cpp
index 21a82e8..611b239 100644
--- a/adb/adb_io_test.cpp
+++ b/adb/adb_io_test.cpp
@@ -37,7 +37,13 @@
 // fds far from the range that open() returns. But all of that might defeat the
 // purpose of the tests.
 
-TEST(io, ReadFdExactly_whole) {
+#if defined(_WIN32)
+#define POSIX_TEST(x,y) TEST(DISABLED_ ## x,y)
+#else
+#define POSIX_TEST TEST
+#endif
+
+POSIX_TEST(io, ReadFdExactly_whole) {
   const char expected[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -51,7 +57,7 @@
   EXPECT_STREQ(expected, buf);
 }
 
-TEST(io, ReadFdExactly_eof) {
+POSIX_TEST(io, ReadFdExactly_eof) {
   const char expected[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -65,7 +71,7 @@
   EXPECT_EQ(0, errno) << strerror(errno);
 }
 
-TEST(io, ReadFdExactly_partial) {
+POSIX_TEST(io, ReadFdExactly_partial) {
   const char input[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -82,7 +88,7 @@
   EXPECT_STREQ(expected.c_str(), buf);
 }
 
-TEST(io, WriteFdExactly_whole) {
+POSIX_TEST(io, WriteFdExactly_whole) {
   const char expected[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -97,7 +103,7 @@
   EXPECT_STREQ(expected, s.c_str());
 }
 
-TEST(io, WriteFdExactly_partial) {
+POSIX_TEST(io, WriteFdExactly_partial) {
   const char buf[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -114,7 +120,7 @@
   EXPECT_EQ(expected, s);
 }
 
-TEST(io, WriteFdExactly_ENOSPC) {
+POSIX_TEST(io, WriteFdExactly_ENOSPC) {
     int fd = open("/dev/full", O_WRONLY);
     ASSERT_NE(-1, fd);
 
@@ -123,7 +129,7 @@
     ASSERT_EQ(ENOSPC, errno);
 }
 
-TEST(io, WriteFdExactly_string) {
+POSIX_TEST(io, WriteFdExactly_string) {
   const char str[] = "Foobar";
   TemporaryFile tf;
   ASSERT_NE(-1, tf.fd);
@@ -137,7 +143,7 @@
   EXPECT_STREQ(str, s.c_str());
 }
 
-TEST(io, WriteFdFmt) {
+POSIX_TEST(io, WriteFdFmt) {
     TemporaryFile tf;
     ASSERT_NE(-1, tf.fd);
 
diff --git a/adb/adb_listeners.cpp b/adb/adb_listeners.cpp
index e8c2338..18b1492 100644
--- a/adb/adb_listeners.cpp
+++ b/adb/adb_listeners.cpp
@@ -20,24 +20,56 @@
 #include <stdlib.h>
 
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <cutils/sockets.h>
 
+#include "socket_spec.h"
 #include "sysdeps.h"
 #include "transport.h"
 
-int gListenAll = 0; /* Not static because it is used in commandline.c. */
+// A listener is an entity which binds to a local port and, upon receiving a connection on that
+// port, creates an asocket to connect the new local connection to a specific remote service.
+//
+// TODO: some listeners read from the new connection to determine what exact service to connect to
+// on the far side.
+class alistener {
+  public:
+    alistener(const std::string& _local_name, const std::string& _connect_to);
+    ~alistener();
 
-static alistener listener_list = {
-    .next = &listener_list,
-    .prev = &listener_list,
+    fdevent fde;
+    int fd = -1;
+
+    std::string local_name;
+    std::string connect_to;
+    atransport* transport = nullptr;
+    adisconnect disconnect;
+
+  private:
+    DISALLOW_COPY_AND_ASSIGN(alistener);
 };
 
+alistener::alistener(const std::string& _local_name, const std::string& _connect_to)
+    : local_name(_local_name), connect_to(_connect_to) {
+}
+
+alistener::~alistener() {
+    // Closes the corresponding fd.
+    fdevent_remove(&fde);
+
+    if (transport) {
+        transport->RemoveDisconnect(&disconnect);
+    }
+}
+
+// listener_list retains ownership of all created alistener objects. Removing an alistener from
+// this list will cause it to be deleted.
+typedef std::list<std::unique_ptr<alistener>> ListenerList;
+static ListenerList& listener_list = *new ListenerList();
+
 static void ss_listener_event_func(int _fd, unsigned ev, void *_l) {
     if (ev & FDE_READ) {
-        sockaddr_storage ss;
-        sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
-        socklen_t alen = sizeof(ss);
-        int fd = adb_socket_accept(_fd, addrp, &alen);
+        int fd = adb_socket_accept(_fd, nullptr, nullptr);
         if (fd < 0) return;
 
         int rcv_buf_size = CHUNK_SIZE;
@@ -59,13 +91,7 @@
     asocket *s;
 
     if (ev & FDE_READ) {
-        sockaddr_storage ss;
-        sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
-        socklen_t alen;
-        int fd;
-
-        alen = sizeof(ss);
-        fd = adb_socket_accept(_fd, addrp, &alen);
+        int fd = adb_socket_accept(_fd, nullptr, nullptr);
         if (fd < 0) {
             return;
         }
@@ -73,7 +99,7 @@
         s = create_local_socket(fd);
         if (s) {
             s->transport = listener->transport;
-            connect_to_remote(s, listener->connect_to);
+            connect_to_remote(s, listener->connect_to.c_str());
             return;
         }
 
@@ -81,66 +107,21 @@
     }
 }
 
-static void free_listener(alistener*  l)
-{
-    if (l->next) {
-        l->next->prev = l->prev;
-        l->prev->next = l->next;
-        l->next = l->prev = l;
-    }
-
-    // closes the corresponding fd
-    fdevent_remove(&l->fde);
-
-    if (l->local_name)
-        free((char*)l->local_name);
-
-    if (l->connect_to)
-        free((char*)l->connect_to);
-
-    if (l->transport) {
-        l->transport->RemoveDisconnect(&l->disconnect);
-    }
-    free(l);
-}
-
+// Called as a transport disconnect function. |arg| is the raw alistener*.
 static void listener_disconnect(void* arg, atransport*) {
-    alistener* listener = reinterpret_cast<alistener*>(arg);
-    listener->transport = nullptr;
-    free_listener(listener);
-}
-
-static int local_name_to_fd(const char* name, std::string* error) {
-    if (!strncmp("tcp:", name, 4)) {
-        int port = atoi(name + 4);
-        if (gListenAll > 0) {
-            return network_inaddr_any_server(port, SOCK_STREAM, error);
-        } else {
-            return network_loopback_server(port, SOCK_STREAM, error);
+    for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
+        if (iter->get() == arg) {
+            (*iter)->transport = nullptr;
+            listener_list.erase(iter);
+            return;
         }
     }
-#if !defined(_WIN32)  // No Unix-domain sockets on Windows.
-    // It's nonsensical to support the "reserved" space on the adb host side
-    if (!strncmp(name, "local:", 6)) {
-        return network_local_server(name + 6,
-                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM, error);
-    } else if (!strncmp(name, "localabstract:", 14)) {
-        return network_local_server(name + 14,
-                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM, error);
-    } else if (!strncmp(name, "localfilesystem:", 16)) {
-        return network_local_server(name + 16,
-                ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM, error);
-    }
-
-#endif
-    *error = android::base::StringPrintf("unknown local portname '%s'", name);
-    return -1;
 }
 
 // Write the list of current listeners (network redirections) into a string.
 std::string format_listeners() {
     std::string result;
-    for (alistener* l = listener_list.next; l != &listener_list; l = l->next) {
+    for (auto& l : listener_list) {
         // Ignore special listeners like those for *smartsocket*
         if (l->connect_to[0] == '*') {
             continue;
@@ -149,65 +130,51 @@
         // Entries from "adb reverse" have no serial.
         android::base::StringAppendF(&result, "%s %s %s\n",
                                      l->transport->serial ? l->transport->serial : "(reverse)",
-                                     l->local_name, l->connect_to);
+                                     l->local_name.c_str(), l->connect_to.c_str());
     }
     return result;
 }
 
-InstallStatus remove_listener(const char *local_name, atransport* transport) {
-    alistener *l;
-
-    for (l = listener_list.next; l != &listener_list; l = l->next) {
-        if (!strcmp(local_name, l->local_name)) {
-            free_listener(l);
+InstallStatus remove_listener(const char* local_name, atransport* transport) {
+    for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
+        if (local_name == (*iter)->local_name) {
+            listener_list.erase(iter);
             return INSTALL_STATUS_OK;
         }
     }
     return INSTALL_STATUS_LISTENER_NOT_FOUND;
 }
 
-void remove_all_listeners(void)
-{
-    alistener *l, *l_next;
-    for (l = listener_list.next; l != &listener_list; l = l_next) {
-        l_next = l->next;
+void remove_all_listeners() {
+    auto iter = listener_list.begin();
+    while (iter != listener_list.end()) {
         // Never remove smart sockets.
-        if (l->connect_to[0] == '*')
-            continue;
-        free_listener(l);
+        if ((*iter)->connect_to[0] == '*') {
+            ++iter;
+        } else {
+            iter = listener_list.erase(iter);
+        }
     }
 }
 
-InstallStatus install_listener(const std::string& local_name,
-                                  const char *connect_to,
-                                  atransport* transport,
-                                  int no_rebind,
-                                  std::string* error)
-{
-    for (alistener* l = listener_list.next; l != &listener_list; l = l->next) {
+InstallStatus install_listener(const std::string& local_name, const char* connect_to,
+                               atransport* transport, int no_rebind, int* resolved_tcp_port,
+                               std::string* error) {
+    for (auto& l : listener_list) {
         if (local_name == l->local_name) {
-            char* cto;
-
-            /* can't repurpose a smartsocket */
+            // Can't repurpose a smartsocket.
             if(l->connect_to[0] == '*') {
                 *error = "cannot repurpose smartsocket";
                 return INSTALL_STATUS_INTERNAL_ERROR;
             }
 
-            /* can't repurpose a listener if 'no_rebind' is true */
+            // Can't repurpose a listener if 'no_rebind' is true.
             if (no_rebind) {
                 *error = "cannot rebind";
                 return INSTALL_STATUS_CANNOT_REBIND;
             }
 
-            cto = strdup(connect_to);
-            if(cto == 0) {
-                *error = "cannot duplicate string";
-                return INSTALL_STATUS_INTERNAL_ERROR;
-            }
-
-            free((void*) l->connect_to);
-            l->connect_to = cto;
+            l->connect_to = connect_to;
             if (l->transport != transport) {
                 l->transport->RemoveDisconnect(&l->disconnect);
                 l->transport = transport;
@@ -217,54 +184,38 @@
         }
     }
 
-    alistener* listener = reinterpret_cast<alistener*>(
-        calloc(1, sizeof(alistener)));
-    if (listener == nullptr) {
-        goto nomem;
-    }
+    std::unique_ptr<alistener> listener(new alistener(local_name, connect_to));
 
-    listener->local_name = strdup(local_name.c_str());
-    if (listener->local_name == nullptr) {
-        goto nomem;
-    }
-
-    listener->connect_to = strdup(connect_to);
-    if (listener->connect_to == nullptr) {
-        goto nomem;
-    }
-
-    listener->fd = local_name_to_fd(listener->local_name, error);
+    int resolved = 0;
+    listener->fd = socket_spec_listen(listener->local_name, error, &resolved);
     if (listener->fd < 0) {
-        free(listener->local_name);
-        free(listener->connect_to);
-        free(listener);
         return INSTALL_STATUS_CANNOT_BIND;
     }
 
+    // If the caller requested port 0, update the listener name with the resolved port.
+    if (resolved != 0) {
+        listener->local_name = android::base::StringPrintf("tcp:%d", resolved);
+        if (resolved_tcp_port) {
+            *resolved_tcp_port = resolved;
+        }
+    }
+
     close_on_exec(listener->fd);
-    if (!strcmp(listener->connect_to, "*smartsocket*")) {
-        fdevent_install(&listener->fde, listener->fd, ss_listener_event_func,
-                        listener);
+    if (listener->connect_to == "*smartsocket*") {
+        fdevent_install(&listener->fde, listener->fd, ss_listener_event_func, listener.get());
     } else {
-        fdevent_install(&listener->fde, listener->fd, listener_event_func,
-                        listener);
+        fdevent_install(&listener->fde, listener->fd, listener_event_func, listener.get());
     }
     fdevent_set(&listener->fde, FDE_READ);
 
-    listener->next = &listener_list;
-    listener->prev = listener_list.prev;
-    listener->next->prev = listener;
-    listener->prev->next = listener;
     listener->transport = transport;
 
     if (transport) {
-        listener->disconnect.opaque = listener;
+        listener->disconnect.opaque = listener.get();
         listener->disconnect.func   = listener_disconnect;
         transport->AddDisconnect(&listener->disconnect);
     }
-    return INSTALL_STATUS_OK;
 
-nomem:
-    fatal("cannot allocate listener");
-    return INSTALL_STATUS_INTERNAL_ERROR;
+    listener_list.push_back(std::move(listener));
+    return INSTALL_STATUS_OK;
 }
diff --git a/adb/adb_listeners.h b/adb/adb_listeners.h
index fa98eed..8eba00a 100644
--- a/adb/adb_listeners.h
+++ b/adb/adb_listeners.h
@@ -21,6 +21,8 @@
 
 #include <string>
 
+#include <android-base/macros.h>
+
 // error/status codes for install_listener.
 enum InstallStatus {
   INSTALL_STATUS_OK = 0,
@@ -30,10 +32,8 @@
   INSTALL_STATUS_LISTENER_NOT_FOUND = -4,
 };
 
-InstallStatus install_listener(const std::string& local_name,
-                               const char* connect_to,
-                               atransport* transport,
-                               int no_rebind,
+InstallStatus install_listener(const std::string& local_name, const char* connect_to,
+                               atransport* transport, int no_rebind, int* resolved_tcp_port,
                                std::string* error);
 
 std::string format_listeners();
diff --git a/adb/adb_listeners_test.cpp b/adb/adb_listeners_test.cpp
new file mode 100644
index 0000000..b697769
--- /dev/null
+++ b/adb/adb_listeners_test.cpp
@@ -0,0 +1,166 @@
+/*
+ * 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 "adb_listeners.h"
+
+#include <gtest/gtest.h>
+
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "fdevent.h"
+#include "sysdeps.h"
+#include "transport.h"
+
+// Returns true if the given listener is present in format_listeners(). Empty parameters will
+// be ignored.
+static bool listener_is_installed(const std::string& serial, const std::string& source,
+                                  const std::string& dest) {
+    // format_listeners() gives lines of "<serial> <source> <dest>\n".
+    for (const std::string& line : android::base::Split(format_listeners(), "\n")) {
+        std::vector<std::string> info = android::base::Split(line, " ");
+        if (info.size() == 3 &&
+                (serial.empty() || info[0] == serial) &&
+                (source.empty() || info[1] == source) &&
+                (dest.empty() || info[2] == dest)) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+class AdbListenersTest : public ::testing::Test {
+  public:
+    void SetUp() override {
+        // We don't need an fdevent loop, but adding/removing listeners must be done from the
+        // fdevent thread if one exists. Since previously run tests may have created an fdevent
+        // thread, we need to reset to prevent the thread check.
+        fdevent_reset();
+    }
+
+    void TearDown() override {
+        // Clean up any listeners that may have been installed.
+        remove_all_listeners();
+
+        // Make sure we didn't leave any dangling events.
+        ASSERT_EQ(0u, fdevent_installed_count());
+    }
+
+  protected:
+    atransport transport_;
+};
+
+TEST_F(AdbListenersTest, test_install_listener) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_TRUE(listener_is_installed("", "tcp:9000", "tcp:9000"));
+}
+
+TEST_F(AdbListenersTest, test_install_listener_rebind) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9001", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_TRUE(listener_is_installed("", "tcp:9000", "tcp:9001"));
+}
+
+TEST_F(AdbListenersTest, test_install_listener_no_rebind) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, true, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_CANNOT_REBIND,
+              install_listener("tcp:9000", "tcp:9001", &transport_, true, nullptr, &error));
+    ASSERT_FALSE(error.empty());
+
+    ASSERT_TRUE(listener_is_installed("", "tcp:9000", "tcp:9000"));
+}
+
+TEST_F(AdbListenersTest, test_install_listener_tcp_port_0) {
+    int port = 0;
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:0", "tcp:9000", &transport_, true, &port, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_TRUE(listener_is_installed("", android::base::StringPrintf("tcp:%d", port), "tcp:9000"));
+}
+
+TEST_F(AdbListenersTest, test_remove_listener) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_OK, remove_listener("tcp:9000", &transport_));
+    ASSERT_TRUE(format_listeners().empty());
+}
+
+TEST_F(AdbListenersTest, test_remove_nonexistent_listener) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_LISTENER_NOT_FOUND, remove_listener("tcp:1", &transport_));
+    ASSERT_TRUE(listener_is_installed("", "tcp:9000", "tcp:9000"));
+}
+
+TEST_F(AdbListenersTest, test_remove_all_listeners) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9001", "tcp:9001", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    remove_all_listeners();
+    ASSERT_TRUE(format_listeners().empty());
+}
+
+TEST_F(AdbListenersTest, test_transport_disconnect) {
+    std::string error;
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9000", "tcp:9000", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    ASSERT_EQ(INSTALL_STATUS_OK,
+              install_listener("tcp:9001", "tcp:9001", &transport_, false, nullptr, &error));
+    ASSERT_TRUE(error.empty());
+
+    transport_.RunDisconnects();
+    ASSERT_TRUE(format_listeners().empty());
+}
diff --git a/adb/adb_mdns.h b/adb/adb_mdns.h
new file mode 100644
index 0000000..2e544d7
--- /dev/null
+++ b/adb/adb_mdns.h
@@ -0,0 +1,22 @@
+/*
+ * 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 _ADB_MDNS_H_
+#define _ADB_MDNS_H_
+
+const char* kADBServiceType = "_adb._tcp";
+
+#endif
diff --git a/adb/adb_trace.cpp b/adb/adb_trace.cpp
index 62900c0..c369d60 100644
--- a/adb/adb_trace.cpp
+++ b/adb/adb_trace.cpp
@@ -27,7 +27,7 @@
 #include "adb.h"
 
 #if !ADB_HOST
-#include <cutils/properties.h>
+#include <android-base/properties.h>
 #endif
 
 #if !ADB_HOST
@@ -88,19 +88,11 @@
     return std::string(setting);
 }
 
-#if !ADB_HOST
-std::string get_trace_setting_from_prop() {
-    char buf[PROPERTY_VALUE_MAX];
-    property_get("persist.adb.trace_mask", buf, "");
-    return std::string(buf);
-}
-#endif
-
 std::string get_trace_setting() {
 #if ADB_HOST
     return get_trace_setting_from_env();
 #else
-    return get_trace_setting_from_prop();
+    return android::base::GetProperty("persist.adb.trace_mask", "");
 #endif
 }
 
@@ -117,8 +109,8 @@
     }
 
     std::unordered_map<std::string, int> trace_flags = {
-        {"1", 0},
-        {"all", 0},
+        {"1", -1},
+        {"all", -1},
         {"adb", ADB},
         {"sockets", SOCKETS},
         {"packets", PACKETS},
@@ -141,8 +133,8 @@
             continue;
         }
 
-        if (flag->second == 0) {
-            // 0 is used for the special values "1" and "all" that enable all
+        if (flag->second == -1) {
+            // -1 is used for the special values "1" and "all" that enable all
             // tracing.
             adb_trace_mask = ~0;
             return;
@@ -163,7 +155,24 @@
     }
 #endif
 
+#if !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;
+    char* ANDROID_LOG_TAGS = getenv("ANDROID_LOG_TAGS");
+    if (ANDROID_LOG_TAGS) {
+        log_tags = ANDROID_LOG_TAGS;
+        unsetenv("ANDROID_LOG_TAGS");
+    }
+#endif
+
     android::base::InitLogging(argv, &AdbLogger);
+
+#if !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
+
     setup_trace_mask();
 
     VLOG(ADB) << adb_version();
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index d50f947..aaffa29 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -41,7 +41,7 @@
 };
 
 #define VLOG_IS_ON(TAG) \
-    ((adb_trace_mask & (1 << TAG)) != 0)
+    ((adb_trace_mask & (1 << (TAG))) != 0)
 
 #define VLOG(TAG)         \
     if (LIKELY(!VLOG_IS_ON(TAG))) \
@@ -58,4 +58,8 @@
 void adb_trace_init(char**);
 void adb_trace_enable(AdbTrace trace_tag);
 
+#define ATRACE_TAG ATRACE_TAG_ADB
+#include <cutils/trace.h>
+#include <utils/Trace.h>
+
 #endif /* __ADB_TRACE_H */
diff --git a/adb/adb_unique_fd.h b/adb/adb_unique_fd.h
new file mode 100644
index 0000000..34c1bbc
--- /dev/null
+++ b/adb/adb_unique_fd.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/unique_fd.h>
+
+// Helper to automatically close an FD when it goes out of scope.
+struct AdbCloser {
+    static void Close(int fd);
+};
+
+using unique_fd = android::base::unique_fd_impl<AdbCloser>;
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 0645122..31d3dc6 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -17,16 +17,19 @@
 #define TRACE_TAG ADB
 
 #include "adb_utils.h"
+#include "adb_unique_fd.h"
 
-#include <libgen.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
 #include <algorithm>
+#include <vector>
 
+#include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 
@@ -40,10 +43,10 @@
 #  endif
 #  include "windows.h"
 #  include "shlobj.h"
+#else
+#include <pwd.h>
 #endif
 
-ADB_MUTEX_DEFINE(basename_lock);
-ADB_MUTEX_DEFINE(dirname_lock);
 
 #if defined(_WIN32)
 constexpr char kNullFileName[] = "NUL";
@@ -72,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) {
@@ -96,52 +99,6 @@
   return result;
 }
 
-std::string adb_basename(const std::string& path) {
-  // Copy path because basename may modify the string passed in.
-  std::string result(path);
-
-  // Use lock because basename() may write to a process global and return a
-  // pointer to that. Note that this locking strategy only works if all other
-  // callers to dirname in the process also grab this same lock.
-  adb_mutex_lock(&basename_lock);
-
-  // Note that if std::string uses copy-on-write strings, &str[0] will cause
-  // the copy to be made, so there is no chance of us accidentally writing to
-  // the storage for 'path'.
-  char* name = basename(&result[0]);
-
-  // In case dirname returned a pointer to a process global, copy that string
-  // before leaving the lock.
-  result.assign(name);
-
-  adb_mutex_unlock(&basename_lock);
-
-  return result;
-}
-
-std::string adb_dirname(const std::string& path) {
-  // Copy path because dirname may modify the string passed in.
-  std::string result(path);
-
-  // Use lock because dirname() may write to a process global and return a
-  // pointer to that. Note that this locking strategy only works if all other
-  // callers to dirname in the process also grab this same lock.
-  adb_mutex_lock(&dirname_lock);
-
-  // Note that if std::string uses copy-on-write strings, &str[0] will cause
-  // the copy to be made, so there is no chance of us accidentally writing to
-  // the storage for 'path'.
-  char* parent = dirname(&result[0]);
-
-  // In case dirname returned a pointer to a process global, copy that string
-  // before leaving the lock.
-  result.assign(parent);
-
-  adb_mutex_unlock(&dirname_lock);
-
-  return result;
-}
-
 // Given a relative or absolute filepath, create the directory hierarchy
 // as needed. Returns true if the hierarchy is/was setup.
 bool mkdirs(const std::string& path) {
@@ -167,7 +124,7 @@
     return true;
   }
 
-  const std::string parent(adb_dirname(path));
+  const std::string parent(android::base::Dirname(path));
 
   // If dirname returned the same path as what we passed in, don't go recursive.
   // This can happen on Windows when walking up the directory hierarchy and not
@@ -239,14 +196,31 @@
 }
 #endif
 
-std::string adb_get_homedir_path(bool check_env_first) {
-#ifdef _WIN32
-    if (check_env_first) {
-        if (const char* const home = getenv("ANDROID_SDK_HOME")) {
-            return home;
+bool forward_targets_are_valid(const std::string& source, const std::string& dest,
+                               std::string* error) {
+    if (android::base::StartsWith(source, "tcp:")) {
+        // The source port may be 0 to allow the system to select an open port.
+        int port;
+        if (!android::base::ParseInt(&source[4], &port) || port < 0) {
+            *error = android::base::StringPrintf("Invalid source port: '%s'", &source[4]);
+            return false;
         }
     }
 
+    if (android::base::StartsWith(dest, "tcp:")) {
+        // The destination port must be > 0.
+        int port;
+        if (!android::base::ParseInt(&dest[4], &port) || port <= 0) {
+            *error = android::base::StringPrintf("Invalid destination port: '%s'", &dest[4]);
+            return false;
+        }
+    }
+
+    return true;
+}
+
+std::string adb_get_homedir_path() {
+#ifdef _WIN32
     WCHAR path[MAX_PATH];
     const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
     if (FAILED(hr)) {
@@ -262,7 +236,45 @@
     if (const char* const home = getenv("HOME")) {
         return home;
     }
+
+    struct passwd pwent;
+    struct passwd* result;
+    int pwent_max = sysconf(_SC_GETPW_R_SIZE_MAX);
+    std::vector<char> buf(pwent_max);
+    int rc = getpwuid_r(getuid(), &pwent, buf.data(), buf.size(), &result);
+    if (rc == 0 && result) {
+        return result->pw_dir;
+    }
+
+    LOG(FATAL) << "failed to get user home directory";
     return {};
 #endif
 }
 
+std::string adb_get_android_dir_path() {
+    std::string user_dir = adb_get_homedir_path();
+    std::string android_dir = user_dir + OS_PATH_SEPARATOR + ".android";
+    struct stat buf;
+    if (stat(android_dir.c_str(), &buf) == -1) {
+        if (adb_mkdir(android_dir.c_str(), 0750) == -1) {
+            PLOG(FATAL) << "Cannot mkdir '" << android_dir << "'";
+        }
+    }
+    return android_dir;
+}
+
+void AdbCloser::Close(int fd) {
+    adb_close(fd);
+}
+
+int usage(const char* fmt, ...) {
+    fprintf(stderr, "adb: ");
+
+    va_list ap;
+    va_start(ap, fmt);
+    vfprintf(stderr, fmt, ap);
+    va_end(ap);
+
+    fprintf(stderr, "\n");
+    return 1;
+}
diff --git a/adb/adb_utils.h b/adb/adb_utils.h
index cd6717d..e0ad103 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -20,23 +20,19 @@
 #include <string>
 
 #include <android-base/macros.h>
-#include <android-base/unique_fd.h>
+
+int usage(const char*, ...);
 
 void close_stdin();
 
 bool getcwd(std::string* cwd);
 bool directory_exists(const std::string& path);
 
-// Like the regular basename and dirname, but thread-safe on all
-// platforms and capable of correctly handling exotic Windows paths.
-std::string adb_basename(const std::string& path);
-std::string adb_dirname(const std::string& path);
-
 // Return the user's home directory.
-// |check_env_first| - if true, on Windows check the ANDROID_SDK_HOME
-// environment variable before trying the WinAPI call (useful when looking for
-// the .android directory)
-std::string adb_get_homedir_path(bool check_env_first);
+std::string adb_get_homedir_path();
+
+// Return the adb user directory.
+std::string adb_get_android_dir_path();
 
 bool mkdirs(const std::string& path);
 
@@ -50,51 +46,11 @@
 
 extern int adb_close(int fd);
 
-// Helper to automatically close an FD when it goes out of scope.
-struct AdbCloser {
-    static void Close(int fd) {
-        adb_close(fd);
-    }
-};
-
-using unique_fd = android::base::unique_fd_impl<AdbCloser>;
-
-class ScopedFd {
-  public:
-    ScopedFd() {
-    }
-
-    ~ScopedFd() {
-        Reset();
-    }
-
-    void Reset(int fd = -1) {
-        if (fd != fd_) {
-            if (valid()) {
-                adb_close(fd_);
-            }
-            fd_ = fd;
-        }
-    }
-
-    int Release() {
-        int temp = fd_;
-        fd_ = -1;
-        return temp;
-    }
-
-    bool valid() const {
-        return fd_ >= 0;
-    }
-
-    int fd() const {
-        return fd_;
-    }
-
-  private:
-    int fd_ = -1;
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedFd);
-};
+// Given forward/reverse targets, returns true if they look sane. If an error is found, fills
+// |error| and returns false.
+// Currently this only checks "tcp:" targets. Additional checking could be added for other targets
+// if needed.
+bool forward_targets_are_valid(const std::string& source, const std::string& dest,
+                               std::string* error);
 
 #endif
diff --git a/adb/adb_utils_test.cpp b/adb/adb_utils_test.cpp
index a78f8d3..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
 }
@@ -109,19 +108,7 @@
   ASSERT_EQ(R"('abc)')", escape_arg("abc)"));
 }
 
-TEST(adb_utils, adb_basename) {
-  EXPECT_EQ("sh", adb_basename("/system/bin/sh"));
-  EXPECT_EQ("sh", adb_basename("sh"));
-  EXPECT_EQ("sh", adb_basename("/system/bin/sh/"));
-}
-
-TEST(adb_utils, adb_dirname) {
-  EXPECT_EQ("/system/bin", adb_dirname("/system/bin/sh"));
-  EXPECT_EQ(".", adb_dirname("sh"));
-  EXPECT_EQ("/system/bin", adb_dirname("/system/bin/sh/"));
-}
-
-void test_mkdirs(const std::string basepath) {
+void test_mkdirs(const std::string& basepath) {
   // Test creating a directory hierarchy.
   ASSERT_TRUE(mkdirs(basepath));
   // Test finding an existing directory hierarchy.
@@ -165,3 +152,24 @@
   ASSERT_EQ(0, adb_close(fd));
 }
 #endif
+
+TEST(adb_utils, test_forward_targets_are_valid) {
+    std::string error;
+
+    // Source port can be >= 0.
+    EXPECT_FALSE(forward_targets_are_valid("tcp:-1", "tcp:9000", &error));
+    EXPECT_TRUE(forward_targets_are_valid("tcp:0", "tcp:9000", &error));
+    EXPECT_TRUE(forward_targets_are_valid("tcp:8000", "tcp:9000", &error));
+
+    // Destination port must be >0.
+    EXPECT_FALSE(forward_targets_are_valid("tcp:8000", "tcp:-1", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:8000", "tcp:0", &error));
+
+    // Port must be a number.
+    EXPECT_FALSE(forward_targets_are_valid("tcp:", "tcp:9000", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:a", "tcp:9000", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:22x", "tcp:9000", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:8000", "tcp:", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:8000", "tcp:a", &error));
+    EXPECT_FALSE(forward_targets_are_valid("tcp:8000", "tcp:22x", &error));
+}
diff --git a/adb/adbd_auth.cpp b/adb/adbd_auth.cpp
new file mode 100644
index 0000000..b5f87be
--- /dev/null
+++ b/adb/adbd_auth.cpp
@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define TRACE_TAG AUTH
+
+#include "adb.h"
+#include "adb_auth.h"
+#include "fdevent.h"
+#include "sysdeps.h"
+#include "transport.h"
+
+#include <resolv.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <memory>
+
+#include <android-base/file.h>
+#include <android-base/strings.h>
+#include <crypto_utils/android_pubkey.h>
+#include <openssl/obj_mac.h>
+#include <openssl/rsa.h>
+#include <openssl/sha.h>
+
+static fdevent listener_fde;
+static fdevent framework_fde;
+static int framework_fd = -1;
+
+static void usb_disconnected(void* unused, atransport* t);
+static struct adisconnect usb_disconnect = { usb_disconnected, nullptr};
+static atransport* usb_transport;
+static bool needs_retry = false;
+
+bool auth_required = true;
+
+bool adbd_auth_verify(const char* token, size_t token_size, const char* sig, int sig_len) {
+    static constexpr const char* key_paths[] = { "/adb_keys", "/data/misc/adb/adb_keys", nullptr };
+
+    for (const auto& path : key_paths) {
+        if (access(path, R_OK) == 0) {
+            LOG(INFO) << "Loading keys from " << path;
+
+            std::string content;
+            if (!android::base::ReadFileToString(path, &content)) {
+                PLOG(ERROR) << "Couldn't read " << path;
+                continue;
+            }
+
+            for (const auto& line : android::base::Split(content, "\n")) {
+                // TODO: do we really have to support both ' ' and '\t'?
+                char* sep = strpbrk(const_cast<char*>(line.c_str()), " \t");
+                if (sep) *sep = '\0';
+
+                // b64_pton requires one additional byte in the target buffer for
+                // decoding to succeed. See http://b/28035006 for details.
+                uint8_t keybuf[ANDROID_PUBKEY_ENCODED_SIZE + 1];
+                if (__b64_pton(line.c_str(), keybuf, sizeof(keybuf)) != ANDROID_PUBKEY_ENCODED_SIZE) {
+                    LOG(ERROR) << "Invalid base64 key " << line.c_str() << " in " << path;
+                    continue;
+                }
+
+                RSA* key = nullptr;
+                if (!android_pubkey_decode(keybuf, ANDROID_PUBKEY_ENCODED_SIZE, &key)) {
+                    LOG(ERROR) << "Failed to parse key " << line.c_str() << " in " << path;
+                    continue;
+                }
+
+                bool verified =
+                    (RSA_verify(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
+                                reinterpret_cast<const uint8_t*>(sig), sig_len, key) == 1);
+                RSA_free(key);
+                if (verified) return true;
+            }
+        }
+    }
+    return false;
+}
+
+static bool adbd_auth_generate_token(void* token, size_t token_size) {
+    FILE* fp = fopen("/dev/urandom", "re");
+    if (!fp) return false;
+    bool okay = (fread(token, token_size, 1, fp) == 1);
+    fclose(fp);
+    return okay;
+}
+
+static void usb_disconnected(void* unused, atransport* t) {
+    LOG(INFO) << "USB disconnect";
+    usb_transport = NULL;
+    needs_retry = false;
+}
+
+static void framework_disconnected() {
+    LOG(INFO) << "Framework disconnect";
+    fdevent_remove(&framework_fde);
+    framework_fd = -1;
+}
+
+static void adbd_auth_event(int fd, unsigned events, void*) {
+    if (events & FDE_READ) {
+        char response[2];
+        int ret = unix_read(fd, response, sizeof(response));
+        if (ret <= 0) {
+            framework_disconnected();
+        } else if (ret == 2 && response[0] == 'O' && response[1] == 'K') {
+            if (usb_transport) {
+                adbd_auth_verified(usb_transport);
+            }
+        }
+    }
+}
+
+void adbd_auth_confirm_key(const char* key, size_t len, atransport* t) {
+    if (!usb_transport) {
+        usb_transport = t;
+        t->AddDisconnect(&usb_disconnect);
+    }
+
+    if (framework_fd < 0) {
+        LOG(ERROR) << "Client not connected";
+        needs_retry = true;
+        return;
+    }
+
+    if (key[len - 1] != '\0') {
+        LOG(ERROR) << "Key must be a null-terminated string";
+        return;
+    }
+
+    char msg[MAX_PAYLOAD_V1];
+    int msg_len = snprintf(msg, sizeof(msg), "PK%s", key);
+    if (msg_len >= static_cast<int>(sizeof(msg))) {
+        LOG(ERROR) << "Key too long (" << msg_len << ")";
+        return;
+    }
+    LOG(DEBUG) << "Sending '" << msg << "'";
+
+    if (unix_write(framework_fd, msg, msg_len) == -1) {
+        PLOG(ERROR) << "Failed to write PK";
+        return;
+    }
+}
+
+static void adbd_auth_listener(int fd, unsigned events, void* data) {
+    int s = adb_socket_accept(fd, nullptr, nullptr);
+    if (s < 0) {
+        PLOG(ERROR) << "Failed to accept";
+        return;
+    }
+
+    if (framework_fd >= 0) {
+        LOG(WARNING) << "adb received framework auth socket connection again";
+        framework_disconnected();
+    }
+
+    framework_fd = s;
+    fdevent_install(&framework_fde, framework_fd, adbd_auth_event, nullptr);
+    fdevent_add(&framework_fde, FDE_READ);
+
+    if (needs_retry) {
+        needs_retry = false;
+        send_auth_request(usb_transport);
+    }
+}
+
+void adbd_cloexec_auth_socket() {
+    int fd = android_get_control_socket("adbd");
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to get adbd socket";
+        return;
+    }
+    fcntl(fd, F_SETFD, FD_CLOEXEC);
+}
+
+void adbd_auth_init(void) {
+    int fd = android_get_control_socket("adbd");
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to get adbd socket";
+        return;
+    }
+
+    if (listen(fd, 4) == -1) {
+        PLOG(ERROR) << "Failed to listen on '" << fd << "'";
+        return;
+    }
+
+    fdevent_install(&listener_fde, fd, adbd_auth_listener, NULL);
+    fdevent_add(&listener_fde, FDE_READ);
+}
+
+void send_auth_request(atransport* t) {
+    LOG(INFO) << "Calling send_auth_request...";
+
+    if (!adbd_auth_generate_token(t->token, sizeof(t->token))) {
+        PLOG(ERROR) << "Error generating token";
+        return;
+    }
+
+    apacket* p = get_apacket();
+    memcpy(p->data, t->token, sizeof(t->token));
+    p->msg.command = A_AUTH;
+    p->msg.arg0 = ADB_AUTH_TOKEN;
+    p->msg.data_length = sizeof(t->token);
+    send_packet(p, t);
+}
+
+void adbd_auth_verified(atransport *t)
+{
+    handle_online(t);
+    send_connect(t);
+}
diff --git a/adb/bugreport.cpp b/adb/bugreport.cpp
index c348dd5..b3e391b 100644
--- a/adb/bugreport.cpp
+++ b/adb/bugreport.cpp
@@ -21,6 +21,7 @@
 #include <string>
 #include <vector>
 
+#include <android-base/file.h>
 #include <android-base/strings.h>
 
 #include "sysdeps.h"
@@ -46,7 +47,8 @@
           invalid_lines_(),
           show_progress_(show_progress),
           status_(0),
-          line_() {
+          line_(),
+          last_progress_percentage_(0) {
         SetLineMessage("generating");
     }
 
@@ -65,6 +67,7 @@
     void OnStderr(const char* buffer, int length) {
         OnStream(nullptr, stderr, buffer, length);
     }
+
     int Done(int unused_) {
         // Process remaining line, if any.
         ProcessLine(line_);
@@ -113,14 +116,14 @@
 
   private:
     void SetLineMessage(const std::string& action) {
-        line_message_ = action + " " + adb_basename(dest_file_);
+        line_message_ = action + " " + android::base::Basename(dest_file_);
     }
 
     void SetSrcFile(const std::string path) {
         src_file_ = path;
         if (!dest_dir_.empty()) {
             // Only uses device-provided name when user passed a directory.
-            dest_file_ = adb_basename(path);
+            dest_file_ = android::base::Basename(path);
             SetLineMessage("generating");
         }
     }
@@ -145,7 +148,13 @@
             size_t idx2 = line.rfind(BUGZ_PROGRESS_SEPARATOR);
             int progress = std::stoi(line.substr(idx1, (idx2 - idx1)));
             int total = std::stoi(line.substr(idx2 + 1));
-            br_->UpdateProgress(line_message_, progress, total);
+            int progress_percentage = (progress * 100 / total);
+            if (progress_percentage != 0 && progress_percentage <= last_progress_percentage_) {
+                // Ignore.
+                return;
+            }
+            last_progress_percentage_ = progress_percentage;
+            br_->UpdateProgress(line_message_, progress_percentage);
         } else {
             invalid_lines_.push_back(line);
         }
@@ -179,14 +188,15 @@
     // Temporary buffer containing the characters read since the last newline (\n).
     std::string line_;
 
+    // Last displayed progress.
+    // Since dumpstate progress can recede, only forward progress should be displayed
+    int last_progress_percentage_;
+
     DISALLOW_COPY_AND_ASSIGN(BugreportStandardStreamsCallback);
 };
 
-// Implemented in commandline.cpp
-int usage();
-
 int Bugreport::DoIt(TransportType transport_type, const char* serial, int argc, const char** argv) {
-    if (argc > 2) return usage();
+    if (argc > 2) return usage("usage: adb bugreport [PATH]");
 
     // Gets bugreportz version.
     std::string bugz_stdout, bugz_stderr;
@@ -237,8 +247,7 @@
         // Uses a default value until device provides the proper name
         dest_file = "bugreport.zip";
     } else {
-        if (!android::base::EndsWith(dest_file, ".zip")) {
-            // TODO: use a case-insensitive comparison (like EndsWithIgnoreCase
+        if (!android::base::EndsWithIgnoreCase(dest_file, ".zip")) {
             dest_file += ".zip";
         }
     }
@@ -259,8 +268,7 @@
     return SendShellCommand(transport_type, serial, bugz_command, false, &bugz_callback);
 }
 
-void Bugreport::UpdateProgress(const std::string& message, int progress, int total) {
-    int progress_percentage = (progress * 100 / total);
+void Bugreport::UpdateProgress(const std::string& message, int progress_percentage) {
     line_printer_.Print(
         android::base::StringPrintf("[%3d%%] %s", progress_percentage, message.c_str()),
         LinePrinter::INFO);
diff --git a/adb/bugreport.h b/adb/bugreport.h
index ee99cbc..d9a4468 100644
--- a/adb/bugreport.h
+++ b/adb/bugreport.h
@@ -43,7 +43,7 @@
                             const char* name);
 
   private:
-    virtual void UpdateProgress(const std::string& file_name, int progress, int total);
+    virtual void UpdateProgress(const std::string& file_name, int progress_percentage);
     LinePrinter line_printer_;
     DISALLOW_COPY_AND_ASSIGN(Bugreport);
 };
diff --git a/adb/bugreport_test.cpp b/adb/bugreport_test.cpp
index 1129285..d3787b4 100644
--- a/adb/bugreport_test.cpp
+++ b/adb/bugreport_test.cpp
@@ -50,9 +50,7 @@
 
 // Empty functions so tests don't need to be linked against commandline.cpp
 DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
-int usage() {
-    return -42;
-}
+
 int send_shell_command(TransportType transport_type, const char* serial, const std::string& command,
                        bool disable_shell_protocol, StandardStreamsCallbackInterface* callback) {
     ADD_FAILURE() << "send_shell_command() should have been mocked";
@@ -125,7 +123,7 @@
                      bool disable_shell_protocol, StandardStreamsCallbackInterface* callback));
     MOCK_METHOD4(DoSyncPull, bool(const std::vector<const char*>& srcs, const char* dst,
                                   bool copy_attrs, const char* name));
-    MOCK_METHOD3(UpdateProgress, void(const std::string&, int, int));
+    MOCK_METHOD2(UpdateProgress, void(const std::string&, int));
 };
 
 class BugreportTest : public ::testing::Test {
@@ -144,8 +142,8 @@
                             WithArg<4>(ReturnCallbackDone(0))));
     }
 
-    void ExpectProgress(int progress, int total, const std::string& file = "file.zip") {
-        EXPECT_CALL(br_, UpdateProgress(StrEq("generating " + file), progress, total));
+    void ExpectProgress(int progress_percentage, const std::string& file = "file.zip") {
+        EXPECT_CALL(br_, UpdateProgress(StrEq("generating " + file), progress_percentage));
     }
 
     BugreportMock br_;
@@ -155,7 +153,7 @@
 // Tests when called with invalid number of arguments
 TEST_F(BugreportTest, InvalidNumberArgs) {
     const char* args[] = {"bugreport", "to", "principal"};
-    ASSERT_EQ(-42, br_.DoIt(kTransportLocal, "HannibalLecter", 3, args));
+    ASSERT_EQ(1, br_.DoIt(kTransportLocal, "HannibalLecter", 3, args));
 }
 
 // Tests the 'adb bugreport' option when the device does not support 'bugreportz' - it falls back
@@ -202,7 +200,7 @@
     ExpectBugreportzVersion("1.1");
     std::string dest_file =
         android::base::StringPrintf("%s%cda_bugreport.zip", cwd_.c_str(), OS_PATH_SEPARATOR);
-    ExpectProgress(50, 100, "da_bugreport.zip");
+    ExpectProgress(50, "da_bugreport.zip");
     EXPECT_CALL(br_, SendShellCommand(kTransportLocal, "HannibalLecter", "bugreportz -p", false, _))
         .WillOnce(DoAll(WithArg<4>(WriteOnStdout("BEGIN:/device/da_bugreport.zip\n")),
                         WithArg<4>(WriteOnStdout("PROGRESS:50/100\n")),
@@ -249,10 +247,10 @@
 // Tests 'adb bugreport file.zip' when it succeeds and displays progress.
 TEST_F(BugreportTest, OkProgress) {
     ExpectBugreportzVersion("1.1");
-    ExpectProgress(1, 100);
-    ExpectProgress(10, 100);
-    ExpectProgress(50, 100);
-    ExpectProgress(99, 100);
+    ExpectProgress(1);
+    ExpectProgress(10);
+    ExpectProgress(50);
+    ExpectProgress(99);
     // clang-format off
     EXPECT_CALL(br_, SendShellCommand(kTransportLocal, "HannibalLecter", "bugreportz -p", false, _))
         // NOTE: DoAll accepts at most 10 arguments, and we're almost reached that limit...
@@ -282,6 +280,60 @@
     ASSERT_EQ(0, br_.DoIt(kTransportLocal, "HannibalLecter", 2, args));
 }
 
+// Tests 'adb bugreport file.zip' when it succeeds and displays progress, even if progress recedes.
+TEST_F(BugreportTest, OkProgressAlwaysForward) {
+    ExpectBugreportzVersion("1.1");
+    ExpectProgress(1);
+    ExpectProgress(50);
+    ExpectProgress(75);
+    // clang-format off
+    EXPECT_CALL(br_, SendShellCommand(kTransportLocal, "HannibalLecter", "bugreportz -p", false, _))
+        // NOTE: DoAll accepts at most 10 arguments, and we're almost reached that limit...
+        .WillOnce(DoAll(
+            WithArg<4>(WriteOnStdout("BEGIN:/device/bugreport.zip\n")),
+            WithArg<4>(WriteOnStdout("PROGRESS:1/100\n")), // 1%
+            WithArg<4>(WriteOnStdout("PROGRESS:50/100\n")), // 50%
+            // 25% should be ignored becaused it receded.
+            WithArg<4>(WriteOnStdout("PROGRESS:25/100\n")), // 25%
+            WithArg<4>(WriteOnStdout("PROGRESS:75/100\n")), // 75%
+            // 75% should be ignored becaused it didn't change.
+            WithArg<4>(WriteOnStdout("PROGRESS:75/100\n")), // 75%
+            // Try a receeding percentage with a different max progress
+            WithArg<4>(WriteOnStdout("PROGRESS:700/1000\n")), // 70%
+            WithArg<4>(WriteOnStdout("OK:/device/bugreport.zip")),
+            WithArg<4>(ReturnCallbackDone())));
+    // clang-format on
+    EXPECT_CALL(br_, DoSyncPull(ElementsAre(StrEq("/device/bugreport.zip")), StrEq("file.zip"),
+                                true, StrEq("pulling file.zip")))
+        .WillOnce(Return(true));
+
+    const char* args[] = {"bugreport", "file.zip"};
+    ASSERT_EQ(0, br_.DoIt(kTransportLocal, "HannibalLecter", 2, args));
+}
+
+// Tests 'adb bugreport file.zip' when it succeeds and displays the initial progress of 0%
+TEST_F(BugreportTest, OkProgressZeroPercentIsNotIgnored) {
+    ExpectBugreportzVersion("1.1");
+    ExpectProgress(0);
+    ExpectProgress(1);
+    // clang-format off
+    EXPECT_CALL(br_, SendShellCommand(kTransportLocal, "HannibalLecter", "bugreportz -p", false, _))
+        // NOTE: DoAll accepts at most 10 arguments, and we're almost reached that limit...
+        .WillOnce(DoAll(
+            WithArg<4>(WriteOnStdout("BEGIN:/device/bugreport.zip\n")),
+            WithArg<4>(WriteOnStdout("PROGRESS:1/100000\n")),
+            WithArg<4>(WriteOnStdout("PROGRESS:1/100\n")), // 1%
+            WithArg<4>(WriteOnStdout("OK:/device/bugreport.zip")),
+            WithArg<4>(ReturnCallbackDone())));
+    // clang-format on
+    EXPECT_CALL(br_, DoSyncPull(ElementsAre(StrEq("/device/bugreport.zip")), StrEq("file.zip"),
+                                true, StrEq("pulling file.zip")))
+        .WillOnce(Return(true));
+
+    const char* args[] = {"bugreport", "file.zip"};
+    ASSERT_EQ(0, br_.DoIt(kTransportLocal, "HannibalLecter", 2, args));
+}
+
 // Tests 'adb bugreport dir' when it succeeds and destination is a directory.
 TEST_F(BugreportTest, OkDirectory) {
     ExpectBugreportzVersion("1.1");
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index ba4737f..606203c 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -23,9 +23,12 @@
 #include <stdlib.h>
 #include <unistd.h>
 
+#include <thread>
+
 #include <android-base/errors.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/quick_exit.h>
 #include <android-base/stringprintf.h>
 
 #include "adb.h"
@@ -33,6 +36,7 @@
 #include "adb_listeners.h"
 #include "adb_utils.h"
 #include "commandline.h"
+#include "sysdeps/chrono.h"
 #include "transport.h"
 
 static std::string GetLogFilePath() {
@@ -83,12 +87,12 @@
 static BOOL WINAPI ctrlc_handler(DWORD type) {
     // TODO: Consider trying to kill a starting up adb server (if we're in
     // launch_server) by calling GenerateConsoleCtrlEvent().
-    exit(STATUS_CONTROL_C_EXIT);
+    android::base::quick_exit(STATUS_CONTROL_C_EXIT);
     return TRUE;
 }
 #endif
 
-int adb_server_main(int is_daemon, int server_port, int ack_reply_fd) {
+int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply_fd) {
 #if defined(_WIN32)
     // adb start-server starts us up with stdout and stderr hooked up to
     // anonymous pipes. When the C Runtime sees this, it makes stderr and
@@ -105,34 +109,55 @@
     }
 
     SetConsoleCtrlHandler(ctrlc_handler, TRUE);
+#else
+    signal(SIGINT, [](int) {
+        android::base::quick_exit(0);
+    });
 #endif
 
     init_transport_registration();
 
+    init_mdns_transport_discovery();
+
     usb_init();
     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
-    adb_auth_init();
 
     std::string error;
-    std::string local_name = android::base::StringPrintf("tcp:%d", server_port);
-    if (install_listener(local_name, "*smartsocket*", nullptr, 0, &error)) {
-        fatal("could not install *smartsocket* listener: %s", error.c_str());
+
+    auto start = std::chrono::steady_clock::now();
+
+    // If we told a previous adb server to quit because of version mismatch, we can get to this
+    // point before it's finished exiting. Retry for a while to give it some time.
+    while (install_listener(socket_spec, "*smartsocket*", nullptr, 0, nullptr, &error) !=
+           INSTALL_STATUS_OK) {
+        if (std::chrono::steady_clock::now() - start > 0.5s) {
+            fatal("could not install *smartsocket* listener: %s", error.c_str());
+        }
+
+        std::this_thread::sleep_for(100ms);
     }
 
-    // Inform our parent that we are up and running.
     if (is_daemon) {
         close_stdin();
         setup_daemon_logging();
+    }
 
+    adb_auth_init();
+
+    if (is_daemon) {
 #if !defined(_WIN32)
         // Start a new session for the daemon. Do this here instead of after the fork so
         // that a ctrl-c between the "starting server" and "done starting server" messages
         // gets a chance to terminate the server.
-        if (setsid() == -1) {
+        // setsid will fail with EPERM if it's already been a lead process of new session.
+        // Ignore such error.
+        if (setsid() == -1 && errno != EPERM) {
             fatal("setsid() failed: %s", strerror(errno));
         }
 #endif
 
+        // Inform our parent that we are up and running.
+
         // Any error output written to stderr now goes to adb.log. We could
         // keep around a copy of the stderr fd and use that to write any errors
         // encountered by the following code, but that is probably overkill.
@@ -167,7 +192,6 @@
 }
 
 int main(int argc, char** argv) {
-    adb_sysdeps_init();
     adb_trace_init(argv);
     return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
 }
diff --git a/adb/client/usb_dispatch.cpp b/adb/client/usb_dispatch.cpp
new file mode 100644
index 0000000..bfc8e16
--- /dev/null
+++ b/adb/client/usb_dispatch.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/logging.h>
+#include "usb.h"
+
+void usb_init() {
+    if (should_use_libusb()) {
+        LOG(DEBUG) << "using libusb backend";
+        libusb::usb_init();
+    } else {
+        LOG(DEBUG) << "using native backend";
+        native::usb_init();
+    }
+}
+
+int usb_write(usb_handle* h, const void* data, int len) {
+    return should_use_libusb()
+               ? libusb::usb_write(reinterpret_cast<libusb::usb_handle*>(h), data, len)
+               : native::usb_write(reinterpret_cast<native::usb_handle*>(h), data, len);
+}
+
+int usb_read(usb_handle* h, void* data, int len) {
+    return should_use_libusb()
+               ? libusb::usb_read(reinterpret_cast<libusb::usb_handle*>(h), data, len)
+               : native::usb_read(reinterpret_cast<native::usb_handle*>(h), data, len);
+}
+
+int usb_close(usb_handle* h) {
+    return should_use_libusb() ? libusb::usb_close(reinterpret_cast<libusb::usb_handle*>(h))
+                               : native::usb_close(reinterpret_cast<native::usb_handle*>(h));
+}
+
+void usb_kick(usb_handle* h) {
+    should_use_libusb() ? libusb::usb_kick(reinterpret_cast<libusb::usb_handle*>(h))
+                        : native::usb_kick(reinterpret_cast<native::usb_handle*>(h));
+}
diff --git a/adb/client/usb_libusb.cpp b/adb/client/usb_libusb.cpp
new file mode 100644
index 0000000..7adb262
--- /dev/null
+++ b/adb/client/usb_libusb.cpp
@@ -0,0 +1,519 @@
+/*
+ * 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 "usb.h"
+
+#include "sysdeps.h"
+
+#include <stdint.h>
+
+#include <atomic>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <unordered_map>
+
+#include <libusb/libusb.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/quick_exit.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "adb.h"
+#include "transport.h"
+#include "usb.h"
+
+using namespace std::literals;
+
+using android::base::StringPrintf;
+
+// RAII wrappers for libusb.
+struct ConfigDescriptorDeleter {
+    void operator()(libusb_config_descriptor* desc) {
+        libusb_free_config_descriptor(desc);
+    }
+};
+
+using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
+
+struct DeviceHandleDeleter {
+    void operator()(libusb_device_handle* h) {
+        libusb_close(h);
+    }
+};
+
+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() {
+        libusb_free_transfer(transfer);
+    }
+
+    const char* name;
+    libusb_transfer* transfer;
+    bool transfer_complete;
+    std::condition_variable cv;
+    std::mutex mutex;
+    uint16_t zero_mask;
+
+    void Notify() {
+        LOG(DEBUG) << "notifying " << name << " transfer complete";
+        transfer_complete = true;
+        cv.notify_one();
+    }
+};
+
+namespace libusb {
+struct usb_handle : public ::usb_handle {
+    usb_handle(const std::string& device_address, const std::string& serial,
+               unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in,
+               uint8_t bulk_out, size_t zero_mask)
+        : device_address(device_address),
+          serial(serial),
+          closing(false),
+          device_handle(device_handle.release()),
+          read("read", zero_mask),
+          write("write", zero_mask),
+          interface(interface),
+          bulk_in(bulk_in),
+          bulk_out(bulk_out) {
+    }
+
+    ~usb_handle() {
+        Close();
+    }
+
+    void Close() {
+        std::unique_lock<std::mutex> lock(device_handle_mutex);
+        // Cancelling transfers will trigger more Closes, so make sure this only happens once.
+        if (closing) {
+            return;
+        }
+        closing = true;
+
+        // Make sure that no new transfers come in.
+        libusb_device_handle* handle = device_handle;
+        if (!handle) {
+            return;
+        }
+
+        device_handle = nullptr;
+
+        // Cancel already dispatched transfers.
+        libusb_cancel_transfer(read.transfer);
+        libusb_cancel_transfer(write.transfer);
+
+        libusb_release_interface(handle, interface);
+        libusb_close(handle);
+    }
+
+    std::string device_address;
+    std::string serial;
+
+    std::atomic<bool> closing;
+    std::mutex device_handle_mutex;
+    libusb_device_handle* device_handle;
+
+    transfer_info read;
+    transfer_info write;
+
+    uint8_t interface;
+    uint8_t bulk_in;
+    uint8_t bulk_out;
+};
+
+static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
+static auto& usb_handles_mutex = *new std::mutex();
+
+static std::thread* device_poll_thread = nullptr;
+static std::atomic<bool> terminate_device_poll_thread(false);
+
+static std::string get_device_address(libusb_device* device) {
+    return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
+                        libusb_get_device_address(device));
+}
+
+static bool endpoint_is_output(uint8_t endpoint) {
+    return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
+}
+
+static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
+    return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
+           (write_length & zero_mask) == 0;
+}
+
+static void poll_for_devices() {
+    libusb_device** list;
+    adb_thread_setname("device poll");
+    while (!terminate_device_poll_thread) {
+        const ssize_t device_count = libusb_get_device_list(nullptr, &list);
+
+        LOG(VERBOSE) << "found " << device_count << " attached devices";
+
+        for (ssize_t i = 0; i < device_count; ++i) {
+            libusb_device* device = list[i];
+            std::string device_address = get_device_address(device);
+            std::string device_serial;
+
+            // Figure out if we want to open the device.
+            libusb_device_descriptor device_desc;
+            int rc = libusb_get_device_descriptor(device, &device_desc);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to get device descriptor for device at " << device_address
+                             << ": " << libusb_error_name(rc);
+            }
+
+            if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
+                // Assume that all Android devices have the device class set to per interface.
+                // TODO: Is this assumption valid?
+                LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
+                continue;
+            }
+
+            libusb_config_descriptor* config_raw;
+            rc = libusb_get_active_config_descriptor(device, &config_raw);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to get active config descriptor for device at "
+                             << device_address << ": " << libusb_error_name(rc);
+                continue;
+            }
+            const unique_config_descriptor config(config_raw);
+
+            // Use size_t for interface_num so <iostream>s don't mangle it.
+            size_t interface_num;
+            uint16_t zero_mask;
+            uint8_t bulk_in = 0, bulk_out = 0;
+            bool found_adb = false;
+
+            for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
+                const libusb_interface& interface = config->interface[interface_num];
+                if (interface.num_altsetting != 1) {
+                    // Assume that interfaces with alternate settings aren't adb interfaces.
+                    // TODO: Is this assumption valid?
+                    LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
+                                 << device_address << " (interface " << interface_num << ")";
+                    continue;
+                }
+
+                const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
+                if (!is_adb_interface(interface_desc.bInterfaceClass,
+                                      interface_desc.bInterfaceSubClass,
+                                      interface_desc.bInterfaceProtocol)) {
+                    LOG(VERBOSE) << "skipping non-adb interface at " << device_address
+                                 << " (interface " << interface_num << ")";
+                    continue;
+                }
+
+                LOG(VERBOSE) << "found potential adb interface at " << device_address
+                             << " (interface " << interface_num << ")";
+
+                bool found_in = false;
+                bool found_out = false;
+                for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
+                     ++endpoint_num) {
+                    const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
+                    const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
+                    const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
+
+                    const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
+
+                    if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
+                        continue;
+                    }
+
+                    if (endpoint_is_output(endpoint_addr) && !found_out) {
+                        found_out = true;
+                        bulk_out = endpoint_addr;
+                        zero_mask = endpoint_desc.wMaxPacketSize - 1;
+                    } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
+                        found_in = true;
+                        bulk_in = endpoint_addr;
+                    }
+                }
+
+                if (found_in && found_out) {
+                    found_adb = true;
+                    break;
+                } else {
+                    LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
+                                 << "(interface " << interface_num << "): missing bulk endpoints "
+                                 << "(found_in = " << found_in << ", found_out = " << found_out
+                                 << ")";
+                }
+            }
+
+            if (!found_adb) {
+                LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
+                continue;
+            }
+
+            {
+                std::unique_lock<std::mutex> lock(usb_handles_mutex);
+                if (usb_handles.find(device_address) != usb_handles.end()) {
+                    LOG(VERBOSE) << "device at " << device_address
+                                 << " has already been registered, skipping";
+                    continue;
+                }
+            }
+
+            libusb_device_handle* handle_raw;
+            rc = libusb_open(list[i], &handle_raw);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to open usb device at " << device_address << ": "
+                             << libusb_error_name(rc);
+                continue;
+            }
+
+            unique_device_handle handle(handle_raw);
+            LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
+                       << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
+
+            device_serial.resize(255);
+            rc = libusb_get_string_descriptor_ascii(
+                handle_raw, device_desc.iSerialNumber,
+                reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length());
+            if (rc == 0) {
+                LOG(WARNING) << "received empty serial from device at " << device_address;
+                continue;
+            } else if (rc < 0) {
+                LOG(WARNING) << "failed to get serial from device at " << device_address
+                             << libusb_error_name(rc);
+                continue;
+            }
+            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) {
+                LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
+                             << libusb_error_name(rc);
+                continue;
+            }
+
+            for (uint8_t endpoint : {bulk_in, bulk_out}) {
+                rc = libusb_clear_halt(handle.get(), endpoint);
+                if (rc != 0) {
+                    LOG(WARNING) << "failed to clear halt on device '" << device_serial
+                                 << "' endpoint 0x" << std::hex << endpoint << ": "
+                                 << libusb_error_name(rc);
+                    libusb_release_interface(handle.get(), interface_num);
+                    continue;
+                }
+            }
+
+            auto result =
+                std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
+                                             interface_num, bulk_in, bulk_out, zero_mask);
+            usb_handle* usb_handle_raw = result.get();
+
+            {
+                std::unique_lock<std::mutex> lock(usb_handles_mutex);
+                usb_handles[device_address] = std::move(result);
+            }
+
+            register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1);
+
+            LOG(INFO) << "registered new usb device '" << device_serial << "'";
+        }
+        libusb_free_device_list(list, 1);
+
+        std::this_thread::sleep_for(500ms);
+    }
+}
+
+void usb_init() {
+    LOG(DEBUG) << "initializing libusb...";
+    int rc = libusb_init(nullptr);
+    if (rc != 0) {
+        LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
+    }
+
+    // Spawn a thread for libusb_handle_events.
+    std::thread([]() {
+        adb_thread_setname("libusb");
+        while (true) {
+            libusb_handle_events(nullptr);
+        }
+    }).detach();
+
+    // Spawn a thread to do device enumeration.
+    // TODO: Use libusb_hotplug_* instead?
+    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();
+    });
+}
+
+// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
+static int perform_usb_transfer(usb_handle* h, transfer_info* info,
+                                std::unique_lock<std::mutex> device_lock) {
+    libusb_transfer* transfer = info->transfer;
+
+    transfer->user_data = info;
+    transfer->callback = [](libusb_transfer* transfer) {
+        transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
+
+        LOG(DEBUG) << info->name << " transfer callback entered";
+
+        // Make sure that the original submitter has made it to the condition_variable wait.
+        std::unique_lock<std::mutex> lock(info->mutex);
+
+        LOG(DEBUG) << info->name << " callback successfully acquired lock";
+
+        if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+            LOG(WARNING) << info->name
+                         << " transfer failed: " << libusb_error_name(transfer->status);
+            info->Notify();
+            return;
+        }
+
+        if (transfer->actual_length != transfer->length) {
+            LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
+            transfer->length -= transfer->actual_length;
+            transfer->buffer += transfer->actual_length;
+            int rc = libusb_submit_transfer(transfer);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to submit " << info->name
+                             << " transfer: " << libusb_error_name(rc);
+                transfer->status = LIBUSB_TRANSFER_ERROR;
+                info->Notify();
+            }
+            return;
+        }
+
+        if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
+            LOG(DEBUG) << "submitting zero-length write";
+            transfer->length = 0;
+            int rc = libusb_submit_transfer(transfer);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
+                transfer->status = LIBUSB_TRANSFER_ERROR;
+                info->Notify();
+            }
+            return;
+        }
+
+        LOG(VERBOSE) << info->name << "transfer fully complete";
+        info->Notify();
+    };
+
+    LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
+    std::unique_lock<std::mutex> lock(info->mutex);
+    info->transfer_complete = false;
+    LOG(DEBUG) << "submitting " << info->name << " transfer";
+    int rc = libusb_submit_transfer(transfer);
+    if (rc != 0) {
+        LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
+        errno = EIO;
+        return -1;
+    }
+
+    LOG(DEBUG) << info->name << " transfer successfully submitted";
+    device_lock.unlock();
+    info->cv.wait(lock, [info]() { return info->transfer_complete; });
+    if (transfer->status != 0) {
+        errno = EIO;
+        return -1;
+    }
+
+    return 0;
+}
+
+int usb_write(usb_handle* h, const void* d, int len) {
+    LOG(DEBUG) << "usb_write of length " << len;
+
+    std::unique_lock<std::mutex> lock(h->device_handle_mutex);
+    if (!h->device_handle) {
+        errno = EIO;
+        return -1;
+    }
+
+    transfer_info* info = &h->write;
+    info->transfer->dev_handle = h->device_handle;
+    info->transfer->flags = 0;
+    info->transfer->endpoint = h->bulk_out;
+    info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
+    info->transfer->length = len;
+    info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
+    info->transfer->num_iso_packets = 0;
+
+    int rc = perform_usb_transfer(h, info, std::move(lock));
+    LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
+    return rc;
+}
+
+int usb_read(usb_handle* h, void* d, int len) {
+    LOG(DEBUG) << "usb_read of length " << len;
+
+    std::unique_lock<std::mutex> lock(h->device_handle_mutex);
+    if (!h->device_handle) {
+        errno = EIO;
+        return -1;
+    }
+
+    transfer_info* info = &h->read;
+    info->transfer->dev_handle = h->device_handle;
+    info->transfer->flags = 0;
+    info->transfer->endpoint = h->bulk_in;
+    info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
+    info->transfer->length = len;
+    info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
+    info->transfer->num_iso_packets = 0;
+
+    int rc = perform_usb_transfer(h, info, std::move(lock));
+    LOG(DEBUG) << "usb_read(" << len << ") = " << rc;
+    return rc;
+}
+
+int usb_close(usb_handle* h) {
+    std::unique_lock<std::mutex> lock(usb_handles_mutex);
+    auto it = usb_handles.find(h->device_address);
+    if (it == usb_handles.end()) {
+        LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
+    }
+    usb_handles.erase(h->device_address);
+    return 0;
+}
+
+void usb_kick(usb_handle* h) {
+    h->Close();
+}
+} // namespace libusb
diff --git a/adb/client/usb_linux.cpp b/adb/client/usb_linux.cpp
new file mode 100644
index 0000000..13b7674
--- /dev/null
+++ b/adb/client/usb_linux.cpp
@@ -0,0 +1,600 @@
+/*
+ * 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.
+ */
+
+#define TRACE_TAG USB
+
+#include "sysdeps.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/usb/ch9.h>
+#include <linux/usbdevice_fs.h>
+#include <linux/version.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <chrono>
+#include <condition_variable>
+#include <list>
+#include <mutex>
+#include <string>
+#include <thread>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "adb.h"
+#include "transport.h"
+#include "usb.h"
+
+using namespace std::chrono_literals;
+using namespace std::literals;
+
+/* usb scan debugging is waaaay too verbose */
+#define DBGX(x...)
+
+namespace native {
+struct usb_handle : public ::usb_handle {
+    ~usb_handle() {
+      if (fd != -1) unix_close(fd);
+    }
+
+    std::string path;
+    int fd = -1;
+    unsigned char ep_in;
+    unsigned char ep_out;
+
+    unsigned zero_mask;
+    unsigned writeable = 1;
+
+    usbdevfs_urb urb_in;
+    usbdevfs_urb urb_out;
+
+    bool urb_in_busy = false;
+    bool urb_out_busy = false;
+    bool dead = false;
+
+    std::condition_variable cv;
+    std::mutex mutex;
+
+    // for garbage collecting disconnected devices
+    bool mark;
+
+    // ID of thread currently in REAPURB
+    pthread_t reaper_thread = 0;
+};
+
+static auto& g_usb_handles_mutex = *new std::mutex();
+static auto& g_usb_handles = *new std::list<usb_handle*>();
+
+static int is_known_device(const char* dev_name) {
+    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+    for (usb_handle* usb : g_usb_handles) {
+        if (usb->path == dev_name) {
+            // set mark flag to indicate this device is still alive
+            usb->mark = true;
+            return 1;
+        }
+    }
+    return 0;
+}
+
+static void kick_disconnected_devices() {
+    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+    // kick any devices in the device list that were not found in the device scan
+    for (usb_handle* usb : g_usb_handles) {
+        if (!usb->mark) {
+            usb_kick(usb);
+        } else {
+            usb->mark = false;
+        }
+    }
+}
+
+static inline bool contains_non_digit(const char* name) {
+    while (*name) {
+        if (!isdigit(*name++)) return true;
+    }
+    return false;
+}
+
+static void find_usb_device(const std::string& base,
+        void (*register_device_callback)
+                (const char*, const char*, unsigned char, unsigned char, int, int, unsigned))
+{
+    std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
+    if (!bus_dir) return;
+
+    dirent* de;
+    while ((de = readdir(bus_dir.get())) != 0) {
+        if (contains_non_digit(de->d_name)) continue;
+
+        std::string bus_name = base + "/" + de->d_name;
+
+        std::unique_ptr<DIR, int(*)(DIR*)> dev_dir(opendir(bus_name.c_str()), closedir);
+        if (!dev_dir) continue;
+
+        while ((de = readdir(dev_dir.get()))) {
+            unsigned char devdesc[4096];
+            unsigned char* bufptr = devdesc;
+            unsigned char* bufend;
+            struct usb_device_descriptor* device;
+            struct usb_config_descriptor* config;
+            struct usb_interface_descriptor* interface;
+            struct usb_endpoint_descriptor *ep1, *ep2;
+            unsigned zero_mask = 0;
+            unsigned vid, pid;
+
+            if (contains_non_digit(de->d_name)) continue;
+
+            std::string dev_name = bus_name + "/" + de->d_name;
+            if (is_known_device(dev_name.c_str())) {
+                continue;
+            }
+
+            int fd = unix_open(dev_name.c_str(), O_RDONLY | O_CLOEXEC);
+            if (fd == -1) {
+                continue;
+            }
+
+            size_t desclength = unix_read(fd, devdesc, sizeof(devdesc));
+            bufend = bufptr + desclength;
+
+                // should have device and configuration descriptors, and atleast two endpoints
+            if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
+                D("desclength %zu is too small", desclength);
+                unix_close(fd);
+                continue;
+            }
+
+            device = (struct usb_device_descriptor*)bufptr;
+            bufptr += USB_DT_DEVICE_SIZE;
+
+            if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
+                unix_close(fd);
+                continue;
+            }
+
+            vid = device->idVendor;
+            pid = device->idProduct;
+            DBGX("[ %s is V:%04x P:%04x ]\n", dev_name.c_str(), vid, pid);
+
+                // should have config descriptor next
+            config = (struct usb_config_descriptor *)bufptr;
+            bufptr += USB_DT_CONFIG_SIZE;
+            if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
+                D("usb_config_descriptor not found");
+                unix_close(fd);
+                continue;
+            }
+
+                // loop through all the descriptors and look for the ADB interface
+            while (bufptr < bufend) {
+                unsigned char length = bufptr[0];
+                unsigned char type = bufptr[1];
+
+                if (type == USB_DT_INTERFACE) {
+                    interface = (struct usb_interface_descriptor *)bufptr;
+                    bufptr += length;
+
+                    if (length != USB_DT_INTERFACE_SIZE) {
+                        D("interface descriptor has wrong size");
+                        break;
+                    }
+
+                    DBGX("bInterfaceClass: %d,  bInterfaceSubClass: %d,"
+                         "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
+                         interface->bInterfaceClass, interface->bInterfaceSubClass,
+                         interface->bInterfaceProtocol, interface->bNumEndpoints);
+
+                    if (interface->bNumEndpoints == 2 &&
+                        is_adb_interface(interface->bInterfaceClass, interface->bInterfaceSubClass,
+                                         interface->bInterfaceProtocol)) {
+                        struct stat st;
+                        char pathbuf[128];
+                        char link[256];
+                        char *devpath = nullptr;
+
+                        DBGX("looking for bulk endpoints\n");
+                            // looks like ADB...
+                        ep1 = (struct usb_endpoint_descriptor *)bufptr;
+                        bufptr += USB_DT_ENDPOINT_SIZE;
+                            // For USB 3.0 SuperSpeed devices, skip potential
+                            // USB 3.0 SuperSpeed Endpoint Companion descriptor
+                        if (bufptr+2 <= devdesc + desclength &&
+                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
+                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
+                            bufptr += USB_DT_SS_EP_COMP_SIZE;
+                        }
+                        ep2 = (struct usb_endpoint_descriptor *)bufptr;
+                        bufptr += USB_DT_ENDPOINT_SIZE;
+                        if (bufptr+2 <= devdesc + desclength &&
+                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
+                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
+                            bufptr += USB_DT_SS_EP_COMP_SIZE;
+                        }
+
+                        if (bufptr > devdesc + desclength ||
+                            ep1->bLength != USB_DT_ENDPOINT_SIZE ||
+                            ep1->bDescriptorType != USB_DT_ENDPOINT ||
+                            ep2->bLength != USB_DT_ENDPOINT_SIZE ||
+                            ep2->bDescriptorType != USB_DT_ENDPOINT) {
+                            D("endpoints not found");
+                            break;
+                        }
+
+                            // both endpoints should be bulk
+                        if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
+                            ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
+                            D("bulk endpoints not found");
+                            continue;
+                        }
+                            /* aproto 01 needs 0 termination */
+                        if(interface->bInterfaceProtocol == 0x01) {
+                            zero_mask = ep1->wMaxPacketSize - 1;
+                        }
+
+                            // we have a match.  now we just need to figure out which is in and which is out.
+                        unsigned char local_ep_in, local_ep_out;
+                        if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
+                            local_ep_in = ep1->bEndpointAddress;
+                            local_ep_out = ep2->bEndpointAddress;
+                        } else {
+                            local_ep_in = ep2->bEndpointAddress;
+                            local_ep_out = ep1->bEndpointAddress;
+                        }
+
+                            // Determine the device path
+                        if (!fstat(fd, &st) && S_ISCHR(st.st_mode)) {
+                            snprintf(pathbuf, sizeof(pathbuf), "/sys/dev/char/%d:%d",
+                                     major(st.st_rdev), minor(st.st_rdev));
+                            ssize_t link_len = readlink(pathbuf, link, sizeof(link) - 1);
+                            if (link_len > 0) {
+                                link[link_len] = '\0';
+                                const char* slash = strrchr(link, '/');
+                                if (slash) {
+                                    snprintf(pathbuf, sizeof(pathbuf),
+                                             "usb:%s", slash + 1);
+                                    devpath = pathbuf;
+                                }
+                            }
+                        }
+
+                        register_device_callback(dev_name.c_str(), devpath,
+                                local_ep_in, local_ep_out,
+                                interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
+                        break;
+                    }
+                } else {
+                    bufptr += length;
+                }
+            } // end of while
+
+            unix_close(fd);
+        }
+    }
+}
+
+static int usb_bulk_write(usb_handle* h, const void* data, int len) {
+    std::unique_lock<std::mutex> lock(h->mutex);
+    D("++ usb_bulk_write ++");
+
+    usbdevfs_urb* urb = &h->urb_out;
+    memset(urb, 0, sizeof(*urb));
+    urb->type = USBDEVFS_URB_TYPE_BULK;
+    urb->endpoint = h->ep_out;
+    urb->status = -1;
+    urb->buffer = const_cast<void*>(data);
+    urb->buffer_length = len;
+
+    if (h->dead) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
+        return -1;
+    }
+
+    h->urb_out_busy = true;
+    while (true) {
+        auto now = std::chrono::system_clock::now();
+        if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
+            // TODO: call USBDEVFS_DISCARDURB?
+            errno = ETIMEDOUT;
+            return -1;
+        }
+        if (!h->urb_out_busy) {
+            if (urb->status != 0) {
+                errno = -urb->status;
+                return -1;
+            }
+            return urb->actual_length;
+        }
+    }
+}
+
+static int usb_bulk_read(usb_handle* h, void* data, int len) {
+    std::unique_lock<std::mutex> lock(h->mutex);
+    D("++ usb_bulk_read ++");
+
+    usbdevfs_urb* urb = &h->urb_in;
+    memset(urb, 0, sizeof(*urb));
+    urb->type = USBDEVFS_URB_TYPE_BULK;
+    urb->endpoint = h->ep_in;
+    urb->status = -1;
+    urb->buffer = data;
+    urb->buffer_length = len;
+
+    if (h->dead) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
+        return -1;
+    }
+
+    h->urb_in_busy = true;
+    while (true) {
+        D("[ reap urb - wait ]");
+        h->reaper_thread = pthread_self();
+        int fd = h->fd;
+        lock.unlock();
+
+        // This ioctl must not have TEMP_FAILURE_RETRY because we send SIGALRM to break out.
+        usbdevfs_urb* out = nullptr;
+        int res = ioctl(fd, USBDEVFS_REAPURB, &out);
+        int saved_errno = errno;
+
+        lock.lock();
+        h->reaper_thread = 0;
+        if (h->dead) {
+            errno = EINVAL;
+            return -1;
+        }
+        if (res < 0) {
+            if (saved_errno == EINTR) {
+                continue;
+            }
+            D("[ reap urb - error ]");
+            errno = saved_errno;
+            return -1;
+        }
+        D("[ urb @%p status = %d, actual = %d ]", out, out->status, out->actual_length);
+
+        if (out == &h->urb_in) {
+            D("[ reap urb - IN complete ]");
+            h->urb_in_busy = false;
+            if (urb->status != 0) {
+                errno = -urb->status;
+                return -1;
+            }
+            return urb->actual_length;
+        }
+        if (out == &h->urb_out) {
+            D("[ reap urb - OUT compelete ]");
+            h->urb_out_busy = false;
+            h->cv.notify_all();
+        }
+    }
+}
+
+
+int usb_write(usb_handle *h, const void *_data, int len)
+{
+    D("++ usb_write ++");
+
+    unsigned char *data = (unsigned char*) _data;
+    int n = usb_bulk_write(h, data, len);
+    if (n != len) {
+        D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno));
+        return -1;
+    }
+
+    if (h->zero_mask && !(len & h->zero_mask)) {
+        // If we need 0-markers and our transfer is an even multiple of the packet size,
+        // then send a zero marker.
+        return usb_bulk_write(h, _data, 0);
+    }
+
+    D("-- usb_write --");
+    return 0;
+}
+
+int usb_read(usb_handle *h, void *_data, int len)
+{
+    unsigned char *data = (unsigned char*) _data;
+    int n;
+
+    D("++ usb_read ++");
+    while(len > 0) {
+        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((errno == ETIMEDOUT) && (h->fd != -1)) {
+                D("[ timeout ]");
+                if(n > 0){
+                    data += n;
+                    len -= n;
+                }
+                continue;
+            }
+            D("ERROR: n = %d, errno = %d (%s)",
+                n, errno, strerror(errno));
+            return -1;
+        }
+
+        len -= xfer;
+        data += xfer;
+    }
+
+    D("-- usb_read --");
+    return 0;
+}
+
+void usb_kick(usb_handle* h) {
+    std::lock_guard<std::mutex> lock(h->mutex);
+    D("[ kicking %p (fd = %d) ]", h, h->fd);
+    if (!h->dead) {
+        h->dead = true;
+
+        if (h->writeable) {
+            /* HACK ALERT!
+            ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
+            ** This is a workaround for that problem.
+            */
+            if (h->reaper_thread) {
+                pthread_kill(h->reaper_thread, SIGALRM);
+            }
+
+            /* cancel any pending transactions
+            ** these will quietly fail if the txns are not active,
+            ** but this ensures that a reader blocked on REAPURB
+            ** will get unblocked
+            */
+            ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in);
+            ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out);
+            h->urb_in.status = -ENODEV;
+            h->urb_out.status = -ENODEV;
+            h->urb_in_busy = false;
+            h->urb_out_busy = false;
+            h->cv.notify_all();
+        } else {
+            unregister_usb_transport(h);
+        }
+    }
+}
+
+int usb_close(usb_handle* h) {
+    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+    g_usb_handles.remove(h);
+
+    D("-- usb close %p (fd = %d) --", h, h->fd);
+
+    delete h;
+
+    return 0;
+}
+
+static void register_device(const char* dev_name, const char* dev_path,
+                            unsigned char ep_in, unsigned char ep_out,
+                            int interface, int serial_index,
+                            unsigned zero_mask) {
+    // Since Linux will not reassign the device ID (and dev_name) as long as the
+    // device is open, we can add to the list here once we open it and remove
+    // from the list when we're finally closed and everything will work out
+    // fine.
+    //
+    // If we have a usb_handle on the list of handles with a matching name, we
+    // have no further work to do.
+    {
+        std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+        for (usb_handle* usb: g_usb_handles) {
+            if (usb->path == dev_name) {
+                return;
+            }
+        }
+    }
+
+    D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface);
+    std::unique_ptr<usb_handle> usb(new usb_handle);
+    usb->path = dev_name;
+    usb->ep_in = ep_in;
+    usb->ep_out = ep_out;
+    usb->zero_mask = zero_mask;
+
+    // Initialize mark so we don't get garbage collected after the device scan.
+    usb->mark = true;
+
+    usb->fd = unix_open(usb->path.c_str(), O_RDWR | O_CLOEXEC);
+    if (usb->fd == -1) {
+        // Opening RW failed, so see if we have RO access.
+        usb->fd = unix_open(usb->path.c_str(), O_RDONLY | O_CLOEXEC);
+        if (usb->fd == -1) {
+            D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno));
+            return;
+        }
+        usb->writeable = 0;
+    }
+
+    D("[ usb opened %s%s, fd=%d]",
+      usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd);
+
+    if (usb->writeable) {
+        if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) {
+            D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno));
+            return;
+        }
+    }
+
+    // Read the device's serial number.
+    std::string serial_path = android::base::StringPrintf(
+        "/sys/bus/usb/devices/%s/serial", dev_path + 4);
+    std::string serial;
+    if (!android::base::ReadFileToString(serial_path, &serial)) {
+        D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno));
+        // We don't actually want to treat an unknown serial as an error because
+        // devices aren't able to communicate a serial number in early bringup.
+        // http://b/20883914
+        serial = "";
+    }
+    serial = android::base::Trim(serial);
+
+    // Add to the end of the active handles.
+    usb_handle* done_usb = usb.release();
+    {
+        std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+        g_usb_handles.push_back(done_usb);
+    }
+    register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
+}
+
+static void device_poll_thread(void*) {
+    adb_thread_setname("device poll");
+    D("Created device thread");
+    while (true) {
+        // TODO: Use inotify.
+        find_usb_device("/dev/bus/usb", register_device);
+        kick_disconnected_devices();
+        std::this_thread::sleep_for(1s);
+    }
+}
+
+void usb_init() {
+    struct sigaction actions;
+    memset(&actions, 0, sizeof(actions));
+    sigemptyset(&actions.sa_mask);
+    actions.sa_flags = 0;
+    actions.sa_handler = [](int) {};
+    sigaction(SIGALRM, &actions, nullptr);
+
+    if (!adb_thread_create(device_poll_thread, nullptr)) {
+        fatal_errno("cannot create device_poll thread");
+    }
+}
+} // namespace native
diff --git a/adb/client/usb_osx.cpp b/adb/client/usb_osx.cpp
new file mode 100644
index 0000000..d4fc7c0
--- /dev/null
+++ b/adb/client/usb_osx.cpp
@@ -0,0 +1,563 @@
+/*
+ * 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.
+ */
+
+#define TRACE_TAG USB
+
+#include "sysdeps.h"
+
+#include <CoreFoundation/CoreFoundation.h>
+
+#include <IOKit/IOKitLib.h>
+#include <IOKit/IOCFPlugIn.h>
+#include <IOKit/usb/IOUSBLib.h>
+#include <IOKit/IOMessage.h>
+#include <mach/mach_port.h>
+
+#include <inttypes.h>
+#include <stdio.h>
+
+#include <atomic>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+
+#include "adb.h"
+#include "transport.h"
+
+using namespace std::chrono_literals;
+
+namespace native {
+struct usb_handle
+{
+    UInt8 bulkIn;
+    UInt8 bulkOut;
+    IOUSBInterfaceInterface190** interface;
+    unsigned int zero_mask;
+
+    // For garbage collecting disconnected devices.
+    bool mark;
+    std::string devpath;
+    std::atomic<bool> dead;
+
+    usb_handle() : bulkIn(0), bulkOut(0), interface(nullptr),
+        zero_mask(0), mark(false), dead(false) {
+    }
+};
+
+static std::atomic<bool> usb_inited_flag;
+
+static auto& g_usb_handles_mutex = *new std::mutex();
+static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
+
+static bool IsKnownDevice(const std::string& devpath) {
+    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
+    for (auto& usb : g_usb_handles) {
+        if (usb->devpath == devpath) {
+            // Set mark flag to indicate this device is still alive.
+            usb->mark = true;
+            return true;
+        }
+    }
+    return false;
+}
+
+static void usb_kick_locked(usb_handle* handle);
+
+static void KickDisconnectedDevices() {
+    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
+    for (auto& usb : g_usb_handles) {
+        if (!usb->mark) {
+            usb_kick_locked(usb.get());
+        } else {
+            usb->mark = false;
+        }
+    }
+}
+
+static void AddDevice(std::unique_ptr<usb_handle> handle) {
+    handle->mark = true;
+    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+    g_usb_handles.push_back(std::move(handle));
+}
+
+static void AndroidInterfaceAdded(io_iterator_t iterator);
+static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface190 **iface,
+                                                  UInt16 vendor, UInt16 product);
+
+static bool FindUSBDevices() {
+    // Create the matching dictionary to find the Android device's adb interface.
+    CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
+    if (!matchingDict) {
+        LOG(ERROR) << "couldn't create USB matching dictionary";
+        return false;
+    }
+    // Create an iterator for all I/O Registry objects that match the dictionary.
+    io_iterator_t iter = 0;
+    kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
+    if (kr != KERN_SUCCESS) {
+        LOG(ERROR) << "failed to get matching services";
+        return false;
+    }
+    // Iterate over all matching objects.
+    AndroidInterfaceAdded(iter);
+    IOObjectRelease(iter);
+    return true;
+}
+
+static void
+AndroidInterfaceAdded(io_iterator_t iterator)
+{
+    kern_return_t            kr;
+    io_service_t             usbDevice;
+    io_service_t             usbInterface;
+    IOCFPlugInInterface      **plugInInterface = NULL;
+    IOUSBInterfaceInterface220  **iface = NULL;
+    IOUSBDeviceInterface197  **dev = NULL;
+    HRESULT                  result;
+    SInt32                   score;
+    uint32_t                 locationId;
+    UInt8                    if_class, subclass, protocol;
+    UInt16                   vendor;
+    UInt16                   product;
+    UInt8                    serialIndex;
+    char                     serial[256];
+    std::string devpath;
+
+    while ((usbInterface = IOIteratorNext(iterator))) {
+        //* Create an intermediate interface plugin
+        kr = IOCreatePlugInInterfaceForService(usbInterface,
+                                               kIOUSBInterfaceUserClientTypeID,
+                                               kIOCFPlugInInterfaceID,
+                                               &plugInInterface, &score);
+        IOObjectRelease(usbInterface);
+        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
+            LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
+            continue;
+        }
+
+        //* This gets us the interface object
+        result = (*plugInInterface)->QueryInterface(
+            plugInInterface,
+            CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID*)&iface);
+        //* We only needed the plugin to get the interface, so discard it
+        (*plugInInterface)->Release(plugInInterface);
+        if (result || !iface) {
+            LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
+            continue;
+        }
+
+        kr = (*iface)->GetInterfaceClass(iface, &if_class);
+        kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
+        kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
+        if(if_class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
+            // Ignore non-ADB devices.
+            LOG(DEBUG) << "Ignoring interface with incorrect class/subclass/protocol - " << if_class
+                       << ", " << subclass << ", " << protocol;
+            (*iface)->Release(iface);
+            continue;
+        }
+
+        //* this gets us an ioservice, with which we will find the actual
+        //* device; after getting a plugin, and querying the interface, of
+        //* course.
+        //* Gotta love OS X
+        kr = (*iface)->GetDevice(iface, &usbDevice);
+        if (kIOReturnSuccess != kr || !usbDevice) {
+            LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
+            (*iface)->Release(iface);
+            continue;
+        }
+
+        plugInInterface = NULL;
+        score = 0;
+        //* create an intermediate device plugin
+        kr = IOCreatePlugInInterfaceForService(usbDevice,
+                                               kIOUSBDeviceUserClientTypeID,
+                                               kIOCFPlugInInterfaceID,
+                                               &plugInInterface, &score);
+        //* only needed this to find the plugin
+        (void)IOObjectRelease(usbDevice);
+        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
+            LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
+            (*iface)->Release(iface);
+            continue;
+        }
+
+        result = (*plugInInterface)->QueryInterface(plugInInterface,
+            CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID*)&dev);
+        //* only needed this to query the plugin
+        (*plugInInterface)->Release(plugInInterface);
+        if (result || !dev) {
+            LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
+            (*iface)->Release(iface);
+            continue;
+        }
+
+        //* Now after all that, we actually have a ref to the device and
+        //* the interface that matched our criteria
+        kr = (*dev)->GetDeviceVendor(dev, &vendor);
+        kr = (*dev)->GetDeviceProduct(dev, &product);
+        kr = (*dev)->GetLocationID(dev, &locationId);
+        if (kr == KERN_SUCCESS) {
+            devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
+            if (IsKnownDevice(devpath)) {
+                (*dev)->Release(dev);
+                (*iface)->Release(iface);
+                continue;
+            }
+        }
+        kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
+
+        if (serialIndex > 0) {
+            IOUSBDevRequest req;
+            UInt16          buffer[256];
+            UInt16          languages[128];
+
+            memset(languages, 0, sizeof(languages));
+
+            req.bmRequestType =
+                    USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+            req.bRequest = kUSBRqGetDescriptor;
+            req.wValue = (kUSBStringDesc << 8) | 0;
+            req.wIndex = 0;
+            req.pData = languages;
+            req.wLength = sizeof(languages);
+            kr = (*dev)->DeviceRequest(dev, &req);
+
+            if (kr == kIOReturnSuccess && req.wLenDone > 0) {
+
+                int langCount = (req.wLenDone - 2) / 2, lang;
+
+                for (lang = 1; lang <= langCount; lang++) {
+
+                    memset(buffer, 0, sizeof(buffer));
+                    memset(&req, 0, sizeof(req));
+
+                    req.bmRequestType =
+                            USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+                    req.bRequest = kUSBRqGetDescriptor;
+                    req.wValue = (kUSBStringDesc << 8) | serialIndex;
+                    req.wIndex = languages[lang];
+                    req.pData = buffer;
+                    req.wLength = sizeof(buffer);
+                    kr = (*dev)->DeviceRequest(dev, &req);
+
+                    if (kr == kIOReturnSuccess && req.wLenDone > 0) {
+                        int i, count;
+
+                        // skip first word, and copy the rest to the serial string,
+                        // changing shorts to bytes.
+                        count = (req.wLenDone - 1) / 2;
+                        for (i = 0; i < count; i++)
+                                serial[i] = buffer[i + 1];
+                        serial[i] = 0;
+                        break;
+                    }
+                }
+            }
+        }
+
+        (*dev)->Release(dev);
+
+        VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
+                        vendor, product, serial);
+        if (devpath.empty()) {
+            devpath = serial;
+        }
+        if (IsKnownDevice(devpath)) {
+            (*iface)->USBInterfaceClose(iface);
+            (*iface)->Release(iface);
+            continue;
+        }
+
+        std::unique_ptr<usb_handle> handle = CheckInterface((IOUSBInterfaceInterface190**)iface,
+                                                            vendor, product);
+        if (handle == nullptr) {
+            LOG(ERROR) << "Could not find device interface";
+            (*iface)->Release(iface);
+            continue;
+        }
+        handle->devpath = devpath;
+        usb_handle* handle_p = handle.get();
+        VLOG(USB) << "Add usb device " << serial;
+        AddDevice(std::move(handle));
+        register_usb_transport(reinterpret_cast<::usb_handle*>(handle_p), serial, devpath.c_str(),
+                               1);
+    }
+}
+
+// Used to clear both the endpoints before starting.
+// When adb quits, we might clear the host endpoint but not the device.
+// So we make sure both sides are clear before starting up.
+static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface190** interface, UInt8 bulkEp) {
+    IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
+    if (rc != kIOReturnSuccess) {
+        LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
+        return false;
+    }
+    return true;
+}
+
+//* TODO: simplify this further since we only register to get ADB interface
+//* subclass+protocol events
+static std::unique_ptr<usb_handle>
+CheckInterface(IOUSBInterfaceInterface190 **interface, UInt16 vendor, UInt16 product)
+{
+    std::unique_ptr<usb_handle> handle;
+    IOReturn kr;
+    UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
+    UInt8 endpoint;
+
+    //* Now open the interface.  This will cause the pipes associated with
+    //* the endpoints in the interface descriptor to be instantiated
+    kr = (*interface)->USBInterfaceOpen(interface);
+    if (kr != kIOReturnSuccess) {
+        LOG(ERROR) << "Could not open interface: " << std::hex << kr;
+        return NULL;
+    }
+
+    //* Get the number of endpoints associated with this interface
+    kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
+    if (kr != kIOReturnSuccess) {
+        LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
+        goto err_get_num_ep;
+    }
+
+    //* Get interface class, subclass and protocol
+    if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
+            (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
+            (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
+            LOG(ERROR) << "Unable to get interface class, subclass and protocol";
+            goto err_get_interface_class;
+    }
+
+    //* check to make sure interface class, subclass and protocol match ADB
+    //* avoid opening mass storage endpoints
+    if (!is_adb_interface(interfaceClass, interfaceSubClass, interfaceProtocol)) {
+        goto err_bad_adb_interface;
+    }
+
+    handle.reset(new usb_handle);
+    if (handle == nullptr) {
+        goto err_bad_adb_interface;
+    }
+
+    //* Iterate over the endpoints for this interface and find the first
+    //* bulk in/out pipes available.  These will be our read/write pipes.
+    for (endpoint = 1; endpoint <= interfaceNumEndpoints; endpoint++) {
+        UInt8   transferType;
+        UInt16  maxPacketSize;
+        UInt8   interval;
+        UInt8   number;
+        UInt8   direction;
+
+        kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
+                &number, &transferType, &maxPacketSize, &interval);
+        if (kr != kIOReturnSuccess) {
+            LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
+                       << std::hex << kr;
+            goto err_get_pipe_props;
+        }
+
+        if (kUSBBulk != transferType) continue;
+
+        if (kUSBIn == direction) {
+            handle->bulkIn = endpoint;
+            if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) goto err_get_pipe_props;
+        }
+
+        if (kUSBOut == direction) {
+            handle->bulkOut = endpoint;
+            if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) goto err_get_pipe_props;
+        }
+
+        handle->zero_mask = maxPacketSize - 1;
+    }
+
+    handle->interface = interface;
+    return handle;
+
+err_get_pipe_props:
+err_bad_adb_interface:
+err_get_interface_class:
+err_get_num_ep:
+    (*interface)->USBInterfaceClose(interface);
+    return nullptr;
+}
+
+std::mutex& operate_device_lock = *new std::mutex();
+
+static void RunLoopThread(void* unused) {
+    adb_thread_setname("RunLoop");
+
+    VLOG(USB) << "RunLoopThread started";
+    while (true) {
+        {
+            std::lock_guard<std::mutex> lock_guard(operate_device_lock);
+            FindUSBDevices();
+            KickDisconnectedDevices();
+        }
+        // Signal the parent that we are running
+        usb_inited_flag = true;
+        std::this_thread::sleep_for(1s);
+    }
+    VLOG(USB) << "RunLoopThread done";
+}
+
+static void usb_cleanup() {
+    VLOG(USB) << "usb_cleanup";
+    // Wait until usb operations in RunLoopThread finish, and prevent further operations.
+    operate_device_lock.lock();
+    close_usb_devices();
+}
+
+void usb_init() {
+    static bool initialized = false;
+    if (!initialized) {
+        atexit(usb_cleanup);
+
+        usb_inited_flag = false;
+
+        if (!adb_thread_create(RunLoopThread, nullptr)) {
+            fatal_errno("cannot create RunLoop thread");
+        }
+
+        // Wait for initialization to finish
+        while (!usb_inited_flag) {
+            std::this_thread::sleep_for(100ms);
+        }
+
+        initialized = true;
+    }
+}
+
+int usb_write(usb_handle *handle, const void *buf, int len)
+{
+    IOReturn    result;
+
+    if (!len)
+        return 0;
+
+    if (!handle || handle->dead)
+        return -1;
+
+    if (NULL == handle->interface) {
+        LOG(ERROR) << "usb_write interface was null";
+        return -1;
+    }
+
+    if (0 == handle->bulkOut) {
+        LOG(ERROR) << "bulkOut endpoint not assigned";
+        return -1;
+    }
+
+    result =
+        (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
+
+    if ((result == 0) && (handle->zero_mask)) {
+        /* we need 0-markers and our transfer */
+        if(!(len & handle->zero_mask)) {
+            result =
+                (*handle->interface)->WritePipe(
+                        handle->interface, handle->bulkOut, (void *)buf, 0);
+        }
+    }
+
+    if (0 == result)
+        return 0;
+
+    LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
+    return -1;
+}
+
+int usb_read(usb_handle *handle, void *buf, int len)
+{
+    IOReturn result;
+    UInt32  numBytes = len;
+
+    if (!len) {
+        return 0;
+    }
+
+    if (!handle || handle->dead) {
+        return -1;
+    }
+
+    if (NULL == handle->interface) {
+        LOG(ERROR) << "usb_read interface was null";
+        return -1;
+    }
+
+    if (0 == handle->bulkIn) {
+        LOG(ERROR) << "bulkIn endpoint not assigned";
+        return -1;
+    }
+
+    result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
+
+    if (kIOUSBPipeStalled == result) {
+        LOG(ERROR) << "Pipe stalled, clearing stall.\n";
+        (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
+        result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
+    }
+
+    if (kIOReturnSuccess == result)
+        return 0;
+    else {
+        LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
+    }
+
+    return -1;
+}
+
+int usb_close(usb_handle *handle)
+{
+    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
+    for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
+        if ((*it).get() == handle) {
+            g_usb_handles.erase(it);
+            break;
+        }
+    }
+    return 0;
+}
+
+static void usb_kick_locked(usb_handle *handle)
+{
+    LOG(INFO) << "Kicking handle";
+    /* release the interface */
+    if (!handle)
+        return;
+
+    if (!handle->dead)
+    {
+        handle->dead = true;
+        (*handle->interface)->USBInterfaceClose(handle->interface);
+        (*handle->interface)->Release(handle->interface);
+    }
+}
+
+void usb_kick(usb_handle *handle) {
+    // Use the lock to avoid multiple thread kicking the device at the same time.
+    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
+    usb_kick_locked(handle);
+}
+} // namespace native
diff --git a/adb/client/usb_windows.cpp b/adb/client/usb_windows.cpp
new file mode 100644
index 0000000..640e91e
--- /dev/null
+++ b/adb/client/usb_windows.cpp
@@ -0,0 +1,656 @@
+/*
+ * 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.
+ */
+
+#define TRACE_TAG USB
+
+#include "sysdeps.h"
+
+#include <winsock2.h>  // winsock.h *must* be included before windows.h.
+#include <windows.h>
+#include <usb100.h>
+#include <winerror.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <mutex>
+#include <thread>
+
+#include <adb_api.h>
+
+#include <android-base/errors.h>
+
+#include "adb.h"
+#include "sysdeps/chrono.h"
+#include "transport.h"
+
+/** Structure usb_handle describes our connection to the usb device via
+  AdbWinApi.dll. This structure is returned from usb_open() routine and
+  is expected in each subsequent call that is accessing the device.
+
+  Most members are protected by usb_lock, except for adb_{read,write}_pipe which
+  rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
+  ability to break a thread out of pipe IO.
+*/
+struct usb_handle {
+  /// Previous entry in the list of opened usb handles
+  usb_handle *prev;
+
+  /// Next entry in the list of opened usb handles
+  usb_handle *next;
+
+  /// Handle to USB interface
+  ADBAPIHANDLE  adb_interface;
+
+  /// Handle to USB read pipe (endpoint)
+  ADBAPIHANDLE  adb_read_pipe;
+
+  /// Handle to USB write pipe (endpoint)
+  ADBAPIHANDLE  adb_write_pipe;
+
+  /// Interface name
+  wchar_t*      interface_name;
+
+  /// Mask for determining when to use zero length packets
+  unsigned zero_mask;
+};
+
+/// Class ID assigned to the device by androidusb.sys
+static const GUID usb_class_id = ANDROID_USB_CLASS_ID;
+
+/// List of opened usb handles
+static usb_handle handle_list = {
+  .prev = &handle_list,
+  .next = &handle_list,
+};
+
+/// Locker for the list of opened usb handles
+static std::mutex& usb_lock = *new std::mutex();
+
+/// Checks if there is opened usb handle in handle_list for this device.
+int known_device(const wchar_t* dev_name);
+
+/// Checks if there is opened usb handle in handle_list for this device.
+/// usb_lock mutex must be held before calling this routine.
+int known_device_locked(const wchar_t* dev_name);
+
+/// Registers opened usb handle (adds it to handle_list).
+int register_new_device(usb_handle* handle);
+
+/// Checks if interface (device) matches certain criteria
+int recognized_device(usb_handle* handle);
+
+/// Enumerates present and available interfaces (devices), opens new ones and
+/// registers usb transport for them.
+void find_devices();
+
+/// Kicks all USB devices
+static void kick_devices();
+
+/// 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*);
+
+/// Initializes this module
+void usb_init();
+
+/// Opens usb interface (device) by interface (device) name.
+usb_handle* do_usb_open(const wchar_t* interface_name);
+
+/// Writes data to the opened usb handle
+int usb_write(usb_handle* handle, const void* data, int len);
+
+/// Reads data using the opened usb handle
+int usb_read(usb_handle *handle, void* data, int len);
+
+/// Cleans up opened usb handle
+void usb_cleanup_handle(usb_handle* handle);
+
+/// Cleans up (but don't close) opened usb handle
+void usb_kick(usb_handle* handle);
+
+/// Closes opened usb handle
+int usb_close(usb_handle* handle);
+
+int known_device_locked(const wchar_t* dev_name) {
+  usb_handle* usb;
+
+  if (NULL != dev_name) {
+    // Iterate through the list looking for the name match.
+    for(usb = handle_list.next; usb != &handle_list; usb = usb->next) {
+      // In Windows names are not case sensetive!
+      if((NULL != usb->interface_name) &&
+         (0 == wcsicmp(usb->interface_name, dev_name))) {
+        return 1;
+      }
+    }
+  }
+
+  return 0;
+}
+
+int known_device(const wchar_t* dev_name) {
+  int ret = 0;
+
+  if (NULL != dev_name) {
+    std::lock_guard<std::mutex> lock(usb_lock);
+    ret = known_device_locked(dev_name);
+  }
+
+  return ret;
+}
+
+int register_new_device(usb_handle* handle) {
+  if (NULL == handle)
+    return 0;
+
+  std::lock_guard<std::mutex> lock(usb_lock);
+
+  // Check if device is already in the list
+  if (known_device_locked(handle->interface_name)) {
+    return 0;
+  }
+
+  // Not in the list. Add this handle to the list.
+  handle->next = &handle_list;
+  handle->prev = handle_list.prev;
+  handle->prev->next = handle;
+  handle->next->prev = handle;
+
+  return 1;
+}
+
+void device_poll_thread(void*) {
+  adb_thread_setname("Device Poll");
+  D("Created device thread");
+
+  while (true) {
+    find_devices();
+    std::this_thread::sleep_for(1s);
+  }
+}
+
+static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
+                                           LPARAM lParam) {
+  switch (uMsg) {
+  case WM_POWERBROADCAST:
+    switch (wParam) {
+    case PBT_APMRESUMEAUTOMATIC:
+      // Resuming from sleep or hibernation, so kick all existing USB devices
+      // and then allow the device_poll_thread to redetect USB devices from
+      // scratch. If we don't do this, existing USB devices will never respond
+      // to us because they'll be waiting for the connect/auth handshake.
+      D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
+        "so kicking all USB devices\n");
+      kick_devices();
+      return TRUE;
+    }
+  }
+  return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+}
+
+static void _power_notification_thread(void*) {
+  // 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
+  // heavyweight WMI APIs to get power notifications. But for the common case
+  // of a developer's interactive session, a window message pump is more
+  // appropriate.
+  D("Created power notification thread");
+  adb_thread_setname("Power Notifier");
+
+  // Window class names are process specific.
+  static const WCHAR kPowerNotificationWindowClassName[] =
+    L"PowerNotificationWindow";
+
+  // Get the HINSTANCE corresponding to the module that _power_window_proc
+  // is in (the main module).
+  const HINSTANCE instance = GetModuleHandleW(NULL);
+  if (!instance) {
+    // This is such a common API call that this should never fail.
+    fatal("GetModuleHandleW failed: %s",
+          android::base::SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  WNDCLASSEXW wndclass;
+  memset(&wndclass, 0, sizeof(wndclass));
+  wndclass.cbSize = sizeof(wndclass);
+  wndclass.lpfnWndProc = _power_window_proc;
+  wndclass.hInstance = instance;
+  wndclass.lpszClassName = kPowerNotificationWindowClassName;
+  if (!RegisterClassExW(&wndclass)) {
+    fatal("RegisterClassExW failed: %s",
+          android::base::SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
+                       L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0,
+                       NULL, NULL, instance, NULL)) {
+    fatal("CreateWindowExW failed: %s",
+          android::base::SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  MSG msg;
+  while (GetMessageW(&msg, NULL, 0, 0)) {
+    TranslateMessage(&msg);
+    DispatchMessageW(&msg);
+  }
+
+  // GetMessageW() will return false if a quit message is posted. We don't
+  // do that, but it might be possible for that to occur when logging off or
+  // shutting down. Not a big deal since the whole process will be going away
+  // soon anyway.
+  D("Power notification thread exiting");
+}
+
+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");
+  }
+}
+
+usb_handle* do_usb_open(const wchar_t* interface_name) {
+  unsigned long name_len = 0;
+
+  // Allocate our handle
+  usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
+  if (NULL == ret) {
+    D("Could not allocate %u bytes for usb_handle: %s", sizeof(usb_handle),
+      strerror(errno));
+    goto fail;
+  }
+
+  // Set linkers back to the handle
+  ret->next = ret;
+  ret->prev = ret;
+
+  // Create interface.
+  ret->adb_interface = AdbCreateInterfaceByName(interface_name);
+  if (NULL == ret->adb_interface) {
+    D("AdbCreateInterfaceByName failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // Open read pipe (endpoint)
+  ret->adb_read_pipe =
+    AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
+                                   AdbOpenAccessTypeReadWrite,
+                                   AdbOpenSharingModeReadWrite);
+  if (NULL == ret->adb_read_pipe) {
+    D("AdbOpenDefaultBulkReadEndpoint failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // Open write pipe (endpoint)
+  ret->adb_write_pipe =
+    AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
+                                    AdbOpenAccessTypeReadWrite,
+                                    AdbOpenSharingModeReadWrite);
+  if (NULL == ret->adb_write_pipe) {
+    D("AdbOpenDefaultBulkWriteEndpoint failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // Save interface name
+  // First get expected name length
+  AdbGetInterfaceName(ret->adb_interface,
+                      NULL,
+                      &name_len,
+                      false);
+  if (0 == name_len) {
+    D("AdbGetInterfaceName returned name length of zero: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  ret->interface_name = (wchar_t*)malloc(name_len * sizeof(ret->interface_name[0]));
+  if (NULL == ret->interface_name) {
+    D("Could not allocate %lu characters for interface_name: %s", name_len, strerror(errno));
+    goto fail;
+  }
+
+  // Now save the name
+  if (!AdbGetInterfaceName(ret->adb_interface,
+                           ret->interface_name,
+                           &name_len,
+                           false)) {
+    D("AdbGetInterfaceName failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // We're done at this point
+  return ret;
+
+fail:
+  if (NULL != ret) {
+    usb_cleanup_handle(ret);
+    free(ret);
+  }
+
+  return NULL;
+}
+
+int usb_write(usb_handle* handle, const void* data, int len) {
+  unsigned long time_out = 5000;
+  unsigned long written = 0;
+  int err = 0;
+
+  D("usb_write %d", len);
+  if (NULL == handle) {
+    D("usb_write was passed NULL handle");
+    err = EINVAL;
+    goto fail;
+  }
+
+  // Perform write
+  if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+                            (void*)data,
+                            (unsigned long)len,
+                            &written,
+                            time_out)) {
+    D("AdbWriteEndpointSync failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    err = EIO;
+    goto fail;
+  }
+
+  // Make sure that we've written what we were asked to write
+  D("usb_write got: %ld, expected: %d", written, len);
+  if (written != (unsigned long)len) {
+    // If this occurs, this code should be changed to repeatedly call
+    // AdbWriteEndpointSync() until all bytes are written.
+    D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld",
+      len, written);
+    err = EIO;
+    goto fail;
+  }
+
+  if (handle->zero_mask && (len & handle->zero_mask) == 0) {
+    // Send a zero length packet
+    if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+                              (void*)data,
+                              0,
+                              &written,
+                              time_out)) {
+      D("AdbWriteEndpointSync of zero length packet failed: %s",
+        android::base::SystemErrorCodeToString(GetLastError()).c_str());
+      err = EIO;
+      goto fail;
+    }
+  }
+
+  return 0;
+
+fail:
+  // Any failure should cause us to kick the device instead of leaving it a
+  // zombie state with potential to hang.
+  if (NULL != handle) {
+    D("Kicking device due to error in usb_write");
+    usb_kick(handle);
+  }
+
+  D("usb_write failed");
+  errno = err;
+  return -1;
+}
+
+int usb_read(usb_handle *handle, void* data, int len) {
+  unsigned long time_out = 0;
+  unsigned long read = 0;
+  int err = 0;
+
+  D("usb_read %d", len);
+  if (NULL == handle) {
+    D("usb_read was passed NULL handle");
+    err = EINVAL;
+    goto fail;
+  }
+
+  while (len > 0) {
+    if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
+                             time_out)) {
+      D("AdbReadEndpointSync failed: %s",
+        android::base::SystemErrorCodeToString(GetLastError()).c_str());
+      err = EIO;
+      goto fail;
+    }
+    D("usb_read got: %ld, expected: %d", read, len);
+
+    data = (char *)data + read;
+    len -= read;
+  }
+
+  return 0;
+
+fail:
+  // Any failure should cause us to kick the device instead of leaving it a
+  // zombie state with potential to hang.
+  if (NULL != handle) {
+    D("Kicking device due to error in usb_read");
+    usb_kick(handle);
+  }
+
+  D("usb_read failed");
+  errno = err;
+  return -1;
+}
+
+// Wrapper around AdbCloseHandle() that logs diagnostics.
+static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
+  if (!AdbCloseHandle(adb_handle)) {
+    D("AdbCloseHandle(%p) failed: %s", adb_handle,
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+  }
+}
+
+void usb_cleanup_handle(usb_handle* handle) {
+  D("usb_cleanup_handle");
+  if (NULL != handle) {
+    if (NULL != handle->interface_name)
+      free(handle->interface_name);
+    // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
+    // wait until the pipe no longer uses the interface. Then we can
+    // AdbCloseHandle() the interface.
+    if (NULL != handle->adb_write_pipe)
+      _adb_close_handle(handle->adb_write_pipe);
+    if (NULL != handle->adb_read_pipe)
+      _adb_close_handle(handle->adb_read_pipe);
+    if (NULL != handle->adb_interface)
+      _adb_close_handle(handle->adb_interface);
+
+    handle->interface_name = NULL;
+    handle->adb_write_pipe = NULL;
+    handle->adb_read_pipe = NULL;
+    handle->adb_interface = NULL;
+  }
+}
+
+static void usb_kick_locked(usb_handle* handle) {
+  // The reason the lock must be acquired before calling this function is in
+  // case multiple threads are trying to kick the same device at the same time.
+  usb_cleanup_handle(handle);
+}
+
+void usb_kick(usb_handle* handle) {
+  D("usb_kick");
+  if (NULL != handle) {
+    std::lock_guard<std::mutex> lock(usb_lock);
+    usb_kick_locked(handle);
+  } else {
+    errno = EINVAL;
+  }
+}
+
+int usb_close(usb_handle* handle) {
+  D("usb_close");
+
+  if (NULL != handle) {
+    // Remove handle from the list
+    {
+      std::lock_guard<std::mutex> lock(usb_lock);
+
+      if ((handle->next != handle) && (handle->prev != handle)) {
+        handle->next->prev = handle->prev;
+        handle->prev->next = handle->next;
+        handle->prev = handle;
+        handle->next = handle;
+      }
+    }
+
+    // Cleanup handle
+    usb_cleanup_handle(handle);
+    free(handle);
+  }
+
+  return 0;
+}
+
+int recognized_device(usb_handle* handle) {
+  if (NULL == handle)
+    return 0;
+
+  // Check vendor and product id first
+  USB_DEVICE_DESCRIPTOR device_desc;
+
+  if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
+                                 &device_desc)) {
+    D("AdbGetUsbDeviceDescriptor failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    return 0;
+  }
+
+  // Then check interface properties
+  USB_INTERFACE_DESCRIPTOR interf_desc;
+
+  if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
+                                    &interf_desc)) {
+    D("AdbGetUsbInterfaceDescriptor failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    return 0;
+  }
+
+  // Must have two endpoints
+  if (2 != interf_desc.bNumEndpoints) {
+    return 0;
+  }
+
+  if (is_adb_interface(interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass,
+                       interf_desc.bInterfaceProtocol)) {
+    if (interf_desc.bInterfaceProtocol == 0x01) {
+      AdbEndpointInformation endpoint_info;
+      // assuming zero is a valid bulk endpoint ID
+      if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
+        handle->zero_mask = endpoint_info.max_packet_size - 1;
+        D("device zero_mask: 0x%x", handle->zero_mask);
+      } else {
+        D("AdbGetEndpointInformation failed: %s",
+          android::base::SystemErrorCodeToString(GetLastError()).c_str());
+      }
+    }
+
+    return 1;
+  }
+
+  return 0;
+}
+
+void find_devices() {
+  usb_handle* handle = NULL;
+  char entry_buffer[2048];
+  AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
+  unsigned long entry_buffer_size = sizeof(entry_buffer);
+
+  // Enumerate all present and active interfaces.
+  ADBAPIHANDLE enum_handle =
+    AdbEnumInterfaces(usb_class_id, true, true, true);
+
+  if (NULL == enum_handle) {
+    D("AdbEnumInterfaces failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+    return;
+  }
+
+  while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
+    // Lets see if we already have this device in the list
+    if (!known_device(next_interface->device_name)) {
+      // This seems to be a new device. Open it!
+      handle = do_usb_open(next_interface->device_name);
+      if (NULL != handle) {
+        // Lets see if this interface (device) belongs to us
+        if (recognized_device(handle)) {
+          D("adding a new device %ls", next_interface->device_name);
+
+          // We don't request a wchar_t string from AdbGetSerialNumber() because of a bug in
+          // adb_winusb_interface.cpp:CopyMemory(buffer, ser_num->bString, bytes_written) where the
+          // last parameter should be (str_len * sizeof(wchar_t)). The bug reads 2 bytes past the
+          // end of a stack buffer in the best case, and in the unlikely case of a long serial
+          // number, it will read 2 bytes past the end of a heap allocation. This doesn't affect the
+          // resulting string, but we should avoid the bad reads in the first place.
+          char serial_number[512];
+          unsigned long serial_number_len = sizeof(serial_number);
+          if (AdbGetSerialNumber(handle->adb_interface,
+                                serial_number,
+                                &serial_number_len,
+                                true)) {
+            // Lets make sure that we don't duplicate this device
+            if (register_new_device(handle)) {
+              register_usb_transport(handle, serial_number, NULL, 1);
+            } else {
+              D("register_new_device failed for %ls", next_interface->device_name);
+              usb_cleanup_handle(handle);
+              free(handle);
+            }
+          } else {
+            D("cannot get serial number: %s",
+              android::base::SystemErrorCodeToString(GetLastError()).c_str());
+            usb_cleanup_handle(handle);
+            free(handle);
+          }
+        } else {
+          usb_cleanup_handle(handle);
+          free(handle);
+        }
+      }
+    }
+
+    entry_buffer_size = sizeof(entry_buffer);
+  }
+
+  if (GetLastError() != ERROR_NO_MORE_ITEMS) {
+    // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
+    D("AdbNextInterface failed: %s",
+      android::base::SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  _adb_close_handle(enum_handle);
+}
+
+static void kick_devices() {
+  // Need to acquire lock to safely walk the list which might be modified
+  // by another thread.
+  std::lock_guard<std::mutex> lock(usb_lock);
+  for (usb_handle* usb = handle_list.next; usb != &handle_list; usb = usb->next) {
+    usb_kick_locked(usb);
+  }
+}
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 51d828a..4979eef 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -33,9 +33,12 @@
 
 #include <memory>
 #include <string>
+#include <thread>
 #include <vector>
 
+#include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 
@@ -50,12 +53,14 @@
 #include "adb_auth.h"
 #include "adb_client.h"
 #include "adb_io.h"
+#include "adb_unique_fd.h"
 #include "adb_utils.h"
 #include "bugreport.h"
 #include "commandline.h"
 #include "file_sync_service.h"
 #include "services.h"
 #include "shell_service.h"
+#include "sysdeps/chrono.h"
 
 static int install_app(TransportType t, const char* serial, int argc, const char** argv);
 static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv);
@@ -80,187 +85,152 @@
 }
 
 static void help() {
-    fprintf(stderr, "%s\n", adb_version().c_str());
+    fprintf(stdout, "%s\n", adb_version().c_str());
     // clang-format off
-    fprintf(stderr,
-        " -a                            - directs adb to listen on all interfaces for a connection\n"
-        " -d                            - directs command to the only connected USB device\n"
-        "                                 returns an error if more than one USB device is present.\n"
-        " -e                            - directs command to the only running emulator.\n"
-        "                                 returns an error if more than one emulator is running.\n"
-        " -s <specific device>          - directs command to the device or emulator with the given\n"
-        "                                 serial number or qualifier. Overrides ANDROID_SERIAL\n"
-        "                                 environment variable.\n"
-        " -p <product name or path>     - simple product name like 'sooner', or\n"
-        "                                 a relative/absolute path to a product\n"
-        "                                 out directory like 'out/target/product/sooner'.\n"
-        "                                 If -p is not specified, the ANDROID_PRODUCT_OUT\n"
-        "                                 environment variable is used, which must\n"
-        "                                 be an absolute path.\n"
-        " -H                            - Name of adb server host (default: localhost)\n"
-        " -P                            - Port of adb server (default: 5037)\n"
-        " devices [-l]                  - list all connected devices\n"
-        "                                 ('-l' will also list device qualifiers)\n"
-        " connect <host>[:<port>]       - connect to a device via TCP/IP\n"
-        "                                 Port 5555 is used by default if no port number is specified.\n"
-        " disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.\n"
-        "                                 Port 5555 is used by default if no port number is specified.\n"
-        "                                 Using this command with no additional arguments\n"
-        "                                 will disconnect from all connected TCP/IP devices.\n"
+    fprintf(stdout,
+        "global options:\n"
+        " -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"
+        " -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"
         "\n"
-        "device commands:\n"
-        "  adb push <local>... <remote>\n"
-        "                               - copy files/dirs to device\n"
-        "  adb pull [-a] <remote>... <local>\n"
-        "                               - copy files/dirs from device\n"
-        "                                 (-a preserves file timestamp and mode)\n"
-        "  adb sync [ <directory> ]     - copy host->device only if changed\n"
-        "                                 (-l means list but don't copy)\n"
-        "  adb shell [-e escape] [-n] [-Tt] [-x] [command]\n"
-        "                               - run remote shell command (interactive shell if no command given)\n"
-        "                                 (-e: choose escape character, or \"none\"; default '~')\n"
-        "                                 (-n: don't read from stdin)\n"
-        "                                 (-T: disable PTY allocation)\n"
-        "                                 (-t: force PTY allocation)\n"
-        "                                 (-x: disable remote exit codes and stdout/stderr separation)\n"
-        "  adb emu <command>            - run emulator console command\n"
-        "  adb logcat [ <filter-spec> ] - View device log\n"
-        "  adb forward --list           - list all forward socket connections.\n"
-        "                                 the format is a list of lines with the following format:\n"
-        "                                    <serial> \" \" <local> \" \" <remote> \"\\n\"\n"
-        "  adb forward <local> <remote> - forward socket connections\n"
-        "                                 forward specs are one of: \n"
-        "                                   tcp:<port>\n"
-        "                                   localabstract:<unix domain socket name>\n"
-        "                                   localreserved:<unix domain socket name>\n"
-        "                                   localfilesystem:<unix domain socket name>\n"
-        "                                   dev:<character device name>\n"
-        "                                   jdwp:<process pid> (remote only)\n"
-        "  adb forward --no-rebind <local> <remote>\n"
-        "                               - same as 'adb forward <local> <remote>' but fails\n"
-        "                                 if <local> is already forwarded\n"
-        "  adb forward --remove <local> - remove a specific forward socket connection\n"
-        "  adb forward --remove-all     - remove all forward socket connections\n"
-        "  adb reverse --list           - list all reverse socket connections from device\n"
-        "  adb reverse <remote> <local> - reverse socket connections\n"
-        "                                 reverse specs are one of:\n"
-        "                                   tcp:<port>\n"
-        "                                   localabstract:<unix domain socket name>\n"
-        "                                   localreserved:<unix domain socket name>\n"
-        "                                   localfilesystem:<unix domain socket name>\n"
-        "  adb reverse --no-rebind <remote> <local>\n"
-        "                               - same as 'adb reverse <remote> <local>' but fails\n"
-        "                                 if <remote> is already reversed.\n"
-        "  adb reverse --remove <remote>\n"
-        "                               - remove a specific reversed socket connection\n"
-        "  adb reverse --remove-all     - remove all reversed socket connections from device\n"
-        "  adb jdwp                     - list PIDs of processes hosting a JDWP transport\n"
-        "  adb install [-lrtsdg] <file>\n"
-        "                               - push this package file to the device and install it\n"
-        "                                 (-l: forward lock application)\n"
-        "                                 (-r: replace existing application)\n"
-        "                                 (-t: allow test packages)\n"
-        "                                 (-s: install application on sdcard)\n"
-        "                                 (-d: allow version code downgrade (debuggable packages only))\n"
-        "                                 (-g: grant all runtime permissions)\n"
-        "  adb install-multiple [-lrtsdpg] <file...>\n"
-        "                               - push this package file to the device and install it\n"
-        "                                 (-l: forward lock application)\n"
-        "                                 (-r: replace existing application)\n"
-        "                                 (-t: allow test packages)\n"
-        "                                 (-s: install application on sdcard)\n"
-        "                                 (-d: allow version code downgrade (debuggable packages only))\n"
-        "                                 (-p: partial application install)\n"
-        "                                 (-g: grant all runtime permissions)\n"
-        "  adb uninstall [-k] <package> - remove this app package from the device\n"
-        "                                 ('-k' means keep the data and cache directories)\n"
-        "  adb bugreport [<path>]       - return all information from the device that should be included in a zipped bug report.\n"
-        "                                 If <path> is a file, the bug report will be saved as that file.\n"
-        "                                 If <path> is a directory, the bug report will be saved in that directory with the name provided by the device.\n"
-        "                                 If <path> is omitted, the bug report will be saved in the current directory with the name provided by the device.\n"
-        "                                 NOTE: if the device does not support zipped bug reports, the bug report will be output on stdout.\n"
-        "  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n"
-        "                               - write an archive of the device's data to <file>.\n"
-        "                                 If no -f option is supplied then the data is written\n"
-        "                                 to \"backup.ab\" in the current directory.\n"
-        "                                 (-apk|-noapk enable/disable backup of the .apks themselves\n"
-        "                                    in the archive; the default is noapk.)\n"
-        "                                 (-obb|-noobb enable/disable backup of any installed apk expansion\n"
-        "                                    (aka .obb) files associated with each application; the default\n"
-        "                                    is noobb.)\n"
-        "                                 (-shared|-noshared enable/disable backup of the device's\n"
-        "                                    shared storage / SD card contents; the default is noshared.)\n"
-        "                                 (-all means to back up all installed applications)\n"
-        "                                 (-system|-nosystem toggles whether -all automatically includes\n"
-        "                                    system applications; the default is to include system apps)\n"
-        "                                 (<packages...> is the list of applications to be backed up.  If\n"
-        "                                    the -all or -shared flags are passed, then the package\n"
-        "                                    list is optional.  Applications explicitly given on the\n"
-        "                                    command line will be included even if -nosystem would\n"
-        "                                    ordinarily cause them to be omitted.)\n"
-        "\n"
-        "  adb restore <file>           - restore device contents from the <file> backup archive\n"
-        "\n"
-        "  adb disable-verity           - disable dm-verity checking on USERDEBUG builds\n"
-        "  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds\n"
-        "  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,\n"
-        "                                 and the public key is stored in <file>.pub. Any existing files\n"
-        "                                 are overwritten.\n"
-        "  adb help                     - show this help message\n"
-        "  adb version                  - show version num\n"
-        "\n"
-        "scripting:\n"
-        "  adb wait-for[-<transport>]-<state>\n"
-        "                               - wait for device to be in the given state:\n"
-        "                                 device, recovery, sideload, or bootloader\n"
-        "                                 Transport is: usb, local or any [default=any]\n"
-        "  adb start-server             - ensure that there is a server running\n"
-        "  adb kill-server              - kill the server if it is running\n"
-        "  adb get-state                - prints: offline | bootloader | device\n"
-        "  adb get-serialno             - prints: <serial-number>\n"
-        "  adb get-devpath              - prints: <device-path>\n"
-        "  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n"
-        "  adb reboot [bootloader|recovery]\n"
-        "                               - reboots the device, optionally into the bootloader or recovery program.\n"
-        "  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).\n"
-        "  adb reboot sideload-auto-reboot\n"
-        "                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n"
-        "  adb sideload <file>          - sideloads the given package\n"
-        "  adb root                     - restarts the adbd daemon with root permissions\n"
-        "  adb unroot                   - restarts the adbd daemon without root permissions\n"
-        "  adb usb                      - restarts the adbd daemon listening on USB\n"
-        "  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port\n"
+        "general commands:\n"
+        " devices [-l]             list connected devices (-l for long output)\n"
+        " help                     show this help message\n"
+        " version                  show version num\n"
         "\n"
         "networking:\n"
-        "  adb ppp <tty> [parameters]   - Run PPP over USB.\n"
-        " Note: you should not automatically start a PPP connection.\n"
-        " <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1\n"
-        " [parameters] - Eg. defaultroute debug dump local notty usepeerdns\n"
+        " connect HOST[:PORT]      connect to a device via TCP/IP [default port=5555]\n"
+        " disconnect [HOST[:PORT]]\n"
+        "     disconnect from given TCP/IP device [default port=5555], or all\n"
+        " forward --list           list all forward socket connections\n"
+        " forward [--no-rebind] LOCAL REMOTE\n"
+        "     forward socket connection using:\n"
+        "       tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
+        "       localabstract:<unix domain socket name>\n"
+        "       localreserved:<unix domain socket name>\n"
+        "       localfilesystem:<unix domain socket name>\n"
+        "       dev:<character device name>\n"
+        "       jdwp:<process pid> (remote only)\n"
+        " forward --remove LOCAL   remove specific forward socket connection\n"
+        " forward --remove-all     remove all forward socket connections\n"
+        " ppp TTY [PARAMETER...]   run PPP over USB\n"
+        " reverse --list           list all reverse socket connections from device\n"
+        " reverse [--no-rebind] REMOTE LOCAL\n"
+        "     reverse socket connection using:\n"
+        "       tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
+        "       localabstract:<unix domain socket name>\n"
+        "       localreserved:<unix domain socket name>\n"
+        "       localfilesystem:<unix domain socket name>\n"
+        " reverse --remove REMOTE  remove specific reverse socket connection\n"
+        " reverse --remove-all     remove all reverse socket connections from device\n"
         "\n"
-        "adb sync notes: adb sync [ <directory> ]\n"
-        "  <localdir> can be interpreted in several ways:\n"
+        "file transfer:\n"
+        " push LOCAL... REMOTE\n"
+        "     copy local files/directories to device\n"
+        " 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"
+        "     -l: list but don't copy\n"
         "\n"
-        "  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.\n"
+        "shell:\n"
+        " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
+        "     run remote shell command (interactive shell if no command given)\n"
+        "     -e: choose escape character, or \"none\"; default '~'\n"
+        "     -n: don't read from stdin\n"
+        "     -T: disable PTY allocation\n"
+        "     -t: force PTY allocation\n"
+        "     -x: disable remote exit codes and stdout/stderr separation\n"
+        " emu COMMAND              run emulator console command\n"
         "\n"
-        "  - If it is \"system\", \"vendor\", \"oem\" or \"data\", only the corresponding partition\n"
-        "    is updated.\n"
+        "app installation:\n"
+        " install [-lrtsdg] PACKAGE\n"
+        " install-multiple [-lrtsdpg] PACKAGE...\n"
+        "     push package(s) to the device and install them\n"
+        "     -l: forward lock application\n"
+        "     -r: replace existing application\n"
+        "     -t: allow test packages\n"
+        "     -s: install application on sdcard\n"
+        "     -d: allow version code downgrade (debuggable packages only)\n"
+        "     -p: partial application install (install-multiple only)\n"
+        "     -g: grant all runtime permissions\n"
+        " uninstall [-k] PACKAGE\n"
+        "     remove this app package from the device\n"
+        "     '-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"
+        "\n"
+        "debugging:\n"
+        " bugreport [PATH]\n"
+        "     write bugreport to given PATH [default=bugreport.zip];\n"
+        "     if PATH is a directory, the bug report is saved in that directory.\n"
+        "     devices that don't support zipped bug reports output to stdout.\n"
+        " jdwp                     list pids of processes hosting a JDWP transport\n"
+        " logcat                   show device log (logcat --help for more)\n"
+        "\n"
+        "security:\n"
+        " disable-verity           disable dm-verity checking on userdebug builds\n"
+        " enable-verity            re-enable dm-verity checking on userdebug builds\n"
+        " keygen FILE\n"
+        "     generate adb public/private key; private key stored in FILE,\n"
+        "     public key stored in FILE.pub (existing files overwritten)\n"
+        "\n"
+        "scripting:\n"
+        " wait-for[-TRANSPORT]-STATE\n"
+        "     wait for device to be in the given state\n"
+        "     State: device, recovery, sideload, or bootloader\n"
+        "     Transport: usb, local, or any [default=any]\n"
+        " get-state                print offline | bootloader | device\n"
+        " get-serialno             print <serial-number>\n"
+        " get-devpath              print <device-path>\n"
+        " remount\n"
+        "     remount /system, /vendor, and /oem partitions read-write\n"
+        " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
+        "     reboot the device; defaults to booting system image but\n"
+        "     supports bootloader and recovery too. sideload reboots\n"
+        "     into recovery and automatically starts sideload mode,\n"
+        "     sideload-auto-reboot is the same but reboots after sideloading.\n"
+        " sideload OTAPACKAGE      sideload the given full OTA package\n"
+        " root                     restart adbd with root permissions\n"
+        " unroot                   restart adbd without root permissions\n"
+        " usb                      restart adb server listening on USB\n"
+        " tcpip PORT               restart adb server listening on TCP on PORT\n"
         "\n"
         "internal debugging:\n"
-        "  adb reconnect                  Kick current connection from host side and make it reconnect.\n"
-        "  adb reconnect device           Kick current connection from device side and make it reconnect.\n"
+        " start-server             ensure that there is a server running\n"
+        " 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"
+        "\n"
         "environment variables:\n"
-        "  ADB_TRACE                    - Print debug information. A comma separated list of the following values\n"
-        "                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp\n"
-        "  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.\n"
-        "  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.\n");
+        " $ADB_TRACE\n"
+        "     comma-separated list of debug info to log:\n"
+        "     all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
+        " $ADB_VENDOR_KEYS         colon-separated list of keys (files or directories)\n"
+        " $ANDROID_SERIAL          serial number to connect to (see -s)\n"
+        " $ANDROID_LOG_TAGS        tags to be used by logcat (see logcat --help)\n");
     // clang-format on
 }
 
-int usage() {
-    help();
-    return 1;
-}
-
 #if defined(_WIN32)
 
 // Implemented in sysdeps_win32.cpp.
@@ -713,108 +683,115 @@
 static int adb_shell(int argc, const char** argv) {
     FeatureSet features;
     std::string error;
-
     if (!adb_get_feature_set(&features, &error)) {
         fprintf(stderr, "error: %s\n", error.c_str());
         return 1;
     }
 
-    bool use_shell_protocol = CanUseFeature(features, kFeatureShell2);
-    if (!use_shell_protocol) {
-        D("shell protocol not supported, using raw data transfer");
-    } else {
-        D("using shell protocol");
-    }
+    enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
+
+    // Defaults.
+    char escape_char = '~'; // -e
+    bool use_shell_protocol = CanUseFeature(features, kFeatureShell2); // -x
+    PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
 
     // Parse shell-specific command-line options.
-    // argv[0] is always "shell".
-    --argc;
-    ++argv;
-    int t_arg_count = 0;
-    char escape_char = '~';
-    while (argc) {
-        if (!strcmp(argv[0], "-e")) {
-            if (argc < 2 || !(strlen(argv[1]) == 1 || strcmp(argv[1], "none") == 0)) {
-                fprintf(stderr, "error: -e requires a single-character argument or 'none'\n");
+    argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
+    optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
+    int opt;
+    while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
+        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;
+                }
+                escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
+                break;
+            case 'n':
+                close_stdin();
+                break;
+            case 'x':
+                // This option basically asks for historical behavior, so set options that
+                // correspond to the historical defaults. This is slightly weird in that -Tx
+                // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
+                // be our least worst choice...
+                use_shell_protocol = false;
+                tty = kPtyDefinitely;
+                escape_char = '~';
+                break;
+            case 't':
+                // Like ssh, -t arguments are cumulative so that multiple -t's
+                // are needed to force a PTY.
+                tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
+                break;
+            case 'T':
+                tty = kPtyNo;
+                break;
+            default:
+                // getopt(3) already printed an error message for us.
                 return 1;
-            }
-            escape_char = (strcmp(argv[1], "none") == 0) ? 0 : argv[1][0];
-            argc -= 2;
-            argv += 2;
-        } else if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) {
-            // Like ssh, -t arguments are cumulative so that multiple -t's
-            // are needed to force a PTY.
-            if (argv[0][1] == 't') {
-                ++t_arg_count;
-            } else {
-                t_arg_count = -1;
-            }
-            --argc;
-            ++argv;
-        } else if (!strcmp(argv[0], "-x")) {
-            use_shell_protocol = false;
-            --argc;
-            ++argv;
-        } else if (!strcmp(argv[0], "-n")) {
-            close_stdin();
-
-            --argc;
-            ++argv;
-        } else {
-            break;
         }
     }
 
-    // Legacy shell protocol requires a remote PTY to close the subprocess properly which creates
-    // some weird interactions with -tT.
-    if (!use_shell_protocol && t_arg_count != 0) {
-        if (!CanUseFeature(features, kFeatureShell2)) {
-            fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
-        } else {
-            fprintf(stderr, "error: PTY args -Tt cannot be used with -x\n");
-        }
-        return 1;
-    }
+    bool is_interactive = (optind == argc);
 
-    std::string shell_type_arg;
-    if (CanUseFeature(features, kFeatureShell2)) {
-        if (t_arg_count < 0) {
+    std::string shell_type_arg = kShellServiceArgPty;
+    if (tty == kPtyNo) {
+        shell_type_arg = kShellServiceArgRaw;
+    } else if (tty == kPtyAuto) {
+        // If stdin isn't a TTY, default to a raw shell; this lets
+        // things like `adb shell < my_script.sh` work as expected.
+        // Non-interactive shells should also not have a pty.
+        if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
             shell_type_arg = kShellServiceArgRaw;
-        } else if (t_arg_count == 0) {
-            // If stdin isn't a TTY, default to a raw shell; this lets
-            // things like `adb shell < my_script.sh` work as expected.
-            // Otherwise leave |shell_type_arg| blank which uses PTY for
-            // interactive shells and raw for non-interactive.
-            if (!unix_isatty(STDIN_FILENO)) {
-                shell_type_arg = kShellServiceArgRaw;
-            }
-        } else if (t_arg_count == 1) {
-            // A single -t arg isn't enough to override implicit -T.
-            if (!unix_isatty(STDIN_FILENO)) {
-                fprintf(stderr,
-                        "Remote PTY will not be allocated because stdin is not a terminal.\n"
-                        "Use multiple -t options to force remote PTY allocation.\n");
-                shell_type_arg = kShellServiceArgRaw;
-            } else {
-                shell_type_arg = kShellServiceArgPty;
-            }
+        }
+    } else if (tty == kPtyYes) {
+        // A single -t arg isn't enough to override implicit -T.
+        if (!unix_isatty(STDIN_FILENO)) {
+            fprintf(stderr,
+                    "Remote PTY will not be allocated because stdin is not a terminal.\n"
+                    "Use multiple -t options to force remote PTY allocation.\n");
+            shell_type_arg = kShellServiceArgRaw;
+        }
+    }
+
+    D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
+      escape_char, tty,
+      use_shell_protocol ? "true" : "false",
+      (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
+
+    // Raw mode is only supported when talking to a new device *and* using the shell protocol.
+    if (!use_shell_protocol) {
+        if (shell_type_arg != kShellServiceArgPty) {
+            fprintf(stderr, "error: %s only supports allocating a pty\n",
+                    !CanUseFeature(features, kFeatureShell2) ? "device" : "-x");
+            return 1;
         } else {
-            shell_type_arg = kShellServiceArgPty;
+            // If we're not using the shell protocol, the type argument must be empty.
+            shell_type_arg = "";
         }
     }
 
     std::string command;
-    if (argc) {
+    if (optind < argc) {
         // We don't escape here, just like ssh(1). http://b/20564385.
-        command = android::base::Join(std::vector<const char*>(argv, argv + argc), ' ');
+        command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
     }
 
     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_download_buffer(const char* service, const char* filename) {
+    std::string content;
+    if (!android::base::ReadFileToString(filename, &content)) {
+        fprintf(stderr, "error: couldn't read %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+
+    const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
+    unsigned sz = content.size();
+
     std::string error;
     int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
     if (fd < 0) {
@@ -828,10 +805,8 @@
     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;
-    }
+    const char* x = strrchr(service, ':');
+    if (x) service = x + 1;
 
     while (sz > 0) {
         unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
@@ -844,14 +819,10 @@
         }
         sz -= xfer;
         ptr += xfer;
-        if (show_progress) {
-            printf("sending: '%s' %4d%%    \r", fn, (int)(100LL - ((100LL * sz) / (total))));
-            fflush(stdout);
-        }
+        printf("sending: '%s' %4d%%    \r", filename, (int)(100LL - ((100LL * sz) / (total))));
+        fflush(stdout);
     }
-    if (show_progress) {
-        printf("\n");
-    }
+    printf("\n");
 
     if (!adb_status(fd, &error)) {
         fprintf(stderr,"* error response '%s' *\n", error.c_str());
@@ -884,70 +855,78 @@
  * - When the other side sends "DONEDONE" instead of a block number,
  *   we hang up.
  */
-static int adb_sideload_host(const char* fn) {
-    unsigned sz;
-    size_t xfer = 0;
-    int status;
-    int last_percent = -1;
-    int opt = SIDELOAD_HOST_BLOCK_SIZE;
-
-    printf("loading: '%s'", fn);
-    fflush(stdout);
-    uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz));
-    if (data == 0) {
-        printf("\n");
-        fprintf(stderr, "* cannot read '%s' *\n", fn);
+static int adb_sideload_host(const char* filename) {
+    fprintf(stderr, "opening '%s'...\n", filename);
+    struct stat sb;
+    if (stat(filename, &sb) == -1) {
+        fprintf(stderr, "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, "failed to open file %s: %s\n", filename, strerror(errno));
         return -1;
     }
 
-    std::string service =
-            android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
+    fprintf(stderr, "connecting...\n");
+    std::string service = android::base::StringPrintf(
+        "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
     std::string error;
-    int 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.
-        printf("\n");
-        status = adb_download_buffer("sideload", fn, data, sz, true);
-        goto done;
+        fprintf(stderr, "falling back to older sideload method...\n");
+        return adb_download_buffer("sideload", filename);
     }
 
-    opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
+    int opt = SIDELOAD_HOST_BLOCK_SIZE;
+    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)) {
+        if (!ReadFdExactly(device_fd, buf, 8)) {
             fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
-            status = -1;
-            goto done;
+            return -1;
         }
         buf[8] = '\0';
 
         if (strcmp("DONEDONE", buf) == 0) {
-            status = 0;
-            break;
+            printf("\rTotal xfer: %.2fx%*s\n",
+                   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) {
+        if (offset >= static_cast<size_t>(sb.st_size)) {
             fprintf(stderr, "* attempt to read block %d past end\n", block);
-            status = -1;
-            goto done;
-        }
-        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;
+            return -1;
         }
 
-        if(!WriteFdExactly(fd, start, to_write)) {
-            adb_status(fd, &error);
+        size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
+        if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<size_t>(sb.st_size)) {
+            to_write = sb.st_size - offset;
+        }
+
+        if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) {
+            fprintf(stderr, "* failed to seek to package block: %s\n", strerror(errno));
+            return -1;
+        }
+        if (!ReadFdExactly(package_fd, buf, to_write)) {
+            fprintf(stderr, "* 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,"* failed to write data '%s' *\n", error.c_str());
-            status = -1;
-            goto done;
+            return -1;
         }
         xfer += to_write;
 
@@ -957,20 +936,13 @@
         // 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;
         }
     }
-
-    printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
-
-  done:
-    if (fd >= 0) adb_close(fd);
-    free(data);
-    return status;
 }
 
 /**
@@ -1081,10 +1053,9 @@
 
 static bool adb_root(const char* command) {
     std::string error;
-    ScopedFd fd;
 
-    fd.Reset(adb_connect(android::base::StringPrintf("%s:", command), &error));
-    if (!fd.valid()) {
+    unique_fd fd(adb_connect(android::base::StringPrintf("%s:", command), &error));
+    if (fd < 0) {
         fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
         return false;
     }
@@ -1094,7 +1065,7 @@
     char* cur = buf;
     ssize_t bytes_left = sizeof(buf);
     while (bytes_left > 0) {
-        ssize_t bytes_read = adb_read(fd.fd(), cur, bytes_left);
+        ssize_t bytes_read = adb_read(fd, cur, bytes_left);
         if (bytes_read == 0) {
             break;
         } else if (bytes_read < 0) {
@@ -1116,12 +1087,10 @@
         return true;
     }
 
-    // Give adbd 500ms to kill itself, then wait-for-device for it to come back up.
-    adb_sleep_ms(500);
-    TransportType type;
-    const char* serial;
-    adb_get_transport(&type, &serial);
-    return wait_for_device("wait-for-any", type, serial);
+    // Give adbd some time to kill itself and come back up.
+    // We can't use wait-for-device because devices (e.g. adb over network) might not come back.
+    std::this_thread::sleep_for(3s);
+    return true;
 }
 
 int send_shell_command(TransportType transport_type, const char* serial, const std::string& command,
@@ -1273,7 +1242,7 @@
 }
 
 static int restore(int argc, const char** argv) {
-    if (argc != 2) return usage();
+    if (argc != 2) return usage("restore requires an argument");
 
     const char* filename = argv[1];
     int tarFd = adb_open(filename, O_RDONLY);
@@ -1325,9 +1294,10 @@
         return hint;
     }
 
-    // If there are any slashes in it, assume it's a relative path;
+    // If any of the OS_PATH_SEPARATORS is found, assume it's a relative path;
     // make it absolute.
-    if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) {
+    // 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");
@@ -1440,7 +1410,7 @@
     return !CanUseFeature(features, kFeatureCmd);
 }
 
-int adb_commandline(int argc, const char **argv) {
+int adb_commandline(int argc, const char** argv) {
     int no_daemon = 0;
     int is_daemon = 0;
     int is_server = 0;
@@ -1464,18 +1434,9 @@
     }
     // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
 
-    /* Validate and assign the server port */
-    const char* server_port_str = getenv("ANDROID_ADB_SERVER_PORT");
-    int server_port = DEFAULT_ADB_PORT;
-    if (server_port_str && strlen(server_port_str) > 0) {
-        server_port = strtol(server_port_str, nullptr, 0);
-        if (server_port <= 0 || server_port > 65535) {
-            fprintf(stderr,
-                    "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65536. Got \"%s\"\n",
-                    server_port_str);
-            return usage();
-        }
-    }
+    const char* server_host_str = nullptr;
+    const char* server_port_str = nullptr;
+    const char* server_socket_str = nullptr;
 
     // We need to check for -d and -e before we look at $ANDROID_SERIAL.
     const char* serial = nullptr;
@@ -1489,19 +1450,19 @@
             /* 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();
+            if (argc < 2) return usage("--reply-fd requires an argument");
             const char* reply_fd_str = argv[1];
             argc--;
             argv++;
             ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
             if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
                 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
-                return usage();
+                return 1;
             }
         } else if (!strncmp(argv[0], "-p", 2)) {
             const char* product = nullptr;
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage();
+                if (argc < 2) return usage("-p requires an argument");
                 product = argv[1];
                 argc--;
                 argv++;
@@ -1511,13 +1472,13 @@
             gProductOutPath = find_product_out_path(product);
             if (gProductOutPath.empty()) {
                 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
-                return usage();
+                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();
+                if (argc < 2 || argv[0][2] != '\0') return usage("-s requires an argument");
                 serial = argv[1];
                 argc--;
                 argv++;
@@ -1529,64 +1490,94 @@
         } else if (!strcmp(argv[0],"-a")) {
             gListenAll = 1;
         } else if (!strncmp(argv[0], "-H", 2)) {
-            const char *hostname = NULL;
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage();
-                hostname = argv[1];
+                if (argc < 2) return usage("-H requires an argument");
+                server_host_str = argv[1];
                 argc--;
                 argv++;
             } else {
-                hostname = argv[0] + 2;
+                server_host_str = argv[0] + 2;
             }
-            adb_set_tcp_name(hostname);
-
         } else if (!strncmp(argv[0], "-P", 2)) {
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage();
+                if (argc < 2) return usage("-P requires an argument");
                 server_port_str = argv[1];
                 argc--;
                 argv++;
             } else {
                 server_port_str = argv[0] + 2;
             }
-            if (strlen(server_port_str) > 0) {
-                server_port = (int) strtol(server_port_str, NULL, 0);
-                if (server_port <= 0 || server_port > 65535) {
-                    fprintf(stderr,
-                            "adb: port number must be a positive number less than 65536. Got \"%s\"\n",
-                            server_port_str);
-                    return usage();
-                }
-            } else {
-                fprintf(stderr,
-                "adb: port number must be a positive number less than 65536. Got empty string.\n");
-                return usage();
-            }
+        } else if (!strcmp(argv[0], "-L")) {
+            if (argc < 2) return usage("-L requires an argument");
+            server_socket_str = argv[1];
+            argc--;
+            argv++;
         } else {
-                /* out of recognized modifiers and flags */
+            /* out of recognized modifiers and flags */
             break;
         }
         argc--;
         argv++;
     }
 
+    if ((server_host_str || server_port_str) && server_socket_str) {
+        fprintf(stderr, "adb: -L is incompatible with -H or -P\n");
+        exit(1);
+    }
+
+    // If -L, -H, or -P are specified, ignore environment variables.
+    // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
+    if (!server_host_str && !server_port_str && !server_socket_str) {
+        server_socket_str = getenv("ADB_SERVER_SOCKET");
+    }
+
+    if (!server_socket_str) {
+        // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
+        server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
+
+        int server_port = DEFAULT_ADB_PORT;
+        server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
+        if (server_port_str && strlen(server_port_str) > 0) {
+            if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
+                fprintf(stderr,
+                        "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive"
+                        " number less than 65535. Got \"%s\"\n",
+                        server_port_str);
+                exit(1);
+            }
+        }
+
+        int rc;
+        char* temp;
+        if (server_host_str) {
+            rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
+        } else {
+            rc = asprintf(&temp, "tcp:%d", server_port);
+        }
+        if (rc < 0) {
+            fatal("failed to allocate server socket specification");
+        }
+        server_socket_str = temp;
+    }
+
+    adb_set_socket_spec(server_socket_str);
+
     // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
     if (transport_type == kTransportAny && serial == nullptr) {
         serial = getenv("ANDROID_SERIAL");
     }
 
     adb_set_transport(transport_type, serial);
-    adb_set_tcp_specifics(server_port);
 
     if (is_server) {
         if (no_daemon || is_daemon) {
             if (is_daemon && (ack_reply_fd == -1)) {
                 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
-                return usage();
+                return 1;
             }
-            r = adb_server_main(is_daemon, server_port, ack_reply_fd);
+            r = adb_server_main(is_daemon, server_socket_str, ack_reply_fd);
         } else {
-            r = launch_server(server_port);
+            r = launch_server(server_socket_str);
         }
         if (r) {
             fprintf(stderr,"* could not start server *\n");
@@ -1595,7 +1586,8 @@
     }
 
     if (argc == 0) {
-        return usage();
+        help();
+        return 1;
     }
 
     /* handle wait-for-* prefix */
@@ -1661,6 +1653,11 @@
     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;
+        }
+
         std::string cmd = "exec:";
         cmd += argv[1];
         argc -= 2;
@@ -1707,7 +1704,7 @@
         }
     }
     else if (!strcmp(argv[0], "sideload")) {
-        if (argc != 2) return usage();
+        if (argc != 2) return usage("sideload requires an argument");
         if (adb_sideload_host(argv[1])) {
             return 1;
         } else {
@@ -1741,7 +1738,7 @@
         bool reverse = !strcmp(argv[0], "reverse");
         ++argv;
         --argc;
-        if (argc < 1) return usage();
+        if (argc < 1) return usage("%s requires an argument", argv[0]);
 
         // Determine the <host-prefix> for this command.
         std::string host_prefix;
@@ -1759,32 +1756,55 @@
             }
         }
 
-        std::string cmd;
+        std::string cmd, error;
         if (strcmp(argv[0], "--list") == 0) {
-            if (argc != 1) return usage();
+            if (argc != 1) return usage("--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();
+            if (argc != 1) return usage("--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();
+            if (argc != 2) return usage("--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();
-            cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
+            if (argc != 3) return usage("--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();
-            cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
+            if (argc != 2) return usage("forward takes two arguments");
+            if (forward_targets_are_valid(argv[0], argv[1], &error)) {
+                cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
+            }
         }
 
-        return adb_command(cmd) ? 0 : 1;
+        if (!error.empty()) {
+            fprintf(stderr, "error: %s\n", error.c_str());
+            return 1;
+        }
+
+        int fd = adb_connect(cmd, &error);
+        if (fd < 0 || !adb_status(fd, &error)) {
+            adb_close(fd);
+            fprintf(stderr, "error: %s\n", error.c_str());
+            return 1;
+        }
+
+        // Server or device may optionally return a resolved TCP port number.
+        std::string resolved_port;
+        if (ReadProtocolString(fd, &resolved_port, &error) && !resolved_port.empty()) {
+            printf("%s\n", resolved_port.c_str());
+        }
+
+        ReadOrderlyShutdown(fd);
+        return 0;
     }
     /* do_sync_*() commands */
     else if (!strcmp(argv[0], "ls")) {
-        if (argc != 2) return usage();
+        if (argc != 2) return usage("ls requires an argument");
         return do_sync_ls(argv[1]) ? 0 : 1;
     }
     else if (!strcmp(argv[0], "push")) {
@@ -1793,7 +1813,7 @@
         const char* dst = nullptr;
 
         parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
-        if (srcs.empty() || !dst) return usage();
+        if (srcs.empty() || !dst) return usage("push requires an argument");
         return do_sync_push(srcs, dst) ? 0 : 1;
     }
     else if (!strcmp(argv[0], "pull")) {
@@ -1802,22 +1822,22 @@
         const char* dst = ".";
 
         parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
-        if (srcs.empty()) return usage();
+        if (srcs.empty()) return usage("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();
+        if (argc < 2) return usage("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();
+        if (argc < 2) return usage("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();
+        if (argc < 2) return usage("uninstall requires an argument");
         if (_use_legacy_install()) {
             return uninstall_app_legacy(transport_type, serial, argc, argv);
         }
@@ -1840,12 +1860,12 @@
             // A local path or "android"/"data" arg was specified.
             src = argv[1];
         } else {
-            return usage();
+            return usage("usage: adb sync [-l] [PARTITION]");
         }
 
         if (src != "" &&
             src != "system" && src != "data" && src != "vendor" && src != "oem") {
-            return usage();
+            return usage("don't know how to sync %s partition", src.c_str());
         }
 
         std::string system_src_path = product_file("system");
@@ -1897,7 +1917,7 @@
         return restore(argc, argv);
     }
     else if (!strcmp(argv[0], "keygen")) {
-        if (argc < 2) return usage();
+        if (argc != 2) return usage("keygen requires an argument");
         // Always print key generation information for keygen command.
         adb_trace_enable(AUTH);
         return adb_auth_keygen(argv[1]);
@@ -1905,16 +1925,23 @@
     else if (!strcmp(argv[0], "jdwp")) {
         return adb_connect_command("jdwp");
     }
+    else if (!strcmp(argv[0], "track-jdwp")) {
+        return adb_connect_command("track-jdwp");
+    }
+    else if (!strcmp(argv[0], "track-devices")) {
+        return adb_connect_command("host:track-devices");
+    }
+
+
     /* "adb /?" is a common idiom under Windows */
-    else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
+    else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
         help();
         return 0;
     }
-    else if (!strcmp(argv[0], "version")) {
+    else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
         fprintf(stdout, "%s", adb_version().c_str());
         return 0;
-    }
-    else if (!strcmp(argv[0], "features")) {
+    } else if (!strcmp(argv[0], "features")) {
         // Only list the features common to both the adb client and the device.
         FeatureSet features;
         std::string error;
@@ -1929,17 +1956,26 @@
             }
         }
         return 0;
+    } else if (!strcmp(argv[0], "host-features")) {
+        return adb_query_command("host:host-features");
     } else if (!strcmp(argv[0], "reconnect")) {
         if (argc == 1) {
             return adb_query_command("host:reconnect");
-        } else if (argc == 2 && !strcmp(argv[1], "device")) {
-            std::string err;
-            adb_connect("reconnect", &err);
-            return 0;
+        } else if (argc == 2) {
+            if (!strcmp(argv[1], "device")) {
+                std::string err;
+                adb_connect("reconnect", &err);
+                return 0;
+            } else if (!strcmp(argv[1], "offline")) {
+                std::string err;
+                return adb_query_command("host:reconnect-offline");
+            } else {
+                return usage("usage: adb reconnect [device|offline]");
+            }
         }
     }
 
-    usage();
+    usage("unknown command %s", argv[0]);
     return 1;
 }
 
@@ -1965,20 +2001,15 @@
 static int install_app(TransportType transport, const char* serial, int argc, const char** argv) {
     // The last argument must be the APK file
     const char* file = argv[argc - 1];
-    const char* dot = strrchr(file, '.');
-    bool found_apk = false;
-    struct stat sb;
-    if (dot && !strcasecmp(dot, ".apk")) {
-        if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
-            fprintf(stderr, "Invalid APK file: %s\n", file);
-            return EXIT_FAILURE;
-        }
-        found_apk = true;
+    if (!android::base::EndsWithIgnoreCase(file, ".apk")) {
+        fprintf(stderr, "Filename doesn't end .apk: %s\n", file);
+        return EXIT_FAILURE;
     }
 
-    if (!found_apk) {
-        fprintf(stderr, "Missing APK file\n");
-        return EXIT_FAILURE;
+    struct stat sb;
+    if (stat(file, &sb) == -1) {
+        fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
+        return 1;
     }
 
     int localFd = adb_open(file, O_RDONLY);
@@ -2024,22 +2055,16 @@
 static int install_multiple_app(TransportType transport, const char* serial, int argc,
                                 const char** argv)
 {
-    int i;
-    struct stat sb;
-    uint64_t total_size = 0;
     // Find all APK arguments starting at end.
     // All other arguments passed through verbatim.
     int first_apk = -1;
-    for (i = argc - 1; i >= 0; i--) {
+    uint64_t total_size = 0;
+    for (int i = argc - 1; i >= 0; i--) {
         const char* file = argv[i];
-        const char* dot = strrchr(file, '.');
-        if (dot && !strcasecmp(dot, ".apk")) {
-            if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
-                fprintf(stderr, "Invalid APK file: %s\n", file);
-                return EXIT_FAILURE;
-            }
 
-            total_size += sb.st_size;
+        if (android::base::EndsWithIgnoreCase(file, ".apk")) {
+            struct stat sb;
+            if (stat(file, &sb) != -1) total_size += sb.st_size;
             first_apk = i;
         } else {
             break;
@@ -2047,7 +2072,7 @@
     }
 
     if (first_apk == -1) {
-        fprintf(stderr, "Missing APK file\n");
+        fprintf(stderr, "No APK file on command line\n");
         return 1;
     }
 
@@ -2059,7 +2084,7 @@
     }
 
     std::string cmd = android::base::StringPrintf("%s install-create -S %" PRIu64, install_cmd.c_str(), total_size);
-    for (i = 1; i < first_apk; i++) {
+    for (int i = 1; i < first_apk; i++) {
         cmd += " " + escape_arg(argv[i]);
     }
 
@@ -2091,17 +2116,19 @@
 
     // Valid session, now stream the APKs
     int success = 1;
-    for (i = first_apk; i < argc; i++) {
+    for (int i = first_apk; i < argc; i++) {
         const char* file = argv[i];
+        struct stat sb;
         if (stat(file, &sb) == -1) {
-            fprintf(stderr, "Failed to stat %s\n", file);
+            fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
             success = 0;
             goto finalize_session;
         }
 
         std::string cmd = android::base::StringPrintf(
                 "%s install-write -S %" PRIu64 " %d %d_%s -",
-                install_cmd.c_str(), static_cast<uint64_t>(sb.st_size), session_id, i, adb_basename(file).c_str());
+                install_cmd.c_str(), static_cast<uint64_t>(sb.st_size), session_id, i,
+                android::base::Basename(file).c_str());
 
         int localFd = adb_open(file, O_RDONLY);
         if (localFd < 0) {
@@ -2194,10 +2221,8 @@
     static const char *const DATA_DEST = "/data/local/tmp/%s";
     static const char *const SD_DEST = "/sdcard/tmp/%s";
     const char* where = DATA_DEST;
-    int i;
-    struct stat sb;
 
-    for (i = 1; i < argc; i++) {
+    for (int i = 1; i < argc; i++) {
         if (!strcmp(argv[i], "-s")) {
             where = SD_DEST;
         }
@@ -2206,29 +2231,22 @@
     // Find last APK argument.
     // All other arguments passed through verbatim.
     int last_apk = -1;
-    for (i = argc - 1; i >= 0; i--) {
-        const char* file = argv[i];
-        const char* dot = strrchr(file, '.');
-        if (dot && !strcasecmp(dot, ".apk")) {
-            if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
-                fprintf(stderr, "Invalid APK file: %s\n", file);
-                return EXIT_FAILURE;
-            }
-
+    for (int i = argc - 1; i >= 0; i--) {
+        if (android::base::EndsWithIgnoreCase(argv[i], ".apk")) {
             last_apk = i;
             break;
         }
     }
 
     if (last_apk == -1) {
-        fprintf(stderr, "Missing APK file\n");
+        fprintf(stderr, "No APK file on command line\n");
         return EXIT_FAILURE;
     }
 
     int result = -1;
     std::vector<const char*> apk_file = {argv[last_apk]};
     std::string apk_dest = android::base::StringPrintf(
-        where, adb_basename(argv[last_apk]).c_str());
+        where, android::base::Basename(argv[last_apk]).c_str());
     if (!do_sync_push(apk_file, apk_dest.c_str())) goto cleanup_apk;
     argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
     result = pm_command(transport, serial, argc, argv);
diff --git a/adb/console.cpp b/adb/console.cpp
index e9b90a5..9563eac 100644
--- a/adb/console.cpp
+++ b/adb/console.cpp
@@ -32,7 +32,7 @@
 static std::string adb_construct_auth_command() {
     static const char auth_token_filename[] = ".emulator_console_auth_token";
 
-    std::string auth_token_path = adb_get_homedir_path(false);
+    std::string auth_token_path = adb_get_homedir_path();
     auth_token_path += OS_PATH_SEPARATOR;
     auth_token_path += auth_token_filename;
 
diff --git a/adb/daemon/main.cpp b/adb/daemon/main.cpp
index 4721e2f..7a87df4 100644
--- a/adb/daemon/main.cpp
+++ b/adb/daemon/main.cpp
@@ -28,11 +28,15 @@
 #include <memory>
 
 #include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <libminijail.h>
+#include <log/log_properties.h>
+#include <scoped_minijail.h>
 
-#include "cutils/properties.h"
-#include "private/android_filesystem_config.h"
+#include <private/android_filesystem_config.h>
+#include "debuggerd/handler.h"
 #include "selinux/android.h"
 
 #include "adb.h"
@@ -41,32 +45,21 @@
 #include "adb_utils.h"
 #include "transport.h"
 
+#include "mdns.h"
+
 static const char* root_seclabel = nullptr;
 
-static void drop_capabilities_bounding_set_if_needed() {
-#ifdef ALLOW_ADBD_ROOT
-    char value[PROPERTY_VALUE_MAX];
-    property_get("ro.debuggable", value, "");
-    if (strcmp(value, "1") == 0) {
+static void drop_capabilities_bounding_set_if_needed(struct minijail *j) {
+#if defined(ALLOW_ADBD_ROOT)
+    if (__android_log_is_debuggable()) {
         return;
     }
 #endif
-    for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
-        if (i == CAP_SETUID || i == CAP_SETGID) {
-            // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
-            continue;
-        }
-
-        if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
-            PLOG(FATAL) << "Could not drop capabilities";
-        }
-    }
+    minijail_capbset_drop(j, CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_SETGID));
 }
 
 static bool should_drop_privileges() {
 #if defined(ALLOW_ADBD_ROOT)
-    char value[PROPERTY_VALUE_MAX];
-
     // The properties that affect `adb root` and `adb unroot` are ro.secure and
     // ro.debuggable. In this context the names don't make the expected behavior
     // particularly obvious.
@@ -77,24 +70,19 @@
     //
     // ro.secure:
     //   Drop privileges by default. Set to 1 on userdebug and user builds.
-    property_get("ro.secure", value, "1");
-    bool ro_secure = (strcmp(value, "1") == 0);
-
-    property_get("ro.debuggable", value, "");
-    bool ro_debuggable = (strcmp(value, "1") == 0);
+    bool ro_secure = android::base::GetBoolProperty("ro.secure", true);
+    bool ro_debuggable = __android_log_is_debuggable();
 
     // Drop privileges if ro.secure is set...
     bool drop = ro_secure;
 
-    property_get("service.adb.root", value, "");
-    bool adb_root = (strcmp(value, "1") == 0);
-    bool adb_unroot = (strcmp(value, "0") == 0);
-
     // ... except "adb root" lets you keep privileges in a debuggable build.
+    std::string prop = android::base::GetProperty("service.adb.root", "");
+    bool adb_root = (prop == "1");
+    bool adb_unroot = (prop == "0");
     if (ro_debuggable && adb_root) {
         drop = false;
     }
-
     // ... and "adb unroot" lets you explicitly drop privileges.
     if (adb_unroot) {
         drop = true;
@@ -107,8 +95,7 @@
 }
 
 static void drop_privileges(int server_port) {
-    std::unique_ptr<minijail, void (*)(minijail*)> jail(minijail_new(),
-                                                        &minijail_destroy);
+    ScopedMinijail jail(minijail_new());
 
     // Add extra groups:
     // AID_ADB to access the USB driver
@@ -124,14 +111,12 @@
                       AID_INET,     AID_NET_BT,    AID_NET_BT_ADMIN,
                       AID_SDCARD_R, AID_SDCARD_RW, AID_NET_BW_STATS,
                       AID_READPROC};
-    minijail_set_supplementary_gids(jail.get(),
-                                    sizeof(groups) / sizeof(groups[0]),
-                                    groups);
+    minijail_set_supplementary_gids(jail.get(), arraysize(groups), groups);
 
     // Don't listen on a port (default 5037) if running in secure mode.
     // Don't run as root if running in secure mode.
     if (should_drop_privileges()) {
-        drop_capabilities_bounding_set_if_needed();
+        drop_capabilities_bounding_set_if_needed(jail.get());
 
         minijail_change_gid(jail.get(), AID_SHELL);
         minijail_change_uid(jail.get(), AID_SHELL);
@@ -151,14 +136,17 @@
         std::string error;
         std::string local_name =
             android::base::StringPrintf("tcp:%d", server_port);
-        if (install_listener(local_name, "*smartsocket*", nullptr, 0,
-                             &error)) {
-            LOG(FATAL) << "Could not install *smartsocket* listener: "
-                       << error;
+        if (install_listener(local_name, "*smartsocket*", nullptr, 0, nullptr, &error)) {
+            LOG(FATAL) << "Could not install *smartsocket* listener: " << error;
         }
     }
 }
 
+static void setup_port(int port) {
+    local_init(port);
+    setup_mdns(port);
+}
+
 int adbd_main(int server_port) {
     umask(0);
 
@@ -170,7 +158,7 @@
     // descriptor will always be open.
     adbd_cloexec_auth_socket();
 
-    if (ALLOW_ADBD_NO_AUTH && property_get_bool("ro.adb.secure", 0) == 0) {
+    if (ALLOW_ADBD_NO_AUTH && !android::base::GetBoolProperty("ro.adb.secure", false)) {
         auth_required = false;
     }
 
@@ -189,7 +177,7 @@
     drop_privileges(server_port);
 
     bool is_usb = false;
-    if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
+    if (access(USB_FFS_ADB_EP0, F_OK) == 0) {
         // Listen on USB.
         usb_init();
         is_usb = true;
@@ -198,20 +186,19 @@
     // If one of these properties is set, also listen on that port.
     // If one of the properties isn't set and we couldn't listen on usb, listen
     // on the default port.
-    char prop_port[PROPERTY_VALUE_MAX];
-    property_get("service.adb.tcp.port", prop_port, "");
-    if (prop_port[0] == '\0') {
-        property_get("persist.adb.tcp.port", prop_port, "");
+    std::string prop_port = android::base::GetProperty("service.adb.tcp.port", "");
+    if (prop_port.empty()) {
+        prop_port = android::base::GetProperty("persist.adb.tcp.port", "");
     }
 
     int port;
-    if (sscanf(prop_port, "%d", &port) == 1 && port > 0) {
+    if (sscanf(prop_port.c_str(), "%d", &port) == 1 && port > 0) {
         D("using port=%d", port);
         // Listen on TCP port specified by service.adb.tcp.port property.
-        local_init(port);
+        setup_port(port);
     } else if (!is_usb) {
         // Listen on default port.
-        local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
+        setup_port(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
     }
 
     D("adbd_main(): pre init_jdwp()");
@@ -258,6 +245,7 @@
 
     close_stdin();
 
+    debuggerd_init(nullptr);
     adb_trace_init(argv);
 
     D("Handling main()");
diff --git a/adb/daemon/mdns.cpp b/adb/daemon/mdns.cpp
new file mode 100644
index 0000000..7811143
--- /dev/null
+++ b/adb/daemon/mdns.cpp
@@ -0,0 +1,95 @@
+/*
+ * 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 "adb_mdns.h"
+#include "sysdeps.h"
+
+#include <chrono>
+#include <dns_sd.h>
+#include <endian.h>
+#include <mutex>
+#include <unistd.h>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
+using namespace std::chrono_literals;
+
+static std::mutex& mdns_lock = *new std::mutex();
+static int port;
+static DNSServiceRef mdns_ref;
+static bool mdns_registered = false;
+
+static void start_mdns() {
+    if (android::base::GetProperty("init.svc.mdnsd", "") == "running") {
+        return;
+    }
+
+    android::base::SetProperty("ctl.start", "mdnsd");
+
+    if (! android::base::WaitForProperty("init.svc.mdnsd", "running", 5s)) {
+        LOG(ERROR) << "Could not start mdnsd.";
+    }
+}
+
+static void mdns_callback(DNSServiceRef /*ref*/,
+                          DNSServiceFlags /*flags*/,
+                          DNSServiceErrorType errorCode,
+                          const char* /*name*/,
+                          const char* /*regtype*/,
+                          const char* /*domain*/,
+                          void* /*context*/) {
+    if (errorCode != kDNSServiceErr_NoError) {
+        LOG(ERROR) << "Encountered mDNS registration error ("
+            << errorCode << ").";
+    }
+}
+
+static void setup_mdns_thread(void* /* unused */) {
+    start_mdns();
+    std::lock_guard<std::mutex> lock(mdns_lock);
+
+    std::string hostname = "adb-";
+    hostname += android::base::GetProperty("ro.serialno", "unidentified");
+
+    auto error = DNSServiceRegister(&mdns_ref, 0, 0, hostname.c_str(),
+                                    kADBServiceType, nullptr, nullptr,
+                                    htobe16((uint16_t)port), 0, nullptr,
+                                    mdns_callback, nullptr);
+
+    if (error != kDNSServiceErr_NoError) {
+        LOG(ERROR) << "Could not register mDNS service (" << error << ").";
+        mdns_registered = false;
+    }
+
+    mdns_registered = true;
+}
+
+static void teardown_mdns() {
+    std::lock_guard<std::mutex> lock(mdns_lock);
+
+    if (mdns_registered) {
+        DNSServiceRefDeallocate(mdns_ref);
+    }
+}
+
+void setup_mdns(int port_in) {
+    port = port_in;
+    adb_thread_create(setup_mdns_thread, nullptr, nullptr);
+
+    // TODO: Make this more robust against a hard kill.
+    atexit(teardown_mdns);
+}
diff --git a/adb/daemon/mdns.h b/adb/daemon/mdns.h
new file mode 100644
index 0000000..4c6b1ca
--- /dev/null
+++ b/adb/daemon/mdns.h
@@ -0,0 +1,22 @@
+/*
+ * 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 _DAEMON_MDNS_H_
+#define _DAEMON_MDNS_H_
+
+void setup_mdns(int port);
+
+#endif  // _DAEMON_MDNS_H_
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
new file mode 100644
index 0000000..92e9039
--- /dev/null
+++ b/adb/daemon/usb.cpp
@@ -0,0 +1,480 @@
+/*
+ * 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.
+ */
+
+#define TRACE_TAG USB
+
+#include "sysdeps.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <linux/usb/ch9.h>
+#include <linux/usb/functionfs.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+#include <thread>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
+#include "adb.h"
+#include "daemon/usb.h"
+#include "transport.h"
+
+using namespace std::chrono_literals;
+
+#define MAX_PACKET_SIZE_FS 64
+#define MAX_PACKET_SIZE_HS 512
+#define MAX_PACKET_SIZE_SS 1024
+
+// Kernels before 3.3 have a 16KiB transfer limit  That limit was replaced
+// with a 16MiB global limit in 3.3, but each URB submitted required a
+// contiguous kernel allocation, so you would get ENOMEM if you tried to
+// send something larger than the biggest available contiguous kernel
+// memory region. Large contiguous allocations could be unreliable
+// on a device kernel that has been running for a while fragmenting its
+// memory so we start with a larger allocation, and shrink the amount if
+// necessary.
+#define USB_FFS_BULK_SIZE 16384
+
+#define cpu_to_le16(x) htole16(x)
+#define cpu_to_le32(x) htole32(x)
+
+#define FUNCTIONFS_ENDPOINT_ALLOC       _IOR('g', 231, __u32)
+
+static constexpr size_t ENDPOINT_ALLOC_RETRIES = 2;
+
+static int dummy_fd = -1;
+
+struct func_desc {
+    struct usb_interface_descriptor intf;
+    struct usb_endpoint_descriptor_no_audio source;
+    struct usb_endpoint_descriptor_no_audio sink;
+} __attribute__((packed));
+
+struct ss_func_desc {
+    struct usb_interface_descriptor intf;
+    struct usb_endpoint_descriptor_no_audio source;
+    struct usb_ss_ep_comp_descriptor source_comp;
+    struct usb_endpoint_descriptor_no_audio sink;
+    struct usb_ss_ep_comp_descriptor sink_comp;
+} __attribute__((packed));
+
+struct desc_v1 {
+    struct usb_functionfs_descs_head_v1 {
+        __le32 magic;
+        __le32 length;
+        __le32 fs_count;
+        __le32 hs_count;
+    } __attribute__((packed)) header;
+    struct func_desc fs_descs, hs_descs;
+} __attribute__((packed));
+
+struct desc_v2 {
+    struct usb_functionfs_descs_head_v2 header;
+    // The rest of the structure depends on the flags in the header.
+    __le32 fs_count;
+    __le32 hs_count;
+    __le32 ss_count;
+    __le32 os_count;
+    struct func_desc fs_descs, hs_descs;
+    struct ss_func_desc ss_descs;
+    struct usb_os_desc_header os_header;
+    struct usb_ext_compat_desc os_desc;
+} __attribute__((packed));
+
+static struct func_desc fs_descriptors = {
+    .intf = {
+        .bLength = sizeof(fs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = ADB_CLASS,
+        .bInterfaceSubClass = ADB_SUBCLASS,
+        .bInterfaceProtocol = ADB_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
+    },
+    .source = {
+        .bLength = sizeof(fs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
+    },
+    .sink = {
+        .bLength = sizeof(fs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
+    },
+};
+
+static struct func_desc hs_descriptors = {
+    .intf = {
+        .bLength = sizeof(hs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = ADB_CLASS,
+        .bInterfaceSubClass = ADB_SUBCLASS,
+        .bInterfaceProtocol = ADB_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
+    },
+    .source = {
+        .bLength = sizeof(hs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
+    },
+    .sink = {
+        .bLength = sizeof(hs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
+    },
+};
+
+static struct ss_func_desc ss_descriptors = {
+    .intf = {
+        .bLength = sizeof(ss_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = ADB_CLASS,
+        .bInterfaceSubClass = ADB_SUBCLASS,
+        .bInterfaceProtocol = ADB_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
+    },
+    .source = {
+        .bLength = sizeof(ss_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_SS,
+    },
+    .source_comp = {
+        .bLength = sizeof(ss_descriptors.source_comp),
+        .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
+        .bMaxBurst = 4,
+    },
+    .sink = {
+        .bLength = sizeof(ss_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_SS,
+    },
+    .sink_comp = {
+        .bLength = sizeof(ss_descriptors.sink_comp),
+        .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
+        .bMaxBurst = 4,
+    },
+};
+
+struct usb_ext_compat_desc os_desc_compat = {
+    .bFirstInterfaceNumber = 0,
+    .Reserved1 = cpu_to_le32(1),
+    .CompatibleID = {0},
+    .SubCompatibleID = {0},
+    .Reserved2 = {0},
+};
+
+static struct usb_os_desc_header os_desc_header = {
+    .interface = cpu_to_le32(1),
+    .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)),
+    .bcdVersion = cpu_to_le32(1),
+    .wIndex = cpu_to_le32(4),
+    .bCount = cpu_to_le32(1),
+    .Reserved = cpu_to_le32(0),
+};
+
+#define STR_INTERFACE_ "ADB Interface"
+
+static const struct {
+    struct usb_functionfs_strings_head header;
+    struct {
+        __le16 code;
+        const char str1[sizeof(STR_INTERFACE_)];
+    } __attribute__((packed)) lang0;
+} __attribute__((packed)) strings = {
+    .header = {
+        .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC),
+        .length = cpu_to_le32(sizeof(strings)),
+        .str_count = cpu_to_le32(1),
+        .lang_count = cpu_to_le32(1),
+    },
+    .lang0 = {
+        cpu_to_le16(0x0409), /* en-us */
+        STR_INTERFACE_,
+    },
+};
+
+bool init_functionfs(struct usb_handle* h) {
+    ssize_t ret;
+    struct desc_v1 v1_descriptor;
+    struct desc_v2 v2_descriptor;
+    size_t retries = 0;
+
+    v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
+    v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
+    v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
+                                 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC;
+    v2_descriptor.fs_count = 3;
+    v2_descriptor.hs_count = 3;
+    v2_descriptor.ss_count = 5;
+    v2_descriptor.os_count = 1;
+    v2_descriptor.fs_descs = fs_descriptors;
+    v2_descriptor.hs_descs = hs_descriptors;
+    v2_descriptor.ss_descs = ss_descriptors;
+    v2_descriptor.os_header = os_desc_header;
+    v2_descriptor.os_desc = os_desc_compat;
+
+    if (h->control < 0) { // might have already done this before
+        D("OPENING %s", USB_FFS_ADB_EP0);
+        h->control = adb_open(USB_FFS_ADB_EP0, O_RDWR);
+        if (h->control < 0) {
+            D("[ %s: cannot open control endpoint: errno=%d]", USB_FFS_ADB_EP0, errno);
+            goto err;
+        }
+
+        ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor));
+        if (ret < 0) {
+            v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
+            v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
+            v1_descriptor.header.fs_count = 3;
+            v1_descriptor.header.hs_count = 3;
+            v1_descriptor.fs_descs = fs_descriptors;
+            v1_descriptor.hs_descs = hs_descriptors;
+            D("[ %s: Switching to V1_descriptor format errno=%d ]", USB_FFS_ADB_EP0, errno);
+            ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor));
+            if (ret < 0) {
+                D("[ %s: write descriptors failed: errno=%d ]", USB_FFS_ADB_EP0, errno);
+                goto err;
+            }
+        }
+
+        ret = adb_write(h->control, &strings, sizeof(strings));
+        if (ret < 0) {
+            D("[ %s: writing strings failed: errno=%d]", USB_FFS_ADB_EP0, errno);
+            goto err;
+        }
+        //Signal only when writing the descriptors to ffs
+        android::base::SetProperty("sys.usb.ffs.ready", "1");
+    }
+
+    h->bulk_out = adb_open(USB_FFS_ADB_OUT, O_RDWR);
+    if (h->bulk_out < 0) {
+        D("[ %s: cannot open bulk-out ep: errno=%d ]", USB_FFS_ADB_OUT, errno);
+        goto err;
+    }
+
+    h->bulk_in = adb_open(USB_FFS_ADB_IN, O_RDWR);
+    if (h->bulk_in < 0) {
+        D("[ %s: cannot open bulk-in ep: errno=%d ]", USB_FFS_ADB_IN, errno);
+        goto err;
+    }
+
+    h->max_rw = MAX_PAYLOAD;
+    while (h->max_rw >= USB_FFS_BULK_SIZE && retries < ENDPOINT_ALLOC_RETRIES) {
+        int ret_in = ioctl(h->bulk_in, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(h->max_rw));
+        int errno_in = errno;
+        int ret_out = ioctl(h->bulk_out, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(h->max_rw));
+        int errno_out = errno;
+
+        if (ret_in || ret_out) {
+            if (errno_in == ENODEV || errno_out == ENODEV) {
+                std::this_thread::sleep_for(100ms);
+                retries += 1;
+                continue;
+            }
+            h->max_rw /= 2;
+        } else {
+            return true;
+        }
+    }
+
+    D("[ adb: cannot call endpoint alloc: errno=%d ]", errno);
+    // Kernel pre-allocation could have failed for recoverable reasons.
+    // Continue running with a safe max rw size.
+    h->max_rw = USB_FFS_BULK_SIZE;
+    return true;
+
+err:
+    if (h->bulk_in > 0) {
+        adb_close(h->bulk_in);
+        h->bulk_in = -1;
+    }
+    if (h->bulk_out > 0) {
+        adb_close(h->bulk_out);
+        h->bulk_out = -1;
+    }
+    if (h->control > 0) {
+        adb_close(h->control);
+        h->control = -1;
+    }
+    return false;
+}
+
+static void usb_ffs_open_thread(void* x) {
+    struct usb_handle* usb = (struct usb_handle*)x;
+
+    adb_thread_setname("usb ffs open");
+
+    while (true) {
+        // wait until the USB device needs opening
+        std::unique_lock<std::mutex> lock(usb->lock);
+        while (!usb->open_new_connection) {
+            usb->notify.wait(lock);
+        }
+        usb->open_new_connection = false;
+        lock.unlock();
+
+        while (true) {
+            if (init_functionfs(usb)) {
+                break;
+            }
+            std::this_thread::sleep_for(1s);
+        }
+
+        D("[ usb_thread - registering device ]");
+        register_usb_transport(usb, 0, 0, 1);
+    }
+
+    // never gets here
+    abort();
+}
+
+static int usb_ffs_write(usb_handle* h, const void* data, int len) {
+    D("about to write (fd=%d, len=%d)", h->bulk_in, len);
+
+    const char* buf = static_cast<const char*>(data);
+    while (len > 0) {
+        int write_len = std::min(h->max_rw, len);
+        int n = adb_write(h->bulk_in, buf, write_len);
+        if (n < 0) {
+            D("ERROR: fd = %d, n = %d: %s", h->bulk_in, n, strerror(errno));
+            return -1;
+        }
+        buf += n;
+        len -= n;
+    }
+
+    D("[ done fd=%d ]", h->bulk_in);
+    return 0;
+}
+
+static int usb_ffs_read(usb_handle* h, void* data, int len) {
+    D("about to read (fd=%d, len=%d)", h->bulk_out, len);
+
+    char* buf = static_cast<char*>(data);
+    while (len > 0) {
+        int read_len = std::min(h->max_rw, len);
+        int n = adb_read(h->bulk_out, buf, read_len);
+        if (n < 0) {
+            D("ERROR: fd = %d, n = %d: %s", h->bulk_out, n, strerror(errno));
+            return -1;
+        }
+        buf += n;
+        len -= n;
+    }
+
+    D("[ done fd=%d ]", h->bulk_out);
+    return 0;
+}
+
+static void usb_ffs_kick(usb_handle* h) {
+    int err;
+
+    err = ioctl(h->bulk_in, FUNCTIONFS_CLEAR_HALT);
+    if (err < 0) {
+        D("[ kick: source (fd=%d) clear halt failed (%d) ]", h->bulk_in, errno);
+    }
+
+    err = ioctl(h->bulk_out, FUNCTIONFS_CLEAR_HALT);
+    if (err < 0) {
+        D("[ kick: sink (fd=%d) clear halt failed (%d) ]", h->bulk_out, errno);
+    }
+
+    // don't close ep0 here, since we may not need to reinitialize it with
+    // the same descriptors again. if however ep1/ep2 fail to re-open in
+    // init_functionfs, only then would we close and open ep0 again.
+    // Ditto the comment in usb_adb_kick.
+    h->kicked = true;
+    TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_out));
+    TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_in));
+}
+
+static void usb_ffs_close(usb_handle* h) {
+    h->kicked = false;
+    adb_close(h->bulk_out);
+    adb_close(h->bulk_in);
+    // Notify usb_adb_open_thread to open a new connection.
+    h->lock.lock();
+    h->open_new_connection = true;
+    h->lock.unlock();
+    h->notify.notify_one();
+}
+
+static void usb_ffs_init() {
+    D("[ usb_init - using FunctionFS ]");
+
+    usb_handle* h = new usb_handle();
+
+    h->write = usb_ffs_write;
+    h->read = usb_ffs_read;
+    h->kick = usb_ffs_kick;
+    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");
+    }
+}
+
+void usb_init() {
+    dummy_fd = adb_open("/dev/null", O_WRONLY);
+    CHECK_NE(dummy_fd, -1);
+    usb_ffs_init();
+}
+
+int usb_write(usb_handle* h, const void* data, int len) {
+    return h->write(h, data, len);
+}
+
+int usb_read(usb_handle* h, void* data, int len) {
+    return h->read(h, data, len);
+}
+
+int usb_close(usb_handle* h) {
+    h->close(h);
+    return 0;
+}
+
+void usb_kick(usb_handle* h) {
+    h->kick(h);
+}
diff --git a/adb/daemon/usb.h b/adb/daemon/usb.h
new file mode 100644
index 0000000..55b5995
--- /dev/null
+++ b/adb/daemon/usb.h
@@ -0,0 +1,45 @@
+#pragma once
+
+/*
+ * 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 <atomic>
+#include <condition_variable>
+#include <mutex>
+
+struct usb_handle {
+    usb_handle() : kicked(false) {
+    }
+
+    std::condition_variable notify;
+    std::mutex lock;
+    std::atomic<bool> kicked;
+    bool open_new_connection = true;
+
+    int (*write)(usb_handle* h, const void* data, int len);
+    int (*read)(usb_handle* h, void* data, int len);
+    void (*kick)(usb_handle* h);
+    void (*close)(usb_handle* h);
+
+    // FunctionFS
+    int control = -1;
+    int bulk_out = -1; /* "out" from the host's perspective => source for adbd */
+    int bulk_in = -1;  /* "in" from the host's perspective => sink for adbd */
+
+    int max_rw;
+};
+
+bool init_functionfs(struct usb_handle* h);
diff --git a/adb/fdevent.cpp b/adb/fdevent.cpp
index 902548e..04cd865 100644
--- a/adb/fdevent.cpp
+++ b/adb/fdevent.cpp
@@ -55,7 +55,7 @@
   fdevent* fde;
   adb_pollfd pollfd;
 
-  PollNode(fdevent* fde) : fde(fde) {
+  explicit PollNode(fdevent* fde) : fde(fde) {
       memset(&pollfd, 0, sizeof(pollfd));
       pollfd.fd = fde->fd;
 
diff --git a/adb/fdevent_test.h b/adb/fdevent_test.h
index c853bce..ef65b74 100644
--- a/adb/fdevent_test.h
+++ b/adb/fdevent_test.h
@@ -49,6 +49,16 @@
         dummy = dummy_fds[0];
     }
 
+    size_t GetAdditionalLocalSocketCount() {
+#if ADB_HOST
+        // dummy socket installed in PrepareThread()
+        return 1;
+#else
+        // dummy socket and one more socket installed in fdevent_subproc_setup()
+        return 2;
+#endif
+    }
+
     void TerminateThread(adb_thread_t thread) {
         fdevent_terminate_loop();
         ASSERT_TRUE(WriteFdExactly(dummy, "", 1));
diff --git a/adb/file_sync_client.cpp b/adb/file_sync_client.cpp
index 651e8ca..22bd2f2 100644
--- a/adb/file_sync_client.cpp
+++ b/adb/file_sync_client.cpp
@@ -15,12 +15,10 @@
  */
 
 #include <dirent.h>
-#include <errno.h>
 #include <inttypes.h>
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/types.h>
@@ -28,8 +26,11 @@
 #include <unistd.h>
 #include <utime.h>
 
+#include <chrono>
 #include <functional>
 #include <memory>
+#include <sstream>
+#include <string>
 #include <vector>
 
 #include "sysdeps.h"
@@ -40,6 +41,8 @@
 #include "adb_utils.h"
 #include "file_sync_service.h"
 #include "line_printer.h"
+#include "sysdeps/errno.h"
+#include "sysdeps/stat.h"
 
 #include <android-base/file.h>
 #include <android-base/strings.h>
@@ -61,22 +64,18 @@
 }
 
 static bool should_pull_file(mode_t mode) {
-    return mode & (S_IFREG | S_IFBLK | S_IFCHR);
+    return S_ISREG(mode) || S_ISBLK(mode) || S_ISCHR(mode);
 }
 
 static bool should_push_file(mode_t mode) {
-    mode_t mask = S_IFREG;
-#if !defined(_WIN32)
-    mask |= S_IFLNK;
-#endif
-    return mode & mask;
+    return S_ISREG(mode) || S_ISLNK(mode);
 }
 
 struct copyinfo {
     std::string lpath;
     std::string rpath;
-    unsigned int time = 0;
-    unsigned int mode;
+    int64_t time = 0;
+    uint32_t mode;
     uint64_t size = 0;
     bool skip = false;
 
@@ -94,20 +93,125 @@
     }
 };
 
+enum class TransferDirection {
+    push,
+    pull,
+};
+
+struct TransferLedger {
+    std::chrono::steady_clock::time_point start_time;
+    uint64_t files_transferred;
+    uint64_t files_skipped;
+    uint64_t bytes_transferred;
+    uint64_t bytes_expected;
+    bool expect_multiple_files;
+
+    TransferLedger() {
+        Reset();
+    }
+
+    bool operator==(const TransferLedger& other) const {
+        return files_transferred == other.files_transferred &&
+               files_skipped == other.files_skipped && bytes_transferred == other.bytes_transferred;
+    }
+
+    bool operator!=(const TransferLedger& other) const {
+        return !(*this == other);
+    }
+
+    void Reset() {
+        start_time = std::chrono::steady_clock::now();
+        files_transferred = 0;
+        files_skipped = 0;
+        bytes_transferred = 0;
+        bytes_expected = 0;
+    }
+
+    std::string TransferRate() {
+        if (bytes_transferred == 0) return "";
+
+        std::chrono::duration<double> duration;
+        duration = std::chrono::steady_clock::now() - start_time;
+
+        double s = duration.count();
+        if (s == 0) {
+            return "";
+        }
+        double rate = (static_cast<double>(bytes_transferred) / s) / (1024 * 1024);
+        return android::base::StringPrintf(" %.1f MB/s (%" PRIu64 " bytes in %.3fs)", rate,
+                                           bytes_transferred, s);
+    }
+
+    void ReportProgress(LinePrinter& lp, const std::string& file, uint64_t file_copied_bytes,
+                        uint64_t file_total_bytes) {
+        char overall_percentage_str[5] = "?";
+        if (bytes_expected != 0 && bytes_transferred <= bytes_expected) {
+            int overall_percentage = static_cast<int>(bytes_transferred * 100 / bytes_expected);
+            // If we're pulling symbolic links, we'll pull the target of the link rather than
+            // just create a local link, and that will cause us to go over 100%.
+            if (overall_percentage <= 100) {
+                snprintf(overall_percentage_str, sizeof(overall_percentage_str), "%d%%",
+                         overall_percentage);
+            }
+        }
+
+        std::string output;
+        if (file_copied_bytes > file_total_bytes || file_total_bytes == 0) {
+            // This case can happen if we're racing against something that wrote to the file
+            // between our stat and our read, or if we're reading a magic file that lies about
+            // its size. Just show how much we've copied.
+            output = android::base::StringPrintf("[%4s] %s: %" PRId64 "/?", overall_percentage_str,
+                                                 file.c_str(), file_copied_bytes);
+        } else {
+            // If we're transferring multiple files, we want to know how far through the current
+            // file we are, as well as the overall percentage.
+            if (expect_multiple_files) {
+                int file_percentage = static_cast<int>(file_copied_bytes * 100 / file_total_bytes);
+                output = android::base::StringPrintf("[%4s] %s: %d%%", overall_percentage_str,
+                                                     file.c_str(), file_percentage);
+            } else {
+                output =
+                    android::base::StringPrintf("[%4s] %s", overall_percentage_str, file.c_str());
+            }
+        }
+        lp.Print(output, LinePrinter::LineType::INFO);
+    }
+
+    void ReportTransferRate(LinePrinter& lp, const std::string& name, TransferDirection direction) {
+        const char* direction_str = (direction == TransferDirection::push) ? "pushed" : "pulled";
+        std::stringstream ss;
+        if (!name.empty()) {
+            ss << name << ": ";
+        }
+        ss << files_transferred << " file" << ((files_transferred == 1) ? "" : "s") << " "
+           << direction_str << ".";
+        if (files_skipped > 0) {
+            ss << " " << files_skipped << " file" << ((files_skipped == 1) ? "" : "s")
+               << " skipped.";
+        }
+        ss << TransferRate();
+
+        lp.Print(ss.str(), LinePrinter::LineType::INFO);
+        lp.KeepInfoLine();
+    }
+};
+
 class SyncConnection {
   public:
-    SyncConnection()
-            : total_bytes_(0),
-              start_time_ms_(CurrentTimeMs()),
-              expected_total_bytes_(0),
-              expect_multiple_files_(false),
-              expect_done_(false) {
+    SyncConnection() : expect_done_(false) {
         max = SYNC_DATA_MAX; // TODO: decide at runtime.
 
         std::string error;
-        fd = adb_connect("sync:", &error);
-        if (fd < 0) {
-            Error("connect failed: %s", error.c_str());
+        FeatureSet features;
+        if (!adb_get_feature_set(&features, &error)) {
+            fd = -1;
+            Error("failed to get feature set: %s", error.c_str());
+        } else {
+            have_stat_v2_ = CanUseFeature(features, kFeatureStat2);
+            fd = adb_connect("sync:", &error);
+            if (fd < 0) {
+                Error("connect failed: %s", error.c_str());
+            }
         }
     }
 
@@ -140,6 +244,40 @@
         return rc != 0;
     }
 
+    void NewTransfer() {
+        current_ledger_.Reset();
+    }
+
+    void RecordBytesTransferred(size_t bytes) {
+        current_ledger_.bytes_transferred += bytes;
+        global_ledger_.bytes_transferred += bytes;
+    }
+
+    void RecordFilesTransferred(size_t files) {
+        current_ledger_.files_transferred += files;
+        global_ledger_.files_transferred += files;
+    }
+
+    void RecordFilesSkipped(size_t files) {
+        current_ledger_.files_skipped += files;
+        global_ledger_.files_skipped += files;
+    }
+
+    void ReportProgress(const std::string& file, uint64_t file_copied_bytes,
+                        uint64_t file_total_bytes) {
+        current_ledger_.ReportProgress(line_printer_, file, file_copied_bytes, file_total_bytes);
+    }
+
+    void ReportTransferRate(const std::string& file, TransferDirection direction) {
+        current_ledger_.ReportTransferRate(line_printer_, file, direction);
+    }
+
+    void ReportOverallTransferRate(TransferDirection direction) {
+        if (current_ledger_ != global_ledger_) {
+            global_ledger_.ReportTransferRate(line_printer_, "", direction);
+        }
+    }
+
     bool SendRequest(int id, const char* path_and_mode) {
         size_t path_length = strlen(path_and_mode);
         if (path_length > 1024) {
@@ -160,6 +298,77 @@
         return WriteFdExactly(fd, &buf[0], buf.size());
     }
 
+    bool SendStat(const char* path_and_mode) {
+        if (!have_stat_v2_) {
+            errno = ENOTSUP;
+            return false;
+        }
+        return SendRequest(ID_STAT_V2, path_and_mode);
+    }
+
+    bool SendLstat(const char* path_and_mode) {
+        if (have_stat_v2_) {
+            return SendRequest(ID_LSTAT_V2, path_and_mode);
+        } else {
+            return SendRequest(ID_LSTAT_V1, path_and_mode);
+        }
+    }
+
+    bool FinishStat(struct stat* st) {
+        syncmsg msg;
+
+        memset(st, 0, sizeof(*st));
+        if (have_stat_v2_) {
+            if (!ReadFdExactly(fd, &msg.stat_v2, sizeof(msg.stat_v2))) {
+                fatal_errno("protocol fault: failed to read stat response");
+            }
+
+            if (msg.stat_v2.id != ID_LSTAT_V2 && msg.stat_v2.id != ID_STAT_V2) {
+                fatal_errno("protocol fault: stat response has wrong message id: %" PRIx32,
+                            msg.stat_v2.id);
+            }
+
+            if (msg.stat_v2.error != 0) {
+                errno = errno_from_wire(msg.stat_v2.error);
+                return false;
+            }
+
+            st->st_dev = msg.stat_v2.dev;
+            st->st_ino = msg.stat_v2.ino;
+            st->st_mode = msg.stat_v2.mode;
+            st->st_nlink = msg.stat_v2.nlink;
+            st->st_uid = msg.stat_v2.uid;
+            st->st_gid = msg.stat_v2.gid;
+            st->st_size = msg.stat_v2.size;
+            st->st_atime = msg.stat_v2.atime;
+            st->st_mtime = msg.stat_v2.mtime;
+            st->st_ctime = msg.stat_v2.ctime;
+            return true;
+        } else {
+            if (!ReadFdExactly(fd, &msg.stat_v1, sizeof(msg.stat_v1))) {
+                fatal_errno("protocol fault: failed to read stat response");
+            }
+
+            if (msg.stat_v1.id != ID_LSTAT_V1) {
+                fatal_errno("protocol fault: stat response has wrong message id: %" PRIx32,
+                            msg.stat_v1.id);
+            }
+
+            if (msg.stat_v1.mode == 0 && msg.stat_v1.size == 0 && msg.stat_v1.time == 0) {
+                // There's no way for us to know what the error was.
+                errno = ENOPROTOOPT;
+                return false;
+            }
+
+            st->st_mode = msg.stat_v1.mode;
+            st->st_size = msg.stat_v1.size;
+            st->st_ctime = msg.stat_v1.time;
+            st->st_mtime = msg.stat_v1.time;
+        }
+
+        return true;
+    }
+
     // Sending header, payload, and footer in a single write makes a huge
     // difference to "adb sync" performance.
     bool SendSmallFile(const char* path_and_mode,
@@ -199,7 +408,9 @@
 
         WriteOrDie(lpath, rpath, &buf[0], (p - &buf[0]));
         expect_done_ = true;
-        total_bytes_ += data_length;
+
+        // RecordFilesTransferred gets called in CopyDone.
+        RecordBytesTransferred(data_length);
         ReportProgress(rpath, data_length, data_length);
         return true;
     }
@@ -242,7 +453,7 @@
             sbuf.size = bytes_read;
             WriteOrDie(lpath, rpath, &sbuf, sizeof(SyncRequest) + bytes_read);
 
-            total_bytes_ += bytes_read;
+            RecordBytesTransferred(bytes_read);
             bytes_copied += bytes_read;
 
             // Check to see if we've received an error from the other side.
@@ -259,6 +470,8 @@
         msg.data.id = ID_DONE;
         msg.data.size = mtime;
         expect_done_ = true;
+
+        // RecordFilesTransferred gets called in CopyDone.
         return WriteOrDie(lpath, rpath, &msg.data, sizeof(msg.data));
     }
 
@@ -271,6 +484,7 @@
         if (msg.status.id == ID_OKAY) {
             if (expect_done_) {
                 expect_done_ = false;
+                RecordFilesTransferred(1);
                 return true;
             } else {
                 Error("failed to copy '%s' to '%s': received premature success", from, to);
@@ -292,48 +506,10 @@
             return false;
         }
         buf[msg.status.msglen] = 0;
-        Error("failed to copy '%s' to '%s': %s", from, to, &buf[0]);
+        Error("failed to copy '%s' to '%s': remote %s", from, to, &buf[0]);
         return false;
     }
 
-    std::string TransferRate() {
-        uint64_t ms = CurrentTimeMs() - start_time_ms_;
-        if (total_bytes_ == 0 || ms == 0) return "";
-
-        double s = static_cast<double>(ms) / 1000LL;
-        double rate = (static_cast<double>(total_bytes_) / s) / (1024*1024);
-        return android::base::StringPrintf(" %.1f MB/s (%" PRId64 " bytes in %.3fs)",
-                                           rate, total_bytes_, s);
-    }
-
-    void ReportProgress(const char* file, uint64_t file_copied_bytes, uint64_t file_total_bytes) {
-        char overall_percentage_str[5] = "?";
-        if (expected_total_bytes_ != 0) {
-            int overall_percentage = static_cast<int>(total_bytes_ * 100 / expected_total_bytes_);
-            // If we're pulling symbolic links, we'll pull the target of the link rather than
-            // just create a local link, and that will cause us to go over 100%.
-            if (overall_percentage <= 100) {
-                snprintf(overall_percentage_str, sizeof(overall_percentage_str), "%d%%",
-                         overall_percentage);
-            }
-        }
-
-        if (file_copied_bytes > file_total_bytes || file_total_bytes == 0) {
-            // This case can happen if we're racing against something that wrote to the file
-            // between our stat and our read, or if we're reading a magic file that lies about
-            // its size. Just show how much we've copied.
-            Printf("[%4s] %s: %" PRId64 "/?", overall_percentage_str, file, file_copied_bytes);
-        } else {
-            // If we're transferring multiple files, we want to know how far through the current
-            // file we are, as well as the overall percentage.
-            if (expect_multiple_files_) {
-                int file_percentage = static_cast<int>(file_copied_bytes * 100 / file_total_bytes);
-                Printf("[%4s] %s: %d%%", overall_percentage_str, file, file_percentage);
-            } else {
-                Printf("[%4s] %s", overall_percentage_str, file);
-            }
-        }
-    }
 
     void Printf(const char* fmt, ...) __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3))) {
         std::string s;
@@ -346,6 +522,18 @@
         line_printer_.Print(s, LinePrinter::INFO);
     }
 
+    void Println(const char* fmt, ...) __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3))) {
+        std::string s;
+
+        va_list ap;
+        va_start(ap, fmt);
+        android::base::StringAppendV(&s, fmt, ap);
+        va_end(ap);
+
+        line_printer_.Print(s, LinePrinter::INFO);
+        line_printer_.KeepInfoLine();
+    }
+
     void Error(const char* fmt, ...) __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3))) {
         std::string s = "adb: error: ";
 
@@ -369,33 +557,30 @@
     }
 
     void ComputeExpectedTotalBytes(const std::vector<copyinfo>& file_list) {
-        expected_total_bytes_ = 0;
+        current_ledger_.bytes_expected = 0;
         for (const copyinfo& ci : file_list) {
             // Unfortunately, this doesn't work for symbolic links, because we'll copy the
             // target of the link rather than just creating a link. (But ci.size is the link size.)
-            if (!ci.skip) expected_total_bytes_ += ci.size;
+            if (!ci.skip) current_ledger_.bytes_expected += ci.size;
         }
-        expect_multiple_files_ = true;
+        current_ledger_.expect_multiple_files = true;
     }
 
     void SetExpectedTotalBytes(uint64_t expected_total_bytes) {
-        expected_total_bytes_ = expected_total_bytes;
-        expect_multiple_files_ = false;
+        current_ledger_.bytes_expected = expected_total_bytes;
+        current_ledger_.expect_multiple_files = false;
     }
 
-    uint64_t total_bytes_;
-
     // TODO: add a char[max] buffer here, to replace syncsendbuf...
     int fd;
     size_t max;
 
   private:
-    uint64_t start_time_ms_;
-
-    uint64_t expected_total_bytes_;
-    bool expect_multiple_files_;
     bool expect_done_;
+    bool have_stat_v2_;
 
+    TransferLedger global_ledger_;
+    TransferLedger current_ledger_;
     LinePrinter line_printer_;
 
     bool SendQuit() {
@@ -422,18 +607,12 @@
         }
         return true;
     }
-
-    static uint64_t CurrentTimeMs() {
-        struct timeval tv;
-        gettimeofday(&tv, 0); // (Not clock_gettime because of Mac/Windows.)
-        return static_cast<uint64_t>(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
-    }
 };
 
 typedef void (sync_ls_cb)(unsigned mode, unsigned size, unsigned time, const char* name);
 
 static bool sync_ls(SyncConnection& sc, const char* path,
-                    std::function<sync_ls_cb> func) {
+                    const std::function<sync_ls_cb>& func) {
     if (!sc.SendRequest(ID_LIST, path)) return false;
 
     while (true) {
@@ -454,25 +633,47 @@
     }
 }
 
-static bool sync_finish_stat(SyncConnection& sc, unsigned int* timestamp,
-                             unsigned int* mode, unsigned int* size) {
-    syncmsg msg;
-    if (!ReadFdExactly(sc.fd, &msg.stat, sizeof(msg.stat)) || msg.stat.id != ID_STAT) {
+static bool sync_stat(SyncConnection& sc, const char* path, struct stat* st) {
+    return sc.SendStat(path) && sc.FinishStat(st);
+}
+
+static bool sync_lstat(SyncConnection& sc, const char* path, struct stat* st) {
+    return sc.SendLstat(path) && sc.FinishStat(st);
+}
+
+static bool sync_stat_fallback(SyncConnection& sc, const char* path, struct stat* st) {
+    if (sync_stat(sc, path, st)) {
+        return true;
+    }
+
+    if (errno != ENOTSUP) {
         return false;
     }
 
-    if (timestamp) *timestamp = msg.stat.time;
-    if (mode) *mode = msg.stat.mode;
-    if (size) *size = msg.stat.size;
+    // Try to emulate the parts we can when talking to older adbds.
+    bool lstat_result = sync_lstat(sc, path, st);
+    if (!lstat_result) {
+        return false;
+    }
 
+    if (S_ISLNK(st->st_mode)) {
+        // If the target is a symlink, figure out whether it's a file or a directory.
+        // Also, zero out the st_size field, since no one actually cares what the path length is.
+        st->st_size = 0;
+        std::string dir_path = path;
+        dir_path.push_back('/');
+        struct stat tmp_st;
+
+        st->st_mode &= ~S_IFMT;
+        if (sync_lstat(sc, dir_path.c_str(), &tmp_st)) {
+            st->st_mode |= S_IFDIR;
+        } else {
+            st->st_mode |= S_IFREG;
+        }
+    }
     return true;
 }
 
-static bool sync_stat(SyncConnection& sc, const char* path,
-                      unsigned int* timestamp, unsigned int* mode, unsigned int* size) {
-    return sc.SendRequest(ID_STAT, path) && sync_finish_stat(sc, timestamp, mode, size);
-}
-
 static bool sync_send(SyncConnection& sc, const char* lpath, const char* rpath,
                       unsigned mtime, mode_t mode)
 {
@@ -502,7 +703,7 @@
     }
     if (st.st_size < SYNC_DATA_MAX) {
         std::string data;
-        if (!android::base::ReadFileToString(lpath, &data)) {
+        if (!android::base::ReadFileToString(lpath, &data, true)) {
             sc.Error("failed to read all of '%s': %s", lpath, strerror(errno));
             return false;
         }
@@ -519,10 +720,7 @@
 }
 
 static bool sync_recv(SyncConnection& sc, const char* rpath, const char* lpath,
-                      const char* name=nullptr) {
-    unsigned size = 0;
-    if (!sync_stat(sc, rpath, nullptr, nullptr, &size)) return false;
-
+                      const char* name, uint64_t expected_size) {
     if (!sc.SendRequest(ID_RECV, rpath)) return false;
 
     adb_unlink(lpath);
@@ -571,13 +769,13 @@
             return false;
         }
 
-        sc.total_bytes_ += msg.data.size;
-
         bytes_copied += msg.data.size;
 
-        sc.ReportProgress(name != nullptr ? name : rpath, bytes_copied, size);
+        sc.RecordBytesTransferred(msg.data.size);
+        sc.ReportProgress(name != nullptr ? name : rpath, bytes_copied, expected_size);
     }
 
+    sc.RecordFilesTransferred(1);
     adb_close(lfd);
     return true;
 }
@@ -646,7 +844,8 @@
         // TODO(b/25566053): Make pushing empty directories work.
         // TODO(b/25457350): We don't preserve permissions on directories.
         sc.Warning("skipping empty directory '%s'", lpath.c_str());
-        copyinfo ci(adb_dirname(lpath), adb_dirname(rpath), adb_basename(lpath), S_IFDIR);
+        copyinfo ci(android::base::Dirname(lpath), android::base::Dirname(rpath),
+                    android::base::Basename(lpath), S_IFDIR);
         ci.skip = true;
         file_list->push_back(ci);
         return true;
@@ -662,13 +861,14 @@
 static bool copy_local_dir_remote(SyncConnection& sc, std::string lpath,
                                   std::string rpath, bool check_timestamps,
                                   bool list_only) {
+    sc.NewTransfer();
+
     // Make sure that both directory paths end in a slash.
     // Both paths are known to be nonempty, so we don't need to check.
     ensure_trailing_separators(lpath, rpath);
 
     // Recursively build the list of files to copy.
     std::vector<copyinfo> file_list;
-    int pushed = 0;
     int skipped = 0;
     if (!local_build_list(sc, &file_list, lpath, rpath)) {
         return false;
@@ -676,20 +876,20 @@
 
     if (check_timestamps) {
         for (const copyinfo& ci : file_list) {
-            if (!sc.SendRequest(ID_STAT, ci.rpath.c_str())) {
+            if (!sc.SendLstat(ci.rpath.c_str())) {
+                sc.Error("failed to send lstat");
                 return false;
             }
         }
         for (copyinfo& ci : file_list) {
-            unsigned int timestamp, mode, size;
-            if (!sync_finish_stat(sc, &timestamp, &mode, &size)) {
-                return false;
-            }
-            if (size == ci.size) {
-                // For links, we cannot update the atime/mtime.
-                if ((S_ISREG(ci.mode & mode) && timestamp == ci.time) ||
-                        (S_ISLNK(ci.mode & mode) && timestamp >= ci.time)) {
-                    ci.skip = true;
+            struct stat st;
+            if (sc.FinishStat(&st)) {
+                if (st.st_size == static_cast<off_t>(ci.size)) {
+                    // For links, we cannot update the atime/mtime.
+                    if ((S_ISREG(ci.mode & st.st_mode) && st.st_mtime == ci.time) ||
+                        (S_ISLNK(ci.mode & st.st_mode) && st.st_mtime >= ci.time)) {
+                        ci.skip = true;
+                    }
                 }
             }
         }
@@ -700,21 +900,19 @@
     for (const copyinfo& ci : file_list) {
         if (!ci.skip) {
             if (list_only) {
-                sc.Error("would push: %s -> %s", ci.lpath.c_str(), ci.rpath.c_str());
+                sc.Println("would push: %s -> %s", ci.lpath.c_str(), ci.rpath.c_str());
             } else {
                 if (!sync_send(sc, ci.lpath.c_str(), ci.rpath.c_str(), ci.time, ci.mode)) {
                     return false;
                 }
             }
-            pushed++;
         } else {
             skipped++;
         }
     }
 
-    sc.Printf("%s: %d file%s pushed. %d file%s skipped.%s", rpath.c_str(),
-              pushed, (pushed == 1) ? "" : "s", skipped,
-              (skipped == 1) ? "" : "s", sc.TransferRate().c_str());
+    sc.RecordFilesSkipped(skipped);
+    sc.ReportTransferRate(lpath, TransferDirection::push);
     return true;
 }
 
@@ -723,10 +921,22 @@
     if (!sc.IsValid()) return false;
 
     bool success = true;
-    unsigned dst_mode;
-    if (!sync_stat(sc, dst, nullptr, &dst_mode, nullptr)) return false;
-    bool dst_exists = (dst_mode != 0);
-    bool dst_isdir = S_ISDIR(dst_mode);
+    bool dst_exists;
+    bool dst_isdir;
+
+    struct stat st;
+    if (sync_stat_fallback(sc, dst, &st)) {
+        dst_exists = true;
+        dst_isdir = S_ISDIR(st.st_mode);
+    } else {
+        if (errno == ENOENT || errno == ENOPROTOOPT) {
+            dst_exists = false;
+            dst_isdir = false;
+        } else {
+            sc.Error("stat failed when trying to push to %s: %s", dst, strerror(errno));
+            return false;
+        }
+    }
 
     if (!dst_isdir) {
         if (srcs.size() > 1) {
@@ -768,11 +978,10 @@
                 if (dst_dir.back() != '/') {
                     dst_dir.push_back('/');
                 }
-                dst_dir.append(adb_basename(src_path));
+                dst_dir.append(android::base::Basename(src_path));
             }
 
-            success &= copy_local_dir_remote(sc, src_path, dst_dir.c_str(),
-                                             false, false);
+            success &= copy_local_dir_remote(sc, src_path, dst_dir.c_str(), false, false);
             continue;
         } else if (!should_push_file(st.st_mode)) {
             sc.Warning("skipping special file '%s' (mode = 0o%o)", src_path, st.st_mode);
@@ -787,34 +996,28 @@
             if (path_holder.back() != '/') {
                 path_holder.push_back('/');
             }
-            path_holder += adb_basename(src_path);
+            path_holder += android::base::Basename(src_path);
             dst_path = path_holder.c_str();
         }
+
+        sc.NewTransfer();
         sc.SetExpectedTotalBytes(st.st_size);
         success &= sync_send(sc, src_path, dst_path, st.st_mtime, st.st_mode);
+        sc.ReportTransferRate(src_path, TransferDirection::push);
     }
 
+    sc.ReportOverallTransferRate(TransferDirection::push);
     return success;
 }
 
-static bool remote_symlink_isdir(SyncConnection& sc, const std::string& rpath) {
-    unsigned mode;
-    std::string dir_path = rpath;
-    dir_path.push_back('/');
-    if (!sync_stat(sc, dir_path.c_str(), nullptr, &mode, nullptr)) {
-        sc.Error("failed to stat remote symlink '%s'", dir_path.c_str());
-        return false;
-    }
-    return S_ISDIR(mode);
-}
-
 static bool remote_build_list(SyncConnection& sc, std::vector<copyinfo>* file_list,
                               const std::string& rpath, const std::string& lpath) {
     std::vector<copyinfo> dirlist;
     std::vector<copyinfo> linklist;
 
     // Add an entry for the current directory to ensure it gets created before pulling its contents.
-    copyinfo ci(adb_dirname(lpath), adb_dirname(rpath), adb_basename(lpath), S_IFDIR);
+    copyinfo ci(android::base::Dirname(lpath), android::base::Dirname(rpath),
+                android::base::Basename(lpath), S_IFDIR);
     file_list->push_back(ci);
 
     // Put the files/dirs in rpath on the lists.
@@ -845,7 +1048,13 @@
 
     // Check each symlink we found to see whether it's a file or directory.
     for (copyinfo& link_ci : linklist) {
-        if (remote_symlink_isdir(sc, link_ci.rpath)) {
+        struct stat st;
+        if (!sync_stat_fallback(sc, link_ci.rpath.c_str(), &st)) {
+            sc.Warning("stat failed for path %s: %s", link_ci.rpath.c_str(), strerror(errno));
+            continue;
+        }
+
+        if (S_ISDIR(st.st_mode)) {
             dirlist.emplace_back(std::move(link_ci));
         } else {
             file_list->emplace_back(std::move(link_ci));
@@ -879,6 +1088,8 @@
 
 static bool copy_remote_dir_local(SyncConnection& sc, std::string rpath,
                                   std::string lpath, bool copy_attrs) {
+    sc.NewTransfer();
+
     // Make sure that both directory paths end in a slash.
     // Both paths are known to be nonempty, so we don't need to check.
     ensure_trailing_separators(lpath, rpath);
@@ -892,7 +1103,6 @@
 
     sc.ComputeExpectedTotalBytes(file_list);
 
-    int pulled = 0;
     int skipped = 0;
     for (const copyinfo &ci : file_list) {
         if (!ci.skip) {
@@ -904,26 +1114,23 @@
                              ci.lpath.c_str(), strerror(errno));
                     return false;
                 }
-                pulled++;
                 continue;
             }
 
-            if (!sync_recv(sc, ci.rpath.c_str(), ci.lpath.c_str())) {
+            if (!sync_recv(sc, ci.rpath.c_str(), ci.lpath.c_str(), nullptr, ci.size)) {
                 return false;
             }
 
             if (copy_attrs && set_time_and_mode(ci.lpath, ci.time, ci.mode)) {
                 return false;
             }
-            pulled++;
         } else {
             skipped++;
         }
     }
 
-    sc.Printf("%s: %d file%s pulled. %d file%s skipped.%s", rpath.c_str(),
-              pulled, (pulled == 1) ? "" : "s", skipped,
-              (skipped == 1) ? "" : "s", sc.TransferRate().c_str());
+    sc.RecordFilesSkipped(skipped);
+    sc.ReportTransferRate(rpath, TransferDirection::pull);
     return true;
 }
 
@@ -944,7 +1151,7 @@
         if (srcs.size() == 1 && errno == ENOENT) {
             // However, its parent must exist.
             struct stat parent_st;
-            if (stat(adb_dirname(dst).c_str(), &parent_st) == -1) {
+            if (stat(android::base::Dirname(dst).c_str(), &parent_st) == -1) {
                 sc.Error("cannot create file/directory '%s': %s", dst, strerror(errno));
                 return false;
             }
@@ -973,22 +1180,19 @@
 
     for (const char* src_path : srcs) {
         const char* dst_path = dst;
-        unsigned src_mode, src_time, src_size;
-        if (!sync_stat(sc, src_path, &src_time, &src_mode, &src_size)) {
-            sc.Error("failed to stat remote object '%s'", src_path);
-            return false;
-        }
-        if (src_mode == 0) {
-            sc.Error("remote object '%s' does not exist", src_path);
+        struct stat src_st;
+        if (!sync_stat_fallback(sc, src_path, &src_st)) {
+            if (errno == ENOPROTOOPT) {
+                sc.Error("remote object '%s' does not exist", src_path);
+            } else {
+                sc.Error("failed to stat remote object '%s': %s", src_path, strerror(errno));
+            }
+
             success = false;
             continue;
         }
 
-        bool src_isdir = S_ISDIR(src_mode);
-        if (S_ISLNK(src_mode)) {
-            src_isdir = remote_symlink_isdir(sc, src_path);
-        }
-
+        bool src_isdir = S_ISDIR(src_st.st_mode);
         if (src_isdir) {
             std::string dst_dir = dst;
 
@@ -1002,13 +1206,13 @@
                 if (!adb_is_separator(dst_dir.back())) {
                     dst_dir.push_back(OS_PATH_SEPARATOR);
                 }
-                dst_dir.append(adb_basename(src_path));
+                dst_dir.append(android::base::Basename(src_path));
             }
 
             success &= copy_remote_dir_local(sc, src_path, dst_dir.c_str(), copy_attrs);
             continue;
-        } else if (!should_pull_file(src_mode)) {
-            sc.Warning("skipping special file '%s' (mode = 0o%o)", src_path, src_mode);
+        } else if (!should_pull_file(src_st.st_mode)) {
+            sc.Warning("skipping special file '%s' (mode = 0o%o)", src_path, src_st.st_mode);
             continue;
         }
 
@@ -1018,22 +1222,25 @@
             // really want to copy to local_dir + OS_PATH_SEPARATOR +
             // basename(remote).
             path_holder = android::base::StringPrintf("%s%c%s", dst_path, OS_PATH_SEPARATOR,
-                                                      adb_basename(src_path).c_str());
+                                                      android::base::Basename(src_path).c_str());
             dst_path = path_holder.c_str();
         }
 
-        sc.SetExpectedTotalBytes(src_size);
-        if (!sync_recv(sc, src_path, dst_path, name)) {
+        sc.NewTransfer();
+        sc.SetExpectedTotalBytes(src_st.st_size);
+        if (!sync_recv(sc, src_path, dst_path, name, src_st.st_size)) {
             success = false;
             continue;
         }
 
-        if (copy_attrs && set_time_and_mode(dst_path, src_time, src_mode) != 0) {
+        if (copy_attrs && set_time_and_mode(dst_path, src_st.st_mtime, src_st.st_mode) != 0) {
             success = false;
             continue;
         }
+        sc.ReportTransferRate(src_path, TransferDirection::pull);
     }
 
+    sc.ReportOverallTransferRate(TransferDirection::pull);
     return success;
 }
 
@@ -1041,5 +1248,9 @@
     SyncConnection sc;
     if (!sc.IsValid()) return false;
 
-    return copy_local_dir_remote(sc, lpath, rpath, true, list_only);
+    bool success = copy_local_dir_remote(sc, lpath, rpath, true, list_only);
+    if (!list_only) {
+        sc.ReportOverallTransferRate(TransferDirection::push);
+    }
+    return success;
 }
diff --git a/adb/file_sync_service.cpp b/adb/file_sync_service.cpp
index 926dbcf..2acf661 100644
--- a/adb/file_sync_service.cpp
+++ b/adb/file_sync_service.cpp
@@ -21,24 +21,31 @@
 
 #include <dirent.h>
 #include <errno.h>
-#include <log/log.h>
-#include <selinux/android.h>
+#include <linux/xattr.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <sys/xattr.h>
 #include <unistd.h>
 #include <utime.h>
 
-#include "adb.h"
-#include "adb_io.h"
-#include "adb_utils.h"
-#include "private/android_filesystem_config.h"
-#include "security_log_tags.h"
-
+#include <android-base/file.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
+#include <selinux/android.h>
+
+#include "adb.h"
+#include "adb_io.h"
+#include "adb_trace.h"
+#include "adb_utils.h"
+#include "security_log_tags.h"
+#include "sysdeps/errno.h"
+
+using android::base::StringPrintf;
 
 static bool should_use_fs_config(const std::string& path) {
     // TODO: use fs_config to configure permissions on /data.
@@ -47,11 +54,27 @@
            android::base::StartsWith(path, "/oem/");
 }
 
+static bool update_capabilities(const char* path, uint64_t capabilities) {
+    if (capabilities == 0) {
+        // Ensure we clean up in case the capabilities weren't 0 in the past.
+        removexattr(path, XATTR_NAME_CAPS);
+        return true;
+    }
+
+    vfs_cap_data cap_data = {};
+    cap_data.magic_etc = VFS_CAP_REVISION | VFS_CAP_FLAGS_EFFECTIVE;
+    cap_data.data[0].permitted = (capabilities & 0xffffffff);
+    cap_data.data[0].inheritable = 0;
+    cap_data.data[1].permitted = (capabilities >> 32);
+    cap_data.data[1].inheritable = 0;
+    return setxattr(path, XATTR_NAME_CAPS, &cap_data, sizeof(cap_data), 0) != -1;
+}
+
 static bool secure_mkdirs(const std::string& path) {
     uid_t uid = -1;
     gid_t gid = -1;
     unsigned int mode = 0775;
-    uint64_t cap = 0;
+    uint64_t capabilities = 0;
 
     if (path[0] != '/') return false;
 
@@ -62,36 +85,65 @@
         partial_path += path_component;
 
         if (should_use_fs_config(partial_path)) {
-            fs_config(partial_path.c_str(), 1, nullptr, &uid, &gid, &mode, &cap);
+            fs_config(partial_path.c_str(), 1, nullptr, &uid, &gid, &mode, &capabilities);
         }
         if (adb_mkdir(partial_path.c_str(), mode) == -1) {
             if (errno != EEXIST) {
                 return false;
             }
         } else {
-            if (chown(partial_path.c_str(), uid, gid) == -1) {
-                return false;
-            }
+            if (chown(partial_path.c_str(), uid, gid) == -1) return false;
+
             // Not all filesystems support setting SELinux labels. http://b/23530370.
             selinux_android_restorecon(partial_path.c_str(), 0);
+
+            if (!update_capabilities(partial_path.c_str(), capabilities)) return false;
         }
     }
     return true;
 }
 
-static bool do_stat(int s, const char* path) {
-    syncmsg msg;
-    msg.stat.id = ID_STAT;
+static bool do_lstat_v1(int s, const char* path) {
+    syncmsg msg = {};
+    msg.stat_v1.id = ID_LSTAT_V1;
 
-    struct stat st;
-    memset(&st, 0, sizeof(st));
-    // TODO: add a way to report that the stat failed!
+    struct stat st = {};
     lstat(path, &st);
-    msg.stat.mode = st.st_mode;
-    msg.stat.size = st.st_size;
-    msg.stat.time = st.st_mtime;
+    msg.stat_v1.mode = st.st_mode;
+    msg.stat_v1.size = st.st_size;
+    msg.stat_v1.time = st.st_mtime;
+    return WriteFdExactly(s, &msg.stat_v1, sizeof(msg.stat_v1));
+}
 
-    return WriteFdExactly(s, &msg.stat, sizeof(msg.stat));
+static bool do_stat_v2(int s, uint32_t id, const char* path) {
+    syncmsg msg = {};
+    msg.stat_v2.id = id;
+
+    decltype(&stat) stat_fn;
+    if (id == ID_STAT_V2) {
+        stat_fn = stat;
+    } else {
+        stat_fn = lstat;
+    }
+
+    struct stat st = {};
+    int rc = stat_fn(path, &st);
+    if (rc == -1) {
+        msg.stat_v2.error = errno_to_wire(errno);
+    } else {
+        msg.stat_v2.dev = st.st_dev;
+        msg.stat_v2.ino = st.st_ino;
+        msg.stat_v2.mode = st.st_mode;
+        msg.stat_v2.nlink = st.st_nlink;
+        msg.stat_v2.uid = st.st_uid;
+        msg.stat_v2.gid = st.st_gid;
+        msg.stat_v2.size = st.st_size;
+        msg.stat_v2.atime = st.st_atime;
+        msg.stat_v2.mtime = st.st_mtime;
+        msg.stat_v2.ctime = st.st_ctime;
+    }
+
+    return WriteFdExactly(s, &msg.stat_v2, sizeof(msg.stat_v2));
 }
 
 static bool do_list(int s, const char* path) {
@@ -104,7 +156,7 @@
     if (!d) goto done;
 
     while ((de = readdir(d.get()))) {
-        std::string filename(android::base::StringPrintf("%s/%s", path, de->d_name));
+        std::string filename(StringPrintf("%s/%s", path, de->d_name));
 
         struct stat st;
         if (lstat(filename.c_str(), &st) == 0) {
@@ -143,11 +195,11 @@
 }
 
 static bool SendSyncFailErrno(int fd, const std::string& reason) {
-    return SendSyncFail(fd, android::base::StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
+    return SendSyncFail(fd, StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
 }
 
-static bool handle_send_file(int s, const char* path, uid_t uid,
-                             gid_t gid, mode_t mode, std::vector<char>& buffer, bool do_unlink) {
+static bool handle_send_file(int s, const char* path, uid_t uid, gid_t gid, uint64_t capabilities,
+                             mode_t mode, std::vector<char>& buffer, bool do_unlink) {
     syncmsg msg;
     unsigned int timestamp = 0;
 
@@ -155,7 +207,7 @@
 
     int fd = adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
     if (fd < 0 && errno == ENOENT) {
-        if (!secure_mkdirs(adb_dirname(path))) {
+        if (!secure_mkdirs(android::base::Dirname(path))) {
             SendSyncFailErrno(s, "secure_mkdirs failed");
             goto fail;
         }
@@ -178,7 +230,7 @@
 
         // fchown clears the setuid bit - restore it if present.
         // Ignore the result of calling fchmod. It's not supported
-        // by all filesystems. b/12441485
+        // by all filesystems, so we don't check for success. b/12441485
         fchmod(fd, mode);
     }
 
@@ -209,6 +261,11 @@
 
     adb_close(fd);
 
+    if (!update_capabilities(path, capabilities)) {
+        SendSyncFailErrno(s, "update_capabilities failed");
+        goto fail;
+    }
+
     utimbuf u;
     u.actime = timestamp;
     u.modtime = timestamp;
@@ -277,7 +334,7 @@
 
     ret = symlink(&buffer[0], path.c_str());
     if (ret && errno == ENOENT) {
-        if (!secure_mkdirs(adb_dirname(path))) {
+        if (!secure_mkdirs(android::base::Dirname(path))) {
             SendSyncFailErrno(s, "secure_mkdirs failed");
             return false;
         }
@@ -338,13 +395,13 @@
 
     uid_t uid = -1;
     gid_t gid = -1;
-    uint64_t cap = 0;
+    uint64_t capabilities = 0;
     if (should_use_fs_config(path)) {
         unsigned int broken_api_hack = mode;
-        fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &cap);
+        fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &capabilities);
         mode = broken_api_hack;
     }
-    return handle_send_file(s, path.c_str(), uid, gid, mode, buffer, do_unlink);
+    return handle_send_file(s, path.c_str(), uid, gid, capabilities, mode, buffer, do_unlink);
 }
 
 static bool do_recv(int s, const char* path, std::vector<char>& buffer) {
@@ -380,9 +437,31 @@
     return WriteFdExactly(s, &msg.data, sizeof(msg.data));
 }
 
+static const char* sync_id_to_name(uint32_t id) {
+  switch (id) {
+    case ID_LSTAT_V1:
+      return "lstat_v1";
+    case ID_LSTAT_V2:
+      return "lstat_v2";
+    case ID_STAT_V2:
+      return "stat_v2";
+    case ID_LIST:
+      return "list";
+    case ID_SEND:
+      return "send";
+    case ID_RECV:
+      return "recv";
+    case ID_QUIT:
+        return "quit";
+    default:
+        return "???";
+  }
+}
+
 static bool handle_sync_command(int fd, std::vector<char>& buffer) {
     D("sync: waiting for request");
 
+    ATRACE_CALL();
     SyncRequest request;
     if (!ReadFdExactly(fd, &request, sizeof(request))) {
         SendSyncFail(fd, "command read failure");
@@ -400,34 +479,39 @@
     }
     name[path_length] = 0;
 
-    const char* id = reinterpret_cast<const char*>(&request.id);
-    D("sync: '%.4s' '%s'", id, name);
+    std::string id_name = sync_id_to_name(request.id);
+    std::string trace_name = StringPrintf("%s(%s)", id_name.c_str(), name);
+    ATRACE_NAME(trace_name.c_str());
 
+    D("sync: %s('%s')", id_name.c_str(), name);
     switch (request.id) {
-      case ID_STAT:
-        if (!do_stat(fd, name)) return false;
-        break;
-      case ID_LIST:
-        if (!do_list(fd, name)) return false;
-        break;
-      case ID_SEND:
-        if (!do_send(fd, name, buffer)) return false;
-        break;
-      case ID_RECV:
-        if (!do_recv(fd, name, buffer)) return false;
-        break;
-      case ID_QUIT:
-        return false;
-      default:
-        SendSyncFail(fd, android::base::StringPrintf("unknown command '%.4s' (%08x)",
-                                                     id, request.id));
-        return false;
+        case ID_LSTAT_V1:
+            if (!do_lstat_v1(fd, name)) return false;
+            break;
+        case ID_LSTAT_V2:
+        case ID_STAT_V2:
+            if (!do_stat_v2(fd, request.id, name)) return false;
+            break;
+        case ID_LIST:
+            if (!do_list(fd, name)) return false;
+            break;
+        case ID_SEND:
+            if (!do_send(fd, name, buffer)) return false;
+            break;
+        case ID_RECV:
+            if (!do_recv(fd, name, buffer)) return false;
+            break;
+        case ID_QUIT:
+            return false;
+        default:
+            SendSyncFail(fd, StringPrintf("unknown command %08x", request.id));
+            return false;
     }
 
     return true;
 }
 
-void file_sync_service(int fd, void* cookie) {
+void file_sync_service(int fd, void*) {
     std::vector<char> buffer(SYNC_DATA_MAX);
 
     while (handle_sync_command(fd, buffer)) {
diff --git a/adb/file_sync_service.h b/adb/file_sync_service.h
index 0e25974..90f1965 100644
--- a/adb/file_sync_service.h
+++ b/adb/file_sync_service.h
@@ -22,7 +22,9 @@
 
 #define MKID(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
 
-#define ID_STAT MKID('S','T','A','T')
+#define ID_LSTAT_V1 MKID('S','T','A','T')
+#define ID_STAT_V2 MKID('S','T','A','2')
+#define ID_LSTAT_V2 MKID('L','S','T','2')
 #define ID_LIST MKID('L','I','S','T')
 #define ID_SEND MKID('S','E','N','D')
 #define ID_RECV MKID('R','E','C','V')
@@ -45,7 +47,21 @@
         uint32_t mode;
         uint32_t size;
         uint32_t time;
-    } stat;
+    } stat_v1;
+    struct __attribute__((packed)) {
+        uint32_t id;
+        uint32_t error;
+        uint64_t dev;
+        uint64_t ino;
+        uint32_t mode;
+        uint32_t nlink;
+        uint32_t uid;
+        uint32_t gid;
+        uint64_t size;
+        int64_t atime;
+        int64_t mtime;
+        int64_t ctime;
+    } stat_v2;
     struct __attribute__((packed)) {
         uint32_t id;
         uint32_t mode;
diff --git a/adb/get_my_path_darwin.cpp b/adb/get_my_path_darwin.cpp
deleted file mode 100644
index b0c962e..0000000
--- a/adb/get_my_path_darwin.cpp
+++ /dev/null
@@ -1,32 +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.
- */
-
-#import <Carbon/Carbon.h>
-#include <unistd.h>
-
-#include "adb.h"
-
-void get_my_path(char *s, size_t maxLen)
-{
-    CFBundleRef mainBundle = CFBundleGetMainBundle();
-    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
-    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
-    CFRelease(executableURL);
-
-    CFStringGetFileSystemRepresentation(executablePathString, s, maxLen);
-    CFRelease(executablePathString);
-}
-
diff --git a/adb/get_my_path_linux.cpp b/adb/get_my_path_linux.cpp
deleted file mode 100644
index 11c0b21..0000000
--- a/adb/get_my_path_linux.cpp
+++ /dev/null
@@ -1,35 +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.
- */
-
-#include <limits.h>
-#include <stdio.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "adb.h"
-
-void get_my_path(char *exe, size_t maxLen)
-{
-    char proc[64];
-    snprintf(proc, sizeof proc, "/proc/%d/exe", getpid());
-    int err = readlink(proc, exe, maxLen - 1);
-    if(err > 0) {
-        exe[err] = '\0';
-    } else {
-        exe[0] = '\0';
-    }
-}
-
diff --git a/adb/jdwp_service.cpp b/adb/jdwp_service.cpp
index 3c812cc..f0dff06 100644
--- a/adb/jdwp_service.cpp
+++ b/adb/jdwp_service.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-/* implement the "debug-ports" and "track-debug-ports" device services */
+#if !ADB_HOST
 
 #define TRACE_TAG JDWP
 
@@ -24,22 +24,30 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
 #include <unistd.h>
 
+#include <list>
+#include <memory>
+#include <vector>
+
 #include "adb.h"
+#include "adb_io.h"
+#include "adb_unique_fd.h"
 #include "adb_utils.h"
 
 /* here's how these things work.
 
    when adbd starts, it creates a unix server socket
-   named @vm-debug-control (@ is a shortcut for "first byte is zero"
+   named @jdwp-control (@ is a shortcut for "first byte is zero"
    to use the private namespace instead of the file system)
 
    when a new JDWP daemon thread starts in a new VM process, it creates
-   a connection to @vm-debug-control to announce its availability.
+   a connection to @jdwp-control to announce its availability.
 
 
-     JDWP thread                             @vm-debug-control
+     JDWP thread                             @jdwp-control
          |                                         |
          |------------------------------->         |
          | hello I'm in process <pid>              |
@@ -72,7 +80,7 @@
         to the JDWP process with the help of sendmsg()
 
 
-     JDWP thread                             @vm-debug-control
+     JDWP thread                             @jdwp-control
          |                                         |
          |                  <----------------------|
          |           OK, try this file descriptor  |
@@ -116,249 +124,172 @@
  ** for each JDWP process, we record its pid and its connected socket
  **/
 
-#define  MAX_OUT_FDS   4
+// PIDs are transmitted as 4 hex digits in ascii.
+static constexpr size_t PID_LEN = 4;
 
-#if !ADB_HOST
+static void jdwp_process_event(int socket, unsigned events, void* _proc);
+static void jdwp_process_list_updated(void);
 
-#include <sys/socket.h>
-#include <sys/un.h>
+struct JdwpProcess;
+static std::list<std::unique_ptr<JdwpProcess>> _jdwp_list;
 
 struct JdwpProcess {
-    JdwpProcess*  next;
-    JdwpProcess*  prev;
-    int           pid;
-    int           socket;
-    fdevent*      fde;
+    explicit JdwpProcess(int socket) {
+        this->socket = socket;
+        this->fde = fdevent_create(socket, jdwp_process_event, this);
 
-    char          in_buff[4];  /* input character to read PID */
-    int           in_len;      /* number from JDWP process    */
+        if (!this->fde) {
+            fatal("could not create fdevent for new JDWP process");
+        }
 
-    int           out_fds[MAX_OUT_FDS]; /* output array of file descriptors */
-    int           out_count;            /* to send to the JDWP process      */
+        this->fde->state |= FDE_DONT_CLOSE;
+
+        /* start by waiting for the PID */
+        fdevent_add(this->fde, FDE_READ);
+    }
+
+    ~JdwpProcess() {
+        if (this->socket >= 0) {
+            adb_shutdown(this->socket);
+            adb_close(this->socket);
+            this->socket = -1;
+        }
+
+        if (this->fde) {
+            fdevent_destroy(this->fde);
+            this->fde = nullptr;
+        }
+
+        out_fds.clear();
+    }
+
+    void RemoveFromList() {
+        if (this->pid >= 0) {
+            D("removing pid %d from jdwp process list", this->pid);
+        } else {
+            D("removing transient JdwpProcess from list");
+        }
+
+        auto pred = [this](const auto& proc) { return proc.get() == this; };
+        _jdwp_list.remove_if(pred);
+    }
+
+    int pid = -1;
+    int socket = -1;
+    fdevent* fde = nullptr;
+
+    std::vector<unique_fd> out_fds;
 };
 
-static JdwpProcess  _jdwp_list;
+static size_t jdwp_process_list(char* buffer, size_t bufferlen) {
+    std::string temp;
 
-static int
-jdwp_process_list( char*  buffer, int  bufferlen )
-{
-    char*         end  = buffer + bufferlen;
-    char*         p    = buffer;
-    JdwpProcess*  proc = _jdwp_list.next;
-
-    for ( ; proc != &_jdwp_list; proc = proc->next ) {
-        int  len;
-
+    for (auto& proc : _jdwp_list) {
         /* skip transient connections */
-        if (proc->pid < 0)
+        if (proc->pid < 0) {
             continue;
+        }
 
-        len = snprintf(p, end-p, "%d\n", proc->pid);
-        if (p + len >= end)
+        std::string next = std::to_string(proc->pid) + "\n";
+        if (temp.length() + next.length() > bufferlen) {
+            D("truncating JDWP process list (max len = %zu)", bufferlen);
             break;
-        p += len;
-    }
-    p[0] = 0;
-    return (p - buffer);
-}
-
-
-static int
-jdwp_process_list_msg( char*  buffer, int  bufferlen )
-{
-    char  head[5];
-    int   len = jdwp_process_list( buffer+4, bufferlen-4 );
-    snprintf(head, sizeof head, "%04x", len);
-    memcpy(buffer, head, 4);
-    return len + 4;
-}
-
-
-static void  jdwp_process_list_updated(void);
-
-static void
-jdwp_process_free( JdwpProcess*  proc )
-{
-    if (proc) {
-        int  n;
-
-        proc->prev->next = proc->next;
-        proc->next->prev = proc->prev;
-
-        if (proc->socket >= 0) {
-            adb_shutdown(proc->socket);
-            adb_close(proc->socket);
-            proc->socket = -1;
         }
-
-        if (proc->fde != NULL) {
-            fdevent_destroy(proc->fde);
-            proc->fde = NULL;
-        }
-        proc->pid = -1;
-
-        for (n = 0; n < proc->out_count; n++) {
-            adb_close(proc->out_fds[n]);
-        }
-        proc->out_count = 0;
-
-        free(proc);
-
-        jdwp_process_list_updated();
+        temp.append(next);
     }
+
+    memcpy(buffer, temp.data(), temp.length());
+    return temp.length();
 }
 
-
-static void  jdwp_process_event(int, unsigned, void*);  /* forward */
-
-
-static JdwpProcess*
-jdwp_process_alloc( int  socket )
-{
-    JdwpProcess* proc = reinterpret_cast<JdwpProcess*>(
-        calloc(1, sizeof(*proc)));
-
-    if (proc == NULL) {
-        D("not enough memory to create new JDWP process");
-        return NULL;
+static size_t jdwp_process_list_msg(char* buffer, size_t bufferlen) {
+    // Message is length-prefixed with 4 hex digits in ASCII.
+    static constexpr size_t header_len = 4;
+    if (bufferlen < header_len) {
+        fatal("invalid JDWP process list buffer size: %zu", bufferlen);
     }
 
-    proc->socket = socket;
-    proc->pid    = -1;
-    proc->next   = proc;
-    proc->prev   = proc;
-
-    proc->fde = fdevent_create( socket, jdwp_process_event, proc );
-    if (proc->fde == NULL) {
-        D("could not create fdevent for new JDWP process" );
-        free(proc);
-        return NULL;
-    }
-
-    proc->fde->state |= FDE_DONT_CLOSE;
-    proc->in_len      = 0;
-    proc->out_count   = 0;
-
-    /* append to list */
-    proc->next = &_jdwp_list;
-    proc->prev = proc->next->prev;
-
-    proc->prev->next = proc;
-    proc->next->prev = proc;
-
-    /* start by waiting for the PID */
-    fdevent_add(proc->fde, FDE_READ);
-
-    return proc;
+    char head[header_len + 1];
+    size_t len = jdwp_process_list(buffer + header_len, bufferlen - header_len);
+    snprintf(head, sizeof head, "%04zx", len);
+    memcpy(buffer, head, header_len);
+    return len + header_len;
 }
 
-
-static void
-jdwp_process_event( int  socket, unsigned  events, void*  _proc )
-{
-    JdwpProcess*  proc = reinterpret_cast<JdwpProcess*>(_proc);
+static void jdwp_process_event(int socket, unsigned events, void* _proc) {
+    JdwpProcess* proc = reinterpret_cast<JdwpProcess*>(_proc);
 
     if (events & FDE_READ) {
         if (proc->pid < 0) {
             /* read the PID as a 4-hexchar string */
-            char*  p    = proc->in_buff + proc->in_len;
-            int    size = 4 - proc->in_len;
-            char   temp[5];
-            while (size > 0) {
-                int  len = recv( socket, p, size, 0 );
-                if (len < 0) {
-                    if (errno == EINTR)
-                        continue;
-                    if (errno == EAGAIN)
-                        return;
-                    /* this can fail here if the JDWP process crashes very fast */
-                    D("weird unknown JDWP process failure: %s",
-                      strerror(errno));
-
-                    goto CloseProcess;
-                }
-                if (len == 0) {  /* end of stream ? */
-                    D("weird end-of-stream from unknown JDWP process");
-                    goto CloseProcess;
-                }
-                p            += len;
-                proc->in_len += len;
-                size         -= len;
+            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;
             }
-            /* we have read 4 characters, now decode the pid */
-            memcpy(temp, proc->in_buff, 4);
-            temp[4] = 0;
+            buf[PID_LEN] = '\0';
 
-            if (sscanf( temp, "%04x", &proc->pid ) != 1) {
-                D("could not decode JDWP %p PID number: '%s'", proc, temp);
+            if (sscanf(buf, "%04x", &proc->pid) != 1) {
+                D("could not decode JDWP %p PID number: '%s'", proc, buf);
                 goto CloseProcess;
             }
 
             /* all is well, keep reading to detect connection closure */
             D("Adding pid %d to jdwp process list", proc->pid);
             jdwp_process_list_updated();
-        }
-        else
-        {
+        } else {
             /* the pid was read, if we get there it's probably because the connection
              * was closed (e.g. the JDWP process exited or crashed) */
-            char  buf[32];
+            char buf[32];
 
-            for (;;) {
-                int  len = recv(socket, buf, sizeof(buf), 0);
+            while (true) {
+                int len = TEMP_FAILURE_RETRY(recv(socket, buf, sizeof(buf), 0));
 
-                if (len <= 0) {
-                    if (len < 0 && errno == EINTR)
-                        continue;
-                    if (len < 0 && errno == EAGAIN)
+                if (len == 0) {
+                    D("terminating JDWP %d connection: EOF", proc->pid);
+                    break;
+                } else if (len < 0) {
+                    if (len < 0 && errno == EAGAIN) {
                         return;
-                    else {
-                        D("terminating JDWP %d connection: %s", proc->pid,
-                          strerror(errno));
-                        break;
                     }
-                }
-                else {
-                    D( "ignoring unexpected JDWP %d control socket activity (%d bytes)",
-                       proc->pid, len );
+
+                    D("terminating JDWP %d connection: EOF", proc->pid);
+                    break;
+                } else {
+                    D("ignoring unexpected JDWP %d control socket activity (%d bytes)", proc->pid,
+                      len);
                 }
             }
 
-        CloseProcess:
-            if (proc->pid >= 0) {
-                D( "remove pid %d to jdwp process list", proc->pid );
-            }
-            jdwp_process_free(proc);
-            return;
+            goto CloseProcess;
         }
     }
 
     if (events & FDE_WRITE) {
-        D("trying to write to JDWP pid controli (count=%d first=%d) %d",
-          proc->pid, proc->out_count, proc->out_fds[0]);
-        if (proc->out_count > 0) {
-            int  fd = proc->out_fds[0];
-            int  n, ret;
-            struct cmsghdr*  cmsg;
-            struct msghdr    msg;
-            struct iovec     iov;
-            char             dummy = '!';
-            char             buffer[sizeof(struct cmsghdr) + sizeof(int)];
+        D("trying to send fd to JDWP process (count = %zu)", proc->out_fds.size());
+        if (!proc->out_fds.empty()) {
+            int fd = proc->out_fds.back().get();
+            struct cmsghdr* cmsg;
+            struct msghdr msg;
+            struct iovec iov;
+            char dummy = '!';
+            char buffer[sizeof(struct cmsghdr) + sizeof(int)];
 
-            iov.iov_base       = &dummy;
-            iov.iov_len        = 1;
-            msg.msg_name       = NULL;
-            msg.msg_namelen    = 0;
-            msg.msg_iov        = &iov;
-            msg.msg_iovlen     = 1;
-            msg.msg_flags      = 0;
-            msg.msg_control    = buffer;
+            iov.iov_base = &dummy;
+            iov.iov_len = 1;
+            msg.msg_name = NULL;
+            msg.msg_namelen = 0;
+            msg.msg_iov = &iov;
+            msg.msg_iovlen = 1;
+            msg.msg_flags = 0;
+            msg.msg_control = buffer;
             msg.msg_controllen = sizeof(buffer);
 
             cmsg = CMSG_FIRSTHDR(&msg);
-            cmsg->cmsg_len   = msg.msg_controllen;
+            cmsg->cmsg_len = msg.msg_controllen;
             cmsg->cmsg_level = SOL_SOCKET;
-            cmsg->cmsg_type  = SCM_RIGHTS;
+            cmsg->cmsg_type = SCM_RIGHTS;
             ((int*)CMSG_DATA(cmsg))[0] = fd;
 
             if (!set_file_block_mode(proc->socket, true)) {
@@ -366,74 +297,59 @@
                 goto CloseProcess;
             }
 
-            for (;;) {
-                ret = sendmsg(proc->socket, &msg, 0);
-                if (ret >= 0) {
-                    adb_close(fd);
-                    break;
-                }
-                if (errno == EINTR)
-                    continue;
-                D("sending new file descriptor to JDWP %d failed: %s",
-                  proc->pid, strerror(errno));
+            int ret = TEMP_FAILURE_RETRY(sendmsg(proc->socket, &msg, 0));
+            if (ret < 0) {
+                D("sending new file descriptor to JDWP %d failed: %s", proc->pid, strerror(errno));
                 goto CloseProcess;
             }
 
-            D("sent file descriptor %d to JDWP process %d",
-              fd, proc->pid);
+            adb_close(fd);
 
-            for (n = 1; n < proc->out_count; n++)
-                proc->out_fds[n-1] = proc->out_fds[n];
+            D("sent file descriptor %d to JDWP process %d", fd, proc->pid);
+
+            proc->out_fds.pop_back();
 
             if (!set_file_block_mode(proc->socket, false)) {
                 VLOG(JDWP) << "failed to set non-blocking mode for fd " << proc->socket;
                 goto CloseProcess;
             }
 
-            if (--proc->out_count == 0)
-                fdevent_del( proc->fde, FDE_WRITE );
+            if (proc->out_fds.empty()) {
+                fdevent_del(proc->fde, FDE_WRITE);
+            }
         }
     }
+
+    return;
+
+CloseProcess:
+    proc->RemoveFromList();
+    jdwp_process_list_updated();
 }
 
-
-int
-create_jdwp_connection_fd(int  pid)
-{
-    JdwpProcess*  proc = _jdwp_list.next;
-
+int create_jdwp_connection_fd(int pid) {
     D("looking for pid %d in JDWP process list", pid);
-    for ( ; proc != &_jdwp_list; proc = proc->next ) {
+
+    for (auto& proc : _jdwp_list) {
         if (proc->pid == pid) {
-            goto FoundIt;
+            int fds[2];
+
+            if (adb_socketpair(fds) < 0) {
+                D("%s: socket pair creation failed: %s", __FUNCTION__, strerror(errno));
+                return -1;
+            }
+            D("socketpair: (%d,%d)", fds[0], fds[1]);
+
+            proc->out_fds.emplace_back(fds[1]);
+            if (proc->out_fds.size() == 1) {
+                fdevent_add(proc->fde, FDE_WRITE);
+            }
+
+            return fds[0];
         }
     }
     D("search failed !!");
     return -1;
-
-FoundIt:
-    {
-        int  fds[2];
-
-        if (proc->out_count >= MAX_OUT_FDS) {
-            D("%s: too many pending JDWP connection for pid %d",
-              __FUNCTION__, pid);
-            return -1;
-        }
-
-        if (adb_socketpair(fds) < 0) {
-            D("%s: socket pair creation failed: %s",
-              __FUNCTION__, strerror(errno));
-            return -1;
-        }
-        D("socketpair: (%d,%d)", fds[0], fds[1]);
-
-        proc->out_fds[ proc->out_count ] = fds[1];
-        if (++proc->out_count == 1)
-            fdevent_add( proc->fde, FDE_WRITE );
-
-        return fds[0];
-    }
 }
 
 /**  VM DEBUG CONTROL SOCKET
@@ -442,33 +358,27 @@
  **/
 
 /* name of the debug control Unix socket */
-#define  JDWP_CONTROL_NAME      "\0jdwp-control"
-#define  JDWP_CONTROL_NAME_LEN  (sizeof(JDWP_CONTROL_NAME)-1)
+#define JDWP_CONTROL_NAME "\0jdwp-control"
+#define JDWP_CONTROL_NAME_LEN (sizeof(JDWP_CONTROL_NAME) - 1)
 
 struct JdwpControl {
-    int       listen_socket;
-    fdevent*  fde;
+    int listen_socket;
+    fdevent* fde;
 };
 
+static JdwpControl _jdwp_control;
 
-static void
-jdwp_control_event(int  s, unsigned events, void*  user);
+static void jdwp_control_event(int s, unsigned events, void* user);
 
-
-static int
-jdwp_control_init( JdwpControl*  control,
-                   const char*   sockname,
-                   int           socknamelen )
-{
-    sockaddr_un   addr;
-    socklen_t     addrlen;
-    int           s;
-    int           maxpath = sizeof(addr.sun_path);
-    int           pathlen = socknamelen;
+static int jdwp_control_init(JdwpControl* control, const char* sockname, int socknamelen) {
+    sockaddr_un addr;
+    socklen_t addrlen;
+    int s;
+    int maxpath = sizeof(addr.sun_path);
+    int pathlen = socknamelen;
 
     if (pathlen >= maxpath) {
-        D( "vm debug control socket name too long (%d extra chars)",
-           pathlen+1-maxpath );
+        D("vm debug control socket name too long (%d extra chars)", pathlen + 1 - maxpath);
         return -1;
     }
 
@@ -476,25 +386,22 @@
     addr.sun_family = AF_UNIX;
     memcpy(addr.sun_path, sockname, socknamelen);
 
-    s = socket( AF_UNIX, SOCK_STREAM, 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));
+        D("could not create vm debug control socket. %d: %s", errno, strerror(errno));
         return -1;
     }
 
-    addrlen = (pathlen + sizeof(addr.sun_family));
+    addrlen = pathlen + sizeof(addr.sun_family);
 
     if (bind(s, reinterpret_cast<sockaddr*>(&addr), addrlen) < 0) {
-        D( "could not bind vm debug control socket: %d: %s",
-           errno, strerror(errno) );
+        D("could not bind vm debug control socket: %d: %s", errno, strerror(errno));
         adb_close(s);
         return -1;
     }
 
-    if ( listen(s, 4) < 0 ) {
-        D("listen failed in jdwp control socket: %d: %s",
-          errno, strerror(errno));
+    if (listen(s, 4) < 0) {
+        D("listen failed in jdwp control socket: %d: %s", errno, strerror(errno));
         adb_close(s);
         return -1;
     }
@@ -503,128 +410,106 @@
 
     control->fde = fdevent_create(s, jdwp_control_event, control);
     if (control->fde == NULL) {
-        D( "could not create fdevent for jdwp control socket" );
+        D("could not create fdevent for jdwp control socket");
         adb_close(s);
         return -1;
     }
 
     /* only wait for incoming connections */
     fdevent_add(control->fde, FDE_READ);
-    close_on_exec(s);
 
     D("jdwp control socket started (%d)", control->listen_socket);
     return 0;
 }
 
-
-static void
-jdwp_control_event( int  s, unsigned  events, void*  _control )
-{
-    JdwpControl*  control = (JdwpControl*) _control;
+static void jdwp_control_event(int s, unsigned events, void* _control) {
+    JdwpControl* control = (JdwpControl*)_control;
 
     if (events & FDE_READ) {
-        sockaddr_storage   ss;
-        sockaddr*          addrp = reinterpret_cast<sockaddr*>(&ss);
-        socklen_t          addrlen = sizeof(ss);
-        int                s = -1;
-        JdwpProcess*       proc;
-
-        do {
-            s = adb_socket_accept(control->listen_socket, addrp, &addrlen);
-            if (s < 0) {
-                if (errno == EINTR)
-                    continue;
-                if (errno == ECONNABORTED) {
-                    /* oops, the JDWP process died really quick */
-                    D("oops, the JDWP process died really quick");
-                    return;
-                }
+        int s = adb_socket_accept(control->listen_socket, nullptr, nullptr);
+        if (s < 0) {
+            if (errno == ECONNABORTED) {
+                /* oops, the JDWP process died really quick */
+                D("oops, the JDWP process died really quick");
+                return;
+            } else {
                 /* the socket is probably closed ? */
-                D( "weird accept() failed on jdwp control socket: %s",
-                   strerror(errno) );
+                D("weird accept() failed on jdwp control socket: %s", strerror(errno));
                 return;
             }
         }
-        while (s < 0);
 
-        proc = jdwp_process_alloc( s );
-        if (proc == NULL)
-            return;
+        auto proc = std::make_unique<JdwpProcess>(s);
+        if (!proc) {
+            fatal("failed to allocate JdwpProcess");
+        }
+
+        _jdwp_list.emplace_back(std::move(proc));
     }
 }
 
-
-static JdwpControl   _jdwp_control;
-
 /** "jdwp" local service implementation
  ** this simply returns the list of known JDWP process pids
  **/
 
-struct JdwpSocket {
-    asocket  socket;
-    int      pass;
+struct JdwpSocket : public asocket {
+    bool pass;
 };
 
-static void
-jdwp_socket_close( asocket*  s )
-{
-    asocket*  peer = s->peer;
+static void jdwp_socket_close(asocket* s) {
+    D("LS(%d): closing jdwp socket", s->id);
+
+    if (s->peer) {
+        D("LS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
+        s->peer->peer = nullptr;
+        s->peer->close(s->peer);
+        s->peer = nullptr;
+    }
 
     remove_socket(s);
-
-    if (peer) {
-        peer->peer = NULL;
-        peer->close(peer);
-    }
     free(s);
 }
 
-static int
-jdwp_socket_enqueue( asocket*  s, apacket*  p )
-{
+static int jdwp_socket_enqueue(asocket* s, apacket* p) {
     /* you can't write to this asocket */
+    D("LS(%d): JDWP socket received data?", s->id);
     put_apacket(p);
     s->peer->close(s->peer);
     return -1;
 }
 
+static void jdwp_socket_ready(asocket* s) {
+    JdwpSocket* jdwp = (JdwpSocket*)s;
+    asocket* peer = jdwp->peer;
 
-static void
-jdwp_socket_ready( asocket*  s )
-{
-    JdwpSocket*  jdwp = (JdwpSocket*)s;
-    asocket*     peer = jdwp->socket.peer;
-
-   /* on the first call, send the list of pids,
-    * on the second one, close the connection
-    */
-    if (jdwp->pass == 0) {
-        apacket*  p = get_apacket();
+    /* on the first call, send the list of pids,
+     * on the second one, close the connection
+     */
+    if (!jdwp->pass) {
+        apacket* p = get_apacket();
         p->len = jdwp_process_list((char*)p->data, s->get_max_payload());
         peer->enqueue(peer, p);
-        jdwp->pass = 1;
-    }
-    else {
+        jdwp->pass = true;
+    } else {
         peer->close(peer);
     }
 }
 
-asocket*
-create_jdwp_service_socket( void )
-{
+asocket* create_jdwp_service_socket(void) {
     JdwpSocket* s = reinterpret_cast<JdwpSocket*>(calloc(sizeof(*s), 1));
 
-    if (s == NULL)
-        return NULL;
+    if (!s) {
+        fatal("failed to allocate JdwpSocket");
+    }
 
-    install_local_socket(&s->socket);
+    install_local_socket(s);
 
-    s->socket.ready   = jdwp_socket_ready;
-    s->socket.enqueue = jdwp_socket_enqueue;
-    s->socket.close   = jdwp_socket_close;
-    s->pass           = 0;
+    s->ready = jdwp_socket_ready;
+    s->enqueue = jdwp_socket_enqueue;
+    s->close = jdwp_socket_close;
+    s->pass = false;
 
-    return &s->socket;
+    return s;
 }
 
 /** "track-jdwp" local service implementation
@@ -632,113 +517,89 @@
  ** to the client...
  **/
 
-struct JdwpTracker {
-    asocket       socket;
-    JdwpTracker*  next;
-    JdwpTracker*  prev;
-    int           need_update;
+struct JdwpTracker : public asocket {
+    bool need_initial;
 };
 
-static JdwpTracker   _jdwp_trackers_list;
+static std::vector<std::unique_ptr<JdwpTracker>> _jdwp_trackers;
 
+static void jdwp_process_list_updated(void) {
+    char buffer[1024];
+    int len = jdwp_process_list_msg(buffer, sizeof(buffer));
 
-static void
-jdwp_process_list_updated(void)
-{
-    char             buffer[1024];
-    int              len;
-    JdwpTracker*  t = _jdwp_trackers_list.next;
-
-    len = jdwp_process_list_msg(buffer, sizeof(buffer));
-
-    for ( ; t != &_jdwp_trackers_list; t = t->next ) {
-        apacket*  p    = get_apacket();
-        asocket*  peer = t->socket.peer;
+    for (auto& t : _jdwp_trackers) {
+        apacket* p = get_apacket();
         memcpy(p->data, buffer, len);
         p->len = len;
-        peer->enqueue( peer, p );
+
+        if (t->peer) {
+            // The tracker might not have been connected yet.
+            t->peer->enqueue(t->peer, p);
+        }
     }
 }
 
-static void
-jdwp_tracker_close( asocket*  s )
-{
-    JdwpTracker*  tracker = (JdwpTracker*) s;
-    asocket*      peer    = s->peer;
+static void jdwp_tracker_close(asocket* s) {
+    D("LS(%d): destroying jdwp tracker service", s->id);
 
-    if (peer) {
-        peer->peer = NULL;
-        peer->close(peer);
+    if (s->peer) {
+        D("LS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
+        s->peer->peer = nullptr;
+        s->peer->close(s->peer);
+        s->peer = nullptr;
     }
 
     remove_socket(s);
 
-    tracker->prev->next = tracker->next;
-    tracker->next->prev = tracker->prev;
-
-    free(s);
+    auto pred = [s](const auto& tracker) { return tracker.get() == s; };
+    _jdwp_trackers.erase(std::remove_if(_jdwp_trackers.begin(), _jdwp_trackers.end(), pred),
+                         _jdwp_trackers.end());
 }
 
-static void
-jdwp_tracker_ready( asocket*  s )
-{
-    JdwpTracker*  t = (JdwpTracker*) s;
+static void jdwp_tracker_ready(asocket* s) {
+    JdwpTracker* t = (JdwpTracker*)s;
 
-    if (t->need_update) {
-        apacket*  p = get_apacket();
-        t->need_update = 0;
+    if (t->need_initial) {
+        apacket* p = get_apacket();
+        t->need_initial = false;
         p->len = jdwp_process_list_msg((char*)p->data, s->get_max_payload());
         s->peer->enqueue(s->peer, p);
     }
 }
 
-static int
-jdwp_tracker_enqueue( asocket*  s, apacket*  p )
-{
+static int jdwp_tracker_enqueue(asocket* s, apacket* p) {
     /* you can't write to this socket */
+    D("LS(%d): JDWP tracker received data?", s->id);
     put_apacket(p);
     s->peer->close(s->peer);
     return -1;
 }
 
+asocket* create_jdwp_tracker_service_socket(void) {
+    auto t = std::make_unique<JdwpTracker>();
+    if (!t) {
+        fatal("failed to allocate JdwpTracker");
+    }
 
-asocket*
-create_jdwp_tracker_service_socket( void )
-{
-    JdwpTracker* t = reinterpret_cast<JdwpTracker*>(calloc(sizeof(*t), 1));
+    memset(t.get(), 0, sizeof(asocket));
 
-    if (t == NULL)
-        return NULL;
+    install_local_socket(t.get());
+    D("LS(%d): created new jdwp tracker service", t->id);
 
-    t->next = &_jdwp_trackers_list;
-    t->prev = t->next->prev;
+    t->ready = jdwp_tracker_ready;
+    t->enqueue = jdwp_tracker_enqueue;
+    t->close = jdwp_tracker_close;
+    t->need_initial = true;
 
-    t->next->prev = t;
-    t->prev->next = t;
+    asocket* result = t.get();
 
-    install_local_socket(&t->socket);
+    _jdwp_trackers.emplace_back(std::move(t));
 
-    t->socket.ready   = jdwp_tracker_ready;
-    t->socket.enqueue = jdwp_tracker_enqueue;
-    t->socket.close   = jdwp_tracker_close;
-    t->need_update    = 1;
-
-    return &t->socket;
+    return result;
 }
 
-
-int
-init_jdwp(void)
-{
-    _jdwp_list.next = &_jdwp_list;
-    _jdwp_list.prev = &_jdwp_list;
-
-    _jdwp_trackers_list.next = &_jdwp_trackers_list;
-    _jdwp_trackers_list.prev = &_jdwp_trackers_list;
-
-    return jdwp_control_init( &_jdwp_control,
-                              JDWP_CONTROL_NAME,
-                              JDWP_CONTROL_NAME_LEN );
+int init_jdwp(void) {
+    return jdwp_control_init(&_jdwp_control, JDWP_CONTROL_NAME, JDWP_CONTROL_NAME_LEN);
 }
 
 #endif /* !ADB_HOST */
diff --git a/adb/line_printer.cpp b/adb/line_printer.cpp
index 4ec8979..64d10b6 100644
--- a/adb/line_printer.cpp
+++ b/adb/line_printer.cpp
@@ -124,4 +124,5 @@
 
 void LinePrinter::KeepInfoLine() {
   if (!have_blank_line_) Out("\n");
+  have_blank_line_ = true;
 }
diff --git a/adb/mutex_list.h b/adb/mutex_list.h
deleted file mode 100644
index 4a188ee..0000000
--- a/adb/mutex_list.h
+++ /dev/null
@@ -1,17 +0,0 @@
-/* the list of mutexes used by adb */
-/* #ifndef __MUTEX_LIST_H
- * Do not use an include-guard. This file is included once to declare the locks
- * and once in win32 to actually do the runtime initialization.
- */
-#ifndef ADB_MUTEX
-#error ADB_MUTEX not defined when including this file
-#endif
-ADB_MUTEX(basename_lock)
-ADB_MUTEX(dirname_lock)
-ADB_MUTEX(transport_lock)
-#if ADB_HOST
-ADB_MUTEX(local_transports_lock)
-#endif
-ADB_MUTEX(usb_lock)
-
-#undef ADB_MUTEX
diff --git a/adb/protocol.txt b/adb/protocol.txt
index 5c7c6ba..55ea87f 100644
--- a/adb/protocol.txt
+++ b/adb/protocol.txt
@@ -29,12 +29,12 @@
 32 bit words which are sent across the wire in little endian format.
 
 struct message {
-    unsigned command;       /* command identifier constant      */
-    unsigned arg0;          /* first argument                   */
-    unsigned arg1;          /* second argument                  */
-    unsigned data_length;   /* length of payload (0 is allowed) */
-    unsigned data_crc32;    /* crc32 of data payload            */
-    unsigned magic;         /* command ^ 0xffffffff             */
+    unsigned command;       /* command identifier constant (A_CNXN, ...) */
+    unsigned arg0;          /* first argument                            */
+    unsigned arg1;          /* second argument                           */
+    unsigned data_length;   /* length of payload (0 is allowed)          */
+    unsigned data_crc32;    /* crc32 of data payload                     */
+    unsigned magic;         /* command ^ 0xffffffff                      */
 };
 
 Receipt of an invalid message header, corrupt message payload, or an
@@ -55,6 +55,8 @@
 
 --- CONNECT(version, maxdata, "system-identity-string") ----------------
 
+Command constant: A_CNXN
+
 The CONNECT message establishes the presence of a remote system.
 The version is used to ensure protocol compatibility and maxdata
 declares the maximum message body size that the remote system
@@ -80,6 +82,8 @@
 
 --- AUTH(type, 0, "data") ----------------------------------------------
 
+Command constant: A_AUTH
+
 The AUTH message informs the recipient that authentication is required to
 connect to the sender. If type is TOKEN(1), data is a random token that
 the recipient can sign with a private key. The recipient replies with an
@@ -98,6 +102,8 @@
 
 --- OPEN(local-id, 0, "destination") -----------------------------------
 
+Command constant: A_OPEN
+
 The OPEN message informs the recipient that the sender has a stream
 identified by local-id that it wishes to connect to the named
 destination in the message payload.  The local-id may not be zero.
@@ -120,11 +126,13 @@
 
 --- READY(local-id, remote-id, "") -------------------------------------
 
+Command constant: A_OKAY
+
 The READY message informs the recipient that the sender's stream
 identified by local-id is ready for write messages and that it is
 connected to the recipient's stream identified by remote-id.
 
-Neither the local-id nor the remote-id may be zero. 
+Neither the local-id nor the remote-id may be zero.
 
 A READY message containing a remote-id which does not map to an open
 stream on the recipient's side is ignored.  The stream may have been
@@ -135,9 +143,10 @@
 not change on later READY messages sent to the same stream.
 
 
-
 --- WRITE(local-id, remote-id, "data") ---------------------------------
 
+Command constant: A_WRTE
+
 The WRITE message sends data to the recipient's stream identified by
 remote-id.  The payload MUST be <= maxdata in length.
 
@@ -154,6 +163,8 @@
 
 --- CLOSE(local-id, remote-id, "") -------------------------------------
 
+Command constant: A_CLSE
+
 The CLOSE message informs recipient that the connection between the
 sender's stream (local-id) and the recipient's stream (remote-id) is
 broken.  The remote-id MUST not be zero, but the local-id MAY be zero
@@ -170,12 +181,14 @@
 
 --- SYNC(online, sequence, "") -----------------------------------------
 
+Command constant: A_SYNC
+
 The SYNC message is used by the io pump to make sure that stale
 outbound messages are discarded when the connection to the remote side
 is broken.  It is only used internally to the bridge and never valid
-to send across the wire.  
+to send across the wire.
 
-* when the connection to the remote side goes offline, the io pump 
+* when the connection to the remote side goes offline, the io pump
   sends a SYNC(0, 0) and starts discarding all messages
 * when the connection to the remote side is established, the io pump
   sends a SYNC(1, token) and continues to discard messages
diff --git a/adb/remount_service.cpp b/adb/remount_service.cpp
index 8f1c9b0..32ed28f 100644
--- a/adb/remount_service.cpp
+++ b/adb/remount_service.cpp
@@ -29,10 +29,11 @@
 
 #include <string>
 
+#include <android-base/properties.h>
+
 #include "adb.h"
 #include "adb_io.h"
 #include "adb_utils.h"
-#include "cutils/properties.h"
 #include "fs_mgr.h"
 
 // Returns the device used to mount a directory in /proc/mounts.
@@ -53,15 +54,10 @@
 
 // Returns the device used to mount a directory in the fstab.
 static std::string find_fstab_mount(const char* dir) {
-    char propbuf[PROPERTY_VALUE_MAX];
-
-    property_get("ro.hardware", propbuf, "");
-    std::string fstab_filename = std::string("/fstab.") + propbuf;
-    struct fstab* fstab = fs_mgr_read_fstab(fstab_filename.c_str());
-    struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, dir);
-    std::string dev = rec ? std::string(rec->blk_device) : "";
-    fs_mgr_free_fstab(fstab);
-    return dev;
+    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
+                                                               fs_mgr_free_fstab);
+    struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab.get(), dir);
+    return rec ? rec->blk_device : "";
 }
 
 // The proc entry for / is full of lies, so check fstab instead.
@@ -113,12 +109,8 @@
         return;
     }
 
-    char prop_buf[PROPERTY_VALUE_MAX];
-    property_get("partition.system.verified", prop_buf, "");
-    bool system_verified = (strlen(prop_buf) > 0);
-
-    property_get("partition.vendor.verified", prop_buf, "");
-    bool vendor_verified = (strlen(prop_buf) > 0);
+    bool system_verified = !(android::base::GetProperty("partition.system.verified", "").empty());
+    bool vendor_verified = !(android::base::GetProperty("partition.vendor.verified", "").empty());
 
     if (system_verified || vendor_verified) {
         // Allow remount but warn of likely bad effects
@@ -136,9 +128,7 @@
     }
 
     bool success = true;
-    property_get("ro.build.system_root_image", prop_buf, "");
-    bool system_root = !strcmp(prop_buf, "true");
-    if (system_root) {
+    if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
         success &= remount_partition(fd, "/");
     } else {
         success &= remount_partition(fd, "/system");
diff --git a/adb/services.cpp b/adb/services.cpp
index 3b212e9..c9ea039 100644
--- a/adb/services.cpp
+++ b/adb/services.cpp
@@ -38,8 +38,10 @@
 #include <cutils/sockets.h>
 
 #if !ADB_HOST
-#include "cutils/android_reboot.h"
-#include "cutils/properties.h"
+#include <android-base/properties.h>
+#include <bootloader_message/bootloader_message.h>
+#include <cutils/android_reboot.h>
+#include <log/log_properties.h>
 #endif
 
 #include "adb.h"
@@ -49,6 +51,7 @@
 #include "remount_service.h"
 #include "services.h"
 #include "shell_service.h"
+#include "socket_spec.h"
 #include "sysdeps.h"
 #include "transport.h"
 
@@ -72,15 +75,13 @@
         WriteFdExactly(fd, "adbd is already running as root\n");
         adb_close(fd);
     } else {
-        char value[PROPERTY_VALUE_MAX];
-        property_get("ro.debuggable", value, "");
-        if (strcmp(value, "1") != 0) {
+        if (!__android_log_is_debuggable()) {
             WriteFdExactly(fd, "adbd cannot run as root in production builds\n");
             adb_close(fd);
             return;
         }
 
-        property_set("service.adb.root", "1");
+        android::base::SetProperty("service.adb.root", "1");
         WriteFdExactly(fd, "restarting adbd as root\n");
         adb_close(fd);
     }
@@ -91,7 +92,7 @@
         WriteFdExactly(fd, "adbd not running as root\n");
         adb_close(fd);
     } else {
-        property_set("service.adb.root", "0");
+        android::base::SetProperty("service.adb.root", "0");
         WriteFdExactly(fd, "restarting adbd as non root\n");
         adb_close(fd);
     }
@@ -105,15 +106,13 @@
         return;
     }
 
-    char value[PROPERTY_VALUE_MAX];
-    snprintf(value, sizeof(value), "%d", port);
-    property_set("service.adb.tcp.port", value);
+    android::base::SetProperty("service.adb.tcp.port", android::base::StringPrintf("%d", port));
     WriteFdFmt(fd, "restarting in TCP mode port: %d\n", port);
     adb_close(fd);
 }
 
 void restart_usb_service(int fd, void *cookie) {
-    property_set("service.adb.tcp.port", "0");
+    android::base::SetProperty("service.adb.tcp.port", "0");
     WriteFdExactly(fd, "restarting in USB mode\n");
     adb_close(fd);
 }
@@ -135,17 +134,12 @@
             return false;
         }
 
-        const char* const recovery_dir = "/cache/recovery";
-        const char* const command_file = "/cache/recovery/command";
-        // Ensure /cache/recovery exists.
-        if (adb_mkdir(recovery_dir, 0770) == -1 && errno != EEXIST) {
-            D("Failed to create directory '%s': %s", recovery_dir, strerror(errno));
-            return false;
-        }
-
-        bool write_status = android::base::WriteStringToFile(
-                auto_reboot ? "--sideload_auto_reboot" : "--sideload", command_file);
-        if (!write_status) {
+        const std::vector<std::string> options = {
+            auto_reboot ? "--sideload_auto_reboot" : "--sideload"
+        };
+        std::string err;
+        if (!write_bootloader_message(options, &err)) {
+            D("Failed to set bootloader message: %s", err.c_str());
             return false;
         }
 
@@ -154,16 +148,9 @@
 
     sync();
 
-    char property_val[PROPERTY_VALUE_MAX];
-    int ret = snprintf(property_val, sizeof(property_val), "reboot,%s", reboot_arg);
-    if (ret >= static_cast<int>(sizeof(property_val))) {
-        WriteFdFmt(fd, "reboot string too long: %d\n", ret);
-        return false;
-    }
-
-    ret = property_set(ANDROID_RB_PROPERTY, property_val);
-    if (ret < 0) {
-        WriteFdFmt(fd, "reboot failed: %d\n", ret);
+    std::string reboot_string = android::base::StringPrintf("reboot,%s", reboot_arg);
+    if (!android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_string)) {
+        WriteFdFmt(fd, "reboot (%s) failed\n", reboot_string.c_str());
         return false;
     }
 
@@ -255,6 +242,15 @@
     }
     D("socketpair: (%d,%d)", s[0], s[1]);
 
+#if !ADB_HOST
+    if (func == &file_sync_service) {
+        // Set file sync service socket to maximum size
+        int max_buf = LINUX_MAX_SOCKET_SIZE;
+        adb_setsockopt(s[0], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
+        adb_setsockopt(s[1], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
+    }
+#endif // !ADB_HOST
+
     stinfo* sti = reinterpret_cast<stinfo*>(malloc(sizeof(stinfo)));
     if (sti == nullptr) {
         fatal("cannot allocate stinfo");
@@ -278,36 +274,12 @@
 int service_to_fd(const char* name, const atransport* transport) {
     int ret = -1;
 
-    if(!strncmp(name, "tcp:", 4)) {
-        int port = atoi(name + 4);
-        name = strchr(name + 4, ':');
-        if(name == 0) {
-            std::string error;
-            ret = network_loopback_client(port, SOCK_STREAM, &error);
-            if (ret >= 0)
-                disable_tcp_nagle(ret);
-        } else {
-#if ADB_HOST
-            std::string error;
-            ret = network_connect(name + 1, port, SOCK_STREAM, 0, &error);
-#else
-            return -1;
-#endif
+    if (is_socket_spec(name)) {
+        std::string error;
+        ret = socket_spec_connect(name, &error);
+        if (ret < 0) {
+            LOG(ERROR) << "failed to connect to socket '" << name << "': " << error;
         }
-#if !defined(_WIN32)   /* winsock doesn't implement unix domain sockets */
-    } else if(!strncmp(name, "local:", 6)) {
-        ret = socket_local_client(name + 6,
-                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
-    } else if(!strncmp(name, "localreserved:", 14)) {
-        ret = socket_local_client(name + 14,
-                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
-    } else if(!strncmp(name, "localabstract:", 14)) {
-        ret = socket_local_client(name + 14,
-                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
-    } else if(!strncmp(name, "localfilesystem:", 16)) {
-        ret = socket_local_client(name + 16,
-                ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
-#endif
 #if !ADB_HOST
     } else if(!strncmp("dev:", name, 4)) {
         ret = unix_open(name + 4, O_RDWR | O_CLOEXEC);
@@ -405,45 +377,6 @@
     D("wait_for_state is done");
 }
 
-static void connect_device(const std::string& address, std::string* response) {
-    if (address.empty()) {
-        *response = "empty address";
-        return;
-    }
-
-    std::string serial;
-    std::string host;
-    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
-    if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
-        return;
-    }
-
-    std::string error;
-    int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error);
-    if (fd == -1) {
-        *response = android::base::StringPrintf("unable to connect to %s: %s",
-                                                serial.c_str(), error.c_str());
-        return;
-    }
-
-    D("client: connected %s remote on fd %d", serial.c_str(), fd);
-    close_on_exec(fd);
-    disable_tcp_nagle(fd);
-
-    // Send a TCP keepalive ping to the device every second so we can detect disconnects.
-    if (!set_tcp_keepalive(fd, 1)) {
-        D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
-    }
-
-    int ret = register_socket_transport(fd, serial.c_str(), port, 0);
-    if (ret < 0) {
-        adb_close(fd);
-        *response = android::base::StringPrintf("already connected to %s", serial.c_str());
-    } else {
-        *response = android::base::StringPrintf("connected to %s", serial.c_str());
-    }
-}
-
 void connect_emulator(const std::string& port_spec, std::string* response) {
     std::vector<std::string> pieces = android::base::Split(port_spec, ",");
     if (pieces.size() != 2) {
diff --git a/adb/set_verity_enable_state_service.cpp b/adb/set_verity_enable_state_service.cpp
index f5188e9..d4dd256 100644
--- a/adb/set_verity_enable_state_service.cpp
+++ b/adb/set_verity_enable_state_service.cpp
@@ -24,16 +24,18 @@
 #include <stdio.h>
 #include <sys/stat.h>
 
-#include "cutils/properties.h"
+#include "android-base/properties.h"
+#include "android-base/stringprintf.h"
+#include <log/log_properties.h>
 
 #include "adb.h"
 #include "adb_io.h"
+#include "adb_unique_fd.h"
 #include "fs_mgr.h"
 #include "remount_service.h"
 
 #include "fec/io.h"
 
-#define FSTAB_PREFIX "/fstab."
 struct fstab *fstab;
 
 #ifdef ALLOW_ADBD_DISABLE_VERITY
@@ -88,56 +90,44 @@
     return 0;
 }
 
-void set_verity_enabled_state_service(int fd, void* cookie)
-{
+void set_verity_enabled_state_service(int fd, void* cookie) {
+    unique_fd closer(fd);
+
     bool enable = (cookie != NULL);
-    if (kAllowDisableVerity) {
-        char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
-        char propbuf[PROPERTY_VALUE_MAX];
-        int i;
-        bool any_changed = false;
-
-        property_get("ro.secure", propbuf, "0");
-        if (strcmp(propbuf, "1")) {
-            WriteFdFmt(fd, "verity not enabled - ENG build\n");
-            goto errout;
-        }
-
-        property_get("ro.debuggable", propbuf, "0");
-        if (strcmp(propbuf, "1")) {
-            WriteFdFmt(fd, "verity cannot be disabled/enabled - USER build\n");
-            goto errout;
-        }
-
-        property_get("ro.hardware", propbuf, "");
-        snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s",
-                 propbuf);
-
-        fstab = fs_mgr_read_fstab(fstab_filename);
-        if (!fstab) {
-            WriteFdFmt(fd, "Failed to open %s\nMaybe run adb root?\n", fstab_filename);
-            goto errout;
-        }
-
-        /* Loop through entries looking for ones that vold manages */
-        for (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;
-                }
-           }
-        }
-
-        if (any_changed) {
-            WriteFdFmt(fd, "Now reboot your device for settings to take effect\n");
-        }
-    } else {
+    if (!kAllowDisableVerity) {
         WriteFdFmt(fd, "%s-verity only works for userdebug builds\n",
                    enable ? "enable" : "disable");
     }
 
-errout:
-    adb_close(fd);
+    if (!android::base::GetBoolProperty("ro.secure", false)) {
+        WriteFdFmt(fd, "verity not enabled - ENG build\n");
+        return;
+    }
+    if (!__android_log_is_debuggable()) {
+        WriteFdFmt(fd, "verity cannot be disabled/enabled - USER build\n");
+        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;
+    }
+
+    // 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;
+            }
+        }
+    }
+
+    if (any_changed) {
+        WriteFdFmt(fd, "Now reboot your device for settings to take effect\n");
+    }
 }
diff --git a/adb/shell_service.cpp b/adb/shell_service.cpp
index 104f399..d4f334b 100644
--- a/adb/shell_service.cpp
+++ b/adb/shell_service.cpp
@@ -82,6 +82,7 @@
 #include "shell_service.h"
 
 #include <errno.h>
+#include <paths.h>
 #include <pty.h>
 #include <pwd.h>
 #include <sys/select.h>
@@ -94,31 +95,17 @@
 
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
-#include <paths.h>
-#include <log/log.h>
+#include <private/android_logger.h>
 
 #include "adb.h"
 #include "adb_io.h"
 #include "adb_trace.h"
+#include "adb_unique_fd.h"
 #include "adb_utils.h"
 #include "security_log_tags.h"
 
 namespace {
 
-void init_subproc_child()
-{
-    setsid();
-
-    // Set OOM score adjustment to prevent killing
-    int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
-    if (fd >= 0) {
-        adb_write(fd, "0", 1);
-        adb_close(fd);
-    } else {
-       D("adb: unable to update oom_score_adj");
-    }
-}
-
 // Reads from |fd| until close or failure.
 std::string ReadAll(int fd) {
     char buffer[512];
@@ -136,14 +123,14 @@
 }
 
 // Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
-bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
+bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
     int sockets[2];
     if (adb_socketpair(sockets) < 0) {
         PLOG(ERROR) << "cannot create socket pair";
         return false;
     }
-    fd1->Reset(sockets[0]);
-    fd2->Reset(sockets[1]);
+    fd1->reset(sockets[0]);
+    fd2->reset(sockets[1]);
     return true;
 }
 
@@ -155,7 +142,7 @@
 
     const std::string& command() const { return command_; }
 
-    int ReleaseLocalSocket() { return local_socket_sfd_.Release(); }
+    int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
 
     pid_t pid() const { return pid_; }
 
@@ -170,19 +157,19 @@
 
   private:
     // Opens the file at |pts_name|.
-    int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
+    int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
 
     static void ThreadHandler(void* userdata);
     void PassDataStreams();
     void WaitForExit();
 
-    ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
-                         fd_set* master_write_set_ptr);
+    unique_fd* SelectLoop(fd_set* master_read_set_ptr,
+                          fd_set* master_write_set_ptr);
 
     // Input/output stream handlers. Success returns nullptr, failure returns
     // a pointer to the failed FD.
-    ScopedFd* PassInput();
-    ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
+    unique_fd* PassInput();
+    unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
 
     const std::string command_;
     const std::string terminal_type_;
@@ -190,10 +177,10 @@
     SubprocessType type_;
     SubprocessProtocol protocol_;
     pid_t pid_ = -1;
-    ScopedFd local_socket_sfd_;
+    unique_fd local_socket_sfd_;
 
     // Shell protocol variables.
-    ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
+    unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
     std::unique_ptr<ShellProtocol> input_, output_;
     size_t input_bytes_left_ = 0;
 
@@ -225,8 +212,8 @@
 }
 
 bool Subprocess::ForkAndExec(std::string* error) {
-    ScopedFd child_stdinout_sfd, child_stderr_sfd;
-    ScopedFd parent_error_sfd, child_error_sfd;
+    unique_fd child_stdinout_sfd, child_stderr_sfd;
+    unique_fd parent_error_sfd, child_error_sfd;
     char pts_name[PATH_MAX];
 
     if (command_.empty()) {
@@ -251,7 +238,7 @@
         char** current = environ;
         while (char* env_cstr = *current++) {
             std::string env_string = env_cstr;
-            char* delimiter = strchr(env_string.c_str(), '=');
+            char* delimiter = strchr(&env_string[0], '=');
 
             // Drop any values that don't contain '='.
             if (delimiter) {
@@ -290,7 +277,7 @@
         int fd;
         pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
         if (pid_ > 0) {
-          stdinout_sfd_.Reset(fd);
+          stdinout_sfd_.reset(fd);
         }
     } else {
         if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
@@ -315,43 +302,46 @@
 
     if (pid_ == 0) {
         // Subprocess child.
-        init_subproc_child();
+        setsid();
 
         if (type_ == SubprocessType::kPty) {
-            child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
+            child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
         }
 
-        dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
-        dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
-        dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
-             STDERR_FILENO);
+        dup2(child_stdinout_sfd, STDIN_FILENO);
+        dup2(child_stdinout_sfd, STDOUT_FILENO);
+        dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
 
         // exec doesn't trigger destructors, close the FDs manually.
-        stdinout_sfd_.Reset();
-        stderr_sfd_.Reset();
-        child_stdinout_sfd.Reset();
-        child_stderr_sfd.Reset();
-        parent_error_sfd.Reset();
-        close_on_exec(child_error_sfd.fd());
+        stdinout_sfd_.reset(-1);
+        stderr_sfd_.reset(-1);
+        child_stdinout_sfd.reset(-1);
+        child_stderr_sfd.reset(-1);
+        parent_error_sfd.reset(-1);
+        close_on_exec(child_error_sfd);
+
+        // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
+        // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
+        signal(SIGPIPE, SIG_DFL);
 
         if (command_.empty()) {
             execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
         } else {
             execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
         }
-        WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed: ");
-        WriteFdExactly(child_error_sfd.fd(), strerror(errno));
-        child_error_sfd.Reset();
+        WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
+        WriteFdExactly(child_error_sfd, strerror(errno));
+        child_error_sfd.reset(-1);
         _Exit(1);
     }
 
     // Subprocess parent.
     D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
-      stdinout_sfd_.fd(), stderr_sfd_.fd());
+      stdinout_sfd_.get(), stderr_sfd_.get());
 
     // Wait to make sure the subprocess exec'd without error.
-    child_error_sfd.Reset();
-    std::string error_message = ReadAll(parent_error_sfd.fd());
+    child_error_sfd.reset(-1);
+    std::string error_message = ReadAll(parent_error_sfd);
     if (!error_message.empty()) {
         *error = error_message;
         return false;
@@ -361,7 +351,7 @@
     if (protocol_ == SubprocessProtocol::kNone) {
         // No protocol: all streams pass through the stdinout FD and hook
         // directly into the local socket for raw data transfer.
-        local_socket_sfd_.Reset(stdinout_sfd_.Release());
+        local_socket_sfd_.reset(stdinout_sfd_.release());
     } else {
         // Shell protocol: create another socketpair to intercept data.
         if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
@@ -370,10 +360,10 @@
             kill(pid_, SIGKILL);
             return false;
         }
-        D("protocol FD = %d", protocol_sfd_.fd());
+        D("protocol FD = %d", protocol_sfd_.get());
 
-        input_.reset(new ShellProtocol(protocol_sfd_.fd()));
-        output_.reset(new ShellProtocol(protocol_sfd_.fd()));
+        input_.reset(new ShellProtocol(protocol_sfd_));
+        output_.reset(new ShellProtocol(protocol_sfd_));
         if (!input_ || !output_) {
             *error = "failed to allocate shell protocol objects";
             kill(pid_, SIGKILL);
@@ -384,7 +374,7 @@
         // likely but could happen under unusual circumstances, such as if we
         // write a ton of data to stdin but the subprocess never reads it and
         // the pipe fills up.
-        for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
+        for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
             if (fd >= 0) {
                 if (!set_file_block_mode(fd, false)) {
                     *error = android::base::StringPrintf(
@@ -412,7 +402,7 @@
     return true;
 }
 
-int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
+int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
     int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
     if (child_fd == -1) {
         // Don't use WriteFdFmt; since we're in the fork() child we don't want
@@ -420,26 +410,26 @@
         const char* messages[] = {"child failed to open pseudo-term slave ",
                                   pts_name, ": ", strerror(errno)};
         for (const char* message : messages) {
-            WriteFdExactly(error_sfd->fd(), message);
+            WriteFdExactly(*error_sfd, message);
         }
-        exit(-1);
+        abort();
     }
 
     if (make_pty_raw_) {
         termios tattr;
         if (tcgetattr(child_fd, &tattr) == -1) {
             int saved_errno = errno;
-            WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
-            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
-            exit(-1);
+            WriteFdExactly(*error_sfd, "tcgetattr failed: ");
+            WriteFdExactly(*error_sfd, strerror(saved_errno));
+            abort();
         }
 
         cfmakeraw(&tattr);
         if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
             int saved_errno = errno;
-            WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
-            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
-            exit(-1);
+            WriteFdExactly(*error_sfd, "tcsetattr failed: ");
+            WriteFdExactly(*error_sfd, strerror(saved_errno));
+            abort();
         }
     }
 
@@ -460,7 +450,7 @@
 }
 
 void Subprocess::PassDataStreams() {
-    if (!protocol_sfd_.valid()) {
+    if (protocol_sfd_ == -1) {
         return;
     }
 
@@ -468,21 +458,20 @@
     fd_set master_read_set, master_write_set;
     FD_ZERO(&master_read_set);
     FD_ZERO(&master_write_set);
-    for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
-        if (sfd->valid()) {
-            FD_SET(sfd->fd(), &master_read_set);
+    for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
+        if (*sfd != -1) {
+            FD_SET(*sfd, &master_read_set);
         }
     }
 
     // Pass data until the protocol FD or both the subprocess pipes die, at
     // which point we can't pass any more data.
-    while (protocol_sfd_.valid() &&
-            (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
-        ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
+    while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
+        unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
         if (dead_sfd) {
-            D("closing FD %d", dead_sfd->fd());
-            FD_CLR(dead_sfd->fd(), &master_read_set);
-            FD_CLR(dead_sfd->fd(), &master_write_set);
+            D("closing FD %d", dead_sfd->get());
+            FD_CLR(*dead_sfd, &master_read_set);
+            FD_CLR(*dead_sfd, &master_write_set);
             if (dead_sfd == &protocol_sfd_) {
                 // Using SIGHUP is a decent general way to indicate that the
                 // controlling process is going away. If specific signals are
@@ -494,28 +483,27 @@
                 // We also need to close the pipes connected to the child process
                 // so that if it ignores SIGHUP and continues to write data it
                 // won't fill up the pipe and block.
-                stdinout_sfd_.Reset();
-                stderr_sfd_.Reset();
+                stdinout_sfd_.reset();
+                stderr_sfd_.reset();
             }
-            dead_sfd->Reset();
+            dead_sfd->reset();
         }
     }
 }
 
 namespace {
 
-inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
-    return sfd.valid() && FD_ISSET(sfd.fd(), set);
+inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
+    return sfd != -1 && FD_ISSET(sfd, set);
 }
 
 }   // namespace
 
-ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
-                                 fd_set* master_write_set_ptr) {
+unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
+                                  fd_set* master_write_set_ptr) {
     fd_set read_set, write_set;
-    int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
-                            stderr_sfd_.fd()) + 1;
-    ScopedFd* dead_sfd = nullptr;
+    int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
+    unique_fd* dead_sfd = nullptr;
 
     // Keep calling select() and passing data until an FD closes/errors.
     while (!dead_sfd) {
@@ -526,8 +514,8 @@
                 continue;
             } else {
                 PLOG(ERROR) << "select failed, closing subprocess pipes";
-                stdinout_sfd_.Reset();
-                stderr_sfd_.Reset();
+                stdinout_sfd_.reset(-1);
+                stderr_sfd_.reset(-1);
                 return nullptr;
             }
         }
@@ -547,8 +535,8 @@
             dead_sfd = PassInput();
             // If we didn't finish writing, block on stdin write.
             if (input_bytes_left_) {
-                FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
-                FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
+                FD_CLR(protocol_sfd_, master_read_set_ptr);
+                FD_SET(stdinout_sfd_, master_write_set_ptr);
             }
         }
 
@@ -557,8 +545,8 @@
             dead_sfd = PassInput();
             // If we finished writing, go back to blocking on protocol read.
             if (!input_bytes_left_) {
-                FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
-                FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
+                FD_SET(protocol_sfd_, master_read_set_ptr);
+                FD_CLR(stdinout_sfd_, master_write_set_ptr);
             }
         }
     }  // while (!dead_sfd)
@@ -566,19 +554,18 @@
     return dead_sfd;
 }
 
-ScopedFd* Subprocess::PassInput() {
+unique_fd* Subprocess::PassInput() {
     // Only read a new packet if we've finished writing the last one.
     if (!input_bytes_left_) {
         if (!input_->Read()) {
             // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
             if (errno != 0) {
-                PLOG(ERROR) << "error reading protocol FD "
-                            << protocol_sfd_.fd();
+                PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
             }
             return &protocol_sfd_;
         }
 
-        if (stdinout_sfd_.valid()) {
+        if (stdinout_sfd_ != -1) {
             switch (input_->id()) {
                 case ShellProtocol::kIdWindowSizeChange:
                     int rows, cols, x_pixels, y_pixels;
@@ -589,7 +576,7 @@
                         ws.ws_col = cols;
                         ws.ws_xpixel = x_pixels;
                         ws.ws_ypixel = y_pixels;
-                        ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
+                        ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
                     }
                     break;
                 case ShellProtocol::kIdStdin:
@@ -597,11 +584,11 @@
                     break;
                 case ShellProtocol::kIdCloseStdin:
                     if (type_ == SubprocessType::kRaw) {
-                        if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
+                        if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
                             return nullptr;
                         }
                         PLOG(ERROR) << "failed to shutdown writes to FD "
-                                    << stdinout_sfd_.fd();
+                                    << stdinout_sfd_;
                         return &stdinout_sfd_;
                     } else {
                         // PTYs can't close just input, so rather than close the
@@ -610,7 +597,7 @@
                         // non-interactively which is rare and unsupported.
                         // If necessary, the client can manually close the shell
                         // with `exit` or by killing the adb client process.
-                        D("can't close input for PTY FD %d", stdinout_sfd_.fd());
+                        D("can't close input for PTY FD %d", stdinout_sfd_.get());
                     }
                     break;
             }
@@ -619,11 +606,10 @@
 
     if (input_bytes_left_ > 0) {
         int index = input_->data_length() - input_bytes_left_;
-        int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
-                              input_bytes_left_);
+        int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
         if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
             if (bytes < 0) {
-                PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
+                PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
             }
             // stdin is done, mark this packet as finished and we'll just start
             // dumping any further data received from the protocol FD.
@@ -637,20 +623,20 @@
     return nullptr;
 }
 
-ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
-    int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
+unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
+    int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
     if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
         // read() returns EIO if a PTY closes; don't report this as an error,
         // it just means the subprocess completed.
         if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
-            PLOG(ERROR) << "error reading output FD " << sfd->fd();
+            PLOG(ERROR) << "error reading output FD " << *sfd;
         }
         return sfd;
     }
 
     if (bytes > 0 && !output_->Write(id, bytes)) {
         if (errno != 0) {
-            PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
+            PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
         }
         return &protocol_sfd_;
     }
@@ -682,25 +668,25 @@
     }
 
     // If we have an open protocol FD send an exit packet.
-    if (protocol_sfd_.valid()) {
+    if (protocol_sfd_ != -1) {
         output_->data()[0] = exit_code;
         if (output_->Write(ShellProtocol::kIdExit, 1)) {
             D("wrote the exit code packet: %d", exit_code);
         } else {
             PLOG(ERROR) << "failed to write the exit code packet";
         }
-        protocol_sfd_.Reset();
+        protocol_sfd_.reset(-1);
     }
 
     // Pass the local socket FD to the shell cleanup fdevent.
     if (SHELL_EXIT_NOTIFY_FD >= 0) {
-        int fd = local_socket_sfd_.fd();
+        int fd = local_socket_sfd_;
         if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
             D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
               fd, SHELL_EXIT_NOTIFY_FD, pid_);
             // The shell exit fdevent now owns the FD and will close it once
             // the last bit of data flushes through.
-            local_socket_sfd_.Release();
+            static_cast<void>(local_socket_sfd_.release());
         } else {
             PLOG(ERROR) << "failed to write fd " << fd
                         << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
@@ -761,13 +747,14 @@
         return ReportError(protocol, error);
     }
 
-    int local_socket = subprocess->ReleaseLocalSocket();
-    D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket, subprocess->pid());
+    unique_fd local_socket(subprocess->ReleaseLocalSocket());
+    D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
+      subprocess->pid());
 
     if (!Subprocess::StartThread(std::move(subprocess), &error)) {
         LOG(ERROR) << "failed to start subprocess management thread: " << error;
         return ReportError(protocol, error);
     }
 
-    return local_socket;
+    return local_socket.release();
 }
diff --git a/adb/shell_service_protocol_test.cpp b/adb/shell_service_protocol_test.cpp
index a826035..b0fa3ed 100644
--- a/adb/shell_service_protocol_test.cpp
+++ b/adb/shell_service_protocol_test.cpp
@@ -86,9 +86,10 @@
 
 namespace {
 
-// Returns true if the packet contains the given values.
+// Returns true if the packet contains the given values. `data` can't be null.
 bool PacketEquals(const ShellProtocol* protocol, ShellProtocol::Id id,
                     const void* data, size_t data_length) {
+    // Note that passing memcmp null is bad, even if data_length is 0.
     return (protocol->id() == id &&
             protocol->data_length() == data_length &&
             !memcmp(data, protocol->data(), data_length));
@@ -130,7 +131,8 @@
 
     ASSERT_TRUE(write_protocol_->Write(id, 0));
     ASSERT_TRUE(read_protocol_->Read());
-    ASSERT_TRUE(PacketEquals(read_protocol_, id, nullptr, 0));
+    char buf[1];
+    ASSERT_TRUE(PacketEquals(read_protocol_, id, buf, 0));
 }
 
 // Tests exit code packets.
diff --git a/adb/socket.h b/adb/socket.h
index 9eb1b19..4acdf4a 100644
--- a/adb/socket.h
+++ b/adb/socket.h
@@ -118,7 +118,7 @@
 namespace internal {
 
 #if ADB_HOST
-char* skip_host_serial(const char* service);
+char* skip_host_serial(char* service);
 #endif
 
 }  // namespace internal
diff --git a/adb/socket_spec.cpp b/adb/socket_spec.cpp
new file mode 100644
index 0000000..14eb16b
--- /dev/null
+++ b/adb/socket_spec.cpp
@@ -0,0 +1,230 @@
+/*
+ * 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 "socket_spec.h"
+
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <android-base/parseint.h>
+#include <android-base/parsenetaddress.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <cutils/sockets.h>
+
+#include "adb.h"
+#include "sysdeps.h"
+
+using android::base::StartsWith;
+using android::base::StringPrintf;
+
+#if defined(__linux__)
+#define ADB_LINUX 1
+#else
+#define ADB_LINUX 0
+#endif
+
+#if defined(_WIN32)
+#define ADB_WINDOWS 1
+#else
+#define ADB_WINDOWS 0
+#endif
+
+// Not static because it is used in commandline.c.
+int gListenAll = 0;
+
+struct LocalSocketType {
+    int socket_namespace;
+    bool available;
+};
+
+static auto& kLocalSocketTypes = *new std::unordered_map<std::string, LocalSocketType>({
+#if ADB_HOST
+    { "local", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
+#else
+    { "local", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_WINDOWS } },
+#endif
+
+    { "localreserved", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_HOST } },
+    { "localabstract", { ANDROID_SOCKET_NAMESPACE_ABSTRACT, ADB_LINUX } },
+    { "localfilesystem", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
+});
+
+bool parse_tcp_socket_spec(const std::string& spec, std::string* hostname, int* port,
+                           std::string* error) {
+    if (!StartsWith(spec, "tcp:")) {
+        *error = StringPrintf("specification is not tcp: '%s'", spec.c_str());
+        return false;
+    }
+
+    std::string hostname_value;
+    int port_value;
+
+    // If the spec is tcp:<port>, parse it ourselves.
+    // Otherwise, delegate to android::base::ParseNetAddress.
+    if (android::base::ParseInt(&spec[4], &port_value)) {
+        // Do the range checking ourselves, because ParseInt rejects 'tcp:65536' and 'tcp:foo:1234'
+        // identically.
+        if (port_value < 0 || port_value > 65535) {
+            *error = StringPrintf("bad port number '%d'", port_value);
+            return false;
+        }
+    } else {
+        std::string addr = spec.substr(4);
+        port_value = -1;
+
+        // FIXME: ParseNetAddress rejects port 0. This currently doesn't hurt, because listening
+        //        on an address that isn't 'localhost' is unsupported.
+        if (!android::base::ParseNetAddress(addr, &hostname_value, &port_value, nullptr, error)) {
+            return false;
+        }
+
+        if (port_value == -1) {
+            *error = StringPrintf("missing port in specification: '%s'", spec.c_str());
+            return false;
+        }
+    }
+
+    if (hostname) {
+        *hostname = std::move(hostname_value);
+    }
+
+    if (port) {
+        *port = port_value;
+    }
+
+    return true;
+}
+
+static bool tcp_host_is_local(const std::string& hostname) {
+    // FIXME
+    return hostname.empty() || hostname == "localhost";
+}
+
+bool is_socket_spec(const std::string& spec) {
+    for (const auto& it : kLocalSocketTypes) {
+        std::string prefix = it.first + ":";
+        if (StartsWith(spec, prefix.c_str())) {
+            return true;
+        }
+    }
+    return StartsWith(spec, "tcp:");
+}
+
+bool is_local_socket_spec(const std::string& spec) {
+    for (const auto& it : kLocalSocketTypes) {
+        std::string prefix = it.first + ":";
+        if (StartsWith(spec, prefix.c_str())) {
+            return true;
+        }
+    }
+
+    std::string error;
+    std::string hostname;
+    if (!parse_tcp_socket_spec(spec, &hostname, nullptr, &error)) {
+        return false;
+    }
+    return tcp_host_is_local(hostname);
+}
+
+int socket_spec_connect(const std::string& spec, std::string* error) {
+    if (StartsWith(spec, "tcp:")) {
+        std::string hostname;
+        int port;
+        if (!parse_tcp_socket_spec(spec, &hostname, &port, error)) {
+            return -1;
+        }
+
+        int result;
+        if (tcp_host_is_local(hostname)) {
+            result = network_loopback_client(port, SOCK_STREAM, error);
+        } else {
+#if ADB_HOST
+            result = network_connect(hostname, port, SOCK_STREAM, 0, error);
+#else
+            // Disallow arbitrary connections in adbd.
+            *error = "adbd does not support arbitrary tcp connections";
+            return -1;
+#endif
+        }
+
+        if (result >= 0) {
+            disable_tcp_nagle(result);
+        }
+        return result;
+    }
+
+    for (const auto& it : kLocalSocketTypes) {
+        std::string prefix = it.first + ":";
+        if (StartsWith(spec, prefix.c_str())) {
+            if (!it.second.available) {
+                *error = StringPrintf("socket type %s is unavailable on this platform",
+                                      it.first.c_str());
+                return -1;
+            }
+
+            return network_local_client(&spec[prefix.length()], it.second.socket_namespace,
+                                        SOCK_STREAM, error);
+        }
+    }
+
+    *error = StringPrintf("unknown socket specification '%s'", spec.c_str());
+    return -1;
+}
+
+int socket_spec_listen(const std::string& spec, std::string* error, int* resolved_tcp_port) {
+    if (StartsWith(spec, "tcp:")) {
+        std::string hostname;
+        int port;
+        if (!parse_tcp_socket_spec(spec, &hostname, &port, error)) {
+            return -1;
+        }
+
+        int result;
+        if (hostname.empty() && gListenAll) {
+            result = network_inaddr_any_server(port, SOCK_STREAM, error);
+        } else if (tcp_host_is_local(hostname)) {
+            result = network_loopback_server(port, SOCK_STREAM, error);
+        } else {
+            // TODO: Implement me.
+            *error = "listening on specified hostname currently unsupported";
+            return -1;
+        }
+
+        if (result >= 0 && port == 0 && resolved_tcp_port) {
+            *resolved_tcp_port = adb_socket_get_local_port(result);
+        }
+        return result;
+    }
+
+    for (const auto& it : kLocalSocketTypes) {
+        std::string prefix = it.first + ":";
+        if (StartsWith(spec, prefix.c_str())) {
+            if (!it.second.available) {
+                *error = StringPrintf("attempted to listen on unavailable socket type: '%s'",
+                                      spec.c_str());
+                return -1;
+            }
+
+            return network_local_server(&spec[prefix.length()], it.second.socket_namespace,
+                                        SOCK_STREAM, error);
+        }
+    }
+
+    *error = StringPrintf("unknown socket specification '%s'", spec.c_str());
+    return -1;
+}
diff --git a/adb/socket_spec.h b/adb/socket_spec.h
new file mode 100644
index 0000000..6920e91
--- /dev/null
+++ b/adb/socket_spec.h
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <string>
+
+// Returns true if the argument starts with a plausible socket prefix.
+bool is_socket_spec(const std::string& spec);
+bool is_local_socket_spec(const std::string& spec);
+
+int socket_spec_connect(const std::string& spec, std::string* error);
+int socket_spec_listen(const std::string& spec, std::string* error,
+                       int* resolved_tcp_port = nullptr);
+
+// Exposed for testing.
+bool parse_tcp_socket_spec(const std::string& spec, std::string* hostname, int* port,
+                           std::string* error);
diff --git a/adb/socket_spec_test.cpp b/adb/socket_spec_test.cpp
new file mode 100644
index 0000000..40ce21c
--- /dev/null
+++ b/adb/socket_spec_test.cpp
@@ -0,0 +1,54 @@
+/*
+ * 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 "socket_spec.h"
+
+#include <string>
+
+#include <gtest/gtest.h>
+
+TEST(socket_spec, parse_tcp_socket_spec) {
+    std::string hostname, error;
+    int port;
+    EXPECT_TRUE(parse_tcp_socket_spec("tcp:5037", &hostname, &port, &error));
+    EXPECT_EQ("", hostname);
+    EXPECT_EQ(5037, port);
+
+    // Bad ports:
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:-1", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:65536", &hostname, &port, &error));
+
+    EXPECT_TRUE(parse_tcp_socket_spec("tcp:localhost:1234", &hostname, &port, &error));
+    EXPECT_EQ("localhost", hostname);
+    EXPECT_EQ(1234, port);
+
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:localhost", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:localhost:", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:localhost:-1", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:localhost:65536", &hostname, &port, &error));
+
+    // IPv6:
+    EXPECT_TRUE(parse_tcp_socket_spec("tcp:[::1]:1234", &hostname, &port, &error));
+    EXPECT_EQ("::1", hostname);
+    EXPECT_EQ(1234, port);
+
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:[::1]", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:[::1]:", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:[::1]:-1", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:::1", &hostname, &port, &error));
+    EXPECT_FALSE(parse_tcp_socket_spec("tcp:::1:1234", &hostname, &port, &error));
+}
diff --git a/adb/socket_test.cpp b/adb/socket_test.cpp
index 5cbef6d..f56f7f7 100644
--- a/adb/socket_test.cpp
+++ b/adb/socket_test.cpp
@@ -22,6 +22,7 @@
 #include <limits>
 #include <queue>
 #include <string>
+#include <thread>
 #include <vector>
 
 #include <unistd.h>
@@ -31,6 +32,7 @@
 #include "fdevent_test.h"
 #include "socket.h"
 #include "sysdeps.h"
+#include "sysdeps/chrono.h"
 
 struct ThreadArg {
     int first_read_fd;
@@ -44,6 +46,8 @@
     fdevent_loop();
 }
 
+constexpr auto SLEEP_FOR_FDEVENT = 100ms;
+
 TEST_F(LocalSocketTest, smoke) {
     // Join two socketpairs with a chain of intermediate socketpairs.
     int first[2];
@@ -99,7 +103,8 @@
     ASSERT_EQ(0, adb_close(last[1]));
 
     // Wait until the local sockets are closed.
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
     TerminateThread(thread);
 }
 
@@ -151,12 +156,13 @@
     ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseWithPacketThreadFunc),
                                   &arg, &thread));
     // Wait until the fdevent_loop() starts.
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     ASSERT_EQ(0, adb_close(cause_close_fd[0]));
-    adb_sleep_ms(100);
-    EXPECT_EQ(2u, fdevent_installed_count());
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
     ASSERT_EQ(0, adb_close(socket_fd[0]));
-
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
     TerminateThread(thread);
 }
 
@@ -175,10 +181,10 @@
     ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseWithPacketThreadFunc),
                                   &arg, &thread));
     // Wait until the fdevent_loop() starts.
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     ASSERT_EQ(0, adb_close(cause_close_fd[0]));
-    adb_sleep_ms(100);
-    EXPECT_EQ(2u, fdevent_installed_count());
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
 
     // Verify if we can read successfully.
     std::vector<char> buf(arg.bytes_written);
@@ -186,6 +192,8 @@
     ASSERT_EQ(true, ReadFdExactly(socket_fd[0], buf.data(), buf.size()));
     ASSERT_EQ(0, adb_close(socket_fd[0]));
 
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
     TerminateThread(thread);
 }
 
@@ -208,10 +216,12 @@
                                   &arg, &thread));
 
     // Wait until the fdevent_loop() starts.
-    adb_sleep_ms(100);
-    EXPECT_EQ(3u, fdevent_installed_count());
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    EXPECT_EQ(2u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
     ASSERT_EQ(0, adb_close(socket_fd[0]));
 
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
     TerminateThread(thread);
 }
 
@@ -221,7 +231,7 @@
     std::string error;
     int fd = network_loopback_client(5038, SOCK_STREAM, &error);
     ASSERT_GE(fd, 0) << error;
-    adb_sleep_ms(200);
+    std::this_thread::sleep_for(200ms);
     ASSERT_EQ(0, adb_close(fd));
 }
 
@@ -246,10 +256,7 @@
     ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(ClientThreadFunc), nullptr,
                                   &client_thread));
 
-    struct sockaddr addr;
-    socklen_t alen;
-    alen = sizeof(addr);
-    int accept_fd = adb_socket_accept(listen_fd, &addr, &alen);
+    int accept_fd = adb_socket_accept(listen_fd, nullptr, nullptr);
     ASSERT_GE(accept_fd, 0);
     CloseRdHupSocketArg arg;
     arg.socket_fd = accept_fd;
@@ -260,12 +267,14 @@
                                   &arg, &thread));
 
     // Wait until the fdevent_loop() starts.
-    adb_sleep_ms(100);
-    EXPECT_EQ(2u, fdevent_installed_count());
+    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));
 
+    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
+    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
     TerminateThread(thread);
 }
 
@@ -275,8 +284,8 @@
 
 // Checks that skip_host_serial(serial) returns a pointer to the part of |serial| which matches
 // |expected|, otherwise logs the failure to gtest.
-void VerifySkipHostSerial(const std::string& serial, const char* expected) {
-    const char* result = internal::skip_host_serial(serial.c_str());
+void VerifySkipHostSerial(std::string serial, const char* expected) {
+    char* result = internal::skip_host_serial(&serial[0]);
     if (expected == nullptr) {
         EXPECT_EQ(nullptr, result);
     } else {
@@ -300,6 +309,17 @@
         // Don't register a port unless it's all numbers and ends with ':'.
         VerifySkipHostSerial(protocol + "foo:123", ":123");
         VerifySkipHostSerial(protocol + "foo:123bar:baz", ":123bar:baz");
+
+        VerifySkipHostSerial(protocol + "100.100.100.100:5555:foo", ":foo");
+        VerifySkipHostSerial(protocol + "[0123:4567:89ab:CDEF:0:9:a:f]:5555:foo", ":foo");
+        VerifySkipHostSerial(protocol + "[::1]:5555:foo", ":foo");
+
+        // If we can't find both [] then treat it as a normal serial with [ in it.
+        VerifySkipHostSerial(protocol + "[0123:foo", ":foo");
+
+        // Don't be fooled by random IPv6 addresses in the command string.
+        VerifySkipHostSerial(protocol + "foo:ping [0123:4567:89ab:CDEF:0:9:a:f]:5555",
+                             ":ping [0123:4567:89ab:CDEF:0:9:a:f]:5555");
     }
 }
 
diff --git a/adb/sockets.cpp b/adb/sockets.cpp
index 63b7df6..59a48f5 100644
--- a/adb/sockets.cpp
+++ b/adb/sockets.cpp
@@ -31,12 +31,12 @@
 #include <vector>
 
 #if !ADB_HOST
-#include "cutils/properties.h"
+#include <android-base/properties.h>
+#include <log/log_properties.h>
 #endif
 
 #include "adb.h"
 #include "adb_io.h"
-#include "sysdeps/mutex.h"
 #include "transport.h"
 
 static std::recursive_mutex& local_socket_list_lock = *new std::recursive_mutex();
@@ -123,7 +123,7 @@
 }
 
 static int local_socket_enqueue(asocket* s, apacket* p) {
-    D("LS(%d): enqueue %d", s->id, p->len);
+    D("LS(%d): enqueue %zu", s->id, p->len);
 
     p->ptr = p->data;
 
@@ -196,7 +196,7 @@
 
     /* dispose of any unwritten data */
     for (p = s->pkt_first; p; p = n) {
-        D("LS(%d): discarding %d bytes", s->id, p->len);
+        D("LS(%d): discarding %zu bytes", s->id, p->len);
         n = p->next;
         put_apacket(p);
     }
@@ -306,7 +306,7 @@
 
     if (ev & FDE_READ) {
         apacket* p = get_apacket();
-        unsigned char* x = p->data;
+        char* x = p->data;
         const size_t max_payload = s->get_max_payload();
         size_t avail = max_payload;
         int r = 0;
@@ -410,19 +410,14 @@
 #endif
     int fd = service_to_fd(name, transport);
     if (fd < 0) {
-        return 0;
+        return nullptr;
     }
 
     asocket* s = create_local_socket(fd);
     D("LS(%d): bound to '%s' via %d", s->id, name, fd);
 
 #if !ADB_HOST
-    char debug[PROPERTY_VALUE_MAX];
-    if (!strncmp(name, "root:", 5)) {
-        property_get("ro.debuggable", debug, "");
-    }
-
-    if ((!strncmp(name, "root:", 5) && getuid() != 0 && strcmp(debug, "1") == 0) ||
+    if ((!strncmp(name, "root:", 5) && getuid() != 0 && __android_log_is_debuggable()) ||
         (!strncmp(name, "unroot:", 7) && getuid() == 0) ||
         !strncmp(name, "usb:", 4) ||
         !strncmp(name, "tcpip:", 6)) {
@@ -554,7 +549,7 @@
     s->close(s);
 }
 
-static unsigned unhex(unsigned char* s, int len) {
+static unsigned unhex(char* s, int len) {
     unsigned n = 0, c;
 
     while (len-- > 0) {
@@ -608,7 +603,7 @@
 // Where <port> must be a base-10 number and <prefix> may be any of {usb,product,model,device}.
 //
 // The returned pointer will point to the ':' just before <command>, or nullptr if not found.
-char* skip_host_serial(const char* service) {
+char* skip_host_serial(char* service) {
     static const std::vector<std::string>& prefixes =
         *(new std::vector<std::string>{"usb:", "product:", "model:", "device:"});
 
@@ -623,21 +618,32 @@
         service += 4;
     }
 
-    char* first_colon = strchr(service, ':');
-    if (!first_colon) {
+    // Check for an IPv6 address. `adb connect` creates the serial number from the canonical
+    // network address so it will always have the [] delimiters.
+    if (service[0] == '[') {
+        char* ipv6_end = strchr(service, ']');
+        if (ipv6_end != nullptr) {
+            service = ipv6_end;
+        }
+    }
+
+    // The next colon we find must either begin the port field or the command field.
+    char* colon_ptr = strchr(service, ':');
+    if (!colon_ptr) {
         // No colon in service string.
         return nullptr;
     }
 
-    char* serial_end = first_colon;
+    // If the next field is only decimal digits and ends with another colon, it's a port.
+    char* serial_end = colon_ptr;
     if (isdigit(serial_end[1])) {
         serial_end++;
         while (*serial_end && isdigit(*serial_end)) {
             serial_end++;
         }
         if (*serial_end != ':') {
-            // Something other than numbers was found, reset the end.
-            serial_end = first_colon;
+            // Something other than "<port>:" was found, this must be the command field instead.
+            serial_end = colon_ptr;
         }
     }
     return serial_end;
@@ -655,7 +661,7 @@
     TransportType type = kTransportAny;
 #endif
 
-    D("SS(%d): enqueue %d", s->id, p->len);
+    D("SS(%d): enqueue %zu", s->id, p->len);
 
     if (s->pkt_first == 0) {
         s->pkt_first = p;
@@ -688,7 +694,7 @@
     D("SS(%d): len is %d", s->id, len);
     /* can't do anything until we have the full header */
     if ((len + 4) > p->len) {
-        D("SS(%d): waiting for %d more bytes", s->id, len + 4 - p->len);
+        D("SS(%d): waiting for %zu more bytes", s->id, len + 4 - p->len);
         return 0;
     }
 
@@ -785,11 +791,14 @@
     }
 #endif
 
-    if (!(s->transport) || (s->transport->connection_state == kCsOffline)) {
+    if (!s->transport) {
+        SendFail(s->peer->fd, "device offline (no transport)");
+        goto fail;
+    } else if (s->transport->connection_state == kCsOffline) {
         /* if there's no remote we fail the connection
          ** right here and terminate it
          */
-        SendFail(s->peer->fd, "device offline (x)");
+        SendFail(s->peer->fd, "device offline (transport offline)");
         goto fail;
     }
 
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index bd19f88..f195b4e 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -34,6 +34,7 @@
 #include <android-base/unique_fd.h>
 #include <android-base/utf8.h>
 
+#include "sysdeps/errno.h"
 #include "sysdeps/stat.h"
 
 /*
@@ -97,27 +98,6 @@
     return c == '\\' || c == '/';
 }
 
-typedef CRITICAL_SECTION          adb_mutex_t;
-
-#define  ADB_MUTEX_DEFINE(x)     adb_mutex_t   x
-
-/* declare all mutexes */
-/* For win32, adb_sysdeps_init() will do the mutex runtime initialization. */
-#define  ADB_MUTEX(x)   extern adb_mutex_t  x;
-#include "mutex_list.h"
-
-extern void  adb_sysdeps_init(void);
-
-static __inline__ void adb_mutex_lock( adb_mutex_t*  lock )
-{
-    EnterCriticalSection( lock );
-}
-
-static __inline__ void  adb_mutex_unlock( adb_mutex_t*  lock )
-{
-    LeaveCriticalSection( lock );
-}
-
 typedef void (*adb_thread_func_t)(void* arg);
 typedef HANDLE adb_thread_t;
 
@@ -201,8 +181,6 @@
     /* nothing really */
 }
 
-#define  S_ISLNK(m)   0   /* no symlinks on Win32 */
-
 extern int  adb_unlink(const char*  path);
 #undef  unlink
 #define unlink  ___xxx_unlink
@@ -219,6 +197,7 @@
 extern int  adb_lseek(int  fd, int  pos, int  where);
 extern int  adb_shutdown(int  fd);
 extern int  adb_close(int  fd);
+extern int  adb_register_socket(SOCKET s);
 
 // See the comments for the !defined(_WIN32) version of unix_close().
 static __inline__ int  unix_close(int fd)
@@ -269,17 +248,18 @@
 int unix_isatty(int fd);
 #define  isatty  ___xxx_isatty
 
-/* normally provided by <cutils/misc.h> */
-extern void*  load_file(const char*  pathname, unsigned*  psize);
-
-static __inline__ void  adb_sleep_ms( int  mseconds )
-{
-    Sleep( mseconds );
-}
-
 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) {
+    abort();
+}
+
+inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
+    abort();
+}
+
 int network_connect(const std::string& host, int port, int type, int timeout,
                     std::string* error);
 
@@ -288,6 +268,13 @@
 #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);
+
 extern int  adb_setsockopt(int  fd, int  level, int  optname, const void*  optval, socklen_t  optlen);
 
 #undef   setsockopt
@@ -376,9 +363,6 @@
 
 #define getcwd adb_getcwd
 
-char* adb_strerror(int err);
-#define strerror adb_strerror
-
 // Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
 // passed to main().
 class NarrowArgs {
@@ -434,7 +418,6 @@
 
 #else /* !_WIN32 a.k.a. Unix */
 
-#include <cutils/misc.h>
 #include <cutils/sockets.h>
 #include <cutils/threads.h>
 #include <fcntl.h>
@@ -464,27 +447,6 @@
     return c == '/';
 }
 
-typedef  pthread_mutex_t          adb_mutex_t;
-
-#define  ADB_MUTEX_INITIALIZER    PTHREAD_MUTEX_INITIALIZER
-#define  adb_mutex_init           pthread_mutex_init
-#define  adb_mutex_lock           pthread_mutex_lock
-#define  adb_mutex_unlock         pthread_mutex_unlock
-#define  adb_mutex_destroy        pthread_mutex_destroy
-
-#define  ADB_MUTEX_DEFINE(m)      adb_mutex_t   m = PTHREAD_MUTEX_INITIALIZER
-
-#define  adb_cond_t               pthread_cond_t
-#define  adb_cond_init            pthread_cond_init
-#define  adb_cond_wait            pthread_cond_wait
-#define  adb_cond_broadcast       pthread_cond_broadcast
-#define  adb_cond_signal          pthread_cond_signal
-#define  adb_cond_destroy         pthread_cond_destroy
-
-/* declare all mutexes */
-#define  ADB_MUTEX(x)   extern adb_mutex_t  x;
-#include "mutex_list.h"
-
 static __inline__ void  close_on_exec(int  fd)
 {
     fcntl( fd, F_SETFD, FD_CLOEXEC );
@@ -562,6 +524,12 @@
 #undef   close
 #define  close   ____xxx_close
 
+// On Windows, ADB has an indirection layer for file descriptors. If we get a
+// Win32 SOCKET object from an external library, we have to map it in to that
+// indirection layer, which this does.
+__inline__ int  adb_register_socket(int s) {
+    return s;
+}
 
 static __inline__  int  adb_read(int  fd, void*  buf, size_t  len)
 {
@@ -624,21 +592,26 @@
 }
 
 inline int network_loopback_client(int port, int type, std::string* error) {
-  return _fd_set_error_str(socket_loopback_client(port, type), 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) {
-  return _fd_set_error_str(socket_loopback_server(port, type), 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);
 }
 
-inline int network_local_server(const char *name, int namespace_id, int type,
-                                std::string* error) {
-  return _fd_set_error_str(socket_local_server(name, namespace_id, type),
-                           error);
+inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
+    return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
+}
+
+inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
+    return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
 }
 
 inline int network_connect(const std::string& host, int port, int type,
@@ -671,6 +644,10 @@
 #undef   accept
 #define  accept  ___xxx_accept
 
+inline int adb_socket_get_local_port(int fd) {
+    return socket_get_local_port(fd);
+}
+
 // Operate on a file descriptor returned from unix_open() or a well-known file
 // descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
 //
@@ -787,11 +764,6 @@
 
 #define poll ___xxx_poll
 
-static __inline__ void  adb_sleep_ms( int  mseconds )
-{
-    usleep( mseconds*1000 );
-}
-
 static __inline__ int  adb_mkdir(const std::string& path, int mode)
 {
     return mkdir(path.c_str(), mode);
@@ -800,10 +772,6 @@
 #undef   mkdir
 #define  mkdir  ___xxx_mkdir
 
-static __inline__ void  adb_sysdeps_init(void)
-{
-}
-
 static __inline__ int adb_is_absolute_host_path(const char* path) {
     return path[0] == '/';
 }
@@ -825,4 +793,9 @@
 // configured to drop after 10 missed keepalives. Returns true on success.
 bool set_tcp_keepalive(int fd, int interval_sec);
 
+#if defined(_WIN32)
+// Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
+#undef ERROR
+#endif
+
 #endif /* _ADB_SYSDEPS_H */
diff --git a/adb/sysdeps/chrono.h b/adb/sysdeps/chrono.h
new file mode 100644
index 0000000..c73a638
--- /dev/null
+++ b/adb/sysdeps/chrono.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <chrono>
+
+#if defined(_WIN32)
+// We don't have C++14 on Windows yet.
+// Reimplement std::chrono_literals ourselves until we do.
+
+// Silence the following warning (which gets promoted to an error):
+// error: literal operator suffixes not preceded by ‘_’ are reserved for future standardization
+#pragma GCC system_header
+
+constexpr std::chrono::seconds operator"" s(unsigned long long s) {
+    return std::chrono::seconds(s);
+}
+
+constexpr std::chrono::duration<long double> operator"" s(long double s) {
+    return std::chrono::duration<long double>(s);
+}
+
+constexpr std::chrono::milliseconds operator"" ms(unsigned long long ms) {
+    return std::chrono::milliseconds(ms);
+}
+
+constexpr std::chrono::duration<long double, std::milli> operator"" ms(long double ms) {
+    return std::chrono::duration<long double, std::milli>(ms);
+}
+#else
+using namespace std::chrono_literals;
+#endif
diff --git a/adb/sysdeps/errno.cpp b/adb/sysdeps/errno.cpp
new file mode 100644
index 0000000..6869947
--- /dev/null
+++ b/adb/sysdeps/errno.cpp
@@ -0,0 +1,100 @@
+/*
+ * 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 "sysdeps/errno.h"
+
+#include <errno.h>
+
+#include <thread>
+#include <unordered_map>
+#include <utility>
+
+#include "adb.h"
+
+#if defined(_WIN32)
+#define ETXTBSY EBUSY
+#endif
+
+// Use the linux asm-generic values for errno (which are used on all android archs but mips).
+#define ERRNO_VALUES()             \
+    ERRNO_VALUE(EACCES, 13);       \
+    ERRNO_VALUE(EEXIST, 17);       \
+    ERRNO_VALUE(EFAULT, 14);       \
+    ERRNO_VALUE(EFBIG, 27);        \
+    ERRNO_VALUE(EINTR, 4);         \
+    ERRNO_VALUE(EINVAL, 22);       \
+    ERRNO_VALUE(EIO, 5);           \
+    ERRNO_VALUE(EISDIR, 21);       \
+    ERRNO_VALUE(ELOOP, 40);        \
+    ERRNO_VALUE(EMFILE, 24);       \
+    ERRNO_VALUE(ENAMETOOLONG, 36); \
+    ERRNO_VALUE(ENFILE, 23);       \
+    ERRNO_VALUE(ENOENT, 2);        \
+    ERRNO_VALUE(ENOMEM, 12);       \
+    ERRNO_VALUE(ENOSPC, 28);       \
+    ERRNO_VALUE(ENOTDIR, 20);      \
+    ERRNO_VALUE(EOVERFLOW, 75);    \
+    ERRNO_VALUE(EPERM, 1);         \
+    ERRNO_VALUE(EROFS, 30);        \
+    ERRNO_VALUE(ETXTBSY, 26)
+
+// Make sure these values are actually correct.
+#if defined(__linux__) && !defined(__mips__)
+#define ERRNO_VALUE(error_name, wire_value) static_assert((error_name) == (wire_value), "")
+ERRNO_VALUES();
+#undef ERRNO_VALUE
+#endif
+
+static std::unordered_map<int, int>* generate_host_to_wire() {
+    auto result = new std::unordered_map<int, int>();
+#define ERRNO_VALUE(error_name, wire_value) \
+    result->insert(std::make_pair((error_name), (wire_value)))
+    ERRNO_VALUES();
+#undef ERRNO_VALUE
+    return result;
+}
+
+static std::unordered_map<int, int>* generate_wire_to_host() {
+    auto result = new std::unordered_map<int, int>();
+#define ERRNO_VALUE(error_name, wire_value) \
+    result->insert(std::make_pair((wire_value), (error_name)))
+    ERRNO_VALUES();
+#undef ERRNO_VALUE
+    return result;
+}
+
+static std::unordered_map<int, int>& host_to_wire = *generate_host_to_wire();
+static std::unordered_map<int, int>& wire_to_host = *generate_wire_to_host();
+
+int errno_to_wire(int error) {
+    auto it = host_to_wire.find(error);
+    if (it == host_to_wire.end()) {
+        LOG(ERROR) << "failed to convert errno " << error << " (" << strerror(error) << ") to wire";
+
+        // Return EIO;
+        return 5;
+    }
+    return it->second;
+}
+
+int errno_from_wire(int error) {
+    auto it = host_to_wire.find(error);
+    if (it == host_to_wire.end()) {
+        LOG(ERROR) << "failed to convert errno " << error << " from wire";
+        return EIO;
+    }
+    return it->second;
+}
diff --git a/adb/sysdeps/errno.h b/adb/sysdeps/errno.h
new file mode 100644
index 0000000..72816b1
--- /dev/null
+++ b/adb/sysdeps/errno.h
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <errno.h>
+#include <string.h>
+
+#if defined(_WIN32)
+char* adb_strerror(int err);
+#define strerror adb_strerror
+#endif
+
+// errno values differ between operating systems and between Linux architectures.
+// Arbitrarily select the Linux asm-generic values to use in the wire protocol.
+int errno_to_wire(int error);
+int errno_from_wire(int error);
diff --git a/adb/sysdeps/mutex.h b/adb/sysdeps/mutex.h
deleted file mode 100644
index 73c9e6e..0000000
--- a/adb/sysdeps/mutex.h
+++ /dev/null
@@ -1,107 +0,0 @@
-#pragma once
-
-/*
- * 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.
- */
-
-#if defined(_WIN32)
-
-#include <windows.h>
-
-#include <android-base/macros.h>
-
-#include "adb.h"
-
-// The prebuilt version of mingw we use doesn't support mutex or recursive_mutex.
-// Therefore, implement our own using the Windows primitives.
-// Put them directly into the std namespace, so that when they're actually available, the build
-// breaks until they're removed.
-
-#include <mutex>
-namespace std {
-
-// CRITICAL_SECTION is recursive, so just wrap it in a Mutex-compatible class.
-class recursive_mutex {
-  public:
-    recursive_mutex() {
-        InitializeCriticalSection(&mutex_);
-    }
-
-    ~recursive_mutex() {
-        DeleteCriticalSection(&mutex_);
-    }
-
-    void lock() {
-        EnterCriticalSection(&mutex_);
-    }
-
-    bool try_lock() {
-        return TryEnterCriticalSection(&mutex_);
-    }
-
-    void unlock() {
-        LeaveCriticalSection(&mutex_);
-    }
-
-  private:
-    CRITICAL_SECTION mutex_;
-
-    DISALLOW_COPY_AND_ASSIGN(recursive_mutex);
-};
-
-class mutex {
-  public:
-    mutex() {
-    }
-
-    ~mutex() {
-    }
-
-    void lock() {
-        mutex_.lock();
-        if (++lock_count_ != 1) {
-            fatal("non-recursive mutex locked reentrantly");
-        }
-    }
-
-    void unlock() {
-        if (--lock_count_ != 0) {
-            fatal("non-recursive mutex unlock resulted in unexpected lock count: %d", lock_count_);
-        }
-        mutex_.unlock();
-    }
-
-    bool try_lock() {
-        if (!mutex_.try_lock()) {
-            return false;
-        }
-
-        if (lock_count_ != 0) {
-            mutex_.unlock();
-            return false;
-        }
-
-        ++lock_count_;
-        return true;
-    }
-
-  private:
-    recursive_mutex mutex_;
-    size_t lock_count_ = 0;
-};
-
-}
-
-#endif
diff --git a/adb/sysdeps/stat.h b/adb/sysdeps/stat.h
index 5953595..ed2cf25 100644
--- a/adb/sysdeps/stat.h
+++ b/adb/sysdeps/stat.h
@@ -43,4 +43,21 @@
 // Windows doesn't have lstat.
 #define lstat adb_stat
 
+// mingw doesn't define S_IFLNK or S_ISLNK.
+#define S_IFLNK 0120000
+#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
+
+// mingw defines S_IFBLK to a different value from bionic.
+#undef S_IFBLK
+#define S_IFBLK 0060000
+#undef S_ISBLK
+#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
 #endif
+
+// Make sure that host file mode values match the ones on the device.
+static_assert(S_IFMT == 00170000, "");
+static_assert(S_IFLNK == 0120000, "");
+static_assert(S_IFREG == 0100000, "");
+static_assert(S_IFBLK == 0060000, "");
+static_assert(S_IFDIR == 0040000, "");
+static_assert(S_IFCHR == 0020000, "");
diff --git a/adb/sysdeps/win32/errno.cpp b/adb/sysdeps/win32/errno.cpp
new file mode 100644
index 0000000..a3b9d9b
--- /dev/null
+++ b/adb/sysdeps/win32/errno.cpp
@@ -0,0 +1,95 @@
+/*
+ * 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 "sysdeps/errno.h"
+
+#include <windows.h>
+
+#include <string>
+
+// Overrides strerror() to handle error codes not supported by the Windows C
+// Runtime (MSVCRT.DLL).
+char* adb_strerror(int err) {
+// sysdeps.h defines strerror to adb_strerror, but in this function, we
+// want to call the real C Runtime strerror().
+#pragma push_macro("strerror")
+#undef strerror
+    const int saved_err = errno;  // Save because we overwrite it later.
+
+    // Lookup the string for an unknown error.
+    char* errmsg = strerror(-1);
+    const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
+
+    // Lookup the string for this error to see if the C Runtime has it.
+    errmsg = strerror(err);
+    if (errmsg != nullptr && unknown_error != errmsg) {
+        // The CRT returned an error message and it is different than the error
+        // message for an unknown error, so it is probably valid, so use it.
+    } else {
+        // Check if we have a string for this error code.
+        const char* custom_msg = nullptr;
+        switch (err) {
+#pragma push_macro("ERR")
+#undef ERR
+#define ERR(errnum, desc) case errnum: custom_msg = desc; break
+            // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
+            // Note that these cannot be longer than 94 characters because we
+            // pass this to _strerror() which has that requirement.
+            ERR(ECONNRESET,    "Connection reset by peer");
+            ERR(EHOSTUNREACH,  "No route to host");
+            ERR(ENETDOWN,      "Network is down");
+            ERR(ENETRESET,     "Network dropped connection because of reset");
+            ERR(ENOBUFS,       "No buffer space available");
+            ERR(ENOPROTOOPT,   "Protocol not available");
+            ERR(ENOTCONN,      "Transport endpoint is not connected");
+            ERR(ENOTSOCK,      "Socket operation on non-socket");
+            ERR(EOPNOTSUPP,    "Operation not supported on transport endpoint");
+#pragma pop_macro("ERR")
+        }
+
+        if (custom_msg != nullptr) {
+            // Use _strerror() to write our string into the writable per-thread
+            // buffer used by strerror()/_strerror(). _strerror() appends the
+            // msg for the current value of errno, so set errno to a consistent
+            // value for every call so that our code-path is always the same.
+            errno = 0;
+            errmsg = _strerror(custom_msg);
+            const size_t custom_msg_len = strlen(custom_msg);
+            // Just in case _strerror() returned a read-only string, check if
+            // the returned string starts with our custom message because that
+            // implies that the string is not read-only.
+            if ((errmsg != nullptr) && !strncmp(custom_msg, errmsg, custom_msg_len)) {
+                // _strerror() puts other text after our custom message, so
+                // remove that by terminating after our message.
+                errmsg[custom_msg_len] = '\0';
+            } else {
+                // For some reason nullptr was returned or a pointer to a
+                // read-only string was returned, so fallback to whatever
+                // strerror() can muster (probably "Unknown error" or some
+                // generic CRT error string).
+                errmsg = strerror(err);
+            }
+        } else {
+            // We don't have a custom message, so use whatever strerror(err)
+            // returned earlier.
+        }
+    }
+
+    errno = saved_err;  // restore
+
+    return errmsg;
+#pragma pop_macro("strerror")
+}
diff --git a/adb/sysdeps/win32/errno_test.cpp b/adb/sysdeps/win32/errno_test.cpp
new file mode 100644
index 0000000..09ec52c
--- /dev/null
+++ b/adb/sysdeps/win32/errno_test.cpp
@@ -0,0 +1,51 @@
+/*
+ * 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 "sysdeps/errno.h"
+
+#include <string>
+
+#include <gtest/gtest.h>
+
+void TestAdbStrError(int err, const char* expected) {
+    errno = 12345;
+    const char* result = adb_strerror(err);
+    // Check that errno is not overwritten.
+    EXPECT_EQ(12345, errno);
+    EXPECT_STREQ(expected, result);
+}
+
+TEST(sysdeps_win32, adb_strerror) {
+    // Test an error code that should not have a mapped string. Use an error
+    // code that is not used by the internal implementation of adb_strerror().
+    TestAdbStrError(-2, "Unknown error");
+    // adb_strerror() uses -1 internally, so test that it can still be passed
+    // as a parameter.
+    TestAdbStrError(-1, "Unknown error");
+    // Test very big, positive unknown error.
+    TestAdbStrError(1000000, "Unknown error");
+
+    // Test success case.
+    // Wine returns "Success" for strerror(0), Windows returns "No error", so accept both.
+    std::string success = adb_strerror(0);
+    EXPECT_TRUE(success == "Success" || success == "No error") << "strerror(0) = " << success;
+
+    // Test error that regular strerror() should have a string for.
+    TestAdbStrError(EPERM, "Operation not permitted");
+    // Test error that regular strerror() doesn't have a string for, but that
+    // adb_strerror() returns.
+    TestAdbStrError(ECONNRESET, "Connection reset by peer");
+}
diff --git a/adb/sysdeps_test.cpp b/adb/sysdeps_test.cpp
index 5ac8f82..9007e75 100644
--- a/adb/sysdeps_test.cpp
+++ b/adb/sysdeps_test.cpp
@@ -16,13 +16,17 @@
 
 #include <gtest/gtest.h>
 #include <unistd.h>
+
 #include <atomic>
+#include <condition_variable>
+#include <thread>
 
 #include "adb_io.h"
 #include "sysdeps.h"
+#include "sysdeps/chrono.h"
 
 static void increment_atomic_int(void* c) {
-    sleep(1);
+    std::this_thread::sleep_for(1s);
     reinterpret_cast<std::atomic<int>*>(c)->fetch_add(1);
 }
 
@@ -33,7 +37,7 @@
         ASSERT_TRUE(adb_thread_create(increment_atomic_int, &counter));
     }
 
-    sleep(2);
+    std::this_thread::sleep_for(2s);
     ASSERT_EQ(100, counter.load());
 }
 
@@ -218,7 +222,7 @@
 
 TEST_F(sysdeps_poll, fd_count) {
     // https://code.google.com/p/android/issues/detail?id=12141
-    static constexpr int num_sockets = 512;
+    static constexpr int num_sockets = 256;
     std::vector<int> sockets;
     std::vector<adb_pollfd> pfds;
     sockets.resize(num_sockets * 2);
@@ -245,7 +249,6 @@
     }
 }
 
-#include "sysdeps/mutex.h"
 TEST(sysdeps_mutex, mutex_smoke) {
     static std::atomic<bool> finished(false);
     static std::mutex &m = *new std::mutex();
@@ -255,31 +258,20 @@
         ASSERT_FALSE(m.try_lock());
         m.lock();
         finished.store(true);
-        adb_sleep_ms(200);
+        std::this_thread::sleep_for(200ms);
         m.unlock();
     }, nullptr);
 
     ASSERT_FALSE(finished.load());
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(100ms);
     ASSERT_FALSE(finished.load());
     m.unlock();
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(100ms);
     m.lock();
     ASSERT_TRUE(finished.load());
     m.unlock();
 }
 
-// Our implementation on Windows aborts on double lock.
-#if defined(_WIN32)
-TEST(sysdeps_mutex, mutex_reentrant_lock) {
-    std::mutex &m = *new std::mutex();
-
-    m.lock();
-    ASSERT_FALSE(m.try_lock());
-    EXPECT_DEATH(m.lock(), "non-recursive mutex locked reentrantly");
-}
-#endif
-
 TEST(sysdeps_mutex, recursive_mutex_smoke) {
     static std::recursive_mutex &m = *new std::recursive_mutex();
 
@@ -290,14 +282,32 @@
     adb_thread_create([](void*) {
         ASSERT_FALSE(m.try_lock());
         m.lock();
-        adb_sleep_ms(500);
+        std::this_thread::sleep_for(500ms);
         m.unlock();
     }, nullptr);
 
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(100ms);
     m.unlock();
-    adb_sleep_ms(100);
+    std::this_thread::sleep_for(100ms);
     ASSERT_FALSE(m.try_lock());
     m.lock();
     m.unlock();
 }
+
+TEST(sysdeps_condition_variable, smoke) {
+    static std::mutex &m = *new std::mutex;
+    static std::condition_variable &cond = *new std::condition_variable;
+    static volatile bool flag = false;
+
+    std::unique_lock<std::mutex> lock(m);
+    adb_thread_create([](void*) {
+        m.lock();
+        flag = true;
+        cond.notify_one();
+        m.unlock();
+    }, nullptr);
+
+    while (!flag) {
+        cond.wait(lock);
+    }
+}
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index e641680..f997e6b 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -27,6 +27,7 @@
 
 #include <algorithm>
 #include <memory>
+#include <mutex>
 #include <string>
 #include <unordered_map>
 #include <vector>
@@ -110,62 +111,6 @@
 /**************************************************************************/
 /**************************************************************************/
 /*****                                                                *****/
-/*****      replaces libs/cutils/load_file.c                          *****/
-/*****                                                                *****/
-/**************************************************************************/
-/**************************************************************************/
-
-void *load_file(const char *fn, unsigned *_sz)
-{
-    HANDLE    file;
-    char     *data;
-    DWORD     file_size;
-
-    std::wstring fn_wide;
-    if (!android::base::UTF8ToWide(fn, &fn_wide))
-        return NULL;
-
-    file = CreateFileW( fn_wide.c_str(),
-                        GENERIC_READ,
-                        FILE_SHARE_READ,
-                        NULL,
-                        OPEN_EXISTING,
-                        0,
-                        NULL );
-
-    if (file == INVALID_HANDLE_VALUE)
-        return NULL;
-
-    file_size = GetFileSize( file, NULL );
-    data      = NULL;
-
-    if (file_size > 0) {
-        data = (char*) malloc( file_size + 1 );
-        if (data == NULL) {
-            D("load_file: could not allocate %ld bytes", file_size );
-            file_size = 0;
-        } else {
-            DWORD  out_bytes;
-
-            if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
-                 out_bytes != file_size )
-            {
-                D("load_file: could not read %ld bytes from '%s'", file_size, fn);
-                free(data);
-                data      = NULL;
-                file_size = 0;
-            }
-        }
-    }
-    CloseHandle( file );
-
-    *_sz = (unsigned) file_size;
-    return  data;
-}
-
-/**************************************************************************/
-/**************************************************************************/
-/*****                                                                *****/
 /*****    common file descriptor handling                             *****/
 /*****                                                                *****/
 /**************************************************************************/
@@ -181,10 +126,7 @@
         SOCKET      socket;
     } u;
 
-    int       mask;
-
     char  name[32];
-
 } FHRec;
 
 #define  fh_handle  u.handle
@@ -193,7 +135,7 @@
 #define  WIN32_FH_BASE    2048
 #define  WIN32_MAX_FHS    2048
 
-static adb_mutex_t   _win32_lock;
+static  std::mutex&  _win32_lock = *new std::mutex();
 static  FHRec        _win32_fhs[ WIN32_MAX_FHS ];
 static  int          _win32_fh_next;  // where to start search for free FHRec
 
@@ -238,27 +180,24 @@
 {
     FH   f = NULL;
 
-    adb_mutex_lock( &_win32_lock );
+    std::lock_guard<std::mutex> lock(_win32_lock);
 
     for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
         if (_win32_fhs[i].clazz == NULL) {
             f = &_win32_fhs[i];
             _win32_fh_next = i + 1;
-            goto Exit;
+            f->clazz = clazz;
+            f->used = 1;
+            f->eof = 0;
+            f->name[0] = '\0';
+            clazz->_fh_init(f);
+            return f;
         }
     }
-    D( "_fh_alloc: no more free file descriptors" );
-    errno = EMFILE;   // Too many open files
-Exit:
-    if (f) {
-        f->clazz   = clazz;
-        f->used    = 1;
-        f->eof     = 0;
-        f->name[0] = '\0';
-        clazz->_fh_init(f);
-    }
-    adb_mutex_unlock( &_win32_lock );
-    return f;
+
+    D("_fh_alloc: no more free file descriptors");
+    errno = EMFILE;  // Too many open files
+    return nullptr;
 }
 
 
@@ -267,7 +206,7 @@
 {
     // Use lock so that closing only happens once and so that _fh_alloc can't
     // allocate a FH that we're in the middle of closing.
-    adb_mutex_lock(&_win32_lock);
+    std::lock_guard<std::mutex> lock(_win32_lock);
 
     int offset = f - _win32_fhs;
     if (_win32_fh_next > offset) {
@@ -281,7 +220,6 @@
         f->used    = 0;
         f->clazz   = NULL;
     }
-    adb_mutex_unlock(&_win32_lock);
     return 0;
 }
 
@@ -536,81 +474,6 @@
     return 0;
 }
 
-// Overrides strerror() to handle error codes not supported by the Windows C
-// Runtime (MSVCRT.DLL).
-char* adb_strerror(int err) {
-    // sysdeps.h defines strerror to adb_strerror, but in this function, we
-    // want to call the real C Runtime strerror().
-#pragma push_macro("strerror")
-#undef strerror
-    const int saved_err = errno;      // Save because we overwrite it later.
-
-    // Lookup the string for an unknown error.
-    char* errmsg = strerror(-1);
-    const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
-
-    // Lookup the string for this error to see if the C Runtime has it.
-    errmsg = strerror(err);
-    if (errmsg != nullptr && unknown_error != errmsg) {
-        // The CRT returned an error message and it is different than the error
-        // message for an unknown error, so it is probably valid, so use it.
-    } else {
-        // Check if we have a string for this error code.
-        const char* custom_msg = nullptr;
-        switch (err) {
-#pragma push_macro("ERR")
-#undef ERR
-#define ERR(errnum, desc) case errnum: custom_msg = desc; break
-            // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
-            // Note that these cannot be longer than 94 characters because we
-            // pass this to _strerror() which has that requirement.
-            ERR(ECONNRESET,    "Connection reset by peer");
-            ERR(EHOSTUNREACH,  "No route to host");
-            ERR(ENETDOWN,      "Network is down");
-            ERR(ENETRESET,     "Network dropped connection because of reset");
-            ERR(ENOBUFS,       "No buffer space available");
-            ERR(ENOPROTOOPT,   "Protocol not available");
-            ERR(ENOTCONN,      "Transport endpoint is not connected");
-            ERR(ENOTSOCK,      "Socket operation on non-socket");
-            ERR(EOPNOTSUPP,    "Operation not supported on transport endpoint");
-#pragma pop_macro("ERR")
-        }
-
-        if (custom_msg != nullptr) {
-            // Use _strerror() to write our string into the writable per-thread
-            // buffer used by strerror()/_strerror(). _strerror() appends the
-            // msg for the current value of errno, so set errno to a consistent
-            // value for every call so that our code-path is always the same.
-            errno = 0;
-            errmsg = _strerror(custom_msg);
-            const size_t custom_msg_len = strlen(custom_msg);
-            // Just in case _strerror() returned a read-only string, check if
-            // the returned string starts with our custom message because that
-            // implies that the string is not read-only.
-            if ((errmsg != nullptr) &&
-                !strncmp(custom_msg, errmsg, custom_msg_len)) {
-                // _strerror() puts other text after our custom message, so
-                // remove that by terminating after our message.
-                errmsg[custom_msg_len] = '\0';
-            } else {
-                // For some reason nullptr was returned or a pointer to a
-                // read-only string was returned, so fallback to whatever
-                // strerror() can muster (probably "Unknown error" or some
-                // generic CRT error string).
-                errmsg = strerror(err);
-            }
-        } else {
-            // We don't have a custom message, so use whatever strerror(err)
-            // returned earlier.
-        }
-    }
-
-    errno = saved_err;  // restore
-
-    return errmsg;
-#pragma pop_macro("strerror")
-}
-
 /**************************************************************************/
 /**************************************************************************/
 /*****                                                                *****/
@@ -624,7 +487,7 @@
 static void _socket_set_errno( const DWORD err ) {
     // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
     // lot of POSIX and socket error codes, some of the resulting error codes
-    // are mapped to strings by adb_strerror() above.
+    // are mapped to strings by adb_strerror().
     switch ( err ) {
     case 0:              errno = 0; break;
     // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
@@ -711,7 +574,6 @@
 
 static void _fh_socket_init(FH f) {
     f->fh_socket = INVALID_SOCKET;
-    f->mask      = 0;
 }
 
 static int _fh_socket_close( FH  f ) {
@@ -732,7 +594,6 @@
         }
         f->fh_socket = INVALID_SOCKET;
     }
-    f->mask = 0;
     return 0;
 }
 
@@ -1008,7 +869,7 @@
         _socket_set_errno(err);
         return -1;
     }
-    std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*> addrinfo(addrinfo_ptr, freeaddrinfo);
+    std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
     addrinfo_ptr = nullptr;
 
     // TODO: Try all the addresses if there's more than one? This just uses
@@ -1047,6 +908,12 @@
     return fd;
 }
 
+int  adb_register_socket(SOCKET s) {
+    FH f = _fh_alloc( &_fh_socket_class );
+    f->fh_socket = s;
+    return _fh_to_int(f);
+}
+
 #undef accept
 int  adb_socket_accept(int  serverfd, struct sockaddr*  addr, socklen_t  *addrlen)
 {
@@ -1117,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,
@@ -1128,6 +995,24 @@
     return result;
 }
 
+int adb_socket_get_local_port(int fd) {
+    sockaddr_storage addr_storage;
+    socklen_t addr_len = sizeof(addr_storage);
+
+    if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
+        D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
+        return -1;
+    }
+
+    if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
+        D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
+        errno = ECONNABORTED;
+        return -1;
+    }
+
+    return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
+}
+
 int  adb_shutdown(int  fd)
 {
     FH   f = _fh_from_int(fd, __func__);
@@ -1154,42 +1039,59 @@
     int server = -1;
     int client = -1;
     int accepted = -1;
-    sockaddr_storage addr_storage;
-    socklen_t addr_len = sizeof(addr_storage);
-    sockaddr_in* addr = nullptr;
+    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());
         goto fail;
     }
 
-    if (adb_getsockname(server, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
-        D("adb_socketpair: adb_getsockname failed: %s", strerror(errno));
+    local_port = adb_socket_get_local_port(server);
+    if (local_port < 0) {
+        D("adb_socketpair: failed to get server port number: %s", error.c_str());
         goto fail;
     }
+    D("adb_socketpair: bound on port %d", local_port);
 
-    if (addr_storage.ss_family != AF_INET) {
-        D("adb_socketpair: unknown address family received: %d", addr_storage.ss_family);
-        errno = ECONNABORTED;
-        goto fail;
-    }
-
-    addr = reinterpret_cast<sockaddr_in*>(&addr_storage);
-    D("adb_socketpair: bound on port %d", ntohs(addr->sin_port));
-    client = network_loopback_client(ntohs(addr->sin_port), SOCK_STREAM, &error);
+    client = network_loopback_client(local_port, SOCK_STREAM, &error);
     if (client < 0) {
         D("adb_socketpair: failed to connect client: %s", error.c_str());
         goto fail;
     }
 
-    accepted = adb_socket_accept(server, nullptr, nullptr);
+    // 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);
     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;
@@ -1212,18 +1114,22 @@
 
     if (!fh || !fh->used) {
         errno = EBADF;
+        D("Setting nonblocking on bad file descriptor %d", fd);
         return false;
     }
 
     if (fh->clazz == &_fh_socket_class) {
         u_long x = !block;
         if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
-            _socket_set_errno(WSAGetLastError());
+            int error = WSAGetLastError();
+            _socket_set_errno(error);
+            D("Setting %d nonblocking failed (%d)", fd, error);
             return false;
         }
         return true;
     } else {
         errno = ENOTSOCK;
+        D("Setting nonblocking on non-socket %d", fd);
         return false;
     }
 }
@@ -1255,17 +1161,6 @@
     return true;
 }
 
-static adb_mutex_t g_console_output_buffer_lock;
-
-void
-adb_sysdeps_init( void )
-{
-#define  ADB_MUTEX(x)  InitializeCriticalSection( & x );
-#include "mutex_list.h"
-    InitializeCriticalSection( &_win32_lock );
-    InitializeCriticalSection( &g_console_output_buffer_lock );
-}
-
 /**************************************************************************/
 /**************************************************************************/
 /*****                                                                *****/
@@ -2458,12 +2353,13 @@
 // Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
 // Note that we use only one buffer even though stderr and stdout are logically separate streams.
 // This matches the behavior of Linux.
-// Protected by g_console_output_buffer_lock.
-static auto& g_console_output_buffer = *new std::vector<char>();
 
 // Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
 static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
                                HANDLE console) {
+    static std::mutex& console_output_buffer_lock = *new std::mutex();
+    static auto& console_output_buffer = *new std::vector<char>();
+
     const int saved_errno = errno;
     std::vector<char> combined_buffer;
 
@@ -2471,24 +2367,25 @@
     const char* utf8;
     size_t utf8_size;
 
-    adb_mutex_lock(&g_console_output_buffer_lock);
-    if (g_console_output_buffer.empty()) {
-        // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
-        // common case with plain ASCII), parse buf directly.
-        utf8 = buf;
-        utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
-    } else {
-        // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
-        // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
-        // combined_buffer, then parse it all together.
-        combined_buffer.swap(g_console_output_buffer);
-        combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
+    {
+        std::lock_guard<std::mutex> lock(console_output_buffer_lock);
+        if (console_output_buffer.empty()) {
+            // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
+            // common case with plain ASCII), parse buf directly.
+            utf8 = buf;
+            utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
+        } else {
+            // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
+            // combined_buffer (and effectively clear console_output_buffer) and append buf to
+            // combined_buffer, then parse it all together.
+            combined_buffer.swap(console_output_buffer);
+            combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
 
-        utf8 = combined_buffer.data();
-        utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
-                                                &g_console_output_buffer);
+            utf8 = combined_buffer.data();
+            utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
+                                                    &console_output_buffer);
+        }
     }
-    adb_mutex_unlock(&g_console_output_buffer_lock);
 
     std::wstring utf16;
 
diff --git a/adb/sysdeps_win32_test.cpp b/adb/sysdeps_win32_test.cpp
old mode 100755
new mode 100644
index c3a3fd7..529b212
--- a/adb/sysdeps_win32_test.cpp
+++ b/adb/sysdeps_win32_test.cpp
@@ -70,36 +70,6 @@
     }
 }
 
-void TestAdbStrError(int err, const char* expected) {
-    errno = 12345;
-    const char* result = adb_strerror(err);
-    // Check that errno is not overwritten.
-    EXPECT_EQ(12345, errno);
-    EXPECT_STREQ(expected, result);
-}
-
-TEST(sysdeps_win32, adb_strerror) {
-    // Test an error code that should not have a mapped string. Use an error
-    // code that is not used by the internal implementation of adb_strerror().
-    TestAdbStrError(-2, "Unknown error");
-    // adb_strerror() uses -1 internally, so test that it can still be passed
-    // as a parameter.
-    TestAdbStrError(-1, "Unknown error");
-    // Test very big, positive unknown error.
-    TestAdbStrError(1000000, "Unknown error");
-
-    // Test success case.
-    // Wine returns "Success" for strerror(0), Windows returns "No error", so accept both.
-    std::string success = adb_strerror(0);
-    EXPECT_TRUE(success == "Success" || success == "No error") << "strerror(0) = " << success;
-
-    // Test error that regular strerror() should have a string for.
-    TestAdbStrError(EPERM, "Operation not permitted");
-    // Test error that regular strerror() doesn't have a string for, but that
-    // adb_strerror() returns.
-    TestAdbStrError(ECONNRESET, "Connection reset by peer");
-}
-
 TEST(sysdeps_win32, unix_isatty) {
     // stdin and stdout should be consoles. Use CONIN$ and CONOUT$ special files
     // so that we can test this even if stdin/stdout have been redirected. Read
diff --git a/adb/test_adb.py b/adb/test_adb.py
index 0f1b034..cb3e0d8 100644
--- a/adb/test_adb.py
+++ b/adb/test_adb.py
@@ -207,6 +207,28 @@
             # reading the response from the adb emu kill command (on Windows).
             self.assertEqual(0, p.returncode)
 
+    def test_connect_ipv4_ipv6(self):
+        """Ensure that `adb connect localhost:1234` will try both IPv4 and IPv6.
+
+        Bug: http://b/30313466
+        """
+        ipv4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        ipv4.bind(('127.0.0.1', 0))
+        ipv4.listen(1)
+
+        ipv6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
+        ipv6.bind(('::1', ipv4.getsockname()[1] + 1))
+        ipv6.listen(1)
+
+        for s in (ipv4, ipv6):
+            port = s.getsockname()[1]
+            output = subprocess.check_output(
+                ['adb', 'connect', 'localhost:{}'.format(port)])
+
+            self.assertEqual(
+                output.strip(), 'connected to localhost:{}'.format(port))
+            s.close()
+
 
 def main():
     random.seed(0)
diff --git a/adb/test_device.py b/adb/test_device.py
index 9dab3ae..e76aaed 100644
--- a/adb/test_device.py
+++ b/adb/test_device.py
@@ -31,6 +31,7 @@
 import subprocess
 import sys
 import tempfile
+import time
 import unittest
 
 import mock
@@ -191,6 +192,22 @@
         msg = self.device.forward_list()
         self.assertEqual('', msg.strip())
 
+    def test_forward_tcp_port_0(self):
+        self.assertEqual('', self.device.forward_list().strip(),
+                         'Forwarding list must be empty to run this test.')
+
+        try:
+            # If resolving TCP port 0 is supported, `adb forward` will print
+            # the actual port number.
+            port = self.device.forward('tcp:0', 'tcp:8888').strip()
+            if not port:
+                raise unittest.SkipTest('Forwarding tcp:0 is not available.')
+
+            self.assertTrue(re.search(r'tcp:{}.+tcp:8888'.format(port),
+                                      self.device.forward_list()))
+        finally:
+            self.device.forward_remove_all()
+
     def test_reverse(self):
         msg = self.device.reverse_list()
         self.assertEqual('', msg.strip(),
@@ -210,6 +227,22 @@
         msg = self.device.reverse_list()
         self.assertEqual('', msg.strip())
 
+    def test_reverse_tcp_port_0(self):
+        self.assertEqual('', self.device.reverse_list().strip(),
+                         'Reverse list must be empty to run this test.')
+
+        try:
+            # If resolving TCP port 0 is supported, `adb reverse` will print
+            # the actual port number.
+            port = self.device.reverse('tcp:0', 'tcp:8888').strip()
+            if not port:
+                raise unittest.SkipTest('Reversing tcp:0 is not available.')
+
+            self.assertTrue(re.search(r'tcp:{}.+tcp:8888'.format(port),
+                                      self.device.reverse_list()))
+        finally:
+            self.device.reverse_remove_all()
+
     # Note: If you run this test when adb connect'd to a physical device over
     # TCP, it will fail in adb reverse due to https://code.google.com/p/android/issues/detail?id=189821
     def test_forward_reverse_echo(self):
@@ -279,7 +312,7 @@
         Raises:
           unittest.SkipTest: The device doesn't support exit codes.
         """
-        if self.device.SHELL_PROTOCOL_FEATURE not in self.device.features:
+        if not self.device.has_shell_protocol():
             raise unittest.SkipTest('exit codes are unavailable on this device')
 
         proc = subprocess.Popen(
@@ -338,15 +371,8 @@
     def test_pty_logic(self):
         """Tests that a PTY is allocated when it should be.
 
-        PTY allocation behavior should match ssh; some behavior requires
-        a terminal stdin to test so this test will be skipped if stdin
-        is not a terminal.
+        PTY allocation behavior should match ssh.
         """
-        if self.device.SHELL_PROTOCOL_FEATURE not in self.device.features:
-            raise unittest.SkipTest('PTY arguments unsupported on this device')
-        if not os.isatty(sys.stdin.fileno()):
-            raise unittest.SkipTest('PTY tests require stdin terminal')
-
         def check_pty(args):
             """Checks adb shell PTY allocation.
 
@@ -376,16 +402,34 @@
         # -T: never allocate PTY.
         self.assertEqual((False, False), check_pty(['-T']))
 
-        # No args: PTY only if stdin is a terminal and shell is interactive,
-        # which is difficult to reliably test from a script.
-        self.assertEqual((False, False), check_pty([]))
+        # These tests require a new device.
+        if self.device.has_shell_protocol() and os.isatty(sys.stdin.fileno()):
+            # No args: PTY only if stdin is a terminal and shell is interactive,
+            # which is difficult to reliably test from a script.
+            self.assertEqual((False, False), check_pty([]))
 
-        # -t: PTY if stdin is a terminal.
-        self.assertEqual((True, False), check_pty(['-t']))
+            # -t: PTY if stdin is a terminal.
+            self.assertEqual((True, False), check_pty(['-t']))
 
         # -t -t: always allocate PTY.
         self.assertEqual((True, True), check_pty(['-t', '-t']))
 
+        # -tt: always allocate PTY, POSIX style (http://b/32216152).
+        self.assertEqual((True, True), check_pty(['-tt']))
+
+        # -ttt: ssh has weird even/odd behavior with multiple -t flags, but
+        # we follow the man page instead.
+        self.assertEqual((True, True), check_pty(['-ttt']))
+
+        # -ttx: -x and -tt aren't incompatible (though -Tx would be an error).
+        self.assertEqual((True, True), check_pty(['-ttx']))
+
+        # -Ttt: -tt cancels out -T.
+        self.assertEqual((True, True), check_pty(['-Ttt']))
+
+        # -ttT: -T cancels out -tt.
+        self.assertEqual((False, False), check_pty(['-ttT']))
+
     def test_shell_protocol(self):
         """Tests the shell protocol on the device.
 
@@ -394,7 +438,7 @@
 
         Bug: http://b/19734861
         """
-        if self.device.SHELL_PROTOCOL_FEATURE not in self.device.features:
+        if not self.device.has_shell_protocol():
             raise unittest.SkipTest('shell protocol unsupported on this device')
 
         # Shell protocol should be used by default.
@@ -424,7 +468,7 @@
 
         Bug: http://b/23825725
         """
-        if self.device.SHELL_PROTOCOL_FEATURE not in self.device.features:
+        if not self.device.has_shell_protocol():
             raise unittest.SkipTest('shell protocol unsupported on this device')
 
         # Start a long-running process.
@@ -440,12 +484,16 @@
         self.device.shell(proc_query)
         os.kill(sleep_proc.pid, signal.SIGINT)
         sleep_proc.communicate()
-        self.assertEqual(1, self.device.shell_nocheck(proc_query)[0],
-                         'subprocess failed to terminate')
+
+        # It can take some time for the process to receive the signal and die.
+        end_time = time.time() + 3
+        while self.device.shell_nocheck(proc_query)[0] != 1:
+            self.assertFalse(time.time() > end_time,
+                             'subprocess failed to terminate in time')
 
     def test_non_interactive_stdin(self):
         """Tests that non-interactive shells send stdin."""
-        if self.device.SHELL_PROTOCOL_FEATURE not in self.device.features:
+        if not self.device.has_shell_protocol():
             raise unittest.SkipTest('non-interactive stdin unsupported '
                                     'on this device')
 
@@ -463,6 +511,37 @@
             self.assertEqual(input.splitlines(), stdout.splitlines())
             self.assertEqual('', stderr)
 
+    def test_sighup(self):
+        """Ensure that SIGHUP gets sent upon non-interactive ctrl-c"""
+        log_path = "/data/local/tmp/adb_signal_test.log"
+
+        # Clear the output file.
+        self.device.shell_nocheck(["echo", ">", log_path])
+
+        script = """
+            trap "echo SIGINT > {path}; exit 0" SIGINT
+            trap "echo SIGHUP > {path}; exit 0" SIGHUP
+            echo Waiting
+            read
+        """.format(path=log_path)
+
+        script = ";".join([x.strip() for x in script.strip().splitlines()])
+
+        process = self.device.shell_popen([script], kill_atexit=False,
+                                          stdin=subprocess.PIPE,
+                                          stdout=subprocess.PIPE)
+
+        self.assertEqual("Waiting\n", process.stdout.readline())
+        process.send_signal(signal.SIGINT)
+        process.wait()
+
+        # Waiting for the local adb to finish is insufficient, since it hangs
+        # up immediately.
+        time.sleep(1)
+
+        stdout, _ = self.device.shell(["cat", log_path])
+        self.assertEqual(stdout.strip(), "SIGHUP")
+
 
 class ArgumentEscapingTest(DeviceTest):
     def test_shell_escaping(self):
@@ -724,6 +803,36 @@
             if host_dir is not None:
                 shutil.rmtree(host_dir)
 
+    @unittest.skipIf(sys.platform == "win32", "symlinks require elevated privileges on windows")
+    def test_push_symlink(self):
+        """Push a symlink.
+
+        Bug: http://b/31491920
+        """
+        try:
+            host_dir = tempfile.mkdtemp()
+
+            # Make sure the temp directory isn't setuid, or else adb will
+            # complain.
+            os.chmod(host_dir, 0o700)
+
+            with open(os.path.join(host_dir, 'foo'), 'w') as f:
+                f.write('foo')
+
+            symlink_path = os.path.join(host_dir, 'symlink')
+            os.symlink('foo', symlink_path)
+
+            self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
+            self.device.shell(['mkdir', self.DEVICE_TEMP_DIR])
+            self.device.push(symlink_path, self.DEVICE_TEMP_DIR)
+            rc, out, _ = self.device.shell_nocheck(
+                ['cat', posixpath.join(self.DEVICE_TEMP_DIR, 'symlink')])
+            self.assertEqual(0, rc)
+            self.assertEqual(out.strip(), 'foo')
+        finally:
+            if host_dir is not None:
+                shutil.rmtree(host_dir)
+
     def test_multiple_push(self):
         """Push multiple files to the device in one adb push command.
 
@@ -781,7 +890,8 @@
             except subprocess.CalledProcessError as e:
                 output = e.output
 
-            self.assertIn('Permission denied', output)
+            self.assertTrue('Permission denied' in output or
+                            'Read-only file system' in output)
 
     def _test_pull(self, remote_file, checksum):
         tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
diff --git a/adb/test_track_devices.cpp b/adb/test_track_devices.cpp
deleted file mode 100644
index b10f8ee..0000000
--- a/adb/test_track_devices.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-// TODO: replace this with a shell/python script.
-
-/* a simple test program, connects to ADB server, and opens a track-devices session */
-#include <errno.h>
-#include <memory.h>
-#include <netdb.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include <android-base/file.h>
-
-static void
-panic( const char*  msg )
-{
-    fprintf(stderr, "PANIC: %s: %s\n", msg, strerror(errno));
-    exit(1);
-}
-
-int main(int argc, char* argv[]) {
-    const char* request = "host:track-devices";
-
-    if (argv[1] && strcmp(argv[1], "--jdwp") == 0) {
-        request = "track-jdwp";
-    }
-
-    int                  ret;
-    struct sockaddr_in   server;
-    char                 buffer[1024];
-
-    memset( &server, 0, sizeof(server) );
-    server.sin_family      = AF_INET;
-    server.sin_port        = htons(5037);
-    server.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-
-    int s = socket( PF_INET, SOCK_STREAM, 0 );
-    ret = connect( s, (struct sockaddr*) &server, sizeof(server) );
-    if (ret < 0) panic( "could not connect to server" );
-
-    /* send the request */
-    int len = snprintf(buffer, sizeof(buffer), "%04zx%s", strlen(request), request);
-    if (!android::base::WriteFully(s, buffer, len))
-        panic( "could not send request" );
-
-    /* read the OKAY answer */
-    if (!android::base::ReadFully(s, buffer, 4))
-        panic( "could not read request" );
-
-    printf( "server answer: %.*s\n", 4, buffer );
-
-    /* now loop */
-    while (true) {
-        char  head[5] = "0000";
-
-        if (!android::base::ReadFully(s, head, 4))
-            panic("could not read length");
-
-        int len;
-        if (sscanf(head, "%04x", &len) != 1 )
-            panic("could not decode length");
-
-        if (!android::base::ReadFully(s, buffer, len))
-            panic("could not read data");
-
-        printf( "received header %.*s (%d bytes):\n%.*s----\n", 4, head, len, len, buffer );
-    }
-    close(s);
-}
diff --git a/adb/trace.sh b/adb/trace.sh
new file mode 100755
index 0000000..49e5026
--- /dev/null
+++ b/adb/trace.sh
@@ -0,0 +1,17 @@
+set -e
+
+if ! [ -e $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py ]; then
+    echo "error: can't find systrace.py at \$ANDROID_BUILD_TOP/external/chromium-trace/systrace.py"
+    exit 1
+fi
+
+adb shell "sleep 1; atrace -b 65536 --async_start adb sched power freq idle disk mmc load"
+adb shell killall adbd
+adb wait-for-device
+echo "press enter to finish..."
+read
+TRACE_TEMP=`mktemp /tmp/trace.XXXXXX`
+echo Saving trace to ${TRACE_TEMP}, html file to ${TRACE_TEMP}.html
+adb shell atrace --async_stop -z > ${TRACE_TEMP}
+$ANDROID_BUILD_TOP/external/chromium-trace/systrace.py --from-file=${TRACE_TEMP} -o ${TRACE_TEMP}.html
+chrome ${TRACE_TEMP}.html
diff --git a/adb/transport.cpp b/adb/transport.cpp
index c31f655..c951f5b 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -28,6 +28,7 @@
 
 #include <algorithm>
 #include <list>
+#include <mutex>
 
 #include <android-base/logging.h>
 #include <android-base/parsenetaddress.h>
@@ -35,6 +36,8 @@
 #include <android-base/strings.h>
 
 #include "adb.h"
+#include "adb_auth.h"
+#include "adb_trace.h"
 #include "adb_utils.h"
 #include "diagnose_usb.h"
 
@@ -43,22 +46,23 @@
 static auto& transport_list = *new std::list<atransport*>();
 static auto& pending_list = *new std::list<atransport*>();
 
-ADB_MUTEX_DEFINE( transport_lock );
+static std::mutex& transport_lock = *new std::mutex();
 
 const char* const kFeatureShell2 = "shell_v2";
 const char* const kFeatureCmd = "cmd";
+const char* const kFeatureStat2 = "stat_v2";
+const char* const kFeatureLibusb = "libusb";
 
 static std::string dump_packet(const char* name, const char* func, apacket* p) {
-    unsigned  command = p->msg.command;
-    int       len     = p->msg.data_length;
-    char      cmd[9];
-    char      arg0[12], arg1[12];
-    int       n;
+    unsigned command = p->msg.command;
+    int len = p->msg.data_length;
+    char cmd[9];
+    char arg0[12], arg1[12];
+    int n;
 
     for (n = 0; n < 4; n++) {
-        int  b = (command >> (n*8)) & 255;
-        if (b < 32 || b >= 127)
-            break;
+        int b = (command >> (n * 8)) & 255;
+        if (b < 32 || b >= 127) break;
         cmd[n] = (char)b;
     }
     if (n == 4) {
@@ -79,25 +83,24 @@
     else
         snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
 
-    std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ",
-                                                     name, func, cmd, arg0, arg1, len);
+    std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
+                                                     func, cmd, arg0, arg1, len);
     result += dump_hex(p->data, len);
     return result;
 }
 
-static int
-read_packet(int  fd, const char* name, apacket** ppacket)
-{
+static int read_packet(int fd, const char* name, apacket** ppacket) {
+    ATRACE_NAME("read_packet");
     char buff[8];
     if (!name) {
         snprintf(buff, sizeof buff, "fd=%d", fd);
         name = buff;
     }
-    char* p = reinterpret_cast<char*>(ppacket);  /* really read a packet address */
+    char* p = reinterpret_cast<char*>(ppacket); /* really read a packet address */
     int len = sizeof(apacket*);
-    while(len > 0) {
+    while (len > 0) {
         int r = adb_read(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
             p += r;
         } else {
@@ -110,20 +113,19 @@
     return 0;
 }
 
-static int
-write_packet(int  fd, const char* name, apacket** ppacket)
-{
+static int write_packet(int fd, const char* name, apacket** ppacket) {
+    ATRACE_NAME("write_packet");
     char buff[8];
     if (!name) {
         snprintf(buff, sizeof buff, "fd=%d", fd);
         name = buff;
     }
     VLOG(TRANSPORT) << dump_packet(name, "to remote", *ppacket);
-    char* p = reinterpret_cast<char*>(ppacket);  /* we really write the packet address */
+    char* p = reinterpret_cast<char*>(ppacket); /* we really write the packet address */
     int len = sizeof(apacket*);
-    while(len > 0) {
+    while (len > 0) {
         int r = adb_write(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
             p += r;
         } else {
@@ -134,46 +136,30 @@
     return 0;
 }
 
-static void transport_socket_events(int fd, unsigned events, void *_t)
-{
-    atransport *t = reinterpret_cast<atransport*>(_t);
+static void transport_socket_events(int fd, unsigned events, void* _t) {
+    atransport* t = reinterpret_cast<atransport*>(_t);
     D("transport_socket_events(fd=%d, events=%04x,...)", fd, events);
-    if(events & FDE_READ){
-        apacket *p = 0;
-        if(read_packet(fd, t->serial, &p)){
+    if (events & FDE_READ) {
+        apacket* p = 0;
+        if (read_packet(fd, t->serial, &p)) {
             D("%s: failed to read packet from transport socket on fd %d", t->serial, fd);
         } else {
-            handle_packet(p, (atransport *) _t);
+            handle_packet(p, (atransport*)_t);
         }
     }
 }
 
-void send_packet(apacket *p, atransport *t)
-{
-    unsigned char *x;
-    unsigned sum;
-    unsigned count;
-
+void send_packet(apacket* p, atransport* t) {
     p->msg.magic = p->msg.command ^ 0xffffffff;
-
-    count = p->msg.data_length;
-    x = (unsigned char *) p->data;
-    sum = 0;
-    while(count-- > 0){
-        sum += *x++;
-    }
-    p->msg.data_check = sum;
+    p->msg.data_check = calculate_apacket_checksum(p);
 
     print_packet("send", p);
 
     if (t == NULL) {
-        D("Transport is null");
-        // Zap errno because print_packet() and other stuff have errno effect.
-        errno = 0;
-        fatal_errno("Transport is null");
+        fatal("Transport is null");
     }
 
-    if(write_packet(t->transport_socket, t->serial, &p)){
+    if (write_packet(t->transport_socket, t->serial, &p)) {
         fatal_errno("cannot enqueue packet on transport socket");
     }
 }
@@ -192,40 +178,43 @@
 // read_transport thread reads data from a transport (representing a usb/tcp connection),
 // and makes the main thread call handle_packet().
 static void read_transport_thread(void* _t) {
-    atransport *t = reinterpret_cast<atransport*>(_t);
-    apacket *p;
+    atransport* t = reinterpret_cast<atransport*>(_t);
+    apacket* p;
 
-    adb_thread_setname(android::base::StringPrintf("<-%s",
-                                                   (t->serial != nullptr ? t->serial : "transport")));
-    D("%s: starting read_transport thread on fd %d, SYNC online (%d)",
-       t->serial, t->fd, t->sync_token + 1);
+    adb_thread_setname(
+        android::base::StringPrintf("<-%s", (t->serial != nullptr ? t->serial : "transport")));
+    D("%s: starting read_transport thread on fd %d, SYNC online (%d)", t->serial, t->fd,
+      t->sync_token + 1);
     p = get_apacket();
     p->msg.command = A_SYNC;
     p->msg.arg0 = 1;
     p->msg.arg1 = ++(t->sync_token);
     p->msg.magic = A_SYNC ^ 0xffffffff;
-    if(write_packet(t->fd, t->serial, &p)) {
+    if (write_packet(t->fd, t->serial, &p)) {
         put_apacket(p);
         D("%s: failed to write SYNC packet", t->serial);
         goto oops;
     }
 
     D("%s: data pump started", t->serial);
-    for(;;) {
+    for (;;) {
+        ATRACE_NAME("read_transport loop");
         p = get_apacket();
 
-        if(t->read_from_remote(p, t) == 0){
-            D("%s: received remote packet, sending to transport",
-              t->serial);
-            if(write_packet(t->fd, t->serial, &p)){
+        {
+            ATRACE_NAME("read_transport read_remote");
+            if (t->read_from_remote(p, t) != 0) {
+                D("%s: remote read failed for transport", t->serial);
                 put_apacket(p);
-                D("%s: failed to write apacket to transport", t->serial);
-                goto oops;
+                break;
             }
-        } else {
-            D("%s: remote read failed for transport", t->serial);
+        }
+
+        D("%s: received remote packet, sending to transport", t->serial);
+        if (write_packet(t->fd, t->serial, &p)) {
             put_apacket(p);
-            break;
+            D("%s: failed to write apacket to transport", t->serial);
+            goto oops;
         }
     }
 
@@ -235,7 +224,7 @@
     p->msg.arg0 = 0;
     p->msg.arg1 = 0;
     p->msg.magic = A_SYNC ^ 0xffffffff;
-    if(write_packet(t->fd, t->serial, &p)) {
+    if (write_packet(t->fd, t->serial, &p)) {
         put_apacket(p);
         D("%s: failed to write SYNC apacket to transport", t->serial);
     }
@@ -249,38 +238,38 @@
 // write_transport thread gets packets sent by the main thread (through send_packet()),
 // and writes to a transport (representing a usb/tcp connection).
 static void write_transport_thread(void* _t) {
-    atransport *t = reinterpret_cast<atransport*>(_t);
-    apacket *p;
+    atransport* t = reinterpret_cast<atransport*>(_t);
+    apacket* p;
     int active = 0;
 
-    adb_thread_setname(android::base::StringPrintf("->%s",
-                                                   (t->serial != nullptr ? t->serial : "transport")));
-    D("%s: starting write_transport thread, reading from fd %d",
-       t->serial, t->fd);
+    adb_thread_setname(
+        android::base::StringPrintf("->%s", (t->serial != nullptr ? t->serial : "transport")));
+    D("%s: starting write_transport thread, reading from fd %d", t->serial, t->fd);
 
-    for(;;){
-        if(read_packet(t->fd, t->serial, &p)) {
-            D("%s: failed to read apacket from transport on fd %d",
-               t->serial, t->fd );
+    for (;;) {
+        ATRACE_NAME("write_transport loop");
+        if (read_packet(t->fd, t->serial, &p)) {
+            D("%s: failed to read apacket from transport on fd %d", t->serial, t->fd);
             break;
         }
-        if(p->msg.command == A_SYNC){
-            if(p->msg.arg0 == 0) {
+
+        if (p->msg.command == A_SYNC) {
+            if (p->msg.arg0 == 0) {
                 D("%s: transport SYNC offline", t->serial);
                 put_apacket(p);
                 break;
             } else {
-                if(p->msg.arg1 == t->sync_token) {
+                if (p->msg.arg1 == t->sync_token) {
                     D("%s: transport SYNC online", t->serial);
                     active = 1;
                 } else {
-                    D("%s: transport ignoring SYNC %d != %d",
-                      t->serial, p->msg.arg1, t->sync_token);
+                    D("%s: transport ignoring SYNC %d != %d", t->serial, p->msg.arg1, t->sync_token);
                 }
             }
         } else {
-            if(active) {
+            if (active) {
                 D("%s: transport got packet, sending to remote", t->serial);
+                ATRACE_NAME("write_transport write_remote");
                 t->write_to_remote(p, t);
             } else {
                 D("%s: transport ignoring packet while offline", t->serial);
@@ -296,20 +285,18 @@
 }
 
 void kick_transport(atransport* t) {
-    adb_mutex_lock(&transport_lock);
+    std::lock_guard<std::mutex> lock(transport_lock);
     // As kick_transport() can be called from threads without guarantee that t is valid,
     // check if the transport is in transport_list first.
     if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
         t->Kick();
     }
-    adb_mutex_unlock(&transport_lock);
 }
 
 static int transport_registration_send = -1;
 static int transport_registration_recv = -1;
 static fdevent transport_registration_fde;
 
-
 #if ADB_HOST
 
 /* this adds support required by the 'track-devices' service.
@@ -318,39 +305,34 @@
  * live TCP connection
  */
 struct device_tracker {
-    asocket          socket;
-    int              update_needed;
-    device_tracker*  next;
+    asocket socket;
+    int update_needed;
+    device_tracker* next;
 };
 
 /* linked list of all device trackers */
-static device_tracker*   device_tracker_list;
+static device_tracker* device_tracker_list;
 
-static void
-device_tracker_remove( device_tracker*  tracker )
-{
-    device_tracker**  pnode = &device_tracker_list;
-    device_tracker*   node  = *pnode;
+static void device_tracker_remove(device_tracker* tracker) {
+    device_tracker** pnode = &device_tracker_list;
+    device_tracker* node = *pnode;
 
-    adb_mutex_lock( &transport_lock );
+    std::lock_guard<std::mutex> lock(transport_lock);
     while (node) {
         if (node == tracker) {
             *pnode = node->next;
             break;
         }
         pnode = &node->next;
-        node  = *pnode;
+        node = *pnode;
     }
-    adb_mutex_unlock( &transport_lock );
 }
 
-static void
-device_tracker_close( asocket*  socket )
-{
-    device_tracker*  tracker = (device_tracker*) socket;
-    asocket*         peer    = socket->peer;
+static void device_tracker_close(asocket* socket) {
+    device_tracker* tracker = (device_tracker*)socket;
+    asocket* peer = socket->peer;
 
-    D( "device tracker %p removed", tracker);
+    D("device tracker %p removed", tracker);
     if (peer) {
         peer->peer = NULL;
         peer->close(peer);
@@ -359,9 +341,7 @@
     free(tracker);
 }
 
-static int
-device_tracker_enqueue( asocket*  socket, apacket*  p )
-{
+static int device_tracker_enqueue(asocket* socket, apacket* p) {
     /* you can't read from a device tracker, close immediately */
     put_apacket(p);
     device_tracker_close(socket);
@@ -391,26 +371,23 @@
     }
 }
 
-asocket*
-create_device_tracker(void)
-{
+asocket* create_device_tracker(void) {
     device_tracker* tracker = reinterpret_cast<device_tracker*>(calloc(1, sizeof(*tracker)));
     if (tracker == nullptr) fatal("cannot allocate device tracker");
 
-    D( "device tracker %p created", tracker);
+    D("device tracker %p created", tracker);
 
     tracker->socket.enqueue = device_tracker_enqueue;
-    tracker->socket.ready   = device_tracker_ready;
-    tracker->socket.close   = device_tracker_close;
-    tracker->update_needed  = 1;
+    tracker->socket.ready = device_tracker_ready;
+    tracker->socket.close = device_tracker_close;
+    tracker->update_needed = 1;
 
-    tracker->next       = device_tracker_list;
+    tracker->next = device_tracker_list;
     device_tracker_list = tracker;
 
     return &tracker->socket;
 }
 
-
 // Call this function each time the transport list has changed.
 void update_transports() {
     std::string transports = list_transports(false);
@@ -430,26 +407,23 @@
     // Nothing to do on the device side.
 }
 
-#endif // ADB_HOST
+#endif  // ADB_HOST
 
-struct tmsg
-{
-    atransport *transport;
-    int         action;
+struct tmsg {
+    atransport* transport;
+    int action;
 };
 
-static int
-transport_read_action(int  fd, struct tmsg*  m)
-{
-    char *p   = (char*)m;
-    int   len = sizeof(*m);
-    int   r;
+static int transport_read_action(int fd, struct tmsg* m) {
+    char* p = (char*)m;
+    int len = sizeof(*m);
+    int r;
 
-    while(len > 0) {
+    while (len > 0) {
         r = adb_read(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
-            p   += r;
+            p += r;
         } else {
             D("transport_read_action: on fd %d: %s", fd, strerror(errno));
             return -1;
@@ -458,18 +432,16 @@
     return 0;
 }
 
-static int
-transport_write_action(int  fd, struct tmsg*  m)
-{
-    char *p   = (char*)m;
-    int   len = sizeof(*m);
-    int   r;
+static int transport_write_action(int fd, struct tmsg* m) {
+    char* p = (char*)m;
+    int len = sizeof(*m);
+    int r;
 
-    while(len > 0) {
+    while (len > 0) {
         r = adb_write(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
-            p   += r;
+            p += r;
         } else {
             D("transport_write_action: on fd %d: %s", fd, strerror(errno));
             return -1;
@@ -478,17 +450,16 @@
     return 0;
 }
 
-static void transport_registration_func(int _fd, unsigned ev, void *data)
-{
+static void transport_registration_func(int _fd, unsigned ev, void* data) {
     tmsg m;
     int s[2];
-    atransport *t;
+    atransport* t;
 
-    if(!(ev & FDE_READ)) {
+    if (!(ev & FDE_READ)) {
         return;
     }
 
-    if(transport_read_action(_fd, &m)) {
+    if (transport_read_action(_fd, &m)) {
         fatal_errno("cannot read transport registration socket");
     }
 
@@ -497,26 +468,22 @@
     if (m.action == 0) {
         D("transport: %s removing and free'ing %d", t->serial, t->transport_socket);
 
-            /* IMPORTANT: the remove closes one half of the
-            ** socket pair.  The close closes the other half.
-            */
+        /* IMPORTANT: the remove closes one half of the
+        ** socket pair.  The close closes the other half.
+        */
         fdevent_remove(&(t->transport_fde));
         adb_close(t->fd);
 
-        adb_mutex_lock(&transport_lock);
-        transport_list.remove(t);
-        adb_mutex_unlock(&transport_lock);
+        {
+            std::lock_guard<std::mutex> lock(transport_lock);
+            transport_list.remove(t);
+        }
 
-        if (t->product)
-            free(t->product);
-        if (t->serial)
-            free(t->serial);
-        if (t->model)
-            free(t->model);
-        if (t->device)
-            free(t->device);
-        if (t->devpath)
-            free(t->devpath);
+        if (t->product) free(t->product);
+        if (t->serial) free(t->serial);
+        if (t->model) free(t->model);
+        if (t->device) free(t->device);
+        if (t->devpath) free(t->devpath);
 
         delete t;
 
@@ -538,10 +505,7 @@
         t->transport_socket = s[0];
         t->fd = s[1];
 
-        fdevent_install(&(t->transport_fde),
-                        t->transport_socket,
-                        transport_socket_events,
-                        t);
+        fdevent_install(&(t->transport_fde), t->transport_socket, transport_socket_events, t);
 
         fdevent_set(&(t->transport_fde), FDE_READ);
 
@@ -554,19 +518,19 @@
         }
     }
 
-    adb_mutex_lock(&transport_lock);
-    pending_list.remove(t);
-    transport_list.push_front(t);
-    adb_mutex_unlock(&transport_lock);
+    {
+        std::lock_guard<std::mutex> lock(transport_lock);
+        pending_list.remove(t);
+        transport_list.push_front(t);
+    }
 
     update_transports();
 }
 
-void init_transport_registration(void)
-{
+void init_transport_registration(void) {
     int s[2];
 
-    if(adb_socketpair(s)){
+    if (adb_socketpair(s)) {
         fatal_errno("cannot open transport registration socketpair");
     }
     D("socketpair: (%d,%d)", s[0], s[1]);
@@ -574,41 +538,37 @@
     transport_registration_send = s[0];
     transport_registration_recv = s[1];
 
-    fdevent_install(&transport_registration_fde,
-                    transport_registration_recv,
-                    transport_registration_func,
-                    0);
+    fdevent_install(&transport_registration_fde, transport_registration_recv,
+                    transport_registration_func, 0);
 
     fdevent_set(&transport_registration_fde, FDE_READ);
 }
 
 /* the fdevent select pump is single threaded */
-static void register_transport(atransport *transport)
-{
+static void register_transport(atransport* transport) {
     tmsg m;
     m.transport = transport;
     m.action = 1;
     D("transport: %s registered", transport->serial);
-    if(transport_write_action(transport_registration_send, &m)) {
+    if (transport_write_action(transport_registration_send, &m)) {
         fatal_errno("cannot write transport registration socket\n");
     }
 }
 
-static void remove_transport(atransport *transport)
-{
+static void remove_transport(atransport* transport) {
     tmsg m;
     m.transport = transport;
     m.action = 0;
     D("transport: %s removed", transport->serial);
-    if(transport_write_action(transport_registration_send, &m)) {
+    if (transport_write_action(transport_registration_send, &m)) {
         fatal_errno("cannot write transport registration socket\n");
     }
 }
 
-
 static void transport_unref(atransport* t) {
     CHECK(t != nullptr);
-    adb_mutex_lock(&transport_lock);
+
+    std::lock_guard<std::mutex> lock(transport_lock);
     CHECK_GT(t->ref_count, 0u);
     t->ref_count--;
     if (t->ref_count == 0) {
@@ -618,40 +578,33 @@
     } else {
         D("transport: %s unref (count=%zu)", t->serial, t->ref_count);
     }
-    adb_mutex_unlock(&transport_lock);
 }
 
-static int qual_match(const char *to_test,
-                      const char *prefix, const char *qual, bool sanitize_qual)
-{
-    if (!to_test || !*to_test)
-        /* Return true if both the qual and to_test are null strings. */
+static int qual_match(const char* to_test, const char* prefix, const char* qual,
+                      bool sanitize_qual) {
+    if (!to_test || !*to_test) /* Return true if both the qual and to_test are null strings. */
         return !qual || !*qual;
 
-    if (!qual)
-        return 0;
+    if (!qual) return 0;
 
     if (prefix) {
         while (*prefix) {
-            if (*prefix++ != *to_test++)
-                return 0;
+            if (*prefix++ != *to_test++) return 0;
         }
     }
 
     while (*qual) {
         char ch = *qual++;
-        if (sanitize_qual && !isalnum(ch))
-            ch = '_';
-        if (ch != *to_test++)
-            return 0;
+        if (sanitize_qual && !isalnum(ch)) ch = '_';
+        if (ch != *to_test++) return 0;
     }
 
     /* Everything matched so far.  Return true if *to_test is a NUL. */
     return !*to_test;
 }
 
-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) {
     atransport* result = nullptr;
 
     if (serial) {
@@ -664,7 +617,7 @@
         *error_out = "no devices found";
     }
 
-    adb_mutex_lock(&transport_lock);
+    std::unique_lock<std::mutex> lock(transport_lock);
     for (const auto& t : transport_list) {
         if (t->connection_state == kCsNoPerm) {
 #if ADB_HOST
@@ -712,7 +665,7 @@
             }
         }
     }
-    adb_mutex_unlock(&transport_lock);
+    lock.unlock();
 
     // Don't return unauthorized devices; the caller can't do anything with them.
     if (result && result->connection_state == kCsUnauthorized) {
@@ -749,15 +702,24 @@
 
 const std::string atransport::connection_state_name() const {
     switch (connection_state) {
-        case kCsOffline: return "offline";
-        case kCsBootloader: return "bootloader";
-        case kCsDevice: return "device";
-        case kCsHost: return "host";
-        case kCsRecovery: return "recovery";
-        case kCsNoPerm: return UsbNoPermissionsShortHelpText();
-        case kCsSideload: return "sideload";
-        case kCsUnauthorized: return "unauthorized";
-        default: return "unknown";
+        case kCsOffline:
+            return "offline";
+        case kCsBootloader:
+            return "bootloader";
+        case kCsDevice:
+            return "device";
+        case kCsHost:
+            return "host";
+        case kCsRecovery:
+            return "recovery";
+        case kCsNoPerm:
+            return UsbNoPermissionsShortHelpText();
+        case kCsSideload:
+            return "sideload";
+        case kCsUnauthorized:
+            return "unauthorized";
+        default:
+            return "unknown";
     }
 }
 
@@ -783,8 +745,7 @@
 const FeatureSet& supported_features() {
     // Local static allocation to avoid global non-POD variables.
     static const FeatureSet* features = new FeatureSet{
-        kFeatureShell2,
-        kFeatureCmd
+        kFeatureShell2, kFeatureCmd, kFeatureStat2,
         // Increment ADB_SERVER_VERSION whenever the feature list changes to
         // make sure that the adb client and server features stay in sync
         // (http://b/24370690).
@@ -802,14 +763,12 @@
         return FeatureSet();
     }
 
-    auto names = android::base::Split(features_string,
-                                      {kFeatureStringDelimiter});
+    auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
     return FeatureSet(names.begin(), names.end());
 }
 
 bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
-    return feature_set.count(feature) > 0 &&
-            supported_features().count(feature) > 0;
+    return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
 }
 
 bool atransport::has_feature(const std::string& feature) const {
@@ -845,21 +804,20 @@
 
             // For fastboot compatibility, ignore protocol prefixes.
             if (android::base::StartsWith(target, "tcp:") ||
-                    android::base::StartsWith(target, "udp:")) {
+                android::base::StartsWith(target, "udp:")) {
                 local_target_ptr += 4;
             }
 
             // Parse our |serial| and the given |target| to check if the hostnames and ports match.
             std::string serial_host, error;
             int serial_port = -1;
-            if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr,
-                                               &error)) {
+            if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
                 // |target| may omit the port to default to ours.
                 std::string target_host;
                 int target_port = serial_port;
                 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
                                                    nullptr, &error) &&
-                        serial_host == target_host && serial_port == target_port) {
+                    serial_host == target_host && serial_port == target_port) {
                     return true;
                 }
             }
@@ -874,8 +832,8 @@
 
 #if ADB_HOST
 
-static void append_transport_info(std::string* result, const char* key,
-                                  const char* value, bool sanitize) {
+static void append_transport_info(std::string* result, const char* key, const char* value,
+                                  bool sanitize) {
     if (value == nullptr || *value == '\0') {
         return;
     }
@@ -888,8 +846,7 @@
     }
 }
 
-static void append_transport(const atransport* t, std::string* result,
-                             bool long_listing) {
+static void append_transport(const atransport* t, std::string* result, bool long_listing) {
     const char* serial = t->serial;
     if (!serial || !serial[0]) {
         serial = "(no serial number)";
@@ -900,8 +857,7 @@
         *result += '\t';
         *result += t->connection_state_name();
     } else {
-        android::base::StringAppendF(result, "%-22s %s", serial,
-                                     t->connection_state_name().c_str());
+        android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
 
         append_transport_info(result, "", t->devpath, false);
         append_transport_info(result, "product:", t->product, false);
@@ -913,25 +869,30 @@
 
 std::string list_transports(bool long_listing) {
     std::string result;
-    adb_mutex_lock(&transport_lock);
+
+    std::lock_guard<std::mutex> lock(transport_lock);
     for (const auto& t : transport_list) {
         append_transport(t, &result, long_listing);
     }
-    adb_mutex_unlock(&transport_lock);
     return result;
 }
 
+void close_usb_devices(std::function<bool(const atransport*)> predicate) {
+    std::lock_guard<std::mutex> lock(transport_lock);
+    for (auto& t : transport_list) {
+        if (predicate(t)) {
+            t->Kick();
+        }
+    }
+}
+
 /* hack for osx */
 void close_usb_devices() {
-    adb_mutex_lock(&transport_lock);
-    for (const auto& t : transport_list) {
-        t->Kick();
-    }
-    adb_mutex_unlock(&transport_lock);
+    close_usb_devices([](const atransport*) { return true; });
 }
-#endif // ADB_HOST
+#endif  // ADB_HOST
 
-int register_socket_transport(int s, const char *serial, int port, int local) {
+int register_socket_transport(int s, const char* serial, int port, int local) {
     atransport* t = new atransport();
 
     if (!serial) {
@@ -946,10 +907,11 @@
         return -1;
     }
 
-    adb_mutex_lock(&transport_lock);
+    std::unique_lock<std::mutex> lock(transport_lock);
     for (const auto& transport : pending_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
-            adb_mutex_unlock(&transport_lock);
+            VLOG(TRANSPORT) << "socket transport " << transport->serial
+                            << " is already in pending_list and fails to register";
             delete t;
             return -1;
         }
@@ -957,7 +919,8 @@
 
     for (const auto& transport : transport_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
-            adb_mutex_unlock(&transport_lock);
+            VLOG(TRANSPORT) << "socket transport " << transport->serial
+                            << " is already in transport_list and fails to register";
             delete t;
             return -1;
         }
@@ -965,33 +928,32 @@
 
     pending_list.push_front(t);
     t->serial = strdup(serial);
-    adb_mutex_unlock(&transport_lock);
+
+    lock.unlock();
 
     register_transport(t);
     return 0;
 }
 
 #if ADB_HOST
-atransport *find_transport(const char *serial) {
+atransport* find_transport(const char* serial) {
     atransport* result = nullptr;
 
-    adb_mutex_lock(&transport_lock);
+    std::lock_guard<std::mutex> lock(transport_lock);
     for (auto& t : transport_list) {
         if (t->serial && strcmp(serial, t->serial) == 0) {
             result = t;
             break;
         }
     }
-    adb_mutex_unlock(&transport_lock);
 
     return result;
 }
 
 void kick_all_tcp_devices() {
-    adb_mutex_lock(&transport_lock);
+    std::lock_guard<std::mutex> lock(transport_lock);
     for (auto& t : transport_list) {
-        // TCP/IP devices have adb_port == 0.
-        if (t->type == kTransportLocal && t->adb_port == 0) {
+        if (t->IsTcpDevice()) {
             // Kicking breaks the read_transport thread of this transport out of any read, then
             // the read_transport thread will notify the main thread to make this transport
             // offline. Then the main thread will notify the write_transport thread to exit.
@@ -999,19 +961,17 @@
             t->Kick();
         }
     }
-    adb_mutex_unlock(&transport_lock);
 }
 
 #endif
 
-void register_usb_transport(usb_handle* usb, const char* serial,
-                            const char* devpath, unsigned writeable) {
+void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
+                            unsigned writeable) {
     atransport* t = new atransport();
 
-    D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb,
-      serial ? serial : "");
+    D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
     init_usb_transport(t, usb, (writeable ? kCsOffline : kCsNoPerm));
-    if(serial) {
+    if (serial) {
         t->serial = strdup(serial);
     }
 
@@ -1019,53 +979,49 @@
         t->devpath = strdup(devpath);
     }
 
-    adb_mutex_lock(&transport_lock);
-    pending_list.push_front(t);
-    adb_mutex_unlock(&transport_lock);
+    {
+        std::lock_guard<std::mutex> lock(transport_lock);
+        pending_list.push_front(t);
+    }
 
     register_transport(t);
 }
 
 // This should only be used for transports with connection_state == kCsNoPerm.
-void unregister_usb_transport(usb_handle *usb) {
-    adb_mutex_lock(&transport_lock);
-    transport_list.remove_if([usb](atransport* t) {
-        return t->usb == usb && t->connection_state == kCsNoPerm;
-    });
-    adb_mutex_unlock(&transport_lock);
+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; });
 }
 
-int check_header(apacket *p, atransport *t)
-{
-    if(p->msg.magic != (p->msg.command ^ 0xffffffff)) {
+int check_header(apacket* p, atransport* t) {
+    if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
         VLOG(RWX) << "check_header(): invalid magic";
         return -1;
     }
 
-    if(p->msg.data_length > t->get_max_payload()) {
-        VLOG(RWX) << "check_header(): " << p->msg.data_length << " atransport::max_payload = "
-                  << t->get_max_payload();
+    if (p->msg.data_length > t->get_max_payload()) {
+        VLOG(RWX) << "check_header(): " << p->msg.data_length
+                  << " atransport::max_payload = " << t->get_max_payload();
         return -1;
     }
 
     return 0;
 }
 
-int check_data(apacket *p)
-{
-    unsigned count, sum;
-    unsigned char *x;
-
-    count = p->msg.data_length;
-    x = p->data;
-    sum = 0;
-    while(count-- > 0) {
-        sum += *x++;
-    }
-
-    if(sum != p->msg.data_check) {
+int check_data(apacket* p) {
+    if (calculate_apacket_checksum(p) != p->msg.data_check) {
         return -1;
-    } else {
-        return 0;
     }
+    return 0;
 }
+
+#if ADB_HOST
+std::shared_ptr<RSA> atransport::NextKey() {
+    if (keys_.empty()) keys_ = adb_auth_get_private_keys();
+
+    std::shared_ptr<RSA> result = keys_[0];
+    keys_.pop_front();
+    return result;
+}
+#endif
diff --git a/adb/transport.h b/adb/transport.h
index 35d7b50..4d97fc7 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -19,12 +19,17 @@
 
 #include <sys/types.h>
 
+#include <deque>
+#include <functional>
 #include <list>
+#include <memory>
 #include <string>
 #include <unordered_set>
 
 #include "adb.h"
 
+#include <openssl/rsa.h>
+
 typedef std::unordered_set<std::string> FeatureSet;
 
 const FeatureSet& supported_features();
@@ -41,6 +46,9 @@
 extern const char* const kFeatureShell2;
 // The 'cmd' command is available
 extern const char* const kFeatureCmd;
+extern const char* const kFeatureStat2;
+// The server is running with libusb enabled.
+extern const char* const kFeatureLibusb;
 
 class atransport {
 public:
@@ -87,10 +95,28 @@
     char* model = nullptr;
     char* device = nullptr;
     char* devpath = nullptr;
-    int adb_port = -1;  // Use for emulators (local transport)
+    void SetLocalPortForEmulator(int port) {
+        CHECK_EQ(local_port_for_emulator_, -1);
+        local_port_for_emulator_ = port;
+    }
 
-    void* key = nullptr;
-    unsigned char token[TOKEN_SIZE] = {};
+    bool GetLocalPortForEmulator(int* port) const {
+        if (type == kTransportLocal && local_port_for_emulator_ != -1) {
+            *port = local_port_for_emulator_;
+            return true;
+        }
+        return false;
+    }
+
+    bool IsTcpDevice() const {
+        return type == kTransportLocal && local_port_for_emulator_ == -1;
+    }
+
+#if ADB_HOST
+    std::shared_ptr<RSA> NextKey();
+#endif
+
+    char token[TOKEN_SIZE] = {};
     size_t failed_auth_attempts = 0;
 
     const std::string connection_state_name() const;
@@ -128,6 +154,7 @@
     bool MatchesTarget(const std::string& target) const;
 
 private:
+    int local_port_for_emulator_ = -1;
     bool kicked_ = false;
     void (*kick_func_)(atransport*) = nullptr;
 
@@ -140,6 +167,10 @@
     // A list of adisconnect callbacks called when the transport is kicked.
     std::list<adisconnect*> disconnects_;
 
+#if ADB_HOST
+    std::deque<std::shared_ptr<RSA>> keys_;
+#endif
+
     DISALLOW_COPY_AND_ASSIGN(atransport);
 };
 
@@ -156,6 +187,7 @@
 void update_transports(void);
 
 void init_transport_registration(void);
+void init_mdns_transport_discovery(void);
 std::string list_transports(bool long_listing);
 atransport* find_transport(const char* serial);
 void kick_all_tcp_devices();
@@ -163,6 +195,9 @@
 void register_usb_transport(usb_handle* h, const char* serial,
                             const char* devpath, unsigned writeable);
 
+/* Connect to a network address and register it as a device */
+void connect_device(const std::string& address, std::string* response);
+
 /* cause new transports to be init'd and added to the list */
 int register_socket_transport(int s, const char* serial, int port, int local);
 
@@ -172,8 +207,8 @@
 int check_header(apacket* p, atransport* t);
 int check_data(apacket* p);
 
-/* for MacOS X cleanup */
 void close_usb_devices();
+void close_usb_devices(std::function<bool(const atransport*)> predicate);
 
 void send_packet(apacket* p, atransport* t);
 
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index 1f5a258..4198a52 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -25,16 +25,23 @@
 #include <string.h>
 #include <sys/types.h>
 
+#include <condition_variable>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+#include <android-base/parsenetaddress.h>
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
 
 #if !ADB_HOST
-#include "cutils/properties.h"
+#include <android-base/properties.h>
 #endif
 
 #include "adb.h"
 #include "adb_io.h"
 #include "adb_utils.h"
+#include "sysdeps/chrono.h"
 
 #if ADB_HOST
 
@@ -44,7 +51,7 @@
 // connected.
 #define ADB_LOCAL_TRANSPORT_MAX 16
 
-ADB_MUTEX_DEFINE(local_transports_lock);
+static std::mutex& local_transports_lock = *new std::mutex();
 
 /* we keep a list of opened transports. The atransport struct knows to which
  * local transport it is connected. The list is used to detect when we're
@@ -90,11 +97,51 @@
     return 0;
 }
 
-void local_connect(int port) {
+bool local_connect(int port) {
     std::string dummy;
-    local_connect_arbitrary_ports(port-1, port, &dummy);
+    return local_connect_arbitrary_ports(port-1, port, &dummy) == 0;
 }
 
+void connect_device(const std::string& address, std::string* response) {
+    if (address.empty()) {
+        *response = "empty address";
+        return;
+    }
+
+    std::string serial;
+    std::string host;
+    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
+        return;
+    }
+
+    std::string error;
+    int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error);
+    if (fd == -1) {
+        *response = android::base::StringPrintf("unable to connect to %s: %s",
+                                                serial.c_str(), error.c_str());
+        return;
+    }
+
+    D("client: connected %s remote on fd %d", serial.c_str(), fd);
+    close_on_exec(fd);
+    disable_tcp_nagle(fd);
+
+    // Send a TCP keepalive ping to the device every second so we can detect disconnects.
+    if (!set_tcp_keepalive(fd, 1)) {
+        D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
+    }
+
+    int ret = register_socket_transport(fd, serial.c_str(), port, 0);
+    if (ret < 0) {
+        adb_close(fd);
+        *response = android::base::StringPrintf("already connected to %s", serial.c_str());
+    } else {
+        *response = android::base::StringPrintf("connected to %s", serial.c_str());
+    }
+}
+
+
 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
     int fd = -1;
 
@@ -127,18 +174,71 @@
 }
 
 #if ADB_HOST
+
+static void PollAllLocalPortsForEmulator() {
+    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    int count = ADB_LOCAL_TRANSPORT_MAX;
+
+    // Try to connect to any number of running emulator instances.
+    for ( ; count > 0; count--, port += 2 ) {
+        local_connect(port);
+    }
+}
+
+// Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
+constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
+constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s;
+
+struct RetryPort {
+    int port;
+    uint32_t retry_count;
+};
+
+// Retry emulators just kicked.
+static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
+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) {
     adb_thread_setname("client_socket_thread");
     D("transport: client_socket_thread() starting");
+    PollAllLocalPortsForEmulator();
     while (true) {
-        int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
-        int count = ADB_LOCAL_TRANSPORT_MAX;
-
-        // Try to connect to any number of running emulator instances.
-        for ( ; count > 0; count--, port += 2 ) {
-            local_connect(port);
+        std::vector<RetryPort> ports;
+        // Collect retry ports.
+        {
+            std::unique_lock<std::mutex> lock(retry_ports_lock);
+            while (retry_ports.empty()) {
+                retry_ports_cond.wait(lock);
+            }
+            retry_ports.swap(ports);
         }
-        sleep(1);
+        // Sleep here instead of the end of loop, because if we immediately try to reconnect
+        // the emulator just kicked, the adbd on the emulator may not have time to remove the
+        // just kicked transport.
+        std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL);
+
+        // Try connecting retry ports.
+        std::vector<RetryPort> next_ports;
+        for (auto& port : ports) {
+            VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
+                << port.retry_count;
+            if (local_connect(port.port)) {
+                VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
+                continue;
+            }
+            if (--port.retry_count > 0) {
+                next_ports.push_back(port);
+            } else {
+                VLOG(TRANSPORT) << "stop retrying port " << port.port;
+            }
+        }
+
+        // Copy back left retry ports.
+        {
+            std::unique_lock<std::mutex> lock(retry_ports_lock);
+            retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
+        }
     }
 }
 
@@ -146,9 +246,6 @@
 
 static void server_socket_thread(void* arg) {
     int serverfd, fd;
-    sockaddr_storage ss;
-    sockaddr *addrp = reinterpret_cast<sockaddr*>(&ss);
-    socklen_t alen;
     int port = (int) (uintptr_t) arg;
 
     adb_thread_setname("server socket");
@@ -160,20 +257,22 @@
             serverfd = network_inaddr_any_server(port, SOCK_STREAM, &error);
             if(serverfd < 0) {
                 D("server: cannot bind socket yet: %s", error.c_str());
-                adb_sleep_ms(1000);
+                std::this_thread::sleep_for(1s);
                 continue;
             }
             close_on_exec(serverfd);
         }
 
-        alen = sizeof(ss);
         D("server: trying to get new connection from %d", port);
-        fd = adb_socket_accept(serverfd, addrp, &alen);
+        fd = adb_socket_accept(serverfd, nullptr, nullptr);
         if(fd >= 0) {
             D("server: new connection on fd %d", fd);
             close_on_exec(fd);
             disable_tcp_nagle(fd);
-            register_socket_transport(fd, "host", port, 1);
+            std::string serial = android::base::StringPrintf("host-%d", fd);
+            if (register_socket_transport(fd, serial.c_str(), port, 1) != 0) {
+                adb_close(fd);
+            }
         }
     }
     D("transport: server_socket_thread() exiting");
@@ -182,16 +281,20 @@
 /* This is relevant only for ADB daemon running inside the emulator. */
 /*
  * Redefine open and write for qemu_pipe.h that contains inlined references
- * to those routines. We will redifine them back after qemu_pipe.h inclusion.
+ * to those routines. We will redefine them back after qemu_pipe.h inclusion.
  */
 #undef open
+#undef read
 #undef write
 #define open    adb_open
+#define read    adb_read
 #define write   adb_write
-#include <hardware/qemu_pipe.h>
+#include <system/qemu_pipe.h>
 #undef open
+#undef read
 #undef write
 #define open    ___xxx_open
+#define read    ___xxx_read
 #define write   ___xxx_write
 
 /* A worker thread that monitors host connections, and registers a transport for
@@ -239,7 +342,7 @@
     D("transport: qemu_socket_thread() starting");
 
     /* adb QEMUD service connection request. */
-    snprintf(con_name, sizeof(con_name), "qemud:adb:%d", port);
+    snprintf(con_name, sizeof(con_name), "pipe:qemud:adb:%d", port);
 
     /* Connect to the adb QEMUD service. */
     fd = qemu_pipe_open(con_name);
@@ -267,8 +370,8 @@
                 /* Host is connected. Register the transport, and start the
                  * exchange. */
                 std::string serial = android::base::StringPrintf("host-%d", fd);
-                register_socket_transport(fd, serial.c_str(), port, 1);
-                if (!WriteFdExactly(fd, _start_req, strlen(_start_req))) {
+                if (register_socket_transport(fd, serial.c_str(), port, 1) != 0 ||
+                    !WriteFdExactly(fd, _start_req, strlen(_start_req))) {
                     adb_close(fd);
                 }
             }
@@ -298,15 +401,13 @@
     func = client_socket_thread;
     debug_name = "client";
 #else
-    /* For the adbd daemon in the system image we need to distinguish
-     * between the device, and the emulator. */
-    char is_qemu[PROPERTY_VALUE_MAX];
-    property_get("ro.kernel.qemu", is_qemu, "");
-    if (!strcmp(is_qemu, "1")) {
-        /* Running inside the emulator: use QEMUD pipe as the transport. */
+    // For the adbd daemon in the system image we need to distinguish
+    // between the device, and the emulator.
+    if (android::base::GetBoolProperty("ro.kernel.qemu", false)) {
+        // Running inside the emulator: use QEMUD pipe as the transport.
         func = qemu_socket_thread;
     } else {
-        /* Running inside the device: use TCP socket as the transport. */
+        // Running inside the device: use TCP socket as the transport.
         func = server_socket_thread;
     }
     debug_name = "server";
@@ -327,14 +428,13 @@
 
 #if ADB_HOST
     int  nn;
-    adb_mutex_lock( &local_transports_lock );
+    std::lock_guard<std::mutex> lock(local_transports_lock);
     for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) {
         if (local_transports[nn] == t) {
             local_transports[nn] = NULL;
             break;
         }
     }
-    adb_mutex_unlock( &local_transports_lock );
 #endif
 }
 
@@ -345,17 +445,32 @@
         t->sfd = -1;
         adb_close(fd);
     }
+#if ADB_HOST
+    int local_port;
+    if (t->GetLocalPortForEmulator(&local_port)) {
+        VLOG(TRANSPORT) << "remote_close, local_port = " << local_port;
+        std::unique_lock<std::mutex> lock(retry_ports_lock);
+        RetryPort port;
+        port.port = local_port;
+        port.retry_count = LOCAL_PORT_RETRY_COUNT;
+        retry_ports.push_back(port);
+        retry_ports_cond.notify_one();
+    }
+#endif
 }
 
 
 #if ADB_HOST
 /* Only call this function if you already hold local_transports_lock. */
-atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
+static atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
 {
     int i;
     for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
-        if (local_transports[i] && local_transports[i]->adb_port == adb_port) {
-            return local_transports[i];
+        int local_port;
+        if (local_transports[i] && local_transports[i]->GetLocalPortForEmulator(&local_port)) {
+            if (local_port == adb_port) {
+                return local_transports[i];
+            }
         }
     }
     return NULL;
@@ -368,9 +483,8 @@
 
 atransport* find_emulator_transport_by_adb_port(int adb_port)
 {
-    adb_mutex_lock( &local_transports_lock );
+    std::lock_guard<std::mutex> lock(local_transports_lock);
     atransport* result = find_emulator_transport_by_adb_port_locked(adb_port);
-    adb_mutex_unlock( &local_transports_lock );
     return result;
 }
 
@@ -394,9 +508,8 @@
 
 int get_available_local_transport_index()
 {
-    adb_mutex_lock( &local_transports_lock );
+    std::lock_guard<std::mutex> lock(local_transports_lock);
     int result = get_available_local_transport_index_locked();
-    adb_mutex_unlock( &local_transports_lock );
     return result;
 }
 #endif
@@ -413,30 +526,23 @@
     t->sync_token = 1;
     t->connection_state = kCsOffline;
     t->type = kTransportLocal;
-    t->adb_port = 0;
 
 #if ADB_HOST
     if (local) {
-        adb_mutex_lock( &local_transports_lock );
-        {
-            t->adb_port = adb_port;
-            atransport* existing_transport =
-                    find_emulator_transport_by_adb_port_locked(adb_port);
-            int index = get_available_local_transport_index_locked();
-            if (existing_transport != NULL) {
-                D("local transport for port %d already registered (%p)?",
-                adb_port, existing_transport);
-                fail = -1;
-            } else if (index < 0) {
-                // Too many emulators.
-                D("cannot register more emulators. Maximum is %d",
-                        ADB_LOCAL_TRANSPORT_MAX);
-                fail = -1;
-            } else {
-                local_transports[index] = t;
-            }
-       }
-       adb_mutex_unlock( &local_transports_lock );
+        std::lock_guard<std::mutex> lock(local_transports_lock);
+        t->SetLocalPortForEmulator(adb_port);
+        atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port);
+        int index = get_available_local_transport_index_locked();
+        if (existing_transport != NULL) {
+            D("local transport for port %d already registered (%p)?", adb_port, existing_transport);
+            fail = -1;
+        } else if (index < 0) {
+            // Too many emulators.
+            D("cannot register more emulators. Maximum is %d", ADB_LOCAL_TRANSPORT_MAX);
+            fail = -1;
+        } else {
+            local_transports[index] = t;
+        }
     }
 #endif
     return fail;
diff --git a/adb/transport_mdns.cpp b/adb/transport_mdns.cpp
new file mode 100644
index 0000000..e49b1c6
--- /dev/null
+++ b/adb/transport_mdns.cpp
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+#define TRACE_TAG TRANSPORT
+
+#include "transport.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <arpa/inet.h>
+#endif
+
+#include <android-base/stringprintf.h>
+#include <dns_sd.h>
+
+#include "adb_mdns.h"
+#include "adb_trace.h"
+#include "fdevent.h"
+#include "sysdeps.h"
+
+static DNSServiceRef service_ref;
+static fdevent service_ref_fde;
+
+// Use adb_DNSServiceRefSockFD() instead of calling DNSServiceRefSockFD()
+// directly so that the socket is put through the appropriate compatibility
+// layers to work with the rest of ADB's internal APIs.
+static inline int adb_DNSServiceRefSockFD(DNSServiceRef ref) {
+    return adb_register_socket(DNSServiceRefSockFD(ref));
+}
+#define DNSServiceRefSockFD ___xxx_DNSServiceRefSockFD
+
+static void DNSSD_API register_service_ip(DNSServiceRef sdRef,
+                                          DNSServiceFlags flags,
+                                          uint32_t interfaceIndex,
+                                          DNSServiceErrorType errorCode,
+                                          const char* hostname,
+                                          const sockaddr* address,
+                                          uint32_t ttl,
+                                          void* context);
+
+static void pump_service_ref(int /*fd*/, unsigned ev, void* data) {
+    DNSServiceRef* ref = reinterpret_cast<DNSServiceRef*>(data);
+
+    if (ev & FDE_READ)
+        DNSServiceProcessResult(*ref);
+}
+
+class AsyncServiceRef {
+  public:
+    bool Initialized() {
+        return initialized_;
+    }
+
+    virtual ~AsyncServiceRef() {
+        if (! initialized_) {
+            return;
+        }
+
+        DNSServiceRefDeallocate(sdRef_);
+        fdevent_remove(&fde_);
+    }
+
+  protected:
+    DNSServiceRef sdRef_;
+
+    void Initialize() {
+        fdevent_install(&fde_, adb_DNSServiceRefSockFD(sdRef_),
+                        pump_service_ref, &sdRef_);
+        fdevent_set(&fde_, FDE_READ);
+        initialized_ = true;
+    }
+
+  private:
+    bool initialized_;
+    fdevent fde_;
+};
+
+class ResolvedService : public AsyncServiceRef {
+  public:
+    virtual ~ResolvedService() = default;
+
+    ResolvedService(std::string name, uint32_t interfaceIndex,
+                    const char* hosttarget, uint16_t port) :
+            name_(name),
+            port_(port) {
+
+        /* TODO: We should be able to get IPv6 support by adding
+         * kDNSServiceProtocol_IPv6 to the flags below. However, when we do
+         * this, we get served link-local addresses that are usually useless to
+         * connect to. What's more, we seem to /only/ get those and nothing else.
+         * If we want IPv6 in the future we'll have to figure out why.
+         */
+        DNSServiceErrorType ret =
+            DNSServiceGetAddrInfo(
+                &sdRef_, 0, interfaceIndex,
+                kDNSServiceProtocol_IPv4, hosttarget,
+                register_service_ip, reinterpret_cast<void*>(this));
+
+        if (ret != kDNSServiceErr_NoError) {
+            D("Got %d from DNSServiceGetAddrInfo.", ret);
+        } else {
+            Initialize();
+        }
+    }
+
+    void Connect(const sockaddr* address) {
+        char ip_addr[INET6_ADDRSTRLEN];
+        const void* ip_addr_data;
+        const char* addr_format;
+
+        if (address->sa_family == AF_INET) {
+            ip_addr_data =
+                &reinterpret_cast<const sockaddr_in*>(address)->sin_addr;
+            addr_format = "%s:%hu";
+        } else if (address->sa_family == AF_INET6) {
+            ip_addr_data =
+                &reinterpret_cast<const sockaddr_in6*>(address)->sin6_addr;
+            addr_format = "[%s]:%hu";
+        } else { // Should be impossible
+            D("mDNS resolved non-IP address.");
+            return;
+        }
+
+        // Winsock version requires the const cast Because Microsoft.
+        if (!inet_ntop(address->sa_family, const_cast<void*>(ip_addr_data),
+                       ip_addr, INET6_ADDRSTRLEN)) {
+            D("Could not convert IP address to string.");
+            return;
+        }
+
+        std::string response;
+        connect_device(android::base::StringPrintf(addr_format, ip_addr, port_),
+                       &response);
+        D("Connect to %s (%s:%hu) : %s", name_.c_str(), ip_addr, port_,
+          response.c_str());
+    }
+
+  private:
+    std::string name_;
+    const uint16_t port_;
+};
+
+static void DNSSD_API register_service_ip(DNSServiceRef /*sdRef*/,
+                                          DNSServiceFlags /*flags*/,
+                                          uint32_t /*interfaceIndex*/,
+                                          DNSServiceErrorType /*errorCode*/,
+                                          const char* /*hostname*/,
+                                          const sockaddr* address,
+                                          uint32_t /*ttl*/,
+                                          void* context) {
+    D("Got IP for service.");
+    std::unique_ptr<ResolvedService> data(
+        reinterpret_cast<ResolvedService*>(context));
+    data->Connect(address);
+}
+
+static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
+                                                     DNSServiceFlags flags,
+                                                     uint32_t interfaceIndex,
+                                                     DNSServiceErrorType errorCode,
+                                                     const char* fullname,
+                                                     const char* hosttarget,
+                                                     uint16_t port,
+                                                     uint16_t txtLen,
+                                                     const unsigned char* txtRecord,
+                                                     void* context);
+
+class DiscoveredService : public AsyncServiceRef {
+  public:
+    DiscoveredService(uint32_t interfaceIndex, const char* serviceName,
+                      const char* regtype, const char* domain)
+        : serviceName_(serviceName) {
+
+        DNSServiceErrorType ret =
+            DNSServiceResolve(&sdRef_, 0, interfaceIndex, serviceName, regtype,
+                              domain, register_resolved_mdns_service,
+                              reinterpret_cast<void*>(this));
+
+        if (ret != kDNSServiceErr_NoError) {
+            D("Got %d from DNSServiceResolve.", ret);
+        } else {
+            Initialize();
+        }
+    }
+
+    const char* ServiceName() {
+        return serviceName_.c_str();
+    }
+
+  private:
+    std::string serviceName_;
+};
+
+static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
+                                                     DNSServiceFlags flags,
+                                                     uint32_t interfaceIndex,
+                                                     DNSServiceErrorType errorCode,
+                                                     const char* fullname,
+                                                     const char* hosttarget,
+                                                     uint16_t port,
+                                                     uint16_t /*txtLen*/,
+                                                     const unsigned char* /*txtRecord*/,
+                                                     void* context) {
+    D("Resolved a service.");
+    std::unique_ptr<DiscoveredService> discovered(
+        reinterpret_cast<DiscoveredService*>(context));
+
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got error %d resolving service.", errorCode);
+        return;
+    }
+
+
+    auto resolved =
+        new ResolvedService(discovered->ServiceName(),
+                            interfaceIndex, hosttarget, ntohs(port));
+
+    if (! resolved->Initialized()) {
+        delete resolved;
+    }
+
+    if (flags) { /* Only ever equals MoreComing or 0 */
+        discovered.release();
+    }
+}
+
+static void DNSSD_API register_mdns_transport(DNSServiceRef sdRef,
+                                              DNSServiceFlags flags,
+                                              uint32_t interfaceIndex,
+                                              DNSServiceErrorType errorCode,
+                                              const char* serviceName,
+                                              const char* regtype,
+                                              const char* domain,
+                                              void*  /*context*/) {
+    D("Registering a transport.");
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got error %d during mDNS browse.", errorCode);
+        DNSServiceRefDeallocate(sdRef);
+        fdevent_remove(&service_ref_fde);
+        return;
+    }
+
+    auto discovered = new DiscoveredService(interfaceIndex, serviceName,
+                                            regtype, domain);
+
+    if (! discovered->Initialized()) {
+        delete discovered;
+    }
+}
+
+void init_mdns_transport_discovery(void) {
+    DNSServiceErrorType errorCode =
+        DNSServiceBrowse(&service_ref, 0, 0, kADBServiceType, nullptr,
+                         register_mdns_transport, nullptr);
+
+    if (errorCode != kDNSServiceErr_NoError) {
+        D("Got %d initiating mDNS browse.", errorCode);
+        return;
+    }
+
+    fdevent_install(&service_ref_fde,
+                    adb_DNSServiceRefSockFD(service_ref),
+                    pump_service_ref,
+                    &service_ref);
+    fdevent_set(&service_ref_fde, FDE_READ);
+}
diff --git a/adb/transport_mdns_unsupported.cpp b/adb/transport_mdns_unsupported.cpp
new file mode 100644
index 0000000..387d341
--- /dev/null
+++ b/adb/transport_mdns_unsupported.cpp
@@ -0,0 +1,18 @@
+/*
+ * 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.
+ */
+
+/* For when mDNS discovery is unsupported */
+void init_mdns_transport_discovery(void) {}
diff --git a/adb/transport_test.cpp b/adb/transport_test.cpp
index a6db07a..8b38e03 100644
--- a/adb/transport_test.cpp
+++ b/adb/transport_test.cpp
@@ -20,27 +20,6 @@
 
 #include "adb.h"
 
-class TransportSetup {
-public:
-  TransportSetup() {
-#ifdef _WIN32
-    // Use extern instead of including sysdeps.h which brings in various macros
-    // that conflict with APIs used in this file.
-    extern void adb_sysdeps_init(void);
-    adb_sysdeps_init();
-#else
-    // adb_sysdeps_init() is an inline function that we cannot link against.
-#endif
-  }
-};
-
-// Static initializer will call adb_sysdeps_init() before main() to initialize
-// the transport mutex before it is used in the tests. Alternatives would be to
-// use __attribute__((constructor)) here or to use that or a static initializer
-// for adb_sysdeps_init() itself in sysdeps_win32.cpp (caveats of unclear
-// init order), or to use a test fixture whose SetUp() could do the init once.
-static TransportSetup g_TransportSetup;
-
 TEST(transport, kick_transport) {
   atransport t;
   static size_t kick_count;
diff --git a/adb/transport_usb.cpp b/adb/transport_usb.cpp
index d05d928..516b4f2 100644
--- a/adb/transport_usb.cpp
+++ b/adb/transport_usb.cpp
@@ -93,9 +93,16 @@
     t->usb = h;
 }
 
-#if ADB_HOST
-int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol)
+int is_adb_interface(int usb_class, int usb_subclass, int usb_protocol)
 {
     return (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS && usb_protocol == ADB_PROTOCOL);
 }
+
+bool should_use_libusb() {
+#if defined(_WIN32) || !ADB_HOST
+    return false;
+#else
+    static bool disable = getenv("ADB_LIBUSB") && strcmp(getenv("ADB_LIBUSB"), "0") == 0;
+    return !disable;
 #endif
+}
diff --git a/adb/usb.h b/adb/usb.h
new file mode 100644
index 0000000..ba70de4
--- /dev/null
+++ b/adb/usb.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+// USB host/client interface.
+
+#define ADB_USB_INTERFACE(handle_ref_type)                       \
+    void usb_init();                                             \
+    int usb_write(handle_ref_type h, const void* data, int len); \
+    int usb_read(handle_ref_type h, void* data, int len);        \
+    int usb_close(handle_ref_type h);                            \
+    void usb_kick(handle_ref_type h)
+
+#if defined(_WIN32) || !ADB_HOST
+// Windows and the daemon have a single implementation.
+
+struct usb_handle;
+ADB_USB_INTERFACE(usb_handle*);
+
+#else // linux host || darwin
+// Linux and Darwin clients have native and libusb implementations.
+
+namespace libusb {
+    struct usb_handle;
+    ADB_USB_INTERFACE(libusb::usb_handle*);
+}
+
+namespace native {
+    struct usb_handle;
+    ADB_USB_INTERFACE(native::usb_handle*);
+}
+
+// Empty base that both implementations' opaque handles inherit from.
+struct usb_handle {
+};
+
+ADB_USB_INTERFACE(::usb_handle*);
+
+#endif // linux host || darwin
+
+
+// USB device detection.
+int is_adb_interface(int usb_class, int usb_subclass, int usb_protocol);
+
+bool should_use_libusb();
diff --git a/adb/usb_linux.cpp b/adb/usb_linux.cpp
deleted file mode 100644
index 500898a..0000000
--- a/adb/usb_linux.cpp
+++ /dev/null
@@ -1,596 +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.
- */
-
-#define TRACE_TAG USB
-
-#include "sysdeps.h"
-
-#include <ctype.h>
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/usb/ch9.h>
-#include <linux/usbdevice_fs.h>
-#include <linux/version.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <chrono>
-#include <condition_variable>
-#include <list>
-#include <mutex>
-#include <string>
-
-#include <android-base/file.h>
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-
-#include "adb.h"
-#include "transport.h"
-
-using namespace std::literals;
-
-/* usb scan debugging is waaaay too verbose */
-#define DBGX(x...)
-
-struct usb_handle {
-    ~usb_handle() {
-      if (fd != -1) unix_close(fd);
-    }
-
-    std::string path;
-    int fd = -1;
-    unsigned char ep_in;
-    unsigned char ep_out;
-
-    unsigned zero_mask;
-    unsigned writeable = 1;
-
-    usbdevfs_urb urb_in;
-    usbdevfs_urb urb_out;
-
-    bool urb_in_busy = false;
-    bool urb_out_busy = false;
-    bool dead = false;
-
-    std::condition_variable cv;
-    std::mutex mutex;
-
-    // for garbage collecting disconnected devices
-    bool mark;
-
-    // ID of thread currently in REAPURB
-    pthread_t reaper_thread = 0;
-};
-
-static auto& g_usb_handles_mutex = *new std::mutex();
-static auto& g_usb_handles = *new std::list<usb_handle*>();
-
-static int is_known_device(const char* dev_name) {
-    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-    for (usb_handle* usb : g_usb_handles) {
-        if (usb->path == dev_name) {
-            // set mark flag to indicate this device is still alive
-            usb->mark = true;
-            return 1;
-        }
-    }
-    return 0;
-}
-
-static void kick_disconnected_devices() {
-    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-    // kick any devices in the device list that were not found in the device scan
-    for (usb_handle* usb : g_usb_handles) {
-        if (!usb->mark) {
-            usb_kick(usb);
-        } else {
-            usb->mark = false;
-        }
-    }
-}
-
-static inline bool contains_non_digit(const char* name) {
-    while (*name) {
-        if (!isdigit(*name++)) return true;
-    }
-    return false;
-}
-
-static void find_usb_device(const std::string& base,
-        void (*register_device_callback)
-                (const char*, const char*, unsigned char, unsigned char, int, int, unsigned))
-{
-    std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
-    if (!bus_dir) return;
-
-    dirent* de;
-    while ((de = readdir(bus_dir.get())) != 0) {
-        if (contains_non_digit(de->d_name)) continue;
-
-        std::string bus_name = base + "/" + de->d_name;
-
-        std::unique_ptr<DIR, int(*)(DIR*)> dev_dir(opendir(bus_name.c_str()), closedir);
-        if (!dev_dir) continue;
-
-        while ((de = readdir(dev_dir.get()))) {
-            unsigned char devdesc[4096];
-            unsigned char* bufptr = devdesc;
-            unsigned char* bufend;
-            struct usb_device_descriptor* device;
-            struct usb_config_descriptor* config;
-            struct usb_interface_descriptor* interface;
-            struct usb_endpoint_descriptor *ep1, *ep2;
-            unsigned zero_mask = 0;
-            unsigned vid, pid;
-
-            if (contains_non_digit(de->d_name)) continue;
-
-            std::string dev_name = bus_name + "/" + de->d_name;
-            if (is_known_device(dev_name.c_str())) {
-                continue;
-            }
-
-            int fd = unix_open(dev_name.c_str(), O_RDONLY | O_CLOEXEC);
-            if (fd == -1) {
-                continue;
-            }
-
-            size_t desclength = unix_read(fd, devdesc, sizeof(devdesc));
-            bufend = bufptr + desclength;
-
-                // should have device and configuration descriptors, and atleast two endpoints
-            if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
-                D("desclength %zu is too small", desclength);
-                unix_close(fd);
-                continue;
-            }
-
-            device = (struct usb_device_descriptor*)bufptr;
-            bufptr += USB_DT_DEVICE_SIZE;
-
-            if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
-                unix_close(fd);
-                continue;
-            }
-
-            vid = device->idVendor;
-            pid = device->idProduct;
-            DBGX("[ %s is V:%04x P:%04x ]\n", dev_name.c_str(), vid, pid);
-
-                // should have config descriptor next
-            config = (struct usb_config_descriptor *)bufptr;
-            bufptr += USB_DT_CONFIG_SIZE;
-            if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
-                D("usb_config_descriptor not found");
-                unix_close(fd);
-                continue;
-            }
-
-                // loop through all the descriptors and look for the ADB interface
-            while (bufptr < bufend) {
-                unsigned char length = bufptr[0];
-                unsigned char type = bufptr[1];
-
-                if (type == USB_DT_INTERFACE) {
-                    interface = (struct usb_interface_descriptor *)bufptr;
-                    bufptr += length;
-
-                    if (length != USB_DT_INTERFACE_SIZE) {
-                        D("interface descriptor has wrong size");
-                        break;
-                    }
-
-                    DBGX("bInterfaceClass: %d,  bInterfaceSubClass: %d,"
-                         "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
-                         interface->bInterfaceClass, interface->bInterfaceSubClass,
-                         interface->bInterfaceProtocol, interface->bNumEndpoints);
-
-                    if (interface->bNumEndpoints == 2 &&
-                            is_adb_interface(vid, pid, interface->bInterfaceClass,
-                            interface->bInterfaceSubClass, interface->bInterfaceProtocol))  {
-
-                        struct stat st;
-                        char pathbuf[128];
-                        char link[256];
-                        char *devpath = nullptr;
-
-                        DBGX("looking for bulk endpoints\n");
-                            // looks like ADB...
-                        ep1 = (struct usb_endpoint_descriptor *)bufptr;
-                        bufptr += USB_DT_ENDPOINT_SIZE;
-                            // For USB 3.0 SuperSpeed devices, skip potential
-                            // USB 3.0 SuperSpeed Endpoint Companion descriptor
-                        if (bufptr+2 <= devdesc + desclength &&
-                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
-                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
-                            bufptr += USB_DT_SS_EP_COMP_SIZE;
-                        }
-                        ep2 = (struct usb_endpoint_descriptor *)bufptr;
-                        bufptr += USB_DT_ENDPOINT_SIZE;
-                        if (bufptr+2 <= devdesc + desclength &&
-                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
-                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
-                            bufptr += USB_DT_SS_EP_COMP_SIZE;
-                        }
-
-                        if (bufptr > devdesc + desclength ||
-                            ep1->bLength != USB_DT_ENDPOINT_SIZE ||
-                            ep1->bDescriptorType != USB_DT_ENDPOINT ||
-                            ep2->bLength != USB_DT_ENDPOINT_SIZE ||
-                            ep2->bDescriptorType != USB_DT_ENDPOINT) {
-                            D("endpoints not found");
-                            break;
-                        }
-
-                            // both endpoints should be bulk
-                        if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
-                            ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
-                            D("bulk endpoints not found");
-                            continue;
-                        }
-                            /* aproto 01 needs 0 termination */
-                        if(interface->bInterfaceProtocol == 0x01) {
-                            zero_mask = ep1->wMaxPacketSize - 1;
-                        }
-
-                            // we have a match.  now we just need to figure out which is in and which is out.
-                        unsigned char local_ep_in, local_ep_out;
-                        if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
-                            local_ep_in = ep1->bEndpointAddress;
-                            local_ep_out = ep2->bEndpointAddress;
-                        } else {
-                            local_ep_in = ep2->bEndpointAddress;
-                            local_ep_out = ep1->bEndpointAddress;
-                        }
-
-                            // Determine the device path
-                        if (!fstat(fd, &st) && S_ISCHR(st.st_mode)) {
-                            snprintf(pathbuf, sizeof(pathbuf), "/sys/dev/char/%d:%d",
-                                     major(st.st_rdev), minor(st.st_rdev));
-                            ssize_t link_len = readlink(pathbuf, link, sizeof(link) - 1);
-                            if (link_len > 0) {
-                                link[link_len] = '\0';
-                                const char* slash = strrchr(link, '/');
-                                if (slash) {
-                                    snprintf(pathbuf, sizeof(pathbuf),
-                                             "usb:%s", slash + 1);
-                                    devpath = pathbuf;
-                                }
-                            }
-                        }
-
-                        register_device_callback(dev_name.c_str(), devpath,
-                                local_ep_in, local_ep_out,
-                                interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
-                        break;
-                    }
-                } else {
-                    bufptr += length;
-                }
-            } // end of while
-
-            unix_close(fd);
-        }
-    }
-}
-
-static int usb_bulk_write(usb_handle* h, const void* data, int len) {
-    std::unique_lock<std::mutex> lock(h->mutex);
-    D("++ usb_bulk_write ++");
-
-    usbdevfs_urb* urb = &h->urb_out;
-    memset(urb, 0, sizeof(*urb));
-    urb->type = USBDEVFS_URB_TYPE_BULK;
-    urb->endpoint = h->ep_out;
-    urb->status = -1;
-    urb->buffer = const_cast<void*>(data);
-    urb->buffer_length = len;
-
-    if (h->dead) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
-        return -1;
-    }
-
-    h->urb_out_busy = true;
-    while (true) {
-        auto now = std::chrono::system_clock::now();
-        if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
-            // TODO: call USBDEVFS_DISCARDURB?
-            errno = ETIMEDOUT;
-            return -1;
-        }
-        if (!h->urb_out_busy) {
-            if (urb->status != 0) {
-                errno = -urb->status;
-                return -1;
-            }
-            return urb->actual_length;
-        }
-    }
-}
-
-static int usb_bulk_read(usb_handle* h, void* data, int len) {
-    std::unique_lock<std::mutex> lock(h->mutex);
-    D("++ usb_bulk_read ++");
-
-    usbdevfs_urb* urb = &h->urb_in;
-    memset(urb, 0, sizeof(*urb));
-    urb->type = USBDEVFS_URB_TYPE_BULK;
-    urb->endpoint = h->ep_in;
-    urb->status = -1;
-    urb->buffer = data;
-    urb->buffer_length = len;
-
-    if (h->dead) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    if (TEMP_FAILURE_RETRY(ioctl(h->fd, USBDEVFS_SUBMITURB, urb)) == -1) {
-        return -1;
-    }
-
-    h->urb_in_busy = true;
-    while (true) {
-        D("[ reap urb - wait ]");
-        h->reaper_thread = pthread_self();
-        int fd = h->fd;
-        lock.unlock();
-
-        // This ioctl must not have TEMP_FAILURE_RETRY because we send SIGALRM to break out.
-        usbdevfs_urb* out = nullptr;
-        int res = ioctl(fd, USBDEVFS_REAPURB, &out);
-        int saved_errno = errno;
-
-        lock.lock();
-        h->reaper_thread = 0;
-        if (h->dead) {
-            errno = EINVAL;
-            return -1;
-        }
-        if (res < 0) {
-            if (saved_errno == EINTR) {
-                continue;
-            }
-            D("[ reap urb - error ]");
-            errno = saved_errno;
-            return -1;
-        }
-        D("[ urb @%p status = %d, actual = %d ]", out, out->status, out->actual_length);
-
-        if (out == &h->urb_in) {
-            D("[ reap urb - IN complete ]");
-            h->urb_in_busy = false;
-            if (urb->status != 0) {
-                errno = -urb->status;
-                return -1;
-            }
-            return urb->actual_length;
-        }
-        if (out == &h->urb_out) {
-            D("[ reap urb - OUT compelete ]");
-            h->urb_out_busy = false;
-            h->cv.notify_all();
-        }
-    }
-}
-
-
-int usb_write(usb_handle *h, const void *_data, int len)
-{
-    D("++ usb_write ++");
-
-    unsigned char *data = (unsigned char*) _data;
-    int n = usb_bulk_write(h, data, len);
-    if (n != len) {
-        D("ERROR: n = %d, errno = %d (%s)", n, errno, strerror(errno));
-        return -1;
-    }
-
-    if (h->zero_mask && !(len & h->zero_mask)) {
-        // If we need 0-markers and our transfer is an even multiple of the packet size,
-        // then send a zero marker.
-        return usb_bulk_write(h, _data, 0);
-    }
-
-    D("-- usb_write --");
-    return 0;
-}
-
-int usb_read(usb_handle *h, void *_data, int len)
-{
-    unsigned char *data = (unsigned char*) _data;
-    int n;
-
-    D("++ usb_read ++");
-    while(len > 0) {
-        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((errno == ETIMEDOUT) && (h->fd != -1)) {
-                D("[ timeout ]");
-                if(n > 0){
-                    data += n;
-                    len -= n;
-                }
-                continue;
-            }
-            D("ERROR: n = %d, errno = %d (%s)",
-                n, errno, strerror(errno));
-            return -1;
-        }
-
-        len -= xfer;
-        data += xfer;
-    }
-
-    D("-- usb_read --");
-    return 0;
-}
-
-void usb_kick(usb_handle* h) {
-    std::lock_guard<std::mutex> lock(h->mutex);
-    D("[ kicking %p (fd = %d) ]", h, h->fd);
-    if (!h->dead) {
-        h->dead = true;
-
-        if (h->writeable) {
-            /* HACK ALERT!
-            ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
-            ** This is a workaround for that problem.
-            */
-            if (h->reaper_thread) {
-                pthread_kill(h->reaper_thread, SIGALRM);
-            }
-
-            /* cancel any pending transactions
-            ** these will quietly fail if the txns are not active,
-            ** but this ensures that a reader blocked on REAPURB
-            ** will get unblocked
-            */
-            ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_in);
-            ioctl(h->fd, USBDEVFS_DISCARDURB, &h->urb_out);
-            h->urb_in.status = -ENODEV;
-            h->urb_out.status = -ENODEV;
-            h->urb_in_busy = false;
-            h->urb_out_busy = false;
-            h->cv.notify_all();
-        } else {
-            unregister_usb_transport(h);
-        }
-    }
-}
-
-int usb_close(usb_handle* h) {
-    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-    g_usb_handles.remove(h);
-
-    D("-- usb close %p (fd = %d) --", h, h->fd);
-
-    delete h;
-
-    return 0;
-}
-
-static void register_device(const char* dev_name, const char* dev_path,
-                            unsigned char ep_in, unsigned char ep_out,
-                            int interface, int serial_index,
-                            unsigned zero_mask) {
-    // Since Linux will not reassign the device ID (and dev_name) as long as the
-    // device is open, we can add to the list here once we open it and remove
-    // from the list when we're finally closed and everything will work out
-    // fine.
-    //
-    // If we have a usb_handle on the list of handles with a matching name, we
-    // have no further work to do.
-    {
-        std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-        for (usb_handle* usb: g_usb_handles) {
-            if (usb->path == dev_name) {
-                return;
-            }
-        }
-    }
-
-    D("[ usb located new device %s (%d/%d/%d) ]", dev_name, ep_in, ep_out, interface);
-    std::unique_ptr<usb_handle> usb(new usb_handle);
-    usb->path = dev_name;
-    usb->ep_in = ep_in;
-    usb->ep_out = ep_out;
-    usb->zero_mask = zero_mask;
-
-    // Initialize mark so we don't get garbage collected after the device scan.
-    usb->mark = true;
-
-    usb->fd = unix_open(usb->path.c_str(), O_RDWR | O_CLOEXEC);
-    if (usb->fd == -1) {
-        // Opening RW failed, so see if we have RO access.
-        usb->fd = unix_open(usb->path.c_str(), O_RDONLY | O_CLOEXEC);
-        if (usb->fd == -1) {
-            D("[ usb open %s failed: %s]", usb->path.c_str(), strerror(errno));
-            return;
-        }
-        usb->writeable = 0;
-    }
-
-    D("[ usb opened %s%s, fd=%d]",
-      usb->path.c_str(), (usb->writeable ? "" : " (read-only)"), usb->fd);
-
-    if (usb->writeable) {
-        if (ioctl(usb->fd, USBDEVFS_CLAIMINTERFACE, &interface) != 0) {
-            D("[ usb ioctl(%d, USBDEVFS_CLAIMINTERFACE) failed: %s]", usb->fd, strerror(errno));
-            return;
-        }
-    }
-
-    // Read the device's serial number.
-    std::string serial_path = android::base::StringPrintf(
-        "/sys/bus/usb/devices/%s/serial", dev_path + 4);
-    std::string serial;
-    if (!android::base::ReadFileToString(serial_path, &serial)) {
-        D("[ usb read %s failed: %s ]", serial_path.c_str(), strerror(errno));
-        // We don't actually want to treat an unknown serial as an error because
-        // devices aren't able to communicate a serial number in early bringup.
-        // http://b/20883914
-        serial = "";
-    }
-    serial = android::base::Trim(serial);
-
-    // Add to the end of the active handles.
-    usb_handle* done_usb = usb.release();
-    {
-        std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-        g_usb_handles.push_back(done_usb);
-    }
-    register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
-}
-
-static void device_poll_thread(void*) {
-    adb_thread_setname("device poll");
-    D("Created device thread");
-    while (true) {
-        // TODO: Use inotify.
-        find_usb_device("/dev/bus/usb", register_device);
-        kick_disconnected_devices();
-        sleep(1);
-    }
-}
-
-void usb_init() {
-    struct sigaction actions;
-    memset(&actions, 0, sizeof(actions));
-    sigemptyset(&actions.sa_mask);
-    actions.sa_flags = 0;
-    actions.sa_handler = [](int) {};
-    sigaction(SIGALRM, &actions, nullptr);
-
-    if (!adb_thread_create(device_poll_thread, nullptr)) {
-        fatal_errno("cannot create device_poll thread");
-    }
-}
diff --git a/adb/usb_linux_client.cpp b/adb/usb_linux_client.cpp
deleted file mode 100644
index 0ba6b4b..0000000
--- a/adb/usb_linux_client.cpp
+++ /dev/null
@@ -1,620 +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.
- */
-
-#define TRACE_TAG USB
-
-#include "sysdeps.h"
-
-#include <cutils/properties.h>
-#include <dirent.h>
-#include <errno.h>
-#include <linux/usb/ch9.h>
-#include <linux/usb/functionfs.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <algorithm>
-#include <atomic>
-
-#include <android-base/logging.h>
-
-#include "adb.h"
-#include "transport.h"
-
-#define MAX_PACKET_SIZE_FS	64
-#define MAX_PACKET_SIZE_HS	512
-#define MAX_PACKET_SIZE_SS	1024
-
-// Writes larger than 16k fail on some devices (seed with 3.10.49-g209ea2f in particular).
-#define USB_FFS_MAX_WRITE 16384
-
-// The kernel allocates a contiguous buffer for reads, which can fail for large ones due to
-// fragmentation. 16k chosen arbitrarily to match the write limit.
-#define USB_FFS_MAX_READ 16384
-
-#define cpu_to_le16(x)  htole16(x)
-#define cpu_to_le32(x)  htole32(x)
-
-static int dummy_fd = -1;
-
-struct usb_handle
-{
-    adb_cond_t notify;
-    adb_mutex_t lock;
-    bool open_new_connection;
-    std::atomic<bool> kicked;
-
-    int (*write)(usb_handle *h, const void *data, int len);
-    int (*read)(usb_handle *h, void *data, int len);
-    void (*kick)(usb_handle *h);
-    void (*close)(usb_handle *h);
-
-    // Legacy f_adb
-    int fd;
-
-    // FunctionFS
-    int control;
-    int bulk_out; /* "out" from the host's perspective => source for adbd */
-    int bulk_in;  /* "in" from the host's perspective => sink for adbd */
-};
-
-struct func_desc {
-    struct usb_interface_descriptor intf;
-    struct usb_endpoint_descriptor_no_audio source;
-    struct usb_endpoint_descriptor_no_audio sink;
-} __attribute__((packed));
-
-struct ss_func_desc {
-    struct usb_interface_descriptor intf;
-    struct usb_endpoint_descriptor_no_audio source;
-    struct usb_ss_ep_comp_descriptor source_comp;
-    struct usb_endpoint_descriptor_no_audio sink;
-    struct usb_ss_ep_comp_descriptor sink_comp;
-} __attribute__((packed));
-
-struct desc_v1 {
-    struct usb_functionfs_descs_head_v1 {
-        __le32 magic;
-        __le32 length;
-        __le32 fs_count;
-        __le32 hs_count;
-    } __attribute__((packed)) header;
-    struct func_desc fs_descs, hs_descs;
-} __attribute__((packed));
-
-struct desc_v2 {
-    struct usb_functionfs_descs_head_v2 header;
-    // The rest of the structure depends on the flags in the header.
-    __le32 fs_count;
-    __le32 hs_count;
-    __le32 ss_count;
-    __le32 os_count;
-    struct func_desc fs_descs, hs_descs;
-    struct ss_func_desc ss_descs;
-    struct usb_os_desc_header os_header;
-    struct usb_ext_compat_desc os_desc;
-} __attribute__((packed));
-
-static struct func_desc fs_descriptors = {
-    .intf = {
-        .bLength = sizeof(fs_descriptors.intf),
-        .bDescriptorType = USB_DT_INTERFACE,
-        .bInterfaceNumber = 0,
-        .bNumEndpoints = 2,
-        .bInterfaceClass = ADB_CLASS,
-        .bInterfaceSubClass = ADB_SUBCLASS,
-        .bInterfaceProtocol = ADB_PROTOCOL,
-        .iInterface = 1, /* first string from the provided table */
-    },
-    .source = {
-        .bLength = sizeof(fs_descriptors.source),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 1 | USB_DIR_OUT,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-    },
-    .sink = {
-        .bLength = sizeof(fs_descriptors.sink),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 2 | USB_DIR_IN,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-    },
-};
-
-static struct func_desc hs_descriptors = {
-    .intf = {
-        .bLength = sizeof(hs_descriptors.intf),
-        .bDescriptorType = USB_DT_INTERFACE,
-        .bInterfaceNumber = 0,
-        .bNumEndpoints = 2,
-        .bInterfaceClass = ADB_CLASS,
-        .bInterfaceSubClass = ADB_SUBCLASS,
-        .bInterfaceProtocol = ADB_PROTOCOL,
-        .iInterface = 1, /* first string from the provided table */
-    },
-    .source = {
-        .bLength = sizeof(hs_descriptors.source),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 1 | USB_DIR_OUT,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-    },
-    .sink = {
-        .bLength = sizeof(hs_descriptors.sink),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 2 | USB_DIR_IN,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-    },
-};
-
-static struct ss_func_desc ss_descriptors = {
-    .intf = {
-        .bLength = sizeof(ss_descriptors.intf),
-        .bDescriptorType = USB_DT_INTERFACE,
-        .bInterfaceNumber = 0,
-        .bNumEndpoints = 2,
-        .bInterfaceClass = ADB_CLASS,
-        .bInterfaceSubClass = ADB_SUBCLASS,
-        .bInterfaceProtocol = ADB_PROTOCOL,
-        .iInterface = 1, /* first string from the provided table */
-    },
-    .source = {
-        .bLength = sizeof(ss_descriptors.source),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 1 | USB_DIR_OUT,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_SS,
-    },
-    .source_comp = {
-        .bLength = sizeof(ss_descriptors.source_comp),
-        .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
-    },
-    .sink = {
-        .bLength = sizeof(ss_descriptors.sink),
-        .bDescriptorType = USB_DT_ENDPOINT,
-        .bEndpointAddress = 2 | USB_DIR_IN,
-        .bmAttributes = USB_ENDPOINT_XFER_BULK,
-        .wMaxPacketSize = MAX_PACKET_SIZE_SS,
-    },
-    .sink_comp = {
-        .bLength = sizeof(ss_descriptors.sink_comp),
-        .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
-    },
-};
-
-struct usb_ext_compat_desc os_desc_compat = {
-    .bFirstInterfaceNumber = 0,
-    .Reserved1 = cpu_to_le32(1),
-    .CompatibleID = {0},
-    .SubCompatibleID = {0},
-    .Reserved2 = {0},
-};
-
-static struct usb_os_desc_header os_desc_header = {
-    .interface = cpu_to_le32(1),
-    .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)),
-    .bcdVersion = cpu_to_le32(1),
-    .wIndex = cpu_to_le32(4),
-    .bCount = cpu_to_le32(1),
-    .Reserved = cpu_to_le32(0),
-};
-
-
-#define STR_INTERFACE_ "ADB Interface"
-
-static const struct {
-    struct usb_functionfs_strings_head header;
-    struct {
-        __le16 code;
-        const char str1[sizeof(STR_INTERFACE_)];
-    } __attribute__((packed)) lang0;
-} __attribute__((packed)) strings = {
-    .header = {
-        .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC),
-        .length = cpu_to_le32(sizeof(strings)),
-        .str_count = cpu_to_le32(1),
-        .lang_count = cpu_to_le32(1),
-    },
-    .lang0 = {
-        cpu_to_le16(0x0409), /* en-us */
-        STR_INTERFACE_,
-    },
-};
-
-static void usb_adb_open_thread(void* x) {
-    struct usb_handle *usb = (struct usb_handle *)x;
-    int fd;
-
-    adb_thread_setname("usb open");
-
-    while (true) {
-        // wait until the USB device needs opening
-        adb_mutex_lock(&usb->lock);
-        while (!usb->open_new_connection) {
-            adb_cond_wait(&usb->notify, &usb->lock);
-        }
-        usb->open_new_connection = false;
-        adb_mutex_unlock(&usb->lock);
-
-        D("[ usb_thread - opening device ]");
-        do {
-            /* XXX use inotify? */
-            fd = unix_open("/dev/android_adb", O_RDWR);
-            if (fd < 0) {
-                // to support older kernels
-                fd = unix_open("/dev/android", O_RDWR);
-            }
-            if (fd < 0) {
-                adb_sleep_ms(1000);
-            }
-        } while (fd < 0);
-        D("[ opening device succeeded ]");
-
-        close_on_exec(fd);
-        usb->fd = fd;
-
-        D("[ usb_thread - registering device ]");
-        register_usb_transport(usb, 0, 0, 1);
-    }
-
-    // never gets here
-    abort();
-}
-
-static int usb_adb_write(usb_handle *h, const void *data, int len)
-{
-    int n;
-
-    D("about to write (fd=%d, len=%d)", h->fd, len);
-    n = unix_write(h->fd, data, len);
-    if(n != len) {
-        D("ERROR: fd = %d, n = %d, errno = %d (%s)",
-            h->fd, n, errno, strerror(errno));
-        return -1;
-    }
-    if (h->kicked) {
-        D("usb_adb_write finished due to kicked");
-        return -1;
-    }
-    D("[ done fd=%d ]", h->fd);
-    return 0;
-}
-
-static int usb_adb_read(usb_handle *h, void *data, int len)
-{
-    D("about to read (fd=%d, len=%d)", h->fd, len);
-    while (len > 0) {
-        // The kernel implementation of adb_read in f_adb.c doesn't support
-        // reads larger then 4096 bytes. Read the data in 4096 byte chunks to
-        // avoid the issue. (The ffs implementation doesn't have this limit.)
-        int bytes_to_read = len < 4096 ? len : 4096;
-        int n = unix_read(h->fd, data, bytes_to_read);
-        if (n != bytes_to_read) {
-            D("ERROR: fd = %d, n = %d, errno = %d (%s)",
-                h->fd, n, errno, strerror(errno));
-            return -1;
-        }
-        if (h->kicked) {
-            D("usb_adb_read finished due to kicked");
-            return -1;
-        }
-        len -= n;
-        data = ((char*)data) + n;
-    }
-    D("[ done fd=%d ]", h->fd);
-    return 0;
-}
-
-static void usb_adb_kick(usb_handle *h) {
-    D("usb_kick");
-    // Other threads may be calling usb_adb_read/usb_adb_write at the same time.
-    // If we close h->fd, the file descriptor will be reused to open other files,
-    // and the read/write thread may operate on the wrong file. So instead
-    // we set the kicked flag and reopen h->fd to a dummy file here. After read/write
-    // threads finish, we close h->fd in usb_adb_close().
-    h->kicked = true;
-    TEMP_FAILURE_RETRY(dup2(dummy_fd, h->fd));
-}
-
-static void usb_adb_close(usb_handle *h) {
-    h->kicked = false;
-    adb_close(h->fd);
-    // Notify usb_adb_open_thread to open a new connection.
-    adb_mutex_lock(&h->lock);
-    h->open_new_connection = true;
-    adb_cond_signal(&h->notify);
-    adb_mutex_unlock(&h->lock);
-}
-
-static void usb_adb_init()
-{
-    usb_handle* h = reinterpret_cast<usb_handle*>(calloc(1, sizeof(usb_handle)));
-    if (h == nullptr) fatal("couldn't allocate usb_handle");
-
-    h->write = usb_adb_write;
-    h->read = usb_adb_read;
-    h->kick = usb_adb_kick;
-    h->close = usb_adb_close;
-    h->kicked = false;
-    h->fd = -1;
-
-    h->open_new_connection = true;
-    adb_cond_init(&h->notify, 0);
-    adb_mutex_init(&h->lock, 0);
-
-    // Open the file /dev/android_adb_enable to trigger
-    // the enabling of the adb USB function in the kernel.
-    // We never touch this file again - just leave it open
-    // indefinitely so the kernel will know when we are running
-    // and when we are not.
-    int fd = unix_open("/dev/android_adb_enable", O_RDWR);
-    if (fd < 0) {
-       D("failed to open /dev/android_adb_enable");
-    } else {
-        close_on_exec(fd);
-    }
-
-    D("[ usb_init - starting thread ]");
-    if (!adb_thread_create(usb_adb_open_thread, h)) {
-        fatal_errno("cannot create usb thread");
-    }
-}
-
-
-static bool init_functionfs(struct usb_handle *h)
-{
-    ssize_t ret;
-    struct desc_v1 v1_descriptor;
-    struct desc_v2 v2_descriptor;
-
-    v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
-    v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
-    v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
-                                 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC;
-    v2_descriptor.fs_count = 3;
-    v2_descriptor.hs_count = 3;
-    v2_descriptor.ss_count = 5;
-    v2_descriptor.os_count = 1;
-    v2_descriptor.fs_descs = fs_descriptors;
-    v2_descriptor.hs_descs = hs_descriptors;
-    v2_descriptor.ss_descs = ss_descriptors;
-    v2_descriptor.os_header = os_desc_header;
-    v2_descriptor.os_desc = os_desc_compat;
-
-    if (h->control < 0) { // might have already done this before
-        D("OPENING %s", USB_FFS_ADB_EP0);
-        h->control = adb_open(USB_FFS_ADB_EP0, O_RDWR);
-        if (h->control < 0) {
-            D("[ %s: cannot open control endpoint: errno=%d]", USB_FFS_ADB_EP0, errno);
-            goto err;
-        }
-
-        ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor));
-        if (ret < 0) {
-            v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
-            v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
-            v1_descriptor.header.fs_count = 3;
-            v1_descriptor.header.hs_count = 3;
-            v1_descriptor.fs_descs = fs_descriptors;
-            v1_descriptor.hs_descs = hs_descriptors;
-            D("[ %s: Switching to V1_descriptor format errno=%d ]", USB_FFS_ADB_EP0, errno);
-            ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor));
-            if (ret < 0) {
-                D("[ %s: write descriptors failed: errno=%d ]", USB_FFS_ADB_EP0, errno);
-                goto err;
-            }
-        }
-
-        ret = adb_write(h->control, &strings, sizeof(strings));
-        if (ret < 0) {
-            D("[ %s: writing strings failed: errno=%d]", USB_FFS_ADB_EP0, errno);
-            goto err;
-        }
-    }
-
-    h->bulk_out = adb_open(USB_FFS_ADB_OUT, O_RDWR);
-    if (h->bulk_out < 0) {
-        D("[ %s: cannot open bulk-out ep: errno=%d ]", USB_FFS_ADB_OUT, errno);
-        goto err;
-    }
-
-    h->bulk_in = adb_open(USB_FFS_ADB_IN, O_RDWR);
-    if (h->bulk_in < 0) {
-        D("[ %s: cannot open bulk-in ep: errno=%d ]", USB_FFS_ADB_IN, errno);
-        goto err;
-    }
-
-    return true;
-
-err:
-    if (h->bulk_in > 0) {
-        adb_close(h->bulk_in);
-        h->bulk_in = -1;
-    }
-    if (h->bulk_out > 0) {
-        adb_close(h->bulk_out);
-        h->bulk_out = -1;
-    }
-    if (h->control > 0) {
-        adb_close(h->control);
-        h->control = -1;
-    }
-    return false;
-}
-
-static void usb_ffs_open_thread(void* x) {
-    struct usb_handle *usb = (struct usb_handle *)x;
-
-    adb_thread_setname("usb ffs open");
-
-    while (true) {
-        // wait until the USB device needs opening
-        adb_mutex_lock(&usb->lock);
-        while (!usb->open_new_connection) {
-            adb_cond_wait(&usb->notify, &usb->lock);
-        }
-        usb->open_new_connection = false;
-        adb_mutex_unlock(&usb->lock);
-
-        while (true) {
-            if (init_functionfs(usb)) {
-                break;
-            }
-            adb_sleep_ms(1000);
-        }
-        property_set("sys.usb.ffs.ready", "1");
-
-        D("[ usb_thread - registering device ]");
-        register_usb_transport(usb, 0, 0, 1);
-    }
-
-    // never gets here
-    abort();
-}
-
-static int usb_ffs_write(usb_handle* h, const void* data, int len) {
-    D("about to write (fd=%d, len=%d)", h->bulk_in, len);
-
-    const char* buf = static_cast<const char*>(data);
-    while (len > 0) {
-        int write_len = std::min(USB_FFS_MAX_WRITE, len);
-        int n = adb_write(h->bulk_in, buf, write_len);
-        if (n < 0) {
-            D("ERROR: fd = %d, n = %d: %s", h->bulk_in, n, strerror(errno));
-            return -1;
-        }
-        buf += n;
-        len -= n;
-    }
-
-    D("[ done fd=%d ]", h->bulk_in);
-    return 0;
-}
-
-static int usb_ffs_read(usb_handle* h, void* data, int len) {
-    D("about to read (fd=%d, len=%d)", h->bulk_out, len);
-
-    char* buf = static_cast<char*>(data);
-    while (len > 0) {
-        int read_len = std::min(USB_FFS_MAX_READ, len);
-        int n = adb_read(h->bulk_out, buf, read_len);
-        if (n < 0) {
-            D("ERROR: fd = %d, n = %d: %s", h->bulk_out, n, strerror(errno));
-            return -1;
-        }
-        buf += n;
-        len -= n;
-    }
-
-    D("[ done fd=%d ]", h->bulk_out);
-    return 0;
-}
-
-static void usb_ffs_kick(usb_handle *h)
-{
-    int err;
-
-    err = ioctl(h->bulk_in, FUNCTIONFS_CLEAR_HALT);
-    if (err < 0) {
-        D("[ kick: source (fd=%d) clear halt failed (%d) ]", h->bulk_in, errno);
-    }
-
-    err = ioctl(h->bulk_out, FUNCTIONFS_CLEAR_HALT);
-    if (err < 0) {
-        D("[ kick: sink (fd=%d) clear halt failed (%d) ]", h->bulk_out, errno);
-    }
-
-    // don't close ep0 here, since we may not need to reinitialize it with
-    // the same descriptors again. if however ep1/ep2 fail to re-open in
-    // init_functionfs, only then would we close and open ep0 again.
-    // Ditto the comment in usb_adb_kick.
-    h->kicked = true;
-    TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_out));
-    TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_in));
-}
-
-static void usb_ffs_close(usb_handle *h) {
-    h->kicked = false;
-    adb_close(h->bulk_out);
-    adb_close(h->bulk_in);
-    // Notify usb_adb_open_thread to open a new connection.
-    adb_mutex_lock(&h->lock);
-    h->open_new_connection = true;
-    adb_cond_signal(&h->notify);
-    adb_mutex_unlock(&h->lock);
-}
-
-static void usb_ffs_init()
-{
-    D("[ usb_init - using FunctionFS ]");
-
-    usb_handle* h = reinterpret_cast<usb_handle*>(calloc(1, sizeof(usb_handle)));
-    if (h == nullptr) fatal("couldn't allocate usb_handle");
-
-    h->write = usb_ffs_write;
-    h->read = usb_ffs_read;
-    h->kick = usb_ffs_kick;
-    h->close = usb_ffs_close;
-    h->kicked = false;
-    h->control = -1;
-    h->bulk_out = -1;
-    h->bulk_out = -1;
-
-    h->open_new_connection = true;
-    adb_cond_init(&h->notify, 0);
-    adb_mutex_init(&h->lock, 0);
-
-    D("[ usb_init - starting thread ]");
-    if (!adb_thread_create(usb_ffs_open_thread, h)) {
-        fatal_errno("[ cannot create usb thread ]\n");
-    }
-}
-
-void usb_init()
-{
-    dummy_fd = adb_open("/dev/null", O_WRONLY);
-    CHECK_NE(dummy_fd, -1);
-    if (access(USB_FFS_ADB_EP0, F_OK) == 0)
-        usb_ffs_init();
-    else
-        usb_adb_init();
-}
-
-int usb_write(usb_handle *h, const void *data, int len)
-{
-    return h->write(h, data, len);
-}
-
-int usb_read(usb_handle *h, void *data, int len)
-{
-    return h->read(h, data, len);
-}
-int usb_close(usb_handle *h)
-{
-    h->close(h);
-    return 0;
-}
-
-void usb_kick(usb_handle *h)
-{
-    h->kick(h);
-}
diff --git a/adb/usb_osx.cpp b/adb/usb_osx.cpp
deleted file mode 100644
index adcbb3e..0000000
--- a/adb/usb_osx.cpp
+++ /dev/null
@@ -1,556 +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.
- */
-
-#define TRACE_TAG USB
-
-#include "sysdeps.h"
-
-#include <CoreFoundation/CoreFoundation.h>
-
-#include <IOKit/IOKitLib.h>
-#include <IOKit/IOCFPlugIn.h>
-#include <IOKit/usb/IOUSBLib.h>
-#include <IOKit/IOMessage.h>
-#include <mach/mach_port.h>
-
-#include <inttypes.h>
-#include <stdio.h>
-
-#include <atomic>
-#include <memory>
-#include <mutex>
-#include <vector>
-
-#include <android-base/logging.h>
-#include <android-base/stringprintf.h>
-
-#include "adb.h"
-#include "transport.h"
-
-struct usb_handle
-{
-    UInt8 bulkIn;
-    UInt8 bulkOut;
-    IOUSBInterfaceInterface190** interface;
-    unsigned int zero_mask;
-
-    // For garbage collecting disconnected devices.
-    bool mark;
-    std::string devpath;
-    std::atomic<bool> dead;
-
-    usb_handle() : bulkIn(0), bulkOut(0), interface(nullptr),
-        zero_mask(0), mark(false), dead(false) {
-    }
-};
-
-static std::atomic<bool> usb_inited_flag;
-
-static auto& g_usb_handles_mutex = *new std::mutex();
-static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
-
-static bool IsKnownDevice(const std::string& devpath) {
-    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
-    for (auto& usb : g_usb_handles) {
-        if (usb->devpath == devpath) {
-            // Set mark flag to indicate this device is still alive.
-            usb->mark = true;
-            return true;
-        }
-    }
-    return false;
-}
-
-static void usb_kick_locked(usb_handle* handle);
-
-static void KickDisconnectedDevices() {
-    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
-    for (auto& usb : g_usb_handles) {
-        if (!usb->mark) {
-            usb_kick_locked(usb.get());
-        } else {
-            usb->mark = false;
-        }
-    }
-}
-
-static void AddDevice(std::unique_ptr<usb_handle> handle) {
-    handle->mark = true;
-    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-    g_usb_handles.push_back(std::move(handle));
-}
-
-static void AndroidInterfaceAdded(io_iterator_t iterator);
-static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface190 **iface,
-                                                  UInt16 vendor, UInt16 product);
-
-static bool FindUSBDevices() {
-    // Create the matching dictionary to find the Android device's adb interface.
-    CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
-    if (!matchingDict) {
-        LOG(ERROR) << "couldn't create USB matching dictionary";
-        return false;
-    }
-    // Create an iterator for all I/O Registry objects that match the dictionary.
-    io_iterator_t iter = 0;
-    kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
-    if (kr != KERN_SUCCESS) {
-        LOG(ERROR) << "failed to get matching services";
-        return false;
-    }
-    // Iterate over all matching objects.
-    AndroidInterfaceAdded(iter);
-    IOObjectRelease(iter);
-    return true;
-}
-
-static void
-AndroidInterfaceAdded(io_iterator_t iterator)
-{
-    kern_return_t            kr;
-    io_service_t             usbDevice;
-    io_service_t             usbInterface;
-    IOCFPlugInInterface      **plugInInterface = NULL;
-    IOUSBInterfaceInterface220  **iface = NULL;
-    IOUSBDeviceInterface197  **dev = NULL;
-    HRESULT                  result;
-    SInt32                   score;
-    uint32_t                 locationId;
-    UInt8                    if_class, subclass, protocol;
-    UInt16                   vendor;
-    UInt16                   product;
-    UInt8                    serialIndex;
-    char                     serial[256];
-    std::string devpath;
-
-    while ((usbInterface = IOIteratorNext(iterator))) {
-        //* Create an intermediate interface plugin
-        kr = IOCreatePlugInInterfaceForService(usbInterface,
-                                               kIOUSBInterfaceUserClientTypeID,
-                                               kIOCFPlugInInterfaceID,
-                                               &plugInInterface, &score);
-        IOObjectRelease(usbInterface);
-        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
-            LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
-            continue;
-        }
-
-        //* This gets us the interface object
-        result = (*plugInInterface)->QueryInterface(
-            plugInInterface,
-            CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID*)&iface);
-        //* We only needed the plugin to get the interface, so discard it
-        (*plugInInterface)->Release(plugInInterface);
-        if (result || !iface) {
-            LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
-            continue;
-        }
-
-        kr = (*iface)->GetInterfaceClass(iface, &if_class);
-        kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
-        kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
-        if(if_class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
-            // Ignore non-ADB devices.
-            LOG(DEBUG) << "Ignoring interface with incorrect class/subclass/protocol - " << if_class
-                       << ", " << subclass << ", " << protocol;
-            (*iface)->Release(iface);
-            continue;
-        }
-
-        //* this gets us an ioservice, with which we will find the actual
-        //* device; after getting a plugin, and querying the interface, of
-        //* course.
-        //* Gotta love OS X
-        kr = (*iface)->GetDevice(iface, &usbDevice);
-        if (kIOReturnSuccess != kr || !usbDevice) {
-            LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
-            (*iface)->Release(iface);
-            continue;
-        }
-
-        plugInInterface = NULL;
-        score = 0;
-        //* create an intermediate device plugin
-        kr = IOCreatePlugInInterfaceForService(usbDevice,
-                                               kIOUSBDeviceUserClientTypeID,
-                                               kIOCFPlugInInterfaceID,
-                                               &plugInInterface, &score);
-        //* only needed this to find the plugin
-        (void)IOObjectRelease(usbDevice);
-        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
-            LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
-            (*iface)->Release(iface);
-            continue;
-        }
-
-        result = (*plugInInterface)->QueryInterface(plugInInterface,
-            CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID*)&dev);
-        //* only needed this to query the plugin
-        (*plugInInterface)->Release(plugInInterface);
-        if (result || !dev) {
-            LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
-            (*iface)->Release(iface);
-            continue;
-        }
-
-        //* Now after all that, we actually have a ref to the device and
-        //* the interface that matched our criteria
-        kr = (*dev)->GetDeviceVendor(dev, &vendor);
-        kr = (*dev)->GetDeviceProduct(dev, &product);
-        kr = (*dev)->GetLocationID(dev, &locationId);
-        if (kr == KERN_SUCCESS) {
-            devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
-            if (IsKnownDevice(devpath)) {
-                (*dev)->Release(dev);
-                (*iface)->Release(iface);
-                continue;
-            }
-        }
-        kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
-
-        if (serialIndex > 0) {
-            IOUSBDevRequest req;
-            UInt16          buffer[256];
-            UInt16          languages[128];
-
-            memset(languages, 0, sizeof(languages));
-
-            req.bmRequestType =
-                    USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
-            req.bRequest = kUSBRqGetDescriptor;
-            req.wValue = (kUSBStringDesc << 8) | 0;
-            req.wIndex = 0;
-            req.pData = languages;
-            req.wLength = sizeof(languages);
-            kr = (*dev)->DeviceRequest(dev, &req);
-
-            if (kr == kIOReturnSuccess && req.wLenDone > 0) {
-
-                int langCount = (req.wLenDone - 2) / 2, lang;
-
-                for (lang = 1; lang <= langCount; lang++) {
-
-                    memset(buffer, 0, sizeof(buffer));
-                    memset(&req, 0, sizeof(req));
-
-                    req.bmRequestType =
-                            USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
-                    req.bRequest = kUSBRqGetDescriptor;
-                    req.wValue = (kUSBStringDesc << 8) | serialIndex;
-                    req.wIndex = languages[lang];
-                    req.pData = buffer;
-                    req.wLength = sizeof(buffer);
-                    kr = (*dev)->DeviceRequest(dev, &req);
-
-                    if (kr == kIOReturnSuccess && req.wLenDone > 0) {
-                        int i, count;
-
-                        // skip first word, and copy the rest to the serial string,
-                        // changing shorts to bytes.
-                        count = (req.wLenDone - 1) / 2;
-                        for (i = 0; i < count; i++)
-                                serial[i] = buffer[i + 1];
-                        serial[i] = 0;
-                        break;
-                    }
-                }
-            }
-        }
-
-        (*dev)->Release(dev);
-
-        VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
-                        vendor, product, serial);
-        if (devpath.empty()) {
-            devpath = serial;
-        }
-        if (IsKnownDevice(devpath)) {
-            (*iface)->USBInterfaceClose(iface);
-            (*iface)->Release(iface);
-            continue;
-        }
-
-        std::unique_ptr<usb_handle> handle = CheckInterface((IOUSBInterfaceInterface190**)iface,
-                                                            vendor, product);
-        if (handle == nullptr) {
-            LOG(ERROR) << "Could not find device interface";
-            (*iface)->Release(iface);
-            continue;
-        }
-        handle->devpath = devpath;
-        usb_handle* handle_p = handle.get();
-        VLOG(USB) << "Add usb device " << serial;
-        AddDevice(std::move(handle));
-        register_usb_transport(handle_p, serial, devpath.c_str(), 1);
-    }
-}
-
-// Used to clear both the endpoints before starting.
-// When adb quits, we might clear the host endpoint but not the device.
-// So we make sure both sides are clear before starting up.
-static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface190** interface, UInt8 bulkEp) {
-    IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
-    if (rc != kIOReturnSuccess) {
-        LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
-        return false;
-    }
-    return true;
-}
-
-//* TODO: simplify this further since we only register to get ADB interface
-//* subclass+protocol events
-static std::unique_ptr<usb_handle>
-CheckInterface(IOUSBInterfaceInterface190 **interface, UInt16 vendor, UInt16 product)
-{
-    std::unique_ptr<usb_handle> handle;
-    IOReturn kr;
-    UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
-    UInt8 endpoint;
-
-    //* Now open the interface.  This will cause the pipes associated with
-    //* the endpoints in the interface descriptor to be instantiated
-    kr = (*interface)->USBInterfaceOpen(interface);
-    if (kr != kIOReturnSuccess) {
-        LOG(ERROR) << "Could not open interface: " << std::hex << kr;
-        return NULL;
-    }
-
-    //* Get the number of endpoints associated with this interface
-    kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
-    if (kr != kIOReturnSuccess) {
-        LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
-        goto err_get_num_ep;
-    }
-
-    //* Get interface class, subclass and protocol
-    if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
-            (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
-            (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
-            LOG(ERROR) << "Unable to get interface class, subclass and protocol";
-            goto err_get_interface_class;
-    }
-
-    //* check to make sure interface class, subclass and protocol match ADB
-    //* avoid opening mass storage endpoints
-    if (!is_adb_interface(vendor, product, interfaceClass, interfaceSubClass, interfaceProtocol)) {
-        goto err_bad_adb_interface;
-    }
-
-    handle.reset(new usb_handle);
-    if (handle == nullptr) {
-        goto err_bad_adb_interface;
-    }
-
-    //* Iterate over the endpoints for this interface and find the first
-    //* bulk in/out pipes available.  These will be our read/write pipes.
-    for (endpoint = 1; endpoint <= interfaceNumEndpoints; endpoint++) {
-        UInt8   transferType;
-        UInt16  maxPacketSize;
-        UInt8   interval;
-        UInt8   number;
-        UInt8   direction;
-
-        kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
-                &number, &transferType, &maxPacketSize, &interval);
-        if (kr != kIOReturnSuccess) {
-            LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
-                       << std::hex << kr;
-            goto err_get_pipe_props;
-        }
-
-        if (kUSBBulk != transferType) continue;
-
-        if (kUSBIn == direction) {
-            handle->bulkIn = endpoint;
-            if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) goto err_get_pipe_props;
-        }
-
-        if (kUSBOut == direction) {
-            handle->bulkOut = endpoint;
-            if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) goto err_get_pipe_props;
-        }
-
-        handle->zero_mask = maxPacketSize - 1;
-    }
-
-    handle->interface = interface;
-    return handle;
-
-err_get_pipe_props:
-err_bad_adb_interface:
-err_get_interface_class:
-err_get_num_ep:
-    (*interface)->USBInterfaceClose(interface);
-    return nullptr;
-}
-
-std::mutex& operate_device_lock = *new std::mutex();
-
-static void RunLoopThread(void* unused) {
-    adb_thread_setname("RunLoop");
-
-    VLOG(USB) << "RunLoopThread started";
-    while (true) {
-        {
-            std::lock_guard<std::mutex> lock_guard(operate_device_lock);
-            FindUSBDevices();
-            KickDisconnectedDevices();
-        }
-        // Signal the parent that we are running
-        usb_inited_flag = true;
-        adb_sleep_ms(1000);
-    }
-    VLOG(USB) << "RunLoopThread done";
-}
-
-static void usb_cleanup() {
-    VLOG(USB) << "usb_cleanup";
-    // Wait until usb operations in RunLoopThread finish, and prevent further operations.
-    operate_device_lock.lock();
-    close_usb_devices();
-}
-
-void usb_init() {
-    static bool initialized = false;
-    if (!initialized) {
-        atexit(usb_cleanup);
-
-        usb_inited_flag = false;
-
-        if (!adb_thread_create(RunLoopThread, nullptr)) {
-            fatal_errno("cannot create RunLoop thread");
-        }
-
-        // Wait for initialization to finish
-        while (!usb_inited_flag) {
-            adb_sleep_ms(100);
-        }
-
-        initialized = true;
-    }
-}
-
-int usb_write(usb_handle *handle, const void *buf, int len)
-{
-    IOReturn    result;
-
-    if (!len)
-        return 0;
-
-    if (!handle || handle->dead)
-        return -1;
-
-    if (NULL == handle->interface) {
-        LOG(ERROR) << "usb_write interface was null";
-        return -1;
-    }
-
-    if (0 == handle->bulkOut) {
-        LOG(ERROR) << "bulkOut endpoint not assigned";
-        return -1;
-    }
-
-    result =
-        (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
-
-    if ((result == 0) && (handle->zero_mask)) {
-        /* we need 0-markers and our transfer */
-        if(!(len & handle->zero_mask)) {
-            result =
-                (*handle->interface)->WritePipe(
-                        handle->interface, handle->bulkOut, (void *)buf, 0);
-        }
-    }
-
-    if (0 == result)
-        return 0;
-
-    LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
-    return -1;
-}
-
-int usb_read(usb_handle *handle, void *buf, int len)
-{
-    IOReturn result;
-    UInt32  numBytes = len;
-
-    if (!len) {
-        return 0;
-    }
-
-    if (!handle || handle->dead) {
-        return -1;
-    }
-
-    if (NULL == handle->interface) {
-        LOG(ERROR) << "usb_read interface was null";
-        return -1;
-    }
-
-    if (0 == handle->bulkIn) {
-        LOG(ERROR) << "bulkIn endpoint not assigned";
-        return -1;
-    }
-
-    result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
-
-    if (kIOUSBPipeStalled == result) {
-        LOG(ERROR) << "Pipe stalled, clearing stall.\n";
-        (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
-        result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
-    }
-
-    if (kIOReturnSuccess == result)
-        return 0;
-    else {
-        LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
-    }
-
-    return -1;
-}
-
-int usb_close(usb_handle *handle)
-{
-    std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
-    for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
-        if ((*it).get() == handle) {
-            g_usb_handles.erase(it);
-            break;
-        }
-    }
-    return 0;
-}
-
-static void usb_kick_locked(usb_handle *handle)
-{
-    LOG(INFO) << "Kicking handle";
-    /* release the interface */
-    if (!handle)
-        return;
-
-    if (!handle->dead)
-    {
-        handle->dead = true;
-        (*handle->interface)->USBInterfaceClose(handle->interface);
-        (*handle->interface)->Release(handle->interface);
-    }
-}
-
-void usb_kick(usb_handle *handle) {
-    // Use the lock to avoid multiple thread kicking the device at the same time.
-    std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
-    usb_kick_locked(handle);
-}
diff --git a/adb/usb_windows.cpp b/adb/usb_windows.cpp
deleted file mode 100644
index 8ecca37..0000000
--- a/adb/usb_windows.cpp
+++ /dev/null
@@ -1,659 +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.
- */
-
-#define TRACE_TAG USB
-
-#include "sysdeps.h"
-
-#include <winsock2.h>  // winsock.h *must* be included before windows.h.
-#include <adb_api.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <usb100.h>
-#include <windows.h>
-#include <winerror.h>
-
-#include <android-base/errors.h>
-
-#include "adb.h"
-#include "transport.h"
-
-/** Structure usb_handle describes our connection to the usb device via
-  AdbWinApi.dll. This structure is returned from usb_open() routine and
-  is expected in each subsequent call that is accessing the device.
-
-  Most members are protected by usb_lock, except for adb_{read,write}_pipe which
-  rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
-  ability to break a thread out of pipe IO.
-*/
-struct usb_handle {
-  /// Previous entry in the list of opened usb handles
-  usb_handle *prev;
-
-  /// Next entry in the list of opened usb handles
-  usb_handle *next;
-
-  /// Handle to USB interface
-  ADBAPIHANDLE  adb_interface;
-
-  /// Handle to USB read pipe (endpoint)
-  ADBAPIHANDLE  adb_read_pipe;
-
-  /// Handle to USB write pipe (endpoint)
-  ADBAPIHANDLE  adb_write_pipe;
-
-  /// Interface name
-  wchar_t*      interface_name;
-
-  /// Mask for determining when to use zero length packets
-  unsigned zero_mask;
-};
-
-/// Class ID assigned to the device by androidusb.sys
-static const GUID usb_class_id = ANDROID_USB_CLASS_ID;
-
-/// List of opened usb handles
-static usb_handle handle_list = {
-  .prev = &handle_list,
-  .next = &handle_list,
-};
-
-/// Locker for the list of opened usb handles
-ADB_MUTEX_DEFINE( usb_lock );
-
-/// Checks if there is opened usb handle in handle_list for this device.
-int known_device(const wchar_t* dev_name);
-
-/// Checks if there is opened usb handle in handle_list for this device.
-/// usb_lock mutex must be held before calling this routine.
-int known_device_locked(const wchar_t* dev_name);
-
-/// Registers opened usb handle (adds it to handle_list).
-int register_new_device(usb_handle* handle);
-
-/// Checks if interface (device) matches certain criteria
-int recognized_device(usb_handle* handle);
-
-/// Enumerates present and available interfaces (devices), opens new ones and
-/// registers usb transport for them.
-void find_devices();
-
-/// Kicks all USB devices
-static void kick_devices();
-
-/// 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*);
-
-/// Initializes this module
-void usb_init();
-
-/// Opens usb interface (device) by interface (device) name.
-usb_handle* do_usb_open(const wchar_t* interface_name);
-
-/// Writes data to the opened usb handle
-int usb_write(usb_handle* handle, const void* data, int len);
-
-/// Reads data using the opened usb handle
-int usb_read(usb_handle *handle, void* data, int len);
-
-/// Cleans up opened usb handle
-void usb_cleanup_handle(usb_handle* handle);
-
-/// Cleans up (but don't close) opened usb handle
-void usb_kick(usb_handle* handle);
-
-/// Closes opened usb handle
-int usb_close(usb_handle* handle);
-
-int known_device_locked(const wchar_t* dev_name) {
-  usb_handle* usb;
-
-  if (NULL != dev_name) {
-    // Iterate through the list looking for the name match.
-    for(usb = handle_list.next; usb != &handle_list; usb = usb->next) {
-      // In Windows names are not case sensetive!
-      if((NULL != usb->interface_name) &&
-         (0 == wcsicmp(usb->interface_name, dev_name))) {
-        return 1;
-      }
-    }
-  }
-
-  return 0;
-}
-
-int known_device(const wchar_t* dev_name) {
-  int ret = 0;
-
-  if (NULL != dev_name) {
-    adb_mutex_lock(&usb_lock);
-    ret = known_device_locked(dev_name);
-    adb_mutex_unlock(&usb_lock);
-  }
-
-  return ret;
-}
-
-int register_new_device(usb_handle* handle) {
-  if (NULL == handle)
-    return 0;
-
-  adb_mutex_lock(&usb_lock);
-
-  // Check if device is already in the list
-  if (known_device_locked(handle->interface_name)) {
-    adb_mutex_unlock(&usb_lock);
-    return 0;
-  }
-
-  // Not in the list. Add this handle to the list.
-  handle->next = &handle_list;
-  handle->prev = handle_list.prev;
-  handle->prev->next = handle;
-  handle->next->prev = handle;
-
-  adb_mutex_unlock(&usb_lock);
-
-  return 1;
-}
-
-void device_poll_thread(void*) {
-  adb_thread_setname("Device Poll");
-  D("Created device thread");
-
-  while(1) {
-    find_devices();
-    adb_sleep_ms(1000);
-  }
-}
-
-static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
-                                           LPARAM lParam) {
-  switch (uMsg) {
-  case WM_POWERBROADCAST:
-    switch (wParam) {
-    case PBT_APMRESUMEAUTOMATIC:
-      // Resuming from sleep or hibernation, so kick all existing USB devices
-      // and then allow the device_poll_thread to redetect USB devices from
-      // scratch. If we don't do this, existing USB devices will never respond
-      // to us because they'll be waiting for the connect/auth handshake.
-      D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
-        "so kicking all USB devices\n");
-      kick_devices();
-      return TRUE;
-    }
-  }
-  return DefWindowProcW(hwnd, uMsg, wParam, lParam);
-}
-
-static void _power_notification_thread(void*) {
-  // 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
-  // heavyweight WMI APIs to get power notifications. But for the common case
-  // of a developer's interactive session, a window message pump is more
-  // appropriate.
-  D("Created power notification thread");
-  adb_thread_setname("Power Notifier");
-
-  // Window class names are process specific.
-  static const WCHAR kPowerNotificationWindowClassName[] =
-    L"PowerNotificationWindow";
-
-  // Get the HINSTANCE corresponding to the module that _power_window_proc
-  // is in (the main module).
-  const HINSTANCE instance = GetModuleHandleW(NULL);
-  if (!instance) {
-    // This is such a common API call that this should never fail.
-    fatal("GetModuleHandleW failed: %s",
-          android::base::SystemErrorCodeToString(GetLastError()).c_str());
-  }
-
-  WNDCLASSEXW wndclass;
-  memset(&wndclass, 0, sizeof(wndclass));
-  wndclass.cbSize = sizeof(wndclass);
-  wndclass.lpfnWndProc = _power_window_proc;
-  wndclass.hInstance = instance;
-  wndclass.lpszClassName = kPowerNotificationWindowClassName;
-  if (!RegisterClassExW(&wndclass)) {
-    fatal("RegisterClassExW failed: %s",
-          android::base::SystemErrorCodeToString(GetLastError()).c_str());
-  }
-
-  if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
-                       L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0,
-                       NULL, NULL, instance, NULL)) {
-    fatal("CreateWindowExW failed: %s",
-          android::base::SystemErrorCodeToString(GetLastError()).c_str());
-  }
-
-  MSG msg;
-  while (GetMessageW(&msg, NULL, 0, 0)) {
-    TranslateMessage(&msg);
-    DispatchMessageW(&msg);
-  }
-
-  // GetMessageW() will return false if a quit message is posted. We don't
-  // do that, but it might be possible for that to occur when logging off or
-  // shutting down. Not a big deal since the whole process will be going away
-  // soon anyway.
-  D("Power notification thread exiting");
-}
-
-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");
-  }
-}
-
-usb_handle* do_usb_open(const wchar_t* interface_name) {
-  unsigned long name_len = 0;
-
-  // Allocate our handle
-  usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
-  if (NULL == ret) {
-    D("Could not allocate %u bytes for usb_handle: %s", sizeof(usb_handle),
-      strerror(errno));
-    goto fail;
-  }
-
-  // Set linkers back to the handle
-  ret->next = ret;
-  ret->prev = ret;
-
-  // Create interface.
-  ret->adb_interface = AdbCreateInterfaceByName(interface_name);
-  if (NULL == ret->adb_interface) {
-    D("AdbCreateInterfaceByName failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    goto fail;
-  }
-
-  // Open read pipe (endpoint)
-  ret->adb_read_pipe =
-    AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
-                                   AdbOpenAccessTypeReadWrite,
-                                   AdbOpenSharingModeReadWrite);
-  if (NULL == ret->adb_read_pipe) {
-    D("AdbOpenDefaultBulkReadEndpoint failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    goto fail;
-  }
-
-  // Open write pipe (endpoint)
-  ret->adb_write_pipe =
-    AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
-                                    AdbOpenAccessTypeReadWrite,
-                                    AdbOpenSharingModeReadWrite);
-  if (NULL == ret->adb_write_pipe) {
-    D("AdbOpenDefaultBulkWriteEndpoint failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    goto fail;
-  }
-
-  // Save interface name
-  // First get expected name length
-  AdbGetInterfaceName(ret->adb_interface,
-                      NULL,
-                      &name_len,
-                      false);
-  if (0 == name_len) {
-    D("AdbGetInterfaceName returned name length of zero: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    goto fail;
-  }
-
-  ret->interface_name = (wchar_t*)malloc(name_len * sizeof(ret->interface_name[0]));
-  if (NULL == ret->interface_name) {
-    D("Could not allocate %lu characters for interface_name: %s", name_len, strerror(errno));
-    goto fail;
-  }
-
-  // Now save the name
-  if (!AdbGetInterfaceName(ret->adb_interface,
-                           ret->interface_name,
-                           &name_len,
-                           false)) {
-    D("AdbGetInterfaceName failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    goto fail;
-  }
-
-  // We're done at this point
-  return ret;
-
-fail:
-  if (NULL != ret) {
-    usb_cleanup_handle(ret);
-    free(ret);
-  }
-
-  return NULL;
-}
-
-int usb_write(usb_handle* handle, const void* data, int len) {
-  unsigned long time_out = 5000;
-  unsigned long written = 0;
-  int err = 0;
-
-  D("usb_write %d", len);
-  if (NULL == handle) {
-    D("usb_write was passed NULL handle");
-    err = EINVAL;
-    goto fail;
-  }
-
-  // Perform write
-  if (!AdbWriteEndpointSync(handle->adb_write_pipe,
-                            (void*)data,
-                            (unsigned long)len,
-                            &written,
-                            time_out)) {
-    D("AdbWriteEndpointSync failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    err = EIO;
-    goto fail;
-  }
-
-  // Make sure that we've written what we were asked to write
-  D("usb_write got: %ld, expected: %d", written, len);
-  if (written != (unsigned long)len) {
-    // If this occurs, this code should be changed to repeatedly call
-    // AdbWriteEndpointSync() until all bytes are written.
-    D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld",
-      len, written);
-    err = EIO;
-    goto fail;
-  }
-
-  if (handle->zero_mask && (len & handle->zero_mask) == 0) {
-    // Send a zero length packet
-    if (!AdbWriteEndpointSync(handle->adb_write_pipe,
-                              (void*)data,
-                              0,
-                              &written,
-                              time_out)) {
-      D("AdbWriteEndpointSync of zero length packet failed: %s",
-        android::base::SystemErrorCodeToString(GetLastError()).c_str());
-      err = EIO;
-      goto fail;
-    }
-  }
-
-  return 0;
-
-fail:
-  // Any failure should cause us to kick the device instead of leaving it a
-  // zombie state with potential to hang.
-  if (NULL != handle) {
-    D("Kicking device due to error in usb_write");
-    usb_kick(handle);
-  }
-
-  D("usb_write failed");
-  errno = err;
-  return -1;
-}
-
-int usb_read(usb_handle *handle, void* data, int len) {
-  unsigned long time_out = 0;
-  unsigned long read = 0;
-  int err = 0;
-
-  D("usb_read %d", len);
-  if (NULL == handle) {
-    D("usb_read was passed NULL handle");
-    err = EINVAL;
-    goto fail;
-  }
-
-  while (len > 0) {
-    if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
-                             time_out)) {
-      D("AdbReadEndpointSync failed: %s",
-        android::base::SystemErrorCodeToString(GetLastError()).c_str());
-      err = EIO;
-      goto fail;
-    }
-    D("usb_read got: %ld, expected: %d", read, len);
-
-    data = (char *)data + read;
-    len -= read;
-  }
-
-  return 0;
-
-fail:
-  // Any failure should cause us to kick the device instead of leaving it a
-  // zombie state with potential to hang.
-  if (NULL != handle) {
-    D("Kicking device due to error in usb_read");
-    usb_kick(handle);
-  }
-
-  D("usb_read failed");
-  errno = err;
-  return -1;
-}
-
-// Wrapper around AdbCloseHandle() that logs diagnostics.
-static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
-  if (!AdbCloseHandle(adb_handle)) {
-    D("AdbCloseHandle(%p) failed: %s", adb_handle,
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-  }
-}
-
-void usb_cleanup_handle(usb_handle* handle) {
-  D("usb_cleanup_handle");
-  if (NULL != handle) {
-    if (NULL != handle->interface_name)
-      free(handle->interface_name);
-    // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
-    // wait until the pipe no longer uses the interface. Then we can
-    // AdbCloseHandle() the interface.
-    if (NULL != handle->adb_write_pipe)
-      _adb_close_handle(handle->adb_write_pipe);
-    if (NULL != handle->adb_read_pipe)
-      _adb_close_handle(handle->adb_read_pipe);
-    if (NULL != handle->adb_interface)
-      _adb_close_handle(handle->adb_interface);
-
-    handle->interface_name = NULL;
-    handle->adb_write_pipe = NULL;
-    handle->adb_read_pipe = NULL;
-    handle->adb_interface = NULL;
-  }
-}
-
-static void usb_kick_locked(usb_handle* handle) {
-  // The reason the lock must be acquired before calling this function is in
-  // case multiple threads are trying to kick the same device at the same time.
-  usb_cleanup_handle(handle);
-}
-
-void usb_kick(usb_handle* handle) {
-  D("usb_kick");
-  if (NULL != handle) {
-    adb_mutex_lock(&usb_lock);
-
-    usb_kick_locked(handle);
-
-    adb_mutex_unlock(&usb_lock);
-  } else {
-    errno = EINVAL;
-  }
-}
-
-int usb_close(usb_handle* handle) {
-  D("usb_close");
-
-  if (NULL != handle) {
-    // Remove handle from the list
-    adb_mutex_lock(&usb_lock);
-
-    if ((handle->next != handle) && (handle->prev != handle)) {
-      handle->next->prev = handle->prev;
-      handle->prev->next = handle->next;
-      handle->prev = handle;
-      handle->next = handle;
-    }
-
-    adb_mutex_unlock(&usb_lock);
-
-    // Cleanup handle
-    usb_cleanup_handle(handle);
-    free(handle);
-  }
-
-  return 0;
-}
-
-int recognized_device(usb_handle* handle) {
-  if (NULL == handle)
-    return 0;
-
-  // Check vendor and product id first
-  USB_DEVICE_DESCRIPTOR device_desc;
-
-  if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
-                                 &device_desc)) {
-    D("AdbGetUsbDeviceDescriptor failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    return 0;
-  }
-
-  // Then check interface properties
-  USB_INTERFACE_DESCRIPTOR interf_desc;
-
-  if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
-                                    &interf_desc)) {
-    D("AdbGetUsbInterfaceDescriptor failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    return 0;
-  }
-
-  // Must have two endpoints
-  if (2 != interf_desc.bNumEndpoints) {
-    return 0;
-  }
-
-  if (is_adb_interface(device_desc.idVendor, device_desc.idProduct,
-      interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass, interf_desc.bInterfaceProtocol)) {
-
-    if(interf_desc.bInterfaceProtocol == 0x01) {
-      AdbEndpointInformation endpoint_info;
-      // assuming zero is a valid bulk endpoint ID
-      if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
-        handle->zero_mask = endpoint_info.max_packet_size - 1;
-        D("device zero_mask: 0x%x", handle->zero_mask);
-      } else {
-        D("AdbGetEndpointInformation failed: %s",
-          android::base::SystemErrorCodeToString(GetLastError()).c_str());
-      }
-    }
-
-    return 1;
-  }
-
-  return 0;
-}
-
-void find_devices() {
-  usb_handle* handle = NULL;
-  char entry_buffer[2048];
-  AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
-  unsigned long entry_buffer_size = sizeof(entry_buffer);
-
-  // Enumerate all present and active interfaces.
-  ADBAPIHANDLE enum_handle =
-    AdbEnumInterfaces(usb_class_id, true, true, true);
-
-  if (NULL == enum_handle) {
-    D("AdbEnumInterfaces failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-    return;
-  }
-
-  while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
-    // Lets see if we already have this device in the list
-    if (!known_device(next_interface->device_name)) {
-      // This seems to be a new device. Open it!
-      handle = do_usb_open(next_interface->device_name);
-      if (NULL != handle) {
-        // Lets see if this interface (device) belongs to us
-        if (recognized_device(handle)) {
-          D("adding a new device %ls", next_interface->device_name);
-
-          // We don't request a wchar_t string from AdbGetSerialNumber() because of a bug in
-          // adb_winusb_interface.cpp:CopyMemory(buffer, ser_num->bString, bytes_written) where the
-          // last parameter should be (str_len * sizeof(wchar_t)). The bug reads 2 bytes past the
-          // end of a stack buffer in the best case, and in the unlikely case of a long serial
-          // number, it will read 2 bytes past the end of a heap allocation. This doesn't affect the
-          // resulting string, but we should avoid the bad reads in the first place.
-          char serial_number[512];
-          unsigned long serial_number_len = sizeof(serial_number);
-          if (AdbGetSerialNumber(handle->adb_interface,
-                                serial_number,
-                                &serial_number_len,
-                                true)) {
-            // Lets make sure that we don't duplicate this device
-            if (register_new_device(handle)) {
-              register_usb_transport(handle, serial_number, NULL, 1);
-            } else {
-              D("register_new_device failed for %ls", next_interface->device_name);
-              usb_cleanup_handle(handle);
-              free(handle);
-            }
-          } else {
-            D("cannot get serial number: %s",
-              android::base::SystemErrorCodeToString(GetLastError()).c_str());
-            usb_cleanup_handle(handle);
-            free(handle);
-          }
-        } else {
-          usb_cleanup_handle(handle);
-          free(handle);
-        }
-      }
-    }
-
-    entry_buffer_size = sizeof(entry_buffer);
-  }
-
-  if (GetLastError() != ERROR_NO_MORE_ITEMS) {
-    // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
-    D("AdbNextInterface failed: %s",
-      android::base::SystemErrorCodeToString(GetLastError()).c_str());
-  }
-
-  _adb_close_handle(enum_handle);
-}
-
-static void kick_devices() {
-  // Need to acquire lock to safely walk the list which might be modified
-  // by another thread.
-  adb_mutex_lock(&usb_lock);
-  for (usb_handle* usb = handle_list.next; usb != &handle_list; usb = usb->next) {
-    usb_kick_locked(usb);
-  }
-  adb_mutex_unlock(&usb_lock);
-}
diff --git a/adf/Android.bp b/adf/Android.bp
new file mode 100644
index 0000000..b44c296
--- /dev/null
+++ b/adf/Android.bp
@@ -0,0 +1 @@
+subdirs = ["*"]
diff --git a/adf/Android.mk b/adf/Android.mk
deleted file mode 100644
index 64d486e..0000000
--- a/adf/Android.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-LOCAL_PATH := $(my-dir)
-
-include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/adf/libadf/Android.bp b/adf/libadf/Android.bp
new file mode 100644
index 0000000..c276c53
--- /dev/null
+++ b/adf/libadf/Android.bp
@@ -0,0 +1,23 @@
+// Copyright (C) 2013 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_library_static {
+    name: "libadf",
+    srcs: ["adf.cpp"],
+    cflags: ["-Werror"],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+}
+
+subdirs = ["tests"]
diff --git a/adf/libadf/Android.mk b/adf/libadf/Android.mk
deleted file mode 100644
index 7df354b..0000000
--- a/adf/libadf/Android.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := adf.c
-LOCAL_MODULE := libadf
-LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS += -Werror
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES += $(LOCAL_EXPORT_C_INCLUDE_DIRS)
-include $(BUILD_STATIC_LIBRARY)
diff --git a/adf/libadf/adf.c b/adf/libadf/adf.c
deleted file mode 100644
index c4d6681..0000000
--- a/adf/libadf/adf.c
+++ /dev/null
@@ -1,811 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <malloc.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <linux/limits.h>
-
-#include <sys/ioctl.h>
-
-#include <adf/adf.h>
-
-#define ADF_BASE_PATH "/dev/"
-
-static ssize_t adf_find_nodes(const char *pattern, adf_id_t **ids)
-{
-    DIR *dir;
-    struct dirent *dirent;
-    size_t n = 0;
-    ssize_t ret;
-    adf_id_t *ids_ret = NULL;
-
-    dir = opendir(ADF_BASE_PATH);
-    if (!dir)
-        return -errno;
-
-    errno = 0;
-    while ((dirent = readdir(dir))) {
-        adf_id_t id;
-        int matched = sscanf(dirent->d_name, pattern, &id);
-
-        if (matched < 0) {
-            ret = -errno;
-            goto done;
-        } else if (matched != 1) {
-            continue;
-        }
-
-        adf_id_t *new_ids = realloc(ids_ret, (n + 1) * sizeof(ids_ret[0]));
-        if (!new_ids) {
-            ret = -ENOMEM;
-            goto done;
-        }
-
-        ids_ret = new_ids;
-        ids_ret[n] = id;
-        n++;
-    }
-    if (errno)
-        ret = -errno;
-    else
-        ret = n;
-
-done:
-    closedir(dir);
-    if (ret < 0)
-        free(ids_ret);
-    else
-        *ids = ids_ret;
-    return ret;
-}
-
-ssize_t adf_devices(adf_id_t **ids)
-{
-    return adf_find_nodes("adf%u", ids);
-}
-
-int adf_device_open(adf_id_t id, int flags, struct adf_device *dev)
-{
-    char filename[64];
-
-    dev->id = id;
-
-    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf%u", id);
-    dev->fd = open(filename, flags);
-    if (dev->fd < 0)
-        return -errno;
-
-    return 0;
-}
-
-void adf_device_close(struct adf_device *dev)
-{
-    if (dev->fd >= 0)
-        close(dev->fd);
-}
-
-int adf_get_device_data(struct adf_device *dev, struct adf_device_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
-    if (err < 0)
-        return -ENOMEM;
-
-    if (data->n_attachments) {
-        data->attachments = malloc(sizeof(data->attachments[0]) *
-                data->n_attachments);
-        if (!data->attachments)
-            return -ENOMEM;
-    }
-
-    if (data->n_allowed_attachments) {
-        data->allowed_attachments =
-                malloc(sizeof(data->allowed_attachments[0]) *
-                        data->n_allowed_attachments);
-        if (!data->allowed_attachments) {
-            ret = -ENOMEM;
-            goto done;
-        }
-    }
-
-    if (data->custom_data_size) {
-        data->custom_data = malloc(data->custom_data_size);
-        if (!data->custom_data) {
-            ret = -ENOMEM;
-            goto done;
-        }
-    }
-
-    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
-    if (err < 0)
-        ret = -errno;
-
-done:
-    if (ret < 0)
-        adf_free_device_data(data);
-    return ret;
-}
-
-void adf_free_device_data(struct adf_device_data *data)
-{
-    free(data->attachments);
-    free(data->allowed_attachments);
-    free(data->custom_data);
-}
-
-int adf_device_post(struct adf_device *dev,
-        adf_id_t *interfaces, size_t n_interfaces,
-        struct adf_buffer_config *bufs, size_t n_bufs,
-        void *custom_data, size_t custom_data_size)
-{
-    int err;
-    struct adf_post_config data;
-
-    memset(&data, 0, sizeof(data));
-    data.interfaces = interfaces;
-    data.n_interfaces = n_interfaces;
-    data.bufs = bufs;
-    data.n_bufs = n_bufs;
-    data.custom_data = custom_data;
-    data.custom_data_size = custom_data_size;
-
-    err = ioctl(dev->fd, ADF_POST_CONFIG, &data);
-    if (err < 0)
-        return -errno;
-
-    return (int)data.complete_fence;
-}
-
-static int adf_device_attachment(struct adf_device *dev,
-        adf_id_t overlay_engine, adf_id_t interface, bool attach)
-{
-    int err;
-    struct adf_attachment_config data;
-
-    memset(&data, 0, sizeof(data));
-    data.overlay_engine = overlay_engine;
-    data.interface = interface;
-
-    err = ioctl(dev->fd, attach ? ADF_ATTACH : ADF_DETACH, &data);
-    if (err < 0)
-        return -errno;
-
-    return 0;
-}
-
-int adf_device_attach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface)
-{
-   return adf_device_attachment(dev, overlay_engine, interface, true);
-}
-
-int adf_device_detach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface)
-{
-   return adf_device_attachment(dev, overlay_engine, interface, false);
-}
-
-ssize_t adf_interfaces(struct adf_device *dev, adf_id_t **interfaces)
-{
-    char pattern[64];
-
-    snprintf(pattern, sizeof(pattern), "adf-interface%u.%%u", dev->id);
-    return adf_find_nodes(pattern, interfaces);
-}
-
-ssize_t adf_interfaces_for_overlay_engine(struct adf_device *dev,
-        adf_id_t overlay_engine, adf_id_t **interfaces)
-{
-    struct adf_device_data data;
-    ssize_t n = 0;
-    ssize_t ret;
-    adf_id_t *ids_ret = NULL;
-
-    ret = adf_get_device_data(dev, &data);
-    if (ret < 0)
-        return ret;
-
-    size_t i;
-    for (i = 0; i < data.n_allowed_attachments; i++) {
-        if (data.allowed_attachments[i].overlay_engine != overlay_engine)
-            continue;
-
-        adf_id_t *new_ids = realloc(ids_ret, (n + 1) * sizeof(ids_ret[0]));
-        if (!new_ids) {
-            ret = -ENOMEM;
-            goto done;
-        }
-
-        ids_ret = new_ids;
-        ids_ret[n] = data.allowed_attachments[i].interface;
-        n++;
-    }
-
-    ret = n;
-
-done:
-    adf_free_device_data(&data);
-    if (ret < 0)
-        free(ids_ret);
-    else
-        *interfaces = ids_ret;
-    return ret;
-}
-
-static ssize_t adf_interfaces_filter(struct adf_device *dev,
-        adf_id_t *in, size_t n_in, adf_id_t **out,
-        bool (*filter)(struct adf_interface_data *data, __u32 match),
-        __u32 match)
-{
-    size_t n = 0;
-    ssize_t ret;
-    adf_id_t *ids_ret = NULL;
-
-    size_t i;
-    for (i = 0; i < n_in; i++) {
-        int fd = adf_interface_open(dev, in[i], O_RDONLY);
-        if (fd < 0) {
-            ret = fd;
-            goto done;
-        }
-
-        struct adf_interface_data data;
-        ret = adf_get_interface_data(fd, &data);
-        close(fd);
-        if (ret < 0)
-            goto done;
-
-        if (!filter(&data, match))
-            continue;
-
-        adf_id_t *new_ids = realloc(ids_ret, (n + 1) * sizeof(ids_ret[0]));
-        if (!new_ids) {
-            ret = -ENOMEM;
-            goto done;
-        }
-
-        ids_ret = new_ids;
-        ids_ret[n] = in[i];
-        n++;
-    }
-
-    ret = n;
-
-done:
-    if (ret < 0)
-        free(ids_ret);
-    else
-        *out = ids_ret;
-    return ret;
-}
-
-static bool adf_interface_type_filter(struct adf_interface_data *data,
-        __u32 type)
-{
-    return data->type == (enum adf_interface_type)type;
-}
-
-ssize_t adf_interfaces_filter_by_type(struct adf_device *dev,
-        enum adf_interface_type type,
-        adf_id_t *in, size_t n_in, adf_id_t **out)
-{
-    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_type_filter,
-            type);
-}
-
-static bool adf_interface_flags_filter(struct adf_interface_data *data,
-        __u32 flag)
-{
-    return !!(data->flags & flag);
-}
-
-ssize_t adf_interfaces_filter_by_flag(struct adf_device *dev, __u32 flag,
-        adf_id_t *in, size_t n_in, adf_id_t **out)
-{
-    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_flags_filter,
-            flag);
-}
-
-int adf_interface_open(struct adf_device *dev, adf_id_t id, int flags)
-{
-    char filename[64];
-
-    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf-interface%u.%u",
-            dev->id, id);
-
-    int fd = open(filename, flags);
-    if (fd < 0)
-        return -errno;
-    return fd;
-}
-
-int adf_get_interface_data(int fd, struct adf_interface_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
-    if (err < 0)
-        return -errno;
-
-    if (data->n_available_modes) {
-        data->available_modes = malloc(sizeof(data->available_modes[0]) *
-                data->n_available_modes);
-        if (!data->available_modes)
-            return -ENOMEM;
-    }
-
-    if (data->custom_data_size) {
-        data->custom_data = malloc(data->custom_data_size);
-        if (!data->custom_data) {
-            ret = -ENOMEM;
-            goto done;
-        }
-    }
-
-    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
-    if (err < 0)
-        ret = -errno;
-
-done:
-    if (ret < 0)
-        adf_free_interface_data(data);
-    return ret;
-}
-
-void adf_free_interface_data(struct adf_interface_data *data)
-{
-    free(data->available_modes);
-    free(data->custom_data);
-}
-
-int adf_interface_blank(int fd, __u8 mode)
-{
-    int err = ioctl(fd, ADF_BLANK, mode);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_interface_set_mode(int fd, struct drm_mode_modeinfo *mode)
-{
-    int err = ioctl(fd, ADF_SET_MODE, mode);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_interface_simple_buffer_alloc(int fd, __u32 w, __u32 h,
-        __u32 format, __u32 *offset, __u32 *pitch)
-{
-    int err;
-    struct adf_simple_buffer_alloc data;
-
-    memset(&data, 0, sizeof(data));
-    data.w = w;
-    data.h = h;
-    data.format = format;
-
-    err = ioctl(fd, ADF_SIMPLE_BUFFER_ALLOC, &data);
-    if (err < 0)
-        return -errno;
-
-    *offset = data.offset;
-    *pitch = data.pitch;
-    return (int)data.fd;
-}
-
-int adf_interface_simple_post(int fd, __u32 overlay_engine,
-        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
-        __u32 pitch, int acquire_fence)
-{
-    int ret;
-    struct adf_simple_post_config data;
-
-    memset(&data, 0, sizeof(data));
-    data.buf.overlay_engine = overlay_engine;
-    data.buf.w = w;
-    data.buf.h = h;
-    data.buf.format = format;
-    data.buf.fd[0] = buf_fd;
-    data.buf.offset[0] = offset;
-    data.buf.pitch[0] = pitch;
-    data.buf.n_planes = 1;
-    data.buf.acquire_fence = acquire_fence;
-
-    ret = ioctl(fd, ADF_SIMPLE_POST_CONFIG, &data);
-    if (ret < 0)
-        return -errno;
-
-    return (int)data.complete_fence;
-}
-
-ssize_t adf_overlay_engines(struct adf_device *dev, adf_id_t **overlay_engines)
-{
-    char pattern[64];
-
-    snprintf(pattern, sizeof(pattern), "adf-overlay-engine%u.%%u", dev->id);
-    return adf_find_nodes(pattern, overlay_engines);
-}
-
-ssize_t adf_overlay_engines_for_interface(struct adf_device *dev,
-        adf_id_t interface, adf_id_t **overlay_engines)
-{
-    struct adf_device_data data;
-    ssize_t n = 0;
-    ssize_t ret;
-    adf_id_t *ids_ret = NULL;
-
-    ret = adf_get_device_data(dev, &data);
-    if (ret < 0)
-        return ret;
-
-    size_t i;
-    for (i = 0; i < data.n_allowed_attachments; i++) {
-        if (data.allowed_attachments[i].interface != interface)
-            continue;
-
-        adf_id_t *new_ids = realloc(ids_ret, (n + 1) * sizeof(ids_ret[0]));
-        if (!new_ids) {
-            ret = -ENOMEM;
-            goto done;
-        }
-
-        ids_ret = new_ids;
-        ids_ret[n] = data.allowed_attachments[i].overlay_engine;
-        n++;
-    }
-
-    ret = n;
-
-done:
-    adf_free_device_data(&data);
-    if (ret < 0)
-        free(ids_ret);
-    else
-        *overlay_engines = ids_ret;
-    return ret;
-}
-
-static ssize_t adf_overlay_engines_filter(struct adf_device *dev,
-        adf_id_t *in, size_t n_in, adf_id_t **out,
-        bool (*filter)(struct adf_overlay_engine_data *data, void *cookie),
-        void *cookie)
-{
-    size_t n = 0;
-    ssize_t ret;
-    adf_id_t *ids_ret = NULL;
-
-    size_t i;
-    for (i = 0; i < n_in; i++) {
-        int fd = adf_overlay_engine_open(dev, in[i], O_RDONLY);
-        if (fd < 0) {
-            ret = fd;
-            goto done;
-        }
-
-        struct adf_overlay_engine_data data;
-        ret = adf_get_overlay_engine_data(fd, &data);
-        close(fd);
-        if (ret < 0)
-            goto done;
-
-        if (!filter(&data, cookie))
-            continue;
-
-        adf_id_t *new_ids = realloc(ids_ret, (n + 1) * sizeof(ids_ret[0]));
-        if (!new_ids) {
-            ret = -ENOMEM;
-            goto done;
-        }
-
-        ids_ret = new_ids;
-        ids_ret[n] = in[i];
-        n++;
-    }
-
-    ret = n;
-
-done:
-    if (ret < 0)
-        free(ids_ret);
-    else
-        *out = ids_ret;
-    return ret;
-}
-
-struct format_filter_cookie {
-    const __u32 *formats;
-    size_t n_formats;
-};
-
-static bool adf_overlay_engine_format_filter(
-        struct adf_overlay_engine_data *data, void *cookie)
-{
-    struct format_filter_cookie *c = cookie;
-    size_t i;
-    for (i = 0; i < data->n_supported_formats; i++) {
-        size_t j;
-        for (j = 0; j < c->n_formats; j++)
-            if (data->supported_formats[i] == c->formats[j])
-                return true;
-    }
-    return false;
-}
-
-ssize_t adf_overlay_engines_filter_by_format(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats, adf_id_t *in, size_t n_in,
-        adf_id_t **out)
-{
-    struct format_filter_cookie cookie = { formats, n_formats };
-    return adf_overlay_engines_filter(dev, in, n_in, out,
-            adf_overlay_engine_format_filter, &cookie);
-}
-
-int adf_overlay_engine_open(struct adf_device *dev, adf_id_t id, int flags)
-{
-    char filename[64];
-
-    snprintf(filename, sizeof(filename),
-            ADF_BASE_PATH "adf-overlay-engine%u.%u", dev->id, id);
-
-    int fd = open(filename, flags);
-    if (fd < 0)
-        return -errno;
-    return fd;
-}
-
-int adf_get_overlay_engine_data(int fd, struct adf_overlay_engine_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
-    if (err < 0)
-        return -errno;
-
-    if (data->n_supported_formats) {
-        data->supported_formats = malloc(sizeof(data->supported_formats[0]) *
-              data->n_supported_formats);
-        if (!data->supported_formats)
-            return -ENOMEM;
-    }
-
-    if (data->custom_data_size) {
-      data->custom_data = malloc(data->custom_data_size);
-      if (!data->custom_data) {
-          ret = -ENOMEM;
-          goto done;
-      }
-    }
-
-    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
-    if (err < 0)
-        ret = -errno;
-
-done:
-    if (ret < 0)
-        adf_free_overlay_engine_data(data);
-    return ret;
-}
-
-void adf_free_overlay_engine_data(struct adf_overlay_engine_data *data)
-{
-    free(data->supported_formats);
-    free(data->custom_data);
-}
-
-bool adf_overlay_engine_supports_format(int fd, __u32 format)
-{
-    struct adf_overlay_engine_data data;
-    bool ret = false;
-    size_t i;
-
-    int err = adf_get_overlay_engine_data(fd, &data);
-    if (err < 0)
-        return false;
-
-    for (i = 0; i < data.n_supported_formats; i++) {
-        if (data.supported_formats[i] == format) {
-            ret = true;
-            break;
-        }
-    }
-
-    adf_free_overlay_engine_data(&data);
-    return ret;
-}
-
-int adf_set_event(int fd, enum adf_event_type type, bool enabled)
-{
-    struct adf_set_event data;
-
-    data.type = type;
-    data.enabled = enabled;
-
-    int err = ioctl(fd, ADF_SET_EVENT, &data);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_read_event(int fd, struct adf_event **event)
-{
-    struct adf_event header;
-    struct {
-        struct adf_event base;
-        uint8_t data[0];
-    } *event_ret;
-    size_t data_size;
-    int ret = 0;
-
-    int err = read(fd, &header, sizeof(header));
-    if (err < 0)
-        return -errno;
-    if ((size_t)err < sizeof(header))
-        return -EIO;
-    if (header.length < sizeof(header))
-        return -EIO;
-
-    event_ret = malloc(header.length);
-    if (!event_ret)
-        return -ENOMEM;
-    data_size = header.length - sizeof(header);
-
-    memcpy(event_ret, &header, sizeof(header));
-    ssize_t read_size = read(fd, &event_ret->data, data_size);
-    if (read_size < 0) {
-        ret = -errno;
-        goto done;
-    }
-    if ((size_t)read_size < data_size) {
-        ret = -EIO;
-        goto done;
-    }
-
-    *event = &event_ret->base;
-
-done:
-    if (ret < 0)
-        free(event_ret);
-    return ret;
-}
-
-void adf_format_str(__u32 format, char buf[ADF_FORMAT_STR_SIZE])
-{
-    buf[0] = format & 0xFF;
-    buf[1] = (format >> 8) & 0xFF;
-    buf[2] = (format >> 16) & 0xFF;
-    buf[3] = (format >> 24) & 0xFF;
-    buf[4] = '\0';
-}
-
-static bool adf_find_simple_post_overlay_engine(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats,
-        adf_id_t interface, adf_id_t *overlay_engine)
-{
-    adf_id_t *engs;
-    ssize_t n_engs = adf_overlay_engines_for_interface(dev, interface, &engs);
-
-    if (n_engs <= 0)
-        return false;
-
-    adf_id_t *filtered_engs;
-    ssize_t n_filtered_engs = adf_overlay_engines_filter_by_format(dev,
-            formats, n_formats, engs, n_engs, &filtered_engs);
-    free(engs);
-
-    if (n_filtered_engs <= 0)
-        return false;
-
-    *overlay_engine = filtered_engs[0];
-    free(filtered_engs);
-    return true;
-}
-
-static const __u32 any_rgb_format[] = {
-    DRM_FORMAT_C8,
-    DRM_FORMAT_RGB332,
-    DRM_FORMAT_BGR233,
-    DRM_FORMAT_XRGB1555,
-    DRM_FORMAT_XBGR1555,
-    DRM_FORMAT_RGBX5551,
-    DRM_FORMAT_BGRX5551,
-    DRM_FORMAT_ARGB1555,
-    DRM_FORMAT_ABGR1555,
-    DRM_FORMAT_RGBA5551,
-    DRM_FORMAT_BGRA5551,
-    DRM_FORMAT_RGB565,
-    DRM_FORMAT_BGR565,
-    DRM_FORMAT_RGB888,
-    DRM_FORMAT_BGR888,
-    DRM_FORMAT_XRGB8888,
-    DRM_FORMAT_XBGR8888,
-    DRM_FORMAT_RGBX8888,
-    DRM_FORMAT_BGRX8888,
-    DRM_FORMAT_XRGB2101010,
-    DRM_FORMAT_XBGR2101010,
-    DRM_FORMAT_RGBX1010102,
-    DRM_FORMAT_BGRX1010102,
-    DRM_FORMAT_ARGB2101010,
-    DRM_FORMAT_ABGR2101010,
-    DRM_FORMAT_RGBA1010102,
-    DRM_FORMAT_BGRA1010102,
-    DRM_FORMAT_ARGB8888,
-    DRM_FORMAT_ABGR8888,
-    DRM_FORMAT_RGBA8888,
-    DRM_FORMAT_BGRA8888,
-};
-
-int adf_find_simple_post_configuration(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats,
-        adf_id_t *interface, adf_id_t *overlay_engine)
-{
-    adf_id_t *intfs = NULL;
-    ssize_t n_intfs = adf_interfaces(dev, &intfs);
-
-    if (n_intfs < 0)
-        return n_intfs;
-    else if (!n_intfs)
-        return -ENODEV;
-
-    adf_id_t *primary_intfs;
-    ssize_t n_primary_intfs = adf_interfaces_filter_by_flag(dev,
-            ADF_INTF_FLAG_PRIMARY, intfs, n_intfs, &primary_intfs);
-    free(intfs);
-
-    if (n_primary_intfs < 0)
-        return n_primary_intfs;
-    else if (!n_primary_intfs)
-        return -ENODEV;
-
-    if (!formats) {
-        formats = any_rgb_format;
-        n_formats = sizeof(any_rgb_format) / sizeof(any_rgb_format[0]);
-    }
-
-    bool found = false;
-    ssize_t i = 0;
-    for (i = 0; i < n_primary_intfs; i++) {
-        found = adf_find_simple_post_overlay_engine(dev, formats, n_formats,
-                primary_intfs[i], overlay_engine);
-        if (found) {
-            *interface = primary_intfs[i];
-            break;
-        }
-    }
-    free(primary_intfs);
-
-    if (!found)
-        return -ENODEV;
-
-    return 0;
-}
diff --git a/adf/libadf/adf.cpp b/adf/libadf/adf.cpp
new file mode 100644
index 0000000..60d8ef0
--- /dev/null
+++ b/adf/libadf/adf.cpp
@@ -0,0 +1,737 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <malloc.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <memory>
+#include <vector>
+
+#include <linux/limits.h>
+
+#include <sys/ioctl.h>
+
+#include <adf/adf.h>
+
+#define ADF_BASE_PATH "/dev/"
+
+static ssize_t adf_id_vector_to_array(const std::vector<adf_id_t> &in,
+        adf_id_t **out)
+{
+    auto size = sizeof(in[0]) * in.size();
+    // We can't use new[] since the existing API says the caller should free()
+    // the returned array
+    auto ret = static_cast<adf_id_t *>(malloc(size));
+    if (!ret)
+        return -ENOMEM;
+
+    std::copy(in.begin(), in.end(), ret);
+    *out = ret;
+    return in.size();
+}
+
+static ssize_t adf_find_nodes(const char *pattern, adf_id_t **ids_out)
+{
+    struct dirent *dirent;
+    std::unique_ptr<DIR, decltype(&closedir)>
+        dir{opendir(ADF_BASE_PATH), closedir};
+    if (!dir)
+        return -errno;
+
+    std::vector<adf_id_t> ids;
+    errno = 0;
+    while ((dirent = readdir(dir.get()))) {
+        adf_id_t id;
+        int matched = sscanf(dirent->d_name, pattern, &id);
+
+        if (matched < 0)
+            return -errno;
+        else if (matched == 1)
+            ids.push_back(id);
+    }
+    if (errno)
+        return -errno;
+
+    return adf_id_vector_to_array(ids, ids_out);
+}
+
+ssize_t adf_devices(adf_id_t **ids)
+{
+    return adf_find_nodes("adf%u", ids);
+}
+
+int adf_device_open(adf_id_t id, int flags, struct adf_device *dev)
+{
+    char filename[64];
+
+    dev->id = id;
+
+    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf%u", id);
+    dev->fd = open(filename, flags);
+    if (dev->fd < 0)
+        return -errno;
+
+    return 0;
+}
+
+void adf_device_close(struct adf_device *dev)
+{
+    if (dev->fd >= 0)
+        close(dev->fd);
+}
+
+int adf_get_device_data(struct adf_device *dev, struct adf_device_data *data)
+{
+    int err;
+    int ret = 0;
+
+    memset(data, 0, sizeof(*data));
+
+    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
+    if (err < 0)
+        return -ENOMEM;
+
+    if (data->n_attachments)
+        data->attachments = new adf_attachment_config[data->n_attachments];
+
+    if (data->n_allowed_attachments)
+        data->allowed_attachments =
+                new adf_attachment_config[data->n_allowed_attachments];
+
+    if (data->custom_data_size)
+        data->custom_data = new char[data->custom_data_size];
+
+    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
+    if (err < 0) {
+        ret = -errno;
+        adf_free_device_data(data);
+    }
+    return ret;
+}
+
+void adf_free_device_data(struct adf_device_data *data)
+{
+    delete [] data->attachments;
+    delete [] data->allowed_attachments;
+    delete [] static_cast<char *>(data->custom_data);
+}
+
+int adf_device_post(struct adf_device *dev,
+        adf_id_t *interfaces, size_t n_interfaces,
+        struct adf_buffer_config *bufs, size_t n_bufs,
+        void *custom_data, size_t custom_data_size)
+{
+    int err;
+    struct adf_post_config data;
+
+    memset(&data, 0, sizeof(data));
+    data.interfaces = interfaces;
+    data.n_interfaces = n_interfaces;
+    data.bufs = bufs;
+    data.n_bufs = n_bufs;
+    data.custom_data = custom_data;
+    data.custom_data_size = custom_data_size;
+
+    err = ioctl(dev->fd, ADF_POST_CONFIG, &data);
+    if (err < 0)
+        return -errno;
+
+    return (int)data.complete_fence;
+}
+
+int adf_device_post_v2(struct adf_device *dev,
+        adf_id_t *interfaces, __u32 n_interfaces,
+        struct adf_buffer_config *bufs, __u32 n_bufs,
+        void *custom_data, __u64 custom_data_size,
+        enum adf_complete_fence_type complete_fence_type,
+        int *complete_fence)
+{
+    int err;
+    struct adf_post_config_v2 data;
+
+    memset(&data, 0, sizeof(data));
+    data.interfaces = (uintptr_t)interfaces;
+    data.n_interfaces = n_interfaces;
+    data.bufs = (uintptr_t)bufs;
+    data.n_bufs = n_bufs;
+    data.custom_data = (uintptr_t)custom_data;
+    data.custom_data_size = custom_data_size;
+    data.complete_fence_type = complete_fence_type;
+
+    err = ioctl(dev->fd, ADF_POST_CONFIG_V2, &data);
+    if (err < 0)
+        return -errno;
+
+    if (complete_fence)
+        *complete_fence = data.complete_fence;
+    else if (data.complete_fence >= 0)
+        close(data.complete_fence);
+
+    return 0;
+}
+
+static int adf_device_attachment(struct adf_device *dev,
+        adf_id_t overlay_engine, adf_id_t interface, bool attach)
+{
+    int err;
+    struct adf_attachment_config data;
+
+    memset(&data, 0, sizeof(data));
+    data.overlay_engine = overlay_engine;
+    data.interface = interface;
+
+    err = ioctl(dev->fd, attach ? ADF_ATTACH : ADF_DETACH, &data);
+    if (err < 0)
+        return -errno;
+
+    return 0;
+}
+
+int adf_device_attach(struct adf_device *dev, adf_id_t overlay_engine,
+                      adf_id_t interface)
+{
+   return adf_device_attachment(dev, overlay_engine, interface, true);
+}
+
+int adf_device_detach(struct adf_device *dev, adf_id_t overlay_engine,
+                      adf_id_t interface)
+{
+   return adf_device_attachment(dev, overlay_engine, interface, false);
+}
+
+ssize_t adf_interfaces(struct adf_device *dev, adf_id_t **interfaces)
+{
+    char pattern[64];
+
+    snprintf(pattern, sizeof(pattern), "adf-interface%u.%%u", dev->id);
+    return adf_find_nodes(pattern, interfaces);
+}
+
+ssize_t adf_interfaces_for_overlay_engine(struct adf_device *dev,
+        adf_id_t overlay_engine, adf_id_t **interfaces)
+{
+    struct adf_device_data data;
+    auto err = adf_get_device_data(dev, &data);
+    if (err < 0)
+        return err;
+
+    std::vector<adf_id_t> ids;
+    for (size_t i = 0; i < data.n_allowed_attachments; i++)
+        if (data.allowed_attachments[i].overlay_engine == overlay_engine)
+            ids.push_back(data.allowed_attachments[i].interface);
+
+    adf_free_device_data(&data);
+    return adf_id_vector_to_array(ids, interfaces);
+}
+
+static ssize_t adf_interfaces_filter(struct adf_device *dev,
+        adf_id_t *in, size_t n_in, adf_id_t **out,
+        bool (*filter)(struct adf_interface_data *data, __u32 match),
+        __u32 match)
+{
+    std::vector<adf_id_t> ids;
+    for (size_t i = 0; i < n_in; i++) {
+        int fd = adf_interface_open(dev, in[i], O_RDONLY);
+        if (fd < 0)
+            return fd;
+
+        struct adf_interface_data data;
+        auto ret = adf_get_interface_data(fd, &data);
+        close(fd);
+        if (ret < 0)
+            return ret;
+
+        if (filter(&data, match))
+            ids.push_back(in[i]);
+    }
+
+    return adf_id_vector_to_array(ids, out);
+}
+
+static bool adf_interface_type_filter(struct adf_interface_data *data,
+        __u32 type)
+{
+    return data->type == (enum adf_interface_type)type;
+}
+
+ssize_t adf_interfaces_filter_by_type(struct adf_device *dev,
+        enum adf_interface_type type,
+        adf_id_t *in, size_t n_in, adf_id_t **out)
+{
+    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_type_filter,
+            type);
+}
+
+static bool adf_interface_flags_filter(struct adf_interface_data *data,
+        __u32 flag)
+{
+    return !!(data->flags & flag);
+}
+
+ssize_t adf_interfaces_filter_by_flag(struct adf_device *dev, __u32 flag,
+        adf_id_t *in, size_t n_in, adf_id_t **out)
+{
+    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_flags_filter,
+            flag);
+}
+
+int adf_interface_open(struct adf_device *dev, adf_id_t id, int flags)
+{
+    char filename[64];
+
+    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf-interface%u.%u",
+            dev->id, id);
+
+    int fd = open(filename, flags);
+    if (fd < 0)
+        return -errno;
+    return fd;
+}
+
+int adf_get_interface_data(int fd, struct adf_interface_data *data)
+{
+    int err;
+    int ret = 0;
+
+    memset(data, 0, sizeof(*data));
+
+    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
+    if (err < 0)
+        return -errno;
+
+    if (data->n_available_modes)
+        data->available_modes = new drm_mode_modeinfo[data->n_available_modes];
+
+    if (data->custom_data_size)
+        data->custom_data = new char[data->custom_data_size];
+
+    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
+    if (err < 0) {
+        ret = -errno;
+        adf_free_interface_data(data);
+    }
+    return ret;
+}
+
+void adf_free_interface_data(struct adf_interface_data *data)
+{
+    delete [] data->available_modes;
+    delete [] static_cast<char *>(data->custom_data);
+}
+
+int adf_interface_blank(int fd, __u8 mode)
+{
+    int err = ioctl(fd, ADF_BLANK, mode);
+    if (err < 0)
+        return -errno;
+    return 0;
+}
+
+int adf_interface_set_mode(int fd, struct drm_mode_modeinfo *mode)
+{
+    int err = ioctl(fd, ADF_SET_MODE, mode);
+    if (err < 0)
+        return -errno;
+    return 0;
+}
+
+int adf_interface_simple_buffer_alloc(int fd, __u32 w, __u32 h,
+        __u32 format, __u32 *offset, __u32 *pitch)
+{
+    int err;
+    struct adf_simple_buffer_alloc data;
+
+    memset(&data, 0, sizeof(data));
+    data.w = w;
+    data.h = h;
+    data.format = format;
+
+    err = ioctl(fd, ADF_SIMPLE_BUFFER_ALLOC, &data);
+    if (err < 0)
+        return -errno;
+
+    *offset = data.offset;
+    *pitch = data.pitch;
+    return (int)data.fd;
+}
+
+static void adf_interface_simple_post_config_buf(struct adf_buffer_config *buf,
+        __u32 overlay_engine, __u32 w, __u32 h, __u32 format, int buf_fd,
+        __u32 offset, __u32 pitch, int acquire_fence)
+{
+    buf->overlay_engine = overlay_engine;
+    buf->w = w;
+    buf->h = h;
+    buf->format = format;
+    buf->fd[0] = buf_fd;
+    buf->offset[0] = offset;
+    buf->pitch[0] = pitch;
+    buf->n_planes = 1;
+    buf->acquire_fence = acquire_fence;
+}
+
+int adf_interface_simple_post(int fd, __u32 overlay_engine,
+        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
+        __u32 pitch, int acquire_fence)
+{
+    int ret;
+    struct adf_simple_post_config data;
+
+    memset(&data, 0, sizeof(data));
+    adf_interface_simple_post_config_buf(&data.buf, overlay_engine, w, h, format,
+            buf_fd, offset, pitch, acquire_fence);
+    ret = ioctl(fd, ADF_SIMPLE_POST_CONFIG, &data);
+    if (ret < 0)
+        return -errno;
+
+    return (int)data.complete_fence;
+}
+
+int adf_interface_simple_post_v2(int fd, adf_id_t overlay_engine,
+        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
+        __u32 pitch, int acquire_fence,
+        enum adf_complete_fence_type complete_fence_type,
+        int *complete_fence)
+{
+    int ret;
+    struct adf_simple_post_config_v2 data;
+
+    memset(&data, 0, sizeof(data));
+    adf_interface_simple_post_config_buf(&data.buf, overlay_engine, w, h, format,
+            buf_fd, offset, pitch, acquire_fence);
+    data.complete_fence_type = complete_fence_type;
+
+    ret = ioctl(fd, ADF_SIMPLE_POST_CONFIG_V2, &data);
+    if (ret < 0)
+        return -errno;
+
+    if (complete_fence)
+        *complete_fence = data.complete_fence;
+    else if (data.complete_fence >= 0)
+        close(data.complete_fence);
+
+    return 0;
+}
+
+ssize_t adf_overlay_engines(struct adf_device *dev, adf_id_t **overlay_engines)
+{
+    char pattern[64];
+
+    snprintf(pattern, sizeof(pattern), "adf-overlay-engine%u.%%u", dev->id);
+    return adf_find_nodes(pattern, overlay_engines);
+}
+
+ssize_t adf_overlay_engines_for_interface(struct adf_device *dev,
+        adf_id_t interface, adf_id_t **overlay_engines)
+{
+    struct adf_device_data data;
+    auto err = adf_get_device_data(dev, &data);
+    if (err < 0)
+        return err;
+
+    std::vector<adf_id_t> ids;
+    for (size_t i = 0; i < data.n_allowed_attachments; i++)
+        if (data.allowed_attachments[i].interface == interface)
+            ids.push_back(data.allowed_attachments[i].overlay_engine);
+
+    return adf_id_vector_to_array(ids, overlay_engines);
+}
+
+static ssize_t adf_overlay_engines_filter(struct adf_device *dev,
+        adf_id_t *in, size_t n_in, adf_id_t **out,
+        bool (*filter)(struct adf_overlay_engine_data *data, void *cookie),
+        void *cookie)
+{
+    std::vector<adf_id_t> ids;
+    size_t i;
+    for (i = 0; i < n_in; i++) {
+        int fd = adf_overlay_engine_open(dev, in[i], O_RDONLY);
+        if (fd < 0)
+            return fd;
+
+        struct adf_overlay_engine_data data;
+        auto ret = adf_get_overlay_engine_data(fd, &data);
+        close(fd);
+        if (ret < 0)
+            return ret;
+
+        if (filter(&data, cookie))
+            ids.push_back(in[i]);
+    }
+
+    return adf_id_vector_to_array(ids, out);
+}
+
+struct format_filter_cookie {
+    const __u32 *formats;
+    size_t n_formats;
+};
+
+static bool adf_overlay_engine_format_filter(
+        struct adf_overlay_engine_data *data, void *cookie)
+{
+    auto c = static_cast<format_filter_cookie *>(cookie);
+    size_t i;
+    for (i = 0; i < data->n_supported_formats; i++) {
+        size_t j;
+        for (j = 0; j < c->n_formats; j++)
+            if (data->supported_formats[i] == c->formats[j])
+                return true;
+    }
+    return false;
+}
+
+ssize_t adf_overlay_engines_filter_by_format(struct adf_device *dev,
+        const __u32 *formats, size_t n_formats, adf_id_t *in, size_t n_in,
+        adf_id_t **out)
+{
+    struct format_filter_cookie cookie = { formats, n_formats };
+    return adf_overlay_engines_filter(dev, in, n_in, out,
+            adf_overlay_engine_format_filter, &cookie);
+}
+
+int adf_overlay_engine_open(struct adf_device *dev, adf_id_t id, int flags)
+{
+    char filename[64];
+
+    snprintf(filename, sizeof(filename),
+            ADF_BASE_PATH "adf-overlay-engine%u.%u", dev->id, id);
+
+    int fd = open(filename, flags);
+    if (fd < 0)
+        return -errno;
+    return fd;
+}
+
+int adf_get_overlay_engine_data(int fd, struct adf_overlay_engine_data *data)
+{
+    int err;
+    int ret = 0;
+
+    memset(data, 0, sizeof(*data));
+
+    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
+    if (err < 0)
+        return -errno;
+
+    if (data->n_supported_formats)
+        data->supported_formats = new __u32[data->n_supported_formats];
+
+    if (data->custom_data_size)
+      data->custom_data = new char[data->custom_data_size];
+
+    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
+    if (err < 0) {
+        ret = -errno;
+        adf_free_overlay_engine_data(data);
+    }
+    return ret;
+}
+
+void adf_free_overlay_engine_data(struct adf_overlay_engine_data *data)
+{
+    delete [] data->supported_formats;
+    delete [] static_cast<char *>(data->custom_data);
+}
+
+bool adf_overlay_engine_supports_format(int fd, __u32 format)
+{
+    struct adf_overlay_engine_data data;
+    bool ret = false;
+    size_t i;
+
+    int err = adf_get_overlay_engine_data(fd, &data);
+    if (err < 0)
+        return false;
+
+    for (i = 0; i < data.n_supported_formats; i++) {
+        if (data.supported_formats[i] == format) {
+            ret = true;
+            break;
+        }
+    }
+
+    adf_free_overlay_engine_data(&data);
+    return ret;
+}
+
+int adf_set_event(int fd, enum adf_event_type type, bool enabled)
+{
+    struct adf_set_event data;
+
+    data.type = type;
+    data.enabled = enabled;
+
+    int err = ioctl(fd, ADF_SET_EVENT, &data);
+    if (err < 0)
+        return -errno;
+    return 0;
+}
+
+int adf_read_event(int fd, struct adf_event **event)
+{
+    struct adf_event header;
+    struct event_with_data {
+        struct adf_event base;
+        uint8_t data[0];
+    };
+    using unique_event = std::unique_ptr<event_with_data, decltype(&free)>;
+    size_t data_size;
+
+    int err = read(fd, &header, sizeof(header));
+    if (err < 0)
+        return -errno;
+    if ((size_t)err < sizeof(header))
+        return -EIO;
+    if (header.length < sizeof(header))
+        return -EIO;
+
+    // Again, we can't use new[] since the existing API says the caller should
+    // free() the returned event
+    auto event_ptr = static_cast<event_with_data *>(malloc(header.length));
+    unique_event event_ret{event_ptr, free};
+    if (!event_ret)
+        return -ENOMEM;
+    data_size = header.length - sizeof(header);
+
+    memcpy(event_ret.get(), &header, sizeof(header));
+    ssize_t read_size = read(fd, &event_ret->data, data_size);
+    if (read_size < 0)
+        return -errno;
+    if ((size_t)read_size < data_size)
+        return -EIO;
+
+    *event = &event_ret.release()->base;
+    return 0;
+}
+
+void adf_format_str(__u32 format, char buf[ADF_FORMAT_STR_SIZE])
+{
+    buf[0] = format & 0xFF;
+    buf[1] = (format >> 8) & 0xFF;
+    buf[2] = (format >> 16) & 0xFF;
+    buf[3] = (format >> 24) & 0xFF;
+    buf[4] = '\0';
+}
+
+static bool adf_find_simple_post_overlay_engine(struct adf_device *dev,
+        const __u32 *formats, size_t n_formats,
+        adf_id_t interface, adf_id_t *overlay_engine)
+{
+    adf_id_t *engs;
+    ssize_t n_engs = adf_overlay_engines_for_interface(dev, interface, &engs);
+
+    if (n_engs <= 0)
+        return false;
+
+    adf_id_t *filtered_engs;
+    ssize_t n_filtered_engs = adf_overlay_engines_filter_by_format(dev,
+            formats, n_formats, engs, n_engs, &filtered_engs);
+    free(engs);
+
+    if (n_filtered_engs <= 0)
+        return false;
+
+    *overlay_engine = filtered_engs[0];
+    free(filtered_engs);
+    return true;
+}
+
+static const __u32 any_rgb_format[] = {
+    DRM_FORMAT_C8,
+    DRM_FORMAT_RGB332,
+    DRM_FORMAT_BGR233,
+    DRM_FORMAT_XRGB1555,
+    DRM_FORMAT_XBGR1555,
+    DRM_FORMAT_RGBX5551,
+    DRM_FORMAT_BGRX5551,
+    DRM_FORMAT_ARGB1555,
+    DRM_FORMAT_ABGR1555,
+    DRM_FORMAT_RGBA5551,
+    DRM_FORMAT_BGRA5551,
+    DRM_FORMAT_RGB565,
+    DRM_FORMAT_BGR565,
+    DRM_FORMAT_RGB888,
+    DRM_FORMAT_BGR888,
+    DRM_FORMAT_XRGB8888,
+    DRM_FORMAT_XBGR8888,
+    DRM_FORMAT_RGBX8888,
+    DRM_FORMAT_BGRX8888,
+    DRM_FORMAT_XRGB2101010,
+    DRM_FORMAT_XBGR2101010,
+    DRM_FORMAT_RGBX1010102,
+    DRM_FORMAT_BGRX1010102,
+    DRM_FORMAT_ARGB2101010,
+    DRM_FORMAT_ABGR2101010,
+    DRM_FORMAT_RGBA1010102,
+    DRM_FORMAT_BGRA1010102,
+    DRM_FORMAT_ARGB8888,
+    DRM_FORMAT_ABGR8888,
+    DRM_FORMAT_RGBA8888,
+    DRM_FORMAT_BGRA8888,
+};
+
+int adf_find_simple_post_configuration(struct adf_device *dev,
+        const __u32 *formats, size_t n_formats,
+        adf_id_t *interface, adf_id_t *overlay_engine)
+{
+    adf_id_t *intfs = NULL;
+    ssize_t n_intfs = adf_interfaces(dev, &intfs);
+
+    if (n_intfs < 0)
+        return n_intfs;
+    else if (!n_intfs)
+        return -ENODEV;
+
+    adf_id_t *primary_intfs;
+    ssize_t n_primary_intfs = adf_interfaces_filter_by_flag(dev,
+            ADF_INTF_FLAG_PRIMARY, intfs, n_intfs, &primary_intfs);
+    free(intfs);
+
+    if (n_primary_intfs < 0)
+        return n_primary_intfs;
+    else if (!n_primary_intfs)
+        return -ENODEV;
+
+    if (!formats) {
+        formats = any_rgb_format;
+        n_formats = sizeof(any_rgb_format) / sizeof(any_rgb_format[0]);
+    }
+
+    bool found = false;
+    ssize_t i = 0;
+    for (i = 0; i < n_primary_intfs; i++) {
+        found = adf_find_simple_post_overlay_engine(dev, formats, n_formats,
+                primary_intfs[i], overlay_engine);
+        if (found) {
+            *interface = primary_intfs[i];
+            break;
+        }
+    }
+    free(primary_intfs);
+
+    if (!found)
+        return -ENODEV;
+
+    return 0;
+}
diff --git a/adf/libadf/include/adf/adf.h b/adf/libadf/include/adf/adf.h
index b6bda34..e4c7b28 100644
--- a/adf/libadf/include/adf/adf.h
+++ b/adf/libadf/include/adf/adf.h
@@ -75,6 +75,29 @@
         struct adf_buffer_config *bufs, size_t n_bufs,
         void *custom_data, size_t custom_data_size);
 /**
+ * Atomically posts a new display configuration to the specified interfaces.
+ *
+ * Compared to adf_device_post(), adf_device_post_v2():
+ *
+ *  (*) allows the client to choose the kind of sync fence returned
+ *      (through complete_fence_type)
+ *
+ *  (*) stores the returned sync fence fd in a provided buffer, so the client
+ *      can distinguish between a permission error (ret = -1) and a successful
+ *      call that returns no fence (*complete_fence = -1)
+ *
+ * On error, returns -errno.
+ *
+ * On devices without the corresponding kernel support, returns -ENOTTY.
+ */
+int adf_device_post_v2(struct adf_device *dev,
+        adf_id_t *interfaces, __u32 n_interfaces,
+        struct adf_buffer_config *bufs, __u32 n_bufs,
+        void *custom_data, __u64 custom_data_size,
+        enum adf_complete_fence_type complete_fence_type,
+        int *complete_fence);
+
+/**
  * Attaches the specified interface and overlay engine.
  */
 int adf_device_attach(struct adf_device *dev, adf_id_t overlay_engine,
@@ -163,6 +186,28 @@
 int adf_interface_simple_post(int fd, adf_id_t overlay_engine,
         __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
         __u32 pitch, int acquire_fence);
+/**
+ * Posts a single-plane RGB buffer to the display using the specified
+ * overlay engine.
+ *
+ * Compared to adf_interface_simple_post(), adf_interface_simple_post_v2():
+ *
+ *  (*) allows the client to choose the kind of sync fence returned
+ *      (through complete_fence_type)
+ *
+ *  (*) stores the returned sync fence fd in a provided buffer, so the client
+ *      can distinguish between a permission error (ret = -1) and a successful
+ *      call that returns no fence (*complete_fence = -1)
+ *
+ * On error, returns -errno.
+ *
+ * On devices without the corresponding kernel support, returns -ENOTTY.
+ */
+int adf_interface_simple_post_v2(int fd, adf_id_t overlay_engine,
+        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
+        __u32 pitch, int acquire_fence,
+        enum adf_complete_fence_type complete_fence_type,
+        int *complete_fence);
 
 /**
  * Enumerates all overlay engines belonging to an ADF device.
diff --git a/adf/libadf/include/video/adf.h b/adf/libadf/include/video/adf.h
new file mode 100644
index 0000000..692a425
--- /dev/null
+++ b/adf/libadf/include/video/adf.h
@@ -0,0 +1,209 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ***   To edit the content of this header, modify the corresponding
+ ***   source file (e.g. under external/kernel-headers/original/) then
+ ***   run bionic/libc/kernel/tools/update_all.py
+ ***
+ ***   Any manual change here will be lost the next time this script will
+ ***   be run. You've been warned!
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef _UAPI_VIDEO_ADF_H_
+#define _UAPI_VIDEO_ADF_H_
+#include <linux/ioctl.h>
+#include <linux/types.h>
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#include <drm/drm_fourcc.h>
+#include <drm/drm_mode.h>
+#define ADF_NAME_LEN 32
+#define ADF_MAX_CUSTOM_DATA_SIZE 4096
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+enum adf_interface_type {
+  ADF_INTF_DSI = 0,
+  ADF_INTF_eDP = 1,
+  ADF_INTF_DPI = 2,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  ADF_INTF_VGA = 3,
+  ADF_INTF_DVI = 4,
+  ADF_INTF_HDMI = 5,
+  ADF_INTF_MEMORY = 6,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  ADF_INTF_TYPE_DEVICE_CUSTOM = 128,
+  ADF_INTF_TYPE_MAX = (~(__u32) 0),
+};
+#define ADF_INTF_FLAG_PRIMARY (1 << 0)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_INTF_FLAG_EXTERNAL (1 << 1)
+enum adf_event_type {
+  ADF_EVENT_VSYNC = 0,
+  ADF_EVENT_HOTPLUG = 1,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  ADF_EVENT_DEVICE_CUSTOM = 128,
+  ADF_EVENT_TYPE_MAX = 255,
+};
+enum adf_complete_fence_type {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  ADF_COMPLETE_FENCE_NONE = 0,
+  ADF_COMPLETE_FENCE_PRESENT = 1,
+  ADF_COMPLETE_FENCE_RELEASE = 2,
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_set_event {
+  __u8 type;
+  __u8 enabled;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_event {
+  __u8 type;
+  __u32 length;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_vsync_event {
+  struct adf_event base;
+  __aligned_u64 timestamp;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_hotplug_event {
+  struct adf_event base;
+  __u8 connected;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_MAX_PLANES 4
+struct adf_buffer_config {
+  __u32 overlay_engine;
+  __u32 w;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 h;
+  __u32 format;
+  __s32 fd[ADF_MAX_PLANES];
+  __u32 offset[ADF_MAX_PLANES];
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 pitch[ADF_MAX_PLANES];
+  __u8 n_planes;
+  __s32 acquire_fence;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
+struct adf_post_config {
+  size_t n_interfaces;
+  __u32 __user * interfaces;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  size_t n_bufs;
+  struct adf_buffer_config __user * bufs;
+  size_t custom_data_size;
+  void __user * custom_data;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __s32 complete_fence;
+};
+struct adf_post_config_v2 {
+  __u32 n_interfaces;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u64 interfaces;
+  __u32 n_bufs;
+  __u64 bufs;
+  __u64 custom_data_size;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u64 custom_data;
+  __s32 complete_fence;
+  __u8 complete_fence_type;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_MAX_INTERFACES (4096 / sizeof(__u32))
+struct adf_simple_buffer_alloc {
+  __u16 w;
+  __u16 h;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 format;
+  __s32 fd;
+  __u32 offset;
+  __u32 pitch;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+struct adf_simple_post_config {
+  struct adf_buffer_config buf;
+  __s32 complete_fence;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+struct adf_simple_post_config_v2 {
+  struct adf_buffer_config buf;
+  __s32 complete_fence;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u8 complete_fence_type;
+};
+struct adf_attachment_config {
+  __u32 overlay_engine;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 interface;
+};
+struct adf_device_data {
+  char name[ADF_NAME_LEN];
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  size_t n_attachments;
+  struct adf_attachment_config __user * attachments;
+  size_t n_allowed_attachments;
+  struct adf_attachment_config __user * allowed_attachments;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  size_t custom_data_size;
+  void __user * custom_data;
+};
+#define ADF_MAX_ATTACHMENTS (4096 / sizeof(struct adf_attachment_config))
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_interface_data {
+  char name[ADF_NAME_LEN];
+  __u32 type;
+  __u32 id;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 flags;
+  __u8 dpms_state;
+  __u8 hotplug_detect;
+  __u16 width_mm;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u16 height_mm;
+  struct drm_mode_modeinfo current_mode;
+  size_t n_available_modes;
+  struct drm_mode_modeinfo __user * available_modes;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  size_t custom_data_size;
+  void __user * custom_data;
+};
+#define ADF_MAX_MODES (4096 / sizeof(struct drm_mode_modeinfo))
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_overlay_engine_data {
+  char name[ADF_NAME_LEN];
+  size_t n_supported_formats;
+  __u32 __user * supported_formats;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  size_t custom_data_size;
+  void __user * custom_data;
+};
+#define ADF_MAX_SUPPORTED_FORMATS (4096 / sizeof(__u32))
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_IOCTL_TYPE 'D'
+#define ADF_IOCTL_NR_CUSTOM 128
+#define ADF_SET_EVENT _IOW(ADF_IOCTL_TYPE, 0, struct adf_set_event)
+#define ADF_BLANK _IOW(ADF_IOCTL_TYPE, 1, __u8)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 2, struct adf_post_config)
+#define ADF_SET_MODE _IOW(ADF_IOCTL_TYPE, 3, struct drm_mode_modeinfo)
+#define ADF_GET_DEVICE_DATA _IOR(ADF_IOCTL_TYPE, 4, struct adf_device_data)
+#define ADF_GET_INTERFACE_DATA _IOR(ADF_IOCTL_TYPE, 5, struct adf_interface_data)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_GET_OVERLAY_ENGINE_DATA _IOR(ADF_IOCTL_TYPE, 6, struct adf_overlay_engine_data)
+#define ADF_SIMPLE_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 7, struct adf_simple_post_config)
+#define ADF_SIMPLE_BUFFER_ALLOC _IOW(ADF_IOCTL_TYPE, 8, struct adf_simple_buffer_alloc)
+#define ADF_ATTACH _IOW(ADF_IOCTL_TYPE, 9, struct adf_attachment_config)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define ADF_DETACH _IOW(ADF_IOCTL_TYPE, 10, struct adf_attachment_config)
+#define ADF_POST_CONFIG_V2 _IOW(ADF_IOCTL_TYPE, 11, struct adf_post_config_v2)
+#define ADF_SIMPLE_POST_CONFIG_V2 _IOW(ADF_IOCTL_TYPE, 12, struct adf_simple_post_config_v2)
+#endif
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+
diff --git a/adf/libadf/original-kernel-headers/video/adf.h b/adf/libadf/original-kernel-headers/video/adf.h
new file mode 100644
index 0000000..8293c1d
--- /dev/null
+++ b/adf/libadf/original-kernel-headers/video/adf.h
@@ -0,0 +1,386 @@
+/*
+ * Copyright (C) 2013 Google, Inc.
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#ifndef _UAPI_VIDEO_ADF_H_
+#define _UAPI_VIDEO_ADF_H_
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+#include <drm/drm_fourcc.h>
+#include <drm/drm_mode.h>
+
+#define ADF_NAME_LEN 32
+#define ADF_MAX_CUSTOM_DATA_SIZE 4096
+
+enum adf_interface_type {
+	ADF_INTF_DSI = 0,
+	ADF_INTF_eDP = 1,
+	ADF_INTF_DPI = 2,
+	ADF_INTF_VGA = 3,
+	ADF_INTF_DVI = 4,
+	ADF_INTF_HDMI = 5,
+	ADF_INTF_MEMORY = 6,
+	ADF_INTF_TYPE_DEVICE_CUSTOM = 128,
+	ADF_INTF_TYPE_MAX = (~(__u32)0),
+};
+
+#define ADF_INTF_FLAG_PRIMARY (1 << 0)
+#define ADF_INTF_FLAG_EXTERNAL (1 << 1)
+
+enum adf_event_type {
+	ADF_EVENT_VSYNC = 0,
+	ADF_EVENT_HOTPLUG = 1,
+	ADF_EVENT_DEVICE_CUSTOM = 128,
+	ADF_EVENT_TYPE_MAX = 255,
+};
+
+enum adf_complete_fence_type {
+	/* no fence */
+	ADF_COMPLETE_FENCE_NONE = 0,
+	/* fence fires when the configuration appears on the screen */
+	ADF_COMPLETE_FENCE_PRESENT = 1,
+	/* fence fires when the configuration leaves the screen */
+	ADF_COMPLETE_FENCE_RELEASE = 2,
+};
+
+/**
+ * struct adf_set_event - start or stop subscribing to ADF events
+ *
+ * @type: the type of event to (un)subscribe
+ * @enabled: subscribe or unsubscribe
+ *
+ * After subscribing to an event, userspace may poll() the ADF object's fd
+ * to wait for events or read() to consume the event's data.
+ *
+ * ADF reserves event types 0 to %ADF_EVENT_DEVICE_CUSTOM-1 for its own events.
+ * Devices may use event types %ADF_EVENT_DEVICE_CUSTOM to %ADF_EVENT_TYPE_MAX-1
+ * for driver-private events.
+ */
+struct adf_set_event {
+	__u8 type;
+	__u8 enabled;
+};
+
+/**
+ * struct adf_event - common header for ADF event data
+ *
+ * @type: event type
+ * @length: total size of event data, header inclusive
+ */
+struct adf_event {
+	__u8 type;
+	__u32 length;
+};
+
+/**
+ * struct adf_vsync_event - ADF vsync event
+ *
+ * @base: event header (see &struct adf_event)
+ * @timestamp: time of vsync event, in nanoseconds
+ */
+struct adf_vsync_event {
+	struct adf_event base;
+	__aligned_u64 timestamp;
+};
+
+/**
+ * struct adf_vsync_event - ADF display hotplug event
+ *
+ * @base: event header (see &struct adf_event)
+ * @connected: whether a display is now connected to the interface
+ */
+struct adf_hotplug_event {
+	struct adf_event base;
+	__u8 connected;
+};
+
+#define ADF_MAX_PLANES 4
+/**
+ * struct adf_buffer_config - description of buffer displayed by adf_post_config
+ *
+ * @overlay_engine: id of the target overlay engine
+ * @w: width of display region in pixels
+ * @h: height of display region in pixels
+ * @format: DRM-style fourcc, see drm_fourcc.h for standard formats
+ * @fd: dma_buf fd for each plane
+ * @offset: location of first pixel to scan out, in bytes
+ * @pitch: stride (i.e. length of a scanline including padding) in bytes
+ * @n_planes: number of planes in buffer
+ * @acquire_fence: sync_fence fd which will clear when the buffer is
+ *	ready for display, or <0 if the buffer is already ready
+ */
+struct adf_buffer_config {
+	__u32 overlay_engine;
+
+	__u32 w;
+	__u32 h;
+	__u32 format;
+
+	__s32 fd[ADF_MAX_PLANES];
+	__u32 offset[ADF_MAX_PLANES];
+	__u32 pitch[ADF_MAX_PLANES];
+	__u8 n_planes;
+
+	__s32 acquire_fence;
+};
+#define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
+
+/**
+ * struct adf_post_config - request to flip to a new set of buffers
+ *
+ * This request is equivalent to &struct adf_post_config_v2 with
+ * @complete_fence_type = %ADF_COMPLETE_FENCE_RELEASE.
+ *
+ * @n_interfaces: number of interfaces targeted by the flip (input)
+ * @interfaces: ids of interfaces targeted by the flip (input)
+ * @n_bufs: number of buffers displayed (input)
+ * @bufs: description of buffers displayed (input)
+ * @custom_data_size: size of driver-private data (input)
+ * @custom_data: driver-private data (input)
+ * @complete_fence: sync_fence fd which will clear when this
+ *	configuration has left the screen (output)
+ */
+struct adf_post_config {
+	size_t n_interfaces;
+	__u32 __user *interfaces;
+
+	size_t n_bufs;
+	struct adf_buffer_config __user *bufs;
+
+	size_t custom_data_size;
+	void __user *custom_data;
+
+	__s32 complete_fence;
+};
+
+/**
+ * struct adf_post_config_v2 - request to flip to a new set of buffers
+ *
+ * @n_interfaces: number of interfaces targeted by the flip (input)
+ * @interfaces: ids of interfaces targeted by the flip (input)
+ * @n_bufs: number of buffers displayed (input)
+ * @bufs: description of buffers displayed (input)
+ * @custom_data_size: size of driver-private data (input)
+ * @custom_data: driver-private data (input)
+ * @complete_fence_type: one of &enum adf_complete_fence_type describing what
+ * 	fence to return (input)
+ * @complete_fence: sync_fence fd which will fire at the time
+ * 	requested by @complete_fence_type (output)
+ */
+struct adf_post_config_v2 {
+	__u32 n_interfaces;
+	__u64 interfaces; /* __u32 * packed into __u64 */
+
+	__u32 n_bufs;
+	__u64 bufs; /* struct adf_buffer_config * packed into __u64 */
+
+	__u64 custom_data_size;
+	__u64 custom_data; /* void * packed into __u64 */
+
+	__s32 complete_fence;
+	__u8 complete_fence_type;
+};
+#define ADF_MAX_INTERFACES (4096 / sizeof(__u32))
+
+/**
+ * struct adf_simple_buffer_allocate - request to allocate a "simple" buffer
+ *
+ * @w: width of buffer in pixels (input)
+ * @h: height of buffer in pixels (input)
+ * @format: DRM-style fourcc (input)
+ *
+ * @fd: dma_buf fd (output)
+ * @offset: location of first pixel, in bytes (output)
+ * @pitch: length of a scanline including padding, in bytes (output)
+ *
+ * Simple buffers are analogous to DRM's "dumb" buffers.  They have a single
+ * plane of linear RGB data which can be allocated and scanned out without
+ * any driver-private ioctls or data.
+ *
+ * @format must be a standard RGB format defined in drm_fourcc.h.
+ *
+ * ADF clients must NOT assume that an interface can scan out a simple buffer
+ * allocated by a different ADF interface, even if the two interfaces belong to
+ * the same ADF device.
+ */
+struct adf_simple_buffer_alloc {
+	__u16 w;
+	__u16 h;
+	__u32 format;
+
+	__s32 fd;
+	__u32 offset;
+	__u32 pitch;
+};
+
+/**
+ * struct adf_simple_post_config - request to flip to a single buffer without
+ * driver-private data
+ *
+ * This request is equivalent to &struct adf_simple_post_config_v2 with
+ * @complete_fence_type = %ADF_COMPLETE_FENCE_RELEASE.
+ *
+ * @buf: description of buffer displayed (input)
+ * @complete_fence: sync_fence fd which will clear when this buffer has left the
+ * screen (output)
+ */
+struct adf_simple_post_config {
+	struct adf_buffer_config buf;
+	__s32 complete_fence;
+};
+
+/**
+ * struct adf_simple_post_config_v2 - request to flip to a single buffer without
+ * driver-private data
+ *
+ * @buf: description of buffer displayed (input)
+ * @complete_fence_type: one of &enum adf_complete_fence_type describing what
+ * 	fence to return (input)
+ * @complete_fence: sync_fence fd which will fire at the time
+ * 	requested by @complete_fence_type (output)
+ */
+struct adf_simple_post_config_v2 {
+	struct adf_buffer_config buf;
+	__s32 complete_fence;
+	__u8 complete_fence_type;
+};
+
+/**
+ * struct adf_attachment_config - description of attachment between an overlay
+ * engine and an interface
+ *
+ * @overlay_engine: id of the overlay engine
+ * @interface: id of the interface
+ */
+struct adf_attachment_config {
+	__u32 overlay_engine;
+	__u32 interface;
+};
+
+/**
+ * struct adf_device_data - describes a display device
+ *
+ * @name: display device's name
+ * @n_attachments: the number of current attachments
+ * @attachments: list of current attachments
+ * @n_allowed_attachments: the number of allowed attachments
+ * @allowed_attachments: list of allowed attachments
+ * @custom_data_size: size of driver-private data
+ * @custom_data: driver-private data
+ */
+struct adf_device_data {
+	char name[ADF_NAME_LEN];
+
+	size_t n_attachments;
+	struct adf_attachment_config __user *attachments;
+
+	size_t n_allowed_attachments;
+	struct adf_attachment_config __user *allowed_attachments;
+
+	size_t custom_data_size;
+	void __user *custom_data;
+};
+#define ADF_MAX_ATTACHMENTS (4096 / sizeof(struct adf_attachment_config))
+
+/**
+ * struct adf_device_data - describes a display interface
+ *
+ * @name: display interface's name
+ * @type: interface type (see enum @adf_interface_type)
+ * @id: which interface of type @type;
+ *	e.g. interface DSI.1 -> @type=@ADF_INTF_TYPE_DSI, @id=1
+ * @flags: informational flags (bitmask of %ADF_INTF_FLAG_* values)
+ * @dpms_state: DPMS state (one of @DRM_MODE_DPMS_* defined in drm_mode.h)
+ * @hotplug_detect: whether a display is plugged in
+ * @width_mm: screen width in millimeters, or 0 if unknown
+ * @height_mm: screen height in millimeters, or 0 if unknown
+ * @current_mode: current display mode
+ * @n_available_modes: the number of hardware display modes
+ * @available_modes: list of hardware display modes
+ * @custom_data_size: size of driver-private data
+ * @custom_data: driver-private data
+ */
+struct adf_interface_data {
+	char name[ADF_NAME_LEN];
+
+	__u32 type;
+	__u32 id;
+	/* e.g. type=ADF_INTF_TYPE_DSI, id=1 => DSI.1 */
+	__u32 flags;
+
+	__u8 dpms_state;
+	__u8 hotplug_detect;
+	__u16 width_mm;
+	__u16 height_mm;
+
+	struct drm_mode_modeinfo current_mode;
+	size_t n_available_modes;
+	struct drm_mode_modeinfo __user *available_modes;
+
+	size_t custom_data_size;
+	void __user *custom_data;
+};
+#define ADF_MAX_MODES (4096 / sizeof(struct drm_mode_modeinfo))
+
+/**
+ * struct adf_overlay_engine_data - describes an overlay engine
+ *
+ * @name: overlay engine's name
+ * @n_supported_formats: number of supported formats
+ * @supported_formats: list of supported formats
+ * @custom_data_size: size of driver-private data
+ * @custom_data: driver-private data
+ */
+struct adf_overlay_engine_data {
+	char name[ADF_NAME_LEN];
+
+	size_t n_supported_formats;
+	__u32 __user *supported_formats;
+
+	size_t custom_data_size;
+	void __user *custom_data;
+};
+#define ADF_MAX_SUPPORTED_FORMATS (4096 / sizeof(__u32))
+
+#define ADF_IOCTL_TYPE		'D'
+#define ADF_IOCTL_NR_CUSTOM	128
+
+#define ADF_SET_EVENT		_IOW(ADF_IOCTL_TYPE, 0, struct adf_set_event)
+#define ADF_BLANK		_IOW(ADF_IOCTL_TYPE, 1, __u8)
+#define ADF_POST_CONFIG		_IOW(ADF_IOCTL_TYPE, 2, struct adf_post_config)
+#define ADF_SET_MODE		_IOW(ADF_IOCTL_TYPE, 3, \
+					struct drm_mode_modeinfo)
+#define ADF_GET_DEVICE_DATA	_IOR(ADF_IOCTL_TYPE, 4, struct adf_device_data)
+#define ADF_GET_INTERFACE_DATA	_IOR(ADF_IOCTL_TYPE, 5, \
+					struct adf_interface_data)
+#define ADF_GET_OVERLAY_ENGINE_DATA \
+				_IOR(ADF_IOCTL_TYPE, 6, \
+					struct adf_overlay_engine_data)
+#define ADF_SIMPLE_POST_CONFIG	_IOW(ADF_IOCTL_TYPE, 7, \
+					struct adf_simple_post_config)
+#define ADF_SIMPLE_BUFFER_ALLOC	_IOW(ADF_IOCTL_TYPE, 8, \
+					struct adf_simple_buffer_alloc)
+#define ADF_ATTACH		_IOW(ADF_IOCTL_TYPE, 9, \
+					struct adf_attachment_config)
+#define ADF_DETACH		_IOW(ADF_IOCTL_TYPE, 10, \
+					struct adf_attachment_config)
+
+#define ADF_POST_CONFIG_V2	_IOW(ADF_IOCTL_TYPE, 11, \
+					struct adf_post_config_v2)
+#define ADF_SIMPLE_POST_CONFIG_V2 \
+				_IOW(ADF_IOCTL_TYPE, 12, \
+					struct adf_simple_post_config_v2)
+
+#endif /* _UAPI_VIDEO_ADF_H_ */
diff --git a/adf/libadf/tests/Android.bp b/adf/libadf/tests/Android.bp
new file mode 100644
index 0000000..9b3430e
--- /dev/null
+++ b/adf/libadf/tests/Android.bp
@@ -0,0 +1,23 @@
+//
+// Copyright (C) 2013 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_test {
+    name: "adf-unit-tests",
+    srcs: ["adf_test.cpp"],
+    shared_libs: ["libsync"],
+    static_libs: ["libadf"],
+    cflags: ["-Werror"],
+}
diff --git a/adf/libadf/tests/Android.mk b/adf/libadf/tests/Android.mk
deleted file mode 100644
index 68e5817..0000000
--- a/adf/libadf/tests/Android.mk
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-LOCAL_PATH := $(my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := adf_test.cpp
-LOCAL_MODULE := adf-unit-tests
-LOCAL_STATIC_LIBRARIES := libadf
-LOCAL_CFLAGS += -Werror
-include $(BUILD_NATIVE_TEST)
diff --git a/adf/libadf/tests/adf_test.cpp b/adf/libadf/tests/adf_test.cpp
index 01b2785..82a91f4 100644
--- a/adf/libadf/tests/adf_test.cpp
+++ b/adf/libadf/tests/adf_test.cpp
@@ -20,6 +20,7 @@
 #include <adf/adf.h>
 #include <gtest/gtest.h>
 #include <sys/mman.h>
+#include <sync/sync.h>
 
 class AdfTest : public testing::Test {
 public:
@@ -73,24 +74,6 @@
         FAIL(); /* this should never happen */
     }
 
-    void drawCheckerboard(void *buf, uint32_t w, uint32_t h, uint32_t pitch) {
-        uint8_t *buf8 = reinterpret_cast<uint8_t *>(buf);
-        for (uint32_t y = 0; y < h / 2; y++) {
-            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
-            for (uint32_t x = 0; x < w / 2; x++)
-                scanline[x] = 0xFF0000FF;
-            for (uint32_t x = w / 2; x < w; x++)
-                scanline[x] = 0xFF00FFFF;
-        }
-        for (uint32_t y = h / 2; y < h; y++) {
-            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
-            for (uint32_t x = 0; x < w / 2; x++)
-                scanline[x] = 0xFFFF00FF;
-            for (uint32_t x = w / 2; x < w; x++)
-                scanline[x] = 0xFFFFFFFF;
-        }
-    }
-
     /* various helpers to call ADF and die on failure */
 
     void getInterfaceData(adf_interface_data &data) {
@@ -141,6 +124,42 @@
         free(event);
     }
 
+    void drawCheckerboard(uint32_t &w, uint32_t &h, uint32_t &format,
+            char format_str[ADF_FORMAT_STR_SIZE], int &buf_fd, uint32_t &offset,
+            uint32_t &pitch) {
+        ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
+        ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
+
+        buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
+                &pitch);
+        ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
+                format_str << " buffer failed: " << strerror(-buf_fd);
+        EXPECT_GE(pitch, w * 4);
+
+        void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd,
+                offset);
+        ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " <<
+                format_str << " buffer failed: " << strerror(-errno);
+
+        uint8_t *buf8 = static_cast<uint8_t *>(mapped);
+        for (uint32_t y = 0; y < h / 2; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFF0000FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFF00FFFF;
+        }
+        for (uint32_t y = h / 2; y < h; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFFFF00FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFFFFFFFF;
+        }
+
+        munmap(mapped, pitch * h);
+    }
+
 protected:
     adf_device dev;
     adf_id_t intf_id;
@@ -149,11 +168,13 @@
     int eng;
 
 private:
-    const static adf_id_t dev_id = 0;
+    const static adf_id_t dev_id;
     const static __u32 fmt8888[];
     const static size_t n_fmt8888;
 };
 
+const adf_id_t AdfTest::dev_id = 0;
+
 const __u32 AdfTest::fmt8888[] = {
    DRM_FORMAT_XRGB8888,
    DRM_FORMAT_XBGR8888,
@@ -167,7 +188,7 @@
 const size_t AdfTest::n_fmt8888 = sizeof(fmt8888) / sizeof(fmt8888[0]);
 
 TEST(adf, devices) {
-    adf_id_t *devs;
+    adf_id_t *devs = nullptr;
     ssize_t n_devs = adf_devices(&devs);
     free(devs);
 
@@ -308,27 +329,11 @@
 }
 
 TEST_F(AdfTest, simple_buffer) {
-    uint32_t w = 0, h = 0;
-    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
-
-    uint32_t format = 0;
+    int buf_fd;
+    uint32_t w, h, format, offset, pitch;
     char format_str[ADF_FORMAT_STR_SIZE];
-    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
-
-    uint32_t offset;
-    uint32_t pitch;
-    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
-            &pitch);
-    ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-buf_fd);
-    EXPECT_GE(pitch, w * 4);
-
-    void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd,
-            offset);
-    ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-errno);
-    drawCheckerboard(mapped, w, h, pitch);
-    munmap(mapped, pitch * h);
+    ASSERT_NO_FATAL_FAILURE(drawCheckerboard(w, h, format, format_str,
+            buf_fd, offset, pitch));
 
     ASSERT_NO_FATAL_FAILURE(attach());
     ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
@@ -340,3 +345,59 @@
             format_str << " buffer failed: " << strerror(-release_fence);
     close(release_fence);
 }
+
+TEST_F(AdfTest, simple_buffer_v2) {
+    int buf_fd;
+    uint32_t w, h, format, offset, pitch;
+    char format_str[ADF_FORMAT_STR_SIZE];
+    ASSERT_NO_FATAL_FAILURE(drawCheckerboard(w, h, format, format_str,
+            buf_fd, offset, pitch));
+
+    ASSERT_NO_FATAL_FAILURE(attach());
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+
+    int config_1_release;
+    int err = adf_interface_simple_post_v2(intf, eng_id, w, h,
+            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_RELEASE,
+            &config_1_release);
+    if (err == -ENOTTY) {
+        GTEST_LOG_(INFO) << "ADF_SIMPLE_POST_CONFIG_V2 not supported on this kernel";
+        return;
+    }
+    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-err);
+
+    err = sync_wait(config_1_release, 1000);
+    ASSERT_EQ(-1, err) <<
+            "waiting for config 1's release fence should not have suceeded";
+    ASSERT_EQ(ETIME, errno) <<
+            "config 1's release fence should have timed out, but failed instead: " <<
+            strerror(errno);
+
+    int config_2_present;
+    err = adf_interface_simple_post_v2(intf, eng_id, w, h,
+            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_PRESENT,
+            &config_2_present);
+    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-err);
+
+    err = sync_wait(config_2_present, 1000);
+    ASSERT_EQ(0, err) <<
+            "waiting for config 2's present fence failed: " << strerror(errno);
+    err = sync_wait(config_1_release, 0);
+    ASSERT_EQ(0, err) <<
+            "waiting for config 1's release fence failed: " << strerror(errno);
+    close(config_1_release);
+    close(config_2_present);
+
+    int config_3_no_fence;
+    err = adf_interface_simple_post_v2(intf, eng_id, w, h,
+            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_NONE,
+            &config_3_no_fence);
+    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-err);
+    ASSERT_EQ(-1, config_3_no_fence) <<
+            "fence returned even though the fence type was ADF_COMPLETE_FENCE_NONE";
+
+    close(buf_fd);
+}
diff --git a/adf/libadfhwc/Android.bp b/adf/libadfhwc/Android.bp
new file mode 100644
index 0000000..57a8d76
--- /dev/null
+++ b/adf/libadfhwc/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2013 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_library_static {
+    name: "libadfhwc",
+    srcs: ["adfhwc.cpp"],
+    static_libs: [
+        "libadf",
+        "liblog",
+        "libutils",
+    ],
+    cflags: [
+        "-DLOG_TAG=\"adfhwc\"",
+        "-Werror",
+    ],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+}
diff --git a/adf/libadfhwc/Android.mk b/adf/libadfhwc/Android.mk
deleted file mode 100644
index 898f9c9..0000000
--- a/adf/libadfhwc/Android.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := adfhwc.cpp
-LOCAL_MODULE := libadfhwc
-LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_LIBRARIES := libadf liblog libutils
-LOCAL_CFLAGS += -DLOG_TAG=\"adfhwc\" -Werror
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES += $(LOCAL_EXPORT_C_INCLUDE_DIRS)
-include $(BUILD_STATIC_LIBRARY)
diff --git a/adf/libadfhwc/adfhwc.cpp b/adf/libadfhwc/adfhwc.cpp
index 21f245e..63c0f75 100644
--- a/adf/libadfhwc/adfhwc.cpp
+++ b/adf/libadfhwc/adfhwc.cpp
@@ -20,12 +20,12 @@
 #include <pthread.h>
 #include <sys/resource.h>
 
+#include <log/log.h>
+#include <utils/Vector.h>
+
 #include <adf/adf.h>
 #include <adfhwc/adfhwc.h>
 
-#include <cutils/log.h>
-#include <utils/Vector.h>
-
 struct adf_hwc_helper {
     adf_hwc_event_callbacks const *event_cb;
     void *event_cb_data;
@@ -166,6 +166,71 @@
     return 0;
 }
 
+static int32_t adf_display_attribute_hwc2(const adf_interface_data &data,
+        const drm_mode_modeinfo &mode, const uint32_t attribute)
+{
+    switch (attribute) {
+    case HWC2_ATTRIBUTE_VSYNC_PERIOD:
+        if (mode.vrefresh)
+            return 1000000000 / mode.vrefresh;
+        return 0;
+
+    case HWC2_ATTRIBUTE_WIDTH:
+        return mode.hdisplay;
+
+    case HWC2_ATTRIBUTE_HEIGHT:
+        return mode.vdisplay;
+
+    case HWC2_ATTRIBUTE_DPI_X:
+        return dpi(mode.hdisplay, data.width_mm);
+
+    case HWC2_ATTRIBUTE_DPI_Y:
+        return dpi(mode.vdisplay, data.height_mm);
+
+    default:
+        ALOGE("unknown display attribute %u", attribute);
+        return -EINVAL;
+    }
+}
+
+int adf_getDisplayAttributes_hwc2(struct adf_hwc_helper *dev, int disp,
+        uint32_t config, const uint32_t *attributes, int32_t *values)
+{
+    if ((size_t)disp >= dev->intf_fds.size())
+        return -EINVAL;
+
+    if (config >= dev->display_configs.size())
+        return -EINVAL;
+
+    adf_interface_data data;
+    int err = adf_get_interface_data(dev->intf_fds[disp], &data);
+    if (err < 0) {
+        ALOGE("failed to get ADF interface data: %s", strerror(err));
+        return err;
+    }
+
+    for (int i = 0; attributes[i] != HWC2_ATTRIBUTE_INVALID; i++)
+        values[i] = adf_display_attribute_hwc2(data,
+                dev->display_configs[config], attributes[i]);
+
+    adf_free_interface_data(&data);
+    return 0;
+}
+
+int adf_set_active_config_hwc2(struct adf_hwc_helper *dev, int disp,
+        uint32_t config)
+{
+    if ((size_t)disp >= dev->intf_fds.size())
+        return -EINVAL;
+
+    if (config >= dev->display_configs.size())
+        return -EINVAL;
+
+    struct drm_mode_modeinfo mode = dev->display_configs[config];
+
+    return adf_interface_set_mode(dev->intf_fds[disp], &mode);
+}
+
 static void handle_adf_event(struct adf_hwc_helper *dev, int disp)
 {
     adf_event *event;
@@ -208,28 +273,39 @@
 
     setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
 
-    pollfd *fds = new pollfd[dev->intf_fds.size()];
+    struct sigaction action = { };
+    sigemptyset(&action.sa_mask);
+    action.sa_flags = 0;
+    action.sa_handler = [](int) { pthread_exit(0); };
+
+    if (sigaction(SIGUSR2, &action, NULL) < 0) {
+        ALOGE("failed to set thread exit action %s", strerror(errno));
+        return NULL;
+    }
+
+    sigset_t signal_set;
+    sigemptyset(&signal_set);
+    sigaddset(&signal_set, SIGUSR2);
+
+    pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
+
+    pollfd fds[dev->intf_fds.size()];
     for (size_t i = 0; i < dev->intf_fds.size(); i++) {
         fds[i].fd = dev->intf_fds[i];
         fds[i].events = POLLIN | POLLPRI;
     }
 
     while (true) {
-        int err = poll(fds, dev->intf_fds.size(), -1);
-
-        if (err > 0) {
-            for (size_t i = 0; i < dev->intf_fds.size(); i++)
-                if (fds[i].revents & (POLLIN | POLLPRI))
-                    handle_adf_event(dev, i);
-        }
-        else if (err == -1) {
-            if (errno == EINTR)
-                break;
+        if (TEMP_FAILURE_RETRY(poll(fds, dev->intf_fds.size(), -1)) < 0) {
             ALOGE("error in event thread: %s", strerror(errno));
+            break;
         }
+
+        for (size_t i = 0; i < dev->intf_fds.size(); i++)
+            if (fds[i].revents & (POLLIN | POLLPRI))
+                handle_adf_event(dev, i);
     }
 
-    delete [] fds;
     return NULL;
 }
 
@@ -264,6 +340,12 @@
         }
     }
 
+    sigset_t signal_set;
+    sigemptyset(&signal_set);
+    sigaddset(&signal_set, SIGUSR2);
+
+    pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
+
     ret = pthread_create(&dev_ret->event_thread, NULL, adf_event_thread,
             dev_ret);
     if (ret) {
@@ -284,7 +366,7 @@
 
 void adf_hwc_close(struct adf_hwc_helper *dev)
 {
-    pthread_kill(dev->event_thread, SIGTERM);
+    pthread_kill(dev->event_thread, SIGUSR2);
     pthread_join(dev->event_thread, NULL);
 
     for (size_t i = 0; i < dev->intf_fds.size(); i++)
diff --git a/adf/libadfhwc/include/adfhwc/adfhwc.h b/adf/libadfhwc/include/adfhwc/adfhwc.h
index 71e7624..4f70925 100644
--- a/adf/libadfhwc/include/adfhwc/adfhwc.h
+++ b/adf/libadfhwc/include/adfhwc/adfhwc.h
@@ -23,6 +23,7 @@
 #include <video/adf.h>
 
 #include <hardware/hwcomposer.h>
+#include <hardware/hwcomposer2.h>
 
 struct adf_hwc_helper;
 
@@ -123,6 +124,16 @@
         uint32_t *configs, size_t *numConfigs);
 int adf_getDisplayAttributes(struct adf_hwc_helper *dev, int disp,
         uint32_t config, const uint32_t *attributes, int32_t *values);
+/**
+ * Generic implementation of common HWC2 functions.
+ *
+ * The HWC2 should not return these functions directly through getFunction.
+ * Instead, the HWC2 should return stub functions which call these helpers.
+ */
+int adf_getDisplayAttributes_hwc2(struct adf_hwc_helper *dev, int disp,
+        uint32_t config, const uint32_t *attributes, int32_t *values);
+int adf_set_active_config_hwc2(struct adf_hwc_helper *dev, int disp,
+        uint32_t config);
 
 __END_DECLS
 
diff --git a/base/.clang-format b/base/.clang-format
deleted file mode 100644
index 2b83a1f..0000000
--- a/base/.clang-format
+++ /dev/null
@@ -1,11 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 2
-PointerAlignment: Left
-TabWidth: 2
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/base/.clang-format b/base/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/base/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/base/Android.bp b/base/Android.bp
new file mode 100644
index 0000000..a8dda5d
--- /dev/null
+++ b/base/Android.bp
@@ -0,0 +1,139 @@
+//
+// 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.
+//
+
+libbase_cppflags = [
+    "-Wall",
+    "-Wextra",
+    "-Werror",
+]
+
+cc_library_headers {
+    name: "libbase_headers",
+    vendor_available: true,
+    host_supported: true,
+    export_include_dirs: ["include"],
+
+    header_libs: ["libutils_headers"],
+    export_header_lib_headers: ["libutils_headers"],
+
+    target: {
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
+
+cc_library {
+    name: "libbase",
+    vendor_available: true,
+    clang: true,
+    host_supported: true,
+    srcs: [
+        "file.cpp",
+        "logging.cpp",
+        "parsenetaddress.cpp",
+        "quick_exit.cpp",
+        "stringprintf.cpp",
+        "strings.cpp",
+        "test_utils.cpp",
+    ],
+
+    header_libs: ["libbase_headers"],
+    export_header_lib_headers: ["libbase_headers"],
+
+    cppflags: libbase_cppflags,
+    shared_libs: ["liblog"],
+    target: {
+        android: {
+            srcs: [
+                "errors_unix.cpp",
+                "properties.cpp",
+            ],
+            cppflags: ["-Wexit-time-destructors"],
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
+        },
+        darwin: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+        },
+        linux_bionic: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+            enabled: true,
+        },
+        linux: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+        },
+        windows: {
+            srcs: [
+                "errors_windows.cpp",
+                "utf8.cpp",
+            ],
+            enabled: true,
+        },
+    },
+}
+
+// Tests
+// ------------------------------------------------------------------------------
+cc_test {
+    name: "libbase_test",
+    host_supported: true,
+    clang: true,
+    srcs: [
+        "endian_test.cpp",
+        "errors_test.cpp",
+        "file_test.cpp",
+        "logging_test.cpp",
+        "parsedouble_test.cpp",
+        "parseint_test.cpp",
+        "parsenetaddress_test.cpp",
+        "quick_exit_test.cpp",
+        "stringprintf_test.cpp",
+        "strings_test.cpp",
+        "test_main.cpp",
+    ],
+    target: {
+        android: {
+            srcs: ["properties_test.cpp"],
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
+        },
+        windows: {
+            srcs: ["utf8_test.cpp"],
+            enabled: true,
+        },
+    },
+    local_include_dirs: ["."],
+    cppflags: libbase_cppflags,
+    shared_libs: ["libbase"],
+    compile_multilib: "both",
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
diff --git a/base/Android.mk b/base/Android.mk
deleted file mode 100644
index 1693e74..0000000
--- a/base/Android.mk
+++ /dev/null
@@ -1,140 +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)
-
-libbase_src_files := \
-    file.cpp \
-    logging.cpp \
-    parsenetaddress.cpp \
-    stringprintf.cpp \
-    strings.cpp \
-    test_utils.cpp \
-
-libbase_linux_src_files := \
-    errors_unix.cpp \
-
-libbase_darwin_src_files := \
-    errors_unix.cpp \
-
-libbase_windows_src_files := \
-    errors_windows.cpp \
-    utf8.cpp \
-
-libbase_test_src_files := \
-    errors_test.cpp \
-    file_test.cpp \
-    logging_test.cpp \
-    parseint_test.cpp \
-    parsenetaddress_test.cpp \
-    stringprintf_test.cpp \
-    strings_test.cpp \
-    test_main.cpp \
-
-libbase_test_windows_src_files := \
-    utf8_test.cpp \
-
-libbase_cppflags := \
-    -Wall \
-    -Wextra \
-    -Werror \
-
-libbase_linux_cppflags := \
-    -Wexit-time-destructors \
-
-libbase_darwin_cppflags := \
-    -Wexit-time-destructors \
-
-# Device
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_CLANG := true
-LOCAL_SRC_FILES := $(libbase_src_files) $(libbase_linux_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CPPFLAGS := $(libbase_cppflags) $(libbase_linux_cppflags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_MULTILIB := both
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_CLANG := true
-LOCAL_WHOLE_STATIC_LIBRARIES := libbase
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_MULTILIB := both
-include $(BUILD_SHARED_LIBRARY)
-
-# Host
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_SRC_FILES := $(libbase_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_CPPFLAGS_darwin := $(libbase_darwin_cppflags)
-LOCAL_CPPFLAGS_linux := $(libbase_linux_cppflags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase
-LOCAL_WHOLE_STATIC_LIBRARIES := libbase
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Tests
-# ------------------------------------------------------------------------------
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase_test
-LOCAL_CLANG := true
-LOCAL_SRC_FILES := $(libbase_test_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_test_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_test_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_test_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbase_test
-LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_SRC_FILES := $(libbase_test_src_files)
-LOCAL_SRC_FILES_darwin := $(libbase_test_darwin_src_files)
-LOCAL_SRC_FILES_linux := $(libbase_test_linux_src_files)
-LOCAL_SRC_FILES_windows := $(libbase_test_windows_src_files)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)
-LOCAL_CPPFLAGS := $(libbase_cppflags)
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/base/endian_test.cpp b/base/endian_test.cpp
new file mode 100644
index 0000000..963ab13
--- /dev/null
+++ b/base/endian_test.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "android-base/endian.h"
+
+#include <gtest/gtest.h>
+
+TEST(endian, constants) {
+  ASSERT_TRUE(__LITTLE_ENDIAN == LITTLE_ENDIAN);
+  ASSERT_TRUE(__BIG_ENDIAN == BIG_ENDIAN);
+  ASSERT_TRUE(__BYTE_ORDER == BYTE_ORDER);
+
+  ASSERT_EQ(__LITTLE_ENDIAN, __BYTE_ORDER);
+}
+
+TEST(endian, smoke) {
+  static constexpr uint16_t le16 = 0x1234;
+  static constexpr uint32_t le32 = 0x12345678;
+  static constexpr uint64_t le64 = 0x123456789abcdef0;
+
+  static constexpr uint16_t be16 = 0x3412;
+  static constexpr uint32_t be32 = 0x78563412;
+  static constexpr uint64_t be64 = 0xf0debc9a78563412;
+
+  ASSERT_EQ(be16, htons(le16));
+  ASSERT_EQ(be32, htonl(le32));
+  ASSERT_EQ(be64, htonq(le64));
+
+  ASSERT_EQ(le16, ntohs(be16));
+  ASSERT_EQ(le32, ntohl(be32));
+  ASSERT_EQ(le64, ntohq(be64));
+
+  ASSERT_EQ(be16, htobe16(le16));
+  ASSERT_EQ(be32, htobe32(le32));
+  ASSERT_EQ(be64, htobe64(le64));
+
+  ASSERT_EQ(le16, betoh16(be16));
+  ASSERT_EQ(le32, betoh32(be32));
+  ASSERT_EQ(le64, betoh64(be64));
+
+  ASSERT_EQ(le16, htole16(le16));
+  ASSERT_EQ(le32, htole32(le32));
+  ASSERT_EQ(le64, htole64(le64));
+
+  ASSERT_EQ(le16, letoh16(le16));
+  ASSERT_EQ(le32, letoh32(le32));
+  ASSERT_EQ(le64, letoh64(le64));
+
+  ASSERT_EQ(le16, be16toh(be16));
+  ASSERT_EQ(le32, be32toh(be32));
+  ASSERT_EQ(le64, be64toh(be64));
+
+  ASSERT_EQ(le16, le16toh(le16));
+  ASSERT_EQ(le32, le32toh(le32));
+  ASSERT_EQ(le64, le64toh(le64));
+}
diff --git a/base/file.cpp b/base/file.cpp
index da1adba..d4e5894 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -18,17 +18,28 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <libgen.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <unistd.h>
 
+#include <memory>
+#include <mutex>
 #include <string>
+#include <vector>
 
 #include "android-base/macros.h"  // For TEMP_FAILURE_RETRY on Darwin.
+#include "android-base/logging.h"
 #include "android-base/utf8.h"
-#define LOG_TAG "base.file"
-#include "cutils/log.h"
 #include "utils/Compat.h"
 
+#if defined(__APPLE__)
+#include <mach-o/dyld.h>
+#endif
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+
 namespace android {
 namespace base {
 
@@ -38,6 +49,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) {
@@ -46,10 +65,11 @@
   return (n == 0) ? true : false;
 }
 
-bool ReadFileToString(const std::string& path, std::string* content) {
+bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
   content->clear();
 
-  int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_BINARY));
+  int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
+  int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags));
   if (fd == -1) {
     return false;
   }
@@ -82,26 +102,28 @@
 
 #if !defined(_WIN32)
 bool WriteStringToFile(const std::string& content, const std::string& path,
-                       mode_t mode, uid_t owner, gid_t group) {
-  int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW | O_BINARY;
+                       mode_t mode, uid_t owner, gid_t group,
+                       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));
   if (fd == -1) {
-    ALOGE("android::WriteStringToFile open failed: %s", strerror(errno));
+    PLOG(ERROR) << "android::WriteStringToFile open failed";
     return false;
   }
 
   // We do an explicit fchmod here because we assume that the caller really
   // meant what they said and doesn't want the umask-influenced mode.
   if (fchmod(fd, mode) == -1) {
-    ALOGE("android::WriteStringToFile fchmod failed: %s", strerror(errno));
+    PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
     return CleanUpAfterFailedWrite(path);
   }
   if (fchown(fd, owner, group) == -1) {
-    ALOGE("android::WriteStringToFile fchown failed: %s", strerror(errno));
+    PLOG(ERROR) << "android::WriteStringToFile fchown failed";
     return CleanUpAfterFailedWrite(path);
   }
   if (!WriteStringToFd(content, fd)) {
-    ALOGE("android::WriteStringToFile write failed: %s", strerror(errno));
+    PLOG(ERROR) << "android::WriteStringToFile write failed";
     return CleanUpAfterFailedWrite(path);
   }
   close(fd);
@@ -109,8 +131,10 @@
 }
 #endif
 
-bool WriteStringToFile(const std::string& content, const std::string& path) {
-  int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW | O_BINARY;
+bool WriteStringToFile(const std::string& content, const std::string& path,
+                       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));
   if (fd == -1) {
     return false;
@@ -172,5 +196,123 @@
   return true;
 }
 
+#if !defined(_WIN32)
+bool Readlink(const std::string& path, std::string* result) {
+  result->clear();
+
+  // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
+  // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
+  // waste memory to just start there. We add 1 so that we can recognize
+  // whether it actually fit (rather than being truncated to 4095).
+  std::vector<char> buf(4095 + 1);
+  while (true) {
+    ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
+    // Unrecoverable error?
+    if (size == -1) return false;
+    // It fit! (If size == buf.size(), it may have been truncated.)
+    if (static_cast<size_t>(size) < buf.size()) {
+      result->assign(&buf[0], size);
+      return true;
+    }
+    // Double our buffer and try again.
+    buf.resize(buf.size() * 2);
+  }
+}
+#endif
+
+#if !defined(_WIN32)
+bool Realpath(const std::string& path, std::string* result) {
+  result->clear();
+
+  char* realpath_buf = realpath(path.c_str(), nullptr);
+  if (realpath_buf == nullptr) {
+    return false;
+  }
+  result->assign(realpath_buf);
+  free(realpath_buf);
+  return true;
+}
+#endif
+
+std::string GetExecutablePath() {
+#if defined(__linux__)
+  std::string path;
+  android::base::Readlink("/proc/self/exe", &path);
+  return path;
+#elif defined(__APPLE__)
+  char path[PATH_MAX + 1];
+  uint32_t path_len = sizeof(path);
+  int rc = _NSGetExecutablePath(path, &path_len);
+  if (rc < 0) {
+    std::unique_ptr<char> path_buf(new char[path_len]);
+    _NSGetExecutablePath(path_buf.get(), &path_len);
+    return path_buf.get();
+  }
+  return path;
+#elif defined(_WIN32)
+  char path[PATH_MAX + 1];
+  DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
+  if (result == 0 || result == sizeof(path) - 1) return "";
+  path[PATH_MAX - 1] = 0;
+  return path;
+#else
+#error unknown OS
+#endif
+}
+
+std::string GetExecutableDirectory() {
+  return Dirname(GetExecutablePath());
+}
+
+std::string Basename(const std::string& path) {
+  // Copy path because basename may modify the string passed in.
+  std::string result(path);
+
+#if !defined(__BIONIC__)
+  // Use lock because basename() may write to a process global and return a
+  // pointer to that. Note that this locking strategy only works if all other
+  // callers to basename in the process also grab this same lock, but its
+  // better than nothing.  Bionic's basename returns a thread-local buffer.
+  static std::mutex& basename_lock = *new std::mutex();
+  std::lock_guard<std::mutex> lock(basename_lock);
+#endif
+
+  // Note that if std::string uses copy-on-write strings, &str[0] will cause
+  // the copy to be made, so there is no chance of us accidentally writing to
+  // the storage for 'path'.
+  char* name = basename(&result[0]);
+
+  // In case basename returned a pointer to a process global, copy that string
+  // before leaving the lock.
+  result.assign(name);
+
+  return result;
+}
+
+std::string Dirname(const std::string& path) {
+  // Copy path because dirname may modify the string passed in.
+  std::string result(path);
+
+#if !defined(__BIONIC__)
+  // Use lock because dirname() may write to a process global and return a
+  // pointer to that. Note that this locking strategy only works if all other
+  // callers to dirname in the process also grab this same lock, but its
+  // better than nothing.  Bionic's dirname returns a thread-local buffer.
+  static std::mutex& dirname_lock = *new std::mutex();
+  std::lock_guard<std::mutex> lock(dirname_lock);
+#endif
+
+  // Note that if std::string uses copy-on-write strings, &str[0] will cause
+  // the copy to be made, so there is no chance of us accidentally writing to
+  // the storage for 'path'.
+  char* parent = dirname(&result[0]);
+
+  // In case dirname returned a pointer to a process global, copy that string
+  // before leaving the lock.
+  result.assign(parent);
+
+  return result;
+}
+
 }  // namespace base
 }  // namespace android
diff --git a/base/file_test.cpp b/base/file_test.cpp
index 17755bf..02b431d 100644
--- a/base/file_test.cpp
+++ b/base/file_test.cpp
@@ -45,6 +45,24 @@
   EXPECT_EQ("abc", s);
 }
 
+// symlinks require elevated privileges on Windows.
+#if !defined(_WIN32)
+TEST(file, ReadFileToString_WriteStringToFile_symlink) {
+  TemporaryFile target, link;
+  ASSERT_EQ(0, unlink(link.path));
+  ASSERT_EQ(0, symlink(target.path, link.path));
+  ASSERT_FALSE(android::base::WriteStringToFile("foo", link.path, false));
+  ASSERT_EQ(ELOOP, errno);
+  ASSERT_TRUE(android::base::WriteStringToFile("foo", link.path, true));
+
+  std::string s;
+  ASSERT_FALSE(android::base::ReadFileToString(link.path, &s));
+  ASSERT_EQ(ELOOP, errno);
+  ASSERT_TRUE(android::base::ReadFileToString(link.path, &s, true));
+  ASSERT_EQ("foo", s);
+}
+#endif
+
 // WriteStringToFile2 is explicitly for setting Unix permissions, which make no
 // sense on Windows.
 #if !defined(_WIN32)
@@ -110,3 +128,132 @@
   ASSERT_FALSE(android::base::RemoveFileIfExists(td.path, &err));
   ASSERT_EQ("is not a regular or symbol link file", err);
 }
+
+TEST(file, Readlink) {
+#if !defined(_WIN32)
+  // Linux doesn't allow empty symbolic links.
+  std::string min("x");
+  // ext2 and ext4 both have PAGE_SIZE limits.
+  // If file encryption is enabled, there's extra overhead to store the
+  // size of the encrypted symlink target. There's also an off-by-one
+  // in current kernels (and marlin/sailfish where we're seeing this
+  // failure are still on 3.18, far from current). http://b/33306057.
+  std::string max(static_cast<size_t>(4096 - 2 - 1 - 1), 'x');
+
+  TemporaryDir td;
+  std::string min_path{std::string(td.path) + "/" + "min"};
+  std::string max_path{std::string(td.path) + "/" + "max"};
+
+  ASSERT_EQ(0, symlink(min.c_str(), min_path.c_str()));
+  ASSERT_EQ(0, symlink(max.c_str(), max_path.c_str()));
+
+  std::string result;
+
+  result = "wrong";
+  ASSERT_TRUE(android::base::Readlink(min_path, &result));
+  ASSERT_EQ(min, result);
+
+  result = "wrong";
+  ASSERT_TRUE(android::base::Readlink(max_path, &result));
+  ASSERT_EQ(max, result);
+#endif
+}
+
+TEST(file, Realpath) {
+#if !defined(_WIN32)
+  TemporaryDir td;
+  std::string basename = android::base::Basename(td.path);
+  std::string dir_name = android::base::Dirname(td.path);
+  std::string base_dir_name = android::base::Basename(dir_name);
+
+  {
+    std::string path = dir_name + "/../" + base_dir_name + "/" + basename;
+    std::string result;
+    ASSERT_TRUE(android::base::Realpath(path, &result));
+    ASSERT_EQ(td.path, result);
+  }
+
+  {
+    std::string path = std::string(td.path) + "/..";
+    std::string result;
+    ASSERT_TRUE(android::base::Realpath(path, &result));
+    ASSERT_EQ(dir_name, result);
+  }
+
+  {
+    errno = 0;
+    std::string path = std::string(td.path) + "/foo.noent";
+    std::string result = "wrong";
+    ASSERT_TRUE(!android::base::Realpath(path, &result));
+    ASSERT_TRUE(result.empty());
+    ASSERT_EQ(ENOENT, errno);
+  }
+#endif
+}
+
+TEST(file, GetExecutableDirectory) {
+  std::string path = android::base::GetExecutableDirectory();
+  ASSERT_NE("", path);
+  ASSERT_NE(android::base::GetExecutablePath(), path);
+  ASSERT_EQ('/', path[0]);
+  ASSERT_NE('/', path[path.size() - 1]);
+}
+
+TEST(file, GetExecutablePath) {
+  ASSERT_NE("", android::base::GetExecutablePath());
+}
+
+TEST(file, Basename) {
+  EXPECT_EQ("sh", android::base::Basename("/system/bin/sh"));
+  EXPECT_EQ("sh", android::base::Basename("sh"));
+  EXPECT_EQ("sh", android::base::Basename("/system/bin/sh/"));
+}
+
+TEST(file, Dirname) {
+  EXPECT_EQ("/system/bin", android::base::Dirname("/system/bin/sh"));
+  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/endian.h b/base/include/android-base/endian.h
new file mode 100644
index 0000000..6eb677c
--- /dev/null
+++ b/base/include/android-base/endian.h
@@ -0,0 +1,90 @@
+/*
+ * 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_ENDIAN_H
+#define ANDROID_BASE_ENDIAN_H
+
+/* A cross-platform equivalent of bionic's <sys/endian.h>. */
+
+#if defined(__BIONIC__)
+
+#include <sys/endian.h>
+
+#elif defined(__GLIBC__)
+
+/* glibc's <endian.h> is like bionic's <sys/endian.h>. */
+#include <endian.h>
+
+/* glibc keeps htons and htonl in <netinet/in.h>. */
+#include <netinet/in.h>
+
+/* glibc doesn't have the 64-bit variants. */
+#define htonq(x) htobe64(x)
+#define ntohq(x) be64toh(x)
+
+/* glibc has different names to BSD for these. */
+#define betoh16(x) be16toh(x)
+#define betoh32(x) be32toh(x)
+#define betoh64(x) be64toh(x)
+
+#else
+
+/* Mac OS and Windows have nothing. */
+
+#define __LITTLE_ENDIAN 1234
+#define LITTLE_ENDIAN __LITTLE_ENDIAN
+
+#define __BIG_ENDIAN 4321
+#define BIG_ENDIAN __BIG_ENDIAN
+
+#define __BYTE_ORDER __LITTLE_ENDIAN
+#define BYTE_ORDER __BYTE_ORDER
+
+#define htons(x) __builtin_bswap16(x)
+#define htonl(x) __builtin_bswap32(x)
+#define htonq(x) __builtin_bswap64(x)
+
+#define ntohs(x) __builtin_bswap16(x)
+#define ntohl(x) __builtin_bswap32(x)
+#define ntohq(x) __builtin_bswap64(x)
+
+#define htobe16(x) __builtin_bswap16(x)
+#define htobe32(x) __builtin_bswap32(x)
+#define htobe64(x) __builtin_bswap64(x)
+
+#define betoh16(x) __builtin_bswap16(x)
+#define betoh32(x) __builtin_bswap32(x)
+#define betoh64(x) __builtin_bswap64(x)
+
+#define htole16(x) (x)
+#define htole32(x) (x)
+#define htole64(x) (x)
+
+#define letoh16(x) (x)
+#define letoh32(x) (x)
+#define letoh64(x) (x)
+
+#define be16toh(x) __builtin_bswap16(x)
+#define be32toh(x) __builtin_bswap32(x)
+#define be64toh(x) __builtin_bswap64(x)
+
+#define le16toh(x) (x)
+#define le32toh(x) (x)
+#define le64toh(x) (x)
+
+#endif
+
+#endif  // ANDROID_BASE_ENDIAN_H
diff --git a/base/include/android-base/file.h b/base/include/android-base/file.h
index aa18ea7..651f529 100644
--- a/base/include/android-base/file.h
+++ b/base/include/android-base/file.h
@@ -28,14 +28,17 @@
 namespace base {
 
 bool ReadFdToString(int fd, std::string* content);
-bool ReadFileToString(const std::string& path, std::string* content);
+bool ReadFileToString(const std::string& path, std::string* content,
+                      bool follow_symlinks = false);
 
-bool WriteStringToFile(const std::string& content, const std::string& path);
+bool WriteStringToFile(const std::string& content, const std::string& path,
+                       bool follow_symlinks = false);
 bool WriteStringToFd(const std::string& content, int fd);
 
 #if !defined(_WIN32)
 bool WriteStringToFile(const std::string& content, const std::string& path,
-                       mode_t mode, uid_t owner, gid_t group);
+                       mode_t mode, uid_t owner, gid_t group,
+                       bool follow_symlinks = false);
 #endif
 
 bool ReadFully(int fd, void* data, size_t byte_count);
@@ -43,6 +46,19 @@
 
 bool RemoveFileIfExists(const std::string& path, std::string* err = nullptr);
 
+#if !defined(_WIN32)
+bool Realpath(const std::string& path, std::string* result);
+bool Readlink(const std::string& path, std::string* result);
+#endif
+
+std::string GetExecutablePath();
+std::string GetExecutableDirectory();
+
+// Like the regular basename and dirname, but thread-safe on all
+// platforms and capable of correctly handling exotic Windows paths.
+std::string Basename(const std::string& path);
+std::string Dirname(const std::string& path);
+
 }  // namespace base
 }  // namespace android
 
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index d3f9d0c..e78edbb 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -17,6 +17,37 @@
 #ifndef ANDROID_BASE_LOGGING_H
 #define ANDROID_BASE_LOGGING_H
 
+//
+// Google-style C++ logging.
+//
+
+// This header provides a C++ stream interface to logging.
+//
+// To log:
+//
+//   LOG(INFO) << "Some text; " << some_value;
+//
+// Replace `INFO` with any severity from `enum LogSeverity`.
+//
+// To log the result of a failed function and include the string
+// representation of `errno` at the end:
+//
+//   PLOG(ERROR) << "Write failed";
+//
+// The output will be something like `Write failed: I/O error`.
+// Remember this as 'P' as in perror(3).
+//
+// To output your own types, simply implement operator<< as normal.
+//
+// By default, output goes to logcat on Android and stderr on the host.
+// A process can use `SetLogger` to decide where all logging goes.
+// Implementations are provided for logcat, stderr, and dmesg.
+
+// This header also provides assertions:
+//
+//   CHECK(must_be_true);
+//   CHECK_EQ(a, b) << z_is_interesting_too;
+
 // NOTE: For Windows, you must include logging.h after windows.h to allow the
 // following code to suppress the evil ERROR macro:
 #ifdef _WIN32
@@ -41,6 +72,7 @@
   INFO,
   WARNING,
   ERROR,
+  FATAL_WITHOUT_ABORT,
   FATAL,
 };
 
@@ -50,11 +82,14 @@
   SYSTEM,
 };
 
-typedef std::function<void(LogId, LogSeverity, const char*, const char*,
-                           unsigned int, const char*)> LogFunction;
+using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
+                                       unsigned int, const char*)>;
+using AbortFunction = std::function<void(const char*)>;
 
-extern void StderrLogger(LogId, LogSeverity, const char*, const char*,
-                         unsigned int, const char*);
+void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
+void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
+
+void DefaultAborter(const char* abort_message);
 
 #ifdef __ANDROID__
 // We expose this even though it is the default because a user that wants to
@@ -79,17 +114,21 @@
 // The tag (or '*' for the global level) comes first, followed by a colon and a
 // letter indicating the minimum priority level we're expected to log.  This can
 // be used to reveal or conceal logs with specific tags.
-extern void InitLogging(char* argv[], LogFunction&& logger);
-
-// Configures logging using the default logger (logd for the device, stderr for
-// the host).
-extern void InitLogging(char* argv[]);
+#ifdef __ANDROID__
+#define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
+#else
+#define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
+#endif
+void InitLogging(char* argv[],
+                 LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
+                 AbortFunction&& aborter = DefaultAborter);
+#undef INIT_LOGGING_DEFAULT_LOGGER
 
 // Replace the current logger.
-extern void SetLogger(LogFunction&& logger);
+void SetLogger(LogFunction&& logger);
 
-// Get the minimum severity level for logging.
-extern LogSeverity GetMinimumLogSeverity();
+// Replace the current aborter.
+void SetAborter(AbortFunction&& aborter);
 
 class ErrnoRestorer {
  public:
@@ -112,6 +151,39 @@
   DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
 };
 
+// A helper macro that produces an expression that accepts both a qualified name and an
+// unqualified name for a LogSeverity, and returns a LogSeverity value.
+// Note: DO NOT USE DIRECTLY. This is an implementation detail.
+#define SEVERITY_LAMBDA(severity) ([&]() {    \
+  using ::android::base::VERBOSE;             \
+  using ::android::base::DEBUG;               \
+  using ::android::base::INFO;                \
+  using ::android::base::WARNING;             \
+  using ::android::base::ERROR;               \
+  using ::android::base::FATAL_WITHOUT_ABORT; \
+  using ::android::base::FATAL;               \
+  return (severity); }())
+
+// Defines whether the given severity will be logged or silently swallowed.
+#define WOULD_LOG(severity) \
+  UNLIKELY((SEVERITY_LAMBDA(severity)) >= ::android::base::GetMinimumLogSeverity())
+
+// Get an ostream that can be used for logging at the given severity and to the default
+// destination.
+//
+// Notes:
+// 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter
+//    usage manually.
+// 2) This does not save and restore errno.
+#define LOG_STREAM(severity) LOG_STREAM_TO(DEFAULT, severity)
+
+// Get an ostream that can be used for logging at the given severity and to the
+// given destination. The same notes as for LOG_STREAM apply.
+#define LOG_STREAM_TO(dest, severity)                                   \
+  ::android::base::LogMessage(__FILE__, __LINE__,                       \
+                              ::android::base::dest,                    \
+                              SEVERITY_LAMBDA(severity), -1).stream()
+
 // Logs a message to logcat on Android otherwise to stderr. If the severity is
 // FATAL it also causes an abort. For example:
 //
@@ -124,29 +196,36 @@
 // else statement after LOG() macro, it won't bind to the if statement in the macro.
 // do-while(0) statement doesn't work here. Because we need to support << operator
 // following the macro, like "LOG(DEBUG) << xxx;".
-#define LOG_TO(dest, severity)                                                        \
-  UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) &&  \
-    ::android::base::ErrnoRestorer() &&                                               \
-      ::android::base::LogMessage(__FILE__, __LINE__,                                 \
-          ::android::base::dest,                                                      \
-          ::android::base::severity, -1).stream()
+
+#define LOG_TO(dest, severity) \
+  WOULD_LOG(severity) &&                   \
+    ::android::base::ErrnoRestorer() &&    \
+      LOG_STREAM_TO(dest, severity)
 
 // A variant of LOG that also logs the current errno value. To be used when
 // library calls fail.
 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
 
 // Behaves like PLOG, but logs to the specified log ID.
-#define PLOG_TO(dest, severity)                                                      \
-  UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
-    ::android::base::ErrnoRestorer() &&                                              \
-      ::android::base::LogMessage(__FILE__, __LINE__,                                \
-          ::android::base::dest,                                                     \
-          ::android::base::severity, errno).stream()
+#define PLOG_TO(dest, severity)                         \
+  WOULD_LOG(SEVERITY_LAMBDA(severity)) &&               \
+    ::android::base::ErrnoRestorer() &&                 \
+      ::android::base::LogMessage(__FILE__, __LINE__,   \
+          ::android::base::dest,                        \
+          SEVERITY_LAMBDA(severity), errno).stream()
 
 // Marker that code is yet to be implemented.
 #define UNIMPLEMENTED(level) \
   LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
 
+#ifdef __clang_analyzer__
+// ClangL static analyzer does not see the conditional statement inside
+// LogMessage's destructor that will abort on FATAL severity.
+#define ABORT_AFTER_LOG_FATAL for (;;abort())
+#else
+#define ABORT_AFTER_LOG_FATAL
+#endif
+
 // Check whether condition x holds and LOG(FATAL) if not. The value of the
 // expression x is only evaluated once. Extra logging can be appended using <<
 // after. For example:
@@ -155,6 +234,7 @@
 //       "Check failed: false == true".
 #define CHECK(x)                                                              \
   LIKELY((x)) ||                                                              \
+    ABORT_AFTER_LOG_FATAL                                                     \
     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
                                 ::android::base::FATAL, -1).stream()          \
         << "Check failed: " #x << " "
@@ -164,6 +244,7 @@
   for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);        \
        UNLIKELY(!(_values.lhs OP _values.rhs));                             \
        /* empty */)                                                         \
+  ABORT_AFTER_LOG_FATAL                                                     \
   ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
                               ::android::base::FATAL, -1).stream()          \
       << "Check failed: " << #LHS << " " << #OP << " " << #RHS              \
@@ -183,13 +264,13 @@
 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
 
 // Helper for CHECK_STRxx(s1,s2) macros.
-#define CHECK_STROP(s1, s2, sense)                                         \
-  if (LIKELY((strcmp(s1, s2) == 0) == sense))                              \
-    ;                                                                      \
-  else                                                                     \
-    LOG(FATAL) << "Check failed: "                                         \
-               << "\"" << s1 << "\""                                       \
-               << (sense ? " == " : " != ") << "\"" << s2 << "\""
+#define CHECK_STROP(s1, s2, sense)                                             \
+  while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
+    ABORT_AFTER_LOG_FATAL                                                      \
+    ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
+                                ::android::base::FATAL, -1).stream()           \
+        << "Check failed: " << "\"" << (s1) << "\""                            \
+        << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
 
 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
@@ -201,7 +282,8 @@
     int rc = call args;                                                \
     if (rc != 0) {                                                     \
       errno = rc;                                                      \
-      PLOG(FATAL) << #call << " failed for " << what; \
+      ABORT_AFTER_LOG_FATAL                                            \
+      PLOG(FATAL) << #call << " failed for " << (what);                \
     }                                                                  \
   } while (false)
 
@@ -256,7 +338,7 @@
 // MakeEagerEvaluator to infer the types of LHS and RHS.
 template <typename LHS, typename RHS>
 struct EagerEvaluator {
-  EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
+  constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
   }
   LHS lhs;
   RHS rhs;
@@ -264,7 +346,7 @@
 
 // Helper function for CHECK_xx.
 template <typename LHS, typename RHS>
-static inline EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
+constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
   return EagerEvaluator<LHS, RHS>(lhs, rhs);
 }
 
@@ -322,6 +404,12 @@
   DISALLOW_COPY_AND_ASSIGN(LogMessage);
 };
 
+// Get the minimum severity level for logging.
+LogSeverity GetMinimumLogSeverity();
+
+// Set the minimum severity level for logging, returning the old severity.
+LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
+
 // Allows to temporarily change the minimum severity level for logging.
 class ScopedLogSeverity {
  public:
diff --git a/base/include/android-base/macros.h b/base/include/android-base/macros.h
index 913a9a0..88bbe8a 100644
--- a/base/include/android-base/macros.h
+++ b/base/include/android-base/macros.h
@@ -41,18 +41,9 @@
 // Note, that most uses of DISALLOW_ASSIGN and DISALLOW_COPY are broken
 // semantically, one should either use disallow both or neither. Try to
 // avoid these in new code.
-//
-// When building with C++11 toolchains, just use the language support
-// for explicitly deleted methods.
-#if __cplusplus >= 201103L
 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
   TypeName(const TypeName&) = delete;      \
   void operator=(const TypeName&) = delete
-#else
-#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
-  TypeName(const TypeName&);               \
-  void operator=(const TypeName&)
-#endif
 
 // A macro to disallow all the implicit constructors, namely the
 // default constructor, copy constructor and operator= functions.
@@ -61,7 +52,7 @@
 // that wants to prevent anyone from instantiating it. This is
 // especially useful for classes containing only static methods.
 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
-  TypeName();                                    \
+  TypeName() = delete;                           \
   DISALLOW_COPY_AND_ASSIGN(TypeName)
 
 // The arraysize(arr) macro returns the # of elements in an array arr.
@@ -123,8 +114,11 @@
   ((sizeof(a) / sizeof(*(a))) / \
     static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
 
-#define LIKELY(x) __builtin_expect((x), true)
-#define UNLIKELY(x) __builtin_expect((x), false)
+// Changing this definition will cause you a lot of pain.  A majority of
+// vendor code defines LIKELY and UNLIKELY this way, and includes
+// this header through an indirect path.
+#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
+#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
 
 #define WARN_UNUSED __attribute__((warn_unused_result))
 
@@ -162,10 +156,10 @@
 //  only if there are no statements on the execution path between it and the
 //  next switch label.
 //
-//  When compiled with clang in C++11 mode, the FALLTHROUGH_INTENDED macro is
-//  expanded to [[clang::fallthrough]] attribute, which is analysed when
-//  performing switch labels fall-through diagnostic ('-Wimplicit-fallthrough').
-//  See clang documentation on language extensions for details:
+//  When compiled with clang, the FALLTHROUGH_INTENDED macro is expanded to
+//  [[clang::fallthrough]] attribute, which is analysed when performing switch
+//  labels fall-through diagnostic ('-Wimplicit-fallthrough'). See clang
+//  documentation on language extensions for details:
 //  http://clang.llvm.org/docs/LanguageExtensions.html#clang__fallthrough
 //
 //  When used with unsupported compilers, the FALLTHROUGH_INTENDED macro has no
@@ -173,7 +167,7 @@
 //
 //  In either case this macro has no effect on runtime behavior and performance
 //  of code.
-#if defined(__clang__) && __cplusplus >= 201103L && defined(__has_warning)
+#if defined(__clang__) && defined(__has_warning)
 #if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")
 #define FALLTHROUGH_INTENDED [[clang::fallthrough]]  // NOLINT
 #endif
diff --git a/base/include/android-base/memory.h b/base/include/android-base/memory.h
index 3a2f8fa..9971226 100644
--- a/base/include/android-base/memory.h
+++ b/base/include/android-base/memory.h
@@ -20,25 +20,19 @@
 namespace android {
 namespace base {
 
-// Use packed structures for access to unaligned data on targets with alignment
+// Use memcpy for access to unaligned data on targets with alignment
 // restrictions.  The compiler will generate appropriate code to access these
 // structures without generating alignment exceptions.
 template <typename T>
-static inline T get_unaligned(const T* address) {
-  struct unaligned {
-    T v;
-  } __attribute__((packed));
-  const unaligned* p = reinterpret_cast<const unaligned*>(address);
-  return p->v;
+static inline T get_unaligned(const void* address) {
+  T result;
+  memcpy(&result, address, sizeof(T));
+  return result;
 }
 
 template <typename T>
-static inline void put_unaligned(T* address, T v) {
-  struct unaligned {
-    T v;
-  } __attribute__((packed));
-  unaligned* p = reinterpret_cast<unaligned*>(address);
-  p->v = v;
+static inline void put_unaligned(void* address, T v) {
+  memcpy(address, &v, sizeof(T));
 }
 
 } // namespace base
diff --git a/base/include/android-base/parsedouble.h b/base/include/android-base/parsedouble.h
new file mode 100644
index 0000000..daa6902
--- /dev/null
+++ b/base/include/android-base/parsedouble.h
@@ -0,0 +1,50 @@
+/*
+ * 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 ANDROID_BASE_PARSEDOUBLE_H
+#define ANDROID_BASE_PARSEDOUBLE_H
+
+#include <errno.h>
+#include <stdlib.h>
+
+#include <limits>
+
+namespace android {
+namespace base {
+
+// Parse double value in the string 's' and sets 'out' to that value.
+// Optionally allows the caller to define a 'min' and 'max' beyond which
+// otherwise valid values will be rejected. Returns boolean success.
+static inline bool ParseDouble(const char* s, double* out,
+                               double min = std::numeric_limits<double>::lowest(),
+                               double max = std::numeric_limits<double>::max()) {
+  errno = 0;
+  char* end;
+  double result = strtod(s, &end);
+  if (errno != 0 || s == end || *end != '\0') {
+    return false;
+  }
+  if (result < min || max < result) {
+    return false;
+  }
+  *out = result;
+  return true;
+}
+
+}  // namespace base
+}  // namespace android
+
+#endif  // ANDROID_BASE_PARSEDOUBLE_H
diff --git a/base/include/android-base/parseint.h b/base/include/android-base/parseint.h
index ed75e2d..2c8570e 100644
--- a/base/include/android-base/parseint.h
+++ b/base/include/android-base/parseint.h
@@ -21,17 +21,19 @@
 #include <stdlib.h>
 
 #include <limits>
+#include <string>
 
 namespace android {
 namespace base {
 
 // Parses the unsigned decimal integer in the string 's' and sets 'out' to
 // that value. Optionally allows the caller to define a 'max' beyond which
-// otherwise valid values will be rejected. Returns boolean success.
+// otherwise valid values will be rejected. Returns boolean success; 'out'
+// is untouched if parsing fails.
 template <typename T>
 bool ParseUint(const char* s, T* out,
                T max = std::numeric_limits<T>::max()) {
-  int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
+  int base = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? 16 : 10;
   errno = 0;
   char* end;
   unsigned long long int result = strtoull(s, &end, base);
@@ -45,15 +47,22 @@
   return true;
 }
 
+// TODO: string_view
+template <typename T>
+bool ParseUint(const std::string& s, T* out,
+               T max = std::numeric_limits<T>::max()) {
+  return ParseUint(s.c_str(), out, max);
+}
+
 // Parses the signed decimal integer in the string 's' and sets 'out' to
 // that value. Optionally allows the caller to define a 'min' and 'max
 // beyond which otherwise valid values will be rejected. Returns boolean
-// success.
+// success; 'out' is untouched if parsing fails.
 template <typename T>
 bool ParseInt(const char* s, T* out,
               T min = std::numeric_limits<T>::min(),
               T max = std::numeric_limits<T>::max()) {
-  int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
+  int base = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? 16 : 10;
   errno = 0;
   char* end;
   long long int result = strtoll(s, &end, base);
@@ -67,6 +76,14 @@
   return true;
 }
 
+// TODO: string_view
+template <typename T>
+bool ParseInt(const std::string& s, T* out,
+              T min = std::numeric_limits<T>::min(),
+              T max = std::numeric_limits<T>::max()) {
+  return ParseInt(s.c_str(), out, min, max);
+}
+
 }  // namespace base
 }  // namespace android
 
diff --git a/base/include/android-base/properties.h b/base/include/android-base/properties.h
new file mode 100644
index 0000000..4de5e57
--- /dev/null
+++ b/base/include/android-base/properties.h
@@ -0,0 +1,78 @@
+/*
+ * 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 ANDROID_BASE_PROPERTIES_H
+#define ANDROID_BASE_PROPERTIES_H
+
+#include <sys/cdefs.h>
+
+#if !defined(__BIONIC__)
+#error Only bionic supports system properties.
+#endif
+
+#include <chrono>
+#include <limits>
+#include <string>
+
+namespace android {
+namespace base {
+
+// Returns the current value of the system property `key`,
+// or `default_value` if the property is empty or doesn't exist.
+std::string GetProperty(const std::string& key, const std::string& default_value);
+
+// Returns true if the system property `key` has the value "1", "y", "yes", "on", or "true",
+// false for "0", "n", "no", "off", or "false", or `default_value` otherwise.
+bool GetBoolProperty(const std::string& key, bool default_value);
+
+// Returns the signed integer corresponding to the system property `key`.
+// If the property is empty, doesn't exist, doesn't have an integer value, or is outside
+// the optional bounds, returns `default_value`.
+template <typename T> T GetIntProperty(const std::string& key,
+                                       T default_value,
+                                       T min = std::numeric_limits<T>::min(),
+                                       T max = std::numeric_limits<T>::max());
+
+// Returns the unsigned integer corresponding to the system property `key`.
+// If the property is empty, doesn't exist, doesn't have an integer value, or is outside
+// the optional bound, returns `default_value`.
+template <typename T> T GetUintProperty(const std::string& key,
+                                        T default_value,
+                                        T max = std::numeric_limits<T>::max());
+
+// Sets the system property `key` to `value`.
+// Note that system property setting is inherently asynchronous so a return value of `true`
+// isn't particularly meaningful, and immediately reading back the value won't necessarily
+// tell you whether or not your call succeeded. A `false` return value definitely means failure.
+bool SetProperty(const std::string& key, const std::string& value);
+
+// 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);
+
+// 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);
+
+} // namespace base
+} // namespace android
+
+#endif  // ANDROID_BASE_PROPERTIES_H
diff --git a/base/include/android-base/quick_exit.h b/base/include/android-base/quick_exit.h
new file mode 100644
index 0000000..a03b14f
--- /dev/null
+++ b/base/include/android-base/quick_exit.h
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <stdlib.h>
+
+// Provide emulation for at_quick_exit/quick_exit on platforms that don't have it.
+namespace android {
+namespace base {
+
+// Bionic and glibc have quick_exit, Darwin and Windows don't.
+#if !defined(__linux__)
+  void quick_exit(int exit_code) __attribute__((noreturn));
+  int at_quick_exit(void (*func)());
+#else
+  using ::at_quick_exit;
+  using ::quick_exit;
+#endif
+}
+}
diff --git a/base/include/android-base/strings.h b/base/include/android-base/strings.h
index 69781cd..f5f5c11 100644
--- a/base/include/android-base/strings.h
+++ b/base/include/android-base/strings.h
@@ -58,9 +58,14 @@
 
 // Tests whether 's' starts with 'prefix'.
 bool StartsWith(const std::string& s, const char* prefix);
+bool StartsWithIgnoreCase(const std::string& s, const char* prefix);
 
 // Tests whether 's' ends with 'suffix'.
 bool EndsWith(const std::string& s, const char* suffix);
+bool EndsWithIgnoreCase(const std::string& s, const char* suffix);
+
+// Tests whether 'lhs' equals 'rhs', ignoring case.
+bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs);
 
 }  // namespace base
 }  // namespace android
diff --git a/base/include/android-base/test_utils.h b/base/include/android-base/test_utils.h
index 4ea3c8e..c0bf0c1 100644
--- a/base/include/android-base/test_utils.h
+++ b/base/include/android-base/test_utils.h
@@ -48,4 +48,21 @@
   DISALLOW_COPY_AND_ASSIGN(TemporaryDir);
 };
 
+class CapturedStderr {
+ public:
+  CapturedStderr();
+  ~CapturedStderr();
+
+  int fd() const;
+
+ private:
+  void init();
+  void reset();
+
+  TemporaryFile temp_file_;
+  int old_stderr_;
+
+  DISALLOW_COPY_AND_ASSIGN(CapturedStderr);
+};
+
 #endif  // ANDROID_BASE_TEST_UTILS_H
diff --git a/base/include/android-base/thread_annotations.h b/base/include/android-base/thread_annotations.h
index 2422102..fbb5923 100644
--- a/base/include/android-base/thread_annotations.h
+++ b/base/include/android-base/thread_annotations.h
@@ -29,6 +29,9 @@
 #define SCOPED_CAPABILITY \
       THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
 
+#define SHARED_CAPABILITY(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(shared_capability(__VA_ARGS__))
+
 #define GUARDED_BY(x) \
       THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
 
@@ -77,6 +80,27 @@
 #define RETURN_CAPABILITY(x) \
       THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
 
+#define EXCLUSIVE_LOCK_FUNCTION(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
+
+#define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
+
+#define SHARED_LOCK_FUNCTION(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
+
+#define SHARED_TRYLOCK_FUNCTION(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
+
+#define UNLOCK_FUNCTION(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
+
+#define SCOPED_LOCKABLE \
+      THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
+#define LOCK_RETURNED(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
+
 #define NO_THREAD_SAFETY_ANALYSIS \
       THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
 
diff --git a/base/include/android-base/unique_fd.h b/base/include/android-base/unique_fd.h
index 869e60f..6cfcfcd 100644
--- a/base/include/android-base/unique_fd.h
+++ b/base/include/android-base/unique_fd.h
@@ -55,7 +55,7 @@
   unique_fd_impl() : value_(-1) {}
 
   explicit unique_fd_impl(int value) : value_(value) {}
-  ~unique_fd_impl() { clear(); }
+  ~unique_fd_impl() { reset(); }
 
   unique_fd_impl(unique_fd_impl&& other) : value_(other.release()) {}
   unique_fd_impl& operator=(unique_fd_impl&& s) {
@@ -63,17 +63,13 @@
     return *this;
   }
 
-  void reset(int new_value) {
+  void reset(int new_value = -1) {
     if (value_ != -1) {
       Closer::Close(value_);
     }
     value_ = new_value;
   }
 
-  void clear() {
-    reset(-1);
-  }
-
   int get() const { return value_; }
   operator int() const { return get(); }
 
@@ -95,4 +91,14 @@
 }  // namespace base
 }  // namespace android
 
+template <typename T>
+int close(const android::base::unique_fd_impl<T>&)
+#if defined(__clang__)
+  __attribute__((__unavailable__(
+#else
+  __attribute__((__error__(
+#endif
+    "close called on unique_fd"
+  )));
+
 #endif  // ANDROID_BASE_UNIQUE_FD_H
diff --git a/base/logging.cpp b/base/logging.cpp
index 1741871..6357b4b 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -14,13 +14,15 @@
  * limitations under the License.
  */
 
-#ifdef _WIN32
+#if defined(_WIN32)
 #include <windows.h>
 #endif
 
 #include "android-base/logging.h"
 
+#include <fcntl.h>
 #include <libgen.h>
+#include <time.h>
 
 // For getprogname(3) or program_invocation_short_name.
 #if defined(__ANDROID__) || defined(__APPLE__)
@@ -29,30 +31,30 @@
 #include <errno.h>
 #endif
 
+#if defined(__linux__)
+#include <sys/uio.h>
+#endif
+
 #include <iostream>
 #include <limits>
+#include <mutex>
 #include <sstream>
 #include <string>
 #include <utility>
 #include <vector>
 
-#ifndef _WIN32
-#include <mutex>
-#endif
-
-#include "android-base/macros.h"
-#include "android-base/strings.h"
-#include "cutils/threads.h"
-
 // Headers for LogMessage::LogLine.
 #ifdef __ANDROID__
+#include <log/log.h>
 #include <android/set_abort_message.h>
-#include "cutils/log.h"
 #else
 #include <sys/types.h>
 #include <unistd.h>
 #endif
 
+#include <android-base/macros.h>
+#include <android-base/strings.h>
+
 // For gettid.
 #if defined(__APPLE__)
 #include "AvailabilityMacros.h"  // For MAC_OS_X_VERSION_MAX_ALLOWED
@@ -87,17 +89,11 @@
 }
 
 namespace {
-#ifndef _WIN32
-using std::mutex;
-using std::lock_guard;
-
 #if defined(__GLIBC__)
 const char* getprogname() {
   return program_invocation_short_name;
 }
-#endif
-
-#else
+#elif defined(_WIN32)
 const char* getprogname() {
   static bool first = true;
   static char progname[MAX_PATH] = {};
@@ -116,82 +112,108 @@
 
   return progname;
 }
-
-class mutex {
- public:
-  mutex() {
-    InitializeCriticalSection(&critical_section_);
-  }
-  ~mutex() {
-    DeleteCriticalSection(&critical_section_);
-  }
-
-  void lock() {
-    EnterCriticalSection(&critical_section_);
-  }
-
-  void unlock() {
-    LeaveCriticalSection(&critical_section_);
-  }
-
- private:
-  CRITICAL_SECTION critical_section_;
-};
-
-template <typename LockT>
-class lock_guard {
- public:
-  explicit lock_guard(LockT& lock) : lock_(lock) {
-    lock_.lock();
-  }
-
-  ~lock_guard() {
-    lock_.unlock();
-  }
-
- private:
-  LockT& lock_;
-
-  DISALLOW_COPY_AND_ASSIGN(lock_guard);
-};
 #endif
 } // namespace
 
 namespace android {
 namespace base {
 
-static auto& logging_lock = *new mutex();
+static std::mutex& LoggingLock() {
+  static auto& logging_lock = *new std::mutex();
+  return logging_lock;
+}
 
+static LogFunction& Logger() {
 #ifdef __ANDROID__
-static auto& gLogger = *new LogFunction(LogdLogger());
+  static auto& logger = *new LogFunction(LogdLogger());
 #else
-static auto& gLogger = *new LogFunction(StderrLogger);
+  static auto& logger = *new LogFunction(StderrLogger);
 #endif
+  return logger;
+}
+
+static AbortFunction& Aborter() {
+  static auto& aborter = *new AbortFunction(DefaultAborter);
+  return aborter;
+}
+
+static std::string& ProgramInvocationName() {
+  static auto& programInvocationName = *new std::string(getprogname());
+  return programInvocationName;
+}
 
 static bool gInitialized = false;
 static LogSeverity gMinimumLogSeverity = INFO;
-static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
 
-LogSeverity GetMinimumLogSeverity() {
-  return gMinimumLogSeverity;
-}
+#if defined(__linux__)
+void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
+                  const char* tag, const char*, unsigned int, const char* msg) {
+  // clang-format off
+  static constexpr int kLogSeverityToKernelLogLevel[] = {
+      [android::base::VERBOSE] = 7,              // KERN_DEBUG (there is no verbose kernel log
+                                                 //             level)
+      [android::base::DEBUG] = 7,                // KERN_DEBUG
+      [android::base::INFO] = 6,                 // KERN_INFO
+      [android::base::WARNING] = 4,              // KERN_WARNING
+      [android::base::ERROR] = 3,                // KERN_ERROR
+      [android::base::FATAL_WITHOUT_ABORT] = 2,  // KERN_CRIT
+      [android::base::FATAL] = 2,                // KERN_CRIT
+  };
+  // clang-format on
+  static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
+                "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
 
-static const char* ProgramInvocationName() {
-  if (gProgramInvocationName == nullptr) {
-    gProgramInvocationName.reset(new std::string(getprogname()));
+  static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
+  if (klog_fd == -1) return;
+
+  int level = kLogSeverityToKernelLogLevel[severity];
+
+  // The kernel's printk buffer is only 1024 bytes.
+  // TODO: should we automatically break up long lines into multiple lines?
+  // Or we could log but with something like "..." at the end?
+  char buf[1024];
+  size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
+  if (size > sizeof(buf)) {
+    size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
+                    level, tag, size);
   }
 
-  return gProgramInvocationName->c_str();
+  iovec iov[1];
+  iov[0].iov_base = buf;
+  iov[0].iov_len = size;
+  TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
 }
+#endif
 
 void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
                   unsigned int line, const char* message) {
-  static const char log_characters[] = "VDIWEF";
+  struct tm now;
+  time_t t = time(nullptr);
+
+#if defined(_WIN32)
+  localtime_s(&now, &t);
+#else
+  localtime_r(&t, &now);
+#endif
+
+  char timestamp[32];
+  strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
+
+  static const char log_characters[] = "VDIWEFF";
   static_assert(arraysize(log_characters) - 1 == FATAL + 1,
                 "Mismatch in size of log_characters and values in LogSeverity");
   char severity_char = log_characters[severity];
-  fprintf(stderr, "%s %c %5d %5d %s:%u] %s\n", ProgramInvocationName(),
-          severity_char, getpid(), GetThreadId(), file, line, message);
+  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
+          severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
+}
+
+void DefaultAborter(const char* abort_message) {
+#ifdef __ANDROID__
+  android_set_abort_message(abort_message);
+#else
+  UNUSED(abort_message);
+#endif
+  abort();
 }
 
 
@@ -199,28 +221,27 @@
 LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
 }
 
-static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
-    ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
-    ANDROID_LOG_WARN,    ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
-};
-static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
-              "Mismatch in size of kLogSeverityToAndroidLogPriority and values "
-              "in LogSeverity");
-
-static const log_id kLogIdToAndroidLogId[] = {
-    LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
-};
-static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
-              "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
-
 void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
                             const char* file, unsigned int line,
                             const char* message) {
+  static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
+      ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
+      ANDROID_LOG_WARN,    ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
+      ANDROID_LOG_FATAL,
+  };
+  static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
+                "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
+
   int priority = kLogSeverityToAndroidLogPriority[severity];
   if (id == DEFAULT) {
     id = default_log_id_;
   }
 
+  static constexpr log_id kLogIdToAndroidLogId[] = {
+    LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
+  };
+  static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
+                "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
   log_id lg_id = kLogIdToAndroidLogId[id];
 
   if (priority == ANDROID_LOG_FATAL) {
@@ -232,12 +253,10 @@
 }
 #endif
 
-void InitLogging(char* argv[], LogFunction&& logger) {
+void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
   SetLogger(std::forward<LogFunction>(logger));
-  InitLogging(argv);
-}
+  SetAborter(std::forward<AbortFunction>(aborter));
 
-void InitLogging(char* argv[]) {
   if (gInitialized) {
     return;
   }
@@ -248,7 +267,8 @@
   // Linux to recover this, but we don't have that luxury on the Mac/Windows,
   // and there are a couple of argv[0] variants that are commonly used.
   if (argv != nullptr) {
-    gProgramInvocationName.reset(new std::string(basename(argv[0])));
+    std::lock_guard<std::mutex> lock(LoggingLock());
+    ProgramInvocationName() = basename(argv[0]);
   }
 
   const char* tags = getenv("ANDROID_LOG_TAGS");
@@ -278,12 +298,12 @@
           gMinimumLogSeverity = ERROR;
           continue;
         case 'f':
-          gMinimumLogSeverity = FATAL;
+          gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
           continue;
         // liblog will even suppress FATAL if you say 's' for silent, but that's
         // crazy!
         case 's':
-          gMinimumLogSeverity = FATAL;
+          gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
           continue;
       }
     }
@@ -293,8 +313,13 @@
 }
 
 void SetLogger(LogFunction&& logger) {
-  lock_guard<mutex> lock(logging_lock);
-  gLogger = std::move(logger);
+  std::lock_guard<std::mutex> lock(LoggingLock());
+  Logger() = std::move(logger);
+}
+
+void SetAborter(AbortFunction&& aborter) {
+  std::lock_guard<std::mutex> lock(LoggingLock());
+  Aborter() = std::move(aborter);
 }
 
 static const char* GetFileBasename(const char* file) {
@@ -371,6 +396,11 @@
 }
 
 LogMessage::~LogMessage() {
+  // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
+  if (!WOULD_LOG(data_->GetSeverity())) {
+    return;
+  }
+
   // Finish constructing the message.
   if (data_->GetError() != -1) {
     data_->GetBuffer() << ": " << strerror(data_->GetError());
@@ -379,7 +409,7 @@
 
   {
     // Do the actual logging with the lock held.
-    lock_guard<mutex> lock(logging_lock);
+    std::lock_guard<std::mutex> lock(LoggingLock());
     if (msg.find('\n') == std::string::npos) {
       LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
               data_->GetSeverity(), msg.c_str());
@@ -391,6 +421,8 @@
         msg[nl] = '\0';
         LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
                 data_->GetSeverity(), &msg[i]);
+        // Undo the zero-termination so we can give the complete message to the aborter.
+        msg[nl] = '\n';
         i = nl + 1;
       }
     }
@@ -398,10 +430,7 @@
 
   // Abort if necessary.
   if (data_->GetSeverity() == FATAL) {
-#ifdef __ANDROID__
-    android_set_abort_message(msg.c_str());
-#endif
-    abort();
+    Aborter()(msg.c_str());
   }
 }
 
@@ -411,17 +440,26 @@
 
 void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
                          LogSeverity severity, const char* message) {
-  const char* tag = ProgramInvocationName();
-  gLogger(id, severity, tag, file, line, message);
+  const char* tag = ProgramInvocationName().c_str();
+  Logger()(id, severity, tag, file, line, message);
 }
 
-ScopedLogSeverity::ScopedLogSeverity(LogSeverity level) {
-  old_ = gMinimumLogSeverity;
-  gMinimumLogSeverity = level;
+LogSeverity GetMinimumLogSeverity() {
+    return gMinimumLogSeverity;
+}
+
+LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
+  LogSeverity old_severity = gMinimumLogSeverity;
+  gMinimumLogSeverity = new_severity;
+  return old_severity;
+}
+
+ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
+  old_ = SetMinimumLogSeverity(new_severity);
 }
 
 ScopedLogSeverity::~ScopedLogSeverity() {
-  gMinimumLogSeverity = old_;
+  SetMinimumLogSeverity(old_);
 }
 
 }  // namespace base
diff --git a/base/logging_test.cpp b/base/logging_test.cpp
index 3de42b7..adb041b 100644
--- a/base/logging_test.cpp
+++ b/base/logging_test.cpp
@@ -37,42 +37,6 @@
 #define HOST_TEST(suite, name) TEST(suite, name)
 #endif
 
-class CapturedStderr {
- public:
-  CapturedStderr() : old_stderr_(-1) {
-    init();
-  }
-
-  ~CapturedStderr() {
-    reset();
-  }
-
-  int fd() const {
-    return temp_file_.fd;
-  }
-
- private:
-  void init() {
-#if defined(_WIN32)
-    // On Windows, stderr is often buffered, so make sure it is unbuffered so
-    // that we can immediately read back what was written to stderr.
-    ASSERT_EQ(0, setvbuf(stderr, NULL, _IONBF, 0));
-#endif
-    old_stderr_ = dup(STDERR_FILENO);
-    ASSERT_NE(-1, old_stderr_);
-    ASSERT_NE(-1, dup2(fd(), STDERR_FILENO));
-  }
-
-  void reset() {
-    ASSERT_NE(-1, dup2(old_stderr_, STDERR_FILENO));
-    ASSERT_EQ(0, close(old_stderr_));
-    // Note: cannot restore prior setvbuf() setting.
-  }
-
-  TemporaryFile temp_file_;
-  int old_stderr_;
-};
-
 #if defined(_WIN32)
 static void ExitSignalAbortHandler(int) {
   _exit(3);
@@ -120,162 +84,517 @@
   EXPECT_FALSE(flag) << "CHECK_STREQ probably has a dangling if with no else";
 }
 
-std::string make_log_pattern(android::base::LogSeverity severity,
-                             const char* message) {
-  static const char* log_characters = "VDIWEF";
+TEST(logging, DCHECK) {
+  if (android::base::kEnableDChecks) {
+    ASSERT_DEATH({SuppressAbortUI(); DCHECK(false);}, "DCheck failed: false ");
+  }
+  DCHECK(true);
+
+  if (android::base::kEnableDChecks) {
+    ASSERT_DEATH({SuppressAbortUI(); DCHECK_EQ(0, 1);}, "DCheck failed: 0 == 1 ");
+  }
+  DCHECK_EQ(0, 0);
+
+  if (android::base::kEnableDChecks) {
+    ASSERT_DEATH({SuppressAbortUI(); DCHECK_STREQ("foo", "bar");},
+                 R"(DCheck failed: "foo" == "bar")");
+  }
+  DCHECK_STREQ("foo", "foo");
+
+  // No testing whether we have a dangling else, possibly. That's inherent to the if (constexpr)
+  // setup we intentionally chose to force type-checks of debug code even in release builds (so
+  // we don't get more bit-rot).
+}
+
+
+#define CHECK_WOULD_LOG_DISABLED(severity)                                               \
+  static_assert(android::base::severity < android::base::FATAL, "Bad input");            \
+  for (size_t i = static_cast<size_t>(android::base::severity) + 1;                      \
+       i <= static_cast<size_t>(android::base::FATAL);                                   \
+       ++i) {                                                                            \
+    {                                                                                    \
+      android::base::ScopedLogSeverity sls2(static_cast<android::base::LogSeverity>(i)); \
+      EXPECT_FALSE(WOULD_LOG(severity)) << i;                                            \
+    }                                                                                    \
+    {                                                                                    \
+      android::base::ScopedLogSeverity sls2(static_cast<android::base::LogSeverity>(i)); \
+      EXPECT_FALSE(WOULD_LOG(::android::base::severity)) << i;                           \
+    }                                                                                    \
+  }                                                                                      \
+
+#define CHECK_WOULD_LOG_ENABLED(severity)                                                \
+  for (size_t i = static_cast<size_t>(android::base::VERBOSE);                           \
+       i <= static_cast<size_t>(android::base::severity);                                \
+       ++i) {                                                                            \
+    {                                                                                    \
+      android::base::ScopedLogSeverity sls2(static_cast<android::base::LogSeverity>(i)); \
+      EXPECT_TRUE(WOULD_LOG(severity)) << i;                                             \
+    }                                                                                    \
+    {                                                                                    \
+      android::base::ScopedLogSeverity sls2(static_cast<android::base::LogSeverity>(i)); \
+      EXPECT_TRUE(WOULD_LOG(::android::base::severity)) << i;                            \
+    }                                                                                    \
+  }                                                                                      \
+
+TEST(logging, WOULD_LOG_FATAL) {
+  CHECK_WOULD_LOG_ENABLED(FATAL);
+}
+
+TEST(logging, WOULD_LOG_FATAL_WITHOUT_ABORT_disabled) {
+  CHECK_WOULD_LOG_DISABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, WOULD_LOG_FATAL_WITHOUT_ABORT_enabled) {
+  CHECK_WOULD_LOG_ENABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, WOULD_LOG_ERROR_disabled) {
+  CHECK_WOULD_LOG_DISABLED(ERROR);
+}
+
+TEST(logging, WOULD_LOG_ERROR_enabled) {
+  CHECK_WOULD_LOG_ENABLED(ERROR);
+}
+
+TEST(logging, WOULD_LOG_WARNING_disabled) {
+  CHECK_WOULD_LOG_DISABLED(WARNING);
+}
+
+TEST(logging, WOULD_LOG_WARNING_enabled) {
+  CHECK_WOULD_LOG_ENABLED(WARNING);
+}
+
+TEST(logging, WOULD_LOG_INFO_disabled) {
+  CHECK_WOULD_LOG_DISABLED(INFO);
+}
+
+TEST(logging, WOULD_LOG_INFO_enabled) {
+  CHECK_WOULD_LOG_ENABLED(INFO);
+}
+
+TEST(logging, WOULD_LOG_DEBUG_disabled) {
+  CHECK_WOULD_LOG_DISABLED(DEBUG);
+}
+
+TEST(logging, WOULD_LOG_DEBUG_enabled) {
+  CHECK_WOULD_LOG_ENABLED(DEBUG);
+}
+
+TEST(logging, WOULD_LOG_VERBOSE_disabled) {
+  CHECK_WOULD_LOG_DISABLED(VERBOSE);
+}
+
+TEST(logging, WOULD_LOG_VERBOSE_enabled) {
+  CHECK_WOULD_LOG_ENABLED(VERBOSE);
+}
+
+#undef CHECK_WOULD_LOG_DISABLED
+#undef CHECK_WOULD_LOG_ENABLED
+
+
+static std::string make_log_pattern(android::base::LogSeverity severity,
+                                    const char* message) {
+  static const char log_characters[] = "VDIWEFF";
+  static_assert(arraysize(log_characters) - 1 == android::base::FATAL + 1,
+                "Mismatch in size of log_characters and values in LogSeverity");
   char log_char = log_characters[severity];
   std::string holder(__FILE__);
   return android::base::StringPrintf(
-      "%c[[:space:]]+[[:digit:]]+[[:space:]]+[[:digit:]]+ %s:[[:digit:]]+] %s",
+      "%c \\d+-\\d+ \\d+:\\d+:\\d+ \\s*\\d+ \\s*\\d+ %s:\\d+] %s",
       log_char, basename(&holder[0]), message);
 }
 
-TEST(logging, LOG) {
-  ASSERT_DEATH({SuppressAbortUI(); LOG(FATAL) << "foobar";}, "foobar");
+static void CheckMessage(const CapturedStderr& cap,
+                         android::base::LogSeverity severity, const char* expected) {
+  std::string output;
+  ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+  android::base::ReadFdToString(cap.fd(), &output);
 
   // We can't usefully check the output of any of these on Windows because we
   // don't have std::regex, but we can at least make sure we printed at least as
   // many characters are in the log message.
-  {
-    CapturedStderr cap;
-    LOG(WARNING) << "foobar";
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
-
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_GT(output.length(), strlen("foobar"));
+  ASSERT_GT(output.length(), strlen(expected));
+  ASSERT_NE(nullptr, strstr(output.c_str(), expected)) << output;
 
 #if !defined(_WIN32)
-    std::regex message_regex(
-        make_log_pattern(android::base::WARNING, "foobar"));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
+  std::regex message_regex(make_log_pattern(severity, expected));
+  ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
 #endif
+}
+
+
+#define CHECK_LOG_STREAM_DISABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    LOG_STREAM(severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    LOG_STREAM(::android::base::severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
+
+#define CHECK_LOG_STREAM_ENABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    LOG_STREAM(severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar"); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    LOG_STREAM(::android::base::severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar"); \
+  } \
+
+TEST(logging, LOG_STREAM_FATAL_WITHOUT_ABORT_disabled) {
+  CHECK_LOG_STREAM_DISABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, LOG_STREAM_FATAL_WITHOUT_ABORT_enabled) {
+  CHECK_LOG_STREAM_ENABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, LOG_STREAM_ERROR_disabled) {
+  CHECK_LOG_STREAM_DISABLED(ERROR);
+}
+
+TEST(logging, LOG_STREAM_ERROR_enabled) {
+  CHECK_LOG_STREAM_ENABLED(ERROR);
+}
+
+TEST(logging, LOG_STREAM_WARNING_disabled) {
+  CHECK_LOG_STREAM_DISABLED(WARNING);
+}
+
+TEST(logging, LOG_STREAM_WARNING_enabled) {
+  CHECK_LOG_STREAM_ENABLED(WARNING);
+}
+
+TEST(logging, LOG_STREAM_INFO_disabled) {
+  CHECK_LOG_STREAM_DISABLED(INFO);
+}
+
+TEST(logging, LOG_STREAM_INFO_enabled) {
+  CHECK_LOG_STREAM_ENABLED(INFO);
+}
+
+TEST(logging, LOG_STREAM_DEBUG_disabled) {
+  CHECK_LOG_STREAM_DISABLED(DEBUG);
+}
+
+TEST(logging, LOG_STREAM_DEBUG_enabled) {
+  CHECK_LOG_STREAM_ENABLED(DEBUG);
+}
+
+TEST(logging, LOG_STREAM_VERBOSE_disabled) {
+  CHECK_LOG_STREAM_DISABLED(VERBOSE);
+}
+
+TEST(logging, LOG_STREAM_VERBOSE_enabled) {
+  CHECK_LOG_STREAM_ENABLED(VERBOSE);
+}
+
+#undef CHECK_LOG_STREAM_DISABLED
+#undef CHECK_LOG_STREAM_ENABLED
+
+
+#define CHECK_LOG_DISABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    LOG(severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    LOG(::android::base::severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
+
+#define CHECK_LOG_ENABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    LOG(severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar"); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    LOG(::android::base::severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar"); \
+  } \
+
+TEST(logging, LOG_FATAL) {
+  ASSERT_DEATH({SuppressAbortUI(); LOG(FATAL) << "foobar";}, "foobar");
+  ASSERT_DEATH({SuppressAbortUI(); LOG(::android::base::FATAL) << "foobar";}, "foobar");
+}
+
+TEST(logging, LOG_FATAL_WITHOUT_ABORT_disabled) {
+  CHECK_LOG_DISABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, LOG_FATAL_WITHOUT_ABORT_enabled) {
+  CHECK_LOG_ENABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, LOG_ERROR_disabled) {
+  CHECK_LOG_DISABLED(ERROR);
+}
+
+TEST(logging, LOG_ERROR_enabled) {
+  CHECK_LOG_ENABLED(ERROR);
+}
+
+TEST(logging, LOG_WARNING_disabled) {
+  CHECK_LOG_DISABLED(WARNING);
+}
+
+TEST(logging, LOG_WARNING_enabled) {
+  CHECK_LOG_ENABLED(WARNING);
+}
+
+TEST(logging, LOG_INFO_disabled) {
+  CHECK_LOG_DISABLED(INFO);
+}
+
+TEST(logging, LOG_INFO_enabled) {
+  CHECK_LOG_ENABLED(INFO);
+}
+
+TEST(logging, LOG_DEBUG_disabled) {
+  CHECK_LOG_DISABLED(DEBUG);
+}
+
+TEST(logging, LOG_DEBUG_enabled) {
+  CHECK_LOG_ENABLED(DEBUG);
+}
+
+TEST(logging, LOG_VERBOSE_disabled) {
+  CHECK_LOG_DISABLED(VERBOSE);
+}
+
+TEST(logging, LOG_VERBOSE_enabled) {
+  CHECK_LOG_ENABLED(VERBOSE);
+}
+
+#undef CHECK_LOG_DISABLED
+#undef CHECK_LOG_ENABLED
+
+
+TEST(logging, LOG_complex_param) {
+#define CHECK_LOG_COMBINATION(use_scoped_log_severity_info, use_logging_severity_info)             \
+  {                                                                                                \
+    android::base::ScopedLogSeverity sls(                                                          \
+        (use_scoped_log_severity_info) ? ::android::base::INFO : ::android::base::WARNING);        \
+    CapturedStderr cap;                                                                            \
+    LOG((use_logging_severity_info) ? ::android::base::INFO : ::android::base::WARNING)            \
+        << "foobar";                                                                               \
+    if ((use_scoped_log_severity_info) || !(use_logging_severity_info)) {                          \
+      CheckMessage(cap,                                                                            \
+                   (use_logging_severity_info) ? ::android::base::INFO : ::android::base::WARNING, \
+                   "foobar");                                                                      \
+    } else {                                                                                       \
+      ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_CUR));                                                  \
+    }                                                                                              \
   }
 
-  {
-    CapturedStderr cap;
+  CHECK_LOG_COMBINATION(false,false);
+  CHECK_LOG_COMBINATION(false,true);
+  CHECK_LOG_COMBINATION(true,false);
+  CHECK_LOG_COMBINATION(true,true);
+
+#undef CHECK_LOG_COMBINATION
+}
+
+
+TEST(logging, LOG_does_not_clobber_errno) {
+  CapturedStderr cap;
+  errno = 12345;
+  LOG(INFO) << (errno = 67890);
+  EXPECT_EQ(12345, errno) << "errno was not restored";
+
+  CheckMessage(cap, android::base::INFO, "67890");
+}
+
+TEST(logging, PLOG_does_not_clobber_errno) {
+  CapturedStderr cap;
+  errno = 12345;
+  PLOG(INFO) << (errno = 67890);
+  EXPECT_EQ(12345, errno) << "errno was not restored";
+
+  CheckMessage(cap, android::base::INFO, "67890");
+}
+
+TEST(logging, LOG_does_not_have_dangling_if) {
+  CapturedStderr cap; // So the logging below has no side-effects.
+
+  // Do the test two ways: once where we hypothesize that LOG()'s if
+  // will evaluate to true (when severity is high enough) and once when we
+  // expect it to evaluate to false (when severity is not high enough).
+  bool flag = false;
+  if (true)
     LOG(INFO) << "foobar";
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+  else
+    flag = true;
 
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_GT(output.length(), strlen("foobar"));
+  EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
 
-#if !defined(_WIN32)
-    std::regex message_regex(
-        make_log_pattern(android::base::INFO, "foobar"));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
-#endif
-  }
+  flag = false;
+  if (true)
+    LOG(VERBOSE) << "foobar";
+  else
+    flag = true;
 
-  {
-    CapturedStderr cap;
-    LOG(DEBUG) << "foobar";
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
-
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_TRUE(output.empty());
-  }
-
-  {
-    android::base::ScopedLogSeverity severity(android::base::DEBUG);
-    CapturedStderr cap;
-    LOG(DEBUG) << "foobar";
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
-
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_GT(output.length(), strlen("foobar"));
-
-#if !defined(_WIN32)
-    std::regex message_regex(
-        make_log_pattern(android::base::DEBUG, "foobar"));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
-#endif
-  }
-
-  // Test whether LOG() saves and restores errno.
-  {
-    CapturedStderr cap;
-    errno = 12345;
-    LOG(INFO) << (errno = 67890);
-    EXPECT_EQ(12345, errno) << "errno was not restored";
-
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
-
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    EXPECT_NE(nullptr, strstr(output.c_str(), "67890")) << output;
-
-#if !defined(_WIN32)
-    std::regex message_regex(
-        make_log_pattern(android::base::INFO, "67890"));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
-#endif
-  }
-
-  // Test whether LOG() has a dangling if with no else.
-  {
-    CapturedStderr cap;
-
-    // Do the test two ways: once where we hypothesize that LOG()'s if
-    // will evaluate to true (when severity is high enough) and once when we
-    // expect it to evaluate to false (when severity is not high enough).
-    bool flag = false;
-    if (true)
-      LOG(INFO) << "foobar";
-    else
-      flag = true;
-
-    EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
-
-    flag = false;
-    if (true)
-      LOG(VERBOSE) << "foobar";
-    else
-      flag = true;
-
-    EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
-  }
+  EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
 }
 
-TEST(logging, PLOG) {
-  {
-    CapturedStderr cap;
-    errno = ENOENT;
-    PLOG(INFO) << "foobar";
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+#define CHECK_PLOG_DISABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    PLOG(severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls1(android::base::FATAL); \
+    CapturedStderr cap1; \
+    PLOG(severity) << "foo bar"; \
+    ASSERT_EQ(0, lseek(cap1.fd(), 0, SEEK_CUR)); \
+  } \
 
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_GT(output.length(), strlen("foobar"));
+#define CHECK_PLOG_ENABLED(severity) \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    errno = ENOENT; \
+    PLOG(severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar: No such file or directory"); \
+  } \
+  { \
+    android::base::ScopedLogSeverity sls2(android::base::severity); \
+    CapturedStderr cap2; \
+    errno = ENOENT; \
+    PLOG(severity) << "foobar"; \
+    CheckMessage(cap2, android::base::severity, "foobar: No such file or directory"); \
+  } \
 
-#if !defined(_WIN32)
-    std::regex message_regex(make_log_pattern(
-        android::base::INFO, "foobar: No such file or directory"));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
-#endif
-  }
+TEST(logging, PLOG_FATAL) {
+  ASSERT_DEATH({SuppressAbortUI(); PLOG(FATAL) << "foobar";}, "foobar");
+  ASSERT_DEATH({SuppressAbortUI(); PLOG(::android::base::FATAL) << "foobar";}, "foobar");
 }
 
+TEST(logging, PLOG_FATAL_WITHOUT_ABORT_disabled) {
+  CHECK_PLOG_DISABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, PLOG_FATAL_WITHOUT_ABORT_enabled) {
+  CHECK_PLOG_ENABLED(FATAL_WITHOUT_ABORT);
+}
+
+TEST(logging, PLOG_ERROR_disabled) {
+  CHECK_PLOG_DISABLED(ERROR);
+}
+
+TEST(logging, PLOG_ERROR_enabled) {
+  CHECK_PLOG_ENABLED(ERROR);
+}
+
+TEST(logging, PLOG_WARNING_disabled) {
+  CHECK_PLOG_DISABLED(WARNING);
+}
+
+TEST(logging, PLOG_WARNING_enabled) {
+  CHECK_PLOG_ENABLED(WARNING);
+}
+
+TEST(logging, PLOG_INFO_disabled) {
+  CHECK_PLOG_DISABLED(INFO);
+}
+
+TEST(logging, PLOG_INFO_enabled) {
+  CHECK_PLOG_ENABLED(INFO);
+}
+
+TEST(logging, PLOG_DEBUG_disabled) {
+  CHECK_PLOG_DISABLED(DEBUG);
+}
+
+TEST(logging, PLOG_DEBUG_enabled) {
+  CHECK_PLOG_ENABLED(DEBUG);
+}
+
+TEST(logging, PLOG_VERBOSE_disabled) {
+  CHECK_PLOG_DISABLED(VERBOSE);
+}
+
+TEST(logging, PLOG_VERBOSE_enabled) {
+  CHECK_PLOG_ENABLED(VERBOSE);
+}
+
+#undef CHECK_PLOG_DISABLED
+#undef CHECK_PLOG_ENABLED
+
+
 TEST(logging, UNIMPLEMENTED) {
+  std::string expected = android::base::StringPrintf("%s unimplemented ", __PRETTY_FUNCTION__);
+
+  CapturedStderr cap;
+  errno = ENOENT;
+  UNIMPLEMENTED(ERROR);
+  CheckMessage(cap, android::base::ERROR, expected.c_str());
+}
+
+static void NoopAborter(const char* msg ATTRIBUTE_UNUSED) {
+  LOG(ERROR) << "called noop";
+}
+
+TEST(logging, LOG_FATAL_NOOP_ABORTER) {
   {
+    android::base::SetAborter(NoopAborter);
+
+    android::base::ScopedLogSeverity sls(android::base::ERROR);
     CapturedStderr cap;
-    errno = ENOENT;
-    UNIMPLEMENTED(ERROR);
-    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+    LOG(FATAL) << "foobar";
+    CheckMessage(cap, android::base::FATAL, "foobar");
+    CheckMessage(cap, android::base::ERROR, "called noop");
 
-    std::string output;
-    android::base::ReadFdToString(cap.fd(), &output);
-    ASSERT_GT(output.length(), strlen("unimplemented"));
-
-#if !defined(_WIN32)
-    std::string expected_message =
-        android::base::StringPrintf("%s unimplemented ", __PRETTY_FUNCTION__);
-    std::regex message_regex(
-        make_log_pattern(android::base::ERROR, expected_message.c_str()));
-    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
-#endif
+    android::base::SetAborter(android::base::DefaultAborter);
   }
+
+  ASSERT_DEATH({SuppressAbortUI(); LOG(FATAL) << "foobar";}, "foobar");
+}
+
+struct CountLineAborter {
+  static void CountLineAborterFunction(const char* msg) {
+    while (*msg != 0) {
+      if (*msg == '\n') {
+        newline_count++;
+      }
+      msg++;
+    }
+  }
+  static size_t newline_count;
+};
+size_t CountLineAborter::newline_count = 0;
+
+TEST(logging, LOG_FATAL_ABORTER_MESSAGE) {
+  CountLineAborter::newline_count = 0;
+  android::base::SetAborter(CountLineAborter::CountLineAborterFunction);
+
+  android::base::ScopedLogSeverity sls(android::base::ERROR);
+  CapturedStderr cap;
+  LOG(FATAL) << "foo\nbar";
+
+  EXPECT_EQ(CountLineAborter::newline_count, 1U + 1U);  // +1 for final '\n'.
+}
+
+__attribute__((constructor)) void TestLoggingInConstructor() {
+  LOG(ERROR) << "foobar";
 }
diff --git a/base/parsedouble_test.cpp b/base/parsedouble_test.cpp
new file mode 100644
index 0000000..8734c42
--- /dev/null
+++ b/base/parsedouble_test.cpp
@@ -0,0 +1,38 @@
+/*
+ * 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 "android-base/parsedouble.h"
+
+#include <gtest/gtest.h>
+
+TEST(parsedouble, smoke) {
+  double d;
+  ASSERT_FALSE(android::base::ParseDouble("", &d));
+  ASSERT_FALSE(android::base::ParseDouble("x", &d));
+  ASSERT_FALSE(android::base::ParseDouble("123.4x", &d));
+
+  ASSERT_TRUE(android::base::ParseDouble("123.4", &d));
+  ASSERT_DOUBLE_EQ(123.4, d);
+  ASSERT_TRUE(android::base::ParseDouble("-123.4", &d));
+  ASSERT_DOUBLE_EQ(-123.4, d);
+
+  ASSERT_TRUE(android::base::ParseDouble("0", &d, 0.0));
+  ASSERT_DOUBLE_EQ(0.0, d);
+  ASSERT_FALSE(android::base::ParseDouble("0", &d, 1e-9));
+  ASSERT_FALSE(android::base::ParseDouble("3.0", &d, -1.0, 2.0));
+  ASSERT_TRUE(android::base::ParseDouble("1.0", &d, 0.0, 2.0));
+  ASSERT_DOUBLE_EQ(1.0, d);
+}
diff --git a/base/parseint_test.cpp b/base/parseint_test.cpp
index 6a3ba31..483b1d3 100644
--- a/base/parseint_test.cpp
+++ b/base/parseint_test.cpp
@@ -19,7 +19,7 @@
 #include <gtest/gtest.h>
 
 TEST(parseint, signed_smoke) {
-  int i;
+  int i = 0;
   ASSERT_FALSE(android::base::ParseInt("x", &i));
   ASSERT_FALSE(android::base::ParseInt("123x", &i));
 
@@ -28,7 +28,7 @@
   ASSERT_TRUE(android::base::ParseInt("-123", &i));
   ASSERT_EQ(-123, i);
 
-  short s;
+  short s = 0;
   ASSERT_TRUE(android::base::ParseInt("1234", &s));
   ASSERT_EQ(1234, s);
 
@@ -39,7 +39,7 @@
 }
 
 TEST(parseint, unsigned_smoke) {
-  unsigned int i;
+  unsigned int i = 0u;
   ASSERT_FALSE(android::base::ParseUint("x", &i));
   ASSERT_FALSE(android::base::ParseUint("123x", &i));
 
@@ -47,7 +47,7 @@
   ASSERT_EQ(123u, i);
   ASSERT_FALSE(android::base::ParseUint("-123", &i));
 
-  unsigned short s;
+  unsigned short s = 0u;
   ASSERT_TRUE(android::base::ParseUint("1234", &s));
   ASSERT_EQ(1234u, s);
 
@@ -58,21 +58,41 @@
 }
 
 TEST(parseint, no_implicit_octal) {
-  int i;
+  int i = 0;
   ASSERT_TRUE(android::base::ParseInt("0123", &i));
   ASSERT_EQ(123, i);
 
-  unsigned int u;
+  unsigned int u = 0u;
   ASSERT_TRUE(android::base::ParseUint("0123", &u));
   ASSERT_EQ(123u, u);
 }
 
 TEST(parseint, explicit_hex) {
-  int i;
+  int i = 0;
   ASSERT_TRUE(android::base::ParseInt("0x123", &i));
   ASSERT_EQ(0x123, i);
 
-  unsigned int u;
+  unsigned int u = 0u;
   ASSERT_TRUE(android::base::ParseUint("0x123", &u));
   ASSERT_EQ(0x123u, u);
 }
+
+TEST(parseint, string) {
+  int i = 0;
+  ASSERT_TRUE(android::base::ParseInt(std::string("123"), &i));
+  ASSERT_EQ(123, i);
+
+  unsigned int u = 0u;
+  ASSERT_TRUE(android::base::ParseUint(std::string("123"), &u));
+  ASSERT_EQ(123u, u);
+}
+
+TEST(parseint, untouched_on_failure) {
+  int i = 123;
+  ASSERT_FALSE(android::base::ParseInt("456x", &i));
+  ASSERT_EQ(123, i);
+
+  unsigned int u = 123u;
+  ASSERT_FALSE(android::base::ParseInt("456x", &u));
+  ASSERT_EQ(123u, u);
+}
diff --git a/base/properties.cpp b/base/properties.cpp
new file mode 100644
index 0000000..32c0128
--- /dev/null
+++ b/base/properties.cpp
@@ -0,0 +1,178 @@
+/*
+ * 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.
+ */
+
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+
+#include "android-base/properties.h"
+
+#include <sys/system_properties.h>
+#include <sys/_system_properties.h>
+
+#include <algorithm>
+#include <chrono>
+#include <string>
+
+#include <android-base/parseint.h>
+
+using namespace std::chrono_literals;
+
+namespace android {
+namespace base {
+
+std::string GetProperty(const std::string& key, const std::string& default_value) {
+  const prop_info* pi = __system_property_find(key.c_str());
+  if (pi == nullptr) return default_value;
+
+  char buf[PROP_VALUE_MAX];
+  if (__system_property_read(pi, nullptr, buf) > 0) return buf;
+
+  // If the property exists but is empty, also return the default value.
+  // Since we can't remove system properties, "empty" is traditionally
+  // the same as "missing" (this was true for cutils' property_get).
+  return default_value;
+}
+
+bool GetBoolProperty(const std::string& key, bool default_value) {
+  std::string value = GetProperty(key, "");
+  if (value == "1" || value == "y" || value == "yes" || value == "on" || value == "true") {
+    return true;
+  } else if (value == "0" || value == "n" || value == "no" || value == "off" || value == "false") {
+    return false;
+  }
+  return default_value;
+}
+
+template <typename T>
+T GetIntProperty(const std::string& key, T default_value, T min, T max) {
+  T result;
+  std::string value = GetProperty(key, "");
+  if (!value.empty() && android::base::ParseInt(value, &result, min, max)) return result;
+  return default_value;
+}
+
+template <typename T>
+T GetUintProperty(const std::string& key, T default_value, T max) {
+  T result;
+  std::string value = GetProperty(key, "");
+  if (!value.empty() && android::base::ParseUint(value, &result, max)) return result;
+  return default_value;
+}
+
+template int8_t GetIntProperty(const std::string&, int8_t, int8_t, int8_t);
+template int16_t GetIntProperty(const std::string&, int16_t, int16_t, int16_t);
+template int32_t GetIntProperty(const std::string&, int32_t, int32_t, int32_t);
+template int64_t GetIntProperty(const std::string&, int64_t, int64_t, int64_t);
+
+template uint8_t GetUintProperty(const std::string&, uint8_t, uint8_t);
+template uint16_t GetUintProperty(const std::string&, uint16_t, uint16_t);
+template uint32_t GetUintProperty(const std::string&, uint32_t, uint32_t);
+template uint64_t GetUintProperty(const std::string&, uint64_t, uint64_t);
+
+bool SetProperty(const std::string& key, const std::string& value) {
+  return (__system_property_set(key.c_str(), value.c_str()) == 0);
+}
+
+struct WaitForPropertyData {
+  bool done;
+  const std::string* expected_value;
+  unsigned last_read_serial;
+};
+
+static void WaitForPropertyCallback(void* data_ptr, const char*, const char* value, unsigned serial) {
+  WaitForPropertyData* data = reinterpret_cast<WaitForPropertyData*>(data_ptr);
+  if (*data->expected_value == value) {
+    data->done = true;
+  } else {
+    data->last_read_serial = serial;
+  }
+}
+
+// TODO: chrono_utils?
+static void DurationToTimeSpec(timespec& ts, std::chrono::nanoseconds 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();
+}
+
+using AbsTime = std::chrono::time_point<std::chrono::steady_clock>;
+
+static void UpdateTimeSpec(timespec& ts,
+                           const AbsTime& timeout) {
+  auto now = std::chrono::steady_clock::now();
+  auto remaining_timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(timeout - now);
+  if (remaining_timeout < 0ns) {
+    ts = { 0, 0 };
+  } else {
+    DurationToTimeSpec(ts, remaining_timeout);
+  }
+}
+
+// Waits for the system property `key` to be created.
+// Times out after `relative_timeout`.
+// Sets absolute_timeout which represents absolute time for the timeout.
+// 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;
+
+  // Find the property's prop_info*.
+  const prop_info* pi;
+  unsigned global_serial = 0;
+  while ((pi = __system_property_find(key.c_str())) == nullptr) {
+    // The property doesn't even exist yet.
+    // Wait for a global change and then look again.
+    timespec ts;
+    UpdateTimeSpec(ts, absolute_timeout);
+    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,
+                     std::chrono::milliseconds relative_timeout) {
+  AbsTime absolute_timeout;
+  const prop_info* pi = WaitForPropertyCreation(key, relative_timeout, absolute_timeout);
+  if (pi == nullptr) return false;
+
+  WaitForPropertyData data;
+  data.expected_value = &expected_value;
+  data.done = false;
+  while (true) {
+    timespec ts;
+    // Check whether the property has the value we're looking for?
+    __system_property_read_callback(pi, WaitForPropertyCallback, &data);
+    if (data.done) return true;
+
+    // It didn't, so wait for the property to change before checking again.
+    UpdateTimeSpec(ts, absolute_timeout);
+    uint32_t unused;
+    if (!__system_property_wait(pi, data.last_read_serial, &unused, &ts)) return false;
+  }
+}
+
+bool WaitForPropertyCreation(const std::string& key,
+                             std::chrono::milliseconds relative_timeout) {
+  AbsTime absolute_timeout;
+  return (WaitForPropertyCreation(key, relative_timeout, absolute_timeout) != nullptr);
+}
+
+}  // namespace base
+}  // namespace android
diff --git a/base/properties_test.cpp b/base/properties_test.cpp
new file mode 100644
index 0000000..1bbe482
--- /dev/null
+++ b/base/properties_test.cpp
@@ -0,0 +1,174 @@
+/*
+ * 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 "android-base/properties.h"
+
+#include <gtest/gtest.h>
+
+#include <atomic>
+#include <chrono>
+#include <string>
+#include <thread>
+
+using namespace std::chrono_literals;
+
+TEST(properties, smoke) {
+  android::base::SetProperty("debug.libbase.property_test", "hello");
+
+  std::string s = android::base::GetProperty("debug.libbase.property_test", "");
+  ASSERT_EQ("hello", s);
+
+  android::base::SetProperty("debug.libbase.property_test", "world");
+  s = android::base::GetProperty("debug.libbase.property_test", "");
+  ASSERT_EQ("world", s);
+
+  s = android::base::GetProperty("this.property.does.not.exist", "");
+  ASSERT_EQ("", s);
+
+  s = android::base::GetProperty("this.property.does.not.exist", "default");
+  ASSERT_EQ("default", s);
+}
+
+TEST(properties, empty) {
+  // Because you can't delete a property, people "delete" them by
+  // setting them to the empty string. In that case we'd want to
+  // keep the default value (like cutils' property_get did).
+  android::base::SetProperty("debug.libbase.property_test", "");
+  std::string s = android::base::GetProperty("debug.libbase.property_test", "default");
+  ASSERT_EQ("default", s);
+}
+
+static void CheckGetBoolProperty(bool expected, const std::string& value, bool default_value) {
+  android::base::SetProperty("debug.libbase.property_test", value.c_str());
+  ASSERT_EQ(expected, android::base::GetBoolProperty("debug.libbase.property_test", default_value));
+}
+
+TEST(properties, GetBoolProperty_true) {
+  CheckGetBoolProperty(true, "1", false);
+  CheckGetBoolProperty(true, "y", false);
+  CheckGetBoolProperty(true, "yes", false);
+  CheckGetBoolProperty(true, "on", false);
+  CheckGetBoolProperty(true, "true", false);
+}
+
+TEST(properties, GetBoolProperty_false) {
+  CheckGetBoolProperty(false, "0", true);
+  CheckGetBoolProperty(false, "n", true);
+  CheckGetBoolProperty(false, "no", true);
+  CheckGetBoolProperty(false, "off", true);
+  CheckGetBoolProperty(false, "false", true);
+}
+
+TEST(properties, GetBoolProperty_default) {
+  CheckGetBoolProperty(true, "burp", true);
+  CheckGetBoolProperty(false, "burp", false);
+}
+
+template <typename T> void CheckGetIntProperty() {
+  // Positive and negative.
+  android::base::SetProperty("debug.libbase.property_test", "-12");
+  EXPECT_EQ(T(-12), android::base::GetIntProperty<T>("debug.libbase.property_test", 45));
+  android::base::SetProperty("debug.libbase.property_test", "12");
+  EXPECT_EQ(T(12), android::base::GetIntProperty<T>("debug.libbase.property_test", 45));
+
+  // Default value.
+  android::base::SetProperty("debug.libbase.property_test", "");
+  EXPECT_EQ(T(45), android::base::GetIntProperty<T>("debug.libbase.property_test", 45));
+
+  // Bounds checks.
+  android::base::SetProperty("debug.libbase.property_test", "0");
+  EXPECT_EQ(T(45), android::base::GetIntProperty<T>("debug.libbase.property_test", 45, 1, 2));
+  android::base::SetProperty("debug.libbase.property_test", "1");
+  EXPECT_EQ(T(1), android::base::GetIntProperty<T>("debug.libbase.property_test", 45, 1, 2));
+  android::base::SetProperty("debug.libbase.property_test", "2");
+  EXPECT_EQ(T(2), android::base::GetIntProperty<T>("debug.libbase.property_test", 45, 1, 2));
+  android::base::SetProperty("debug.libbase.property_test", "3");
+  EXPECT_EQ(T(45), android::base::GetIntProperty<T>("debug.libbase.property_test", 45, 1, 2));
+}
+
+template <typename T> void CheckGetUintProperty() {
+  // Positive.
+  android::base::SetProperty("debug.libbase.property_test", "12");
+  EXPECT_EQ(T(12), android::base::GetUintProperty<T>("debug.libbase.property_test", 45));
+
+  // Default value.
+  android::base::SetProperty("debug.libbase.property_test", "");
+  EXPECT_EQ(T(45), android::base::GetUintProperty<T>("debug.libbase.property_test", 45));
+
+  // Bounds checks.
+  android::base::SetProperty("debug.libbase.property_test", "12");
+  EXPECT_EQ(T(12), android::base::GetUintProperty<T>("debug.libbase.property_test", 33, 22));
+  android::base::SetProperty("debug.libbase.property_test", "12");
+  EXPECT_EQ(T(5), android::base::GetUintProperty<T>("debug.libbase.property_test", 5, 10));
+}
+
+TEST(properties, GetIntProperty_int8_t) { CheckGetIntProperty<int8_t>(); }
+TEST(properties, GetIntProperty_int16_t) { CheckGetIntProperty<int16_t>(); }
+TEST(properties, GetIntProperty_int32_t) { CheckGetIntProperty<int32_t>(); }
+TEST(properties, GetIntProperty_int64_t) { CheckGetIntProperty<int64_t>(); }
+
+TEST(properties, GetUintProperty_uint8_t) { CheckGetUintProperty<uint8_t>(); }
+TEST(properties, GetUintProperty_uint16_t) { CheckGetUintProperty<uint16_t>(); }
+TEST(properties, GetUintProperty_uint32_t) { CheckGetUintProperty<uint32_t>(); }
+TEST(properties, GetUintProperty_uint64_t) { CheckGetUintProperty<uint64_t>(); }
+
+TEST(properties, WaitForProperty) {
+  std::atomic<bool> flag{false};
+  std::thread thread([&]() {
+    std::this_thread::sleep_for(100ms);
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "a");
+    while (!flag) std::this_thread::yield();
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "b");
+  });
+
+  ASSERT_TRUE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "a", 1s));
+  flag = true;
+  ASSERT_TRUE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "b", 1s));
+  thread.join();
+}
+
+TEST(properties, WaitForProperty_timeout) {
+  auto t0 = std::chrono::steady_clock::now();
+  ASSERT_FALSE(android::base::WaitForProperty("debug.libbase.WaitForProperty_timeout_test", "a",
+                                              200ms));
+  auto t1 = std::chrono::steady_clock::now();
+
+  ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0), 200ms);
+  // Upper bounds on timing are inherently flaky, but let's try...
+  ASSERT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0), 600ms);
+}
+
+TEST(properties, WaitForPropertyCreation) {
+  std::thread thread([&]() {
+    std::this_thread::sleep_for(100ms);
+    android::base::SetProperty("debug.libbase.WaitForPropertyCreation_test", "a");
+  });
+
+  ASSERT_TRUE(android::base::WaitForPropertyCreation(
+          "debug.libbase.WaitForPropertyCreation_test", 1s));
+  thread.join();
+}
+
+TEST(properties, WaitForPropertyCreation_timeout) {
+  auto t0 = std::chrono::steady_clock::now();
+  ASSERT_FALSE(android::base::WaitForPropertyCreation(
+          "debug.libbase.WaitForPropertyCreation_timeout_test", 200ms));
+  auto t1 = std::chrono::steady_clock::now();
+
+  ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0), 200ms);
+  // Upper bounds on timing are inherently flaky, but let's try...
+  ASSERT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0), 600ms);
+}
diff --git a/base/quick_exit.cpp b/base/quick_exit.cpp
new file mode 100644
index 0000000..e4dd62b
--- /dev/null
+++ b/base/quick_exit.cpp
@@ -0,0 +1,46 @@
+/*
+ * 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 "android-base/quick_exit.h"
+
+#if !defined(__linux__)
+
+#include <mutex>
+#include <vector>
+
+namespace android {
+namespace base {
+
+static auto& quick_exit_mutex = *new std::mutex();
+static auto& quick_exit_handlers = *new std::vector<void (*)()>();
+
+void quick_exit(int exit_code) {
+  std::lock_guard<std::mutex> lock(quick_exit_mutex);
+  for (auto it = quick_exit_handlers.rbegin(); it != quick_exit_handlers.rend(); ++it) {
+    (*it)();
+  }
+  _Exit(exit_code);
+}
+
+int at_quick_exit(void (*func)()) {
+  std::lock_guard<std::mutex> lock(quick_exit_mutex);
+  quick_exit_handlers.push_back(func);
+  return 0;
+}
+
+}  // namespace base
+}  // namespace android
+#endif
diff --git a/base/quick_exit_test.cpp b/base/quick_exit_test.cpp
new file mode 100644
index 0000000..7ca8156
--- /dev/null
+++ b/base/quick_exit_test.cpp
@@ -0,0 +1,54 @@
+/*
+ * 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 "android-base/quick_exit.h"
+
+#include <gtest/gtest.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <string>
+
+#include "android-base/test_utils.h"
+
+// These tests are a bit sketchy, since each test run adds global state that affects subsequent
+// tests (including ones not in this file!). Exit with 0 in Exiter and stick the at_quick_exit test
+// at the end to hack around this.
+struct Exiter {
+  ~Exiter() {
+    _Exit(0);
+  }
+};
+
+TEST(quick_exit, smoke) {
+  ASSERT_EXIT(android::base::quick_exit(123), testing::ExitedWithCode(123), "");
+}
+
+TEST(quick_exit, skip_static_destructors) {
+  static Exiter exiter;
+  ASSERT_EXIT(android::base::quick_exit(123), testing::ExitedWithCode(123), "");
+}
+
+TEST(quick_exit, at_quick_exit) {
+  static int counter = 4;
+  // "Functions passed to at_quick_exit are called in reverse order of their registration."
+  ASSERT_EQ(0, android::base::at_quick_exit([]() { _exit(counter); }));
+  ASSERT_EQ(0, android::base::at_quick_exit([]() { counter += 2; }));
+  ASSERT_EQ(0, android::base::at_quick_exit([]() { counter *= 10; }));
+  ASSERT_EXIT(android::base::quick_exit(123), testing::ExitedWithCode(42), "");
+}
diff --git a/base/strings.cpp b/base/strings.cpp
index b8775df..bfdaf12 100644
--- a/base/strings.cpp
+++ b/base/strings.cpp
@@ -36,11 +36,12 @@
 
   size_t base = 0;
   size_t found;
-  do {
+  while (true) {
     found = s.find_first_of(delimiters, base);
     result.push_back(s.substr(base, found - base));
+    if (found == s.npos) break;
     base = found + 1;
-  } while (found != s.npos);
+  }
 
   return result;
 }
@@ -87,17 +88,33 @@
 template std::string Join(const std::vector<const char*>&, const std::string&);
 
 bool StartsWith(const std::string& s, const char* prefix) {
-  return s.compare(0, strlen(prefix), prefix) == 0;
+  return strncmp(s.c_str(), prefix, strlen(prefix)) == 0;
 }
 
-bool EndsWith(const std::string& s, const char* suffix) {
+bool StartsWithIgnoreCase(const std::string& s, const char* prefix) {
+  return strncasecmp(s.c_str(), prefix, strlen(prefix)) == 0;
+}
+
+static bool EndsWith(const std::string& s, const char* suffix, bool case_sensitive) {
   size_t suffix_length = strlen(suffix);
   size_t string_length = s.size();
   if (suffix_length > string_length) {
     return false;
   }
   size_t offset = string_length - suffix_length;
-  return s.compare(offset, suffix_length, suffix) == 0;
+  return (case_sensitive ? strncmp : strncasecmp)(s.c_str() + offset, suffix, suffix_length) == 0;
+}
+
+bool EndsWith(const std::string& s, const char* suffix) {
+  return EndsWith(s, suffix, true);
+}
+
+bool EndsWithIgnoreCase(const std::string& s, const char* suffix) {
+  return EndsWith(s, suffix, false);
+}
+
+bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs) {
+  return strcasecmp(lhs.c_str(), rhs.c_str()) == 0;
 }
 
 }  // namespace base
diff --git a/base/strings_test.cpp b/base/strings_test.cpp
index 30ae29e..7ed5b2b 100644
--- a/base/strings_test.cpp
+++ b/base/strings_test.cpp
@@ -134,44 +134,124 @@
               "2,1" == android::base::Join(list, ','));
 }
 
-TEST(strings, startswith_empty) {
+TEST(strings, StartsWith_empty) {
   ASSERT_FALSE(android::base::StartsWith("", "foo"));
   ASSERT_TRUE(android::base::StartsWith("", ""));
 }
 
-TEST(strings, startswith_simple) {
+TEST(strings, StartsWithIgnoreCase_empty) {
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("", "foo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("", ""));
+}
+
+TEST(strings, StartsWith_simple) {
   ASSERT_TRUE(android::base::StartsWith("foo", ""));
   ASSERT_TRUE(android::base::StartsWith("foo", "f"));
   ASSERT_TRUE(android::base::StartsWith("foo", "fo"));
   ASSERT_TRUE(android::base::StartsWith("foo", "foo"));
 }
 
-TEST(strings, startswith_prefix_too_long) {
+TEST(strings, StartsWithIgnoreCase_simple) {
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", ""));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "f"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "F"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "fo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "fO"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "Fo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "FO"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "foo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "foO"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "fOo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "fOO"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "Foo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "FoO"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "FOo"));
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("foo", "FOO"));
+}
+
+TEST(strings, StartsWith_prefix_too_long) {
   ASSERT_FALSE(android::base::StartsWith("foo", "foobar"));
 }
 
-TEST(strings, startswith_contains_prefix) {
+TEST(strings, StartsWithIgnoreCase_prefix_too_long) {
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foo", "foobar"));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foo", "FOOBAR"));
+}
+
+TEST(strings, StartsWith_contains_prefix) {
   ASSERT_FALSE(android::base::StartsWith("foobar", "oba"));
   ASSERT_FALSE(android::base::StartsWith("foobar", "bar"));
 }
 
-TEST(strings, endswith_empty) {
+TEST(strings, StartsWithIgnoreCase_contains_prefix) {
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foobar", "oba"));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foobar", "OBA"));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foobar", "bar"));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("foobar", "BAR"));
+}
+
+TEST(strings, EndsWith_empty) {
   ASSERT_FALSE(android::base::EndsWith("", "foo"));
   ASSERT_TRUE(android::base::EndsWith("", ""));
 }
 
-TEST(strings, endswith_simple) {
+TEST(strings, EndsWithIgnoreCase_empty) {
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("", "foo"));
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("", "FOO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("", ""));
+}
+
+TEST(strings, EndsWith_simple) {
   ASSERT_TRUE(android::base::EndsWith("foo", ""));
   ASSERT_TRUE(android::base::EndsWith("foo", "o"));
   ASSERT_TRUE(android::base::EndsWith("foo", "oo"));
   ASSERT_TRUE(android::base::EndsWith("foo", "foo"));
 }
 
-TEST(strings, endswith_prefix_too_long) {
+TEST(strings, EndsWithIgnoreCase_simple) {
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", ""));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "o"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "O"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "oo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "oO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "Oo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "OO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "foo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "foO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "fOo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "fOO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "Foo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "FoO"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "FOo"));
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("foo", "FOO"));
+}
+
+TEST(strings, EndsWith_prefix_too_long) {
   ASSERT_FALSE(android::base::EndsWith("foo", "foobar"));
 }
 
-TEST(strings, endswith_contains_prefix) {
+TEST(strings, EndsWithIgnoreCase_prefix_too_long) {
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("foo", "foobar"));
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("foo", "FOOBAR"));
+}
+
+TEST(strings, EndsWith_contains_prefix) {
   ASSERT_FALSE(android::base::EndsWith("foobar", "oba"));
   ASSERT_FALSE(android::base::EndsWith("foobar", "foo"));
 }
+
+TEST(strings, EndsWithIgnoreCase_contains_prefix) {
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("foobar", "OBA"));
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("foobar", "FOO"));
+}
+
+TEST(strings, EqualsIgnoreCase) {
+  ASSERT_TRUE(android::base::EqualsIgnoreCase("foo", "FOO"));
+  ASSERT_TRUE(android::base::EqualsIgnoreCase("FOO", "foo"));
+  ASSERT_FALSE(android::base::EqualsIgnoreCase("foo", "bar"));
+  ASSERT_FALSE(android::base::EqualsIgnoreCase("foo", "fool"));
+}
+
+TEST(strings, ubsan_28729303) {
+  android::base::Split("/dev/null", ":");
+}
diff --git a/base/test_utils.cpp b/base/test_utils.cpp
index 337ba7c..636477d 100644
--- a/base/test_utils.cpp
+++ b/base/test_utils.cpp
@@ -16,7 +16,6 @@
 
 #include "android-base/logging.h"
 #include "android-base/test_utils.h"
-#include "utils/Compat.h" // For OS_PATH_SEPARATOR.
 
 #include <fcntl.h>
 #include <stdio.h>
@@ -27,6 +26,9 @@
 #if defined(_WIN32)
 #include <windows.h>
 #include <direct.h>
+#define OS_PATH_SEPARATOR '\\'
+#else
+#define OS_PATH_SEPARATOR '/'
 #endif
 
 #include <string>
@@ -55,7 +57,13 @@
 
 static std::string GetSystemTempDir() {
 #if defined(__ANDROID__)
-  return "/data/local/tmp";
+  const char* tmpdir = "/data/local/tmp";
+  if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
+    return tmpdir;
+  }
+  // Tests running in app context can't access /data/local/tmp,
+  // so try current directory if /data/local/tmp is not accessible.
+  return ".";
 #elif defined(_WIN32)
   char tmp_dir[MAX_PATH];
   DWORD result = GetTempPathA(sizeof(tmp_dir), tmp_dir);
@@ -100,3 +108,32 @@
            OS_PATH_SEPARATOR);
   return (mkdtemp(path) != nullptr);
 }
+
+CapturedStderr::CapturedStderr() : old_stderr_(-1) {
+  init();
+}
+
+CapturedStderr::~CapturedStderr() {
+  reset();
+}
+
+int CapturedStderr::fd() const {
+  return temp_file_.fd;
+}
+
+void CapturedStderr::init() {
+#if defined(_WIN32)
+  // On Windows, stderr is often buffered, so make sure it is unbuffered so
+  // that we can immediately read back what was written to stderr.
+  CHECK_EQ(0, setvbuf(stderr, NULL, _IONBF, 0));
+#endif
+  old_stderr_ = dup(STDERR_FILENO);
+  CHECK_NE(-1, old_stderr_);
+  CHECK_NE(-1, dup2(fd(), STDERR_FILENO));
+}
+
+void CapturedStderr::reset() {
+  CHECK_NE(-1, dup2(old_stderr_, STDERR_FILENO));
+  CHECK_EQ(0, close(old_stderr_));
+  // Note: cannot restore prior setvbuf() setting.
+}
diff --git a/bootstat/Android.bp b/bootstat/Android.bp
new file mode 100644
index 0000000..f744ad1
--- /dev/null
+++ b/bootstat/Android.bp
@@ -0,0 +1,88 @@
+//
+// 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.
+//
+
+bootstat_lib_src_files = [
+    "boot_event_record_store.cpp",
+    "uptime_parser.cpp",
+]
+
+cc_defaults {
+    name: "bootstat_defaults",
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+        "libmetricslogger",
+    ],
+    whole_static_libs: ["libgtest_prod"],
+    // Clang is required because of C++14
+    clang: true,
+}
+
+// bootstat static library
+// -----------------------------------------------------------------------------
+cc_library_static {
+    name: "libbootstat",
+    defaults: ["bootstat_defaults"],
+    srcs: bootstat_lib_src_files,
+}
+
+// bootstat static library, debug
+// -----------------------------------------------------------------------------
+cc_library_static {
+    name: "libbootstat_debug",
+    defaults: ["bootstat_defaults"],
+    host_supported: true,
+    srcs: bootstat_lib_src_files,
+
+    target: {
+        host: {
+            cflags: ["-UNDEBUG"],
+        },
+    },
+}
+
+// bootstat binary
+// -----------------------------------------------------------------------------
+cc_binary {
+    name: "bootstat",
+    defaults: ["bootstat_defaults"],
+    static_libs: ["libbootstat"],
+    init_rc: ["bootstat.rc"],
+    srcs: ["bootstat.cpp"],
+}
+
+// Native tests
+// -----------------------------------------------------------------------------
+cc_test {
+    name: "bootstat_tests",
+    defaults: ["bootstat_defaults"],
+    host_supported: true,
+    static_libs: [
+        "libbootstat_debug",
+        "libgmock",
+    ],
+    srcs: [
+        "boot_event_record_store_test.cpp",
+        "testrunner.cpp",
+    ],
+}
diff --git a/bootstat/Android.mk b/bootstat/Android.mk
deleted file mode 100644
index 6300941..0000000
--- a/bootstat/Android.mk
+++ /dev/null
@@ -1,143 +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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-bootstat_c_includes := external/gtest/include
-
-bootstat_lib_src_files := \
-        boot_event_record_store.cpp \
-        event_log_list_builder.cpp \
-        histogram_logger.cpp \
-        uptime_parser.cpp \
-
-bootstat_src_files := \
-        bootstat.cpp \
-
-bootstat_test_src_files := \
-        boot_event_record_store_test.cpp \
-        event_log_list_builder_test.cpp \
-        testrunner.cpp \
-
-bootstat_shared_libs := \
-        libbase \
-        libcutils \
-        liblog \
-
-bootstat_cflags := \
-        -Wall \
-        -Wextra \
-        -Werror \
-
-# 524291 corresponds to sysui_histogram, from
-# frameworks/base/core/java/com/android/internal/logging/EventLogTags.logtags
-bootstat_cflags += -DHISTOGRAM_LOG_TAG=524291
-
-bootstat_debug_cflags := \
-        $(bootstat_cflags) \
-        -UNDEBUG \
-
-# bootstat static library
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbootstat
-LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_C_INCLUDES := $(bootstat_c_includes)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_SRC_FILES := $(bootstat_lib_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_STATIC_LIBRARY)
-
-# bootstat static library, debug
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbootstat_debug
-LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_C_INCLUDES := $(bootstat_c_includes)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_SRC_FILES := $(bootstat_lib_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_STATIC_LIBRARY)
-
-# bootstat host static library, debug
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbootstat_host_debug
-LOCAL_CFLAGS := $(bootstat_debug_cflags)
-LOCAL_C_INCLUDES := $(bootstat_c_includes)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_SRC_FILES := $(bootstat_lib_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-# bootstat binary
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := bootstat
-LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_C_INCLUDES := $(bootstat_c_includes)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_STATIC_LIBRARIES := libbootstat
-LOCAL_INIT_RC := bootstat.rc
-LOCAL_SRC_FILES := $(bootstat_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_EXECUTABLE)
-
-# Native tests
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := bootstat_tests
-LOCAL_CFLAGS := $(bootstat_tests_cflags)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_STATIC_LIBRARIES := libbootstat_debug libgmock
-LOCAL_SRC_FILES := $(bootstat_test_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_NATIVE_TEST)
-
-# Host native tests
-# -----------------------------------------------------------------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := bootstat_tests
-LOCAL_CFLAGS := $(bootstat_tests_cflags)
-LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
-LOCAL_STATIC_LIBRARIES := libbootstat_host_debug libgmock_host
-LOCAL_SRC_FILES := $(bootstat_test_src_files)
-# Clang is required because of C++14
-LOCAL_CLANG := true
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 346eada..2648594 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -26,7 +26,6 @@
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
-#include "histogram_logger.h"
 #include "uptime_parser.h"
 
 namespace {
@@ -46,24 +45,6 @@
 
   *uptime = file_stat.st_mtime;
 
-  // The following code (till function exit) is a debug test to ensure the
-  // validity of the file mtime value, i.e., to check that the record file
-  // mtime values are not changed once set.
-  // TODO(jhawkins): Remove this code.
-  std::string content;
-  if (!android::base::ReadFileToString(path, &content)) {
-    PLOG(ERROR) << "Failed to read " << path;
-    return false;
-  }
-
-  // Ignore existing bootstat records (which do not contain file content).
-  if (!content.empty()) {
-    int32_t value;
-    if (android::base::ParseInt(content.c_str(), &value)) {
-      bootstat::LogHistogram("bootstat_mtime_matches_content", value == *uptime);
-    }
-  }
-
   return true;
 }
 
@@ -89,16 +70,6 @@
     return;
   }
 
-  // Writing the value as content in the record file is a debug measure to
-  // ensure the validity of the file mtime value, i.e., to check that the record
-  // file mtime values are not changed once set.
-  // TODO(jhawkins): Remove this block.
-  if (!android::base::WriteStringToFd(std::to_string(value), record_fd)) {
-    PLOG(ERROR) << "Failed to write value to " << record_path;
-    close(record_fd);
-    return;
-  }
-
   // Fill out the stat structure for |record_path| in order to get the atime to
   // set in the utime() call.
   struct stat file_stat;
diff --git a/bootstat/boot_event_record_store_test.cpp b/bootstat/boot_event_record_store_test.cpp
index 01c2cc1..90f6513 100644
--- a/bootstat/boot_event_record_store_test.cpp
+++ b/bootstat/boot_event_record_store_test.cpp
@@ -45,14 +45,6 @@
     return false;
   }
 
-  // Writing the value as content in the record file is a debug measure to
-  // ensure the validity of the file mtime value, i.e., to check that the record
-  // file mtime values are not changed once set.
-  // TODO(jhawkins): Remove this block.
-  if (!android::base::WriteStringToFd(std::to_string(value), record_fd)) {
-    return false;
-  }
-
   // Set the |mtime| of the file to store the value of the boot event while
   // preserving the |atime|.
   struct timeval atime = {/* tv_sec */ 0, /* tv_usec */ 0};
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index d547c19..a4cc5f2 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -20,6 +20,7 @@
 
 #include <getopt.h>
 #include <unistd.h>
+
 #include <cmath>
 #include <cstddef>
 #include <cstdio>
@@ -27,13 +28,16 @@
 #include <map>
 #include <memory>
 #include <string>
+#include <vector>
+
+#include <android/log.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
+#include <android-base/strings.h>
 #include <cutils/properties.h>
-#include <log/log.h>
+#include <metricslogger/metrics_logger.h>
+
 #include "boot_event_record_store.h"
-#include "event_log_list_builder.h"
-#include "histogram_logger.h"
 #include "uptime_parser.h"
 
 namespace {
@@ -45,7 +49,23 @@
 
   auto events = boot_event_store.GetAllBootEvents();
   for (auto i = events.cbegin(); i != events.cend(); ++i) {
-    bootstat::LogHistogram(i->first, i->second);
+    android::metricslogger::LogHistogram(i->first, i->second);
+  }
+}
+
+// Records the named boot |event| to the record store. If |value| is non-empty
+// and is a proper string representation of an integer value, the converted
+// integer value is associated with the boot event.
+void RecordBootEventFromCommandLine(
+    const std::string& event, const std::string& value_str) {
+  BootEventRecordStore boot_event_store;
+  if (!value_str.empty()) {
+    int32_t value = 0;
+    if (android::base::ParseInt(value_str, &value)) {
+      boot_event_store.AddBootEventWithValue(event, value);
+    }
+  } else {
+    boot_event_store.AddBootEvent(event);
   }
 }
 
@@ -68,6 +88,7 @@
           "  -l, --log             Log all metrics to logstorage\n"
           "  -p, --print           Dump the boot event records to the console\n"
           "  -r, --record          Record the timestamp of a named boot event\n"
+          "  --value               Optional value to associate with the boot event\n"
           "  --record_boot_reason  Record the reason why the device booted\n"
           "  --record_time_since_factory_reset Record the time since the device was reset\n");
 }
@@ -122,6 +143,30 @@
   {"Reboot", 18},
   {"rtc", 19},
   {"edl", 20},
+  {"oem_pon1", 21},
+  {"oem_powerkey", 22},
+  {"oem_unknown_reset", 23},
+  {"srto: HWWDT reset SC", 24},
+  {"srto: HWWDT reset platform", 25},
+  {"srto: bootloader", 26},
+  {"srto: kernel panic", 27},
+  {"srto: kernel watchdog reset", 28},
+  {"srto: normal", 29},
+  {"srto: reboot", 30},
+  {"srto: reboot-bootloader", 31},
+  {"srto: security watchdog reset", 32},
+  {"srto: wakesrc", 33},
+  {"srto: watchdog", 34},
+  {"srto:1-1", 35},
+  {"srto:omap_hsmm", 36},
+  {"srto:phy0", 37},
+  {"srto:rtc0", 38},
+  {"srto:touchpad", 39},
+  {"watchdog", 40},
+  {"watchdogr", 41},
+  {"wdog_bark", 42},
+  {"wdog_bite", 43},
+  {"wdog_reset", 44},
 };
 
 // Converts a string value representing the reason the system booted to an
@@ -149,7 +194,7 @@
 
   std::string build_date_str = GetProperty("ro.build.date.utc");
   int32_t build_date;
-  if (!android::base::ParseInt(build_date_str.c_str(), &build_date)) {
+  if (!android::base::ParseInt(build_date_str, &build_date)) {
     return std::string();
   }
 
@@ -164,6 +209,46 @@
   return boot_complete_prefix;
 }
 
+// Records the value of a given ro.boottime.init property in milliseconds.
+void RecordInitBootTimeProp(
+    BootEventRecordStore* boot_event_store, const char* property) {
+  std::string value = GetProperty(property);
+
+  int32_t time_in_ms;
+  if (android::base::ParseInt(value, &time_in_ms)) {
+    boot_event_store->AddBootEventWithValue(property, time_in_ms);
+  }
+}
+
+// Parses and records the set of bootloader stages and associated boot times
+// from the ro.boot.boottime system property.
+void RecordBootloaderTimings(BootEventRecordStore* boot_event_store) {
+  // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN'.
+  std::string value = GetProperty("ro.boot.boottime");
+  if (value.empty()) {
+    // ro.boot.boottime is not reported on all devices.
+    return;
+  }
+
+  int32_t total_time = 0;
+  auto stages = android::base::Split(value, ",");
+  for (auto const &stageTiming : stages) {
+    // |stageTiming| is of the form 'stage:time'.
+    auto stageTimingValues = android::base::Split(stageTiming, ":");
+    DCHECK_EQ(2, stageTimingValues.size());
+
+    std::string stageName = stageTimingValues[0];
+    int32_t time_ms;
+    if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
+      total_time += time_ms;
+      boot_event_store->AddBootEventWithValue(
+          "boottime.bootloader." + stageName, time_ms);
+    }
+  }
+
+  boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
+}
+
 // Records several metrics related to the time it takes to boot the device,
 // including disambiguating boot time on encrypted or non-encrypted devices.
 void RecordBootComplete() {
@@ -213,6 +298,12 @@
   // Record the total time from device startup to boot complete, regardless of
   // encryption state.
   boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime);
+
+  RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
+  RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
+  RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
+
+  RecordBootloaderTimings(&boot_event_store);
 }
 
 // Records the boot_reason metric by querying the ro.boot.bootreason system
@@ -234,18 +325,18 @@
 
   if (current_time_utc < 0) {
     // UMA does not display negative values in buckets, so convert to positive.
-    bootstat::LogHistogram(
+    android::metricslogger::LogHistogram(
         "factory_reset_current_time_failure", std::abs(current_time_utc));
 
-    // Logging via BootEventRecordStore to see if using bootstat::LogHistogram
+    // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
     // is losing records somehow.
     boot_event_store.AddBootEventWithValue(
         "factory_reset_current_time_failure", std::abs(current_time_utc));
     return;
   } else {
-    bootstat::LogHistogram("factory_reset_current_time", current_time_utc);
+    android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
 
-    // Logging via BootEventRecordStore to see if using bootstat::LogHistogram
+    // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
     // is losing records somehow.
     boot_event_store.AddBootEventWithValue(
         "factory_reset_current_time", current_time_utc);
@@ -264,9 +355,9 @@
   // Calculate and record the difference in time between now and the
   // factory_reset time.
   time_t factory_reset_utc = record.second;
-  bootstat::LogHistogram("factory_reset_record_value", factory_reset_utc);
+  android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
 
-  // Logging via BootEventRecordStore to see if using bootstat::LogHistogram
+  // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
   // is losing records somehow.
   boot_event_store.AddBootEventWithValue(
       "factory_reset_record_value", factory_reset_utc);
@@ -286,6 +377,7 @@
   LOG(INFO) << "Service started: " << cmd_line;
 
   int option_index = 0;
+  static const char value_str[] = "value";
   static const char boot_complete_str[] = "record_boot_complete";
   static const char boot_reason_str[] = "record_boot_reason";
   static const char factory_reset_str[] = "record_time_since_factory_reset";
@@ -294,19 +386,26 @@
     { "log",             no_argument,       NULL,   'l' },
     { "print",           no_argument,       NULL,   'p' },
     { "record",          required_argument, NULL,   'r' },
+    { value_str,         required_argument, NULL,   0 },
     { boot_complete_str, no_argument,       NULL,   0 },
     { boot_reason_str,   no_argument,       NULL,   0 },
     { factory_reset_str, no_argument,       NULL,   0 },
     { NULL,              0,                 NULL,   0 }
   };
 
+  std::string boot_event;
+  std::string value;
   int opt = 0;
   while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
     switch (opt) {
       // This case handles long options which have no single-character mapping.
       case 0: {
         const std::string option_name = long_options[option_index].name;
-        if (option_name == boot_complete_str) {
+        if (option_name == value_str) {
+          // |optarg| is an external variable set by getopt representing
+          // the option argument.
+          value = optarg;
+        } else if (option_name == boot_complete_str) {
           RecordBootComplete();
         } else if (option_name == boot_reason_str) {
           RecordBootReason();
@@ -336,10 +435,7 @@
       case 'r': {
         // |optarg| is an external variable set by getopt representing
         // the option argument.
-        const char* event = optarg;
-
-        BootEventRecordStore boot_event_store;
-        boot_event_store.AddBootEvent(event);
+        boot_event = optarg;
         break;
       }
 
@@ -355,5 +451,9 @@
     }
   }
 
+  if (!boot_event.empty()) {
+    RecordBootEventFromCommandLine(boot_event, value);
+  }
+
   return 0;
 }
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index ca8bea2..f4756d5 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -8,23 +8,24 @@
 #
 # post-fs-data: /data is writable
 # property:init.svc.bootanim=running: The boot animation is running
-on post-fs-data && property:init.svc.bootanim=running
+# property:ro.crypto.type=block: FDE device
+on post-fs-data && property:init.svc.bootanim=running && property:ro.crypto.type=block
     exec - root root -- /system/bin/bootstat -r post_decrypt_time_elapsed
 
 # sys.logbootcomplete is a signal to enable the bootstat logging mechanism.
-# This signaling is necessary to prevent logging boot metrics after a soft
-# reboot (e.g., adb shell stop && adb shell start).  /proc/uptime is not reset
-# during a soft reboot, which leads to false boot time metrics being reported.
+# This signaling is necessary to prevent logging boot metrics after a runtime
+# restart (e.g., adb shell stop && adb shell start).  /proc/uptime is not reset
+# during a runtime restart, which leads to false boot time metrics being reported.
 #
 # The 'on boot' event occurs once per hard boot (device power on), which
-# switches the flag on. If the device performs a soft reboot, the flag is
+# switches the flag on. If the device performs a runtime restart, the flag is
 # switched off and cannot be switched on until the device hard boots again.
 
 # Enable bootstat logging on boot.
 on boot
     setprop sys.logbootcomplete 1
 
-# Disable further bootstat logging on a soft reboot. A soft reboot is
+# Disable further bootstat logging on a runtime restart. A runtime restart is
 # signaled by the zygote stopping.
 on property:init.svc.zygote=stopping
     setprop sys.logbootcomplete 0
diff --git a/bootstat/event_log_list_builder.cpp b/bootstat/event_log_list_builder.cpp
deleted file mode 100644
index 241e3d5..0000000
--- a/bootstat/event_log_list_builder.cpp
+++ /dev/null
@@ -1,107 +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 "event_log_list_builder.h"
-
-#include <cinttypes>
-#include <memory>
-#include <string>
-#include <android-base/logging.h>
-#include <log/log.h>
-
-namespace {
-
-const size_t MAX_EVENT_PAYLOAD_SIZE = 512 - 1;  // Leave room for final '\n'.
-const size_t EVENT_TYPE_SIZE = 1;  // Size in bytes of the event type marker.
-
-}  // namespace
-
-EventLogListBuilder::EventLogListBuilder()
-    : payload_count_(0),
-      payload_size_(0),
-      payload_(std::make_unique<uint8_t[]>(MAX_EVENT_PAYLOAD_SIZE)) {
-  memset(payload_.get(), 0, MAX_EVENT_PAYLOAD_SIZE);
-
-  // Set up the top-level EventLog data type.
-  AppendByte(EVENT_TYPE_LIST);
-
-  // Skip over the byte prepresenting the number of items in the list. This
-  // value is set in Release().
-  payload_size_++;
-}
-
-bool EventLogListBuilder::Append(int value) {
-  DCHECK_NE(static_cast<uint8_t*>(nullptr), payload_.get());
-
-  if (!IsSpaceAvailable(sizeof(value) + EVENT_TYPE_SIZE)) {
-    return false;
-  }
-
-  AppendByte(EVENT_TYPE_INT);
-  AppendData(&value, sizeof(value));
-
-  payload_count_++;
-  return true;
-}
-
-bool EventLogListBuilder::Append(const std::string& value) {
-  DCHECK_NE(static_cast<uint8_t*>(nullptr), payload_.get());
-
-  int len = value.length();
-  if (!IsSpaceAvailable(sizeof(len) + len)) {
-    return false;
-  }
-
-  AppendByte(EVENT_TYPE_STRING);
-  AppendData(&len, sizeof(len));
-  AppendData(value.c_str(), len);
-
-  payload_count_++;
-  return true;
-}
-
-void EventLogListBuilder::Release(std::unique_ptr<uint8_t[]>* log,
-                                  size_t* size) {
-  // Finalize the log payload.
-  payload_[1] = payload_count_;
-
-  // Return the log payload.
-  *size = payload_size_;
-  *log = std::move(payload_);
-}
-
-void EventLogListBuilder::AppendData(const void* data, size_t size) {
-  DCHECK_LT(payload_size_ + size, MAX_EVENT_PAYLOAD_SIZE);
-  memcpy(&payload_[payload_size_], data, size);
-  payload_size_ += size;
-}
-
-void EventLogListBuilder::AppendByte(uint8_t byte) {
-  DCHECK_LT(payload_size_ + sizeof(byte), MAX_EVENT_PAYLOAD_SIZE);
-  payload_[payload_size_++] = byte;
-}
-
-bool EventLogListBuilder::IsSpaceAvailable(size_t value_size) {
-  size_t space_needed = value_size + EVENT_TYPE_SIZE;
-  if (payload_size_ + space_needed > MAX_EVENT_PAYLOAD_SIZE) {
-    size_t remaining = MAX_EVENT_PAYLOAD_SIZE - payload_size_;
-    LOG(WARNING) << "Not enough space for value. remain=" <<
-        remaining << "; needed=" << space_needed;
-    return false;
-  }
-
-  return true;
-}
diff --git a/bootstat/event_log_list_builder.h b/bootstat/event_log_list_builder.h
deleted file mode 100644
index 4e29b01..0000000
--- a/bootstat/event_log_list_builder.h
+++ /dev/null
@@ -1,70 +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 EVENT_LOG_LIST_BUILDER_H_
-#define EVENT_LOG_LIST_BUILDER_H_
-
-#include <cstdint>
-#include <memory>
-
-#include <android-base/macros.h>
-
-// EventLogListBuilder provides a mechanism to build an EventLog list
-// consisting of int and string EventLog values.
-//
-// NOTE: This class does not provide the ability to append an embedded list,
-// i.e., a list containing a list.
-class EventLogListBuilder {
- public:
-  EventLogListBuilder();
-
-  // Append a single value of a specified type.
-  bool Append(int value);
-  bool Append(const std::string& value);
-
-  // Finalizes construction of the EventLog list and releases the data
-  // to the caller. Caller takes ownership of the payload. No further calls
-  // to append* may be made once the payload is acquired by the caller.
-  void Release(std::unique_ptr<uint8_t[]>* log, size_t* size);
-
- private:
-  // Appends |data| of the given |size| to the payload.
-  void AppendData(const void* data, size_t size);
-
-  // Appends a single byte to the payload.
-  void AppendByte(uint8_t byte);
-
-  // Returns true iff the remaining capacity in |payload_| is large enough to
-  // accommodate |value_size| bytes. The space required to log the event type
-  // is included in the internal calculation so must not be passed in to
-  // |value_size|.
-  bool IsSpaceAvailable(size_t value_size);
-
-  // The number of items in the EventLog list.
-  size_t payload_count_;
-
-  // The size of the data stored in |payload_|. Used to track where to insert
-  // new data.
-  size_t payload_size_;
-
-  // The payload constructed by calls to log*. The payload may only contain
-  // MAX_EVENT_PAYLOAD (512) bytes.
-  std::unique_ptr<uint8_t[]> payload_;
-
-  DISALLOW_COPY_AND_ASSIGN(EventLogListBuilder);
-};
-
- #endif  // EVENT_LOG_LIST_BUILDER_H_
diff --git a/bootstat/event_log_list_builder_test.cpp b/bootstat/event_log_list_builder_test.cpp
deleted file mode 100644
index affb4bf..0000000
--- a/bootstat/event_log_list_builder_test.cpp
+++ /dev/null
@@ -1,113 +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 "event_log_list_builder.h"
-
-#include <inttypes.h>
-#include <gtest/gtest.h>
-#include <gmock/gmock.h>
-#include <log/log.h>
-
-using testing::ElementsAreArray;
-
-TEST(EventLogListBuilder, Empty) {
-  EventLogListBuilder builder;
-
-  const uint8_t EXPECTED_LOG[] = {
-    EVENT_TYPE_LIST,
-    0,  // Number of items in the list.
-  };
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  builder.Release(&log, &size);
-  EXPECT_EQ(2U, size);
-
-  uint8_t* log_data = log.get();
-  EXPECT_THAT(std::vector<uint8_t>(log_data, log_data + size),
-              ElementsAreArray(EXPECTED_LOG));
-}
-
-TEST(EventLogListBuilder, SingleInt) {
-  EventLogListBuilder builder;
-
-  const uint8_t EXPECTED_LOG[] = {
-    EVENT_TYPE_LIST,
-    1,                // Number of items in the list.
-    EVENT_TYPE_INT,
-    42, 0, 0, 0,      // 4 byte integer value.
-  };
-
-  builder.Append(42);
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  builder.Release(&log, &size);
-  EXPECT_EQ(7U, size);
-
-  uint8_t* log_data = log.get();
-  EXPECT_THAT(std::vector<uint8_t>(log_data, log_data + size),
-              ElementsAreArray(EXPECTED_LOG));
-}
-
-TEST(EventLogListBuilder, SingleString) {
-  EventLogListBuilder builder;
-
-  const uint8_t EXPECTED_LOG[] = {
-    EVENT_TYPE_LIST,
-    1,                        // Number of items in the list.
-    EVENT_TYPE_STRING,
-    5, 0, 0, 0,               // 4 byte length of the string.
-    'D', 'r', 'o', 'i', 'd',
-  };
-
-  builder.Append("Droid");
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  builder.Release(&log, &size);
-  EXPECT_EQ(12U, size);
-
-  uint8_t* log_data = log.get();
-  EXPECT_THAT(std::vector<uint8_t>(log_data, log_data + size),
-              ElementsAreArray(EXPECTED_LOG));
-}
-
-TEST(EventLogListBuilder, IntThenString) {
-  EventLogListBuilder builder;
-
-  const uint8_t EXPECTED_LOG[] = {
-    EVENT_TYPE_LIST,
-    2,                        // Number of items in the list.
-    EVENT_TYPE_INT,
-    42, 0, 0, 0,              // 4 byte integer value.
-    EVENT_TYPE_STRING,
-    5, 0, 0, 0,               // 4 byte length of the string.
-    'D', 'r', 'o', 'i', 'd',
-  };
-
-  builder.Append(42);
-  builder.Append("Droid");
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  builder.Release(&log, &size);
-  EXPECT_EQ(17U, size);
-
-  uint8_t* log_data = log.get();
-  EXPECT_THAT(std::vector<uint8_t>(log_data, log_data + size),
-              ElementsAreArray(EXPECTED_LOG));
-}
diff --git a/bootstat/histogram_logger.cpp b/bootstat/histogram_logger.cpp
deleted file mode 100644
index e3aad28..0000000
--- a/bootstat/histogram_logger.cpp
+++ /dev/null
@@ -1,41 +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 "histogram_logger.h"
-
-#include <cstdlib>
-#include <memory>
-#include <android-base/logging.h>
-#include <log/log.h>
-#include "event_log_list_builder.h"
-
-namespace bootstat {
-
-void LogHistogram(const std::string& event, int32_t data) {
-  LOG(INFO) << "Logging histogram: " << event << " " << data;
-
-  EventLogListBuilder log_builder;
-  log_builder.Append(event);
-  log_builder.Append(data);
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  log_builder.Release(&log, &size);
-
-  android_bWriteLog(HISTOGRAM_LOG_TAG, log.get(), size);
-}
-
-}  // namespace bootstat
\ No newline at end of file
diff --git a/bootstat/histogram_logger.h b/bootstat/histogram_logger.h
deleted file mode 100644
index 60c7776..0000000
--- a/bootstat/histogram_logger.h
+++ /dev/null
@@ -1,26 +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 <cstdint>
-#include <string>
-
-namespace bootstat {
-
-// Builds an EventLog buffer named |event| containing |data| and writes
-// the log into the Tron histogram logs.
-void LogHistogram(const std::string& event, int32_t data);
-
-}  // namespace bootstat
\ No newline at end of file
diff --git a/cpio/mkbootfs.c b/cpio/mkbootfs.c
index 0e35323..e52762e 100644
--- a/cpio/mkbootfs.c
+++ b/cpio/mkbootfs.c
@@ -51,6 +51,8 @@
 #define CANNED_LINE_LENGTH  (1024)
 #endif
 
+#define TRAILER "TRAILER!!!"
+
 static int verbose = 0;
 static int total_size = 0;
 
@@ -80,8 +82,8 @@
     } else {
         // Use the compiled-in fs_config() function.
         unsigned st_mode = s->st_mode;
-        fs_config(path, S_ISDIR(s->st_mode), target_out_path,
-                       &s->st_uid, &s->st_gid, &st_mode, &capabilities);
+        int is_dir = S_ISDIR(s->st_mode) || strcmp(path, TRAILER) == 0;
+        fs_config(path, is_dir, target_out_path, &s->st_uid, &s->st_gid, &st_mode, &capabilities);
         s->st_mode = (typeof(s->st_mode)) st_mode;
     }
 }
@@ -140,7 +142,7 @@
 {
     struct stat s;
     memset(&s, 0, sizeof(s));
-    _eject(&s, "TRAILER!!!", 10, 0, 0);
+    _eject(&s, TRAILER, 10, 0, 0);
 
     while(total_size & 0xff) {
         total_size++;
@@ -299,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;
@@ -318,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/crash_reporter/.project_alias b/crash_reporter/.project_alias
deleted file mode 100644
index 0bc3798..0000000
--- a/crash_reporter/.project_alias
+++ /dev/null
@@ -1 +0,0 @@
-crash
diff --git a/crash_reporter/99-crash-reporter.rules b/crash_reporter/99-crash-reporter.rules
deleted file mode 100644
index aea5b1c..0000000
--- a/crash_reporter/99-crash-reporter.rules
+++ /dev/null
@@ -1,6 +0,0 @@
-ACTION=="change", SUBSYSTEM=="drm", KERNEL=="card0", ENV{ERROR}=="1", RUN+="/sbin/crash_reporter --udev=KERNEL=card0:SUBSYSTEM=drm:ACTION=change"
-# For detecting cypress trackpad issue. Passing into crash_reporter SUBSYSTEM=i2c-cyapa since crash_reporter does not handle DRIVER string.
-ACTION=="change", SUBSYSTEM=="i2c", DRIVER=="cyapa", ENV{ERROR}=="1", RUN+="/sbin/crash_reporter --udev=SUBSYSTEM=i2c-cyapa:ACTION=change"
-# For detecting Atmel trackpad/touchscreen issue. Passing into crash_reporter SUBSYSTEM=i2c-atmel_mxt_ts since crash_reporter does not handle DRIVER string.
-ACTION=="change", SUBSYSTEM=="i2c", DRIVER=="atmel_mxt_ts", ENV{ERROR}=="1", RUN+="/sbin/crash_reporter --udev=SUBSYSTEM=i2c-atmel_mxt_ts:ACTION=change"
-ACTION=="add", SUBSYSTEM=="devcoredump", RUN+="/sbin/crash_reporter --udev=SUBSYSTEM=devcoredump:ACTION=add:KERNEL_NUMBER=%n"
diff --git a/crash_reporter/Android.mk b/crash_reporter/Android.mk
deleted file mode 100644
index ce9dc73..0000000
--- a/crash_reporter/Android.mk
+++ /dev/null
@@ -1,147 +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)
-
-crash_reporter_cpp_extension := .cc
-
-crash_reporter_src := crash_collector.cc \
-    kernel_collector.cc \
-    kernel_warning_collector.cc \
-    unclean_shutdown_collector.cc \
-    user_collector.cc
-
-crash_reporter_includes := external/gtest/include
-
-crash_reporter_test_src := crash_collector_test.cc \
-    crash_reporter_logs_test.cc \
-    kernel_collector_test.cc \
-    testrunner.cc \
-    unclean_shutdown_collector_test.cc \
-    user_collector_test.cc
-
-warn_collector_src := warn_collector.l
-
-# Crash reporter static library.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcrash
-LOCAL_CPP_EXTENSION := $(crash_reporter_cpp_extension)
-LOCAL_C_INCLUDES := $(crash_reporter_includes)
-LOCAL_SHARED_LIBRARIES := libchrome \
-    libbinder \
-    libbrillo \
-    libcutils \
-    libmetrics \
-    libpcrecpp
-LOCAL_STATIC_LIBRARIES := libmetricscollectorservice
-LOCAL_SRC_FILES := $(crash_reporter_src)
-include $(BUILD_STATIC_LIBRARY)
-
-# Crash reporter client.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := crash_reporter
-LOCAL_CPP_EXTENSION := $(crash_reporter_cpp_extension)
-LOCAL_C_INCLUDES := $(crash_reporter_includes)
-LOCAL_REQUIRED_MODULES := core2md \
-    crash_reporter_logs.conf \
-    crash_sender \
-    crash_server
-LOCAL_INIT_RC := crash_reporter.rc
-LOCAL_SHARED_LIBRARIES := libchrome \
-    libbinder \
-    libbrillo \
-    libcutils \
-    libmetrics \
-    libpcrecpp \
-    libutils
-LOCAL_SRC_FILES := crash_reporter.cc
-LOCAL_STATIC_LIBRARIES := libcrash \
-    libmetricscollectorservice
-include $(BUILD_EXECUTABLE)
-
-# Crash sender script.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := crash_sender
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_PATH := $(TARGET_OUT_EXECUTABLES)
-LOCAL_REQUIRED_MODULES := curl grep periodic_scheduler
-LOCAL_SRC_FILES := crash_sender
-include $(BUILD_PREBUILT)
-
-# Warn collector client.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := warn_collector
-LOCAL_CPP_EXTENSION := $(crash_reporter_cpp_extension)
-LOCAL_SHARED_LIBRARIES := libmetrics
-LOCAL_SRC_FILES := $(warn_collector_src)
-include $(BUILD_EXECUTABLE)
-
-# /etc/os-release.d/crash_server configuration file.
-# ========================================================
-ifdef OSRELEASED_DIRECTORY
-include $(CLEAR_VARS)
-LOCAL_MODULE := crash_server
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)
-include $(BUILD_SYSTEM)/base_rules.mk
-
-# Optionally populate the BRILLO_CRASH_SERVER variable from a product
-# configuration file: brillo/crash_server.
-LOADED_BRILLO_CRASH_SERVER := $(call cfgtree-get-if-exists,brillo/crash_server)
-
-# If the crash server isn't set, use a blank value.  crash_sender
-# will log it as a configuration error.
-$(LOCAL_BUILT_MODULE): BRILLO_CRASH_SERVER ?= "$(LOADED_BRILLO_CRASH_SERVER)"
-$(LOCAL_BUILT_MODULE):
-	$(hide)mkdir -p $(dir $@)
-	echo $(BRILLO_CRASH_SERVER) > $@
-endif
-
-# Crash reporter logs conf file.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := crash_reporter_logs.conf
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/system/etc
-LOCAL_SRC_FILES := crash_reporter_logs.conf
-include $(BUILD_PREBUILT)
-
-# Periodic Scheduler.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := periodic_scheduler
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_PATH := $(TARGET_OUT_EXECUTABLES)
-LOCAL_SRC_FILES := periodic_scheduler
-include $(BUILD_PREBUILT)
-
-# Crash reporter tests.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := crash_reporter_tests
-LOCAL_CPP_EXTENSION := $(crash_reporter_cpp_extension)
-ifdef BRILLO
-LOCAL_MODULE_TAGS := eng
-endif
-LOCAL_SHARED_LIBRARIES := libchrome \
-    libbrillo \
-    libcutils \
-    libpcrecpp
-LOCAL_SRC_FILES := $(crash_reporter_test_src)
-LOCAL_STATIC_LIBRARIES := libcrash libgmock
-include $(BUILD_NATIVE_TEST)
diff --git a/crash_reporter/OWNERS b/crash_reporter/OWNERS
deleted file mode 100644
index 96ea5b2..0000000
--- a/crash_reporter/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-set noparent
-vapier@chromium.org
diff --git a/crash_reporter/README.md b/crash_reporter/README.md
deleted file mode 100644
index 9ac0a86..0000000
--- a/crash_reporter/README.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# crash_reporter
-
-`crash_reporter` is a deamon running on the device that saves the call stack of
-crashing programs. It makes use of the
-[Breakpad](https://chromium.googlesource.com/breakpad/breakpad/) library.
-
-During a build, Breakpad symbol files are generated for all binaries.  They are
-packaged into a zip file when running `m dist`, so that a developer can upload
-them to the crash server.
-
-On a device, if the user has opted in to metrics and crash reporting, a
-Breakpad minidump is generated when an executable crashes, which is then
-uploaded to the crash server.
-
-On the crash server, it compares the minidump's signature to the symbol files
-that the developer has uploaded, and extracts and symbolizes the stack trace
-from the minidump.
-
-## SELinux policies
-
-In order to correctly generate a minidump, `crash_reporter` needs to be given
-the proper SELinux permissions for accessing the domain of the crashing
-executable.  By default, `crash_reporter` has only been given access to a select
-number of system domains, such as `metricsd`, `weave`, and `update_engine`.  If
-a developer wants their executable's crashes to be caught by `crash_reporter`,
-they will have to set their SELinux policies in their .te file to allow
-`crash_reporter` access to their domain.  This can be done through a simple
-[macro](https://android.googlesource.com/device/generic/brillo/+/master/sepolicy/te_macros):
-
-    allow_crash_reporter(domain_name)
-
-Replace *domain_name* with whatever domain is assigned to the executable in
-the `file_contexts` file.
-
-## Configuration
-
-`crash_reporter` has a few different configuration options that have to be set.
-
-- Crashes are only handled and uploaded if analytics reporting is enabled,
-  either via the weave call to set `_metrics.enableAnalyticsReporting` or by
-  manually creating the file `/data/misc/metrics/enabled` (for testing only).
-- The `BRILLO_CRASH_SERVER` make variable should be set in the `product.mk`
-  file to the URL of the crash server.  For Brillo builds, it is set
-  automatically through the product configuration.  Setting this variable will
-  populate the `/etc/os-release.d/crash_server` file on the device, which is
-  read by `crash_sender`.
-- The `BRILLO_PRODUCT_ID` make variable should be set in the `product.mk` file
-  to the product's ID.  For Brillo builds, it is set automatically through the
-  product configuration.  Setting this variable will populate the
-  `/etc/os-release.d/product_id`, which is read by `crash_sender`.
-
-## Uploading crash reports in *eng* builds
-
-By default, crash reports are only uploaded to the server for production
-*user* and *userdebug* images.  In *eng* builds, with crash reporting enabled
-the device will generate minidumps for any crashing executables but will not
-send them to the crash server.  If a developer does want to force an upload,
-they can do so by issuing the command `SECONDS_SEND_SPREAD=5 FORCE_OFFICIAL=1
-crash_sender` from an ADB shell.  This will send the report to the server, with
-the *image_type* field set to *force-official* so that these reports can be
-differentiated from normal reports.
diff --git a/crash_reporter/TEST_WARNING b/crash_reporter/TEST_WARNING
deleted file mode 100644
index 64ad2e9..0000000
--- a/crash_reporter/TEST_WARNING
+++ /dev/null
@@ -1,31 +0,0 @@
-Apr 31 25:25:25 localhost kernel: [117959.226729]  [<ffffffff810e16bf>] do_vfs_ioctl+0x469/0x4b3
-Apr 31 25:25:25 localhost kernel: [117959.226738]  [<ffffffff810d3117>] ? fsnotify_access+0x58/0x60
-Apr 31 25:25:25 localhost kernel: [117959.226747]  [<ffffffff810d3791>] ? vfs_read+0xad/0xd7
-Apr 31 25:25:25 localhost kernel: [117959.226756]  [<ffffffff810e175f>] sys_ioctl+0x56/0x7b
-Apr 31 25:25:25 localhost kernel: [117959.226765]  [<ffffffff810d37fe>] ? sys_read+0x43/0x73
-Apr 31 25:25:25 localhost kernel: [117959.226774]  [<ffffffff8146b7d2>] system_call_fastpath+0x16/0x1b
-Apr 31 25:25:25 localhost kernel: [117959.226782] ---[ end trace f16822cad7406cec ]---
-Apr 31 25:25:25 localhost kernel: [117959.231085] ------------[ cut here ]------------
-Apr 31 25:25:25 localhost kernel: [117959.231100] WARNING: at /mnt/host/source/src/third_party/kernel/files/drivers/gpu/drm/i915/intel_dp.c:351 intel_dp_check_edp+0x6b/0xb9()
-Apr 31 25:25:25 localhost kernel: [117959.231113] Hardware name: Link
-Apr 31 25:25:25 localhost kernel: [117959.231117] eDP powered off while attempting aux channel communication.
-Apr 31 25:25:25 localhost kernel: [117959.231240] Pid: 10508, comm: X Tainted: G        WC   3.4.0 #1
-Apr 31 25:25:25 localhost kernel: [117959.231247] Call Trace:
-Apr 31 25:25:25 localhost kernel: [117959.231393]  [<ffffffff810d3117>] ? fsnotify_access+0x58/0x60
-Apr 31 25:25:25 localhost kernel: [117959.231402]  [<ffffffff810d3791>] ? vfs_read+0xad/0xd7
-Apr 31 25:25:25 localhost kernel: [117959.231411]  [<ffffffff810e175f>] sys_ioctl+0x56/0x7b
-Apr 31 25:25:25 localhost kernel: [117959.231420]  [<ffffffff810d37fe>] ? sys_read+0x43/0x73
-Apr 31 25:25:25 localhost kernel: [117959.231431]  [<ffffffff8146b7d2>] system_call_fastpath+0x16/0x1b
-Apr 31 25:25:25 localhost kernel: [117959.231439] ---[ end trace f16822cad7406ced ]---
-Apr 31 25:25:25 localhost kernel: [117959.231450] ------------[ cut here ]------------
-Apr 31 25:25:25 localhost kernel: [117959.231458] BARNING: at /mnt/host/source/src/third_party/kernel/files/drivers/gpu/drm/i915/intel_dp.c:351 intel_dp_check_edp+0x6b/0xb9()
-Apr 31 25:25:25 localhost kernel: [117959.231458] ("BARNING" above is intentional)
-Apr 31 25:25:25 localhost kernel: [117959.231471] Hardware name: Link
-Apr 31 25:25:25 localhost kernel: [117959.231475] eDP powered off while attempting aux channel communication.
-Apr 31 25:25:25 localhost kernel: [117959.231482] Modules linked in: nls_iso8859_1 nls_cp437 vfat fat rfcomm i2c_dev ath9k_btcoex snd_hda_codec_hdmi snd_hda_codec_ca0132 mac80211 snd_hda_intel ath9k_common_btcoex snd_hda_codec ath9k_hw_btcoex aesni_intel cryptd snd_hwdep ath snd_pcm aes_x86_64 isl29018(C) memconsole snd_timer snd_page_alloc industrialio(C) cfg80211 rtc_cmos nm10_gpio zram(C) zsmalloc(C) lzo_decompress lzo_compress fuse nf_conntrack_ipv6 nf_defrag_ipv6 ip6table_filter ip6_tables xt_mark option usb_wwan cdc_ether usbnet ath3k btusb bluetooth uvcvideo videobuf2_core videodev videobuf2_vmalloc videobuf2_memops joydev
-Apr 31 25:25:25 localhost kernel: [117959.231588] Pid: 10508, comm: X Tainted: G        WC   3.4.0 #1
-Apr 31 25:25:25 localhost kernel: [117959.231595] Call Trace:
-Apr 31 25:25:25 localhost kernel: [117959.231601]  [<ffffffff8102a931>] warn_slowpath_common+0x83/0x9c
-Apr 31 25:25:25 localhost kernel: [117959.231610]  [<ffffffff8102a9ed>] warn_slowpath_fmt+0x46/0x48
-Apr 31 25:25:25 localhost kernel: [117959.231620]  [<ffffffff812af495>] intel_dp_check_edp+0x6b/0xb9
-Apr 31 25:25:25 localhost kernel: [117959.231629]  [<ffffffff8102a9ed>] ? warn_slowpath_fmt+
diff --git a/crash_reporter/crash_collector.cc b/crash_reporter/crash_collector.cc
deleted file mode 100644
index b3fdcb4..0000000
--- a/crash_reporter/crash_collector.cc
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "crash_collector.h"
-
-#include <dirent.h>
-#include <fcntl.h>  // For file creation modes.
-#include <inttypes.h>
-#include <linux/limits.h>  // PATH_MAX
-#include <pwd.h>  // For struct passwd.
-#include <sys/types.h>  // for mode_t.
-#include <sys/wait.h>  // For waitpid.
-#include <unistd.h>  // For execv and fork.
-
-#include <set>
-#include <utility>
-#include <vector>
-
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/posix/eintr_wrapper.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/key_value_store.h>
-#include <brillo/process.h>
-
-namespace {
-
-const char kCollectChromeFile[] =
-    "/mnt/stateful_partition/etc/collect_chrome_crashes";
-const char kCrashTestInProgressPath[] =
-    "/data/misc/crash_reporter/tmp/crash-test-in-progress";
-const char kDefaultLogConfig[] = "/etc/crash_reporter_logs.conf";
-const char kDefaultUserName[] = "chronos";
-const char kLeaveCoreFile[] = "/data/misc/crash_reporter/.leave_core";
-const char kShellPath[] = "/system/bin/sh";
-const char kSystemCrashPath[] = "/data/misc/crash_reporter/crash";
-const char kUploadVarPrefix[] = "upload_var_";
-const char kUploadFilePrefix[] = "upload_file_";
-
-// Normally this path is not used.  Unfortunately, there are a few edge cases
-// where we need this.  Any process that runs as kDefaultUserName that crashes
-// is consider a "user crash".  That includes the initial Chrome browser that
-// runs the login screen.  If that blows up, there is no logged in user yet,
-// so there is no per-user dir for us to stash things in.  Instead we fallback
-// to this path as it is at least encrypted on a per-system basis.
-//
-// This also comes up when running autotests.  The GUI is sitting at the login
-// screen while tests are sshing in, changing users, and triggering crashes as
-// the user (purposefully).
-const char kFallbackUserCrashPath[] = "/home/chronos/crash";
-
-// Directory mode of the user crash spool directory.
-const mode_t kUserCrashPathMode = 0755;
-
-// Directory mode of the system crash spool directory.
-const mode_t kSystemCrashPathMode = 01755;
-
-const uid_t kRootOwner = 0;
-const uid_t kRootGroup = 0;
-
-}  // namespace
-
-// Maximum crash reports per crash spool directory.  Note that this is
-// a separate maximum from the maximum rate at which we upload these
-// diagnostics.  The higher this rate is, the more space we allow for
-// core files, minidumps, and kcrash logs, and equivalently the more
-// processor and I/O bandwidth we dedicate to handling these crashes when
-// many occur at once.  Also note that if core files are configured to
-// be left on the file system, we stop adding crashes when either the
-// number of core files or minidumps reaches this number.
-const int CrashCollector::kMaxCrashDirectorySize = 32;
-
-using base::FilePath;
-using base::StringPrintf;
-
-CrashCollector::CrashCollector()
-    : log_config_path_(kDefaultLogConfig) {
-}
-
-CrashCollector::~CrashCollector() {
-}
-
-void CrashCollector::Initialize(
-    CrashCollector::CountCrashFunction count_crash_function,
-    CrashCollector::IsFeedbackAllowedFunction is_feedback_allowed_function) {
-  CHECK(count_crash_function);
-  CHECK(is_feedback_allowed_function);
-
-  count_crash_function_ = count_crash_function;
-  is_feedback_allowed_function_ = is_feedback_allowed_function;
-}
-
-int CrashCollector::WriteNewFile(const FilePath &filename,
-                                 const char *data,
-                                 int size) {
-  int fd = HANDLE_EINTR(open(filename.value().c_str(),
-                             O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0666));
-  if (fd < 0) {
-    return -1;
-  }
-
-  int rv = base::WriteFileDescriptor(fd, data, size) ? size : -1;
-  IGNORE_EINTR(close(fd));
-  return rv;
-}
-
-std::string CrashCollector::Sanitize(const std::string &name) {
-  // Make sure the sanitized name does not include any periods.
-  // The logic in crash_sender relies on this.
-  std::string result = name;
-  for (size_t i = 0; i < name.size(); ++i) {
-    if (!isalnum(result[i]) && result[i] != '_')
-      result[i] = '_';
-  }
-  return result;
-}
-
-std::string CrashCollector::FormatDumpBasename(const std::string &exec_name,
-                                               time_t timestamp,
-                                               pid_t pid) {
-  struct tm tm;
-  localtime_r(&timestamp, &tm);
-  std::string sanitized_exec_name = Sanitize(exec_name);
-  return StringPrintf("%s.%04d%02d%02d.%02d%02d%02d.%d",
-                      sanitized_exec_name.c_str(),
-                      tm.tm_year + 1900,
-                      tm.tm_mon + 1,
-                      tm.tm_mday,
-                      tm.tm_hour,
-                      tm.tm_min,
-                      tm.tm_sec,
-                      pid);
-}
-
-FilePath CrashCollector::GetCrashPath(const FilePath &crash_directory,
-                                      const std::string &basename,
-                                      const std::string &extension) {
-  return crash_directory.Append(StringPrintf("%s.%s",
-                                             basename.c_str(),
-                                             extension.c_str()));
-}
-
-FilePath CrashCollector::GetCrashDirectoryInfo(
-    mode_t *mode,
-    uid_t *directory_owner,
-    gid_t *directory_group) {
-  *mode = kSystemCrashPathMode;
-  *directory_owner = kRootOwner;
-  *directory_group = kRootGroup;
-  return FilePath(kSystemCrashPath);
-}
-
-bool CrashCollector::GetUserInfoFromName(const std::string &name,
-                                         uid_t *uid,
-                                         gid_t *gid) {
-  char storage[256];
-  struct passwd passwd_storage;
-  struct passwd *passwd_result = nullptr;
-
-  if (getpwnam_r(name.c_str(), &passwd_storage, storage, sizeof(storage),
-                 &passwd_result) != 0 || passwd_result == nullptr) {
-    LOG(ERROR) << "Cannot find user named " << name;
-    return false;
-  }
-
-  *uid = passwd_result->pw_uid;
-  *gid = passwd_result->pw_gid;
-  return true;
-}
-
-bool CrashCollector::GetCreatedCrashDirectoryByEuid(uid_t euid,
-                                                    FilePath *crash_directory,
-                                                    bool *out_of_capacity) {
-  if (out_of_capacity) *out_of_capacity = false;
-
-  // For testing.
-  if (!forced_crash_directory_.empty()) {
-    *crash_directory = forced_crash_directory_;
-    return true;
-  }
-
-  mode_t directory_mode;
-  uid_t directory_owner;
-  gid_t directory_group;
-  *crash_directory =
-      GetCrashDirectoryInfo(&directory_mode,
-                            &directory_owner,
-                            &directory_group);
-
-  if (!base::PathExists(*crash_directory)) {
-    // Create the spool directory with the appropriate mode (regardless of
-    // umask) and ownership.
-    mode_t old_mask = umask(0);
-    if (mkdir(crash_directory->value().c_str(), directory_mode) < 0 ||
-        chown(crash_directory->value().c_str(),
-              directory_owner,
-              directory_group) < 0) {
-      LOG(ERROR) << "Unable to create appropriate crash directory";
-      return false;
-    }
-    umask(old_mask);
-  }
-
-  if (!base::PathExists(*crash_directory)) {
-    LOG(ERROR) << "Unable to create crash directory "
-               << crash_directory->value().c_str();
-    return false;
-  }
-
-  if (!CheckHasCapacity(*crash_directory)) {
-    if (out_of_capacity) *out_of_capacity = true;
-    LOG(ERROR) << "Directory " << crash_directory->value()
-               << " is out of capacity.";
-    return false;
-  }
-
-  return true;
-}
-
-FilePath CrashCollector::GetProcessPath(pid_t pid) {
-  return FilePath(StringPrintf("/proc/%d", pid));
-}
-
-bool CrashCollector::GetSymlinkTarget(const FilePath &symlink,
-                                      FilePath *target) {
-  ssize_t max_size = 64;
-  std::vector<char> buffer;
-
-  while (true) {
-    buffer.resize(max_size + 1);
-    ssize_t size = readlink(symlink.value().c_str(), buffer.data(), max_size);
-    if (size < 0) {
-      int saved_errno = errno;
-      LOG(ERROR) << "Readlink failed on " << symlink.value() << " with "
-                 << saved_errno;
-      return false;
-    }
-
-    buffer[size] = 0;
-    if (size == max_size) {
-      max_size *= 2;
-      if (max_size > PATH_MAX) {
-        return false;
-      }
-      continue;
-    }
-    break;
-  }
-
-  *target = FilePath(buffer.data());
-  return true;
-}
-
-bool CrashCollector::GetExecutableBaseNameFromPid(pid_t pid,
-                                                 std::string *base_name) {
-  FilePath target;
-  FilePath process_path = GetProcessPath(pid);
-  FilePath exe_path = process_path.Append("exe");
-  if (!GetSymlinkTarget(exe_path, &target)) {
-    LOG(INFO) << "GetSymlinkTarget failed - Path " << process_path.value()
-              << " DirectoryExists: "
-              << base::DirectoryExists(process_path);
-    // Try to further diagnose exe readlink failure cause.
-    struct stat buf;
-    int stat_result = stat(exe_path.value().c_str(), &buf);
-    int saved_errno = errno;
-    if (stat_result < 0) {
-      LOG(INFO) << "stat " << exe_path.value() << " failed: " << stat_result
-                << " " << saved_errno;
-    } else {
-      LOG(INFO) << "stat " << exe_path.value() << " succeeded: st_mode="
-                << buf.st_mode;
-    }
-    return false;
-  }
-  *base_name = target.BaseName().value();
-  return true;
-}
-
-// Return true if the given crash directory has not already reached
-// maximum capacity.
-bool CrashCollector::CheckHasCapacity(const FilePath &crash_directory) {
-  DIR* dir = opendir(crash_directory.value().c_str());
-  if (!dir) {
-    LOG(WARNING) << "Unable to open crash directory "
-                 << crash_directory.value();
-    return false;
-  }
-  struct dirent ent_buf;
-  struct dirent* ent;
-  bool full = false;
-  std::set<std::string> basenames;
-  while (readdir_r(dir, &ent_buf, &ent) == 0 && ent) {
-    if ((strcmp(ent->d_name, ".") == 0) ||
-        (strcmp(ent->d_name, "..") == 0))
-      continue;
-
-    std::string filename(ent->d_name);
-    size_t last_dot = filename.rfind(".");
-    std::string basename;
-    // If there is a valid looking extension, use the base part of the
-    // name.  If the only dot is the first byte (aka a dot file), treat
-    // it as unique to avoid allowing a directory full of dot files
-    // from accumulating.
-    if (last_dot != std::string::npos && last_dot != 0)
-      basename = filename.substr(0, last_dot);
-    else
-      basename = filename;
-    basenames.insert(basename);
-
-    if (basenames.size() >= static_cast<size_t>(kMaxCrashDirectorySize)) {
-      LOG(WARNING) << "Crash directory " << crash_directory.value()
-                   << " already full with " << kMaxCrashDirectorySize
-                   << " pending reports";
-      full = true;
-      break;
-    }
-  }
-  closedir(dir);
-  return !full;
-}
-
-bool CrashCollector::GetLogContents(const FilePath &config_path,
-                                    const std::string &exec_name,
-                                    const FilePath &output_file) {
-  brillo::KeyValueStore store;
-  if (!store.Load(config_path)) {
-    LOG(INFO) << "Unable to read log configuration file "
-              << config_path.value();
-    return false;
-  }
-
-  std::string command;
-  if (!store.GetString(exec_name, &command))
-    return false;
-
-  brillo::ProcessImpl diag_process;
-  diag_process.AddArg(kShellPath);
-  diag_process.AddStringOption("-c", command);
-  diag_process.RedirectOutput(output_file.value());
-
-  const int result = diag_process.Run();
-  if (result != 0) {
-    LOG(INFO) << "Log command \"" << command << "\" exited with " << result;
-    return false;
-  }
-  return true;
-}
-
-void CrashCollector::AddCrashMetaData(const std::string &key,
-                                      const std::string &value) {
-  extra_metadata_.append(StringPrintf("%s=%s\n", key.c_str(), value.c_str()));
-}
-
-void CrashCollector::AddCrashMetaUploadFile(const std::string &key,
-                                            const std::string &path) {
-  if (!path.empty())
-    AddCrashMetaData(kUploadFilePrefix + key, path);
-}
-
-void CrashCollector::AddCrashMetaUploadData(const std::string &key,
-                                            const std::string &value) {
-  if (!value.empty())
-    AddCrashMetaData(kUploadVarPrefix + key, value);
-}
-
-void CrashCollector::WriteCrashMetaData(const FilePath &meta_path,
-                                        const std::string &exec_name,
-                                        const std::string &payload_path) {
-  int64_t payload_size = -1;
-  base::GetFileSize(FilePath(payload_path), &payload_size);
-  std::string meta_data = StringPrintf("%sexec_name=%s\n"
-                                       "payload=%s\n"
-                                       "payload_size=%" PRId64 "\n"
-                                       "done=1\n",
-                                       extra_metadata_.c_str(),
-                                       exec_name.c_str(),
-                                       payload_path.c_str(),
-                                       payload_size);
-  // We must use WriteNewFile instead of base::WriteFile as we
-  // do not want to write with root access to a symlink that an attacker
-  // might have created.
-  if (WriteNewFile(meta_path, meta_data.c_str(), meta_data.size()) < 0) {
-    LOG(ERROR) << "Unable to write " << meta_path.value();
-  }
-}
-
-bool CrashCollector::IsCrashTestInProgress() {
-  return base::PathExists(FilePath(kCrashTestInProgressPath));
-}
-
-bool CrashCollector::IsDeveloperImage() {
-  // If we're testing crash reporter itself, we don't want to special-case
-  // for developer images.
-  if (IsCrashTestInProgress())
-    return false;
-  return base::PathExists(FilePath(kLeaveCoreFile));
-}
diff --git a/crash_reporter/crash_collector.h b/crash_reporter/crash_collector.h
deleted file mode 100644
index 24cbfb3..0000000
--- a/crash_reporter/crash_collector.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef CRASH_REPORTER_CRASH_COLLECTOR_H_
-#define CRASH_REPORTER_CRASH_COLLECTOR_H_
-
-#include <sys/stat.h>
-
-#include <map>
-#include <string>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-// User crash collector.
-class CrashCollector {
- public:
-  typedef void (*CountCrashFunction)();
-  typedef bool (*IsFeedbackAllowedFunction)();
-
-  CrashCollector();
-
-  virtual ~CrashCollector();
-
-  // Initialize the crash collector for detection of crashes, given a
-  // crash counting function, and metrics collection enabled oracle.
-  void Initialize(CountCrashFunction count_crash,
-                  IsFeedbackAllowedFunction is_metrics_allowed);
-
- protected:
-  friend class CrashCollectorTest;
-  FRIEND_TEST(ChromeCollectorTest, HandleCrash);
-  FRIEND_TEST(CrashCollectorTest, CheckHasCapacityCorrectBasename);
-  FRIEND_TEST(CrashCollectorTest, CheckHasCapacityStrangeNames);
-  FRIEND_TEST(CrashCollectorTest, CheckHasCapacityUsual);
-  FRIEND_TEST(CrashCollectorTest, GetCrashDirectoryInfo);
-  FRIEND_TEST(CrashCollectorTest, GetCrashPath);
-  FRIEND_TEST(CrashCollectorTest, GetLogContents);
-  FRIEND_TEST(CrashCollectorTest, ForkExecAndPipe);
-  FRIEND_TEST(CrashCollectorTest, FormatDumpBasename);
-  FRIEND_TEST(CrashCollectorTest, Initialize);
-  FRIEND_TEST(CrashCollectorTest, MetaData);
-  FRIEND_TEST(CrashCollectorTest, Sanitize);
-  FRIEND_TEST(CrashCollectorTest, WriteNewFile);
-  FRIEND_TEST(ForkExecAndPipeTest, Basic);
-  FRIEND_TEST(ForkExecAndPipeTest, NonZeroReturnValue);
-  FRIEND_TEST(ForkExecAndPipeTest, BadOutputFile);
-  FRIEND_TEST(ForkExecAndPipeTest, ExistingOutputFile);
-  FRIEND_TEST(ForkExecAndPipeTest, BadExecutable);
-  FRIEND_TEST(ForkExecAndPipeTest, StderrCaptured);
-  FRIEND_TEST(ForkExecAndPipeTest, NULLParam);
-  FRIEND_TEST(ForkExecAndPipeTest, NoParams);
-  FRIEND_TEST(ForkExecAndPipeTest, SegFaultHandling);
-
-  // Set maximum enqueued crashes in a crash directory.
-  static const int kMaxCrashDirectorySize;
-
-  // Writes |data| of |size| to |filename|, which must be a new file.
-  // If the file already exists or writing fails, return a negative value.
-  // Otherwise returns the number of bytes written.
-  int WriteNewFile(const base::FilePath &filename, const char *data, int size);
-
-  // Return a filename that has only [a-z0-1_] characters by mapping
-  // all others into '_'.
-  std::string Sanitize(const std::string &name);
-
-  // For testing, set the directory always returned by
-  // GetCreatedCrashDirectoryByEuid.
-  void ForceCrashDirectory(const base::FilePath &forced_directory) {
-    forced_crash_directory_ = forced_directory;
-  }
-
-  base::FilePath GetCrashDirectoryInfo(mode_t *mode,
-                                       uid_t *directory_owner,
-                                       gid_t *directory_group);
-  bool GetUserInfoFromName(const std::string &name,
-                           uid_t *uid,
-                           gid_t *gid);
-
-  // Determines the crash directory for given euid, and creates the
-  // directory if necessary with appropriate permissions.  If
-  // |out_of_capacity| is not nullptr, it is set to indicate if the call
-  // failed due to not having capacity in the crash directory. Returns
-  // true whether or not directory needed to be created, false on any
-  // failure.  If the crash directory is at capacity, returns false.
-  bool GetCreatedCrashDirectoryByEuid(uid_t euid,
-                                      base::FilePath *crash_file_path,
-                                      bool *out_of_capacity);
-
-  // Format crash name based on components.
-  std::string FormatDumpBasename(const std::string &exec_name,
-                                 time_t timestamp,
-                                 pid_t pid);
-
-  // Create a file path to a file in |crash_directory| with the given
-  // |basename| and |extension|.
-  base::FilePath GetCrashPath(const base::FilePath &crash_directory,
-                              const std::string &basename,
-                              const std::string &extension);
-
-  base::FilePath GetProcessPath(pid_t pid);
-  bool GetSymlinkTarget(const base::FilePath &symlink,
-                        base::FilePath *target);
-  bool GetExecutableBaseNameFromPid(pid_t pid,
-                                    std::string *base_name);
-
-  // Check given crash directory still has remaining capacity for another
-  // crash.
-  bool CheckHasCapacity(const base::FilePath &crash_directory);
-
-  // Write a log applicable to |exec_name| to |output_file| based on the
-  // log configuration file at |config_path|.
-  bool GetLogContents(const base::FilePath &config_path,
-                      const std::string &exec_name,
-                      const base::FilePath &output_file);
-
-  // Add non-standard meta data to the crash metadata file.  Call
-  // before calling WriteCrashMetaData.  Key must not contain "=" or
-  // "\n" characters.  Value must not contain "\n" characters.
-  void AddCrashMetaData(const std::string &key, const std::string &value);
-
-  // Add a file to be uploaded to the crash reporter server. The file must
-  // persist until the crash report is sent; ideally it should live in the same
-  // place as the .meta file, so it can be cleaned up automatically.
-  void AddCrashMetaUploadFile(const std::string &key, const std::string &path);
-
-  // Add non-standard meta data to the crash metadata file.
-  // Data added though this call will be uploaded to the crash reporter server,
-  // appearing as a form field.
-  void AddCrashMetaUploadData(const std::string &key, const std::string &value);
-
-  // Write a file of metadata about crash.
-  void WriteCrashMetaData(const base::FilePath &meta_path,
-                          const std::string &exec_name,
-                          const std::string &payload_path);
-
-  // Returns true if the a crash test is currently running.
-  bool IsCrashTestInProgress();
-  // Returns true if we should consider ourselves to be running on a
-  // developer image.
-  bool IsDeveloperImage();
-
-  CountCrashFunction count_crash_function_;
-  IsFeedbackAllowedFunction is_feedback_allowed_function_;
-  std::string extra_metadata_;
-  base::FilePath forced_crash_directory_;
-  base::FilePath log_config_path_;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(CrashCollector);
-};
-
-#endif  // CRASH_REPORTER_CRASH_COLLECTOR_H_
diff --git a/crash_reporter/crash_collector_test.cc b/crash_reporter/crash_collector_test.cc
deleted file mode 100644
index 11c8c0d..0000000
--- a/crash_reporter/crash_collector_test.cc
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "crash_collector_test.h"
-
-#include <unistd.h>
-#include <utility>
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/syslog_logging.h>
-#include <gtest/gtest.h>
-
-#include "crash_collector.h"
-
-using base::FilePath;
-using base::StringPrintf;
-using brillo::FindLog;
-using ::testing::Invoke;
-using ::testing::Return;
-
-namespace {
-
-void CountCrash() {
-  ADD_FAILURE();
-}
-
-bool IsMetrics() {
-  ADD_FAILURE();
-  return false;
-}
-
-}  // namespace
-
-class CrashCollectorTest : public ::testing::Test {
- public:
-  void SetUp() {
-    EXPECT_CALL(collector_, SetUpDBus()).WillRepeatedly(Return());
-
-    collector_.Initialize(CountCrash, IsMetrics);
-    EXPECT_TRUE(test_dir_.CreateUniqueTempDir());
-    brillo::ClearLog();
-  }
-
-  bool CheckHasCapacity();
-
- protected:
-  CrashCollectorMock collector_;
-
-  // Temporary directory used for tests.
-  base::ScopedTempDir test_dir_;
-};
-
-TEST_F(CrashCollectorTest, Initialize) {
-  ASSERT_TRUE(CountCrash == collector_.count_crash_function_);
-  ASSERT_TRUE(IsMetrics == collector_.is_feedback_allowed_function_);
-}
-
-TEST_F(CrashCollectorTest, WriteNewFile) {
-  FilePath test_file = test_dir_.path().Append("test_new");
-  const char kBuffer[] = "buffer";
-  EXPECT_EQ(strlen(kBuffer),
-            collector_.WriteNewFile(test_file,
-                                    kBuffer,
-                                    strlen(kBuffer)));
-  EXPECT_LT(collector_.WriteNewFile(test_file,
-                                    kBuffer,
-                                    strlen(kBuffer)), 0);
-}
-
-TEST_F(CrashCollectorTest, Sanitize) {
-  EXPECT_EQ("chrome", collector_.Sanitize("chrome"));
-  EXPECT_EQ("CHROME", collector_.Sanitize("CHROME"));
-  EXPECT_EQ("1chrome2", collector_.Sanitize("1chrome2"));
-  EXPECT_EQ("chrome__deleted_", collector_.Sanitize("chrome (deleted)"));
-  EXPECT_EQ("foo_bar", collector_.Sanitize("foo.bar"));
-  EXPECT_EQ("", collector_.Sanitize(""));
-  EXPECT_EQ("_", collector_.Sanitize(" "));
-}
-
-TEST_F(CrashCollectorTest, FormatDumpBasename) {
-  struct tm tm = {0};
-  tm.tm_sec = 15;
-  tm.tm_min = 50;
-  tm.tm_hour = 13;
-  tm.tm_mday = 23;
-  tm.tm_mon = 4;
-  tm.tm_year = 110;
-  tm.tm_isdst = -1;
-  std::string basename =
-      collector_.FormatDumpBasename("foo", mktime(&tm), 100);
-  ASSERT_EQ("foo.20100523.135015.100", basename);
-}
-
-TEST_F(CrashCollectorTest, GetCrashPath) {
-  EXPECT_EQ("/var/spool/crash/myprog.20100101.1200.1234.core",
-            collector_.GetCrashPath(FilePath("/var/spool/crash"),
-                                    "myprog.20100101.1200.1234",
-                                    "core").value());
-  EXPECT_EQ("/home/chronos/user/crash/chrome.20100101.1200.1234.dmp",
-            collector_.GetCrashPath(FilePath("/home/chronos/user/crash"),
-                                    "chrome.20100101.1200.1234",
-                                    "dmp").value());
-}
-
-
-bool CrashCollectorTest::CheckHasCapacity() {
-  const char* kFullMessage =
-      StringPrintf("Crash directory %s already full",
-                   test_dir_.path().value().c_str()).c_str();
-  bool has_capacity = collector_.CheckHasCapacity(test_dir_.path());
-  bool has_message = FindLog(kFullMessage);
-  EXPECT_EQ(has_message, !has_capacity);
-  return has_capacity;
-}
-
-TEST_F(CrashCollectorTest, CheckHasCapacityUsual) {
-  // Test kMaxCrashDirectorySize - 1 non-meta files can be added.
-  for (int i = 0; i < CrashCollector::kMaxCrashDirectorySize - 1; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf("file%d.core", i)),
-                    "", 0);
-    EXPECT_TRUE(CheckHasCapacity());
-  }
-
-  // Test an additional kMaxCrashDirectorySize - 1 meta files fit.
-  for (int i = 0; i < CrashCollector::kMaxCrashDirectorySize - 1; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf("file%d.meta", i)),
-                    "", 0);
-    EXPECT_TRUE(CheckHasCapacity());
-  }
-
-  // Test an additional kMaxCrashDirectorySize meta files don't fit.
-  for (int i = 0; i < CrashCollector::kMaxCrashDirectorySize; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf("overage%d.meta", i)),
-                    "", 0);
-    EXPECT_FALSE(CheckHasCapacity());
-  }
-}
-
-TEST_F(CrashCollectorTest, CheckHasCapacityCorrectBasename) {
-  // Test kMaxCrashDirectorySize - 1 files can be added.
-  for (int i = 0; i < CrashCollector::kMaxCrashDirectorySize - 1; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf("file.%d.core", i)),
-                    "", 0);
-    EXPECT_TRUE(CheckHasCapacity());
-  }
-  base::WriteFile(test_dir_.path().Append("file.last.core"), "", 0);
-  EXPECT_FALSE(CheckHasCapacity());
-}
-
-TEST_F(CrashCollectorTest, CheckHasCapacityStrangeNames) {
-  // Test many files with different extensions and same base fit.
-  for (int i = 0; i < 5 * CrashCollector::kMaxCrashDirectorySize; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf("a.%d", i)), "", 0);
-    EXPECT_TRUE(CheckHasCapacity());
-  }
-  // Test dot files are treated as individual files.
-  for (int i = 0; i < CrashCollector::kMaxCrashDirectorySize - 2; ++i) {
-    base::WriteFile(test_dir_.path().Append(StringPrintf(".file%d", i)), "", 0);
-    EXPECT_TRUE(CheckHasCapacity());
-  }
-  base::WriteFile(test_dir_.path().Append("normal.meta"), "", 0);
-  EXPECT_FALSE(CheckHasCapacity());
-}
-
-TEST_F(CrashCollectorTest, MetaData) {
-  const char kMetaFileBasename[] = "generated.meta";
-  FilePath meta_file = test_dir_.path().Append(kMetaFileBasename);
-  FilePath payload_file = test_dir_.path().Append("payload-file");
-  std::string contents;
-  const char kPayload[] = "foo";
-  ASSERT_TRUE(base::WriteFile(payload_file, kPayload, strlen(kPayload)));
-  collector_.AddCrashMetaData("foo", "bar");
-  collector_.WriteCrashMetaData(meta_file, "kernel", payload_file.value());
-  EXPECT_TRUE(base::ReadFileToString(meta_file, &contents));
-  const std::string kExpectedMeta =
-      StringPrintf("foo=bar\n"
-          "exec_name=kernel\n"
-          "payload=%s\n"
-          "payload_size=3\n"
-          "done=1\n",
-          test_dir_.path().Append("payload-file").value().c_str());
-  EXPECT_EQ(kExpectedMeta, contents);
-
-  // Test target of symlink is not overwritten.
-  payload_file = test_dir_.path().Append("payload2-file");
-  ASSERT_TRUE(base::WriteFile(payload_file, kPayload, strlen(kPayload)));
-  FilePath meta_symlink_path = test_dir_.path().Append("symlink.meta");
-  ASSERT_EQ(0,
-            symlink(kMetaFileBasename,
-                    meta_symlink_path.value().c_str()));
-  ASSERT_TRUE(base::PathExists(meta_symlink_path));
-  brillo::ClearLog();
-  collector_.WriteCrashMetaData(meta_symlink_path,
-                                "kernel",
-                                payload_file.value());
-  // Target metadata contents should have stayed the same.
-  contents.clear();
-  EXPECT_TRUE(base::ReadFileToString(meta_file, &contents));
-  EXPECT_EQ(kExpectedMeta, contents);
-  EXPECT_TRUE(FindLog("Unable to write"));
-
-  // Test target of dangling symlink is not created.
-  base::DeleteFile(meta_file, false);
-  ASSERT_FALSE(base::PathExists(meta_file));
-  brillo::ClearLog();
-  collector_.WriteCrashMetaData(meta_symlink_path, "kernel",
-                                payload_file.value());
-  EXPECT_FALSE(base::PathExists(meta_file));
-  EXPECT_TRUE(FindLog("Unable to write"));
-}
-
-TEST_F(CrashCollectorTest, GetLogContents) {
-  FilePath config_file = test_dir_.path().Append("crash_config");
-  FilePath output_file = test_dir_.path().Append("crash_log");
-  const char kConfigContents[] =
-      "foobar=echo hello there | \\\n  sed -e \"s/there/world/\"";
-  ASSERT_TRUE(
-      base::WriteFile(config_file, kConfigContents, strlen(kConfigContents)));
-  base::DeleteFile(FilePath(output_file), false);
-  EXPECT_FALSE(collector_.GetLogContents(config_file,
-                                         "barfoo",
-                                         output_file));
-  EXPECT_FALSE(base::PathExists(output_file));
-  base::DeleteFile(FilePath(output_file), false);
-  EXPECT_TRUE(collector_.GetLogContents(config_file,
-                                        "foobar",
-                                        output_file));
-  ASSERT_TRUE(base::PathExists(output_file));
-  std::string contents;
-  EXPECT_TRUE(base::ReadFileToString(output_file, &contents));
-  EXPECT_EQ("hello world\n", contents);
-}
diff --git a/crash_reporter/crash_collector_test.h b/crash_reporter/crash_collector_test.h
deleted file mode 100644
index cfbb97b..0000000
--- a/crash_reporter/crash_collector_test.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef CRASH_REPORTER_CRASH_COLLECTOR_TEST_H_
-#define CRASH_REPORTER_CRASH_COLLECTOR_TEST_H_
-
-#include "crash_collector.h"
-
-#include <map>
-#include <string>
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-class CrashCollectorMock : public CrashCollector {
- public:
-  MOCK_METHOD0(SetUpDBus, void());
-  MOCK_METHOD1(GetActiveUserSessions,
-               bool(std::map<std::string, std::string> *sessions));
-};
-
-#endif  // CRASH_REPORTER_CRASH_COLLECTOR_TEST_H_
diff --git a/crash_reporter/crash_reporter.cc b/crash_reporter/crash_reporter.cc
deleted file mode 100644
index 16e70d8..0000000
--- a/crash_reporter/crash_reporter.cc
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <fcntl.h>  // for open
-
-#include <string>
-#include <vector>
-
-#include <base/files/file_util.h>
-#include <base/guid.h>
-#include <base/logging.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <binder/IServiceManager.h>
-#include <brillo/flag_helper.h>
-#include <brillo/syslog_logging.h>
-#include <metrics/metrics_collector_service_client.h>
-#include <metrics/metrics_library.h>
-#include <utils/String16.h>
-
-
-#include "kernel_collector.h"
-#include "kernel_warning_collector.h"
-#include "unclean_shutdown_collector.h"
-#include "user_collector.h"
-
-#if !defined(__ANDROID__)
-#include "udev_collector.h"
-#endif
-
-static const char kCrashCounterHistogram[] = "Logging.CrashCounter";
-static const char kKernelCrashDetected[] =
-    "/data/misc/crash_reporter/run/kernel-crash-detected";
-static const char kUncleanShutdownDetected[] =
-    "/var/run/unclean-shutdown-detected";
-static const char kGUIDFileName[] = "/data/misc/crash_reporter/guid";
-
-// Enumeration of kinds of crashes to be used in the CrashCounter histogram.
-enum CrashKinds {
-  kCrashKindUncleanShutdown = 1,
-  kCrashKindUser = 2,
-  kCrashKindKernel = 3,
-  kCrashKindUdev = 4,
-  kCrashKindKernelWarning = 5,
-  kCrashKindMax
-};
-
-static MetricsLibrary s_metrics_lib;
-
-using android::brillo::metrics::IMetricsCollectorService;
-using base::FilePath;
-using base::StringPrintf;
-
-static bool IsFeedbackAllowed() {
-  return s_metrics_lib.AreMetricsEnabled();
-}
-
-static bool TouchFile(const FilePath &file_path) {
-  return base::WriteFile(file_path, "", 0) == 0;
-}
-
-static void SendCrashMetrics(CrashKinds type, const char* name) {
-  // TODO(kmixter): We can remove this histogram as part of
-  // crosbug.com/11163.
-  s_metrics_lib.SendEnumToUMA(kCrashCounterHistogram, type, kCrashKindMax);
-  s_metrics_lib.SendCrashToUMA(name);
-}
-
-static void CountKernelCrash() {
-  SendCrashMetrics(kCrashKindKernel, "kernel");
-}
-
-static void CountUdevCrash() {
-  SendCrashMetrics(kCrashKindUdev, "udevcrash");
-}
-
-static void CountUncleanShutdown() {
-  SendCrashMetrics(kCrashKindUncleanShutdown, "uncleanshutdown");
-}
-
-static void CountUserCrash() {
-  SendCrashMetrics(kCrashKindUser, "user");
-  // Tell the metrics collector about the user crash, in order to log active
-  // use time between crashes.
-  MetricsCollectorServiceClient metrics_collector_service;
-
-  if (metrics_collector_service.Init())
-    metrics_collector_service.notifyUserCrash();
-  else
-    LOG(ERROR) << "Failed to send user crash notification to metrics_collector";
-}
-
-
-static int Initialize(KernelCollector *kernel_collector,
-                      UserCollector *user_collector,
-                      UncleanShutdownCollector *unclean_shutdown_collector,
-                      const bool unclean_check,
-                      const bool clean_shutdown) {
-  CHECK(!clean_shutdown) << "Incompatible options";
-
-  // Try to read the GUID from kGUIDFileName.  If the file doesn't exist, is
-  // blank, or the read fails, generate a new GUID and write it to the file.
-  std::string guid;
-  base::FilePath filepath(kGUIDFileName);
-  if (!base::ReadFileToString(filepath, &guid) || guid.empty()) {
-    guid = base::GenerateGUID();
-    // If we can't read or write the file, log an error.  However it is not
-    // a fatal error, as the crash server will assign a random GUID based
-    // on a hash of the IP address if one is not provided in the report.
-    if (base::WriteFile(filepath, guid.c_str(), guid.size()) <= 0) {
-      LOG(ERROR) << "Could not write guid " << guid << " to file "
-                 << filepath.value();
-    }
-  }
-
-  bool was_kernel_crash = false;
-  bool was_unclean_shutdown = false;
-  kernel_collector->Enable();
-  if (kernel_collector->is_enabled()) {
-    was_kernel_crash = kernel_collector->Collect();
-  }
-
-  if (unclean_check) {
-    was_unclean_shutdown = unclean_shutdown_collector->Collect();
-  }
-
-  // Touch a file to notify the metrics daemon that a kernel
-  // crash has been detected so that it can log the time since
-  // the last kernel crash.
-  if (IsFeedbackAllowed()) {
-    if (was_kernel_crash) {
-      TouchFile(FilePath(kKernelCrashDetected));
-    } else if (was_unclean_shutdown) {
-      // We only count an unclean shutdown if it did not come with
-      // an associated kernel crash.
-      TouchFile(FilePath(kUncleanShutdownDetected));
-    }
-  }
-
-  // Must enable the unclean shutdown collector *after* collecting.
-  unclean_shutdown_collector->Enable();
-  user_collector->Enable();
-
-  return 0;
-}
-
-static int HandleUserCrash(UserCollector *user_collector,
-                           const std::string& user, const bool crash_test) {
-  // Handle a specific user space crash.
-  CHECK(!user.empty()) << "--user= must be set";
-
-  // Make it possible to test what happens when we crash while
-  // handling a crash.
-  if (crash_test) {
-    *(volatile char *)0 = 0;
-    return 0;
-  }
-
-  // Accumulate logs to help in diagnosing failures during user collection.
-  brillo::LogToString(true);
-  // Handle the crash, get the name of the process from procfs.
-  bool handled = user_collector->HandleCrash(user, nullptr);
-  brillo::LogToString(false);
-  if (!handled)
-    return 1;
-  return 0;
-}
-
-#if !defined(__ANDROID__)
-static int HandleUdevCrash(UdevCollector *udev_collector,
-                           const std::string& udev_event) {
-  // Handle a crash indicated by a udev event.
-  CHECK(!udev_event.empty()) << "--udev= must be set";
-
-  // Accumulate logs to help in diagnosing failures during user collection.
-  brillo::LogToString(true);
-  bool handled = udev_collector->HandleCrash(udev_event);
-  brillo::LogToString(false);
-  if (!handled)
-    return 1;
-  return 0;
-}
-#endif
-
-static int HandleKernelWarning(KernelWarningCollector
-                               *kernel_warning_collector) {
-  // Accumulate logs to help in diagnosing failures during collection.
-  brillo::LogToString(true);
-  bool handled = kernel_warning_collector->Collect();
-  brillo::LogToString(false);
-  if (!handled)
-    return 1;
-  return 0;
-}
-
-// Interactive/diagnostics mode for generating kernel crash signatures.
-static int GenerateKernelSignature(KernelCollector *kernel_collector,
-                                   const std::string& kernel_signature_file) {
-  std::string kcrash_contents;
-  std::string signature;
-  if (!base::ReadFileToString(FilePath(kernel_signature_file),
-                              &kcrash_contents)) {
-    fprintf(stderr, "Could not read file.\n");
-    return 1;
-  }
-  if (!kernel_collector->ComputeKernelStackSignature(
-          kcrash_contents,
-          &signature,
-          true)) {
-    fprintf(stderr, "Signature could not be generated.\n");
-    return 1;
-  }
-  printf("Kernel crash signature is \"%s\".\n", signature.c_str());
-  return 0;
-}
-
-// Ensure stdout, stdin, and stderr are open file descriptors.  If
-// they are not, any code which writes to stderr/stdout may write out
-// to files opened during execution.  In particular, when
-// crash_reporter is run by the kernel coredump pipe handler (via
-// kthread_create/kernel_execve), it will not have file table entries
-// 1 and 2 (stdout and stderr) populated.  We populate them here.
-static void OpenStandardFileDescriptors() {
-  int new_fd = -1;
-  // We open /dev/null to fill in any of the standard [0, 2] file
-  // descriptors.  We leave these open for the duration of the
-  // process.  This works because open returns the lowest numbered
-  // invalid fd.
-  do {
-    new_fd = open("/dev/null", 0);
-    CHECK_GE(new_fd, 0) << "Unable to open /dev/null";
-  } while (new_fd >= 0 && new_fd <= 2);
-  close(new_fd);
-}
-
-int main(int argc, char *argv[]) {
-  DEFINE_bool(init, false, "Initialize crash logging");
-  DEFINE_bool(clean_shutdown, false, "Signal clean shutdown");
-  DEFINE_string(generate_kernel_signature, "",
-                "Generate signature from given kcrash file");
-  DEFINE_bool(crash_test, false, "Crash test");
-  DEFINE_string(user, "", "User crash info (pid:signal:exec_name)");
-  DEFINE_bool(unclean_check, true, "Check for unclean shutdown");
-
-#if !defined(__ANDROID__)
-  DEFINE_string(udev, "", "Udev event description (type:device:subsystem)");
-#endif
-
-  DEFINE_bool(kernel_warning, false, "Report collected kernel warning");
-  DEFINE_string(pid, "", "PID of crashing process");
-  DEFINE_string(uid, "", "UID of crashing process");
-  DEFINE_string(exe, "", "Executable name of crashing process");
-  DEFINE_bool(core2md_failure, false, "Core2md failure test");
-  DEFINE_bool(directory_failure, false, "Spool directory failure test");
-  DEFINE_string(filter_in, "",
-                "Ignore all crashes but this for testing");
-
-  OpenStandardFileDescriptors();
-  FilePath my_path = base::MakeAbsoluteFilePath(FilePath(argv[0]));
-  s_metrics_lib.Init();
-  brillo::FlagHelper::Init(argc, argv, "Chromium OS Crash Reporter");
-  brillo::OpenLog(my_path.BaseName().value().c_str(), true);
-  brillo::InitLog(brillo::kLogToSyslog);
-
-  KernelCollector kernel_collector;
-  kernel_collector.Initialize(CountKernelCrash, IsFeedbackAllowed);
-  UserCollector user_collector;
-  user_collector.Initialize(CountUserCrash,
-                            my_path.value(),
-                            IsFeedbackAllowed,
-                            true,  // generate_diagnostics
-                            FLAGS_core2md_failure,
-                            FLAGS_directory_failure,
-                            FLAGS_filter_in);
-  UncleanShutdownCollector unclean_shutdown_collector;
-  unclean_shutdown_collector.Initialize(CountUncleanShutdown,
-                                        IsFeedbackAllowed);
-
-#if !defined(__ANDROID__)
-  UdevCollector udev_collector;
-  udev_collector.Initialize(CountUdevCrash, IsFeedbackAllowed);
-#endif
-
-  KernelWarningCollector kernel_warning_collector;
-  kernel_warning_collector.Initialize(CountUdevCrash, IsFeedbackAllowed);
-
-  if (FLAGS_init) {
-    return Initialize(&kernel_collector,
-                      &user_collector,
-                      &unclean_shutdown_collector,
-                      FLAGS_unclean_check,
-                      FLAGS_clean_shutdown);
-  }
-
-  if (FLAGS_clean_shutdown) {
-    unclean_shutdown_collector.Disable();
-    user_collector.Disable();
-    return 0;
-  }
-
-  if (!FLAGS_generate_kernel_signature.empty()) {
-    return GenerateKernelSignature(&kernel_collector,
-                                   FLAGS_generate_kernel_signature);
-  }
-
-#if !defined(__ANDROID__)
-  if (!FLAGS_udev.empty()) {
-    return HandleUdevCrash(&udev_collector, FLAGS_udev);
-  }
-#endif
-
-  if (FLAGS_kernel_warning) {
-    return HandleKernelWarning(&kernel_warning_collector);
-  }
-
-  return HandleUserCrash(&user_collector, FLAGS_user, FLAGS_crash_test);
-}
diff --git a/crash_reporter/crash_reporter.rc b/crash_reporter/crash_reporter.rc
deleted file mode 100644
index e6d1ec5..0000000
--- a/crash_reporter/crash_reporter.rc
+++ /dev/null
@@ -1,37 +0,0 @@
-on property:crash_reporter.coredump.enabled=1
-    write /proc/sys/kernel/core_pattern \
-          "|/system/bin/crash_reporter --user=%P:%s:%u:%g:%e"
-
-on property:crash_reporter.coredump.enabled=0
-    write /proc/sys/kernel/core_pattern "core"
-
-on post-fs-data
-    # Allow catching multiple unrelated concurrent crashes, but use a finite
-    # number to prevent infinitely recursing on crash handling.
-    write /proc/sys/kernel/core_pipe_limit 4
-
-    # Remove any previous orphaned locks.
-    rmdir /data/misc/crash_reporter/lock/crash_sender
-
-    # Remove any previous run files.
-    rm /data/misc/crash_reporter/run/kernel-crash-detected
-    rmdir /data/misc/crash_reporter/run
-
-    # Create crash directories.
-    # These directories are group-writable by root so that crash_reporter can
-    # still access them when it switches users.
-    mkdir /data/misc/crash_reporter 0770 root root
-    mkdir /data/misc/crash_reporter/crash 0770 root root
-    mkdir /data/misc/crash_reporter/lock 0700 root root
-    mkdir /data/misc/crash_reporter/log 0700 root root
-    mkdir /data/misc/crash_reporter/run 0700 root root
-    mkdir /data/misc/crash_reporter/tmp 0770 root root
-
-service crash_reporter /system/bin/crash_reporter --init
-    class late_start
-    oneshot
-
-service crash_sender /system/bin/periodic_scheduler 3600 14400 crash_sender \
-    /system/bin/crash_sender
-    class late_start
-    group system
diff --git a/crash_reporter/crash_reporter_logs.conf b/crash_reporter/crash_reporter_logs.conf
deleted file mode 100644
index 7db308c..0000000
--- a/crash_reporter/crash_reporter_logs.conf
+++ /dev/null
@@ -1,122 +0,0 @@
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# This file is parsed by chromeos::KeyValueStore. It has the format:
-#
-# <basename>=<shell command>\n
-#
-# Commands may be split across multiple lines using trailing backslashes.
-#
-# When an executable named <basename> crashes, the corresponding command is
-# executed and its standard output and standard error are attached to the crash
-# report.
-#
-# Use caution in modifying this file. Only run common Unix commands here, as
-# these commands will be run when a crash has recently occurred and we should
-# avoid running anything that might cause another crash. Similarly, these
-# commands block notification of the crash to parent processes, so commands
-# should execute quickly.
-
-update_engine=cat $(ls -1tr /var/log/update_engine | tail -5 | \
-  sed s.^./var/log/update_engine/.) | tail -c 50000
-
-# The cros_installer output is logged into the update engine log file,
-# so it is handled in the same way as update_engine.
-cros_installer=cat $(ls -1tr /var/log/update_engine | tail -5 | \
-  sed s.^./var/log/update_engine/.) | tail -c 50000
-
-# Dump the last 20 lines of the last two files in Chrome's system and user log
-# directories, along with the last 20 messages from the session manager.
-chrome=\
-  for f in $(ls -1rt /var/log/chrome/chrome_[0-9]* | tail -2) \
-    $(ls -1rt /home/chronos/u-*/log/chrome_[0-9]* 2>/dev/null | tail -2); do \
-    echo "===$f (tail)==="; \
-    tail -20 $f; \
-    echo EOF; \
-    echo; \
-  done; \
-  echo "===session_manager (tail)==="; \
-  awk '$3 ~ "^session_manager\[" { print }' /var/log/messages | tail -20; \
-  echo EOF
-
-# The following rule is used for generating additional diagnostics when
-# collection of user crashes fails.  This output should not be too large
-# as it is stored in memory.  The output format specified for 'ps' is the
-# same as with the "u" ("user-oriented") option, except it doesn't show
-# the commands' arguments (i.e. "comm" instead of "command").
-crash_reporter-user-collection=\
-  echo "===ps output==="; \
-  ps axw -o user,pid,%cpu,%mem,vsz,rss,tname,stat,start_time,bsdtime,comm | \
-    tail -c 25000; \
-  echo "===meminfo==="; \
-  cat /proc/meminfo
-
-# This rule is similar to the crash_reporter-user-collection rule, except it is
-# run for kernel errors reported through udev events.
-crash_reporter-udev-collection-change-card0-drm=\
-  for dri in /sys/kernel/debug/dri/*; do \
-    echo "===$dri/i915_error_state==="; \
-    cat $dri/i915_error_state; \
-  done
-
-# When trackpad driver cyapa detects some abnormal behavior, we collect
-# additional logs from kernel messages.
-crash_reporter-udev-collection-change--i2c-cyapa=\
-  /usr/sbin/kernel_log_collector.sh cyapa 30
-# When trackpad/touchscreen driver atmel_mxt_ts detects some abnormal behavior,
-# we collect additional logs from kernel messages.
-crash_reporter-udev-collection-change--i2c-atmel_mxt_ts=\
-  /usr/sbin/kernel_log_collector.sh atmel 30
-# When touch device noise are detected, we collect relevant logs.
-# (crosbug.com/p/16788)
-crash_reporter-udev-collection---TouchNoise=cat /var/log/touch_noise.log
-# Periodically collect touch event log for debugging (crosbug.com/p/17244)
-crash_reporter-udev-collection---TouchEvent=cat /var/log/touch_event.log
-
-# Collect the last 50 lines of /var/log/messages and /var/log/net.log for
-# intel wifi driver (iwlwifi) for debugging purpose.
-crash_reporter-udev-collection-devcoredump-iwlwifi=\
-  echo "===/var/log/messages==="; \
-  tail -n 50 /var/log/messages; \
-  echo "===/var/log/net.log==="; \
-  tail -n 50 /var/log/net.log; \
-  echo EOF
-
-# Dump the last 50 lines of the last two powerd log files -- if the job has
-# already restarted, we want to see the end of the previous instance's logs.
-powerd=\
-  for f in $(ls -1tr /var/log/power_manager/powerd.[0-9]* | tail -2); do \
-    echo "===$(basename $f) (tail)==="; \
-    tail -50 $f; \
-    echo EOF; \
-  done
-# If power_supply_info aborts (due to e.g. a bad battery), its failure message
-# could end up in various places depending on which process was running it.
-# Attach the end of powerd's log since it might've also logged the underlying
-# problem.
-power_supply_info=\
-  echo "===powerd.LATEST (tail)==="; \
-  tail -50 /var/log/power_manager/powerd.LATEST; \
-  echo EOF
-# powerd_setuid_helper gets run by powerd, so its stdout/stderr will be mixed in
-# with powerd's stdout/stderr.
-powerd_setuid_helper=\
-  echo "===powerd.OUT (tail)==="; \
-  tail -50 /var/log/powerd.out; \
-  echo EOF
-
-# The following rules are only for testing purposes.
-crash_log_test=echo hello world
-crash_log_recursion_test=sleep 1 && \
-  /usr/local/autotest/tests/crash_log_recursion_test
diff --git a/crash_reporter/crash_reporter_logs_test.cc b/crash_reporter/crash_reporter_logs_test.cc
deleted file mode 100644
index 77f5a7f..0000000
--- a/crash_reporter/crash_reporter_logs_test.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <string>
-
-#include <base/files/file_path.h>
-#include <brillo/key_value_store.h>
-#include <gtest/gtest.h>
-
-namespace {
-
-// Name of the checked-in configuration file containing log-collection commands.
-const char kConfigFile[] = "/system/etc/crash_reporter_logs.conf";
-
-// Signature name for crash_reporter user collection.
-// kConfigFile is expected to contain this entry.
-const char kUserCollectorSignature[] = "crash_reporter-user-collection";
-
-}  // namespace
-
-// Tests that the config file is parsable and that Chrome is listed.
-TEST(CrashReporterLogsTest, ReadConfig) {
-  brillo::KeyValueStore store;
-  ASSERT_TRUE(store.Load(base::FilePath(kConfigFile)));
-  std::string command;
-  EXPECT_TRUE(store.GetString(kUserCollectorSignature, &command));
-  EXPECT_FALSE(command.empty());
-}
diff --git a/crash_reporter/crash_sender b/crash_reporter/crash_sender
deleted file mode 100755
index a430ab5..0000000
--- a/crash_reporter/crash_sender
+++ /dev/null
@@ -1,719 +0,0 @@
-#!/system/bin/sh
-
-# 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.
-
-set -e
-
-# Default product ID in crash report (used if GOOGLE_CRASH_* is undefined).
-BRILLO_PRODUCT=Brillo
-
-# Base directory that contains any crash reporter state files.
-CRASH_STATE_DIR="/data/misc/crash_reporter"
-
-# File containing crash_reporter's anonymized guid.
-GUID_FILE="${CRASH_STATE_DIR}/guid"
-
-# Crash sender lock in case the sender is already running.
-CRASH_SENDER_LOCK="${CRASH_STATE_DIR}/lock/crash_sender"
-
-# Path to file that indicates a crash test is currently running.
-CRASH_TEST_IN_PROGRESS_FILE="${CRASH_STATE_DIR}/tmp/crash-test-in-progress"
-
-# Set this to 1 in the environment to allow uploading crash reports
-# for unofficial versions.
-FORCE_OFFICIAL=${FORCE_OFFICIAL:-0}
-
-# Path to hardware class description.
-HWCLASS_PATH="/sys/devices/platform/chromeos_acpi/HWID"
-
-# Path to file that indicates this is a developer image.
-LEAVE_CORE_FILE="${CRASH_STATE_DIR}/.leave_core"
-
-# Path to list_proxies.
-LIST_PROXIES="list_proxies"
-
-# Maximum crashes to send per day.
-MAX_CRASH_RATE=${MAX_CRASH_RATE:-32}
-
-# File whose existence mocks crash sending.  If empty we pretend the
-# crash sending was successful, otherwise unsuccessful.
-MOCK_CRASH_SENDING="${CRASH_STATE_DIR}/tmp/mock-crash-sending"
-
-# Set this to 1 in the environment to pretend to have booted in developer
-# mode.  This is used by autotests.
-MOCK_DEVELOPER_MODE=${MOCK_DEVELOPER_MODE:-0}
-
-# Ignore PAUSE_CRASH_SENDING file if set.
-OVERRIDE_PAUSE_SENDING=${OVERRIDE_PAUSE_SENDING:-0}
-
-# File whose existence causes crash sending to be delayed (for testing).
-# Must be stateful to enable testing kernel crashes.
-PAUSE_CRASH_SENDING="${CRASH_STATE_DIR}/lock/crash_sender_paused"
-
-# Path to a directory of restricted certificates which includes
-# a certificate for the crash server.
-RESTRICTED_CERTIFICATES_PATH="/system/etc/security/cacerts"
-RESTRICTED_CERTIFICATES_PATH_GOOGLE="/system/etc/security/cacerts_google"
-
-# File whose existence implies we're running and not to start again.
-RUN_FILE="${CRASH_STATE_DIR}/run/crash_sender.pid"
-
-# Maximum time to sleep between sends.
-SECONDS_SEND_SPREAD=${SECONDS_SEND_SPREAD:-600}
-
-# Set this to 1 to allow uploading of device coredumps.
-DEVCOREDUMP_UPLOAD_FLAG_FILE="${CRASH_STATE_DIR}/device_coredump_upload_allowed"
-
-# The weave configuration file.
-WEAVE_CONF_FILE="/etc/weaved/weaved.conf"
-
-# The os-release.d folder.
-OSRELEASED_FOLDER="/etc/os-release.d"
-
-# The syslog tag for all logging we emit.
-TAG="$(basename $0)[$$]"
-
-# Directory to store timestamp files indicating the uploads in the past 24
-# hours.
-TIMESTAMPS_DIR="${CRASH_STATE_DIR}/crash_sender"
-
-# Temp directory for this process.
-TMP_DIR=""
-
-# Crash report log file.
-CRASH_LOG="${CRASH_STATE_DIR}/log/uploads.log"
-
-lecho() {
-  log -t "${TAG}" "$@"
-}
-
-lwarn() {
-  lecho -psyslog.warn "$@"
-}
-
-# Returns true if mock is enabled.
-is_mock() {
-  [ -f "${MOCK_CRASH_SENDING}" ] && return 0
-  return 1
-}
-
-is_mock_successful() {
-  local mock_in=$(cat "${MOCK_CRASH_SENDING}")
-  [ "${mock_in}" = "" ] && return 0  # empty file means success
-  return 1
-}
-
-cleanup() {
-  if [ -n "${TMP_DIR}" ]; then
-    rm -rf "${TMP_DIR}"
-  fi
-  rm -f "${RUN_FILE}"
-  if [ -n "${CRASH_SENDER_LOCK}" ]; then
-    rm -rf "${CRASH_SENDER_LOCK}"
-  fi
-  crash_done
-}
-
-crash_done() {
-  if is_mock; then
-    # For testing purposes, emit a message to log so that we
-    # know when the test has received all the messages from this run.
-    lecho "crash_sender done."
-  fi
-}
-
-is_official_image() {
-  [ ${FORCE_OFFICIAL} -ne 0 ] && return 0
-  if [ "$(getprop ro.secure)" = "1" ]; then
-    return 0
-  else
-    return 1
-  fi
-}
-
-# Returns 0 if the a crash test is currently running.  NOTE: Mirrors
-# crash_collector.cc:CrashCollector::IsCrashTestInProgress().
-is_crash_test_in_progress() {
-  [ -f "${CRASH_TEST_IN_PROGRESS_FILE}" ] && return 0
-  return 1
-}
-
-# Returns 0 if we should consider ourselves to be running on a developer
-# image.  NOTE: Mirrors crash_collector.cc:CrashCollector::IsDeveloperImage().
-is_developer_image() {
-  # If we're testing crash reporter itself, we don't want to special-case
-  # for developer images.
-  is_crash_test_in_progress && return 1
-  [ -f "${LEAVE_CORE_FILE}" ] && return 0
-  return 1
-}
-
-# Returns 0 if we should consider ourselves to be running on a test image.
-is_test_image() {
-  # If we're testing crash reporter itself, we don't want to special-case
-  # for test images.
-  is_crash_test_in_progress && return 1
-  case $(get_channel) in
-  test*) return 0;;
-  esac
-  return 1
-}
-
-# Returns 0 if the machine booted up in developer mode.
-is_developer_mode() {
-  [ ${MOCK_DEVELOPER_MODE} -ne 0 ] && return 0
-  # If we're testing crash reporter itself, we don't want to special-case
-  # for developer mode.
-  is_crash_test_in_progress && return 1
-  if [ "$(getprop ro.debuggable)" = "1" ]; then
-    return 0
-  else
-    return 1
-  fi
-}
-
-# Returns the path of the certificates directory to be used when sending
-# reports to the crash server.
-# If crash_reporter.full_certs=1, return the full certificates path.
-# Otherwise return the Google-specific certificates path.
-get_certificates_path() {
-  if [ "$(getprop crash_reporter.full_certs)" = "1" ]; then
-    echo "${RESTRICTED_CERTIFICATES_PATH}"
-  else
-    echo "${RESTRICTED_CERTIFICATES_PATH_GOOGLE}"
-  fi
-}
-
-# Return 0 if the uploading of device coredumps is allowed.
-is_device_coredump_upload_allowed() {
-  [ -f "${DEVCOREDUMP_UPLOAD_FLAG_FILE}" ] && return 0
-  return 1
-}
-
-# Generate a uniform random number in 0..max-1.
-# POSIX arithmetic expansion requires support of at least signed long integers.
-# On 32-bit systems, that may mean 32-bit signed integers, in which case the
-# 32-bit random number read from /dev/urandom may be interpreted as negative
-# when used inside an arithmetic expansion (since the high bit might be set).
-# mksh at least is known to behave this way.
-# For this case, simply take the absolute value, which will still give a
-# roughly uniform random distribution for the modulo (as we are merely ignoring
-# the high/sign bit).
-# See corresponding Arithmetic Expansion and Arithmetic Expression sections:
-# POSIX: http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_04
-# mksh: http://linux.die.net/man/1/mksh
-generate_uniform_random() {
-  local max=$1
-  local random="$(od -An -N4 -tu /dev/urandom)"
-  echo $(((random < 0 ? -random : random) % max))
-}
-
-# Check if sending a crash now does not exceed the maximum 24hr rate and
-# commit to doing so, if not.
-check_rate() {
-  mkdir -p ${TIMESTAMPS_DIR}
-  # Only consider minidumps written in the past 24 hours by removing all older.
-  find "${TIMESTAMPS_DIR}" -mindepth 1 -mtime +1 \
-      -exec rm -- '{}' ';'
-  local sends_in_24hrs=$(echo "${TIMESTAMPS_DIR}"/* | wc -w)
-  lecho "Current send rate: ${sends_in_24hrs}sends/24hrs"
-  if [ ${sends_in_24hrs} -ge ${MAX_CRASH_RATE} ]; then
-    lecho "Cannot send more crashes:"
-    lecho "  current ${sends_in_24hrs}send/24hrs >= " \
-          "max ${MAX_CRASH_RATE}send/24hrs"
-    return 1
-  fi
-  mktemp "${TIMESTAMPS_DIR}"/XXXXXX > /dev/null
-  return 0
-}
-
-# Gets the base part of a crash report file, such as name.01234.5678.9012 from
-# name.01234.5678.9012.meta or name.01234.5678.9012.log.tar.xz.  We make sure
-# "name" is sanitized in CrashCollector::Sanitize to not include any periods.
-get_base() {
-  echo "$1" | cut -d. -f-4
-}
-
-get_extension() {
-  local extension="${1##*.}"
-  local filename="${1%.*}"
-  # For gzipped file, we ignore .gz and get the real extension
-  if [ "${extension}" = "gz" ]; then
-    echo "${filename##*.}"
-  else
-    echo "${extension}"
-  fi
-}
-
-# Return which kind of report the given metadata file relates to
-get_kind() {
-  local payload="$(get_key_value "$1" "payload")"
-  if [ ! -r "${payload}" ]; then
-    lecho "Missing payload: ${payload}"
-    echo "undefined"
-    return
-  fi
-  local kind="$(get_extension "${payload}")"
-  if [ "${kind}" = "dmp" ]; then
-    echo "minidump"
-    return
-  fi
-  echo "${kind}"
-}
-
-get_key_value() {
-  local file="$1" key="$2" value
-
-  if [ -f "${file}/${key}" ]; then
-    # Get the value from a folder where each key is its own file.  The key
-    # file's entire contents is the value.
-    value=$(cat "${file}/${key}")
-  elif [ -f "${file}" ]; then
-    # Get the value from a file that has multiple key=value combinations.
-    # Return the first entry.  There shouldn't be more than one anyways.
-    # Substr at length($1) + 2 skips past the key and following = sign (awk
-    # uses 1-based indexes), but preserves embedded = characters.
-    value=$(sed -n "/^${key}[[:space:]]*=/{s:^[^=]*=::p;q}" "${file}")
-  fi
-
-  echo "${value:-undefined}"
-}
-
-get_keys() {
-  local file="$1" regex="$2"
-
-  cut -d '=' -f1 "${file}" | grep --color=never "${regex}"
-}
-
-# Return the channel name (sans "-channel" suffix).
-get_channel() {
-  getprop ro.product.channel | sed 's:-channel$::'
-}
-
-# Return the hardware class or "undefined".
-get_hardware_class() {
-  if [ -r "${HWCLASS_PATH}" ]; then
-    cat "${HWCLASS_PATH}"
-  else
-    echo "undefined"
-  fi
-}
-
-# Return the log string filtered with only JSON-safe white-listed characters.
-filter_log_string() {
-  echo "$1" | tr -cd '[:alnum:]_.\-:;'
-}
-
-send_crash() {
-  local meta_path="$1"
-  local report_payload="$(get_key_value "${meta_path}" "payload")"
-  local kind="$(get_kind "${meta_path}")"
-  local exec_name="$(get_key_value "${meta_path}" "exec_name")"
-  local url="$(get_key_value "${OSRELEASED_FOLDER}" "crash_server")"
-  local bdk_version="$(get_key_value "${meta_path}" "bdk_version")"
-  local hwclass="$(get_hardware_class)"
-  local write_payload_size="$(get_key_value "${meta_path}" "payload_size")"
-  local log="$(get_key_value "${meta_path}" "log")"
-  local sig="$(get_key_value "${meta_path}" "sig")"
-  local send_payload_size="$(stat -c "%s" "${report_payload}" 2>/dev/null)"
-  local product="$(get_key_value "${meta_path}" "product_id")"
-  local version="$(get_key_value "${meta_path}" "product_version")"
-  local upload_prefix="$(get_key_value "${meta_path}" "upload_prefix")"
-  local guid
-  local model_manifest_id="$(get_key_value "${WEAVE_CONF_FILE}" "model_id")"
-
-  # If crash_reporter.server is not set return with an error.
-  if [ -z "${url}" ]; then
-    lecho "Configuration error: crash_reporter.server not set."
-    return 1
-  fi
-
-  set -- \
-    -F "write_payload_size=${write_payload_size}" \
-    -F "send_payload_size=${send_payload_size}"
-  if [ "${sig}" != "undefined" ]; then
-    set -- "$@" \
-      -F "sig=${sig}" \
-      -F "sig2=${sig}"
-  fi
-  if [ -r "${report_payload}" ]; then
-    set -- "$@" \
-      -F "upload_file_${kind}=@${report_payload}"
-  fi
-  if [ "${log}" != "undefined" -a -r "${log}" ]; then
-    set -- "$@" \
-      -F "log=@${log}"
-  fi
-
-  if [ "${upload_prefix}" = "undefined" ]; then
-    upload_prefix=""
-  fi
-
-  # Grab any variable that begins with upload_.
-  local v
-  for k in $(get_keys "${meta_path}" "^upload_"); do
-    v="$(get_key_value "${meta_path}" "${k}")"
-    case ${k} in
-      # Product & version are handled separately.
-      upload_var_prod) ;;
-      upload_var_ver) ;;
-      upload_var_*)
-        set -- "$@" -F "${upload_prefix}${k#upload_var_}=${v}"
-        ;;
-      upload_file_*)
-        if [ -r "${v}" ]; then
-          set -- "$@" -F "${upload_prefix}${k#upload_file_}=@${v}"
-        fi
-        ;;
-    esac
-  done
-
-  # If ID or VERSION_ID is undefined, we use the default product name
-  # and bdk_version from /etc/os-release.d.
-  if [ "${product}" = "undefined" ]; then
-    product="${BRILLO_PRODUCT}"
-  fi
-  if [ "${version}" = "undefined" ]; then
-    version="${bdk_version}"
-  fi
-
-  local image_type
-  if is_test_image; then
-    image_type="test"
-  elif is_developer_image; then
-    image_type="dev"
-  elif [ ${FORCE_OFFICIAL} -ne 0 ]; then
-    image_type="force-official"
-  elif is_mock && ! is_mock_successful; then
-    image_type="mock-fail"
-  fi
-
-  local boot_mode
-  if is_developer_mode; then
-    boot_mode="dev"
-  fi
-
-  # Need to strip dashes ourselves as Chrome preserves it in the file
-  # nowadays.  This is also what the Chrome breakpad client does.
-  guid=$(tr -d '-' < "${GUID_FILE}")
-
-  local error_type="$(get_key_value "${meta_path}" "error_type")"
-  [ "${error_type}" = "undefined" ] && error_type=
-
-  lecho "Sending crash:"
-  if [ "${product}" != "${BRILLO_PRODUCT}" ]; then
-    lecho "  Sending crash report on behalf of ${product}"
-  fi
-  lecho "  Metadata: ${meta_path} (${kind})"
-  lecho "  Payload: ${report_payload}"
-  lecho "  Version: ${version}"
-  lecho "  Bdk Version: ${bdk_version}"
-  [ -n "${image_type}" ] && lecho "  Image type: ${image_type}"
-  [ -n "${boot_mode}" ] && lecho "  Boot mode: ${boot_mode}"
-  if is_mock; then
-    lecho "  Product: ${product}"
-    lecho "  URL: ${url}"
-    lecho "  HWClass: ${hwclass}"
-    lecho "  write_payload_size: ${write_payload_size}"
-    lecho "  send_payload_size: ${send_payload_size}"
-    if [ "${log}" != "undefined" ]; then
-      lecho "  log: @${log}"
-    fi
-    if [ "${sig}" != "undefined" ]; then
-      lecho "  sig: ${sig}"
-    fi
-  fi
-  lecho "  Exec name: ${exec_name}"
-  [ -n "${error_type}" ] && lecho "  Error type: ${error_type}"
-  if is_mock; then
-    if ! is_mock_successful; then
-      lecho "Mocking unsuccessful send"
-      return 1
-    fi
-    lecho "Mocking successful send"
-    return 0
-  fi
-
-  # Read in the first proxy, if any, for a given URL.  NOTE: The
-  # double-quotes are necessary due to a bug in dash with the "local"
-  # builtin command and values that have spaces in them (see
-  # "https://bugs.launchpad.net/ubuntu/+source/dash/+bug/139097").
-  if [ -f "${LIST_PROXIES}" ]; then
-    local proxy ret
-    proxy=$("${LIST_PROXIES}" --quiet "${url}")
-    ret=$?
-    if [ ${ret} -ne 0 ]; then
-      proxy=''
-      lwarn "Listing proxies failed with exit code ${ret}"
-    else
-      proxy=$(echo "${proxy}" | head -1)
-    fi
-  fi
-  # if a direct connection should be used, unset the proxy variable.
-  [ "${proxy}" = "direct://" ] && proxy=
-  local report_id="${TMP_DIR}/report_id"
-  local curl_stderr="${TMP_DIR}/curl_stderr"
-
-  set +e
-  curl "${url}" -f -v ${proxy:+--proxy "$proxy"} \
-    --capath "$(get_certificates_path)" --ciphers HIGH \
-    -F "prod=${product}" \
-    -F "ver=${version}" \
-    -F "bdk_version=${bdk_version}" \
-    -F "hwclass=${hwclass}" \
-    -F "exec_name=${exec_name}" \
-    -F "model_manifest_id=${model_manifest_id}" \
-    ${image_type:+-F "image_type=${image_type}"} \
-    ${boot_mode:+-F "boot_mode=${boot_mode}"} \
-    ${error_type:+-F "error_type=${error_type}"} \
-    -F "guid=${guid}" \
-    -o "${report_id}" \
-    "$@" \
-    2>"${curl_stderr}"
-  curl_result=$?
-  set -e
-
-  if [ ${curl_result} -eq 0 ]; then
-    local id="$(cat "${report_id}")"
-    local timestamp="$(date +%s)"
-    local filter_prod="$(filter_log_string "${product}")"
-    local filter_exec="$(filter_log_string "${exec_name}")"
-    if [ "${filter_prod}" != "${product}" ]; then
-      lwarn "Product name filtered to: ${filter_prod}."
-    fi
-    if [ "${filter_exec}" != "${exec_name}" ]; then
-      lwarn "Exec name filtered to: ${filter_exec}."
-    fi
-    printf "{'time':%s,'id':'%s','product':'%s','exec_name':'%s'}\n" \
-      "${timestamp}" "${id}" "${filter_prod}" "${filter_exec}" >> "${CRASH_LOG}"
-    lecho "Crash report receipt ID ${id}"
-  else
-    lecho "Crash sending failed with exit code ${curl_result}: " \
-      "$(cat "${curl_stderr}")"
-  fi
-
-  rm -f "${report_id}"
-
-  return ${curl_result}
-}
-
-# *.meta files always end with done=1 so we can tell if they are complete.
-is_complete_metadata() {
-  grep -q "done=1" "$1"
-}
-
-# Remove the given report path.
-remove_report() {
-  local base="${1%.*}"
-  rm -f -- "${base}".*
-}
-
-# Send all crashes from the given directory.  This applies even when we're on a
-# 3G connection (see crosbug.com/3304 for discussion).
-send_crashes() {
-  local dir="$1"
-  lecho "Sending crashes for ${dir}"
-
-  if [ ! -d "${dir}" ]; then
-    return
-  fi
-
-  # Consider any old files which still have no corresponding meta file
-  # as orphaned, and remove them.
-  for old_file in $(find "${dir}" -mindepth 1 \
-                    -mtime +1 -type f); do
-    if [ ! -e "$(get_base "${old_file}").meta" ]; then
-      lecho "Removing old orphaned file: ${old_file}."
-      rm -f -- "${old_file}"
-    fi
-  done
-
-  # Look through all metadata (*.meta) files, oldest first.  That way, the rate
-  # limit does not stall old crashes if there's a high amount of new crashes
-  # coming in.
-  # For each crash report, first evaluate conditions that might lead to its
-  # removal to honor user choice and to free disk space as soon as possible,
-  # then decide whether it should be sent right now or kept for later sending.
-  for meta_path in $(ls -1tr "${dir}"/*.meta 2>/dev/null); do
-    lecho "Considering metadata ${meta_path}."
-
-    local kind=$(get_kind "${meta_path}")
-    if [ "${kind}" != "minidump" ] && \
-       [ "${kind}" != "kcrash" ] && \
-       [ "${kind}" != "log" ] &&
-       [ "${kind}" != "devcore" ]; then
-      lecho "Unknown report kind ${kind}.  Removing report."
-      remove_report "${meta_path}"
-      continue
-    fi
-
-    if ! is_complete_metadata "${meta_path}"; then
-      # This report is incomplete, so if it's old, just remove it.
-      local old_meta=$(find "${dir}" -mindepth 1 -name \
-        $(basename "${meta_path}") -mtime +1 -type f)
-      if [ -n "${old_meta}" ]; then
-        lecho "Removing old incomplete metadata."
-        remove_report "${meta_path}"
-      else
-        lecho "Ignoring recent incomplete metadata."
-      fi
-      continue
-    fi
-
-    # Ignore device coredump if device coredump uploading is not allowed.
-    if [ "${kind}" = "devcore" ] && ! is_device_coredump_upload_allowed; then
-      lecho "Ignoring device coredump. Device coredump upload not allowed."
-      continue
-    fi
-
-    if ! is_mock && ! is_official_image; then
-      lecho "Not an official OS version.  Removing crash."
-      remove_report "${meta_path}"
-      continue
-    fi
-
-    # Remove existing crashes in case user consent has not (yet) been given or
-    # has been revoked.  This must come after the guest mode check because
-    # metrics_client always returns "not consented" in guest mode.
-    if ! metrics_client -c; then
-      lecho "Crash reporting is disabled.  Removing crash."
-      remove_report "${meta_path}"
-      continue
-    fi
-
-    # Skip report if the upload rate is exceeded.  (Don't exit right now because
-    # subsequent reports may be candidates for deletion.)
-    if ! check_rate; then
-      lecho "Sending ${meta_path} would exceed rate.  Leaving for later."
-      continue
-    fi
-
-    # The .meta file should be written *after* all to-be-uploaded files that it
-    # references.  Nevertheless, as a safeguard, a hold-off time of thirty
-    # seconds after writing the .meta file is ensured.  Also, sending of crash
-    # reports is spread out randomly by up to SECONDS_SEND_SPREAD.  Thus, for
-    # the sleep call the greater of the two delays is used.
-    local now=$(date +%s)
-    local holdoff_time=$(($(stat -c "%Y" "${meta_path}") + 30 - ${now}))
-    local spread_time=$(generate_uniform_random "${SECONDS_SEND_SPREAD}")
-    local sleep_time
-    if [ ${spread_time} -gt ${holdoff_time} ]; then
-      sleep_time="${spread_time}"
-    else
-      sleep_time="${holdoff_time}"
-    fi
-    lecho "Scheduled to send in ${sleep_time}s."
-    if ! is_mock; then
-      if ! sleep "${sleep_time}"; then
-          lecho "Sleep failed"
-          return 1
-      fi
-    fi
-
-    # Try to upload.
-    if ! send_crash "${meta_path}"; then
-      lecho "Problem sending ${meta_path}, not removing."
-      continue
-    fi
-
-    # Send was successful, now remove.
-    lecho "Successfully sent crash ${meta_path} and removing."
-    remove_report "${meta_path}"
-  done
-}
-
-usage() {
-  cat <<EOF
-Usage: crash_sender [options]
-
-Options:
- -e <var>=<val>     Set env |var| to |val| (only some vars)
-EOF
-  exit ${1:-1}
-}
-
-parseargs() {
-  # Parse the command line arguments.
-  while [ $# -gt 0 ]; do
-    case $1 in
-    -e)
-      shift
-      case $1 in
-      FORCE_OFFICIAL=*|\
-      MAX_CRASH_RATE=*|\
-      MOCK_DEVELOPER_MODE=*|\
-      OVERRIDE_PAUSE_SENDING=*|\
-      SECONDS_SEND_SPREAD=*)
-        export "$1"
-        ;;
-      *)
-        lecho "Unknown var passed to -e: $1"
-        exit 1
-        ;;
-      esac
-      ;;
-    -h)
-      usage 0
-      ;;
-    *)
-      lecho "Unknown options: $*"
-      exit 1
-      ;;
-    esac
-    shift
-  done
-}
-
-main() {
-  parseargs "$@"
-
-  if [ -e "${PAUSE_CRASH_SENDING}" ] && \
-     [ ${OVERRIDE_PAUSE_SENDING} -eq 0 ]; then
-    lecho "Exiting early due to ${PAUSE_CRASH_SENDING}."
-    exit 1
-  fi
-
-  if is_test_image; then
-    lecho "Exiting early due to test image."
-    exit 1
-  fi
-
-  # We don't perform checks on this because we have a master lock with the
-  # CRASH_SENDER_LOCK file.  This pid file is for the system to keep track
-  # (like with autotests) that we're still running.
-  echo $$ > "${RUN_FILE}"
-
-  for dependency in "$(get_certificates_path)"; do
-    if [ ! -x "${dependency}" ]; then
-      lecho "Fatal: Crash sending disabled: ${dependency} not found."
-      exit 1
-    fi
-  done
-
-  TMP_DIR="$(mktemp -d "${CRASH_STATE_DIR}/tmp/crash_sender.XXXXXX")"
-
-  # Send system-wide crashes
-  send_crashes "${CRASH_STATE_DIR}/crash"
-}
-
-trap cleanup EXIT INT TERM
-
-#TODO(http://b/23937249): Change the locking logic back to using flock.
-if ! mkdir "${CRASH_SENDER_LOCK}" 2>/dev/null; then
-  lecho "Already running; quitting."
-  crash_done
-  exit 1
-fi
-main "$@"
diff --git a/crash_reporter/dbus_bindings/org.chromium.LibCrosService.xml b/crash_reporter/dbus_bindings/org.chromium.LibCrosService.xml
deleted file mode 100644
index 64b8b84..0000000
--- a/crash_reporter/dbus_bindings/org.chromium.LibCrosService.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-
-<node name="/org/chromium/LibCrosService"
-      xmlns:tp="http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0">
-  <interface name="org.chromium.LibCrosServiceInterface">
-    <method name="ResolveNetworkProxy">
-      <arg name="source_url" type="s" direction="in"/>
-      <arg name="signal_interface" type="s" direction="in"/>
-      <arg name="signal_name" type="s" direction="in"/>
-      <annotation name="org.chromium.DBus.Method.Kind" value="simple"/>
-    </method>
-  </interface>
-  <interface name="org.chromium.CrashReporterLibcrosProxyResolvedInterface">
-    <signal name="ProxyResolved">
-      <arg name="source_url" type="s" direction="out"/>
-      <arg name="proxy_info" type="s" direction="out"/>
-      <arg name="error_message" type="s" direction="out"/>
-    </signal>
-  </interface>
-</node>
diff --git a/crash_reporter/init/crash-reporter.conf b/crash_reporter/init/crash-reporter.conf
deleted file mode 100644
index 19f2cdb..0000000
--- a/crash_reporter/init/crash-reporter.conf
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-description     "Initialize crash reporting services"
-author          "chromium-os-dev@chromium.org"
-
-# This job merely initializes its service and then terminates; the
-# actual checking and reporting of crash dumps is triggered by an
-# hourly cron job.
-start on starting system-services
-
-pre-start script
-  mkdir -p /var/spool
-
-  # Only allow device coredumps on a "developer system".
-  if ! is_developer_end_user; then
-    # consumer end-user - disable device coredumps, if driver exists.
-    echo 1 > /sys/class/devcoredump/disabled || true
-  fi
-end script
-
-# crash_reporter uses argv[0] as part of the command line for
-# /proc/sys/kernel/core_pattern.  That command line is invoked by
-# the kernel, and can't rely on PATH, so argv[0] must be a full
-# path; we invoke it as such here.
-exec /sbin/crash_reporter --init
diff --git a/crash_reporter/init/crash-sender.conf b/crash_reporter/init/crash-sender.conf
deleted file mode 100644
index 892186f..0000000
--- a/crash_reporter/init/crash-sender.conf
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-description     "Run the crash sender periodically"
-author          "chromium-os-dev@chromium.org"
-
-start on starting system-services
-stop on stopping system-services
-
-exec periodic_scheduler 3600 14400 crash_sender /sbin/crash_sender
diff --git a/crash_reporter/init/warn-collector.conf b/crash_reporter/init/warn-collector.conf
deleted file mode 100644
index 3be80da..0000000
--- a/crash_reporter/init/warn-collector.conf
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-description "Runs a daemon which collects and reports kernel warnings"
-author      "chromium-os-dev@chromium.org"
-
-start on started system-services
-stop on stopping system-services
-respawn
-
-exec warn_collector
diff --git a/crash_reporter/kernel_collector.cc b/crash_reporter/kernel_collector.cc
deleted file mode 100644
index 68f2d9e..0000000
--- a/crash_reporter/kernel_collector.cc
+++ /dev/null
@@ -1,603 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "kernel_collector.h"
-
-#include <map>
-#include <sys/stat.h>
-
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-
-using base::FilePath;
-using base::StringPrintf;
-
-namespace {
-
-const char kDefaultKernelStackSignature[] = "kernel-UnspecifiedStackSignature";
-const char kDumpParentPath[] = "/sys/fs";
-const char kDumpPath[] = "/sys/fs/pstore";
-const char kDumpFormat[] = "dmesg-ramoops-%zu";
-const char kKernelExecName[] = "kernel";
-// Maximum number of records to examine in the kDumpPath.
-const size_t kMaxDumpRecords = 100;
-const pid_t kKernelPid = 0;
-const char kKernelSignatureKey[] = "sig";
-// Byte length of maximum human readable portion of a kernel crash signature.
-const int kMaxHumanStringLength = 40;
-const uid_t kRootUid = 0;
-// Time in seconds from the final kernel log message for a call stack
-// to count towards the signature of the kcrash.
-const int kSignatureTimestampWindow = 2;
-// Kernel log timestamp regular expression.
-const char kTimestampRegex[] = "^<.*>\\[\\s*(\\d+\\.\\d+)\\]";
-
-//
-// These regular expressions enable to us capture the PC in a backtrace.
-// The backtrace is obtained through dmesg or the kernel's preserved/kcrashmem
-// feature.
-//
-// For ARM we see:
-//   "<5>[   39.458982] PC is at write_breakme+0xd0/0x1b4"
-// For MIPS we see:
-//   "<5>[ 3378.552000] epc   : 804010f0 lkdtm_do_action+0x68/0x3f8"
-// For x86:
-//   "<0>[   37.474699] EIP: [<790ed488>] write_breakme+0x80/0x108
-//    SS:ESP 0068:e9dd3efc"
-//
-const char* const kPCRegex[] = {
-  0,
-  " PC is at ([^\\+ ]+).*",
-  " epc\\s+:\\s+\\S+\\s+([^\\+ ]+).*",  // MIPS has an exception program counter
-  " EIP: \\[<.*>\\] ([^\\+ ]+).*",  // X86 uses EIP for the program counter
-  " RIP  \\[<.*>\\] ([^\\+ ]+).*",  // X86_64 uses RIP for the program counter
-};
-
-static_assert(arraysize(kPCRegex) == KernelCollector::kArchCount,
-              "Missing Arch PC regexp");
-
-}  // namespace
-
-KernelCollector::KernelCollector()
-    : is_enabled_(false),
-      ramoops_dump_path_(kDumpPath),
-      records_(0),
-      // We expect crash dumps in the format of architecture we are built for.
-      arch_(GetCompilerArch()) {
-}
-
-KernelCollector::~KernelCollector() {
-}
-
-void KernelCollector::OverridePreservedDumpPath(const FilePath &file_path) {
-  ramoops_dump_path_ = file_path;
-}
-
-bool KernelCollector::ReadRecordToString(std::string *contents,
-                                         size_t current_record,
-                                         bool *record_found) {
-  // A record is a ramoops dump. It has an associated size of "record_size".
-  std::string record;
-  std::string captured;
-
-  // Ramoops appends a header to a crash which contains ==== followed by a
-  // timestamp. Ignore the header.
-  pcrecpp::RE record_re(
-      "====\\d+\\.\\d+\n(.*)",
-      pcrecpp::RE_Options().set_multiline(true).set_dotall(true));
-
-  pcrecpp::RE sanity_check_re("\n<\\d+>\\[\\s*(\\d+\\.\\d+)\\]");
-
-  FilePath ramoops_record;
-  GetRamoopsRecordPath(&ramoops_record, current_record);
-  if (!base::ReadFileToString(ramoops_record, &record)) {
-    LOG(ERROR) << "Unable to open " << ramoops_record.value();
-    return false;
-  }
-
-  *record_found = false;
-  if (record_re.FullMatch(record, &captured)) {
-    // Found a ramoops header, so strip the header and append the rest.
-    contents->append(captured);
-    *record_found = true;
-  } else if (sanity_check_re.PartialMatch(record.substr(0, 1024))) {
-    // pstore compression has been added since kernel 3.12. In order to
-    // decompress dmesg correctly, ramoops driver has to strip the header
-    // before handing over the record to the pstore driver, so we don't
-    // need to do it here anymore. However, the sanity check is needed because
-    // sometimes a pstore record is just a chunk of uninitialized memory which
-    // is not the result of a kernel crash. See crbug.com/443764
-    contents->append(record);
-    *record_found = true;
-  } else {
-    LOG(WARNING) << "Found invalid record at " << ramoops_record.value();
-  }
-
-  // Remove the record from pstore after it's found.
-  if (*record_found)
-    base::DeleteFile(ramoops_record, false);
-
-  return true;
-}
-
-void KernelCollector::GetRamoopsRecordPath(FilePath *path,
-                                           size_t record) {
-  // Disable error "format not a string literal, argument types not checked"
-  // because this is valid, but GNU apparently doesn't bother checking a const
-  // format string.
-  #pragma GCC diagnostic push
-  #pragma GCC diagnostic ignored "-Wformat-nonliteral"
-  *path = ramoops_dump_path_.Append(StringPrintf(kDumpFormat, record));
-  #pragma GCC diagnostic pop
-}
-
-bool KernelCollector::LoadParameters() {
-  // Discover how many ramoops records are being exported by the driver.
-  size_t count;
-
-  for (count = 0; count < kMaxDumpRecords; ++count) {
-    FilePath ramoops_record;
-    GetRamoopsRecordPath(&ramoops_record, count);
-
-    if (!base::PathExists(ramoops_record))
-      break;
-  }
-
-  records_ = count;
-  return (records_ > 0);
-}
-
-bool KernelCollector::LoadPreservedDump(std::string *contents) {
-  // Load dumps from the preserved memory and save them in contents.
-  // Since the system is set to restart on oops we won't actually ever have
-  // multiple records (only 0 or 1), but check in case we don't restart on
-  // oops in the future.
-  bool any_records_found = false;
-  bool record_found = false;
-  // clear contents since ReadFileToString actually appends to the string.
-  contents->clear();
-
-  for (size_t i = 0; i < records_; ++i) {
-    if (!ReadRecordToString(contents, i, &record_found)) {
-      break;
-    }
-    if (record_found) {
-      any_records_found = true;
-    }
-  }
-
-  if (!any_records_found) {
-    LOG(ERROR) << "No valid records found in " << ramoops_dump_path_.value();
-    return false;
-  }
-
-  return true;
-}
-
-void KernelCollector::StripSensitiveData(std::string *kernel_dump) {
-  // Strip any data that the user might not want sent up to the crash servers.
-  // We'll read in from kernel_dump and also place our output there.
-  //
-  // At the moment, the only sensitive data we strip is MAC addresses.
-
-  // Get rid of things that look like MAC addresses, since they could possibly
-  // give information about where someone has been.  This is strings that look
-  // like this: 11:22:33:44:55:66
-  // Complications:
-  // - Within a given kernel_dump, want to be able to tell when the same MAC
-  //   was used more than once.  Thus, we'll consistently replace the first
-  //   MAC found with 00:00:00:00:00:01, the second with ...:02, etc.
-  // - ACPI commands look like MAC addresses.  We'll specifically avoid getting
-  //   rid of those.
-  std::ostringstream result;
-  std::string pre_mac_str;
-  std::string mac_str;
-  std::map<std::string, std::string> mac_map;
-  pcrecpp::StringPiece input(*kernel_dump);
-
-  // This RE will find the next MAC address and can return us the data preceding
-  // the MAC and the MAC itself.
-  pcrecpp::RE mac_re("(.*?)("
-                     "[0-9a-fA-F][0-9a-fA-F]:"
-                     "[0-9a-fA-F][0-9a-fA-F]:"
-                     "[0-9a-fA-F][0-9a-fA-F]:"
-                     "[0-9a-fA-F][0-9a-fA-F]:"
-                     "[0-9a-fA-F][0-9a-fA-F]:"
-                     "[0-9a-fA-F][0-9a-fA-F])",
-                     pcrecpp::RE_Options()
-                       .set_multiline(true)
-                       .set_dotall(true));
-
-  // This RE will identify when the 'pre_mac_str' shows that the MAC address
-  // was really an ACPI cmd.  The full string looks like this:
-  //   ata1.00: ACPI cmd ef/10:03:00:00:00:a0 (SET FEATURES) filtered out
-  pcrecpp::RE acpi_re("ACPI cmd ef/$",
-                      pcrecpp::RE_Options()
-                        .set_multiline(true)
-                        .set_dotall(true));
-
-  // Keep consuming, building up a result string as we go.
-  while (mac_re.Consume(&input, &pre_mac_str, &mac_str)) {
-    if (acpi_re.PartialMatch(pre_mac_str)) {
-      // We really saw an ACPI command; add to result w/ no stripping.
-      result << pre_mac_str << mac_str;
-    } else {
-      // Found a MAC address; look up in our hash for the mapping.
-      std::string replacement_mac = mac_map[mac_str];
-      if (replacement_mac == "") {
-        // It wasn't present, so build up a replacement string.
-        int mac_id = mac_map.size();
-
-        // Handle up to 2^32 unique MAC address; overkill, but doesn't hurt.
-        replacement_mac = StringPrintf("00:00:%02x:%02x:%02x:%02x",
-                                       (mac_id & 0xff000000) >> 24,
-                                       (mac_id & 0x00ff0000) >> 16,
-                                       (mac_id & 0x0000ff00) >> 8,
-                                       (mac_id & 0x000000ff));
-        mac_map[mac_str] = replacement_mac;
-      }
-
-      // Dump the string before the MAC and the fake MAC address into result.
-      result << pre_mac_str << replacement_mac;
-    }
-  }
-
-  // One last bit of data might still be in the input.
-  result << input;
-
-  // We'll just assign right back to kernel_dump.
-  *kernel_dump = result.str();
-}
-
-bool KernelCollector::DumpDirMounted() {
-  struct stat st_parent;
-  if (stat(kDumpParentPath, &st_parent)) {
-    PLOG(WARNING) << "Could not stat " << kDumpParentPath;
-    return false;
-  }
-
-  struct stat st_dump;
-  if (stat(kDumpPath, &st_dump)) {
-    PLOG(WARNING) << "Could not stat " << kDumpPath;
-    return false;
-  }
-
-  if (st_parent.st_dev == st_dump.st_dev) {
-    LOG(WARNING) << "Dump dir " << kDumpPath << " not mounted";
-    return false;
-  }
-
-  return true;
-}
-
-bool KernelCollector::Enable() {
-  if (arch_ == kArchUnknown || arch_ >= kArchCount ||
-      kPCRegex[arch_] == nullptr) {
-    LOG(WARNING) << "KernelCollector does not understand this architecture";
-    return false;
-  }
-
-  if (!DumpDirMounted()) {
-    LOG(WARNING) << "Kernel does not support crash dumping";
-    return false;
-  }
-
-  // To enable crashes, we will eventually need to set
-  // the chnv bit in BIOS, but it does not yet work.
-  LOG(INFO) << "Enabling kernel crash handling";
-  is_enabled_ = true;
-  return true;
-}
-
-// Hash a string to a number.  We define our own hash function to not
-// be dependent on a C++ library that might change.  This function
-// uses basically the same approach as tr1/functional_hash.h but with
-// a larger prime number (16127 vs 131).
-static unsigned HashString(const std::string &input) {
-  unsigned hash = 0;
-  for (size_t i = 0; i < input.length(); ++i)
-    hash = hash * 16127 + input[i];
-  return hash;
-}
-
-void KernelCollector::ProcessStackTrace(
-    pcrecpp::StringPiece kernel_dump,
-    bool print_diagnostics,
-    unsigned *hash,
-    float *last_stack_timestamp,
-    bool *is_watchdog_crash) {
-  pcrecpp::RE line_re("(.+)", pcrecpp::MULTILINE());
-  pcrecpp::RE stack_trace_start_re(std::string(kTimestampRegex) +
-        " (Call Trace|Backtrace):$");
-
-  // Match lines such as the following and grab out "function_name".
-  // The ? may or may not be present.
-  //
-  // For ARM:
-  // <4>[ 3498.731164] [<c0057220>] ? (function_name+0x20/0x2c) from
-  // [<c018062c>] (foo_bar+0xdc/0x1bc)
-  //
-  // For MIPS:
-  // <5>[ 3378.656000] [<804010f0>] lkdtm_do_action+0x68/0x3f8
-  //
-  // For X86:
-  // <4>[ 6066.849504]  [<7937bcee>] ? function_name+0x66/0x6c
-  //
-  pcrecpp::RE stack_entry_re(std::string(kTimestampRegex) +
-    "\\s+\\[<[[:xdigit:]]+>\\]"      // Matches "  [<7937bcee>]"
-    "([\\s\\?(]+)"                   // Matches " ? (" (ARM) or " ? " (X86)
-    "([^\\+ )]+)");                  // Matches until delimiter reached
-  std::string line;
-  std::string hashable;
-  std::string previous_hashable;
-  bool is_watchdog = false;
-
-  *hash = 0;
-  *last_stack_timestamp = 0;
-
-  // Find the last and second-to-last stack traces.  The latter is used when
-  // the panic is from a watchdog timeout.
-  while (line_re.FindAndConsume(&kernel_dump, &line)) {
-    std::string certainty;
-    std::string function_name;
-    if (stack_trace_start_re.PartialMatch(line, last_stack_timestamp)) {
-      if (print_diagnostics) {
-        printf("Stack trace starting.%s\n",
-               hashable.empty() ? "" : "  Saving prior trace.");
-      }
-      previous_hashable = hashable;
-      hashable.clear();
-      is_watchdog = false;
-    } else if (stack_entry_re.PartialMatch(line,
-                                           last_stack_timestamp,
-                                           &certainty,
-                                           &function_name)) {
-      bool is_certain = certainty.find('?') == std::string::npos;
-      if (print_diagnostics) {
-        printf("@%f: stack entry for %s (%s)\n",
-               *last_stack_timestamp,
-               function_name.c_str(),
-               is_certain ? "certain" : "uncertain");
-      }
-      // Do not include any uncertain (prefixed by '?') frames in our hash.
-      if (!is_certain)
-        continue;
-      if (!hashable.empty())
-        hashable.append("|");
-      if (function_name == "watchdog_timer_fn" ||
-          function_name == "watchdog") {
-        is_watchdog = true;
-      }
-      hashable.append(function_name);
-    }
-  }
-
-  // If the last stack trace contains a watchdog function we assume the panic
-  // is from the watchdog timer, and we hash the previous stack trace rather
-  // than the last one, assuming that the previous stack is that of the hung
-  // thread.
-  //
-  // In addition, if the hashable is empty (meaning all frames are uncertain,
-  // for whatever reason) also use the previous frame, as it cannot be any
-  // worse.
-  if (is_watchdog || hashable.empty()) {
-    hashable = previous_hashable;
-  }
-
-  *hash = HashString(hashable);
-  *is_watchdog_crash = is_watchdog;
-
-  if (print_diagnostics) {
-    printf("Hash based on stack trace: \"%s\" at %f.\n",
-           hashable.c_str(), *last_stack_timestamp);
-  }
-}
-
-// static
-KernelCollector::ArchKind KernelCollector::GetCompilerArch() {
-#if defined(COMPILER_GCC) && defined(ARCH_CPU_ARM_FAMILY)
-  return kArchArm;
-#elif defined(COMPILER_GCC) && defined(ARCH_CPU_MIPS_FAMILY)
-  return kArchMips;
-#elif defined(COMPILER_GCC) && defined(ARCH_CPU_X86_64)
-  return kArchX86_64;
-#elif defined(COMPILER_GCC) && defined(ARCH_CPU_X86_FAMILY)
-  return kArchX86;
-#else
-  return kArchUnknown;
-#endif
-}
-
-bool KernelCollector::FindCrashingFunction(
-  pcrecpp::StringPiece kernel_dump,
-  bool print_diagnostics,
-  float stack_trace_timestamp,
-  std::string *crashing_function) {
-  float timestamp = 0;
-
-  // Use the correct regex for this architecture.
-  pcrecpp::RE eip_re(std::string(kTimestampRegex) + kPCRegex[arch_],
-                     pcrecpp::MULTILINE());
-
-  while (eip_re.FindAndConsume(&kernel_dump, &timestamp, crashing_function)) {
-    if (print_diagnostics) {
-      printf("@%f: found crashing function %s\n",
-             timestamp,
-             crashing_function->c_str());
-    }
-  }
-  if (timestamp == 0) {
-    if (print_diagnostics) {
-      printf("Found no crashing function.\n");
-    }
-    return false;
-  }
-  if (stack_trace_timestamp != 0 &&
-      abs(static_cast<int>(stack_trace_timestamp - timestamp))
-        > kSignatureTimestampWindow) {
-    if (print_diagnostics) {
-      printf("Found crashing function but not within window.\n");
-    }
-    return false;
-  }
-  if (print_diagnostics) {
-    printf("Found crashing function %s\n", crashing_function->c_str());
-  }
-  return true;
-}
-
-bool KernelCollector::FindPanicMessage(pcrecpp::StringPiece kernel_dump,
-                                       bool print_diagnostics,
-                                       std::string *panic_message) {
-  // Match lines such as the following and grab out "Fatal exception"
-  // <0>[  342.841135] Kernel panic - not syncing: Fatal exception
-  pcrecpp::RE kernel_panic_re(std::string(kTimestampRegex) +
-                              " Kernel panic[^\\:]*\\:\\s*(.*)",
-                              pcrecpp::MULTILINE());
-  float timestamp = 0;
-  while (kernel_panic_re.FindAndConsume(&kernel_dump,
-                                        &timestamp,
-                                        panic_message)) {
-    if (print_diagnostics) {
-      printf("@%f: panic message %s\n",
-             timestamp,
-             panic_message->c_str());
-    }
-  }
-  if (timestamp == 0) {
-    if (print_diagnostics) {
-      printf("Found no panic message.\n");
-    }
-    return false;
-  }
-  return true;
-}
-
-bool KernelCollector::ComputeKernelStackSignature(
-    const std::string &kernel_dump,
-    std::string *kernel_signature,
-    bool print_diagnostics) {
-  unsigned stack_hash = 0;
-  float last_stack_timestamp = 0;
-  std::string human_string;
-  bool is_watchdog_crash;
-
-  ProcessStackTrace(kernel_dump,
-                    print_diagnostics,
-                    &stack_hash,
-                    &last_stack_timestamp,
-                    &is_watchdog_crash);
-
-  if (!FindCrashingFunction(kernel_dump,
-                            print_diagnostics,
-                            last_stack_timestamp,
-                            &human_string)) {
-    if (!FindPanicMessage(kernel_dump, print_diagnostics, &human_string)) {
-      if (print_diagnostics) {
-        printf("Found no human readable string, using empty string.\n");
-      }
-      human_string.clear();
-    }
-  }
-
-  if (human_string.empty() && stack_hash == 0) {
-    if (print_diagnostics) {
-      printf("Found neither a stack nor a human readable string, failing.\n");
-    }
-    return false;
-  }
-
-  human_string = human_string.substr(0, kMaxHumanStringLength);
-  *kernel_signature = StringPrintf("%s-%s%s-%08X",
-                                   kKernelExecName,
-                                   (is_watchdog_crash ? "(HANG)-" : ""),
-                                   human_string.c_str(),
-                                   stack_hash);
-  return true;
-}
-
-bool KernelCollector::Collect() {
-  std::string kernel_dump;
-  FilePath root_crash_directory;
-
-  if (!LoadParameters()) {
-    return false;
-  }
-  if (!LoadPreservedDump(&kernel_dump)) {
-    return false;
-  }
-  StripSensitiveData(&kernel_dump);
-  if (kernel_dump.empty()) {
-    return false;
-  }
-  std::string signature;
-  if (!ComputeKernelStackSignature(kernel_dump, &signature, false)) {
-    signature = kDefaultKernelStackSignature;
-  }
-
-  std::string reason = "handling";
-  bool feedback = true;
-  if (IsDeveloperImage()) {
-    reason = "developer build - always dumping";
-    feedback = true;
-  } else if (!is_feedback_allowed_function_()) {
-    reason = "ignoring - no consent";
-    feedback = false;
-  }
-
-  LOG(INFO) << "Received prior crash notification from "
-            << "kernel (signature " << signature << ") (" << reason << ")";
-
-  if (feedback) {
-    count_crash_function_();
-
-    if (!GetCreatedCrashDirectoryByEuid(kRootUid,
-                                        &root_crash_directory,
-                                        nullptr)) {
-      return true;
-    }
-
-    std::string dump_basename =
-        FormatDumpBasename(kKernelExecName, time(nullptr), kKernelPid);
-    FilePath kernel_crash_path = root_crash_directory.Append(
-        StringPrintf("%s.kcrash", dump_basename.c_str()));
-
-    // We must use WriteNewFile instead of base::WriteFile as we
-    // do not want to write with root access to a symlink that an attacker
-    // might have created.
-    if (WriteNewFile(kernel_crash_path,
-                     kernel_dump.data(),
-                     kernel_dump.length()) !=
-        static_cast<int>(kernel_dump.length())) {
-      LOG(INFO) << "Failed to write kernel dump to "
-                << kernel_crash_path.value().c_str();
-      return true;
-    }
-
-    AddCrashMetaData(kKernelSignatureKey, signature);
-    WriteCrashMetaData(
-        root_crash_directory.Append(
-            StringPrintf("%s.meta", dump_basename.c_str())),
-        kKernelExecName,
-        kernel_crash_path.value());
-
-    LOG(INFO) << "Stored kcrash to " << kernel_crash_path.value();
-  }
-
-  return true;
-}
diff --git a/crash_reporter/kernel_collector.h b/crash_reporter/kernel_collector.h
deleted file mode 100644
index 206ee26..0000000
--- a/crash_reporter/kernel_collector.h
+++ /dev/null
@@ -1,123 +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 CRASH_REPORTER_KERNEL_COLLECTOR_H_
-#define CRASH_REPORTER_KERNEL_COLLECTOR_H_
-
-#include <pcrecpp.h>
-
-#include <string>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "crash_collector.h"
-
-// Kernel crash collector.
-class KernelCollector : public CrashCollector {
- public:
-  // Enumeration to specify architecture type.
-  enum ArchKind {
-    kArchUnknown,
-    kArchArm,
-    kArchMips,
-    kArchX86,
-    kArchX86_64,
-
-    kArchCount  // Number of architectures.
-  };
-
-  KernelCollector();
-
-  ~KernelCollector() override;
-
-  void OverridePreservedDumpPath(const base::FilePath &file_path);
-
-  // Enable collection.
-  bool Enable();
-
-  // Returns true if the kernel collection currently enabled.
-  bool is_enabled() const { return is_enabled_; }
-
-  // Collect any preserved kernel crash dump. Returns true if there was
-  // a dump (even if there were problems storing the dump), false otherwise.
-  bool Collect();
-
-  // Compute a stack signature string from a kernel dump.
-  bool ComputeKernelStackSignature(const std::string &kernel_dump,
-                                   std::string *kernel_signature,
-                                   bool print_diagnostics);
-
-  // Set the architecture of the crash dumps we are looking at.
-  void set_arch(ArchKind arch) { arch_ = arch; }
-  ArchKind arch() const { return arch_; }
-
- private:
-  friend class KernelCollectorTest;
-  FRIEND_TEST(KernelCollectorTest, LoadPreservedDump);
-  FRIEND_TEST(KernelCollectorTest, StripSensitiveDataBasic);
-  FRIEND_TEST(KernelCollectorTest, StripSensitiveDataBulk);
-  FRIEND_TEST(KernelCollectorTest, StripSensitiveDataSample);
-  FRIEND_TEST(KernelCollectorTest, CollectOK);
-
-  virtual bool DumpDirMounted();
-
-  bool LoadPreservedDump(std::string *contents);
-  void StripSensitiveData(std::string *kernel_dump);
-
-  void GetRamoopsRecordPath(base::FilePath *path, size_t record);
-  bool LoadParameters();
-  bool HasMoreRecords();
-
-  // Read a record to string, modified from file_utils since that didn't
-  // provide a way to restrict the read length.
-  // Return value indicates (only) error state:
-  //  * false when we get an error (can't read from dump location).
-  //  * true if no error occured.
-  // Not finding a valid record is not an error state and is signaled by the
-  // record_found output parameter.
-  bool ReadRecordToString(std::string *contents,
-                          size_t current_record,
-                          bool *record_found);
-
-  void ProcessStackTrace(pcrecpp::StringPiece kernel_dump,
-                         bool print_diagnostics,
-                         unsigned *hash,
-                         float *last_stack_timestamp,
-                         bool *is_watchdog_crash);
-  bool FindCrashingFunction(pcrecpp::StringPiece kernel_dump,
-                            bool print_diagnostics,
-                            float stack_trace_timestamp,
-                            std::string *crashing_function);
-  bool FindPanicMessage(pcrecpp::StringPiece kernel_dump,
-                        bool print_diagnostics,
-                        std::string *panic_message);
-
-  // Returns the architecture kind for which we are built.
-  static ArchKind GetCompilerArch();
-
-  bool is_enabled_;
-  base::FilePath ramoops_dump_path_;
-  size_t records_;
-
-  // The architecture of kernel dump strings we are working with.
-  ArchKind arch_;
-
-  DISALLOW_COPY_AND_ASSIGN(KernelCollector);
-};
-
-#endif  // CRASH_REPORTER_KERNEL_COLLECTOR_H_
diff --git a/crash_reporter/kernel_collector_test.cc b/crash_reporter/kernel_collector_test.cc
deleted file mode 100644
index 015f624..0000000
--- a/crash_reporter/kernel_collector_test.cc
+++ /dev/null
@@ -1,677 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "kernel_collector_test.h"
-
-#include <unistd.h>
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/syslog_logging.h>
-#include <gtest/gtest.h>
-
-using base::FilePath;
-using base::StringPrintf;
-using brillo::FindLog;
-using brillo::GetLog;
-
-namespace {
-
-int s_crashes = 0;
-bool s_metrics = false;
-
-void CountCrash() {
-  ++s_crashes;
-}
-
-bool IsMetrics() {
-  return s_metrics;
-}
-
-}  // namespace
-
-class KernelCollectorTest : public ::testing::Test {
- protected:
-  void WriteStringToFile(const FilePath &file_path,
-                         const char *data) {
-    ASSERT_EQ(strlen(data), base::WriteFile(file_path, data, strlen(data)));
-  }
-
-  void SetUpSuccessfulCollect();
-  void ComputeKernelStackSignatureCommon();
-
-  const FilePath &kcrash_file() const { return test_kcrash_; }
-  const FilePath &test_crash_directory() const { return test_crash_directory_; }
-
-  KernelCollectorMock collector_;
-
- private:
-  void SetUp() override {
-    s_crashes = 0;
-    s_metrics = true;
-
-    EXPECT_CALL(collector_, SetUpDBus()).WillRepeatedly(testing::Return());
-
-    collector_.Initialize(CountCrash, IsMetrics);
-    ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
-    test_kcrash_ = scoped_temp_dir_.path().Append("kcrash");
-    ASSERT_TRUE(base::CreateDirectory(test_kcrash_));
-    collector_.OverridePreservedDumpPath(test_kcrash_);
-
-    test_kcrash_ = test_kcrash_.Append("dmesg-ramoops-0");
-    ASSERT_FALSE(base::PathExists(test_kcrash_));
-
-    test_crash_directory_ = scoped_temp_dir_.path().Append("crash_directory");
-    ASSERT_TRUE(base::CreateDirectory(test_crash_directory_));
-    brillo::ClearLog();
-  }
-
-  FilePath test_kcrash_;
-  FilePath test_crash_directory_;
-  base::ScopedTempDir scoped_temp_dir_;
-};
-
-TEST_F(KernelCollectorTest, ComputeKernelStackSignatureBase) {
-  // Make sure the normal build architecture is detected
-  EXPECT_NE(KernelCollector::kArchUnknown, collector_.arch());
-}
-
-TEST_F(KernelCollectorTest, LoadPreservedDump) {
-  ASSERT_FALSE(base::PathExists(kcrash_file()));
-  std::string dump;
-  dump.clear();
-
-  WriteStringToFile(kcrash_file(),
-      "CrashRecordWithoutRamoopsHeader\n<6>[    0.078852]");
-  ASSERT_TRUE(collector_.LoadParameters());
-  ASSERT_TRUE(collector_.LoadPreservedDump(&dump));
-  ASSERT_EQ("CrashRecordWithoutRamoopsHeader\n<6>[    0.078852]", dump);
-
-  WriteStringToFile(kcrash_file(), "====1.1\nsomething");
-  ASSERT_TRUE(collector_.LoadParameters());
-  ASSERT_TRUE(collector_.LoadPreservedDump(&dump));
-  ASSERT_EQ("something", dump);
-
-  WriteStringToFile(kcrash_file(), "\x01\x02\xfe\xff random blob");
-  ASSERT_TRUE(collector_.LoadParameters());
-  ASSERT_FALSE(collector_.LoadPreservedDump(&dump));
-  ASSERT_EQ("", dump);
-}
-
-TEST_F(KernelCollectorTest, EnableMissingKernel) {
-  ASSERT_FALSE(collector_.Enable());
-  ASSERT_FALSE(collector_.is_enabled());
-  ASSERT_TRUE(FindLog(
-      "Kernel does not support crash dumping"));
-  ASSERT_EQ(s_crashes, 0);
-}
-
-TEST_F(KernelCollectorTest, EnableOK) {
-  WriteStringToFile(kcrash_file(), "");
-  EXPECT_CALL(collector_, DumpDirMounted()).WillOnce(::testing::Return(true));
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(collector_.is_enabled());
-  ASSERT_TRUE(FindLog("Enabling kernel crash handling"));
-  ASSERT_EQ(s_crashes, 0);
-}
-
-TEST_F(KernelCollectorTest, StripSensitiveDataBasic) {
-  // Basic tests of StripSensitiveData...
-
-  // Make sure we work OK with a string w/ no MAC addresses.
-  const std::string kCrashWithNoMacsOrig =
-      "<7>[111566.131728] PM: Entering mem sleep\n";
-  std::string crash_with_no_macs(kCrashWithNoMacsOrig);
-  collector_.StripSensitiveData(&crash_with_no_macs);
-  EXPECT_EQ(kCrashWithNoMacsOrig, crash_with_no_macs);
-
-  // Make sure that we handle the case where there's nothing before/after the
-  // MAC address.
-  const std::string kJustAMacOrig =
-      "11:22:33:44:55:66";
-  const std::string kJustAMacStripped =
-      "00:00:00:00:00:01";
-  std::string just_a_mac(kJustAMacOrig);
-  collector_.StripSensitiveData(&just_a_mac);
-  EXPECT_EQ(kJustAMacStripped, just_a_mac);
-
-  // Test MAC addresses crammed together to make sure it gets both of them.
-  //
-  // I'm not sure that the code does ideal on these two test cases (they don't
-  // look like two MAC addresses to me), but since we don't see them I think
-  // it's OK to behave as shown here.
-  const std::string kCrammedMacs1Orig =
-      "11:22:33:44:55:66:11:22:33:44:55:66";
-  const std::string kCrammedMacs1Stripped =
-      "00:00:00:00:00:01:00:00:00:00:00:01";
-  std::string crammed_macs_1(kCrammedMacs1Orig);
-  collector_.StripSensitiveData(&crammed_macs_1);
-  EXPECT_EQ(kCrammedMacs1Stripped, crammed_macs_1);
-
-  const std::string kCrammedMacs2Orig =
-      "11:22:33:44:55:6611:22:33:44:55:66";
-  const std::string kCrammedMacs2Stripped =
-      "00:00:00:00:00:0100:00:00:00:00:01";
-  std::string crammed_macs_2(kCrammedMacs2Orig);
-  collector_.StripSensitiveData(&crammed_macs_2);
-  EXPECT_EQ(kCrammedMacs2Stripped, crammed_macs_2);
-
-  // Test case-sensitiveness (we shouldn't be case-senstive).
-  const std::string kCapsMacOrig =
-      "AA:BB:CC:DD:EE:FF";
-  const std::string kCapsMacStripped =
-      "00:00:00:00:00:01";
-  std::string caps_mac(kCapsMacOrig);
-  collector_.StripSensitiveData(&caps_mac);
-  EXPECT_EQ(kCapsMacStripped, caps_mac);
-
-  const std::string kLowerMacOrig =
-      "aa:bb:cc:dd:ee:ff";
-  const std::string kLowerMacStripped =
-      "00:00:00:00:00:01";
-  std::string lower_mac(kLowerMacOrig);
-  collector_.StripSensitiveData(&lower_mac);
-  EXPECT_EQ(kLowerMacStripped, lower_mac);
-}
-
-TEST_F(KernelCollectorTest, StripSensitiveDataBulk) {
-  // Test calling StripSensitiveData w/ lots of MAC addresses in the "log".
-
-  // Test that stripping code handles more than 256 unique MAC addresses, since
-  // that overflows past the last byte...
-  // We'll write up some code that generates 258 unique MAC addresses.  Sorta
-  // cheating since the code is very similar to the current code in
-  // StripSensitiveData(), but would catch if someone changed that later.
-  std::string lotsa_macs_orig;
-  std::string lotsa_macs_stripped;
-  int i;
-  for (i = 0; i < 258; i++) {
-    lotsa_macs_orig += StringPrintf(" 11:11:11:11:%02X:%02x",
-                                  (i & 0xff00) >> 8, i & 0x00ff);
-    lotsa_macs_stripped += StringPrintf(" 00:00:00:00:%02X:%02x",
-                                     ((i+1) & 0xff00) >> 8, (i+1) & 0x00ff);
-  }
-  std::string lotsa_macs(lotsa_macs_orig);
-  collector_.StripSensitiveData(&lotsa_macs);
-  EXPECT_EQ(lotsa_macs_stripped, lotsa_macs);
-}
-
-TEST_F(KernelCollectorTest, StripSensitiveDataSample) {
-  // Test calling StripSensitiveData w/ some actual lines from a real crash;
-  // included two MAC addresses (though replaced them with some bogusness).
-  const std::string kCrashWithMacsOrig =
-      "<6>[111567.195339] ata1.00: ACPI cmd ef/10:03:00:00:00:a0 (SET FEATURES)"
-        " filtered out\n"
-      "<7>[108539.540144] wlan0: authenticate with 11:22:33:44:55:66 (try 1)\n"
-      "<7>[108539.554973] wlan0: associate with 11:22:33:44:55:66 (try 1)\n"
-      "<6>[110136.587583] usb0: register 'QCUSBNet2k' at usb-0000:00:1d.7-2,"
-        " QCUSBNet Ethernet Device, 99:88:77:66:55:44\n"
-      "<7>[110964.314648] wlan0: deauthenticated from 11:22:33:44:55:66"
-        " (Reason: 6)\n"
-      "<7>[110964.325057] phy0: Removed STA 11:22:33:44:55:66\n"
-      "<7>[110964.325115] phy0: Destroyed STA 11:22:33:44:55:66\n"
-      "<6>[110969.219172] usb0: register 'QCUSBNet2k' at usb-0000:00:1d.7-2,"
-        " QCUSBNet Ethernet Device, 99:88:77:66:55:44\n"
-      "<7>[111566.131728] PM: Entering mem sleep\n";
-  const std::string kCrashWithMacsStripped =
-      "<6>[111567.195339] ata1.00: ACPI cmd ef/10:03:00:00:00:a0 (SET FEATURES)"
-        " filtered out\n"
-      "<7>[108539.540144] wlan0: authenticate with 00:00:00:00:00:01 (try 1)\n"
-      "<7>[108539.554973] wlan0: associate with 00:00:00:00:00:01 (try 1)\n"
-      "<6>[110136.587583] usb0: register 'QCUSBNet2k' at usb-0000:00:1d.7-2,"
-        " QCUSBNet Ethernet Device, 00:00:00:00:00:02\n"
-      "<7>[110964.314648] wlan0: deauthenticated from 00:00:00:00:00:01"
-        " (Reason: 6)\n"
-      "<7>[110964.325057] phy0: Removed STA 00:00:00:00:00:01\n"
-      "<7>[110964.325115] phy0: Destroyed STA 00:00:00:00:00:01\n"
-      "<6>[110969.219172] usb0: register 'QCUSBNet2k' at usb-0000:00:1d.7-2,"
-        " QCUSBNet Ethernet Device, 00:00:00:00:00:02\n"
-      "<7>[111566.131728] PM: Entering mem sleep\n";
-  std::string crash_with_macs(kCrashWithMacsOrig);
-  collector_.StripSensitiveData(&crash_with_macs);
-  EXPECT_EQ(kCrashWithMacsStripped, crash_with_macs);
-}
-
-TEST_F(KernelCollectorTest, CollectPreservedFileMissing) {
-  ASSERT_FALSE(collector_.Collect());
-  ASSERT_FALSE(FindLog("Stored kcrash to "));
-  ASSERT_EQ(0, s_crashes);
-}
-
-void KernelCollectorTest::SetUpSuccessfulCollect() {
-  collector_.ForceCrashDirectory(test_crash_directory());
-  WriteStringToFile(kcrash_file(), "====1.1\nsomething");
-  ASSERT_EQ(0, s_crashes);
-}
-
-TEST_F(KernelCollectorTest, CollectOptedOut) {
-  SetUpSuccessfulCollect();
-  s_metrics = false;
-  ASSERT_TRUE(collector_.Collect());
-  ASSERT_TRUE(FindLog("(ignoring - no consent)"));
-  ASSERT_EQ(0, s_crashes);
-}
-
-TEST_F(KernelCollectorTest, CollectOK) {
-  SetUpSuccessfulCollect();
-  ASSERT_TRUE(collector_.Collect());
-  ASSERT_EQ(1, s_crashes);
-  ASSERT_TRUE(FindLog("(handling)"));
-  static const char kNamePrefix[] = "Stored kcrash to ";
-  std::string log = brillo::GetLog();
-  size_t pos = log.find(kNamePrefix);
-  ASSERT_NE(std::string::npos, pos)
-      << "Did not find string \"" << kNamePrefix << "\" in log: {\n"
-      << log << "}";
-  pos += strlen(kNamePrefix);
-  std::string filename = log.substr(pos, std::string::npos);
-  // Take the name up until \n
-  size_t end_pos = filename.find_first_of("\n");
-  ASSERT_NE(std::string::npos, end_pos);
-  filename = filename.substr(0, end_pos);
-  ASSERT_EQ(0, filename.find(test_crash_directory().value()));
-  ASSERT_TRUE(base::PathExists(FilePath(filename)));
-  std::string contents;
-  ASSERT_TRUE(base::ReadFileToString(FilePath(filename), &contents));
-  ASSERT_EQ("something", contents);
-}
-
-// Perform tests which are common across architectures
-void KernelCollectorTest::ComputeKernelStackSignatureCommon() {
-  std::string signature;
-
-  const char kStackButNoPC[] =
-      "<4>[ 6066.829029]  [<790340af>] __do_softirq+0xa6/0x143\n";
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kStackButNoPC, &signature, false));
-  EXPECT_EQ("kernel--83615F0A", signature);
-
-  const char kMissingEverything[] =
-      "<4>[ 6066.829029]  [<790340af>] ? __do_softirq+0xa6/0x143\n";
-  EXPECT_FALSE(
-      collector_.ComputeKernelStackSignature(kMissingEverything,
-                                             &signature,
-                                             false));
-
-  // Long message.
-  const char kTruncatedMessage[] =
-      "<0>[   87.485611] Kernel panic - not syncing: 01234567890123456789"
-          "01234567890123456789X\n";
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kTruncatedMessage,
-                                             &signature,
-                                             false));
-  EXPECT_EQ("kernel-0123456789012345678901234567890123456789-00000000",
-            signature);
-}
-
-TEST_F(KernelCollectorTest, ComputeKernelStackSignatureARM) {
-  const char kBugToPanic[] =
-      "<5>[  123.412524] Modules linked in:\n"
-      "<5>[  123.412534] CPU: 0    Tainted: G        W    "
-          "(2.6.37-01030-g51cee64 #153)\n"
-      "<5>[  123.412552] PC is at write_breakme+0xd0/0x1b4\n"
-      "<5>[  123.412560] LR is at write_breakme+0xc8/0x1b4\n"
-      "<5>[  123.412569] pc : [<c0058220>]    lr : [<c005821c>]    "
-          "psr: 60000013\n"
-      "<5>[  123.412574] sp : f4e0ded8  ip : c04d104c  fp : 000e45e0\n"
-      "<5>[  123.412581] r10: 400ff000  r9 : f4e0c000  r8 : 00000004\n"
-      "<5>[  123.412589] r7 : f4e0df80  r6 : f4820c80  r5 : 00000004  "
-          "r4 : f4e0dee8\n"
-      "<5>[  123.412598] r3 : 00000000  r2 : f4e0decc  r1 : c05f88a9  "
-          "r0 : 00000039\n"
-      "<5>[  123.412608] Flags: nZCv  IRQs on  FIQs on  Mode SVC_32  ISA "
-          "ARM  Segment user\n"
-      "<5>[  123.412617] Control: 10c53c7d  Table: 34dcc04a  DAC: 00000015\n"
-      "<0>[  123.412626] Process bash (pid: 1014, stack limit = 0xf4e0c2f8)\n"
-      "<0>[  123.412634] Stack: (0xf4e0ded8 to 0xf4e0e000)\n"
-      "<0>[  123.412641] dec0:                                              "
-          "         f4e0dee8 c0183678\n"
-      "<0>[  123.412654] dee0: 00000000 00000000 00677562 0000081f c06a6a78 "
-          "400ff000 f4e0dfb0 00000000\n"
-      "<0>[  123.412666] df00: bec7ab44 000b1719 bec7ab0c c004f498 bec7a314 "
-          "c024acc8 00000001 c018359c\n"
-      "<0>[  123.412679] df20: f4e0df34 c04d10fc f5803c80 271beb39 000e45e0 "
-          "f5803c80 c018359c c017bfe0\n"
-      "<0>[  123.412691] df40: 00000004 f4820c80 400ff000 f4e0df80 00000004 "
-          "f4e0c000 00000000 c01383e4\n"
-      "<0>[  123.412703] df60: f4820c80 400ff000 f4820c80 400ff000 00000000 "
-          "00000000 00000004 c0138578\n"
-      "<0>[  123.412715] df80: 00000000 00000000 00000004 00000000 00000004 "
-          "402f95d0 00000004 00000004\n"
-      "<0>[  123.412727] dfa0: c0054984 c00547c0 00000004 402f95d0 00000001 "
-          "400ff000 00000004 00000000\n"
-      "<0>[  123.412739] dfc0: 00000004 402f95d0 00000004 00000004 400ff000 "
-          "000c194c bec7ab58 000e45e0\n"
-      "<0>[  123.412751] dfe0: 00000000 bec7aad8 40232520 40284e9c 60000010 "
-          "00000001 00000000 00000000\n"
-      "<5>[   39.496577] Backtrace:\n"
-      "<5>[  123.412782] [<c0058220>] (__bug+0x20/0x2c) from [<c0183678>] "
-          "(write_breakme+0xdc/0x1bc)\n"
-      "<5>[  123.412798] [<c0183678>] (write_breakme+0xdc/0x1bc) from "
-          "[<c017bfe0>] (proc_reg_write+0x88/0x9c)\n";
-  std::string signature;
-
-  collector_.set_arch(KernelCollector::kArchArm);
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kBugToPanic, &signature, false));
-  EXPECT_EQ("kernel-write_breakme-97D3E92F", signature);
-
-  ComputeKernelStackSignatureCommon();
-}
-
-TEST_F(KernelCollectorTest, ComputeKernelStackSignatureMIPS) {
-  const char kBugToPanic[] =
-      "<5>[ 3378.472000] lkdtm: Performing direct entry BUG\n"
-      "<5>[ 3378.476000] Kernel bug detected[#1]:\n"
-      "<5>[ 3378.484000] CPU: 0 PID: 185 Comm: dash Not tainted 3.14.0 #1\n"
-      "<5>[ 3378.488000] task: 8fed5220 ti: 8ec4a000 task.ti: 8ec4a000\n"
-      "<5>[ 3378.496000] $ 0   : 00000000 804018b8 804010f0 7785b507\n"
-      "<5>[ 3378.500000] $ 4   : 8061ab64 81204478 81205b20 00000000\n"
-      "<5>[ 3378.508000] $ 8   : 80830000 20746365 72746e65 55422079\n"
-      "<5>[ 3378.512000] $12   : 8ec4be94 000000fc 00000000 00000048\n"
-      "<5>[ 3378.520000] $16   : 00000004 8ef54000 80710000 00000002\n"
-      "<5>[ 3378.528000] $20   : 7765b6d4 00000004 7fffffff 00000002\n"
-      "<5>[ 3378.532000] $24   : 00000001 803dc0dc                  \n"
-      "<5>[ 3378.540000] $28   : 8ec4a000 8ec4be20 7775438d 804018b8\n"
-      "<5>[ 3378.544000] Hi    : 00000000\n"
-      "<5>[ 3378.548000] Lo    : 49bf8080\n"
-      "<5>[ 3378.552000] epc   : 804010f0 lkdtm_do_action+0x68/0x3f8\n"
-      "<5>[ 3378.560000]     Not tainted\n"
-      "<5>[ 3378.564000] ra    : 804018b8 direct_entry+0x110/0x154\n"
-      "<5>[ 3378.568000] Status: 3100dc03 KERNEL EXL IE \n"
-      "<5>[ 3378.572000] Cause : 10800024\n"
-      "<5>[ 3378.576000] PrId  : 0001a120 (MIPS interAptiv (multi))\n"
-      "<5>[ 3378.580000] Modules linked in: uinput cfg80211 nf_conntrack_ipv6 "
-          "nf_defrag_ipv6 ip6table_filter ip6_tables pcnet32 mii fuse "
-          "ppp_async ppp_generic slhc tun\n"
-      "<5>[ 3378.600000] Process dash (pid: 185, threadinfo=8ec4a000, "
-          "task=8fed5220, tls=77632490)\n"
-      "<5>[ 3378.608000] Stack : 00000006 ffffff9c 00000000 00000000 00000000 "
-          "00000000 8083454a 00000022\n"
-      "<5>          7765baa1 00001fee 80710000 8ef54000 8ec4bf08 00000002 "
-          "7765b6d4 00000004\n"
-      "<5>          7fffffff 00000002 7775438d 805e5158 7fffffff 00000002 "
-          "00000000 7785b507\n"
-      "<5>          806a96bc 00000004 8ef54000 8ec4bf08 00000002 804018b8 "
-          "80710000 806a98bc\n"
-      "<5>          00000002 00000020 00000004 8d515600 77756450 00000004 "
-          "8ec4bf08 802377e4\n"
-      "<5>          ...\n"
-      "<5>[ 3378.652000] Call Trace:\n"
-      "<5>[ 3378.656000] [<804010f0>] lkdtm_do_action+0x68/0x3f8\n"
-      "<5>[ 3378.660000] [<804018b8>] direct_entry+0x110/0x154\n"
-      "<5>[ 3378.664000] [<802377e4>] vfs_write+0xe0/0x1bc\n"
-      "<5>[ 3378.672000] [<80237f90>] SyS_write+0x78/0xf8\n"
-      "<5>[ 3378.676000] [<80111888>] handle_sys+0x128/0x14c\n"
-      "<5>[ 3378.680000] \n"
-      "<5>[ 3378.684000] \n"
-      "<5>Code: 3c04806b  0c1793aa  248494f0 <000c000d> 3c04806b  248494fc  "
-          "0c04cc7f  2405017a  08100514 \n"
-      "<5>[ 3378.696000] ---[ end trace 75067432f24bbc93 ]---\n";
-  std::string signature;
-
-  collector_.set_arch(KernelCollector::kArchMips);
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kBugToPanic, &signature, false));
-  EXPECT_EQ("kernel-lkdtm_do_action-5E600A6B", signature);
-
-  ComputeKernelStackSignatureCommon();
-}
-
-TEST_F(KernelCollectorTest, ComputeKernelStackSignatureX86) {
-  const char kBugToPanic[] =
-      "<4>[ 6066.829029]  [<79039d16>] ? run_timer_softirq+0x165/0x1e6\n"
-      "<4>[ 6066.829029]  [<790340af>] ignore_old_stack+0xa6/0x143\n"
-      "<0>[ 6066.829029] EIP: [<b82d7c15>] ieee80211_stop_tx_ba_session+"
-          "0xa3/0xb5 [mac80211] SS:ESP 0068:7951febc\n"
-      "<0>[ 6066.829029] CR2: 00000000323038a7\n"
-      "<4>[ 6066.845422] ---[ end trace 12b058bb46c43500 ]---\n"
-      "<0>[ 6066.845747] Kernel panic - not syncing: Fatal exception "
-          "in interrupt\n"
-      "<0>[ 6066.846902] Call Trace:\n"
-      "<4>[ 6066.846902]  [<7937a07b>] ? printk+0x14/0x19\n"
-      "<4>[ 6066.949779]  [<79379fc1>] panic+0x3e/0xe4\n"
-      "<4>[ 6066.949971]  [<7937c5c5>] oops_end+0x73/0x81\n"
-      "<4>[ 6066.950208]  [<7901b260>] no_context+0x10d/0x117\n";
-  std::string signature;
-
-  collector_.set_arch(KernelCollector::kArchX86);
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kBugToPanic, &signature, false));
-  EXPECT_EQ("kernel-ieee80211_stop_tx_ba_session-DE253569", signature);
-
-  const char kPCButNoStack[] =
-      "<0>[ 6066.829029] EIP: [<b82d7c15>] ieee80211_stop_tx_ba_session+";
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kPCButNoStack, &signature, false));
-  EXPECT_EQ("kernel-ieee80211_stop_tx_ba_session-00000000", signature);
-
-  const char kBreakmeBug[] =
-      "<4>[  180.492137]  [<790970c6>] ? handle_mm_fault+0x67f/0x96d\n"
-      "<4>[  180.492137]  [<790dcdfe>] ? proc_reg_write+0x5f/0x73\n"
-      "<4>[  180.492137]  [<790e2224>] ? write_breakme+0x0/0x108\n"
-      "<4>[  180.492137]  [<790dcd9f>] ? proc_reg_write+0x0/0x73\n"
-      "<4>[  180.492137]  [<790ac0aa>] vfs_write+0x85/0xe4\n"
-      "<0>[  180.492137] Code: c6 44 05 b2 00 89 d8 e8 0c ef 09 00 85 c0 75 "
-      "0b c7 00 00 00 00 00 e9 8e 00 00 00 ba e6 75 4b 79 89 d8 e8 f1 ee 09 "
-      "00 85 c0 75 04 <0f> 0b eb fe ba 58 47 49 79 89 d8 e8 dd ee 09 00 85 "
-      "c0 75 0a 68\n"
-      "<0>[  180.492137] EIP: [<790e22a4>] write_breakme+0x80/0x108 SS:ESP "
-          "0068:aa3e9efc\n"
-      "<4>[  180.501800] ---[ end trace 2a6b72965e1b1523 ]---\n"
-      "<0>[  180.502026] Kernel panic - not syncing: Fatal exception\n"
-      "<4>[  180.502026] Call Trace:\n"
-      "<4>[  180.502806]  [<79379aba>] ? printk+0x14/0x1a\n"
-      "<4>[  180.503033]  [<79379a00>] panic+0x3e/0xe4\n"
-      "<4>[  180.503287]  [<7937c005>] oops_end+0x73/0x81\n"
-      "<4>[  180.503520]  [<790055dd>] die+0x58/0x5e\n"
-      "<4>[  180.503538]  [<7937b96c>] do_trap+0x8e/0xa7\n"
-      "<4>[  180.503555]  [<79003d70>] ? do_invalid_op+0x0/0x80\n";
-
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kBreakmeBug, &signature, false));
-  EXPECT_EQ("kernel-write_breakme-122AB3CD", signature);
-
-  const char kPCLineTooOld[] =
-      "<4>[  174.492137]  [<790970c6>] ignored_function+0x67f/0x96d\n"
-      "<4>[  175.492137]  [<790970c6>] ignored_function2+0x67f/0x96d\n"
-      "<0>[  174.492137] EIP: [<790e22a4>] write_breakme+0x80/0x108 SS:ESP "
-          "0068:aa3e9efc\n"
-      "<4>[  180.501800] ---[ end trace 2a6b72965e1b1523 ]---\n"
-      "<4>[  180.502026] Call Trace:\n"
-      "<0>[  180.502026] Kernel panic - not syncing: Fatal exception\n"
-      "<4>[  180.502806]  [<79379aba>] printk+0x14/0x1a\n";
-
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kPCLineTooOld, &signature, false));
-  EXPECT_EQ("kernel-Fatal exception-ED4C84FE", signature);
-
-  // Panic without EIP line.
-  const char kExamplePanicOnly[] =
-      "<0>[   87.485611] Kernel panic - not syncing: Testing panic\n"
-      "<4>[   87.485630] Pid: 2825, comm: bash Tainted: G         "
-          "C 2.6.32.23+drm33.10 #1\n"
-      "<4>[   87.485639] Call Trace:\n"
-      "<4>[   87.485660]  [<8133f71d>] ? printk+0x14/0x17\n"
-      "<4>[   87.485674]  [<8133f663>] panic+0x3e/0xe4\n"
-      "<4>[   87.485689]  [<810d062e>] write_breakme+0xaa/0x124\n";
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kExamplePanicOnly,
-                                             &signature,
-                                             false));
-  EXPECT_EQ("kernel-Testing panic-E0FC3552", signature);
-
-  // Panic from hung task.
-  const char kHungTaskBreakMe[] =
-      "<3>[  720.459157] INFO: task bash:2287 blocked blah blah\n"
-      "<5>[  720.459282] Call Trace:\n"
-      "<5>[  720.459307]  [<810a457b>] ? __dentry_open+0x186/0x23e\n"
-      "<5>[  720.459323]  [<810b9c71>] ? mntput_no_expire+0x29/0xe2\n"
-      "<5>[  720.459336]  [<810b9d48>] ? mntput+0x1e/0x20\n"
-      "<5>[  720.459350]  [<810ad135>] ? path_put+0x1a/0x1d\n"
-      "<5>[  720.459366]  [<8137cacc>] schedule+0x4d/0x4f\n"
-      "<5>[  720.459379]  [<8137ccfb>] schedule_timeout+0x26/0xaf\n"
-      "<5>[  720.459394]  [<8102127e>] ? should_resched+0xd/0x27\n"
-      "<5>[  720.459409]  [<81174d1f>] ? _copy_from_user+0x3c/0x50\n"
-      "<5>[  720.459423]  [<8137cd9e>] "
-      "schedule_timeout_uninterruptible+0x1a/0x1c\n"
-      "<5>[  720.459438]  [<810dee63>] write_breakme+0xb3/0x178\n"
-      "<5>[  720.459453]  [<810dedb0>] ? meminfo_proc_show+0x2f2/0x2f2\n"
-      "<5>[  720.459467]  [<810d94ae>] proc_reg_write+0x6d/0x87\n"
-      "<5>[  720.459481]  [<810d9441>] ? proc_reg_poll+0x76/0x76\n"
-      "<5>[  720.459493]  [<810a5e9e>] vfs_write+0x79/0xa5\n"
-      "<5>[  720.459505]  [<810a6011>] sys_write+0x40/0x65\n"
-      "<5>[  720.459519]  [<8137e677>] sysenter_do_call+0x12/0x26\n"
-      "<0>[  720.459530] Kernel panic - not syncing: hung_task: blocked tasks\n"
-      "<5>[  720.459768] Pid: 31, comm: khungtaskd Tainted: "
-      "G         C  3.0.8 #1\n"
-      "<5>[  720.459998] Call Trace:\n"
-      "<5>[  720.460140]  [<81378a35>] panic+0x53/0x14a\n"
-      "<5>[  720.460312]  [<8105f875>] watchdog+0x15b/0x1a0\n"
-      "<5>[  720.460495]  [<8105f71a>] ? hung_task_panic+0x16/0x16\n"
-      "<5>[  720.460693]  [<81043af3>] kthread+0x67/0x6c\n"
-      "<5>[  720.460862]  [<81043a8c>] ? __init_kthread_worker+0x2d/0x2d\n"
-      "<5>[  720.461106]  [<8137eb9e>] kernel_thread_helper+0x6/0x10\n";
-
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kHungTaskBreakMe,
-                                             &signature,
-                                             false));
-
-  EXPECT_EQ("kernel-(HANG)-hung_task: blocked tasks-600B37EA", signature);
-
-  // Panic with all question marks in the last stack trace.
-  const char kUncertainStackTrace[] =
-      "<0>[56279.689669] ------------[ cut here ]------------\n"
-      "<2>[56279.689677] kernel BUG at /build/x86-alex/tmp/portage/"
-      "sys-kernel/chromeos-kernel-0.0.1-r516/work/chromeos-kernel-0.0.1/"
-      "kernel/timer.c:844!\n"
-      "<0>[56279.689683] invalid opcode: 0000 [#1] SMP \n"
-      "<0>[56279.689688] last sysfs file: /sys/power/state\n"
-      "<5>[56279.689692] Modules linked in: nls_iso8859_1 nls_cp437 vfat fat "
-      "gobi usbnet tsl2583(C) industrialio(C) snd_hda_codec_realtek "
-      "snd_hda_intel i2c_dev snd_hda_codec snd_hwdep qcserial snd_pcm usb_wwan "
-      "i2c_i801 snd_timer nm10_gpio snd_page_alloc rtc_cmos fuse "
-      "nf_conntrack_ipv6 nf_defrag_ipv6 uvcvideo videodev ip6table_filter "
-      "ath9k ip6_tables ipv6 mac80211 ath9k_common ath9k_hw ath cfg80211 "
-      "xt_mark\n"
-      "<5>[56279.689731] \n"
-      "<5>[56279.689738] Pid: 24607, comm: powerd_suspend Tainted: G        "
-      "WC  2.6.38.3+ #1 SAMSUNG ELECTRONICS CO., LTD. Alex/G100          \n"
-      "<5>[56279.689748] EIP: 0060:[<8103e3ea>] EFLAGS: 00210286 CPU: 3\n"
-      "<5>[56279.689758] EIP is at add_timer+0xd/0x1b\n"
-      "<5>[56279.689762] EAX: f5e00684 EBX: f5e003c0 ECX: 00000002 EDX: "
-      "00200246\n"
-      "<5>[56279.689767] ESI: f5e003c0 EDI: d28bc03c EBP: d2be5e40 ESP: "
-      "d2be5e40\n"
-      "<5>[56279.689772]  DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068\n"
-      "<0>[56279.689778] Process powerd_suspend (pid: 24607, ti=d2be4000 "
-      "task=f5dc9b60 task.ti=d2be4000)\n"
-      "<0>[56279.689782] Stack:\n"
-      "<5>[56279.689785]  d2be5e4c f8dccced f4ac02c0 d2be5e70 f8ddc752 "
-      "f5e003c0 f4ac0458 f4ac092c\n"
-      "<5>[56279.689797]  f4ac043c f4ac02c0 f4ac0000 f4ac007c d2be5e7c "
-      "f8dd4a33 f4ac0164 d2be5e94\n"
-      "<5>[56279.689809]  f87e0304 f69ff0cc f4ac0164 f87e02a4 f4ac0164 "
-      "d2be5eb0 81248968 00000000\n"
-      "<0>[56279.689821] Call Trace:\n"
-      "<5>[56279.689840]  [<f8dccced>] ieee80211_sta_restart+0x25/0x8c "
-      "[mac80211]\n"
-      "<5>[56279.689854]  [<f8ddc752>] ieee80211_reconfig+0x2e9/0x339 "
-      "[mac80211]\n"
-      "<5>[56279.689869]  [<f8dd4a33>] ieee80211_aes_cmac+0x182d/0x184e "
-      "[mac80211]\n"
-      "<5>[56279.689883]  [<f87e0304>] cfg80211_get_dev_from_info+0x29b/0x2c0 "
-      "[cfg80211]\n"
-      "<5>[56279.689895]  [<f87e02a4>] ? "
-      "cfg80211_get_dev_from_info+0x23b/0x2c0 [cfg80211]\n"
-      "<5>[56279.689904]  [<81248968>] legacy_resume+0x25/0x5d\n"
-      "<5>[56279.689910]  [<812490ae>] device_resume+0xdd/0x110\n"
-      "<5>[56279.689917]  [<812491c2>] dpm_resume_end+0xe1/0x271\n"
-      "<5>[56279.689925]  [<81060481>] suspend_devices_and_enter+0x18b/0x1de\n"
-      "<5>[56279.689932]  [<810605ba>] enter_state+0xe6/0x132\n"
-      "<5>[56279.689939]  [<8105fd4b>] state_store+0x91/0x9d\n"
-      "<5>[56279.689945]  [<8105fcba>] ? state_store+0x0/0x9d\n"
-      "<5>[56279.689953]  [<81178fb1>] kobj_attr_store+0x16/0x22\n"
-      "<5>[56279.689961]  [<810eea5e>] sysfs_write_file+0xc1/0xec\n"
-      "<5>[56279.689969]  [<810af443>] vfs_write+0x8f/0x101\n"
-      "<5>[56279.689975]  [<810ee99d>] ? sysfs_write_file+0x0/0xec\n"
-      "<5>[56279.689982]  [<810af556>] sys_write+0x40/0x65\n"
-      "<5>[56279.689989]  [<81002d57>] sysenter_do_call+0x12/0x26\n"
-      "<0>[56279.689993] Code: c1 d3 e2 4a 89 55 f4 f7 d2 21 f2 6a 00 31 c9 89 "
-      "d8 e8 6e fd ff ff 5a 8d 65 f8 5b 5e 5d c3 55 89 e5 3e 8d 74 26 00 83 38 "
-      "00 74 04 <0f> 0b eb fe 8b 50 08 e8 6f ff ff ff 5d c3 55 89 e5 3e 8d 74 "
-      "26 \n"
-      "<0>[56279.690009] EIP: [<8103e3ea>] add_timer+0xd/0x1b SS:ESP "
-      "0068:d2be5e40\n"
-      "<4>[56279.690113] ---[ end trace b71141bb67c6032a ]---\n"
-      "<7>[56279.694069] wlan0: deauthenticated from 00:00:00:00:00:01 "
-      "(Reason: 6)\n"
-      "<0>[56279.703465] Kernel panic - not syncing: Fatal exception\n"
-      "<5>[56279.703471] Pid: 24607, comm: powerd_suspend Tainted: G      D "
-      "WC  2.6.38.3+ #1\n"
-      "<5>[56279.703475] Call Trace:\n"
-      "<5>[56279.703483]  [<8136648c>] ? panic+0x55/0x152\n"
-      "<5>[56279.703491]  [<810057fa>] ? oops_end+0x73/0x81\n"
-      "<5>[56279.703497]  [<81005a44>] ? die+0xed/0xf5\n"
-      "<5>[56279.703503]  [<810033cb>] ? do_trap+0x7a/0x80\n"
-      "<5>[56279.703509]  [<8100369b>] ? do_invalid_op+0x0/0x80\n"
-      "<5>[56279.703515]  [<81003711>] ? do_invalid_op+0x76/0x80\n"
-      "<5>[56279.703522]  [<8103e3ea>] ? add_timer+0xd/0x1b\n"
-      "<5>[56279.703529]  [<81025e23>] ? check_preempt_curr+0x2e/0x69\n"
-      "<5>[56279.703536]  [<8102ef28>] ? ttwu_post_activation+0x5a/0x11b\n"
-      "<5>[56279.703543]  [<8102fa8d>] ? try_to_wake_up+0x213/0x21d\n"
-      "<5>[56279.703550]  [<81368b7f>] ? error_code+0x67/0x6c\n"
-      "<5>[56279.703557]  [<8103e3ea>] ? add_timer+0xd/0x1b\n"
-      "<5>[56279.703577]  [<f8dccced>] ? ieee80211_sta_restart+0x25/0x8c "
-      "[mac80211]\n"
-      "<5>[56279.703591]  [<f8ddc752>] ? ieee80211_reconfig+0x2e9/0x339 "
-      "[mac80211]\n"
-      "<5>[56279.703605]  [<f8dd4a33>] ? ieee80211_aes_cmac+0x182d/0x184e "
-      "[mac80211]\n"
-      "<5>[56279.703618]  [<f87e0304>] ? "
-      "cfg80211_get_dev_from_info+0x29b/0x2c0 [cfg80211]\n"
-      "<5>[56279.703630]  [<f87e02a4>] ? "
-      "cfg80211_get_dev_from_info+0x23b/0x2c0 [cfg80211]\n"
-      "<5>[56279.703637]  [<81248968>] ? legacy_resume+0x25/0x5d\n"
-      "<5>[56279.703643]  [<812490ae>] ? device_resume+0xdd/0x110\n"
-      "<5>[56279.703649]  [<812491c2>] ? dpm_resume_end+0xe1/0x271\n"
-      "<5>[56279.703657]  [<81060481>] ? "
-      "suspend_devices_and_enter+0x18b/0x1de\n"
-      "<5>[56279.703663]  [<810605ba>] ? enter_state+0xe6/0x132\n"
-      "<5>[56279.703670]  [<8105fd4b>] ? state_store+0x91/0x9d\n"
-      "<5>[56279.703676]  [<8105fcba>] ? state_store+0x0/0x9d\n"
-      "<5>[56279.703683]  [<81178fb1>] ? kobj_attr_store+0x16/0x22\n"
-      "<5>[56279.703690]  [<810eea5e>] ? sysfs_write_file+0xc1/0xec\n"
-      "<5>[56279.703697]  [<810af443>] ? vfs_write+0x8f/0x101\n"
-      "<5>[56279.703703]  [<810ee99d>] ? sysfs_write_file+0x0/0xec\n"
-      "<5>[56279.703709]  [<810af556>] ? sys_write+0x40/0x65\n"
-      "<5>[56279.703716]  [<81002d57>] ? sysenter_do_call+0x12/0x26\n";
-
-  EXPECT_TRUE(
-      collector_.ComputeKernelStackSignature(kUncertainStackTrace,
-                                             &signature,
-                                             false));
-  // The first trace contains only uncertain entries and its hash is 00000000,
-  // so, if we used that, the signature would be kernel-add_timer-00000000.
-  // Instead we use the second-to-last trace for the hash.
-  EXPECT_EQ("kernel-add_timer-B5178878", signature);
-
-  ComputeKernelStackSignatureCommon();
-}
diff --git a/crash_reporter/kernel_collector_test.h b/crash_reporter/kernel_collector_test.h
deleted file mode 100644
index f689e7d..0000000
--- a/crash_reporter/kernel_collector_test.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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 CRASH_REPORTER_KERNEL_COLLECTOR_TEST_H_
-#define CRASH_REPORTER_KERNEL_COLLECTOR_TEST_H_
-
-#include "kernel_collector.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-class KernelCollectorMock : public KernelCollector {
- public:
-  MOCK_METHOD0(DumpDirMounted, bool());
-  MOCK_METHOD0(SetUpDBus, void());
-};
-
-#endif  // CRASH_REPORTER_KERNEL_COLLECTOR_TEST_H_
diff --git a/crash_reporter/kernel_log_collector.sh b/crash_reporter/kernel_log_collector.sh
deleted file mode 100644
index 82512c2..0000000
--- a/crash_reporter/kernel_log_collector.sh
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/bin/sh
-
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Usage example: "kernel_log_collector.sh XXX YYY"
-# This script searches logs in the /var/log/messages which have the keyword XXX.
-# And only those logs which are within the last YYY seconds of the latest log
-# that has the keyword XXX are printed.
-
-# Kernel log has the possible formats:
-# 2013-06-14T16:31:40.514513-07:00 localhost kernel: [    2.682472] MSG MSG ...
-# 2013-06-19T20:38:58.661826+00:00 localhost kernel: [    1.668092] MSG MSG ...
-
-search_key=$1
-time_duration=$2
-msg_pattern="^[0-9-]*T[0-9:.+-]* localhost kernel"
-
-die() {
-  echo "kernel_log_collector: $*" >&2
-  exit 1
-}
-
-get_timestamp() {
-  timestamp="$(echo $1 | cut -d " " -f 1)"
-  timestamp="$(date -d "${timestamp}" +%s)" || exit $?
-  echo "${timestamp}"
-}
-
-last_line=$(grep "${msg_pattern}" /var/log/messages | grep -- "${search_key}" | tail -n 1)
-
-if [ -n "${last_line}" ]; then
-  if ! allowed_timestamp=$(get_timestamp "${last_line}"); then
-    die "coule not get timestamp from: ${last_line}"
-  fi
-  : $(( allowed_timestamp -= ${time_duration} ))
-  grep "${msg_pattern}" /var/log/messages | grep -- "${search_key}" | while read line; do
-    if ! timestamp=$(get_timestamp "${line}"); then
-      die "could not get timestamp from: ${line}"
-    fi
-    if [ ${timestamp} -gt ${allowed_timestamp} ]; then
-      echo "${line}"
-    fi
-  done
-fi
-
-echo "END-OF-LOG"
-
diff --git a/crash_reporter/kernel_warning_collector.cc b/crash_reporter/kernel_warning_collector.cc
deleted file mode 100644
index e28e8fd..0000000
--- a/crash_reporter/kernel_warning_collector.cc
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "kernel_warning_collector.h"
-
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-
-namespace {
-const char kExecName[] = "kernel-warning";
-const char kKernelWarningSignatureKey[] = "sig";
-const char kKernelWarningPath[] = "/var/run/kwarn/warning";
-const pid_t kKernelPid = 0;
-const uid_t kRootUid = 0;
-}  // namespace
-
-using base::FilePath;
-using base::StringPrintf;
-
-KernelWarningCollector::KernelWarningCollector() {
-}
-
-KernelWarningCollector::~KernelWarningCollector() {
-}
-
-bool KernelWarningCollector::LoadKernelWarning(std::string *content,
-                                               std::string *signature) {
-  FilePath kernel_warning_path(kKernelWarningPath);
-  if (!base::ReadFileToString(kernel_warning_path, content)) {
-    LOG(ERROR) << "Could not open " << kKernelWarningPath;
-    return false;
-  }
-  // The signature is in the first line.
-  std::string::size_type end_position = content->find('\n');
-  if (end_position == std::string::npos) {
-    LOG(ERROR) << "unexpected kernel warning format";
-    return false;
-  }
-  *signature = content->substr(0, end_position);
-  return true;
-}
-
-bool KernelWarningCollector::Collect() {
-  std::string reason = "normal collection";
-  bool feedback = true;
-  if (IsDeveloperImage()) {
-    reason = "always collect from developer builds";
-    feedback = true;
-  } else if (!is_feedback_allowed_function_()) {
-    reason = "no user consent";
-    feedback = false;
-  }
-
-  LOG(INFO) << "Processing kernel warning: " << reason;
-
-  if (!feedback) {
-    return true;
-  }
-
-  std::string kernel_warning;
-  std::string warning_signature;
-  if (!LoadKernelWarning(&kernel_warning, &warning_signature)) {
-    return true;
-  }
-
-  FilePath root_crash_directory;
-  if (!GetCreatedCrashDirectoryByEuid(kRootUid, &root_crash_directory,
-                                      nullptr)) {
-    return true;
-  }
-
-  std::string dump_basename =
-      FormatDumpBasename(kExecName, time(nullptr), kKernelPid);
-  FilePath kernel_crash_path = root_crash_directory.Append(
-      StringPrintf("%s.kcrash", dump_basename.c_str()));
-
-  // We must use WriteNewFile instead of base::WriteFile as we
-  // do not want to write with root access to a symlink that an attacker
-  // might have created.
-  if (WriteNewFile(kernel_crash_path,
-                   kernel_warning.data(),
-                   kernel_warning.length()) !=
-      static_cast<int>(kernel_warning.length())) {
-    LOG(INFO) << "Failed to write kernel warning to "
-              << kernel_crash_path.value().c_str();
-    return true;
-  }
-
-  AddCrashMetaData(kKernelWarningSignatureKey, warning_signature);
-  WriteCrashMetaData(
-      root_crash_directory.Append(
-          StringPrintf("%s.meta", dump_basename.c_str())),
-    kExecName, kernel_crash_path.value());
-
-  LOG(INFO) << "Stored kernel warning into " << kernel_crash_path.value();
-  return true;
-}
diff --git a/crash_reporter/kernel_warning_collector.h b/crash_reporter/kernel_warning_collector.h
deleted file mode 100644
index 5ccb780..0000000
--- a/crash_reporter/kernel_warning_collector.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef CRASH_REPORTER_KERNEL_WARNING_COLLECTOR_H_
-#define CRASH_REPORTER_KERNEL_WARNING_COLLECTOR_H_
-
-#include <string>
-
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "crash_collector.h"
-
-// Kernel warning collector.
-class KernelWarningCollector : public CrashCollector {
- public:
-  KernelWarningCollector();
-
-  ~KernelWarningCollector() override;
-
-  // Collects warning.
-  bool Collect();
-
- private:
-  friend class KernelWarningCollectorTest;
-  FRIEND_TEST(KernelWarningCollectorTest, CollectOK);
-
-  // Reads the full content of the kernel warn dump and its signature.
-  bool LoadKernelWarning(std::string *content, std::string *signature);
-
-  DISALLOW_COPY_AND_ASSIGN(KernelWarningCollector);
-};
-
-#endif  // CRASH_REPORTER_KERNEL_WARNING_COLLECTOR_H_
diff --git a/crash_reporter/list_proxies.cc b/crash_reporter/list_proxies.cc
deleted file mode 100644
index 3374b5f..0000000
--- a/crash_reporter/list_proxies.cc
+++ /dev/null
@@ -1,302 +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 <sysexits.h>
-#include <unistd.h>  // for isatty()
-
-#include <string>
-#include <vector>
-
-#include <base/cancelable_callback.h>
-#include <base/command_line.h>
-#include <base/files/file_util.h>
-#include <base/memory/weak_ptr.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_tokenizer.h>
-#include <base/strings/string_util.h>
-#include <base/values.h>
-#include <brillo/daemons/dbus_daemon.h>
-#include <brillo/syslog_logging.h>
-
-#include "libcrosservice/dbus-proxies.h"
-
-using std::unique_ptr;
-
-namespace {
-
-const char kLibCrosProxyResolvedSignalInterface[] =
-    "org.chromium.CrashReporterLibcrosProxyResolvedInterface";
-const char kLibCrosProxyResolvedName[] = "ProxyResolved";
-const char kLibCrosServiceName[] = "org.chromium.LibCrosService";
-const char kNoProxy[] = "direct://";
-
-const int kTimeoutDefaultSeconds = 5;
-
-const char kHelp[] = "help";
-const char kQuiet[] = "quiet";
-const char kTimeout[] = "timeout";
-const char kVerbose[] = "verbose";
-// Help message to show when the --help command line switch is specified.
-const char kHelpMessage[] =
-    "Chromium OS Crash helper: proxy lister\n"
-    "\n"
-    "Available Switches:\n"
-    "  --quiet      Only print the proxies\n"
-    "  --verbose    Print additional messages even when not run from a TTY\n"
-    "  --timeout=N  Set timeout for browser resolving proxies (default is 5)\n"
-    "  --help       Show this help.\n";
-
-// Copied from src/update_engine/chrome_browser_proxy_resolver.cc
-// Parses the browser's answer for resolved proxies.  It returns a
-// list of strings, each of which is a resolved proxy.
-std::vector<std::string> ParseProxyString(const std::string& input) {
-  std::vector<std::string> ret;
-  // Some of this code taken from
-  // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_server.cc and
-  // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_list.cc
-  base::StringTokenizer entry_tok(input, ";");
-  while (entry_tok.GetNext()) {
-    std::string token = entry_tok.token();
-    base::TrimWhitespaceASCII(token, base::TRIM_ALL, &token);
-
-    // Start by finding the first space (if any).
-    std::string::iterator space;
-    for (space = token.begin(); space != token.end(); ++space) {
-      if (base::IsAsciiWhitespace(*space)) {
-        break;
-      }
-    }
-
-    std::string scheme = base::ToLowerASCII(std::string(token.begin(), space));
-    // Chrome uses "socks" to mean socks4 and "proxy" to mean http.
-    if (scheme == "socks")
-      scheme += "4";
-    else if (scheme == "proxy")
-      scheme = "http";
-    else if (scheme != "https" &&
-             scheme != "socks4" &&
-             scheme != "socks5" &&
-             scheme != "direct")
-      continue;  // Invalid proxy scheme
-
-    std::string host_and_port = std::string(space, token.end());
-    base::TrimWhitespaceASCII(host_and_port, base::TRIM_ALL, &host_and_port);
-    if (scheme != "direct" && host_and_port.empty())
-      continue;  // Must supply host/port when non-direct proxy used.
-    ret.push_back(scheme + "://" + host_and_port);
-  }
-  if (ret.empty() || *ret.rbegin() != kNoProxy)
-    ret.push_back(kNoProxy);
-  return ret;
-}
-
-// A class for interfacing with Chrome to resolve proxies for a given source
-// url.  The class is initialized with the given source url to check, the
-// signal interface and name that Chrome will reply to, and how long to wait
-// for the resolve request to timeout.  Once initialized, the Run() function
-// must be called, which blocks on the D-Bus call to Chrome.  The call returns
-// after either the timeout or the proxy has been resolved.  The resolved
-// proxies can then be accessed through the proxies() function.
-class ProxyResolver : public brillo::DBusDaemon {
- public:
-  ProxyResolver(const std::string& source_url,
-                const std::string& signal_interface,
-                const std::string& signal_name,
-                base::TimeDelta timeout)
-      : source_url_(source_url),
-        signal_interface_(signal_interface),
-        signal_name_(signal_name),
-        timeout_(timeout),
-        weak_ptr_factory_(this),
-        timeout_callback_(base::Bind(&ProxyResolver::HandleBrowserTimeout,
-                                     weak_ptr_factory_.GetWeakPtr())) {}
-
-  ~ProxyResolver() override {}
-
-  const std::vector<std::string>& proxies() {
-    return proxies_;
-  }
-
-  int Run() override {
-    // Add task for if the browser proxy call times out.
-    base::MessageLoop::current()->PostDelayedTask(
-        FROM_HERE,
-        timeout_callback_.callback(),
-        timeout_);
-
-    return brillo::DBusDaemon::Run();
-  }
-
- protected:
-  // If the browser times out, quit the run loop.
-  void HandleBrowserTimeout() {
-    LOG(ERROR) << "Timeout while waiting for browser to resolve proxy";
-    Quit();
-  }
-
-  // If the signal handler connects successfully, call the browser's
-  // ResolveNetworkProxy D-Bus method.  Otherwise, don't do anything and let
-  // the timeout task quit the run loop.
-  void HandleDBusSignalConnected(const std::string& interface,
-                                 const std::string& signal,
-                                 bool success) {
-    if (!success) {
-      LOG(ERROR) << "Could not connect to signal " << interface << "."
-                 << signal;
-      timeout_callback_.Cancel();
-      Quit();
-      return;
-    }
-
-    brillo::ErrorPtr error;
-    call_proxy_->ResolveNetworkProxy(source_url_,
-                                     signal_interface_,
-                                     signal_name_,
-                                     &error);
-
-    if (error) {
-      LOG(ERROR) << "Call to ResolveNetworkProxy failed: "
-                 << error->GetMessage();
-      timeout_callback_.Cancel();
-      Quit();
-    }
-  }
-
-  // Handle incoming ProxyResolved signal.
-  void HandleProxyResolvedSignal(const std::string& source_url,
-                                 const std::string& proxy_info,
-                                 const std::string& error_message) {
-    timeout_callback_.Cancel();
-    proxies_ = ParseProxyString(proxy_info);
-    LOG(INFO) << "Found proxies via browser signal: "
-              << base::JoinString(proxies_, "x");
-
-    Quit();
-  }
-
-  int OnInit() override {
-    int return_code = brillo::DBusDaemon::OnInit();
-    if (return_code != EX_OK)
-      return return_code;
-
-    // Initialize D-Bus proxies.
-    call_proxy_.reset(
-        new org::chromium::LibCrosServiceInterfaceProxy(bus_,
-                                                        kLibCrosServiceName));
-    signal_proxy_.reset(
-        new org::chromium::CrashReporterLibcrosProxyResolvedInterfaceProxy(
-            bus_,
-            kLibCrosServiceName));
-
-    // Set up the D-Bus signal handler.
-    // TODO(crbug.com/446115): Update ResolveNetworkProxy call to use an
-    //     asynchronous return value rather than a return signal.
-    signal_proxy_->RegisterProxyResolvedSignalHandler(
-        base::Bind(&ProxyResolver::HandleProxyResolvedSignal,
-                   weak_ptr_factory_.GetWeakPtr()),
-        base::Bind(&ProxyResolver::HandleDBusSignalConnected,
-                   weak_ptr_factory_.GetWeakPtr()));
-
-    return EX_OK;
-  }
-
- private:
-  unique_ptr<org::chromium::LibCrosServiceInterfaceProxy> call_proxy_;
-  unique_ptr<org::chromium::CrashReporterLibcrosProxyResolvedInterfaceProxy>
-      signal_proxy_;
-
-  const std::string source_url_;
-  const std::string signal_interface_;
-  const std::string signal_name_;
-  base::TimeDelta timeout_;
-
-  std::vector<std::string> proxies_;
-  base::WeakPtrFactory<ProxyResolver> weak_ptr_factory_;
-
-  base::CancelableClosure timeout_callback_;
-
-  DISALLOW_COPY_AND_ASSIGN(ProxyResolver);
-};
-
-static bool ShowBrowserProxies(std::string url, base::TimeDelta timeout) {
-  // Initialize and run the proxy resolver to watch for signals.
-  ProxyResolver resolver(url,
-                         kLibCrosProxyResolvedSignalInterface,
-                         kLibCrosProxyResolvedName,
-                         timeout);
-  resolver.Run();
-
-  std::vector<std::string> proxies = resolver.proxies();
-
-  // If proxies is empty, then the timeout was reached waiting for the proxy
-  // resolved signal.  If no proxies are defined, proxies will be populated
-  // with "direct://".
-  if (proxies.empty())
-    return false;
-
-  for (const auto& proxy : proxies) {
-    printf("%s\n", proxy.c_str());
-  }
-  return true;
-}
-
-}  // namespace
-
-int main(int argc, char *argv[]) {
-  base::CommandLine::Init(argc, argv);
-  base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
-
-  if (cl->HasSwitch(kHelp)) {
-    LOG(INFO) << kHelpMessage;
-    return 0;
-  }
-
-  bool quiet = cl->HasSwitch(kQuiet);
-  bool verbose = cl->HasSwitch(kVerbose);
-
-  int timeout = kTimeoutDefaultSeconds;
-  std::string str_timeout = cl->GetSwitchValueASCII(kTimeout);
-  if (!str_timeout.empty() && !base::StringToInt(str_timeout, &timeout)) {
-    LOG(ERROR) << "Invalid timeout value: " << str_timeout;
-    return 1;
-  }
-
-  // Default to logging to syslog.
-  int init_flags = brillo::kLogToSyslog;
-  // Log to stderr if a TTY (and "-quiet" wasn't passed), or if "-verbose"
-  // was passed.
-
-  if ((!quiet && isatty(STDERR_FILENO)) || verbose)
-    init_flags |= brillo::kLogToStderr;
-  brillo::InitLog(init_flags);
-
-  std::string url;
-  base::CommandLine::StringVector urls = cl->GetArgs();
-  if (!urls.empty()) {
-    url = urls[0];
-    LOG(INFO) << "Resolving proxies for URL: " << url;
-  } else {
-    LOG(INFO) << "Resolving proxies without URL";
-  }
-
-  if (!ShowBrowserProxies(url, base::TimeDelta::FromSeconds(timeout))) {
-    LOG(ERROR) << "Error resolving proxies via the browser";
-    LOG(INFO) << "Assuming direct proxy";
-    printf("%s\n", kNoProxy);
-  }
-
-  return 0;
-}
diff --git a/crash_reporter/periodic_scheduler b/crash_reporter/periodic_scheduler
deleted file mode 100755
index 5408da7..0000000
--- a/crash_reporter/periodic_scheduler
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/system/bin/sh
-
-# 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.
-
-# Run tasks periodically.
-# Usage: $0 <delay_seconds> <timeout_seconds> <task_name> <task_binary>
-#
-# Executes task <task_name> by running <task_binary> every <delay_seconds>.
-
-set -e -u
-
-SCRIPT_NAME="$(basename "$0")"
-CHECK_DELAY=300  # Check every 5 minutes.
-KILL_DELAY=10    # How long to let the job clean up after a timeout.
-# Let the unittests override.
-: ${SPOOL_DIR:=/data/misc/crash_reporter/spool/cron-lite}
-
-loginfo() {
-  log -p i -t "${SCRIPT_NAME}" "$@"
-}
-
-trap "loginfo 'exiting'" EXIT
-
-check_and_fix_spool_paths() {
-  # Avoid weird spool paths if possible.
-  rm -f "$(dirname "${SPOOL_DIR}")" "${SPOOL_DIR}" 2>/dev/null || :
-  mkdir -p "${SPOOL_DIR}"
-  if [ ! -O "${SPOOL_DIR}" -o ! -d "${SPOOL_DIR}" ]; then
-    loginfo "Spool directory is damaged. Aborting!"
-    exit 1
-  fi
-}
-
-main() {
-  local delay="$1"
-  local timeout="$2"
-  local name="$3"
-  local spool_file="${SPOOL_DIR}/${name}"
-  shift 3
-
-  [ -z "${delay}" ] && exit 1
-  [ -z "${timeout}" ] && exit 1
-  [ -z "${name}" ] && exit 1
-  [ $# -eq 0 ] && exit 1
-  check_and_fix_spool_paths
-
-  while true; do
-    # Allow the sleep to be killed manually without terminating the handler.
-    # Send stderr to /dev/null to suppress the shell's "Terminated" message.
-    sleep $(( CHECK_DELAY + KILL_DELAY )) 2>/dev/null || true
-
-    [ ! -e "${spool_file}" ] && touch "${spool_file}"
-
-    local last_rotation="$(stat -c "%Y" "${spool_file}" 2>/dev/null || echo 0)"
-    local now="$(date +%s)"
-    local time_diff=$((now - last_rotation))
-
-    if [ ${time_diff} -gt ${delay} ]; then
-      rm "${spool_file}" || true
-      touch "${spool_file}"
-      loginfo "${name}: running $*"
-      timeout -k ${KILL_DELAY} ${timeout} "$@" || true
-      loginfo "${name}: job completed"
-    fi
-  done
-}
-
-main "$@"
diff --git a/crash_reporter/testrunner.cc b/crash_reporter/testrunner.cc
deleted file mode 100644
index 744cf10..0000000
--- a/crash_reporter/testrunner.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <brillo/test_helpers.h>
-#include <gtest/gtest.h>
-
-int main(int argc, char** argv) {
-  SetUpTests(&argc, argv, true);
-  return RUN_ALL_TESTS();
-}
diff --git a/crash_reporter/udev_collector.cc b/crash_reporter/udev_collector.cc
deleted file mode 100644
index 1e018db..0000000
--- a/crash_reporter/udev_collector.cc
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "udev_collector.h"
-
-#include <map>
-#include <utility>
-#include <vector>
-
-#include <base/files/file_enumerator.h>
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/process.h>
-
-using base::FilePath;
-
-namespace {
-
-const char kCollectUdevSignature[] = "crash_reporter-udev-collection";
-const char kGzipPath[] = "/bin/gzip";
-const char kUdevExecName[] = "udev";
-const char kUdevSignatureKey[] = "sig";
-const char kUdevSubsystemDevCoredump[] = "devcoredump";
-const char kDefaultDevCoredumpDirectory[] = "/sys/class/devcoredump";
-const char kDevCoredumpFilePrefixFormat[] = "devcoredump_%s";
-
-}  // namespace
-
-UdevCollector::UdevCollector()
-    : dev_coredump_directory_(kDefaultDevCoredumpDirectory) {}
-
-UdevCollector::~UdevCollector() {}
-
-bool UdevCollector::HandleCrash(const std::string &udev_event) {
-  if (IsDeveloperImage()) {
-    LOG(INFO) << "developer image - collect udev crash info.";
-  } else if (is_feedback_allowed_function_()) {
-    LOG(INFO) << "Consent given - collect udev crash info.";
-  } else {
-    LOG(INFO) << "Ignoring - Non-developer image and no consent given.";
-    return false;
-  }
-
-  // Process the udev event string.
-  // First get all the key-value pairs.
-  std::vector<std::pair<std::string, std::string>> udev_event_keyval;
-  base::SplitStringIntoKeyValuePairs(udev_event, '=', ':', &udev_event_keyval);
-  std::vector<std::pair<std::string, std::string>>::const_iterator iter;
-  std::map<std::string, std::string> udev_event_map;
-  for (iter = udev_event_keyval.begin();
-       iter != udev_event_keyval.end();
-       ++iter) {
-    udev_event_map[iter->first] = iter->second;
-  }
-
-  // Make sure the crash directory exists, or create it if it doesn't.
-  FilePath crash_directory;
-  if (!GetCreatedCrashDirectoryByEuid(0, &crash_directory, nullptr)) {
-    LOG(ERROR) << "Could not get crash directory.";
-    return false;
-  }
-
-  if (udev_event_map["SUBSYSTEM"] == kUdevSubsystemDevCoredump) {
-    int instance_number;
-    if (!base::StringToInt(udev_event_map["KERNEL_NUMBER"], &instance_number)) {
-      LOG(ERROR) << "Invalid kernel number: "
-                 << udev_event_map["KERNEL_NUMBER"];
-      return false;
-    }
-    return ProcessDevCoredump(crash_directory, instance_number);
-  }
-
-  return ProcessUdevCrashLogs(crash_directory,
-                              udev_event_map["ACTION"],
-                              udev_event_map["KERNEL"],
-                              udev_event_map["SUBSYSTEM"]);
-}
-
-bool UdevCollector::ProcessUdevCrashLogs(const FilePath& crash_directory,
-                                         const std::string& action,
-                                         const std::string& kernel,
-                                         const std::string& subsystem) {
-  // Construct the basename string for crash_reporter_logs.conf:
-  //   "crash_reporter-udev-collection-[action]-[name]-[subsystem]"
-  // If a udev field is not provided, "" is used in its place, e.g.:
-  //   "crash_reporter-udev-collection-[action]--[subsystem]"
-  // Hence, "" is used as a wildcard name string.
-  // TODO(sque, crosbug.com/32238): Implement wildcard checking.
-  std::string basename = action + "-" + kernel + "-" + subsystem;
-  std::string udev_log_name = std::string(kCollectUdevSignature) + '-' +
-                              basename;
-
-  // Create the destination path.
-  std::string log_file_name =
-      FormatDumpBasename(basename, time(nullptr), 0);
-  FilePath crash_path = GetCrashPath(crash_directory, log_file_name, "log");
-
-  // Handle the crash.
-  bool result = GetLogContents(log_config_path_, udev_log_name, crash_path);
-  if (!result) {
-    LOG(ERROR) << "Error reading udev log info " << udev_log_name;
-    return false;
-  }
-
-  // Compress the output using gzip.
-  brillo::ProcessImpl gzip_process;
-  gzip_process.AddArg(kGzipPath);
-  gzip_process.AddArg(crash_path.value());
-  int process_result = gzip_process.Run();
-  FilePath crash_path_zipped = FilePath(crash_path.value() + ".gz");
-  // If the zip file was not created, use the uncompressed file.
-  if (process_result != 0 || !base::PathExists(crash_path_zipped))
-    LOG(ERROR) << "Could not create zip file " << crash_path_zipped.value();
-  else
-    crash_path = crash_path_zipped;
-
-  std::string exec_name = std::string(kUdevExecName) + "-" + subsystem;
-  AddCrashMetaData(kUdevSignatureKey, udev_log_name);
-  WriteCrashMetaData(GetCrashPath(crash_directory, log_file_name, "meta"),
-                     exec_name, crash_path.value());
-  return true;
-}
-
-bool UdevCollector::ProcessDevCoredump(const FilePath& crash_directory,
-                                       int instance_number) {
-  FilePath coredump_path =
-      FilePath(base::StringPrintf("%s/devcd%d/data",
-                                  dev_coredump_directory_.c_str(),
-                                  instance_number));
-  if (!base::PathExists(coredump_path)) {
-    LOG(ERROR) << "Device coredump file " << coredump_path.value()
-               << " does not exist";
-    return false;
-  }
-
-  // Add coredump file to the crash directory.
-  if (!AppendDevCoredump(crash_directory, coredump_path, instance_number)) {
-    ClearDevCoredump(coredump_path);
-    return false;
-  }
-
-  // Clear the coredump data to allow generation of future device coredumps
-  // without having to wait for the 5-minutes timeout.
-  return ClearDevCoredump(coredump_path);
-}
-
-bool UdevCollector::AppendDevCoredump(const FilePath& crash_directory,
-                                      const FilePath& coredump_path,
-                                      int instance_number) {
-  // Retrieve the driver name of the failing device.
-  std::string driver_name = GetFailingDeviceDriverName(instance_number);
-  if (driver_name.empty()) {
-    LOG(ERROR) << "Failed to obtain driver name for instance: "
-               << instance_number;
-    return false;
-  }
-
-  std::string coredump_prefix =
-      base::StringPrintf(kDevCoredumpFilePrefixFormat, driver_name.c_str());
-
-  std::string dump_basename = FormatDumpBasename(coredump_prefix,
-                                                 time(nullptr),
-                                                 instance_number);
-  FilePath core_path = GetCrashPath(crash_directory, dump_basename, "devcore");
-  FilePath log_path = GetCrashPath(crash_directory, dump_basename, "log");
-  FilePath meta_path = GetCrashPath(crash_directory, dump_basename, "meta");
-
-  // Collect coredump data.
-  if (!base::CopyFile(coredump_path, core_path)) {
-    LOG(ERROR) << "Failed to copy device coredumpm file from "
-               << coredump_path.value() << " to " << core_path.value();
-    return false;
-  }
-
-  // Collect additional logs if one is specified in the config file.
-  std::string udev_log_name = std::string(kCollectUdevSignature) + '-' +
-      kUdevSubsystemDevCoredump + '-' + driver_name;
-  bool result = GetLogContents(log_config_path_, udev_log_name, log_path);
-  if (result) {
-    AddCrashMetaUploadFile("logs", log_path.value());
-  }
-
-  WriteCrashMetaData(meta_path, coredump_prefix, core_path.value());
-
-  return true;
-}
-
-bool UdevCollector::ClearDevCoredump(const FilePath& coredump_path) {
-  if (!base::WriteFile(coredump_path, "0", 1)) {
-    LOG(ERROR) << "Failed to delete the coredump data file "
-               << coredump_path.value();
-    return false;
-  }
-  return true;
-}
-
-std::string UdevCollector::GetFailingDeviceDriverName(int instance_number) {
-  FilePath failing_uevent_path =
-      FilePath(base::StringPrintf("%s/devcd%d/failing_device/uevent",
-                                  dev_coredump_directory_.c_str(),
-                                  instance_number));
-  if (!base::PathExists(failing_uevent_path)) {
-    LOG(ERROR) << "Failing uevent path " << failing_uevent_path.value()
-               << " does not exist";
-    return "";
-  }
-
-  std::string uevent_content;
-  if (!base::ReadFileToString(failing_uevent_path, &uevent_content)) {
-    LOG(ERROR) << "Failed to read uevent file " << failing_uevent_path.value();
-    return "";
-  }
-
-  // Parse uevent file contents as key-value pairs.
-  std::vector<std::pair<std::string, std::string>> uevent_keyval;
-  base::SplitStringIntoKeyValuePairs(uevent_content, '=', '\n', &uevent_keyval);
-  std::vector<std::pair<std::string, std::string>>::const_iterator iter;
-  for (iter = uevent_keyval.begin();
-       iter != uevent_keyval.end();
-       ++iter) {
-    if (iter->first == "DRIVER") {
-      return iter->second;
-    }
-  }
-
-  return "";
-}
diff --git a/crash_reporter/udev_collector.h b/crash_reporter/udev_collector.h
deleted file mode 100644
index e267b75..0000000
--- a/crash_reporter/udev_collector.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef CRASH_REPORTER_UDEV_COLLECTOR_H_
-#define CRASH_REPORTER_UDEV_COLLECTOR_H_
-
-#include <string>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "crash_collector.h"
-
-// Udev crash collector.
-class UdevCollector : public CrashCollector {
- public:
-  UdevCollector();
-
-  ~UdevCollector() override;
-
-  // The udev event string should be formatted as follows:
-  //   "ACTION=[action]:KERNEL=[name]:SUBSYSTEM=[subsystem]"
-  // The values don't have to be in any particular order. One or more of them
-  // could be omitted, in which case it would be treated as a wildcard (*).
-  bool HandleCrash(const std::string& udev_event);
-
- protected:
-  std::string dev_coredump_directory_;
-
- private:
-  friend class UdevCollectorTest;
-
-  // Process udev crash logs, collecting log files according to the config
-  // file (crash_reporter_logs.conf).
-  bool ProcessUdevCrashLogs(const base::FilePath& crash_directory,
-                            const std::string& action,
-                            const std::string& kernel,
-                            const std::string& subsystem);
-  // Process device coredump, collecting device coredump file.
-  // |instance_number| is the kernel number of the virtual device for the device
-  // coredump instance.
-  bool ProcessDevCoredump(const base::FilePath& crash_directory,
-                          int instance_number);
-  // Copy device coredump file to crash directory, and perform necessary
-  // coredump file management.
-  bool AppendDevCoredump(const base::FilePath& crash_directory,
-                         const base::FilePath& coredump_path,
-                         int instance_number);
-  // Clear the device coredump file by performing a dummy write to it.
-  bool ClearDevCoredump(const base::FilePath& coredump_path);
-  // Return the driver name of the device that generates the coredump.
-  std::string GetFailingDeviceDriverName(int instance_number);
-
-  // Mutator for unit testing.
-  void set_log_config_path(const std::string& path) {
-    log_config_path_ = base::FilePath(path);
-  }
-
-  DISALLOW_COPY_AND_ASSIGN(UdevCollector);
-};
-
-#endif  // CRASH_REPORTER_UDEV_COLLECTOR_H_
diff --git a/crash_reporter/udev_collector_test.cc b/crash_reporter/udev_collector_test.cc
deleted file mode 100644
index 5474f48..0000000
--- a/crash_reporter/udev_collector_test.cc
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <base/files/file_enumerator.h>
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/syslog_logging.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include "udev_collector.h"
-
-using base::FilePath;
-
-namespace {
-
-// Dummy log config file name.
-const char kLogConfigFileName[] = "log_config_file";
-
-// Dummy directory for storing device coredumps.
-const char kDevCoredumpDirectory[] = "devcoredump";
-
-// A bunch of random rules to put into the dummy log config file.
-const char kLogConfigFileContents[] =
-    "crash_reporter-udev-collection-change-card0-drm=echo change card0 drm\n"
-    "crash_reporter-udev-collection-add-state0-cpu=echo change state0 cpu\n"
-    "crash_reporter-udev-collection-devcoredump-iwlwifi=echo devcoredump\n"
-    "cros_installer=echo not for udev";
-
-const char kCrashLogFilePattern[] = "*.log.gz";
-const char kDevCoredumpFilePattern[] = "*.devcore";
-
-// Dummy content for device coredump data file.
-const char kDevCoredumpDataContents[] = "coredump";
-
-// Content for failing device's uevent file.
-const char kFailingDeviceUeventContents[] = "DRIVER=iwlwifi\n";
-
-void CountCrash() {}
-
-bool s_consent_given = true;
-
-bool IsMetrics() {
-  return s_consent_given;
-}
-
-// Returns the number of files found in the given path that matches the
-// specified file name pattern.
-int GetNumFiles(const FilePath& path, const std::string& file_pattern) {
-  base::FileEnumerator enumerator(path, false, base::FileEnumerator::FILES,
-                                  file_pattern);
-  int num_files = 0;
-  for (FilePath file_path = enumerator.Next();
-       !file_path.value().empty();
-       file_path = enumerator.Next()) {
-    num_files++;
-  }
-  return num_files;
-}
-
-}  // namespace
-
-class UdevCollectorMock : public UdevCollector {
- public:
-  MOCK_METHOD0(SetUpDBus, void());
-};
-
-class UdevCollectorTest : public ::testing::Test {
- protected:
-  base::ScopedTempDir temp_dir_generator_;
-
-  void HandleCrash(const std::string &udev_event) {
-    collector_.HandleCrash(udev_event);
-  }
-
-  void GenerateDevCoredump(const std::string& device_name) {
-    // Generate coredump data file.
-    ASSERT_TRUE(CreateDirectory(
-        FilePath(base::StringPrintf("%s/%s",
-                                    collector_.dev_coredump_directory_.c_str(),
-                                    device_name.c_str()))));
-    FilePath data_path =
-        FilePath(base::StringPrintf("%s/%s/data",
-                                    collector_.dev_coredump_directory_.c_str(),
-                                    device_name.c_str()));
-    ASSERT_EQ(strlen(kDevCoredumpDataContents),
-              base::WriteFile(data_path,
-                              kDevCoredumpDataContents,
-                              strlen(kDevCoredumpDataContents)));
-    // Generate uevent file for failing device.
-    ASSERT_TRUE(CreateDirectory(
-        FilePath(base::StringPrintf("%s/%s/failing_device",
-                                    collector_.dev_coredump_directory_.c_str(),
-                                    device_name.c_str()))));
-    FilePath uevent_path =
-        FilePath(base::StringPrintf("%s/%s/failing_device/uevent",
-                                    collector_.dev_coredump_directory_.c_str(),
-                                    device_name.c_str()));
-    ASSERT_EQ(strlen(kFailingDeviceUeventContents),
-              base::WriteFile(uevent_path,
-                              kFailingDeviceUeventContents,
-                              strlen(kFailingDeviceUeventContents)));
-  }
-
- private:
-  void SetUp() override {
-    s_consent_given = true;
-
-    EXPECT_CALL(collector_, SetUpDBus()).WillRepeatedly(testing::Return());
-
-    collector_.Initialize(CountCrash, IsMetrics);
-
-    ASSERT_TRUE(temp_dir_generator_.CreateUniqueTempDir());
-
-    FilePath log_config_path =
-        temp_dir_generator_.path().Append(kLogConfigFileName);
-    collector_.log_config_path_ = log_config_path;
-    collector_.ForceCrashDirectory(temp_dir_generator_.path());
-
-    FilePath dev_coredump_path =
-        temp_dir_generator_.path().Append(kDevCoredumpDirectory);
-    collector_.dev_coredump_directory_ = dev_coredump_path.value();
-
-    // Write to a dummy log config file.
-    ASSERT_EQ(strlen(kLogConfigFileContents),
-              base::WriteFile(log_config_path,
-                              kLogConfigFileContents,
-                              strlen(kLogConfigFileContents)));
-
-    brillo::ClearLog();
-  }
-
-  UdevCollectorMock collector_;
-};
-
-TEST_F(UdevCollectorTest, TestNoConsent) {
-  s_consent_given = false;
-  HandleCrash("ACTION=change:KERNEL=card0:SUBSYSTEM=drm");
-  EXPECT_EQ(0, GetNumFiles(temp_dir_generator_.path(), kCrashLogFilePattern));
-}
-
-TEST_F(UdevCollectorTest, TestNoMatch) {
-  // No rule should match this.
-  HandleCrash("ACTION=change:KERNEL=foo:SUBSYSTEM=bar");
-  EXPECT_EQ(0, GetNumFiles(temp_dir_generator_.path(), kCrashLogFilePattern));
-}
-
-TEST_F(UdevCollectorTest, TestMatches) {
-  // Try multiple udev events in sequence.  The number of log files generated
-  // should increase.
-  HandleCrash("ACTION=change:KERNEL=card0:SUBSYSTEM=drm");
-  EXPECT_EQ(1, GetNumFiles(temp_dir_generator_.path(), kCrashLogFilePattern));
-  HandleCrash("ACTION=add:KERNEL=state0:SUBSYSTEM=cpu");
-  EXPECT_EQ(2, GetNumFiles(temp_dir_generator_.path(), kCrashLogFilePattern));
-}
-
-TEST_F(UdevCollectorTest, TestDevCoredump) {
-  GenerateDevCoredump("devcd0");
-  HandleCrash("ACTION=add:KERNEL_NUMBER=0:SUBSYSTEM=devcoredump");
-  EXPECT_EQ(1, GetNumFiles(temp_dir_generator_.path(),
-                           kDevCoredumpFilePattern));
-  GenerateDevCoredump("devcd1");
-  HandleCrash("ACTION=add:KERNEL_NUMBER=1:SUBSYSTEM=devcoredump");
-  EXPECT_EQ(2, GetNumFiles(temp_dir_generator_.path(),
-                           kDevCoredumpFilePattern));
-}
-
-// TODO(sque, crosbug.com/32238) - test wildcard cases, multiple identical udev
-// events.
diff --git a/crash_reporter/unclean_shutdown_collector.cc b/crash_reporter/unclean_shutdown_collector.cc
deleted file mode 100644
index 8a092ec..0000000
--- a/crash_reporter/unclean_shutdown_collector.cc
+++ /dev/null
@@ -1,93 +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 "unclean_shutdown_collector.h"
-
-#include <base/files/file_util.h>
-#include <base/logging.h>
-
-static const char kUncleanShutdownFile[] =
-    "/var/lib/crash_reporter/pending_clean_shutdown";
-
-// Files created by power manager used for crash reporting.
-static const char kPowerdTracePath[] = "/var/lib/power_manager";
-// Presence of this file indicates that the system was suspended
-static const char kPowerdSuspended[] = "powerd_suspended";
-
-using base::FilePath;
-
-UncleanShutdownCollector::UncleanShutdownCollector()
-    : unclean_shutdown_file_(kUncleanShutdownFile),
-      powerd_trace_path_(kPowerdTracePath),
-      powerd_suspended_file_(powerd_trace_path_.Append(kPowerdSuspended)) {
-}
-
-UncleanShutdownCollector::~UncleanShutdownCollector() {
-}
-
-bool UncleanShutdownCollector::Enable() {
-  FilePath file_path(unclean_shutdown_file_);
-  base::CreateDirectory(file_path.DirName());
-  if (base::WriteFile(file_path, "", 0) != 0) {
-    LOG(ERROR) << "Unable to create shutdown check file";
-    return false;
-  }
-  return true;
-}
-
-bool UncleanShutdownCollector::DeleteUncleanShutdownFiles() {
-  if (!base::DeleteFile(FilePath(unclean_shutdown_file_), false)) {
-    LOG(ERROR) << "Failed to delete unclean shutdown file "
-               << unclean_shutdown_file_;
-    return false;
-  }
-  // Delete power manager state file if it exists.
-  base::DeleteFile(powerd_suspended_file_, false);
-  return true;
-}
-
-bool UncleanShutdownCollector::Collect() {
-  FilePath unclean_file_path(unclean_shutdown_file_);
-  if (!base::PathExists(unclean_file_path)) {
-    return false;
-  }
-  LOG(WARNING) << "Last shutdown was not clean";
-  if (DeadBatteryCausedUncleanShutdown()) {
-    DeleteUncleanShutdownFiles();
-    return false;
-  }
-  DeleteUncleanShutdownFiles();
-
-  if (is_feedback_allowed_function_()) {
-    count_crash_function_();
-  }
-  return true;
-}
-
-bool UncleanShutdownCollector::Disable() {
-  LOG(INFO) << "Clean shutdown signalled";
-  return DeleteUncleanShutdownFiles();
-}
-
-bool UncleanShutdownCollector::DeadBatteryCausedUncleanShutdown() {
-  // Check for case of battery running out while suspended.
-  if (base::PathExists(powerd_suspended_file_)) {
-    LOG(INFO) << "Unclean shutdown occurred while suspended. Not counting "
-              << "toward unclean shutdown statistic.";
-    return true;
-  }
-  return false;
-}
diff --git a/crash_reporter/unclean_shutdown_collector.h b/crash_reporter/unclean_shutdown_collector.h
deleted file mode 100644
index 5bc9968..0000000
--- a/crash_reporter/unclean_shutdown_collector.h
+++ /dev/null
@@ -1,62 +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 CRASH_REPORTER_UNCLEAN_SHUTDOWN_COLLECTOR_H_
-#define CRASH_REPORTER_UNCLEAN_SHUTDOWN_COLLECTOR_H_
-
-#include <string>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "crash_collector.h"
-
-// Unclean shutdown collector.
-class UncleanShutdownCollector : public CrashCollector {
- public:
-  UncleanShutdownCollector();
-  ~UncleanShutdownCollector() override;
-
-  // Enable collection - signal that a boot has started.
-  bool Enable();
-
-  // Collect if there is was an unclean shutdown. Returns true if
-  // there was, false otherwise.
-  bool Collect();
-
-  // Disable collection - signal that the system has been shutdown cleanly.
-  bool Disable();
-
- private:
-  friend class UncleanShutdownCollectorTest;
-  FRIEND_TEST(UncleanShutdownCollectorTest, EnableCannotWrite);
-  FRIEND_TEST(UncleanShutdownCollectorTest, CollectDeadBatterySuspended);
-
-  bool DeleteUncleanShutdownFiles();
-
-  // Check for unclean shutdown due to battery running out by analyzing powerd
-  // trace files.
-  bool DeadBatteryCausedUncleanShutdown();
-
-  const char *unclean_shutdown_file_;
-  base::FilePath powerd_trace_path_;
-  base::FilePath powerd_suspended_file_;
-
-  DISALLOW_COPY_AND_ASSIGN(UncleanShutdownCollector);
-};
-
-#endif  // CRASH_REPORTER_UNCLEAN_SHUTDOWN_COLLECTOR_H_
diff --git a/crash_reporter/unclean_shutdown_collector_test.cc b/crash_reporter/unclean_shutdown_collector_test.cc
deleted file mode 100644
index 56d2704..0000000
--- a/crash_reporter/unclean_shutdown_collector_test.cc
+++ /dev/null
@@ -1,153 +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 "unclean_shutdown_collector.h"
-
-#include <unistd.h>
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/string_util.h>
-#include <brillo/syslog_logging.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using base::FilePath;
-using ::brillo::FindLog;
-
-namespace {
-
-int s_crashes = 0;
-bool s_metrics = true;
-
-void CountCrash() {
-  ++s_crashes;
-}
-
-bool IsMetrics() {
-  return s_metrics;
-}
-
-}  // namespace
-
-class UncleanShutdownCollectorMock : public UncleanShutdownCollector {
- public:
-  MOCK_METHOD0(SetUpDBus, void());
-};
-
-class UncleanShutdownCollectorTest : public ::testing::Test {
-  void SetUp() {
-    s_crashes = 0;
-
-    EXPECT_CALL(collector_, SetUpDBus()).WillRepeatedly(testing::Return());
-
-    collector_.Initialize(CountCrash,
-                          IsMetrics);
-
-    EXPECT_TRUE(test_dir_.CreateUniqueTempDir());
-
-    test_directory_ = test_dir_.path().Append("test");
-    test_unclean_ = test_dir_.path().Append("test/unclean");
-
-    collector_.unclean_shutdown_file_ = test_unclean_.value().c_str();
-    base::DeleteFile(test_unclean_, true);
-    // Set up an alternate power manager state file as well
-    collector_.powerd_suspended_file_ =
-        test_dir_.path().Append("test/suspended");
-    brillo::ClearLog();
-  }
-
- protected:
-  void WriteStringToFile(const FilePath &file_path,
-                         const char *data) {
-    ASSERT_EQ(strlen(data), base::WriteFile(file_path, data, strlen(data)));
-  }
-
-  UncleanShutdownCollectorMock collector_;
-
-  // Temporary directory used for tests.
-  base::ScopedTempDir test_dir_;
-  FilePath test_directory_;
-  FilePath test_unclean_;
-};
-
-TEST_F(UncleanShutdownCollectorTest, EnableWithoutParent) {
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(base::PathExists(test_unclean_));
-}
-
-TEST_F(UncleanShutdownCollectorTest, EnableWithParent) {
-  mkdir(test_directory_.value().c_str(), 0777);
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(base::PathExists(test_unclean_));
-}
-
-TEST_F(UncleanShutdownCollectorTest, EnableCannotWrite) {
-  collector_.unclean_shutdown_file_ = "/bad/path";
-  ASSERT_FALSE(collector_.Enable());
-  ASSERT_TRUE(FindLog("Unable to create shutdown check file"));
-}
-
-TEST_F(UncleanShutdownCollectorTest, CollectTrue) {
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(base::PathExists(test_unclean_));
-  ASSERT_TRUE(collector_.Collect());
-  ASSERT_FALSE(base::PathExists(test_unclean_));
-  ASSERT_EQ(1, s_crashes);
-  ASSERT_TRUE(FindLog("Last shutdown was not clean"));
-}
-
-TEST_F(UncleanShutdownCollectorTest, CollectFalse) {
-  ASSERT_FALSE(collector_.Collect());
-  ASSERT_EQ(0, s_crashes);
-}
-
-TEST_F(UncleanShutdownCollectorTest, CollectDeadBatterySuspended) {
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(base::PathExists(test_unclean_));
-  base::WriteFile(collector_.powerd_suspended_file_, "", 0);
-  ASSERT_FALSE(collector_.Collect());
-  ASSERT_FALSE(base::PathExists(test_unclean_));
-  ASSERT_FALSE(base::PathExists(collector_.powerd_suspended_file_));
-  ASSERT_EQ(0, s_crashes);
-  ASSERT_TRUE(FindLog("Unclean shutdown occurred while suspended."));
-}
-
-TEST_F(UncleanShutdownCollectorTest, Disable) {
-  ASSERT_TRUE(collector_.Enable());
-  ASSERT_TRUE(base::PathExists(test_unclean_));
-  ASSERT_TRUE(collector_.Disable());
-  ASSERT_FALSE(base::PathExists(test_unclean_));
-  ASSERT_FALSE(collector_.Collect());
-}
-
-TEST_F(UncleanShutdownCollectorTest, DisableWhenNotEnabled) {
-  ASSERT_TRUE(collector_.Disable());
-}
-
-TEST_F(UncleanShutdownCollectorTest, CantDisable) {
-  mkdir(test_directory_.value().c_str(), 0700);
-  if (mkdir(test_unclean_.value().c_str(), 0700)) {
-    ASSERT_EQ(EEXIST, errno)
-        << "Error while creating directory '" << test_unclean_.value()
-        << "': " << strerror(errno);
-  }
-  ASSERT_EQ(0, base::WriteFile(test_unclean_.Append("foo"), "", 0))
-      << "Error while creating empty file '"
-      << test_unclean_.Append("foo").value() << "': " << strerror(errno);
-  ASSERT_FALSE(collector_.Disable());
-  rmdir(test_unclean_.value().c_str());
-}
diff --git a/crash_reporter/user_collector.cc b/crash_reporter/user_collector.cc
deleted file mode 100644
index 98d7448..0000000
--- a/crash_reporter/user_collector.cc
+++ /dev/null
@@ -1,669 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "user_collector.h"
-
-#include <elf.h>
-#include <fcntl.h>
-#include <grp.h>  // For struct group.
-#include <pcrecpp.h>
-#include <pwd.h>  // For struct passwd.
-#include <stdint.h>
-#include <sys/cdefs.h>  // For __WORDSIZE
-#include <sys/fsuid.h>
-#include <sys/types.h>  // For getpwuid_r, getgrnam_r, WEXITSTATUS.
-#include <unistd.h>  // For setgroups
-
-#include <iostream>  // For std::oct
-#include <string>
-#include <vector>
-
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/posix/eintr_wrapper.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/osrelease_reader.h>
-#include <brillo/process.h>
-#include <brillo/syslog_logging.h>
-#include <cutils/properties.h>
-#include <private/android_filesystem_config.h>
-
-static const char kCollectionErrorSignature[] =
-    "crash_reporter-user-collection";
-static const char kCorePatternProperty[] = "crash_reporter.coredump.enabled";
-static const char kCoreToMinidumpConverterPath[] = "/system/bin/core2md";
-
-static const char kStatePrefix[] = "State:\t";
-
-static const char kCoreTempFolder[] = "/data/misc/crash_reporter/tmp";
-
-// Define an otherwise invalid value that represents an unknown UID and GID.
-static const uid_t kUnknownUid = -1;
-static const gid_t kUnknownGid = -1;
-
-const char *UserCollector::kUserId = "Uid:\t";
-const char *UserCollector::kGroupId = "Gid:\t";
-
-// Product information keys in the /etc/os-release.d folder.
-static const char kBdkVersionKey[] = "bdk_version";
-static const char kProductIDKey[] = "product_id";
-static const char kProductVersionKey[] = "product_version";
-
-
-using base::FilePath;
-using base::StringPrintf;
-
-UserCollector::UserCollector()
-    : generate_diagnostics_(false),
-      initialized_(false) {
-}
-
-void UserCollector::Initialize(
-    UserCollector::CountCrashFunction count_crash_function,
-    const std::string &our_path,
-    UserCollector::IsFeedbackAllowedFunction is_feedback_allowed_function,
-    bool generate_diagnostics,
-    bool core2md_failure,
-    bool directory_failure,
-    const std::string &filter_in) {
-  CrashCollector::Initialize(count_crash_function,
-                             is_feedback_allowed_function);
-  our_path_ = our_path;
-  initialized_ = true;
-  generate_diagnostics_ = generate_diagnostics;
-  core2md_failure_ = core2md_failure;
-  directory_failure_ = directory_failure;
-  filter_in_ = filter_in;
-
-  gid_t groups[] = { AID_ROOT, AID_SYSTEM, AID_DBUS, AID_READPROC };
-  if (setgroups(arraysize(groups), groups) != 0) {
-    PLOG(FATAL) << "Unable to set groups to root, system, dbus, and readproc";
-  }
-}
-
-UserCollector::~UserCollector() {
-}
-
-std::string UserCollector::GetErrorTypeSignature(ErrorType error_type) const {
-  switch (error_type) {
-    case kErrorSystemIssue:
-      return "system-issue";
-    case kErrorReadCoreData:
-      return "read-core-data";
-    case kErrorUnusableProcFiles:
-      return "unusable-proc-files";
-    case kErrorInvalidCoreFile:
-      return "invalid-core-file";
-    case kErrorUnsupported32BitCoreFile:
-      return "unsupported-32bit-core-file";
-    case kErrorCore2MinidumpConversion:
-      return "core2md-conversion";
-    default:
-      return "";
-  }
-}
-
-bool UserCollector::SetUpInternal(bool enabled) {
-  CHECK(initialized_);
-  LOG(INFO) << (enabled ? "Enabling" : "Disabling") << " user crash handling";
-
-  property_set(kCorePatternProperty, enabled ? "1" : "0");
-
-  return true;
-}
-
-bool UserCollector::GetFirstLineWithPrefix(
-    const std::vector<std::string> &lines,
-    const char *prefix, std::string *line) {
-  std::vector<std::string>::const_iterator line_iterator;
-  for (line_iterator = lines.begin(); line_iterator != lines.end();
-       ++line_iterator) {
-    if (line_iterator->find(prefix) == 0) {
-      *line = *line_iterator;
-      return true;
-    }
-  }
-  return false;
-}
-
-bool UserCollector::GetIdFromStatus(
-    const char *prefix, IdKind kind,
-    const std::vector<std::string> &status_lines, int *id) {
-  // From fs/proc/array.c:task_state(), this file contains:
-  // \nUid:\t<uid>\t<euid>\t<suid>\t<fsuid>\n
-  std::string id_line;
-  if (!GetFirstLineWithPrefix(status_lines, prefix, &id_line)) {
-    return false;
-  }
-  std::string id_substring = id_line.substr(strlen(prefix), std::string::npos);
-  std::vector<std::string> ids = base::SplitString(
-      id_substring, "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-  if (ids.size() != kIdMax || kind < 0 || kind >= kIdMax) {
-    return false;
-  }
-  const char *number = ids[kind].c_str();
-  char *end_number = nullptr;
-  *id = strtol(number, &end_number, 10);
-  if (*end_number != '\0') {
-    return false;
-  }
-  return true;
-}
-
-bool UserCollector::GetStateFromStatus(
-    const std::vector<std::string> &status_lines, std::string *state) {
-  std::string state_line;
-  if (!GetFirstLineWithPrefix(status_lines, kStatePrefix, &state_line)) {
-    return false;
-  }
-  *state = state_line.substr(strlen(kStatePrefix), std::string::npos);
-  return true;
-}
-
-void UserCollector::EnqueueCollectionErrorLog(pid_t pid,
-                                              ErrorType error_type,
-                                              const std::string &exec) {
-  FilePath crash_path;
-  LOG(INFO) << "Writing conversion problems as separate crash report.";
-  if (!GetCreatedCrashDirectoryByEuid(0, &crash_path, nullptr)) {
-    LOG(ERROR) << "Could not even get log directory; out of space?";
-    return;
-  }
-  AddCrashMetaData("sig", kCollectionErrorSignature);
-  AddCrashMetaData("error_type", GetErrorTypeSignature(error_type));
-  std::string dump_basename = FormatDumpBasename(exec, time(nullptr), pid);
-  std::string error_log = brillo::GetLog();
-  FilePath diag_log_path = GetCrashPath(crash_path, dump_basename, "diaglog");
-  if (GetLogContents(FilePath(log_config_path_), kCollectionErrorSignature,
-                     diag_log_path)) {
-    // We load the contents of diag_log into memory and append it to
-    // the error log.  We cannot just append to files because we need
-    // to always create new files to prevent attack.
-    std::string diag_log_contents;
-    base::ReadFileToString(diag_log_path, &diag_log_contents);
-    error_log.append(diag_log_contents);
-    base::DeleteFile(diag_log_path, false);
-  }
-  FilePath log_path = GetCrashPath(crash_path, dump_basename, "log");
-  FilePath meta_path = GetCrashPath(crash_path, dump_basename, "meta");
-  // We must use WriteNewFile instead of base::WriteFile as we do
-  // not want to write with root access to a symlink that an attacker
-  // might have created.
-  if (WriteNewFile(log_path, error_log.data(), error_log.length()) < 0) {
-    LOG(ERROR) << "Error writing new file " << log_path.value();
-    return;
-  }
-  WriteCrashMetaData(meta_path, exec, log_path.value());
-}
-
-bool UserCollector::CopyOffProcFiles(pid_t pid,
-                                     const FilePath &container_dir) {
-  if (!base::CreateDirectory(container_dir)) {
-    PLOG(ERROR) << "Could not create " << container_dir.value();
-    return false;
-  }
-  int dir_mask = base::FILE_PERMISSION_READ_BY_USER
-                 | base::FILE_PERMISSION_WRITE_BY_USER
-                 | base::FILE_PERMISSION_EXECUTE_BY_USER
-                 | base::FILE_PERMISSION_READ_BY_GROUP
-                 | base::FILE_PERMISSION_WRITE_BY_GROUP;
-  if (!base::SetPosixFilePermissions(container_dir,
-                                     base::FILE_PERMISSION_MASK & dir_mask)) {
-    PLOG(ERROR) << "Could not set permissions for " << container_dir.value()
-                << " to " << std::oct
-                << (base::FILE_PERMISSION_MASK & dir_mask);
-    return false;
-  }
-  FilePath process_path = GetProcessPath(pid);
-  if (!base::PathExists(process_path)) {
-    LOG(ERROR) << "Path " << process_path.value() << " does not exist";
-    return false;
-  }
-  static const char *proc_files[] = {
-    "auxv",
-    "cmdline",
-    "environ",
-    "maps",
-    "status"
-  };
-  for (unsigned i = 0; i < arraysize(proc_files); ++i) {
-    if (!base::CopyFile(process_path.Append(proc_files[i]),
-                        container_dir.Append(proc_files[i]))) {
-      LOG(ERROR) << "Could not copy " << proc_files[i] << " file";
-      return false;
-    }
-  }
-  return true;
-}
-
-bool UserCollector::ValidateProcFiles(const FilePath &container_dir) const {
-  // Check if the maps file is empty, which could be due to the crashed
-  // process being reaped by the kernel before finishing a core dump.
-  int64_t file_size = 0;
-  if (!base::GetFileSize(container_dir.Append("maps"), &file_size)) {
-    LOG(ERROR) << "Could not get the size of maps file";
-    return false;
-  }
-  if (file_size == 0) {
-    LOG(ERROR) << "maps file is empty";
-    return false;
-  }
-  return true;
-}
-
-UserCollector::ErrorType UserCollector::ValidateCoreFile(
-    const FilePath &core_path) const {
-  int fd = HANDLE_EINTR(open(core_path.value().c_str(), O_RDONLY));
-  if (fd < 0) {
-    PLOG(ERROR) << "Could not open core file " << core_path.value();
-    return kErrorInvalidCoreFile;
-  }
-
-  char e_ident[EI_NIDENT];
-  bool read_ok = base::ReadFromFD(fd, e_ident, sizeof(e_ident));
-  IGNORE_EINTR(close(fd));
-  if (!read_ok) {
-    LOG(ERROR) << "Could not read header of core file";
-    return kErrorInvalidCoreFile;
-  }
-
-  if (e_ident[EI_MAG0] != ELFMAG0 || e_ident[EI_MAG1] != ELFMAG1 ||
-      e_ident[EI_MAG2] != ELFMAG2 || e_ident[EI_MAG3] != ELFMAG3) {
-    LOG(ERROR) << "Invalid core file";
-    return kErrorInvalidCoreFile;
-  }
-
-#if __WORDSIZE == 64
-  // TODO(benchan, mkrebs): Remove this check once core2md can
-  // handles both 32-bit and 64-bit ELF on a 64-bit platform.
-  if (e_ident[EI_CLASS] == ELFCLASS32) {
-    LOG(ERROR) << "Conversion of 32-bit core file on 64-bit platform is "
-               << "currently not supported";
-    return kErrorUnsupported32BitCoreFile;
-  }
-#endif
-
-  return kErrorNone;
-}
-
-bool UserCollector::GetCreatedCrashDirectory(pid_t pid, uid_t supplied_ruid,
-                                             FilePath *crash_file_path,
-                                             bool *out_of_capacity) {
-  FilePath process_path = GetProcessPath(pid);
-  std::string status;
-  if (directory_failure_) {
-    LOG(ERROR) << "Purposefully failing to create spool directory";
-    return false;
-  }
-
-  uid_t uid;
-  if (base::ReadFileToString(process_path.Append("status"), &status)) {
-    std::vector<std::string> status_lines = base::SplitString(
-        status, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
-    std::string process_state;
-    if (!GetStateFromStatus(status_lines, &process_state)) {
-      LOG(ERROR) << "Could not find process state in status file";
-      return false;
-    }
-    LOG(INFO) << "State of crashed process [" << pid << "]: " << process_state;
-
-    // Get effective UID of crashing process.
-    int id;
-    if (!GetIdFromStatus(kUserId, kIdEffective, status_lines, &id)) {
-      LOG(ERROR) << "Could not find euid in status file";
-      return false;
-    }
-    uid = id;
-  } else if (supplied_ruid != kUnknownUid) {
-    LOG(INFO) << "Using supplied UID " << supplied_ruid
-              << " for crashed process [" << pid
-              << "] due to error reading status file";
-    uid = supplied_ruid;
-  } else {
-    LOG(ERROR) << "Could not read status file and kernel did not supply UID";
-    LOG(INFO) << "Path " << process_path.value() << " DirectoryExists: "
-              << base::DirectoryExists(process_path);
-    return false;
-  }
-
-  if (!GetCreatedCrashDirectoryByEuid(uid, crash_file_path, out_of_capacity)) {
-    LOG(ERROR) << "Could not create crash directory";
-    return false;
-  }
-  return true;
-}
-
-bool UserCollector::CopyStdinToCoreFile(const FilePath &core_path) {
-  // Copy off all stdin to a core file.
-  FilePath stdin_path("/proc/self/fd/0");
-  if (base::CopyFile(stdin_path, core_path)) {
-    return true;
-  }
-
-  PLOG(ERROR) << "Could not write core file";
-  // If the file system was full, make sure we remove any remnants.
-  base::DeleteFile(core_path, false);
-  return false;
-}
-
-bool UserCollector::RunCoreToMinidump(const FilePath &core_path,
-                                      const FilePath &procfs_directory,
-                                      const FilePath &minidump_path,
-                                      const FilePath &temp_directory) {
-  FilePath output_path = temp_directory.Append("output");
-  brillo::ProcessImpl core2md;
-  core2md.RedirectOutput(output_path.value());
-  core2md.AddArg(kCoreToMinidumpConverterPath);
-  core2md.AddArg(core_path.value());
-  core2md.AddArg(procfs_directory.value());
-
-  if (!core2md_failure_) {
-    core2md.AddArg(minidump_path.value());
-  } else {
-    // To test how core2md errors are propagaged, cause an error
-    // by forgetting a required argument.
-  }
-
-  int errorlevel = core2md.Run();
-
-  std::string output;
-  base::ReadFileToString(output_path, &output);
-  if (errorlevel != 0) {
-    LOG(ERROR) << "Problem during " << kCoreToMinidumpConverterPath
-               << " [result=" << errorlevel << "]: " << output;
-    return false;
-  }
-
-  if (!base::PathExists(minidump_path)) {
-    LOG(ERROR) << "Minidump file " << minidump_path.value()
-               << " was not created";
-    return false;
-  }
-  return true;
-}
-
-UserCollector::ErrorType UserCollector::ConvertCoreToMinidump(
-    pid_t pid,
-    const FilePath &container_dir,
-    const FilePath &core_path,
-    const FilePath &minidump_path) {
-  // If proc files are unuable, we continue to read the core file from stdin,
-  // but only skip the core-to-minidump conversion, so that we may still use
-  // the core file for debugging.
-  bool proc_files_usable =
-      CopyOffProcFiles(pid, container_dir) && ValidateProcFiles(container_dir);
-
-  // Switch back to the original UID/GID.
-  gid_t rgid, egid, sgid;
-  if (getresgid(&rgid, &egid, &sgid) != 0) {
-    PLOG(FATAL) << "Unable to read saved gid";
-  }
-  if (setresgid(sgid, sgid, -1) != 0) {
-    PLOG(FATAL) << "Unable to set real group ID back to saved gid";
-  } else {
-    if (getresgid(&rgid, &egid, &sgid) != 0) {
-      // If the groups cannot be read at this point, the rgid variable will
-      // contain the previously read group ID from before changing it.  This
-      // will cause the chown call below to set the incorrect group for
-      // non-root crashes.  But do not treat this as a fatal error, so that
-      // the rest of the collection will continue for potential manual
-      // collection by a developer.
-      PLOG(ERROR) << "Unable to read real group ID after setting it";
-    }
-  }
-
-  uid_t ruid, euid, suid;
-  if (getresuid(&ruid, &euid, &suid) != 0) {
-    PLOG(FATAL) << "Unable to read saved uid";
-  }
-  if (setresuid(suid, suid, -1) != 0) {
-    PLOG(FATAL) << "Unable to set real user ID back to saved uid";
-  } else {
-    if (getresuid(&ruid, &euid, &suid) != 0) {
-      // If the user ID cannot be read at this point, the ruid variable will
-      // contain the previously read user ID from before changing it.  This
-      // will cause the chown call below to set the incorrect user for
-      // non-root crashes.  But do not treat this as a fatal error, so that
-      // the rest of the collection will continue for potential manual
-      // collection by a developer.
-      PLOG(ERROR) << "Unable to read real user ID after setting it";
-    }
-  }
-
-  if (!CopyStdinToCoreFile(core_path)) {
-    return kErrorReadCoreData;
-  }
-
-  if (!proc_files_usable) {
-    LOG(INFO) << "Skipped converting core file to minidump due to "
-              << "unusable proc files";
-    return kErrorUnusableProcFiles;
-  }
-
-  ErrorType error = ValidateCoreFile(core_path);
-  if (error != kErrorNone) {
-    return error;
-  }
-
-  // Chown the temp container directory back to the original user/group that
-  // crash_reporter is run as, so that additional files can be written to
-  // the temp folder.
-  if (chown(container_dir.value().c_str(), ruid, rgid) < 0) {
-    PLOG(ERROR) << "Could not set owner for " << container_dir.value();
-  }
-
-  if (!RunCoreToMinidump(core_path,
-                         container_dir,  // procfs directory
-                         minidump_path,
-                         container_dir)) {  // temporary directory
-    return kErrorCore2MinidumpConversion;
-  }
-
-  LOG(INFO) << "Stored minidump to " << minidump_path.value();
-  return kErrorNone;
-}
-
-UserCollector::ErrorType UserCollector::ConvertAndEnqueueCrash(
-    pid_t pid, const std::string &exec, uid_t supplied_ruid,
-    bool *out_of_capacity) {
-  FilePath crash_path;
-  if (!GetCreatedCrashDirectory(pid, supplied_ruid, &crash_path,
-      out_of_capacity)) {
-    LOG(ERROR) << "Unable to find/create process-specific crash path";
-    return kErrorSystemIssue;
-  }
-
-  // Directory like /tmp/crash_reporter/1234 which contains the
-  // procfs entries and other temporary files used during conversion.
-  FilePath container_dir(StringPrintf("%s/%d", kCoreTempFolder, pid));
-  // Delete a pre-existing directory from crash reporter that may have
-  // been left around for diagnostics from a failed conversion attempt.
-  // If we don't, existing files can cause forking to fail.
-  base::DeleteFile(container_dir, true);
-  std::string dump_basename = FormatDumpBasename(exec, time(nullptr), pid);
-  FilePath core_path = GetCrashPath(crash_path, dump_basename, "core");
-  FilePath meta_path = GetCrashPath(crash_path, dump_basename, "meta");
-  FilePath minidump_path = GetCrashPath(crash_path, dump_basename, "dmp");
-  FilePath log_path = GetCrashPath(crash_path, dump_basename, "log");
-
-  if (GetLogContents(FilePath(log_config_path_), exec, log_path))
-    AddCrashMetaData("log", log_path.value());
-
-  brillo::OsReleaseReader reader;
-  reader.Load();
-  std::string value = "undefined";
-  if (!reader.GetString(kBdkVersionKey, &value)) {
-    LOG(ERROR) << "Could not read " << kBdkVersionKey
-               << " from /etc/os-release.d/";
-  }
-  AddCrashMetaData(kBdkVersionKey, value);
-
-  value = "undefined";
-  if (!reader.GetString(kProductIDKey, &value)) {
-    LOG(ERROR) << "Could not read " << kProductIDKey
-               << " from /etc/os-release.d/";
-  }
-  AddCrashMetaData(kProductIDKey, value);
-
-  value = "undefined";
-  if (!reader.GetString(kProductVersionKey, &value)) {
-    LOG(ERROR) << "Could not read " << kProductVersionKey
-               << " from /etc/os-release.d/";
-  }
-  AddCrashMetaData(kProductVersionKey, value);
-
-  ErrorType error_type =
-      ConvertCoreToMinidump(pid, container_dir, core_path, minidump_path);
-  if (error_type != kErrorNone) {
-    LOG(INFO) << "Leaving core file at " << core_path.value()
-              << " due to conversion error";
-    return error_type;
-  }
-
-  // Here we commit to sending this file.  We must not return false
-  // after this point or we will generate a log report as well as a
-  // crash report.
-  WriteCrashMetaData(meta_path,
-                     exec,
-                     minidump_path.value());
-
-  if (!IsDeveloperImage()) {
-    base::DeleteFile(core_path, false);
-  } else {
-    LOG(INFO) << "Leaving core file at " << core_path.value()
-              << " due to developer image";
-  }
-
-  base::DeleteFile(container_dir, true);
-  return kErrorNone;
-}
-
-bool UserCollector::ParseCrashAttributes(const std::string &crash_attributes,
-                                         pid_t *pid, int *signal, uid_t *uid,
-                                         gid_t *gid,
-                                         std::string *kernel_supplied_name) {
-  pcrecpp::RE re("(\\d+):(\\d+):(\\d+):(\\d+):(.*)");
-  if (re.FullMatch(crash_attributes, pid, signal, uid, gid,
-                   kernel_supplied_name))
-    return true;
-
-  LOG(INFO) << "Falling back to parsing crash attributes '"
-            << crash_attributes << "' without UID and GID";
-  pcrecpp::RE re_without_uid("(\\d+):(\\d+):(.*)");
-  *uid = kUnknownUid;
-  *gid = kUnknownGid;
-  return re_without_uid.FullMatch(crash_attributes, pid, signal,
-      kernel_supplied_name);
-}
-
-bool UserCollector::ShouldDump(bool has_owner_consent,
-                               bool is_developer,
-                               std::string *reason) {
-  reason->clear();
-
-  // For developer builds, we always want to keep the crash reports unless
-  // we're testing the crash facilities themselves.  This overrides
-  // feedback.  Crash sending still obeys consent.
-  if (is_developer) {
-    *reason = "developer build - not testing - always dumping";
-    return true;
-  }
-
-  if (!has_owner_consent) {
-    *reason = "ignoring - no consent";
-    return false;
-  }
-
-  *reason = "handling";
-  return true;
-}
-
-bool UserCollector::HandleCrash(const std::string &crash_attributes,
-                                const char *force_exec) {
-  CHECK(initialized_);
-  pid_t pid = 0;
-  int signal = 0;
-  uid_t supplied_ruid = kUnknownUid;
-  gid_t supplied_rgid = kUnknownGid;
-  std::string kernel_supplied_name;
-
-  if (!ParseCrashAttributes(crash_attributes, &pid, &signal, &supplied_ruid,
-                            &supplied_rgid, &kernel_supplied_name)) {
-    LOG(ERROR) << "Invalid parameter: --user=" <<  crash_attributes;
-    return false;
-  }
-
-  // Switch to the group and user that ran the crashing binary in order to
-  // access their /proc files.  Do not set suid/sgid, so that we can switch
-  // back after copying the necessary files.
-  if (setresgid(supplied_rgid, supplied_rgid, -1) != 0) {
-    PLOG(FATAL) << "Unable to set real group ID to access process files";
-  }
-  if (setresuid(supplied_ruid, supplied_ruid, -1) != 0) {
-    PLOG(FATAL) << "Unable to set real user ID to access process files";
-  }
-
-  std::string exec;
-  if (force_exec) {
-    exec.assign(force_exec);
-  } else if (!GetExecutableBaseNameFromPid(pid, &exec)) {
-    // If we cannot find the exec name, use the kernel supplied name.
-    // We don't always use the kernel's since it truncates the name to
-    // 16 characters.
-    exec = StringPrintf("supplied_%s", kernel_supplied_name.c_str());
-  }
-
-  // Allow us to test the crash reporting mechanism successfully even if
-  // other parts of the system crash.
-  if (!filter_in_.empty() &&
-      (filter_in_ == "none" ||
-       filter_in_ != exec)) {
-    // We use a different format message to make it more obvious in tests
-    // which crashes are test generated and which are real.
-    LOG(WARNING) << "Ignoring crash from " << exec << "[" << pid << "] while "
-                 << "filter_in=" << filter_in_ << ".";
-    return true;
-  }
-
-  std::string reason;
-  bool dump = ShouldDump(is_feedback_allowed_function_(),
-                         IsDeveloperImage(),
-                         &reason);
-
-  LOG(WARNING) << "Received crash notification for " << exec << "[" << pid
-               << "] sig " << signal << ", user " << supplied_ruid
-               << " (" << reason << ")";
-
-  if (dump) {
-    count_crash_function_();
-
-    if (generate_diagnostics_) {
-      bool out_of_capacity = false;
-      ErrorType error_type =
-          ConvertAndEnqueueCrash(pid, exec, supplied_ruid, &out_of_capacity);
-      if (error_type != kErrorNone) {
-        if (!out_of_capacity)
-          EnqueueCollectionErrorLog(pid, error_type, exec);
-        return false;
-      }
-    }
-  }
-
-  return true;
-}
diff --git a/crash_reporter/user_collector.h b/crash_reporter/user_collector.h
deleted file mode 100644
index 7261ed4..0000000
--- a/crash_reporter/user_collector.h
+++ /dev/null
@@ -1,189 +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 CRASH_REPORTER_USER_COLLECTOR_H_
-#define CRASH_REPORTER_USER_COLLECTOR_H_
-
-#include <string>
-#include <vector>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "crash_collector.h"
-
-class SystemLogging;
-
-// User crash collector.
-class UserCollector : public CrashCollector {
- public:
-  UserCollector();
-
-  // Initialize the user crash collector for detection of crashes,
-  // given a crash counting function, the path to this executable,
-  // metrics collection enabled oracle, and system logger facility.
-  // Crash detection/reporting is not enabled until Enable is called.
-  // |generate_diagnostics| is used to indicate whether or not to try
-  // to generate a minidump from crashes.
-  void Initialize(CountCrashFunction count_crash,
-                  const std::string &our_path,
-                  IsFeedbackAllowedFunction is_metrics_allowed,
-                  bool generate_diagnostics,
-                  bool core2md_failure,
-                  bool directory_failure,
-                  const std::string &filter_in);
-
-  ~UserCollector() override;
-
-  // Enable collection.
-  bool Enable() { return SetUpInternal(true); }
-
-  // Disable collection.
-  bool Disable() { return SetUpInternal(false); }
-
-  // Handle a specific user crash.  Returns true on success.
-  bool HandleCrash(const std::string &crash_attributes,
-                   const char *force_exec);
-
- private:
-  friend class UserCollectorTest;
-  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesBadPath);
-  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesBadPid);
-  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesOK);
-  FRIEND_TEST(UserCollectorTest, GetExecutableBaseNameFromPid);
-  FRIEND_TEST(UserCollectorTest, GetFirstLineWithPrefix);
-  FRIEND_TEST(UserCollectorTest, GetIdFromStatus);
-  FRIEND_TEST(UserCollectorTest, GetStateFromStatus);
-  FRIEND_TEST(UserCollectorTest, GetProcessPath);
-  FRIEND_TEST(UserCollectorTest, GetSymlinkTarget);
-  FRIEND_TEST(UserCollectorTest, GetUserInfoFromName);
-  FRIEND_TEST(UserCollectorTest, ParseCrashAttributes);
-  FRIEND_TEST(UserCollectorTest, ShouldDumpChromeOverridesDeveloperImage);
-  FRIEND_TEST(UserCollectorTest, ShouldDumpDeveloperImageOverridesConsent);
-  FRIEND_TEST(UserCollectorTest, ShouldDumpUseConsentProductionImage);
-  FRIEND_TEST(UserCollectorTest, ValidateProcFiles);
-  FRIEND_TEST(UserCollectorTest, ValidateCoreFile);
-
-  // Enumeration to pass to GetIdFromStatus.  Must match the order
-  // that the kernel lists IDs in the status file.
-  enum IdKind {
-    kIdReal = 0,  // uid and gid
-    kIdEffective = 1,  // euid and egid
-    kIdSet = 2,  // suid and sgid
-    kIdFileSystem = 3,  // fsuid and fsgid
-    kIdMax
-  };
-
-  enum ErrorType {
-    kErrorNone,
-    kErrorSystemIssue,
-    kErrorReadCoreData,
-    kErrorUnusableProcFiles,
-    kErrorInvalidCoreFile,
-    kErrorUnsupported32BitCoreFile,
-    kErrorCore2MinidumpConversion,
-  };
-
-  static const int kForkProblem = 255;
-
-  // Returns an error type signature for a given |error_type| value,
-  // which is reported to the crash server along with the
-  // crash_reporter-user-collection signature.
-  std::string GetErrorTypeSignature(ErrorType error_type) const;
-
-  bool SetUpInternal(bool enabled);
-
-  // Returns, via |line|, the first line in |lines| that starts with |prefix|.
-  // Returns true if a line is found, or false otherwise.
-  bool GetFirstLineWithPrefix(const std::vector<std::string> &lines,
-                              const char *prefix, std::string *line);
-
-  // Returns the identifier of |kind|, via |id|, found in |status_lines| on
-  // the line starting with |prefix|. |status_lines| contains the lines in
-  // the status file. Returns true if the identifier can be determined.
-  bool GetIdFromStatus(const char *prefix,
-                       IdKind kind,
-                       const std::vector<std::string> &status_lines,
-                       int *id);
-
-  // Returns the process state, via |state|, found in |status_lines|, which
-  // contains the lines in the status file. Returns true if the process state
-  // can be determined.
-  bool GetStateFromStatus(const std::vector<std::string> &status_lines,
-                          std::string *state);
-
-  void LogCollectionError(const std::string &error_message);
-  void EnqueueCollectionErrorLog(pid_t pid, ErrorType error_type,
-                                 const std::string &exec_name);
-
-  bool CopyOffProcFiles(pid_t pid, const base::FilePath &container_dir);
-
-  // Validates the proc files at |container_dir| and returns true if they
-  // are usable for the core-to-minidump conversion later. For instance, if
-  // a process is reaped by the kernel before the copying of its proc files
-  // takes place, some proc files like /proc/<pid>/maps may contain nothing
-  // and thus become unusable.
-  bool ValidateProcFiles(const base::FilePath &container_dir) const;
-
-  // Validates the core file at |core_path| and returns kErrorNone if
-  // the file contains the ELF magic bytes and an ELF class that matches the
-  // platform (i.e. 32-bit ELF on a 32-bit platform or 64-bit ELF on a 64-bit
-  // platform), which is due to the limitation in core2md. It returns an error
-  // type otherwise.
-  ErrorType ValidateCoreFile(const base::FilePath &core_path) const;
-
-  // Determines the crash directory for given pid based on pid's owner,
-  // and creates the directory if necessary with appropriate permissions.
-  // Returns true whether or not directory needed to be created, false on
-  // any failure.
-  bool GetCreatedCrashDirectory(pid_t pid, uid_t supplied_ruid,
-                                base::FilePath *crash_file_path,
-                                bool *out_of_capacity);
-  bool CopyStdinToCoreFile(const base::FilePath &core_path);
-  bool RunCoreToMinidump(const base::FilePath &core_path,
-                         const base::FilePath &procfs_directory,
-                         const base::FilePath &minidump_path,
-                         const base::FilePath &temp_directory);
-  ErrorType ConvertCoreToMinidump(pid_t pid,
-                                  const base::FilePath &container_dir,
-                                  const base::FilePath &core_path,
-                                  const base::FilePath &minidump_path);
-  ErrorType ConvertAndEnqueueCrash(pid_t pid, const std::string &exec_name,
-                                   uid_t supplied_ruid, bool *out_of_capacity);
-  bool ParseCrashAttributes(const std::string &crash_attributes,
-                            pid_t *pid, int *signal, uid_t *uid, gid_t *gid,
-                            std::string *kernel_supplied_name);
-
-  bool ShouldDump(bool has_owner_consent,
-                  bool is_developer,
-                  std::string *reason);
-
-  bool generate_diagnostics_;
-  std::string our_path_;
-  bool initialized_;
-
-  bool core2md_failure_;
-  bool directory_failure_;
-  std::string filter_in_;
-
-  static const char *kUserId;
-  static const char *kGroupId;
-
-  DISALLOW_COPY_AND_ASSIGN(UserCollector);
-};
-
-#endif  // CRASH_REPORTER_USER_COLLECTOR_H_
diff --git a/crash_reporter/user_collector_test.cc b/crash_reporter/user_collector_test.cc
deleted file mode 100644
index d9c9a5b..0000000
--- a/crash_reporter/user_collector_test.cc
+++ /dev/null
@@ -1,438 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "user_collector.h"
-
-#include <elf.h>
-#include <sys/cdefs.h>  // For __WORDSIZE
-#include <unistd.h>
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/string_split.h>
-#include <brillo/syslog_logging.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using base::FilePath;
-using brillo::FindLog;
-
-namespace {
-
-int s_crashes = 0;
-bool s_metrics = false;
-
-const char kFilePath[] = "/my/path";
-
-void CountCrash() {
-  ++s_crashes;
-}
-
-bool IsMetrics() {
-  return s_metrics;
-}
-
-}  // namespace
-
-class UserCollectorMock : public UserCollector {
- public:
-  MOCK_METHOD0(SetUpDBus, void());
-};
-
-class UserCollectorTest : public ::testing::Test {
-  void SetUp() {
-    s_crashes = 0;
-
-    EXPECT_CALL(collector_, SetUpDBus()).WillRepeatedly(testing::Return());
-
-    collector_.Initialize(CountCrash,
-                          kFilePath,
-                          IsMetrics,
-                          false,
-                          false,
-                          false,
-                          "");
-
-    EXPECT_TRUE(test_dir_.CreateUniqueTempDir());
-
-    mkdir(test_dir_.path().Append("test").value().c_str(), 0777);
-    pid_ = getpid();
-    brillo::ClearLog();
-  }
-
- protected:
-  void ExpectFileEquals(const char *golden,
-                        const FilePath &file_path) {
-    std::string contents;
-    EXPECT_TRUE(base::ReadFileToString(file_path, &contents));
-    EXPECT_EQ(golden, contents);
-  }
-
-  std::vector<std::string> SplitLines(const std::string &lines) const {
-    return base::SplitString(lines, "\n", base::TRIM_WHITESPACE,
-                             base::SPLIT_WANT_ALL);
-  }
-
-  UserCollectorMock collector_;
-  pid_t pid_;
-  base::ScopedTempDir test_dir_;
-};
-
-TEST_F(UserCollectorTest, ParseCrashAttributes) {
-  pid_t pid;
-  int signal;
-  uid_t uid;
-  gid_t gid;
-  std::string exec_name;
-  EXPECT_TRUE(collector_.ParseCrashAttributes("123456:11:1000:2000:foobar",
-      &pid, &signal, &uid, &gid, &exec_name));
-  EXPECT_EQ(123456, pid);
-  EXPECT_EQ(11, signal);
-  EXPECT_EQ(1000, uid);
-  EXPECT_EQ(2000, gid);
-  EXPECT_EQ("foobar", exec_name);
-  EXPECT_TRUE(collector_.ParseCrashAttributes("4321:6:barfoo",
-      &pid, &signal, &uid, &gid, &exec_name));
-  EXPECT_EQ(4321, pid);
-  EXPECT_EQ(6, signal);
-  EXPECT_EQ(-1, uid);
-  EXPECT_EQ(-1, gid);
-  EXPECT_EQ("barfoo", exec_name);
-
-  EXPECT_FALSE(collector_.ParseCrashAttributes("123456:11",
-      &pid, &signal, &uid, &gid, &exec_name));
-
-  EXPECT_TRUE(collector_.ParseCrashAttributes("123456:11:exec:extra",
-      &pid, &signal, &uid, &gid, &exec_name));
-  EXPECT_EQ("exec:extra", exec_name);
-
-  EXPECT_FALSE(collector_.ParseCrashAttributes("12345p:11:foobar",
-      &pid, &signal, &uid, &gid, &exec_name));
-
-  EXPECT_FALSE(collector_.ParseCrashAttributes("123456:1 :foobar",
-      &pid, &signal, &uid, &gid, &exec_name));
-
-  EXPECT_FALSE(collector_.ParseCrashAttributes("123456::foobar",
-      &pid, &signal, &uid, &gid, &exec_name));
-}
-
-TEST_F(UserCollectorTest, ShouldDumpDeveloperImageOverridesConsent) {
-  std::string reason;
-  EXPECT_TRUE(collector_.ShouldDump(false, true, &reason));
-  EXPECT_EQ("developer build - not testing - always dumping", reason);
-
-  // When running a crash test, behave as normal.
-  EXPECT_FALSE(collector_.ShouldDump(false, false, &reason));
-  EXPECT_EQ("ignoring - no consent", reason);
-}
-
-TEST_F(UserCollectorTest, ShouldDumpUseConsentProductionImage) {
-  std::string result;
-  EXPECT_FALSE(collector_.ShouldDump(false, false, &result));
-  EXPECT_EQ("ignoring - no consent", result);
-
-  EXPECT_TRUE(collector_.ShouldDump(true, false, &result));
-  EXPECT_EQ("handling", result);
-}
-
-TEST_F(UserCollectorTest, HandleCrashWithoutConsent) {
-  s_metrics = false;
-  collector_.HandleCrash("20:10:ignored", "foobar");
-  EXPECT_TRUE(FindLog(
-      "Received crash notification for foobar[20] sig 10"));
-  ASSERT_EQ(s_crashes, 0);
-}
-
-TEST_F(UserCollectorTest, HandleNonChromeCrashWithConsent) {
-  s_metrics = true;
-  collector_.HandleCrash("5:2:ignored", "chromeos-wm");
-  EXPECT_TRUE(FindLog(
-      "Received crash notification for chromeos-wm[5] sig 2"));
-  ASSERT_EQ(s_crashes, 1);
-}
-
-TEST_F(UserCollectorTest, GetProcessPath) {
-  FilePath path = collector_.GetProcessPath(100);
-  ASSERT_EQ("/proc/100", path.value());
-}
-
-TEST_F(UserCollectorTest, GetSymlinkTarget) {
-  FilePath result;
-  ASSERT_FALSE(collector_.GetSymlinkTarget(FilePath("/does_not_exist"),
-                                           &result));
-  ASSERT_TRUE(FindLog(
-      "Readlink failed on /does_not_exist with 2"));
-  std::string long_link = test_dir_.path().value();
-  for (int i = 0; i < 50; ++i)
-    long_link += "0123456789";
-  long_link += "/gold";
-
-  for (size_t len = 1; len <= long_link.size(); ++len) {
-    std::string this_link;
-    static const char* kLink =
-        test_dir_.path().Append("test/this_link").value().c_str();
-    this_link.assign(long_link.c_str(), len);
-    ASSERT_EQ(len, this_link.size());
-    unlink(kLink);
-    ASSERT_EQ(0, symlink(this_link.c_str(), kLink));
-    ASSERT_TRUE(collector_.GetSymlinkTarget(FilePath(kLink), &result));
-    ASSERT_EQ(this_link, result.value());
-  }
-}
-
-TEST_F(UserCollectorTest, GetExecutableBaseNameFromPid) {
-  std::string base_name;
-  EXPECT_FALSE(collector_.GetExecutableBaseNameFromPid(0, &base_name));
-  EXPECT_TRUE(FindLog(
-      "Readlink failed on /proc/0/exe with 2"));
-  EXPECT_TRUE(FindLog(
-      "GetSymlinkTarget failed - Path /proc/0 DirectoryExists: 0"));
-  EXPECT_TRUE(FindLog("stat /proc/0/exe failed: -1 2"));
-
-  brillo::ClearLog();
-  pid_t my_pid = getpid();
-  EXPECT_TRUE(collector_.GetExecutableBaseNameFromPid(my_pid, &base_name));
-  EXPECT_FALSE(FindLog("Readlink failed"));
-  EXPECT_EQ("crash_reporter_tests", base_name);
-}
-
-TEST_F(UserCollectorTest, GetFirstLineWithPrefix) {
-  std::vector<std::string> lines;
-  std::string line;
-
-  EXPECT_FALSE(collector_.GetFirstLineWithPrefix(lines, "Name:", &line));
-  EXPECT_EQ("", line);
-
-  lines.push_back("Name:\tls");
-  lines.push_back("State:\tR (running)");
-  lines.push_back(" Foo:\t1000");
-
-  line.clear();
-  EXPECT_TRUE(collector_.GetFirstLineWithPrefix(lines, "Name:", &line));
-  EXPECT_EQ(lines[0], line);
-
-  line.clear();
-  EXPECT_TRUE(collector_.GetFirstLineWithPrefix(lines, "State:", &line));
-  EXPECT_EQ(lines[1], line);
-
-  line.clear();
-  EXPECT_FALSE(collector_.GetFirstLineWithPrefix(lines, "Foo:", &line));
-  EXPECT_EQ("", line);
-
-  line.clear();
-  EXPECT_TRUE(collector_.GetFirstLineWithPrefix(lines, " Foo:", &line));
-  EXPECT_EQ(lines[2], line);
-
-  line.clear();
-  EXPECT_FALSE(collector_.GetFirstLineWithPrefix(lines, "Bar:", &line));
-  EXPECT_EQ("", line);
-}
-
-TEST_F(UserCollectorTest, GetIdFromStatus) {
-  int id = 1;
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                          UserCollector::kIdEffective,
-                                          SplitLines("nothing here"),
-                                          &id));
-  EXPECT_EQ(id, 1);
-
-  // Not enough parameters.
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                          UserCollector::kIdReal,
-                                          SplitLines("line 1\nUid:\t1\n"),
-                                          &id));
-
-  const std::vector<std::string> valid_contents =
-      SplitLines("\nUid:\t1\t2\t3\t4\nGid:\t5\t6\t7\t8\n");
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                         UserCollector::kIdReal,
-                                         valid_contents,
-                                         &id));
-  EXPECT_EQ(1, id);
-
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                         UserCollector::kIdEffective,
-                                         valid_contents,
-                                         &id));
-  EXPECT_EQ(2, id);
-
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                         UserCollector::kIdFileSystem,
-                                         valid_contents,
-                                         &id));
-  EXPECT_EQ(4, id);
-
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kGroupId,
-                                         UserCollector::kIdEffective,
-                                         valid_contents,
-                                         &id));
-  EXPECT_EQ(6, id);
-
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kGroupId,
-                                         UserCollector::kIdSet,
-                                         valid_contents,
-                                         &id));
-  EXPECT_EQ(7, id);
-
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kGroupId,
-                                          UserCollector::IdKind(5),
-                                          valid_contents,
-                                          &id));
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kGroupId,
-                                          UserCollector::IdKind(-1),
-                                          valid_contents,
-                                          &id));
-
-  // Fail if junk after number
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                          UserCollector::kIdReal,
-                                          SplitLines("Uid:\t1f\t2\t3\t4\n"),
-                                          &id));
-  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                         UserCollector::kIdReal,
-                                         SplitLines("Uid:\t1\t2\t3\t4\n"),
-                                         &id));
-  EXPECT_EQ(1, id);
-
-  // Fail if more than 4 numbers.
-  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
-                                          UserCollector::kIdReal,
-                                          SplitLines("Uid:\t1\t2\t3\t4\t5\n"),
-                                          &id));
-}
-
-TEST_F(UserCollectorTest, GetStateFromStatus) {
-  std::string state;
-  EXPECT_FALSE(collector_.GetStateFromStatus(SplitLines("nothing here"),
-                                             &state));
-  EXPECT_EQ("", state);
-
-  EXPECT_TRUE(collector_.GetStateFromStatus(SplitLines("State:\tR (running)"),
-                                            &state));
-  EXPECT_EQ("R (running)", state);
-
-  EXPECT_TRUE(collector_.GetStateFromStatus(
-      SplitLines("Name:\tls\nState:\tZ (zombie)\n"), &state));
-  EXPECT_EQ("Z (zombie)", state);
-}
-
-TEST_F(UserCollectorTest, GetUserInfoFromName) {
-  gid_t gid = 100;
-  uid_t uid = 100;
-  EXPECT_TRUE(collector_.GetUserInfoFromName("root", &uid, &gid));
-  EXPECT_EQ(0, uid);
-  EXPECT_EQ(0, gid);
-}
-
-TEST_F(UserCollectorTest, CopyOffProcFilesBadPath) {
-  // Try a path that is not writable.
-  ASSERT_FALSE(collector_.CopyOffProcFiles(pid_, FilePath("/bad/path")));
-  EXPECT_TRUE(FindLog("Could not create /bad/path"));
-}
-
-TEST_F(UserCollectorTest, CopyOffProcFilesBadPid) {
-  FilePath container_path(test_dir_.path().Append("test/container"));
-  ASSERT_FALSE(collector_.CopyOffProcFiles(0, container_path));
-  EXPECT_TRUE(FindLog("Path /proc/0 does not exist"));
-}
-
-TEST_F(UserCollectorTest, CopyOffProcFilesOK) {
-  FilePath container_path(test_dir_.path().Append("test/container"));
-  ASSERT_TRUE(collector_.CopyOffProcFiles(pid_, container_path));
-  EXPECT_FALSE(FindLog("Could not copy"));
-  static struct {
-    const char *name;
-    bool exists;
-  } expectations[] = {
-    { "auxv", true },
-    { "cmdline", true },
-    { "environ", true },
-    { "maps", true },
-    { "mem", false },
-    { "mounts", false },
-    { "sched", false },
-    { "status", true }
-  };
-  for (unsigned i = 0; i < sizeof(expectations)/sizeof(expectations[0]); ++i) {
-    EXPECT_EQ(expectations[i].exists,
-              base::PathExists(
-                  container_path.Append(expectations[i].name)));
-  }
-}
-
-TEST_F(UserCollectorTest, ValidateProcFiles) {
-  FilePath container_dir = test_dir_.path();
-
-  // maps file not exists (i.e. GetFileSize fails)
-  EXPECT_FALSE(collector_.ValidateProcFiles(container_dir));
-
-  // maps file is empty
-  FilePath maps_file = container_dir.Append("maps");
-  ASSERT_EQ(0, base::WriteFile(maps_file, nullptr, 0));
-  ASSERT_TRUE(base::PathExists(maps_file));
-  EXPECT_FALSE(collector_.ValidateProcFiles(container_dir));
-
-  // maps file is not empty
-  const char data[] = "test data";
-  ASSERT_EQ(sizeof(data), base::WriteFile(maps_file, data, sizeof(data)));
-  ASSERT_TRUE(base::PathExists(maps_file));
-  EXPECT_TRUE(collector_.ValidateProcFiles(container_dir));
-}
-
-TEST_F(UserCollectorTest, ValidateCoreFile) {
-  FilePath container_dir = test_dir_.path();
-  FilePath core_file = container_dir.Append("core");
-
-  // Core file does not exist
-  EXPECT_EQ(UserCollector::kErrorInvalidCoreFile,
-            collector_.ValidateCoreFile(core_file));
-  char e_ident[EI_NIDENT];
-  e_ident[EI_MAG0] = ELFMAG0;
-  e_ident[EI_MAG1] = ELFMAG1;
-  e_ident[EI_MAG2] = ELFMAG2;
-  e_ident[EI_MAG3] = ELFMAG3;
-#if __WORDSIZE == 32
-  e_ident[EI_CLASS] = ELFCLASS32;
-#elif __WORDSIZE == 64
-  e_ident[EI_CLASS] = ELFCLASS64;
-#else
-#error Unknown/unsupported value of __WORDSIZE.
-#endif
-
-  // Core file has the expected header
-  ASSERT_TRUE(base::WriteFile(core_file, e_ident, sizeof(e_ident)));
-  EXPECT_EQ(UserCollector::kErrorNone,
-            collector_.ValidateCoreFile(core_file));
-
-#if __WORDSIZE == 64
-  // 32-bit core file on 64-bit platform
-  e_ident[EI_CLASS] = ELFCLASS32;
-  ASSERT_TRUE(base::WriteFile(core_file, e_ident, sizeof(e_ident)));
-  EXPECT_EQ(UserCollector::kErrorUnsupported32BitCoreFile,
-            collector_.ValidateCoreFile(core_file));
-  e_ident[EI_CLASS] = ELFCLASS64;
-#endif
-
-  // Invalid core files
-  ASSERT_TRUE(base::WriteFile(core_file, e_ident, sizeof(e_ident) - 1));
-  EXPECT_EQ(UserCollector::kErrorInvalidCoreFile,
-            collector_.ValidateCoreFile(core_file));
-
-  e_ident[EI_MAG0] = 0;
-  ASSERT_TRUE(base::WriteFile(core_file, e_ident, sizeof(e_ident)));
-  EXPECT_EQ(UserCollector::kErrorInvalidCoreFile,
-            collector_.ValidateCoreFile(core_file));
-}
diff --git a/crash_reporter/warn_collector.l b/crash_reporter/warn_collector.l
deleted file mode 100644
index 70ab25c..0000000
--- a/crash_reporter/warn_collector.l
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * This flex program reads /var/log/messages as it grows and saves kernel
- * warnings to files.  It keeps track of warnings it has seen (based on
- * file/line only, ignoring differences in the stack trace), and reports only
- * the first warning of each kind, but maintains a count of all warnings by
- * using their hashes as buckets in a UMA sparse histogram.  It also invokes
- * the crash collector, which collects the warnings and prepares them for later
- * shipment to the crash server.
- */
-
-%option noyywrap
-
-%{
-#include <fcntl.h>
-#include <inttypes.h>
-#include <pwd.h>
-#include <stdarg.h>
-#include <sys/inotify.h>
-#include <sys/select.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "metrics/c_metrics_library.h"
-
-int WarnStart(void);
-void WarnEnd(void);
-void WarnInput(char *buf, yy_size_t *result, size_t max_size);
-
-#define YY_INPUT(buf, result, max_size) WarnInput(buf, &result, max_size)
-
-%}
-
-/* Define a few useful regular expressions. */
-
-D               [0-9]
-PREFIX          .*" kernel: [ "*{D}+"."{D}+"]"
-CUT_HERE        {PREFIX}" ------------[ cut here".*
-WARNING         {PREFIX}" WARNING: at "
-END_TRACE       {PREFIX}" ---[ end trace".*
-
-/* Use exclusive start conditions. */
-%x PRE_WARN WARN
-
-%%
- /* The scanner itself. */
-
-^{CUT_HERE}\n{WARNING}          BEGIN(PRE_WARN);
-.|\n                            /* ignore all other input in state 0 */
-<PRE_WARN>[^ ]+.[^ ]+\n         if (WarnStart()) {
-                                  /* yytext is
-                                     "file:line func+offset/offset()\n" */
-                                  BEGIN(WARN); ECHO;
-                                } else {
-                                  BEGIN(0);
-                                }
-
- /* Assume the warning ends at the "end trace" line */
-<WARN>^{END_TRACE}\n            ECHO; BEGIN(0); WarnEnd();
-<WARN>^.*\n                     ECHO;
-
-%%
-
-#define HASH_BITMAP_SIZE        (1 << 15)  /* size in bits */
-#define HASH_BITMAP_MASK        (HASH_BITMAP_SIZE - 1)
-
-const char warn_hist_name[] = "Platform.KernelWarningHashes";
-uint32_t hash_bitmap[HASH_BITMAP_SIZE / 32];
-CMetricsLibrary metrics_library;
-
-const char *prog_name;          /* the name of this program */
-int yyin_fd;                    /* instead of FILE *yyin to avoid buffering */
-int i_fd;                       /* for inotify, to detect file changes */
-int testing;                    /* 1 if running test */
-int filter;                     /* 1 when using as filter (for development) */
-int fifo;                       /* 1 when reading from fifo (for devel) */
-int draining;                   /* 1 when draining renamed log file */
-
-const char *msg_path = "/var/log/messages";
-const char warn_dump_dir[]  = "/var/run/kwarn";
-const char *warn_dump_path = "/var/run/kwarn/warning";
-const char *crash_reporter_command;
-
-__attribute__((__format__(__printf__, 1, 2)))
-static void Die(const char *format, ...) {
-  va_list ap;
-  va_start(ap, format);
-  fprintf(stderr, "%s: ", prog_name);
-  vfprintf(stderr, format, ap);
-  exit(1);
-}
-
-static void RunCrashReporter(void) {
-  int status = system(crash_reporter_command);
-  if (status != 0)
-    Die("%s exited with status %d\n", crash_reporter_command, status);
-}
-
-static uint32_t StringHash(const char *string) {
-  uint32_t hash = 0;
-  while (*string != '\0') {
-    hash = (hash << 5) + hash + *string++;
-  }
-  return hash;
-}
-
-/* We expect only a handful of different warnings per boot session, so the
- * probability of a collision is very low, and statistically it won't matter
- * (unless warnings with the same hash also happens in tandem, which is even
- * rarer).
- */
-static int HashSeen(uint32_t hash) {
-  int word_index = (hash & HASH_BITMAP_MASK) / 32;
-  int bit_index = (hash & HASH_BITMAP_MASK) % 32;
-  return hash_bitmap[word_index] & 1 << bit_index;
-}
-
-static void SetHashSeen(uint32_t hash) {
-  int word_index = (hash & HASH_BITMAP_MASK) / 32;
-  int bit_index = (hash & HASH_BITMAP_MASK) % 32;
-  hash_bitmap[word_index] |= 1 << bit_index;
-}
-
-#pragma GCC diagnostic ignored "-Wwrite-strings"
-int WarnStart(void) {
-  uint32_t hash;
-  char *spacep;
-
-  if (filter)
-    return 1;
-
-  hash = StringHash(yytext);
-  if (!(testing || fifo || filter)) {
-    CMetricsLibrarySendSparseToUMA(metrics_library, warn_hist_name, (int) hash);
-  }
-  if (HashSeen(hash))
-    return 0;
-  SetHashSeen(hash);
-
-  yyout = fopen(warn_dump_path, "w");
-  if (yyout == NULL)
-    Die("fopen %s failed: %s\n", warn_dump_path, strerror(errno));
-  spacep = strchr(yytext, ' ');
-  if (spacep == NULL || spacep[1] == '\0')
-    spacep = "unknown-function";
-  fprintf(yyout, "%08x-%s\n", hash, spacep + 1);
-  return 1;
-}
-
-void WarnEnd(void) {
-  if (filter)
-    return;
-  fclose(yyout);
-  yyout = stdout;               /* for debugging */
-  RunCrashReporter();
-}
-
-static void WarnOpenInput(const char *path) {
-  yyin_fd = open(path, O_RDONLY);
-  if (yyin_fd < 0)
-    Die("could not open %s: %s\n", path, strerror(errno));
-  if (!fifo) {
-    /* Go directly to the end of the file.  We don't want to parse the same
-     * warnings multiple times on reboot/restart.  We might miss some
-     * warnings, but so be it---it's too hard to keep track reliably of the
-     * last parsed position in the syslog.
-     */
-    if (lseek(yyin_fd, 0, SEEK_END) < 0)
-      Die("could not lseek %s: %s\n", path, strerror(errno));
-    /* Set up notification of file growth and rename. */
-    i_fd = inotify_init();
-    if (i_fd < 0)
-      Die("inotify_init: %s\n", strerror(errno));
-    if (inotify_add_watch(i_fd, path, IN_MODIFY | IN_MOVE_SELF) < 0)
-      Die("inotify_add_watch: %s\n", strerror(errno));
-  }
-}
-
-/* We replace the default YY_INPUT() for the following reasons:
- *
- * 1.  We want to read data as soon as it becomes available, but the default
- * YY_INPUT() uses buffered I/O.
- *
- * 2.  We want to block on end of input and wait for the file to grow.
- *
- * 3.  We want to detect log rotation, and reopen the input file as needed.
- */
-void WarnInput(char *buf, yy_size_t *result, size_t max_size) {
-  while (1) {
-    ssize_t ret = read(yyin_fd, buf, max_size);
-    if (ret < 0)
-      Die("read: %s", strerror(errno));
-    *result = ret;
-    if (*result > 0 || fifo || filter)
-      return;
-    if (draining) {
-      /* Assume we're done with this log, and move to next
-       * log.  Rsyslogd may keep writing to the old log file
-       * for a while, but we don't care since we don't have
-       * to be exact.
-       */
-      close(yyin_fd);
-      if (YYSTATE == WARN) {
-        /* Be conservative in case we lose the warn
-         * terminator during the switch---or we may
-         * collect personally identifiable information.
-         */
-        WarnEnd();
-      }
-      BEGIN(0);        /* see above comment */
-      sleep(1);        /* avoid race with log rotator */
-      WarnOpenInput(msg_path);
-      draining = 0;
-      continue;
-    }
-    /* Nothing left to read, so we must wait. */
-    struct inotify_event event;
-    while (1) {
-      int n = read(i_fd, &event, sizeof(event));
-      if (n <= 0) {
-        if (errno == EINTR)
-          continue;
-        else
-          Die("inotify: %s\n", strerror(errno));
-      } else
-        break;
-    }
-    if (event.mask & IN_MOVE_SELF) {
-      /* The file has been renamed.  Before switching
-       * to the new one, we process any remaining
-       * content of this file.
-       */
-      draining = 1;
-    }
-  }
-}
-
-int main(int argc, char **argv) {
-  int result;
-  struct passwd *user;
-  prog_name = argv[0];
-
-  if (argc == 2 && strcmp(argv[1], "--test") == 0)
-    testing = 1;
-  else if (argc == 2 && strcmp(argv[1], "--filter") == 0)
-    filter = 1;
-  else if (argc == 2 && strcmp(argv[1], "--fifo") == 0) {
-    fifo = 1;
-  } else if (argc != 1) {
-    fprintf(stderr,
-            "usage: %s [single-flag]\n"
-            "flags (for testing only):\n"
-            "--fifo\tinput is fifo \"fifo\", output is stdout\n"
-            "--filter\tinput is stdin, output is stdout\n"
-            "--test\trun self-test\n",
-            prog_name);
-    exit(1);
-  }
-
-  metrics_library = CMetricsLibraryNew();
-  CMetricsLibraryInit(metrics_library);
-
-  crash_reporter_command = testing ?
-    "./warn_collector_test_reporter.sh" :
-    "/sbin/crash_reporter --kernel_warning";
-
-  /* When filtering with --filter (for development) use stdin for input.
-   * Otherwise read input from a file or a fifo.
-   */
-  yyin_fd = fileno(stdin);
-  if (testing) {
-    msg_path = "messages";
-    warn_dump_path = "warning";
-  }
-  if (fifo) {
-    msg_path = "fifo";
-  }
-  if (!filter) {
-    WarnOpenInput(msg_path);
-  }
-
-  /* Create directory for dump file.  Still need to be root here. */
-  unlink(warn_dump_path);
-  if (!testing && !fifo && !filter) {
-    rmdir(warn_dump_dir);
-    result = mkdir(warn_dump_dir, 0755);
-    if (result < 0)
-      Die("could not create %s: %s\n",
-          warn_dump_dir, strerror(errno));
-  }
-
-  if (0) {
-    /* TODO(semenzato): put this back in once we decide it's safe
-     * to make /var/spool/crash rwxrwxrwx root, or use a different
-     * owner and setuid for the crash reporter as well.
-     */
-
-    /* Get low privilege uid, gid. */
-    user = getpwnam("chronos");
-    if (user == NULL)
-      Die("getpwnam failed\n");
-
-    /* Change dump directory ownership. */
-    if (chown(warn_dump_dir, user->pw_uid, user->pw_gid) < 0)
-      Die("chown: %s\n", strerror(errno));
-
-    /* Drop privileges. */
-    if (setuid(user->pw_uid) < 0) {
-      Die("setuid: %s\n", strerror(errno));
-    }
-  }
-
-  /* Go! */
-  return yylex();
-}
-
-/* Flex should really know not to generate these functions.
- */
-void UnusedFunctionWarningSuppressor(void) {
-  yyunput(0, 0);
-}
diff --git a/crash_reporter/warn_collector_test.c b/crash_reporter/warn_collector_test.c
deleted file mode 100644
index 7ebe0a8..0000000
--- a/crash_reporter/warn_collector_test.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Test driver for the warn_collector daemon.
- */
-#include <stdlib.h>
-
-int main(int ac, char **av) {
-  int status = system("exec \"${SRC}\"/warn_collector_test.sh");
-  return status < 0 ? EXIT_FAILURE : WEXITSTATUS(status);
-}
diff --git a/crash_reporter/warn_collector_test.sh b/crash_reporter/warn_collector_test.sh
deleted file mode 100755
index a5af16c..0000000
--- a/crash_reporter/warn_collector_test.sh
+++ /dev/null
@@ -1,90 +0,0 @@
-#! /bin/bash
-
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Test for warn_collector.  Run the warn collector in the background, emulate
-# the kernel by appending lines to the log file "messages", and observe the log
-# of the (fake) crash reporter each time is run by the warn collector daemon.
-
-set -e
-
-fail() {
-  printf '[ FAIL ] %b\n' "$*"
-  exit 1
-}
-
-if [[ -z ${SYSROOT} ]]; then
-  fail "SYSROOT must be set for this test to work"
-fi
-: ${OUT:=${PWD}}
-cd "${OUT}"
-PATH=${OUT}:${PATH}
-TESTLOG="${OUT}/warn-test-log"
-
-echo "Testing: $(which warn_collector)"
-
-cleanup() {
-  # Kill daemon (if started) on exit
-  kill %
-}
-
-check_log() {
-  local n_expected=$1
-  if [[ ! -f ${TESTLOG} ]]; then
-    fail "${TESTLOG} was not created"
-  fi
-  if [[ $(wc -l < "${TESTLOG}") -ne ${n_expected} ]]; then
-    fail "expected ${n_expected} lines in ${TESTLOG}, found this instead:
-$(<"${TESTLOG}")"
-  fi
-  if egrep -qv '^[0-9a-f]{8}' "${TESTLOG}"; then
-    fail "found bad lines in ${TESTLOG}:
-$(<"${TESTLOG}")"
-  fi
-}
-
-rm -f "${TESTLOG}"
-cp "${SRC}/warn_collector_test_reporter.sh" .
-cp "${SRC}/TEST_WARNING" .
-cp TEST_WARNING messages
-
-# Start the collector daemon.  With the --test option, the daemon reads input
-# from ./messages, writes the warning into ./warning, and invokes
-# ./warn_collector_test_reporter.sh to report the warning.
-warn_collector --test &
-trap cleanup EXIT
-
-# After a while, check that the first warning has been collected.
-sleep 1
-check_log 1
-
-# Add the same warning to messages, verify that it is NOT collected
-cat TEST_WARNING >> messages
-sleep 1
-check_log 1
-
-# Add a slightly different warning to messages, check that it is collected.
-sed s/intel_dp.c/intel_xx.c/ < TEST_WARNING >> messages
-sleep 1
-check_log 2
-
-# Emulate log rotation, add a warning, and check.
-mv messages messages.1
-sed s/intel_dp.c/intel_xy.c/ < TEST_WARNING > messages
-sleep 2
-check_log 3
-
-# Success!
-exit 0
diff --git a/crash_reporter/warn_collector_test_reporter.sh b/crash_reporter/warn_collector_test_reporter.sh
deleted file mode 100755
index b6096ed..0000000
--- a/crash_reporter/warn_collector_test_reporter.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#! /bin/sh
-
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Replacement for the crash reporter, for testing.  Log the first line of the
-# "warning" file, which by convention contains the warning hash, and remove the
-# file.
-
-set -e
-
-exec 1>> warn-test-log
-exec 2>> warn-test-log
-
-head -1 warning
-rm warning
diff --git a/debuggerd/.clang-format b/debuggerd/.clang-format
deleted file mode 100644
index 9b7478c..0000000
--- a/debuggerd/.clang-format
+++ /dev/null
@@ -1,15 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 2
-ContinuationIndentWidth: 2
-PointerAlignment: Left
-TabWidth: 2
-UseTab: Never
-PenaltyExcessCharacter: 32
-
-Cpp11BracedListStyle: false
diff --git a/debuggerd/.clang-format b/debuggerd/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/debuggerd/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
new file mode 100644
index 0000000..4783d6e
--- /dev/null
+++ b/debuggerd/Android.bp
@@ -0,0 +1,270 @@
+cc_defaults {
+    name: "debuggerd_defaults",
+    defaults: ["linux_bionic_supported"],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-Wno-nullability-completeness",
+        "-Os",
+    ],
+
+    // util.cpp gets async signal safe logging via libc_logging,
+    // which defines its interface in bionic private headers.
+    include_dirs: ["bionic/libc"],
+
+    local_include_dirs: ["include"],
+}
+
+// Utility library to tombstoned and get an output fd.
+cc_library_static {
+    name: "libtombstoned_client",
+    defaults: ["debuggerd_defaults"],
+    srcs: [
+        "tombstoned_client.cpp",
+        "util.cpp",
+    ],
+
+    whole_static_libs: [
+        "libc_logging",
+        "libcutils",
+        "libbase",
+    ],
+}
+
+// Core implementation, linked into libdebuggerd_handler and the dynamic linker.
+cc_library_static {
+    name: "libdebuggerd_handler_core",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["handler/debuggerd_handler.cpp"],
+
+    whole_static_libs: [
+        "libc_logging",
+        "libdebuggerd",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+// Implementation with a no-op fallback.
+cc_library_static {
+    name: "libdebuggerd_handler",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["handler/debuggerd_fallback_nop.cpp"],
+
+    whole_static_libs: [
+        "libdebuggerd_handler_core",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+// Fallback implementation.
+cc_library_static {
+    name: "libdebuggerd_handler_fallback",
+    defaults: ["debuggerd_defaults"],
+    srcs: [
+        "handler/debuggerd_fallback.cpp",
+    ],
+
+    whole_static_libs: [
+        "libdebuggerd_handler_core",
+        "libtombstoned_client",
+        "libbase",
+        "libdebuggerd",
+        "libbacktrace",
+        "libunwind",
+        "liblzma",
+        "libcutils",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+cc_library {
+    name: "libdebuggerd_client",
+    defaults: ["debuggerd_defaults"],
+    srcs: [
+        "client/debuggerd_client.cpp",
+        "util.cpp",
+    ],
+
+    shared_libs: [
+        "libbase",
+        "libcutils",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+cc_library_static {
+    name: "libdebuggerd",
+    defaults: ["debuggerd_defaults"],
+
+    srcs: [
+        "libdebuggerd/backtrace.cpp",
+        "libdebuggerd/elf_utils.cpp",
+        "libdebuggerd/open_files_list.cpp",
+        "libdebuggerd/tombstone.cpp",
+        "libdebuggerd/utility.cpp",
+    ],
+
+    target: {
+        android_arm: {
+            srcs: ["libdebuggerd/arm/machine.cpp"],
+        },
+        android_arm64: {
+            srcs: ["libdebuggerd/arm64/machine.cpp"],
+        },
+        android_mips: {
+            srcs: ["libdebuggerd/mips/machine.cpp"],
+        },
+        android_mips64: {
+            srcs: ["libdebuggerd/mips64/machine.cpp"],
+        },
+        android_x86: {
+            srcs: ["libdebuggerd/x86/machine.cpp"],
+        },
+        android_x86_64: {
+            srcs: ["libdebuggerd/x86_64/machine.cpp"],
+        },
+    },
+
+    local_include_dirs: ["libdebuggerd/include"],
+    export_include_dirs: ["libdebuggerd/include"],
+
+    static_libs: [
+        "libbacktrace",
+        "libunwind",
+        "liblzma",
+        "libbase",
+        "libcutils",
+        "liblog",
+    ],
+}
+
+cc_test {
+    name: "debuggerd_test",
+    defaults: ["debuggerd_defaults"],
+
+    cflags: ["-Wno-missing-field-initializers"],
+    srcs: [
+        "libdebuggerd/test/dump_memory_test.cpp",
+        "libdebuggerd/test/elf_fake.cpp",
+        "libdebuggerd/test/log_fake.cpp",
+        "libdebuggerd/test/open_files_list_test.cpp",
+        "libdebuggerd/test/property_fake.cpp",
+        "libdebuggerd/test/ptrace_fake.cpp",
+        "libdebuggerd/test/tombstone_test.cpp",
+    ],
+
+    target: {
+        android: {
+            srcs: [
+                "client/debuggerd_client_test.cpp",
+                "debuggerd_test.cpp",
+                "tombstoned_client.cpp",
+                "util.cpp"
+            ],
+        },
+    },
+
+    shared_libs: [
+        "libbacktrace",
+        "libbase",
+        "libcutils",
+        "libdebuggerd_client",
+    ],
+
+    static_libs: [
+        "libdebuggerd",
+        "libc_logging",
+    ],
+
+    local_include_dirs: [
+        "libdebuggerd",
+    ],
+
+    compile_multilib: "both",
+    multilib: {
+        lib32: {
+            stem: "debuggerd_test32",
+        },
+        lib64: {
+            stem: "debuggerd_test64",
+        },
+    },
+}
+
+cc_binary {
+    name: "crash_dump",
+    srcs: [
+        "crash_dump.cpp",
+        "util.cpp",
+    ],
+    defaults: ["debuggerd_defaults"],
+
+    compile_multilib: "both",
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+
+    static_libs: [
+        "libtombstoned_client",
+        "libdebuggerd",
+        "libcutils",
+    ],
+
+    shared_libs: [
+        "libbacktrace",
+        "libbase",
+        "liblog",
+        "libprocinfo",
+        "libselinux",
+    ],
+}
+
+cc_binary {
+    name: "debuggerd",
+    srcs: [
+        "debuggerd.cpp",
+    ],
+    defaults: ["debuggerd_defaults"],
+
+    shared_libs: [
+        "libbase",
+        "libdebuggerd_client",
+        "liblog",
+        "libselinux",
+    ],
+
+    local_include_dirs: ["include"],
+}
+
+cc_binary {
+    name: "tombstoned",
+    srcs: [
+        "util.cpp",
+        "tombstoned/intercept_manager.cpp",
+        "tombstoned/tombstoned.cpp",
+    ],
+    defaults: ["debuggerd_defaults"],
+
+    static_libs: [
+        "libbase",
+        "libcutils",
+        "libevent",
+        "liblog",
+    ],
+
+    init_rc: ["tombstoned/tombstoned.rc"]
+}
+
+subdirs = [
+    "crasher",
+]
diff --git a/debuggerd/Android.mk b/debuggerd/Android.mk
deleted file mode 100644
index 6469db4..0000000
--- a/debuggerd/Android.mk
+++ /dev/null
@@ -1,134 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-common_cppflags := \
-    -std=gnu++11 \
-    -W \
-    -Wall \
-    -Wextra \
-    -Wunused \
-    -Werror \
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-    backtrace.cpp \
-    debuggerd.cpp \
-    elf_utils.cpp \
-    getevent.cpp \
-    signal_sender.cpp \
-    tombstone.cpp \
-    utility.cpp \
-
-LOCAL_SRC_FILES_arm    := arm/machine.cpp
-LOCAL_SRC_FILES_arm64  := arm64/machine.cpp
-LOCAL_SRC_FILES_mips   := mips/machine.cpp
-LOCAL_SRC_FILES_mips64 := mips64/machine.cpp
-LOCAL_SRC_FILES_x86    := x86/machine.cpp
-LOCAL_SRC_FILES_x86_64 := x86_64/machine.cpp
-
-LOCAL_CPPFLAGS := $(common_cppflags)
-
-LOCAL_INIT_RC_32 := debuggerd.rc
-LOCAL_INIT_RC_64 := debuggerd64.rc
-
-ifeq ($(TARGET_IS_64_BIT),true)
-LOCAL_CPPFLAGS += -DTARGET_IS_64_BIT
-endif
-
-LOCAL_SHARED_LIBRARIES := \
-    libbacktrace \
-    libbase \
-    libcutils \
-    liblog \
-    libselinux \
-
-LOCAL_CLANG := true
-
-LOCAL_MODULE := debuggerd
-LOCAL_MODULE_STEM_32 := debuggerd
-LOCAL_MODULE_STEM_64 := debuggerd64
-LOCAL_MULTILIB := both
-
-include $(BUILD_EXECUTABLE)
-
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := crasher.c
-LOCAL_SRC_FILES_arm    := arm/crashglue.S
-LOCAL_SRC_FILES_arm64  := arm64/crashglue.S
-LOCAL_SRC_FILES_mips   := mips/crashglue.S
-LOCAL_SRC_FILES_mips64 := mips64/crashglue.S
-LOCAL_SRC_FILES_x86    := x86/crashglue.S
-LOCAL_SRC_FILES_x86_64 := x86_64/crashglue.S
-LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
-LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS += -fstack-protector-all -Werror -Wno-free-nonheap-object -Wno-date-time
-#LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_SHARED_LIBRARIES := libcutils liblog libc
-
-# The arm emulator has VFP but not VFPv3-D32.
-ifeq ($(ARCH_ARM_HAVE_VFP_D32),true)
-LOCAL_ASFLAGS_arm += -DHAS_VFP_D32
-endif
-
-LOCAL_MODULE := crasher
-LOCAL_MODULE_STEM_32 := crasher
-LOCAL_MODULE_STEM_64 := crasher64
-LOCAL_MULTILIB := both
-
-include $(BUILD_EXECUTABLE)
-
-debuggerd_test_src_files := \
-    utility.cpp \
-    test/dump_memory_test.cpp \
-    test/elf_fake.cpp \
-    test/log_fake.cpp \
-    test/property_fake.cpp \
-    test/ptrace_fake.cpp \
-    test/tombstone_test.cpp \
-    test/selinux_fake.cpp \
-
-debuggerd_shared_libraries := \
-    libbacktrace \
-    libbase \
-    libcutils \
-
-debuggerd_c_includes := \
-    $(LOCAL_PATH)/test \
-
-debuggerd_cpp_flags := \
-    $(common_cppflags) \
-    -Wno-missing-field-initializers \
-    -fno-rtti \
-
-# Only build the host tests on linux.
-ifeq ($(HOST_OS),linux)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := debuggerd_test
-LOCAL_SRC_FILES := $(debuggerd_test_src_files)
-LOCAL_SHARED_LIBRARIES := $(debuggerd_shared_libraries)
-LOCAL_C_INCLUDES := $(debuggerd_c_includes)
-LOCAL_CPPFLAGS := $(debuggerd_cpp_flags)
-
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_MULTILIB := both
-include $(BUILD_HOST_NATIVE_TEST)
-
-endif
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := debuggerd_test
-LOCAL_SRC_FILES := $(debuggerd_test_src_files)
-LOCAL_SHARED_LIBRARIES := $(debuggerd_shared_libraries)
-LOCAL_C_INCLUDES := $(debuggerd_c_includes)
-LOCAL_CPPFLAGS := $(debuggerd_cpp_flags)
-
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_MULTILIB := both
-include $(BUILD_NATIVE_TEST)
diff --git a/debuggerd/arm/machine.cpp b/debuggerd/arm/machine.cpp
deleted file mode 100644
index 78c2306..0000000
--- a/debuggerd/arm/machine.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- *
- * Copyright 2006, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "machine.h"
-#include "utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  pt_regs regs;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &regs)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  static const char reg_names[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";
-
-  for (int reg = 0; reg < 14; reg++) {
-    dump_memory(log, backtrace, regs.uregs[reg], "memory near %.2s:", &reg_names[reg * 2]);
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_pc), "code around pc:");
-
-  if (regs.ARM_pc != regs.ARM_lr) {
-    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_lr), "code around lr:");
-  }
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  pt_regs r;
-  if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, "    r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",
-       static_cast<uint32_t>(r.ARM_r0), static_cast<uint32_t>(r.ARM_r1),
-       static_cast<uint32_t>(r.ARM_r2), static_cast<uint32_t>(r.ARM_r3));
-  _LOG(log, logtype::REGISTERS, "    r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",
-       static_cast<uint32_t>(r.ARM_r4), static_cast<uint32_t>(r.ARM_r5),
-       static_cast<uint32_t>(r.ARM_r6), static_cast<uint32_t>(r.ARM_r7));
-  _LOG(log, logtype::REGISTERS, "    r8 %08x  r9 %08x  sl %08x  fp %08x\n",
-       static_cast<uint32_t>(r.ARM_r8), static_cast<uint32_t>(r.ARM_r9),
-       static_cast<uint32_t>(r.ARM_r10), static_cast<uint32_t>(r.ARM_fp));
-  _LOG(log, logtype::REGISTERS, "    ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n",
-       static_cast<uint32_t>(r.ARM_ip), static_cast<uint32_t>(r.ARM_sp),
-       static_cast<uint32_t>(r.ARM_lr), static_cast<uint32_t>(r.ARM_pc),
-       static_cast<uint32_t>(r.ARM_cpsr));
-
-  user_vfp vfp_regs;
-  if (ptrace(PTRACE_GETVFPREGS, tid, 0, &vfp_regs)) {
-    ALOGE("cannot get FP registers: %s\n", strerror(errno));
-    return;
-  }
-
-  for (size_t i = 0; i < 32; i += 2) {
-    _LOG(log, logtype::FP_REGISTERS, "    d%-2d %016llx  d%-2d %016llx\n",
-         i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
-  }
-  _LOG(log, logtype::FP_REGISTERS, "    scr %08lx\n", vfp_regs.fpscr);
-}
diff --git a/debuggerd/arm64/machine.cpp b/debuggerd/arm64/machine.cpp
deleted file mode 100644
index e7bf79a..0000000
--- a/debuggerd/arm64/machine.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- *
- * Copyright 2014, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include <elf.h>
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-#include <sys/uio.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "machine.h"
-#include "utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  struct user_pt_regs regs;
-  struct iovec io;
-  io.iov_base = &regs;
-  io.iov_len = sizeof(regs);
-
-  if (ptrace(PTRACE_GETREGSET, backtrace->Tid(), reinterpret_cast<void*>(NT_PRSTATUS), &io) == -1) {
-    ALOGE("ptrace failed to get registers: %s", strerror(errno));
-    return;
-  }
-
-  for (int reg = 0; reg < 31; reg++) {
-    dump_memory(log, backtrace, regs.regs[reg], "memory near x%d:", reg);
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.pc), "code around pc:");
-
-  if (regs.pc != regs.sp) {
-    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.sp), "code around sp:");
-  }
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  struct user_pt_regs r;
-  struct iovec io;
-  io.iov_base = &r;
-  io.iov_len = sizeof(r);
-
-  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRSTATUS, (void*) &io) == -1) {
-    ALOGE("ptrace error: %s\n", strerror(errno));
-    return;
-  }
-
-  for (int i = 0; i < 28; i += 4) {
-    _LOG(log, logtype::REGISTERS,
-         "    x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx\n",
-         i, r.regs[i],
-         i+1, r.regs[i+1],
-         i+2, r.regs[i+2],
-         i+3, r.regs[i+3]);
-  }
-
-  _LOG(log, logtype::REGISTERS, "    x28  %016llx  x29  %016llx  x30  %016llx\n",
-       r.regs[28], r.regs[29], r.regs[30]);
-
-  _LOG(log, logtype::REGISTERS, "    sp   %016llx  pc   %016llx  pstate %016llx\n",
-       r.sp, r.pc, r.pstate);
-
-  struct user_fpsimd_state f;
-  io.iov_base = &f;
-  io.iov_len = sizeof(f);
-
-  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRFPREG, (void*) &io) == -1) {
-    ALOGE("ptrace error: %s\n", strerror(errno));
-    return;
-  }
-
-  for (int i = 0; i < 32; i += 2) {
-    _LOG(log, logtype::FP_REGISTERS,
-         "    v%-2d  %016" PRIx64 "%016" PRIx64 "  v%-2d  %016" PRIx64 "%016" PRIx64 "\n",
-         i,
-         static_cast<uint64_t>(f.vregs[i] >> 64),
-         static_cast<uint64_t>(f.vregs[i]),
-         i+1,
-         static_cast<uint64_t>(f.vregs[i+1] >> 64),
-         static_cast<uint64_t>(f.vregs[i+1]));
-  }
-  _LOG(log, logtype::FP_REGISTERS, "    fpsr %08x  fpcr %08x\n", f.fpsr, f.fpcr);
-}
diff --git a/debuggerd/backtrace.cpp b/debuggerd/backtrace.cpp
deleted file mode 100644
index 8f4a53f..0000000
--- a/debuggerd/backtrace.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <time.h>
-#include <errno.h>
-#include <limits.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/ptrace.h>
-
-#include <memory>
-#include <string>
-
-#include <backtrace/Backtrace.h>
-
-#include <log/log.h>
-
-#include "backtrace.h"
-
-#include "utility.h"
-
-static void dump_process_header(log_t* log, pid_t pid) {
-  char path[PATH_MAX];
-  char procnamebuf[1024];
-  char* procname = NULL;
-  FILE* fp;
-
-  snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
-  if ((fp = fopen(path, "r"))) {
-    procname = fgets(procnamebuf, sizeof(procnamebuf), fp);
-    fclose(fp);
-  }
-
-  time_t t = time(NULL);
-  struct tm tm;
-  localtime_r(&t, &tm);
-  char timestr[64];
-  strftime(timestr, sizeof(timestr), "%F %T", &tm);
-  _LOG(log, logtype::BACKTRACE, "\n\n----- pid %d at %s -----\n", pid, timestr);
-
-  if (procname) {
-    _LOG(log, logtype::BACKTRACE, "Cmd line: %s\n", procname);
-  }
-  _LOG(log, logtype::BACKTRACE, "ABI: '%s'\n", ABI_STRING);
-}
-
-static void dump_process_footer(log_t* log, pid_t pid) {
-  _LOG(log, logtype::BACKTRACE, "\n----- end %d -----\n", pid);
-}
-
-static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid) {
-  char path[PATH_MAX];
-  char threadnamebuf[1024];
-  char* threadname = NULL;
-  FILE* fp;
-
-  snprintf(path, sizeof(path), "/proc/%d/comm", tid);
-  if ((fp = fopen(path, "r"))) {
-    threadname = fgets(threadnamebuf, sizeof(threadnamebuf), fp);
-    fclose(fp);
-    if (threadname) {
-      size_t len = strlen(threadname);
-      if (len && threadname[len - 1] == '\n') {
-          threadname[len - 1] = '\0';
-      }
-    }
-  }
-
-  _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", threadname ? threadname : "<unknown>", tid);
-
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
-  if (backtrace->Unwind(0)) {
-    dump_backtrace_to_log(backtrace.get(), log, "  ");
-  } else {
-    ALOGE("Unwind failed: tid = %d: %s", tid,
-          backtrace->GetErrorString(backtrace->GetError()).c_str());
-  }
-}
-
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid,
-                    const std::set<pid_t>& siblings, std::string* amfd_data) {
-  log_t log;
-  log.tfd = fd;
-  log.amfd_data = amfd_data;
-
-  dump_process_header(&log, pid);
-  dump_thread(&log, map, pid, tid);
-
-  for (pid_t sibling : siblings) {
-    dump_thread(&log, map, pid, sibling);
-  }
-
-  dump_process_footer(&log, pid);
-}
-
-void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix) {
-  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
-    _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, backtrace->FormatFrameData(i).c_str());
-  }
-}
diff --git a/debuggerd/backtrace.h b/debuggerd/backtrace.h
deleted file mode 100644
index acd5eaa..0000000
--- a/debuggerd/backtrace.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DEBUGGERD_BACKTRACE_H
-#define _DEBUGGERD_BACKTRACE_H
-
-#include <sys/types.h>
-
-#include <set>
-#include <string>
-
-#include "utility.h"
-
-class Backtrace;
-class BacktraceMap;
-
-// Dumps a backtrace using a format similar to what Dalvik uses so that the result
-// can be intermixed in a bug report.
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid,
-                    const std::set<pid_t>& siblings, std::string* amfd_data);
-
-/* Dumps the backtrace in the backtrace data structure to the log. */
-void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix);
-
-#endif // _DEBUGGERD_BACKTRACE_H
diff --git a/debuggerd/client/debuggerd_client.cpp b/debuggerd/client/debuggerd_client.cpp
new file mode 100644
index 0000000..d1df088
--- /dev/null
+++ b/debuggerd/client/debuggerd_client.cpp
@@ -0,0 +1,237 @@
+/*
+ * Copyright 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 <debuggerd/client.h>
+
+#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/parseint.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+#include <debuggerd/handler.h>
+#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) {
+  sigval val;
+  val.sival_int = backtrace;
+  if (sigqueue(pid, DEBUGGER_SIGNAL, val) != 0) {
+    PLOG(ERROR) << "libdebuggerd_client: failed to send signal to pid " << pid;
+    return false;
+  }
+  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,
+                            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 time_left = [&end]() { return end - std::chrono::steady_clock::now(); };
+  auto set_timeout = [timeout_ms, &time_left](int sockfd) {
+    if (timeout_ms <= 0) {
+      return sockfd;
+    }
+
+    auto remaining = time_left();
+    if (remaining < decltype(remaining)::zero()) {
+      LOG(ERROR) << "libdebuggerd_client: timeout expired";
+      return -1;
+    }
+
+    struct timeval timeout;
+    populate_timeval(&timeout, remaining);
+
+    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0) {
+      PLOG(ERROR) << "libdebuggerd_client: failed to set receive timeout";
+      return -1;
+    }
+    if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0) {
+      PLOG(ERROR) << "libdebuggerd_client: failed to set send timeout";
+      return -1;
+    }
+
+    return sockfd;
+  };
+
+  sockfd.reset(socket(AF_LOCAL, SOCK_SEQPACKET, 0));
+  if (sockfd == -1) {
+    PLOG(ERROR) << "libdebugger_client: failed to create socket";
+    return false;
+  }
+
+  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(sockfd)) {
+    PLOG(ERROR) << "libdebugger_client: failed to set timeout";
+    return false;
+  }
+
+  // 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;
+  }
+
+  std::string pipe_size_str;
+  int pipe_buffer_size = 1024 * 1024;
+  if (android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
+    pipe_size_str = android::base::Trim(pipe_size_str);
+
+    if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
+      LOG(FATAL) << "failed to parse pipe max size '" << pipe_size_str << "'";
+    }
+  }
+
+  if (fcntl(pipe_read.get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
+    PLOG(ERROR) << "failed to set pipe buffer size";
+  }
+
+  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;
+  }
+
+  // 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;
+  }
+
+  if (response.status != InterceptStatus::kRegistered) {
+    LOG(ERROR) << "libdebuggerd_client: unexpected registration response: "
+               << static_cast<int>(response.status);
+    return false;
+  }
+
+  bool backtrace = dump_type == kDebuggerdBacktrace;
+  send_signal(pid, backtrace);
+
+  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;
+  }
+
+  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;
+
+  return true;
+}
+
+int dump_backtrace_to_file(pid_t tid, int fd) {
+  return dump_backtrace_to_file_timeout(tid, fd, 0);
+}
+
+int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs) {
+  android::base::unique_fd copy(dup(fd));
+  if (copy == -1) {
+    return -1;
+  }
+  int timeout_ms = timeout_secs > 0 ? timeout_secs * 1000 : 0;
+  return debuggerd_trigger_dump(tid, std::move(copy), kDebuggerdBacktrace, timeout_ms) ? 0 : -1;
+}
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/crash_dump.cpp b/debuggerd/crash_dump.cpp
new file mode 100644
index 0000000..0a29844
--- /dev/null
+++ b/debuggerd/crash_dump.cpp
@@ -0,0 +1,429 @@
+/*
+ * Copyright 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 <arpa/inet.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <syscall.h>
+#include <unistd.h>
+
+#include <limits>
+#include <map>
+#include <memory>
+#include <set>
+#include <vector>
+
+#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 <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+#include <log/log.h>
+#include <private/android_filesystem_config.h>
+#include <procinfo/process.h>
+#include <selinux/selinux.h>
+
+#include "backtrace.h"
+#include "tombstone.h"
+#include "utility.h"
+
+#include "debuggerd/handler.h"
+#include "debuggerd/protocol.h"
+#include "debuggerd/tombstoned.h"
+#include "debuggerd/util.h"
+
+using android::base::unique_fd;
+using android::base::ReadFileToString;
+using android::base::StringPrintf;
+using android::base::Trim;
+
+static std::string get_process_name(pid_t pid) {
+  std::string result = "<unknown>";
+  ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &result);
+  return result;
+}
+
+static std::string get_thread_name(pid_t tid) {
+  std::string result = "<unknown>";
+  ReadFileToString(StringPrintf("/proc/%d/comm", tid), &result);
+  return Trim(result);
+}
+
+static bool pid_contains_tid(int pid_proc_fd, pid_t tid) {
+  struct stat st;
+  std::string task_path = StringPrintf("task/%d", tid);
+  return fstatat(pid_proc_fd, task_path.c_str(), &st, 0) == 0;
+}
+
+// Attach to a thread, and verify that it's still a member of the given process
+static bool ptrace_seize_thread(int pid_proc_fd, pid_t tid, std::string* error) {
+  if (ptrace(PTRACE_SEIZE, tid, 0, 0) != 0) {
+    *error = StringPrintf("failed to attach to thread %d: %s", tid, strerror(errno));
+    return false;
+  }
+
+  // Make sure that the task we attached to is actually part of the pid we're dumping.
+  if (!pid_contains_tid(pid_proc_fd, tid)) {
+    if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
+      PLOG(FATAL) << "failed to detach from thread " << tid;
+    }
+    *error = StringPrintf("thread %d is not in process", tid);
+    return false;
+  }
+
+  // Put the task into ptrace-stop state.
+  if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) != 0) {
+    PLOG(FATAL) << "failed to interrupt thread " << tid;
+  }
+
+  return true;
+}
+
+static bool activity_manager_notify(pid_t pid, int signal, const std::string& amfd_data) {
+  android::base::unique_fd amfd(socket_local_client(
+      "/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
+  if (amfd.get() == -1) {
+    PLOG(ERROR) << "unable to connect to activity manager";
+    return false;
+  }
+
+  struct timeval tv = {
+    .tv_sec = 1,
+    .tv_usec = 0,
+  };
+  if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
+    PLOG(ERROR) << "failed to set send timeout on activity manager socket";
+    return false;
+  }
+  tv.tv_sec = 3;  // 3 seconds on handshake read
+  if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
+    PLOG(ERROR) << "failed to set receive timeout on activity manager socket";
+    return false;
+  }
+
+  // Activity Manager protocol: binary 32-bit network-byte-order ints for the
+  // pid and signal number, followed by the raw text of the dump, culminating
+  // in a zero byte that marks end-of-data.
+  uint32_t datum = htonl(pid);
+  if (!android::base::WriteFully(amfd, &datum, 4)) {
+    PLOG(ERROR) << "AM pid write failed";
+    return false;
+  }
+  datum = htonl(signal);
+  if (!android::base::WriteFully(amfd, &datum, 4)) {
+    PLOG(ERROR) << "AM signal write failed";
+    return false;
+  }
+  if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size() + 1)) {
+    PLOG(ERROR) << "AM data write failed";
+    return false;
+  }
+
+  // 3 sec timeout reading the ack; we're fine if the read fails.
+  char ack;
+  android::base::ReadFully(amfd, &ack, 1);
+  return true;
+}
+
+static void signal_handler(int) {
+  // We can't log easily, because the heap might be corrupt.
+  // Just die and let the surrounding log context explain things.
+  _exit(1);
+}
+
+static void abort_handler(pid_t target, const bool& tombstoned_connected,
+                          unique_fd& tombstoned_socket, unique_fd& output_fd,
+                          const char* abort_msg) {
+  // If we abort before we get an output fd, contact tombstoned to let any
+  // potential listeners know that we failed.
+  if (!tombstoned_connected) {
+    if (!tombstoned_connect(target, &tombstoned_socket, &output_fd)) {
+      // We failed to connect, not much we can do.
+      LOG(ERROR) << "failed to connected to tombstoned to report failure";
+      _exit(1);
+    }
+  }
+
+  dprintf(output_fd.get(), "crash_dump failed to dump process");
+  if (target != 1) {
+    dprintf(output_fd.get(), " %d: %s\n", target, abort_msg);
+  } else {
+    dprintf(output_fd.get(), ": %s\n", abort_msg);
+  }
+
+  _exit(1);
+}
+
+static void drop_capabilities() {
+  __user_cap_header_struct capheader;
+  memset(&capheader, 0, sizeof(capheader));
+  capheader.version = _LINUX_CAPABILITY_VERSION_3;
+  capheader.pid = 0;
+
+  __user_cap_data_struct capdata[2];
+  memset(&capdata, 0, sizeof(capdata));
+
+  if (capset(&capheader, &capdata[0]) == -1) {
+    PLOG(FATAL) << "failed to drop capabilities";
+  }
+
+  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
+    PLOG(FATAL) << "failed to set PR_SET_NO_NEW_PRIVS";
+  }
+}
+
+int main(int argc, char** argv) {
+  pid_t target = getppid();
+  bool tombstoned_connected = false;
+  unique_fd tombstoned_socket;
+  unique_fd output_fd;
+
+  android::base::InitLogging(argv);
+  android::base::SetAborter([&](const char* abort_msg) {
+    abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
+  });
+
+  // Don't try to dump ourselves.
+  struct sigaction action = {};
+  action.sa_handler = signal_handler;
+  debuggerd_register_handlers(&action);
+
+  if (argc != 3) {
+    return 1;
+  }
+
+  sigset_t mask;
+  sigemptyset(&mask);
+  if (sigprocmask(SIG_SETMASK, &mask, nullptr) != 0) {
+    PLOG(FATAL) << "failed to set signal mask";
+  }
+
+  pid_t main_tid;
+  pid_t pseudothread_tid;
+
+  if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
+    LOG(FATAL) << "invalid main tid: " << argv[1];
+  }
+
+  if (!android::base::ParseInt(argv[2], &pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
+    LOG(FATAL) << "invalid pseudothread tid: " << argv[2];
+  }
+
+  if (target == 1) {
+    LOG(FATAL) << "target died before we could attach (received main tid = " << main_tid << ")";
+  }
+
+  android::procinfo::ProcessInfo target_info;
+  if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
+    LOG(FATAL) << "failed to fetch process info for target " << main_tid;
+  }
+
+  if (main_tid != target_info.tid || target != target_info.pid) {
+    LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
+               << ", received pid " << target_info.pid << ", tid " << target_info.tid;
+  }
+
+  // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
+  std::string target_proc_path = "/proc/" + std::to_string(target);
+  int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
+  if (target_proc_fd == -1) {
+    PLOG(FATAL) << "failed to open " << target_proc_path;
+  }
+
+  // Make sure our parent didn't die.
+  if (getppid() != target) {
+    PLOG(FATAL) << "parent died";
+  }
+
+  // Reparent ourselves to init, so that the signal handler can waitpid on the
+  // original process to avoid leaving a zombie for non-fatal dumps.
+  pid_t forkpid = fork();
+  if (forkpid == -1) {
+    PLOG(FATAL) << "fork failed";
+  } else if (forkpid != 0) {
+    exit(0);
+  }
+
+  // Die if we take too long.
+  //
+  // Note: processes with many threads and minidebug-info can take a bit to
+  //       unwind, do not make this too small. b/62828735
+  alarm(5);
+
+  std::string attach_error;
+
+  // Seize the main thread.
+  if (!ptrace_seize_thread(target_proc_fd, main_tid, &attach_error)) {
+    LOG(FATAL) << attach_error;
+  }
+
+  // Seize the siblings.
+  std::map<pid_t, std::string> threads;
+  {
+    std::set<pid_t> siblings;
+    if (!android::procinfo::GetProcessTids(target, &siblings)) {
+      PLOG(FATAL) << "failed to get process siblings";
+    }
+
+    // but not the already attached main thread.
+    siblings.erase(main_tid);
+    // or the handler pseudothread.
+    siblings.erase(pseudothread_tid);
+
+    for (pid_t sibling_tid : siblings) {
+      if (!ptrace_seize_thread(target_proc_fd, sibling_tid, &attach_error)) {
+        LOG(WARNING) << attach_error;
+      } else {
+        threads.emplace(sibling_tid, get_thread_name(sibling_tid));
+      }
+    }
+  }
+
+  // Collect the backtrace map, open files, and process/thread names, while we still have caps.
+  std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
+  if (!backtrace_map) {
+    LOG(FATAL) << "failed to create backtrace map";
+  }
+
+  // Collect the list of open files.
+  OpenFilesList open_files;
+  populate_open_files_list(target, &open_files);
+
+  std::string process_name = get_process_name(main_tid);
+  threads.emplace(main_tid, get_thread_name(main_tid));
+
+  // Drop our capabilities now that we've attached to the threads we care about.
+  drop_capabilities();
+
+  LOG(INFO) << "obtaining output fd from tombstoned";
+  tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
+
+  // Write a '\1' to stdout to tell the crashing process to resume.
+  // It also restores the value of PR_SET_DUMPABLE at this point.
+  if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
+    PLOG(ERROR) << "failed to communicate to target process";
+  }
+
+  if (tombstoned_connected) {
+    if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
+      PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
+    }
+  } else {
+    unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
+    TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
+    output_fd = std::move(devnull);
+  }
+
+  LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
+
+  // At this point, the thread that made the request has been attached and is
+  // in ptrace-stopped state. After resumption, the triggering signal that has
+  // been queued will be delivered.
+  if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
+    PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
+    exit(1);
+  }
+
+  siginfo_t siginfo = {};
+  if (!wait_for_signal(main_tid, &siginfo)) {
+    printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
+    exit(1);
+  }
+
+  int signo = siginfo.si_signo;
+  bool fatal_signal = signo != DEBUGGER_SIGNAL;
+  bool backtrace = false;
+  uintptr_t abort_address = 0;
+
+  // si_value can represent three things:
+  //   0: dump tombstone
+  //   1: dump backtrace
+  //   everything else: abort message address (implies dump tombstone)
+  if (siginfo.si_value.sival_int == 1) {
+    backtrace = true;
+  } else if (siginfo.si_value.sival_ptr != nullptr) {
+    abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
+  }
+
+  // TODO: Use seccomp to lock ourselves down.
+
+  std::string amfd_data;
+  if (backtrace) {
+    dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, process_name, threads, 0);
+  } else {
+    engrave_tombstone(output_fd.get(), backtrace_map.get(), &open_files, target, main_tid,
+                      process_name, threads, abort_address, fatal_signal ? &amfd_data : nullptr);
+  }
+
+  // We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
+  // group-stop state, which is true as long as no stopping signals are sent.
+
+  bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
+  if (!fatal_signal || siginfo.si_code == SI_USER) {
+    // Don't wait_for_gdb when the process didn't actually crash.
+    wait_for_gdb = false;
+  }
+
+  // If the process crashed or we need to send it SIGSTOP for wait_for_gdb,
+  // get it in a state where it can receive signals, and then send the relevant
+  // signal.
+  if (wait_for_gdb || fatal_signal) {
+    if (ptrace(PTRACE_INTERRUPT, main_tid, 0, 0) != 0) {
+      PLOG(ERROR) << "failed to use PTRACE_INTERRUPT on " << main_tid;
+    }
+
+    if (tgkill(target, main_tid, wait_for_gdb ? SIGSTOP : signo) != 0) {
+      PLOG(ERROR) << "failed to resend signal " << signo << " to " << main_tid;
+    }
+  }
+
+  if (wait_for_gdb) {
+    // Use ALOGI to line up with output from engrave_tombstone.
+    ALOGI(
+      "***********************************************************\n"
+      "* Process %d has been suspended while crashing.\n"
+      "* To attach gdbserver and start gdb, run this on the host:\n"
+      "*\n"
+      "*     gdbclient.py -p %d\n"
+      "*\n"
+      "***********************************************************",
+      target, main_tid);
+  }
+
+  if (fatal_signal) {
+    // Don't try to notify ActivityManager if it just crashed, or we might hang until timeout.
+    if (target_info.name != "system_server" || target_info.uid != AID_SYSTEM) {
+      activity_manager_notify(target, signo, amfd_data);
+    }
+  }
+
+  // Close stdout before we notify tombstoned of completion.
+  close(STDOUT_FILENO);
+  if (tombstoned_connected && !tombstoned_notify_completion(tombstoned_socket.get())) {
+    LOG(ERROR) << "failed to notify tombstoned of completion";
+  }
+
+  return 0;
+}
diff --git a/debuggerd/crasher.c b/debuggerd/crasher.c
deleted file mode 100644
index 75f070b..0000000
--- a/debuggerd/crasher.c
+++ /dev/null
@@ -1,215 +0,0 @@
-#include <assert.h>
-#include <errno.h>
-#include <pthread.h>
-#include <sched.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/cdefs.h>
-#include <sys/mman.h>
-#include <sys/ptrace.h>
-#include <sys/socket.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include <cutils/sockets.h>
-#include <log/log.h>
-
-#ifndef __unused
-#define __unused __attribute__((__unused__))
-#endif
-
-extern const char* __progname;
-
-void crash1(void);
-void crashnostack(void);
-static int do_action(const char* arg);
-
-static void maybe_abort() {
-    if (time(0) != 42) {
-        abort();
-    }
-}
-
-static char* smash_stack_dummy_buf;
-__attribute__ ((noinline)) static void smash_stack_dummy_function(volatile int* plen) {
-  smash_stack_dummy_buf[*plen] = 0;
-}
-
-// This must be marked with "__attribute__ ((noinline))", to ensure the
-// compiler generates the proper stack guards around this function.
-// Assign local array address to global variable to force stack guards.
-// Use another noinline function to corrupt the stack.
-__attribute__ ((noinline)) static int smash_stack(volatile int* plen) {
-    printf("crasher: deliberately corrupting stack...\n");
-
-    char buf[128];
-    smash_stack_dummy_buf = buf;
-    // This should corrupt stack guards and make process abort.
-    smash_stack_dummy_function(plen);
-    return 0;
-}
-
-#if defined(__clang__)
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Winfinite-recursion"
-#endif
-
-static void* global = 0; // So GCC doesn't optimize the tail recursion out of overflow_stack.
-
-__attribute__((noinline)) static void overflow_stack(void* p) {
-    void* buf[1];
-    buf[0] = p;
-    global = buf;
-    overflow_stack(&buf);
-}
-
-#if defined(__clang__)
-#pragma clang diagnostic pop
-#endif
-
-static void *noisy(void *x)
-{
-    char c = (uintptr_t) x;
-    for(;;) {
-        usleep(250*1000);
-        write(2, &c, 1);
-        if(c == 'C') *((volatile unsigned*) 0) = 42;
-    }
-    return NULL;
-}
-
-static int ctest()
-{
-    pthread_t thr;
-    pthread_attr_t attr;
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-    pthread_create(&thr, &attr, noisy, (void*) 'A');
-    pthread_create(&thr, &attr, noisy, (void*) 'B');
-    pthread_create(&thr, &attr, noisy, (void*) 'C');
-    for(;;) ;
-    return 0;
-}
-
-static void* thread_callback(void* raw_arg)
-{
-    return (void*) (uintptr_t) do_action((const char*) raw_arg);
-}
-
-static int do_action_on_thread(const char* arg)
-{
-    pthread_t t;
-    pthread_create(&t, NULL, thread_callback, (void*) arg);
-    void* result = NULL;
-    pthread_join(t, &result);
-    return (int) (uintptr_t) result;
-}
-
-__attribute__((noinline)) static int crash3(int a) {
-    *((int*) 0xdead) = a;
-    return a*4;
-}
-
-__attribute__((noinline)) static int crash2(int a) {
-    a = crash3(a) + 2;
-    return a*3;
-}
-
-__attribute__((noinline)) static int crash(int a) {
-    a = crash2(a) + 1;
-    return a*2;
-}
-
-static void abuse_heap() {
-    char buf[16];
-    free((void*) buf); // GCC is smart enough to warn about this, but we're doing it deliberately.
-}
-
-static void sigsegv_non_null() {
-    int* a = (int *)(&do_action);
-    *a = 42;
-}
-
-static int do_action(const char* arg)
-{
-    fprintf(stderr,"crasher: init pid=%d tid=%d\n", getpid(), gettid());
-
-    if (!strncmp(arg, "thread-", strlen("thread-"))) {
-        return do_action_on_thread(arg + strlen("thread-"));
-    } else if (!strcmp(arg, "SIGSEGV-non-null")) {
-        sigsegv_non_null();
-    } else if (!strcmp(arg, "smash-stack")) {
-        volatile int len = 128;
-        return smash_stack(&len);
-    } else if (!strcmp(arg, "stack-overflow")) {
-        overflow_stack(NULL);
-    } else if (!strcmp(arg, "nostack")) {
-        crashnostack();
-    } else if (!strcmp(arg, "ctest")) {
-        return ctest();
-    } else if (!strcmp(arg, "exit")) {
-        exit(1);
-    } else if (!strcmp(arg, "crash") || !strcmp(arg, "SIGSEGV")) {
-        return crash(42);
-    } else if (!strcmp(arg, "abort")) {
-        maybe_abort();
-    } else if (!strcmp(arg, "assert")) {
-        __assert("some_file.c", 123, "false");
-    } else if (!strcmp(arg, "assert2")) {
-        __assert2("some_file.c", 123, "some_function", "false");
-    } else if (!strcmp(arg, "LOG_ALWAYS_FATAL")) {
-        LOG_ALWAYS_FATAL("hello %s", "world");
-    } else if (!strcmp(arg, "LOG_ALWAYS_FATAL_IF")) {
-        LOG_ALWAYS_FATAL_IF(true, "hello %s", "world");
-    } else if (!strcmp(arg, "SIGFPE")) {
-        raise(SIGFPE);
-        return EXIT_SUCCESS;
-    } else if (!strcmp(arg, "SIGTRAP")) {
-        raise(SIGTRAP);
-        return EXIT_SUCCESS;
-    } else if (!strcmp(arg, "heap-usage")) {
-        abuse_heap();
-    } else if (!strcmp(arg, "SIGSEGV-unmapped")) {
-        char* map = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
-        munmap(map, sizeof(int));
-        map[0] = '8';
-    }
-
-    fprintf(stderr, "%s OP\n", __progname);
-    fprintf(stderr, "where OP is:\n");
-    fprintf(stderr, "  smash-stack           overwrite a stack-guard canary\n");
-    fprintf(stderr, "  stack-overflow        recurse until the stack overflows\n");
-    fprintf(stderr, "  heap-corruption       cause a libc abort by corrupting the heap\n");
-    fprintf(stderr, "  heap-usage            cause a libc abort by abusing a heap function\n");
-    fprintf(stderr, "  nostack               crash with a NULL stack pointer\n");
-    fprintf(stderr, "  ctest                 (obsoleted by thread-crash?)\n");
-    fprintf(stderr, "  exit                  call exit(1)\n");
-    fprintf(stderr, "  abort                 call abort()\n");
-    fprintf(stderr, "  assert                call assert() without a function\n");
-    fprintf(stderr, "  assert2               call assert() with a function\n");
-    fprintf(stderr, "  LOG_ALWAYS_FATAL      call LOG_ALWAYS_FATAL\n");
-    fprintf(stderr, "  LOG_ALWAYS_FATAL_IF   call LOG_ALWAYS_FATAL\n");
-    fprintf(stderr, "  SIGFPE                cause a SIGFPE\n");
-    fprintf(stderr, "  SIGSEGV               cause a SIGSEGV at address 0x0 (synonym: crash)\n");
-    fprintf(stderr, "  SIGSEGV-non-null      cause a SIGSEGV at a non-zero address\n");
-    fprintf(stderr, "  SIGSEGV-unmapped      mmap/munmap a region of memory and then attempt to access it\n");
-    fprintf(stderr, "  SIGTRAP               cause a SIGTRAP\n");
-    fprintf(stderr, "prefix any of the above with 'thread-' to not run\n");
-    fprintf(stderr, "on the process' main thread.\n");
-    return EXIT_SUCCESS;
-}
-
-int main(int argc, char **argv)
-{
-    fprintf(stderr,"crasher: built at " __TIME__ "!@\n");
-
-    if(argc > 1) {
-        return do_action(argv[1]);
-    } else {
-        crash1();
-    }
-
-    return 0;
-}
diff --git a/debuggerd/crasher/Android.bp b/debuggerd/crasher/Android.bp
new file mode 100644
index 0000000..f73f672
--- /dev/null
+++ b/debuggerd/crasher/Android.bp
@@ -0,0 +1,83 @@
+cc_defaults {
+    name: "crasher-defaults",
+
+    cppflags: [
+        "-std=gnu++14",
+        "-W",
+        "-Wall",
+        "-Wextra",
+        "-Wunused",
+        "-Werror",
+        "-O0",
+        "-fstack-protector-all",
+        "-Wno-free-nonheap-object",
+        "-Wno-date-time",
+    ],
+    srcs: ["crasher.cpp"],
+    arch: {
+        arm: {
+            srcs: ["arm/crashglue.S"],
+
+            armv7_a_neon: {
+                asflags: ["-DHAS_VFP_D32"],
+            },
+        },
+        arm64: {
+            srcs: ["arm64/crashglue.S"],
+        },
+        mips: {
+            srcs: ["mips/crashglue.S"],
+        },
+        mips64: {
+            srcs: ["mips64/crashglue.S"],
+        },
+        x86: {
+            srcs: ["x86/crashglue.S"],
+        },
+        x86_64: {
+            srcs: ["x86_64/crashglue.S"],
+        },
+    },
+    compile_multilib: "both",
+}
+
+cc_binary {
+    name: "crasher",
+
+    defaults: ["crasher-defaults"],
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libseccomp_policy",
+    ],
+    multilib: {
+        lib32: {
+            stem: "crasher",
+        },
+        lib64: {
+            stem: "crasher64",
+        },
+    },
+}
+
+cc_binary {
+    name: "static_crasher",
+
+    defaults: ["crasher-defaults"],
+    cppflags: ["-DSTATIC_CRASHER"],
+    static_executable: true,
+    static_libs: [
+        "libdebuggerd_handler",
+        "libbase",
+        "liblog",
+        "libseccomp_policy",
+    ],
+    multilib: {
+        lib32: {
+            stem: "static_crasher",
+        },
+        lib64: {
+            stem: "static_crasher64",
+        },
+    },
+}
diff --git a/debuggerd/arm/crashglue.S b/debuggerd/crasher/arm/crashglue.S
similarity index 100%
rename from debuggerd/arm/crashglue.S
rename to debuggerd/crasher/arm/crashglue.S
diff --git a/debuggerd/arm64/crashglue.S b/debuggerd/crasher/arm64/crashglue.S
similarity index 100%
rename from debuggerd/arm64/crashglue.S
rename to debuggerd/crasher/arm64/crashglue.S
diff --git a/debuggerd/crasher/crasher.cpp b/debuggerd/crasher/crasher.cpp
new file mode 100644
index 0000000..6970201
--- /dev/null
+++ b/debuggerd/crasher/crasher.cpp
@@ -0,0 +1,326 @@
+/*
+ * Copyright 2006, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "crasher"
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <unistd.h>
+
+// We test both kinds of logging.
+#include <android-base/logging.h>
+#include <log/log.h>
+
+#include "seccomp_policy.h"
+
+#if defined(STATIC_CRASHER)
+#include "debuggerd/handler.h"
+#endif
+
+#if defined(__arm__)
+// See https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt for details.
+#define __kuser_helper_version (*(int32_t*) 0xffff0ffc)
+typedef void * (__kuser_get_tls_t)(void);
+#define __kuser_get_tls (*(__kuser_get_tls_t*) 0xffff0fe0)
+typedef int (__kuser_cmpxchg_t)(int oldval, int newval, volatile int *ptr);
+#define __kuser_cmpxchg (*(__kuser_cmpxchg_t*) 0xffff0fc0)
+typedef void (__kuser_dmb_t)(void);
+#define __kuser_dmb (*(__kuser_dmb_t*) 0xffff0fa0)
+typedef int (__kuser_cmpxchg64_t)(const int64_t*, const int64_t*, volatile int64_t*);
+#define __kuser_cmpxchg64 (*(__kuser_cmpxchg64_t*) 0xffff0f60)
+#endif
+
+#define noinline __attribute__((__noinline__))
+
+// Avoid name mangling so that stacks are more readable.
+extern "C" {
+
+void crash1(void);
+void crashnostack(void);
+
+int do_action(const char* arg);
+
+noinline void maybe_abort() {
+    if (time(0) != 42) {
+        abort();
+    }
+}
+
+char* smash_stack_dummy_buf;
+noinline void smash_stack_dummy_function(volatile int* plen) {
+  smash_stack_dummy_buf[*plen] = 0;
+}
+
+// This must be marked with "__attribute__ ((noinline))", to ensure the
+// compiler generates the proper stack guards around this function.
+// Assign local array address to global variable to force stack guards.
+// Use another noinline function to corrupt the stack.
+noinline int smash_stack(volatile int* plen) {
+    printf("%s: deliberately corrupting stack...\n", getprogname());
+
+    char buf[128];
+    smash_stack_dummy_buf = buf;
+    // This should corrupt stack guards and make process abort.
+    smash_stack_dummy_function(plen);
+    return 0;
+}
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Winfinite-recursion"
+
+void* global = 0; // So GCC doesn't optimize the tail recursion out of overflow_stack.
+
+noinline void overflow_stack(void* p) {
+    void* buf[1];
+    buf[0] = p;
+    global = buf;
+    overflow_stack(&buf);
+}
+
+#pragma clang diagnostic pop
+
+noinline void* thread_callback(void* raw_arg) {
+    const char* arg = reinterpret_cast<const char*>(raw_arg);
+    return reinterpret_cast<void*>(static_cast<uintptr_t>(do_action(arg)));
+}
+
+noinline int do_action_on_thread(const char* arg) {
+    pthread_t t;
+    pthread_create(&t, nullptr, thread_callback, const_cast<char*>(arg));
+    void* result = nullptr;
+    pthread_join(t, &result);
+    return reinterpret_cast<uintptr_t>(result);
+}
+
+noinline int crash3(int a) {
+    *reinterpret_cast<int*>(0xdead) = a;
+    return a*4;
+}
+
+noinline int crash2(int a) {
+    a = crash3(a) + 2;
+    return a*3;
+}
+
+noinline int crash(int a) {
+    a = crash2(a) + 1;
+    return a*2;
+}
+
+noinline void abuse_heap() {
+    char buf[16];
+    free(buf); // GCC is smart enough to warn about this, but we're doing it deliberately.
+}
+
+noinline void sigsegv_non_null() {
+    int* a = (int *)(&do_action);
+    *a = 42;
+}
+
+noinline void fprintf_null() {
+    fprintf(nullptr, "oops");
+}
+
+noinline void readdir_null() {
+    readdir(nullptr);
+}
+
+noinline int strlen_null() {
+    char* sneaky_null = nullptr;
+    return strlen(sneaky_null);
+}
+
+static int usage() {
+    fprintf(stderr, "usage: %s KIND\n", getprogname());
+    fprintf(stderr, "\n");
+    fprintf(stderr, "where KIND is:\n");
+    fprintf(stderr, "  smash-stack           overwrite a -fstack-protector guard\n");
+    fprintf(stderr, "  stack-overflow        recurse until the stack overflows\n");
+    fprintf(stderr, "  nostack               crash with a NULL stack pointer\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  heap-corruption       cause a libc abort by corrupting the heap\n");
+    fprintf(stderr, "  heap-usage            cause a libc abort by abusing a heap function\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  abort                 call abort()\n");
+    fprintf(stderr, "  assert                call assert() without a function\n");
+    fprintf(stderr, "  assert2               call assert() with a function\n");
+    fprintf(stderr, "  exit                  call exit(1)\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  fortify               fail a _FORTIFY_SOURCE check\n");
+    fprintf(stderr, "  seccomp               fail a seccomp check\n");
+#if defined(__arm__)
+    fprintf(stderr, "  kuser_helper_version  call kuser_helper_version\n");
+    fprintf(stderr, "  kuser_get_tls         call kuser_get_tls\n");
+    fprintf(stderr, "  kuser_cmpxchg         call kuser_cmpxchg\n");
+    fprintf(stderr, "  kuser_memory_barrier  call kuser_memory_barrier\n");
+    fprintf(stderr, "  kuser_cmpxchg64       call kuser_cmpxchg64\n");
+#endif
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  LOG_ALWAYS_FATAL      call liblog LOG_ALWAYS_FATAL\n");
+    fprintf(stderr, "  LOG_ALWAYS_FATAL_IF   call liblog LOG_ALWAYS_FATAL_IF\n");
+    fprintf(stderr, "  LOG-FATAL             call libbase LOG(FATAL)\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  SIGFPE                cause a SIGFPE\n");
+    fprintf(stderr, "  SIGSEGV               cause a SIGSEGV at address 0x0 (synonym: crash)\n");
+    fprintf(stderr, "  SIGSEGV-non-null      cause a SIGSEGV at a non-zero address\n");
+    fprintf(stderr, "  SIGSEGV-unmapped      mmap/munmap a region of memory and then attempt to access it\n");
+    fprintf(stderr, "  SIGTRAP               cause a SIGTRAP\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  fprintf-NULL          pass a null pointer to fprintf\n");
+    fprintf(stderr, "  readdir-NULL          pass a null pointer to readdir\n");
+    fprintf(stderr, "  strlen-NULL           pass a null pointer to strlen\n");
+    fprintf(stderr, "  pthread_join-NULL     pass a null pointer to pthread_join\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "  no_new_privs          set PR_SET_NO_NEW_PRIVS and then abort\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "prefix any of the above with 'thread-' to run on a new thread\n");
+    fprintf(stderr, "prefix any of the above with 'exhaustfd-' to exhaust\n");
+    fprintf(stderr, "all available file descriptors before crashing.\n");
+    fprintf(stderr, "prefix any of the above with 'wait-' to wait until input is received on stdin\n");
+
+    return EXIT_FAILURE;
+}
+
+noinline int do_action(const char* arg) {
+    // Prefixes.
+    if (!strncmp(arg, "wait-", strlen("wait-"))) {
+      char buf[1];
+      TEMP_FAILURE_RETRY(read(STDIN_FILENO, buf, sizeof(buf)));
+      return do_action(arg + strlen("wait-"));
+    } else if (!strncmp(arg, "exhaustfd-", strlen("exhaustfd-"))) {
+      errno = 0;
+      while (errno != EMFILE) {
+        open("/dev/null", O_RDONLY);
+      }
+      return do_action(arg + strlen("exhaustfd-"));
+    } else if (!strncmp(arg, "thread-", strlen("thread-"))) {
+        return do_action_on_thread(arg + strlen("thread-"));
+    }
+
+    // Actions.
+    if (!strcasecmp(arg, "SIGSEGV-non-null")) {
+        sigsegv_non_null();
+    } else if (!strcasecmp(arg, "smash-stack")) {
+        volatile int len = 128;
+        return smash_stack(&len);
+    } else if (!strcasecmp(arg, "stack-overflow")) {
+        overflow_stack(nullptr);
+    } else if (!strcasecmp(arg, "nostack")) {
+        crashnostack();
+    } else if (!strcasecmp(arg, "exit")) {
+        exit(1);
+    } else if (!strcasecmp(arg, "crash") || !strcmp(arg, "SIGSEGV")) {
+        return crash(42);
+    } else if (!strcasecmp(arg, "abort")) {
+        maybe_abort();
+    } else if (!strcasecmp(arg, "assert")) {
+        __assert("some_file.c", 123, "false");
+    } else if (!strcasecmp(arg, "assert2")) {
+        __assert2("some_file.c", 123, "some_function", "false");
+    } else if (!strcasecmp(arg, "fortify")) {
+        char buf[10];
+        __read_chk(-1, buf, 32, 10);
+        while (true) pause();
+    } else if (!strcasecmp(arg, "LOG(FATAL)")) {
+        LOG(FATAL) << "hello " << 123;
+    } else if (!strcasecmp(arg, "LOG_ALWAYS_FATAL")) {
+        LOG_ALWAYS_FATAL("hello %s", "world");
+    } else if (!strcasecmp(arg, "LOG_ALWAYS_FATAL_IF")) {
+        LOG_ALWAYS_FATAL_IF(true, "hello %s", "world");
+    } else if (!strcasecmp(arg, "SIGFPE")) {
+        raise(SIGFPE);
+        return EXIT_SUCCESS;
+    } else if (!strcasecmp(arg, "SIGTRAP")) {
+        raise(SIGTRAP);
+        return EXIT_SUCCESS;
+    } else if (!strcasecmp(arg, "fprintf-NULL")) {
+        fprintf_null();
+    } else if (!strcasecmp(arg, "readdir-NULL")) {
+        readdir_null();
+    } else if (!strcasecmp(arg, "strlen-NULL")) {
+        return strlen_null();
+    } else if (!strcasecmp(arg, "pthread_join-NULL")) {
+        return pthread_join(0, nullptr);
+    } else if (!strcasecmp(arg, "heap-usage")) {
+        abuse_heap();
+    } else if (!strcasecmp(arg, "SIGSEGV-unmapped")) {
+        char* map = reinterpret_cast<char*>(mmap(nullptr, sizeof(int), PROT_READ | PROT_WRITE,
+                                                 MAP_SHARED | MAP_ANONYMOUS, -1, 0));
+        munmap(map, sizeof(int));
+        map[0] = '8';
+    } else if (!strcasecmp(arg, "seccomp")) {
+        set_seccomp_filter();
+        syscall(99999);
+#if defined(__arm__)
+    } else if (!strcasecmp(arg, "kuser_helper_version")) {
+        return __kuser_helper_version;
+    } else if (!strcasecmp(arg, "kuser_get_tls")) {
+        return !__kuser_get_tls();
+    } else if (!strcasecmp(arg, "kuser_cmpxchg")) {
+        return __kuser_cmpxchg(0, 0, 0);
+    } else if (!strcasecmp(arg, "kuser_memory_barrier")) {
+        __kuser_dmb();
+    } else if (!strcasecmp(arg, "kuser_cmpxchg64")) {
+        return __kuser_cmpxchg64(0, 0, 0);
+#endif
+    } else if (!strcasecmp(arg, "no_new_privs")) {
+        if (prctl(PR_SET_NO_NEW_PRIVS, 1) != 0) {
+          fprintf(stderr, "prctl(PR_SET_NO_NEW_PRIVS, 1) failed: %s\n", strerror(errno));
+          return EXIT_SUCCESS;
+        }
+        abort();
+    } else {
+        return usage();
+    }
+
+    fprintf(stderr, "%s: exiting normally!\n", getprogname());
+    return EXIT_SUCCESS;
+}
+
+int main(int argc, char** argv) {
+#if defined(STATIC_CRASHER)
+    debuggerd_callbacks_t callbacks = {
+      .get_abort_message = []() {
+        static struct {
+          size_t size;
+          char msg[32];
+        } msg;
+
+        msg.size = strlen("dummy abort message");
+        memcpy(msg.msg, "dummy abort message", strlen("dummy abort message"));
+        return reinterpret_cast<abort_msg_t*>(&msg);
+      },
+      .post_dump = nullptr
+    };
+    debuggerd_init(&callbacks);
+#endif
+
+    if (argc == 1) crash1();
+    else if (argc == 2) return do_action(argv[1]);
+
+    return usage();
+}
+
+};
diff --git a/debuggerd/mips/crashglue.S b/debuggerd/crasher/mips/crashglue.S
similarity index 100%
rename from debuggerd/mips/crashglue.S
rename to debuggerd/crasher/mips/crashglue.S
diff --git a/debuggerd/mips64/crashglue.S b/debuggerd/crasher/mips64/crashglue.S
similarity index 100%
rename from debuggerd/mips64/crashglue.S
rename to debuggerd/crasher/mips64/crashglue.S
diff --git a/debuggerd/x86/crashglue.S b/debuggerd/crasher/x86/crashglue.S
similarity index 100%
rename from debuggerd/x86/crashglue.S
rename to debuggerd/crasher/x86/crashglue.S
diff --git a/debuggerd/x86_64/crashglue.S b/debuggerd/crasher/x86_64/crashglue.S
similarity index 100%
rename from debuggerd/x86_64/crashglue.S
rename to debuggerd/crasher/x86_64/crashglue.S
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 7b57c20..492e9f0 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006, The Android Open Source Project
+ * Copyright 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.
@@ -14,937 +14,70 @@
  * limitations under the License.
  */
 
-#include <arpa/inet.h>
-#include <dirent.h>
-#include <elf.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdarg.h>
+#include <err.h>
 #include <stdio.h>
-#include <sys/poll.h>
-#include <sys/prctl.h>
-#include <sys/ptrace.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/un.h>
-#include <time.h>
+#include <stdlib.h>
+#include <string.h>
 
-#include <memory>
-#include <set>
-#include <string>
-
-#include <selinux/android.h>
-
-#include <log/logger.h>
+#include <limits>
+#include <thread>
 
 #include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
 #include <android-base/unique_fd.h>
-#include <cutils/debugger.h>
-#include <cutils/properties.h>
-#include <cutils/sockets.h>
-#include <nativehelper/ScopedFd.h>
+#include <debuggerd/client.h>
+#include <debuggerd/util.h>
+#include <selinux/selinux.h>
 
-#include <linux/input.h>
+using android::base::unique_fd;
 
-#include <private/android_filesystem_config.h>
+static void usage(int exit_code) {
+  fprintf(stderr, "usage: debuggerd [-b] PID\n");
+  fprintf(stderr, "\n");
+  fprintf(stderr, "-b, --backtrace    just a backtrace rather than a full tombstone\n");
+  _exit(exit_code);
+}
 
-#include "backtrace.h"
-#include "getevent.h"
-#include "signal_sender.h"
-#include "tombstone.h"
-#include "utility.h"
+static std::thread spawn_redirect_thread(unique_fd fd) {
+  return std::thread([fd{ std::move(fd) }]() {
+    while (true) {
+      char buf[BUFSIZ];
+      ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), buf, sizeof(buf)));
+      if (rc <= 0) {
+        return;
+      }
 
-// If the 32 bit executable is compiled on a 64 bit system,
-// use the 32 bit socket name.
-#if defined(TARGET_IS_64_BIT) && !defined(__LP64__)
-#define SOCKET_NAME DEBUGGER32_SOCKET_NAME
-#else
-#define SOCKET_NAME DEBUGGER_SOCKET_NAME
-#endif
-
-struct debugger_request_t {
-  debugger_action_t action;
-  pid_t pid, tid;
-  uid_t uid, gid;
-  uintptr_t abort_msg_address;
-  int32_t original_si_code;
-};
-
-static void wait_for_user_action(const debugger_request_t& request) {
-  // Explain how to attach the debugger.
-  ALOGI("***********************************************************\n"
-        "* Process %d has been suspended while crashing.\n"
-        "* To attach gdbserver and start gdb, run this on the host:\n"
-        "*\n"
-        "*     gdbclient.py -p %d\n"
-        "*\n"
-        "* Wait for gdb to start, then press the VOLUME DOWN key\n"
-        "* to let the process continue crashing.\n"
-        "***********************************************************",
-        request.pid, request.tid);
-
-  // Wait for VOLUME DOWN.
-  while (true) {
-    input_event e;
-    if (get_event(&e, -1) == 0) {
-      if (e.type == EV_KEY && e.code == KEY_VOLUMEDOWN && e.value == 0) {
-        break;
+      if (!android::base::WriteFully(STDOUT_FILENO, buf, rc)) {
+        return;
       }
     }
-  }
-
-  ALOGI("debuggerd resuming process %d", request.pid);
+  });
 }
 
-static int get_process_info(pid_t tid, pid_t* out_pid, uid_t* out_uid, uid_t* out_gid) {
-  char path[64];
-  snprintf(path, sizeof(path), "/proc/%d/status", tid);
+int main(int argc, char* argv[]) {
+  if (argc <= 1) usage(0);
+  if (argc > 3) usage(1);
+  if (argc == 3 && strcmp(argv[1], "-b") != 0 && strcmp(argv[1], "--backtrace") != 0) usage(1);
+  bool backtrace_only = argc == 3;
 
-  FILE* fp = fopen(path, "r");
-  if (!fp) {
-    return -1;
+  pid_t pid;
+  if (!android::base::ParseInt(argv[argc - 1], &pid, 1, std::numeric_limits<pid_t>::max())) {
+    usage(1);
   }
 
-  int fields = 0;
-  char line[1024];
-  while (fgets(line, sizeof(line), fp)) {
-    size_t len = strlen(line);
-    if (len > 6 && !memcmp(line, "Tgid:\t", 6)) {
-      *out_pid = atoi(line + 6);
-      fields |= 1;
-    } else if (len > 5 && !memcmp(line, "Uid:\t", 5)) {
-      *out_uid = atoi(line + 5);
-      fields |= 2;
-    } else if (len > 5 && !memcmp(line, "Gid:\t", 5)) {
-      *out_gid = atoi(line + 5);
-      fields |= 4;
-    }
-  }
-  fclose(fp);
-  return fields == 7 ? 0 : -1;
-}
-
-/*
- * Corresponds with debugger_action_t enum type in
- * include/cutils/debugger.h.
- */
-static const char *debuggerd_perms[] = {
-  NULL, /* crash is only used on self, no check applied */
-  "dump_tombstone",
-  "dump_backtrace"
-};
-
-static int audit_callback(void* data, security_class_t /* cls */, char* buf, size_t len)
-{
-    struct debugger_request_t* req = reinterpret_cast<debugger_request_t*>(data);
-
-    if (!req) {
-        ALOGE("No debuggerd request audit data");
-        return 0;
-    }
-
-    snprintf(buf, len, "pid=%d uid=%d gid=%d", req->pid, req->uid, req->gid);
-    return 0;
-}
-
-static bool selinux_action_allowed(int s, debugger_request_t* request)
-{
-  char *scon = NULL, *tcon = NULL;
-  const char *tclass = "debuggerd";
-  const char *perm;
-  bool allowed = false;
-
-  if (request->action <= 0 || request->action >= (sizeof(debuggerd_perms)/sizeof(debuggerd_perms[0]))) {
-    ALOGE("SELinux:  No permission defined for debugger action %d", request->action);
-    return false;
+  unique_fd piperead, pipewrite;
+  if (!Pipe(&piperead, &pipewrite)) {
+    err(1, "failed to create pipe");
   }
 
-  perm = debuggerd_perms[request->action];
-
-  if (getpeercon(s, &scon) < 0) {
-    ALOGE("Cannot get peer context from socket\n");
-    goto out;
+  std::thread redirect_thread = spawn_redirect_thread(std::move(piperead));
+  if (!debuggerd_trigger_dump(pid, std::move(pipewrite),
+                              backtrace_only ? kDebuggerdBacktrace : kDebuggerdTombstone, 0)) {
+    redirect_thread.join();
+    errx(1, "failed to dump process %d", pid);
   }
 
-  if (getpidcon(request->tid, &tcon) < 0) {
-    ALOGE("Cannot get context for tid %d\n", request->tid);
-    goto out;
-  }
-
-  allowed = (selinux_check_access(scon, tcon, tclass, perm, reinterpret_cast<void*>(request)) == 0);
-
-out:
-   freecon(scon);
-   freecon(tcon);
-   return allowed;
-}
-
-static bool pid_contains_tid(pid_t pid, pid_t tid) {
-  char task_path[PATH_MAX];
-  if (snprintf(task_path, PATH_MAX, "/proc/%d/task/%d", pid, tid) >= PATH_MAX) {
-    ALOGE("debuggerd: task path overflow (pid = %d, tid = %d)\n", pid, tid);
-    exit(1);
-  }
-
-  return access(task_path, F_OK) == 0;
-}
-
-static int read_request(int fd, debugger_request_t* out_request) {
-  ucred cr;
-  socklen_t len = sizeof(cr);
-  int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
-  if (status != 0) {
-    ALOGE("cannot get credentials");
-    return -1;
-  }
-
-  ALOGV("reading tid");
-  fcntl(fd, F_SETFL, O_NONBLOCK);
-
-  pollfd pollfds[1];
-  pollfds[0].fd = fd;
-  pollfds[0].events = POLLIN;
-  pollfds[0].revents = 0;
-  status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000));
-  if (status != 1) {
-    ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid);
-    return -1;
-  }
-
-  debugger_msg_t msg;
-  memset(&msg, 0, sizeof(msg));
-  status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg)));
-  if (status < 0) {
-    ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid);
-    return -1;
-  }
-  if (status != sizeof(debugger_msg_t)) {
-    ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid);
-    return -1;
-  }
-
-  out_request->action = static_cast<debugger_action_t>(msg.action);
-  out_request->tid = msg.tid;
-  out_request->pid = cr.pid;
-  out_request->uid = cr.uid;
-  out_request->gid = cr.gid;
-  out_request->abort_msg_address = msg.abort_msg_address;
-  out_request->original_si_code = msg.original_si_code;
-
-  if (msg.action == DEBUGGER_ACTION_CRASH) {
-    // Ensure that the tid reported by the crashing process is valid.
-    // This check needs to happen again after ptracing the requested thread to prevent a race.
-    if (!pid_contains_tid(out_request->pid, out_request->tid)) {
-      ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid,
-            out_request->pid);
-      return -1;
-    }
-  } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
-    // Only root or system can ask us to attach to any process and dump it explicitly.
-    // However, system is only allowed to collect backtraces but cannot dump tombstones.
-    status = get_process_info(out_request->tid, &out_request->pid,
-                              &out_request->uid, &out_request->gid);
-    if (status < 0) {
-      ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid);
-      return -1;
-    }
-
-    if (!selinux_action_allowed(fd, out_request))
-      return -1;
-  } else {
-    // No one else is allowed to dump arbitrary processes.
-    return -1;
-  }
+  redirect_thread.join();
   return 0;
 }
-
-static int activity_manager_connect() {
-  android::base::unique_fd amfd(socket(PF_UNIX, SOCK_STREAM, 0));
-  if (amfd.get() < -1) {
-    ALOGE("debuggerd: Unable to connect to activity manager (socket failed: %s)", strerror(errno));
-    return -1;
-  }
-
-  struct sockaddr_un address;
-  memset(&address, 0, sizeof(address));
-  address.sun_family = AF_UNIX;
-  // The path used here must match the value defined in NativeCrashListener.java.
-  strncpy(address.sun_path, "/data/system/ndebugsocket", sizeof(address.sun_path));
-  if (TEMP_FAILURE_RETRY(connect(amfd.get(), reinterpret_cast<struct sockaddr*>(&address),
-                                 sizeof(address))) == -1) {
-    ALOGE("debuggerd: Unable to connect to activity manager (connect failed: %s)", strerror(errno));
-    return -1;
-  }
-
-  struct timeval tv;
-  memset(&tv, 0, sizeof(tv));
-  tv.tv_sec = 1;  // tight leash
-  if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
-    ALOGE("debuggerd: Unable to connect to activity manager (setsockopt SO_SNDTIMEO failed: %s)",
-          strerror(errno));
-    return -1;
-  }
-
-  tv.tv_sec = 3;  // 3 seconds on handshake read
-  if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
-    ALOGE("debuggerd: Unable to connect to activity manager (setsockopt SO_RCVTIMEO failed: %s)",
-          strerror(errno));
-    return -1;
-  }
-
-  return amfd.release();
-}
-
-static void activity_manager_write(int pid, int signal, int amfd, const std::string& amfd_data) {
-  if (amfd == -1) {
-    return;
-  }
-
-  // Activity Manager protocol: binary 32-bit network-byte-order ints for the
-  // pid and signal number, followed by the raw text of the dump, culminating
-  // in a zero byte that marks end-of-data.
-  uint32_t datum = htonl(pid);
-  if (!android::base::WriteFully(amfd, &datum, 4)) {
-    ALOGE("AM pid write failed: %s\n", strerror(errno));
-    return;
-  }
-  datum = htonl(signal);
-  if (!android::base::WriteFully(amfd, &datum, 4)) {
-    ALOGE("AM signal write failed: %s\n", strerror(errno));
-    return;
-  }
-
-  if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size())) {
-    ALOGE("AM data write failed: %s\n", strerror(errno));
-    return;
-  }
-
-  // Send EOD to the Activity Manager, then wait for its ack to avoid racing
-  // ahead and killing the target out from under it.
-  uint8_t eodMarker = 0;
-  if (!android::base::WriteFully(amfd, &eodMarker, 1)) {
-    ALOGE("AM eod write failed: %s\n", strerror(errno));
-    return;
-  }
-  // 3 sec timeout reading the ack; we're fine if the read fails.
-  android::base::ReadFully(amfd, &eodMarker, 1);
-}
-
-static bool should_attach_gdb(const debugger_request_t& request) {
-  if (request.action == DEBUGGER_ACTION_CRASH) {
-    return property_get_bool("debug.debuggerd.wait_for_gdb", false);
-  }
-  return false;
-}
-
-#if defined(__LP64__)
-static bool is32bit(pid_t tid) {
-  char* exeline;
-  if (asprintf(&exeline, "/proc/%d/exe", tid) == -1) {
-    return false;
-  }
-  int fd = TEMP_FAILURE_RETRY(open(exeline, O_RDONLY | O_CLOEXEC));
-  int saved_errno = errno;
-  free(exeline);
-  if (fd == -1) {
-    ALOGW("Failed to open /proc/%d/exe %s", tid, strerror(saved_errno));
-    return false;
-  }
-
-  char ehdr[EI_NIDENT];
-  ssize_t bytes = TEMP_FAILURE_RETRY(read(fd, &ehdr, sizeof(ehdr)));
-  close(fd);
-  if (bytes != (ssize_t) sizeof(ehdr) || memcmp(ELFMAG, ehdr, SELFMAG) != 0) {
-    return false;
-  }
-  if (ehdr[EI_CLASS] == ELFCLASS32) {
-    return true;
-  }
-  return false;
-}
-
-static void redirect_to_32(int fd, debugger_request_t* request) {
-  debugger_msg_t msg;
-  memset(&msg, 0, sizeof(msg));
-  msg.tid = request->tid;
-  msg.action = request->action;
-
-  int sock_fd = socket_local_client(DEBUGGER32_SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
-                                    SOCK_STREAM | SOCK_CLOEXEC);
-  if (sock_fd < 0) {
-    ALOGE("Failed to connect to debuggerd32: %s", strerror(errno));
-    return;
-  }
-
-  if (TEMP_FAILURE_RETRY(write(sock_fd, &msg, sizeof(msg))) != (ssize_t) sizeof(msg)) {
-    ALOGE("Failed to write request to debuggerd32 socket: %s", strerror(errno));
-    close(sock_fd);
-    return;
-  }
-
-  char ack;
-  if (TEMP_FAILURE_RETRY(read(sock_fd, &ack, 1)) == -1) {
-    ALOGE("Failed to read ack from debuggerd32 socket: %s", strerror(errno));
-    close(sock_fd);
-    return;
-  }
-
-  char buffer[1024];
-  ssize_t bytes_read;
-  while ((bytes_read = TEMP_FAILURE_RETRY(read(sock_fd, buffer, sizeof(buffer)))) > 0) {
-    ssize_t bytes_to_send = bytes_read;
-    ssize_t bytes_written;
-    do {
-      bytes_written = TEMP_FAILURE_RETRY(write(fd, buffer + bytes_read - bytes_to_send,
-                                               bytes_to_send));
-      if (bytes_written == -1) {
-        if (errno == EAGAIN) {
-          // Retry the write.
-          continue;
-        }
-        ALOGE("Error while writing data to fd: %s", strerror(errno));
-        break;
-      }
-      bytes_to_send -= bytes_written;
-    } while (bytes_written != 0 && bytes_to_send > 0);
-    if (bytes_to_send != 0) {
-        ALOGE("Failed to write all data to fd: read %zd, sent %zd", bytes_read, bytes_to_send);
-        break;
-    }
-  }
-  close(sock_fd);
-}
-#endif
-
-// Attach to a thread, and verify that it's still a member of the given process
-static bool ptrace_attach_thread(pid_t pid, pid_t tid) {
-  if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) {
-    return false;
-  }
-
-  // Make sure that the task we attached to is actually part of the pid we're dumping.
-  if (!pid_contains_tid(pid, tid)) {
-    if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
-      ALOGE("debuggerd: failed to detach from thread '%d'", tid);
-      exit(1);
-    }
-    return false;
-  }
-
-  return true;
-}
-
-static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
-  char task_path[PATH_MAX];
-
-  if (snprintf(task_path, PATH_MAX, "/proc/%d/task", pid) >= PATH_MAX) {
-    ALOGE("debuggerd: task path overflow (pid = %d)\n", pid);
-    abort();
-  }
-
-  std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
-
-  // Bail early if the task directory cannot be opened.
-  if (!d) {
-    ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
-    return;
-  }
-
-  struct dirent* de;
-  while ((de = readdir(d.get())) != NULL) {
-    // Ignore "." and "..".
-    if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
-      continue;
-    }
-
-    char* end;
-    pid_t tid = strtoul(de->d_name, &end, 10);
-    if (*end) {
-      continue;
-    }
-
-    if (tid == main_tid) {
-      continue;
-    }
-
-    if (!ptrace_attach_thread(pid, tid)) {
-      ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
-      continue;
-    }
-
-    tids.insert(tid);
-  }
-}
-
-static bool perform_dump(const debugger_request_t& request, int fd, int tombstone_fd,
-                         BacktraceMap* backtrace_map, const std::set<pid_t>& siblings,
-                         int* crash_signal, std::string* amfd_data) {
-  if (TEMP_FAILURE_RETRY(write(fd, "\0", 1)) != 1) {
-    ALOGE("debuggerd: failed to respond to client: %s\n", strerror(errno));
-    return false;
-  }
-
-  int total_sleep_time_usec = 0;
-  while (true) {
-    int signal = wait_for_signal(request.tid, &total_sleep_time_usec);
-    switch (signal) {
-      case -1:
-        ALOGE("debuggerd: timed out waiting for signal");
-        return false;
-
-      case SIGSTOP:
-        if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
-          ALOGV("debuggerd: stopped -- dumping to tombstone");
-          engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings, signal,
-                            request.original_si_code, request.abort_msg_address, amfd_data);
-        } else if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE) {
-          ALOGV("debuggerd: stopped -- dumping to fd");
-          dump_backtrace(fd, backtrace_map, request.pid, request.tid, siblings, nullptr);
-        } else {
-          ALOGV("debuggerd: stopped -- continuing");
-          if (ptrace(PTRACE_CONT, request.tid, 0, 0) != 0) {
-            ALOGE("debuggerd: ptrace continue failed: %s", strerror(errno));
-            return false;
-          }
-          continue;  // loop again
-        }
-        break;
-
-      case SIGABRT:
-      case SIGBUS:
-      case SIGFPE:
-      case SIGILL:
-      case SIGSEGV:
-#ifdef SIGSTKFLT
-      case SIGSTKFLT:
-#endif
-      case SIGSYS:
-      case SIGTRAP:
-        ALOGV("stopped -- fatal signal\n");
-        *crash_signal = signal;
-        engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings, signal,
-                          request.original_si_code, request.abort_msg_address, amfd_data);
-        break;
-
-      default:
-        ALOGE("debuggerd: process stopped due to unexpected signal %d\n", signal);
-        break;
-    }
-    break;
-  }
-
-  return true;
-}
-
-static bool drop_privileges() {
-  // AID_LOG: for reading the logs data associated with the crashing process.
-  // AID_READPROC: for reading /proc/<PID>/{comm,cmdline}.
-  gid_t groups[] = { AID_DEBUGGERD, AID_LOG, AID_READPROC };
-  if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
-    ALOGE("debuggerd: failed to setgroups: %s", strerror(errno));
-    return false;
-  }
-
-  if (setresgid(AID_DEBUGGERD, AID_DEBUGGERD, AID_DEBUGGERD) != 0) {
-    ALOGE("debuggerd: failed to setresgid: %s", strerror(errno));
-    return false;
-  }
-
-  if (setresuid(AID_DEBUGGERD, AID_DEBUGGERD, AID_DEBUGGERD) != 0) {
-    ALOGE("debuggerd: failed to setresuid: %s", strerror(errno));
-    return false;
-  }
-
-  return true;
-}
-
-static void worker_process(int fd, debugger_request_t& request) {
-  // Open the tombstone file if we need it.
-  std::string tombstone_path;
-  int tombstone_fd = -1;
-  switch (request.action) {
-    case DEBUGGER_ACTION_DUMP_TOMBSTONE:
-    case DEBUGGER_ACTION_CRASH:
-      tombstone_fd = open_tombstone(&tombstone_path);
-      if (tombstone_fd == -1) {
-        ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno));
-        exit(1);
-      }
-      break;
-
-    case DEBUGGER_ACTION_DUMP_BACKTRACE:
-      break;
-
-    default:
-      ALOGE("debuggerd: unexpected request action: %d", request.action);
-      exit(1);
-  }
-
-  // At this point, the thread that made the request is blocked in
-  // a read() call.  If the thread has crashed, then this gives us
-  // time to PTRACE_ATTACH to it before it has a chance to really fault.
-  //
-  // The PTRACE_ATTACH sends a SIGSTOP to the target process, but it
-  // won't necessarily have stopped by the time ptrace() returns.  (We
-  // currently assume it does.)  We write to the file descriptor to
-  // ensure that it can run as soon as we call PTRACE_CONT below.
-  // See details in bionic/libc/linker/debugger.c, in function
-  // debugger_signal_handler().
-
-  // Attach to the target process.
-  if (!ptrace_attach_thread(request.pid, request.tid)) {
-    ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno));
-    exit(1);
-  }
-
-  // DEBUGGER_ACTION_CRASH requests can come from arbitrary processes and the tid field in the
-  // request is sent from the other side. If an attacker can cause a process to be spawned with the
-  // pid of their process, they could trick debuggerd into dumping that process by exiting after
-  // sending the request. Validate the trusted request.uid/gid to defend against this.
-  if (request.action == DEBUGGER_ACTION_CRASH) {
-    pid_t pid;
-    uid_t uid;
-    gid_t gid;
-    if (get_process_info(request.tid, &pid, &uid, &gid) != 0) {
-      ALOGE("debuggerd: failed to get process info for tid '%d'", request.tid);
-      exit(1);
-    }
-
-    if (pid != request.pid || uid != request.uid || gid != request.gid) {
-      ALOGE(
-        "debuggerd: attached task %d does not match request: "
-        "expected pid=%d,uid=%d,gid=%d, actual pid=%d,uid=%d,gid=%d",
-        request.tid, request.pid, request.uid, request.gid, pid, uid, gid);
-      exit(1);
-    }
-  }
-
-  // Don't attach to the sibling threads if we want to attach gdb.
-  // Supposedly, it makes the process less reliable.
-  bool attach_gdb = should_attach_gdb(request);
-  if (attach_gdb) {
-    // Open all of the input devices we need to listen for VOLUMEDOWN before dropping privileges.
-    if (init_getevent() != 0) {
-      ALOGE("debuggerd: failed to initialize input device, not waiting for gdb");
-      attach_gdb = false;
-    }
-
-  }
-
-  std::set<pid_t> siblings;
-  if (!attach_gdb) {
-    ptrace_siblings(request.pid, request.tid, siblings);
-  }
-
-  // Generate the backtrace map before dropping privileges.
-  std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid));
-
-  int amfd = -1;
-  std::unique_ptr<std::string> amfd_data;
-  if (request.action == DEBUGGER_ACTION_CRASH) {
-    // Connect to the activity manager before dropping privileges.
-    amfd = activity_manager_connect();
-    amfd_data.reset(new std::string);
-  }
-
-  bool succeeded = false;
-
-  // Now that we've done everything that requires privileges, we can drop them.
-  if (!drop_privileges()) {
-    ALOGE("debuggerd: failed to drop privileges, exiting");
-    _exit(1);
-  }
-
-  int crash_signal = SIGKILL;
-  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings,
-                           &crash_signal, amfd_data.get());
-  if (succeeded) {
-    if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
-      if (!tombstone_path.empty()) {
-        android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length());
-      }
-    }
-  }
-
-  if (attach_gdb) {
-    // Tell the signal process to send SIGSTOP to the target.
-    if (!send_signal(request.pid, 0, SIGSTOP)) {
-      ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno));
-      attach_gdb = false;
-    }
-  }
-
-  if (!attach_gdb) {
-    // Tell the Activity Manager about the crashing process. If we are
-    // waiting for gdb to attach, do not send this or Activity Manager
-    // might kill the process before anyone can attach.
-    activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
-  }
-
-  if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) {
-    ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno));
-  }
-
-  for (pid_t sibling : siblings) {
-    ptrace(PTRACE_DETACH, sibling, 0, 0);
-  }
-
-  // Send the signal back to the process if it crashed and we're not waiting for gdb.
-  if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) {
-    if (!send_signal(request.pid, request.tid, crash_signal)) {
-      ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno));
-    }
-  }
-
-  // Wait for gdb, if requested.
-  if (attach_gdb) {
-    wait_for_user_action(request);
-
-    // Now tell the activity manager about this process.
-    activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
-
-    // Tell the signal process to send SIGCONT to the target.
-    if (!send_signal(request.pid, 0, SIGCONT)) {
-      ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno));
-    }
-
-    uninit_getevent();
-  }
-
-  close(amfd);
-
-  exit(!succeeded);
-}
-
-static void monitor_worker_process(int child_pid, const debugger_request_t& request) {
-  struct timespec timeout = {.tv_sec = 10, .tv_nsec = 0 };
-  if (should_attach_gdb(request)) {
-    // If wait_for_gdb is enabled, set the timeout to something large.
-    timeout.tv_sec = INT_MAX;
-  }
-
-  sigset_t signal_set;
-  sigemptyset(&signal_set);
-  sigaddset(&signal_set, SIGCHLD);
-
-  bool kill_worker = false;
-  bool kill_target = false;
-  bool kill_self = false;
-
-  int status;
-  siginfo_t siginfo;
-  int signal = TEMP_FAILURE_RETRY(sigtimedwait(&signal_set, &siginfo, &timeout));
-  if (signal == SIGCHLD) {
-    pid_t rc = waitpid(-1, &status, WNOHANG | WUNTRACED);
-    if (rc != child_pid) {
-      ALOGE("debuggerd: waitpid returned unexpected pid (%d), committing murder-suicide", rc);
-
-      if (WIFEXITED(status)) {
-        ALOGW("debuggerd: pid %d exited with status %d", rc, WEXITSTATUS(status));
-      } else if (WIFSIGNALED(status)) {
-        ALOGW("debuggerd: pid %d received signal %d", rc, WTERMSIG(status));
-      } else if (WIFSTOPPED(status)) {
-        ALOGW("debuggerd: pid %d stopped by signal %d", rc, WSTOPSIG(status));
-      } else if (WIFCONTINUED(status)) {
-        ALOGW("debuggerd: pid %d continued", rc);
-      }
-
-      kill_worker = true;
-      kill_target = true;
-      kill_self = true;
-    } else if (WIFSIGNALED(status)) {
-      ALOGE("debuggerd: worker process %d terminated due to signal %d", child_pid, WTERMSIG(status));
-      kill_worker = false;
-      kill_target = true;
-    } else if (WIFSTOPPED(status)) {
-      ALOGE("debuggerd: worker process %d stopped due to signal %d", child_pid, WSTOPSIG(status));
-      kill_worker = true;
-      kill_target = true;
-    }
-  } else {
-    ALOGE("debuggerd: worker process %d timed out", child_pid);
-    kill_worker = true;
-    kill_target = true;
-  }
-
-  if (kill_worker) {
-    // Something bad happened, kill the worker.
-    if (kill(child_pid, SIGKILL) != 0) {
-      ALOGE("debuggerd: failed to kill worker process %d: %s", child_pid, strerror(errno));
-    } else {
-      waitpid(child_pid, &status, 0);
-    }
-  }
-
-  int exit_signal = SIGCONT;
-  if (kill_target && request.action == DEBUGGER_ACTION_CRASH) {
-    ALOGE("debuggerd: killing target %d", request.pid);
-    exit_signal = SIGKILL;
-  } else {
-    ALOGW("debuggerd: resuming target %d", request.pid);
-  }
-
-  if (kill(request.pid, exit_signal) != 0) {
-    ALOGE("debuggerd: failed to send signal %d to target: %s", exit_signal, strerror(errno));
-  }
-
-  if (kill_self) {
-    stop_signal_sender();
-    _exit(1);
-  }
-}
-
-static void handle_request(int fd) {
-  ALOGV("handle_request(%d)\n", fd);
-
-  ScopedFd closer(fd);
-  debugger_request_t request;
-  memset(&request, 0, sizeof(request));
-  int status = read_request(fd, &request);
-  if (status != 0) {
-    return;
-  }
-
-  ALOGW("debuggerd: handling request: pid=%d uid=%d gid=%d tid=%d\n", request.pid, request.uid,
-        request.gid, request.tid);
-
-#if defined(__LP64__)
-  // On 64 bit systems, requests to dump 32 bit and 64 bit tids come
-  // to the 64 bit debuggerd. If the process is a 32 bit executable,
-  // redirect the request to the 32 bit debuggerd.
-  if (is32bit(request.tid)) {
-    // Only dump backtrace and dump tombstone requests can be redirected.
-    if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE ||
-        request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
-      redirect_to_32(fd, &request);
-    } else {
-      ALOGE("debuggerd: Not allowed to redirect action %d to 32 bit debuggerd\n", request.action);
-    }
-    return;
-  }
-#endif
-
-  // Fork a child to handle the rest of the request.
-  pid_t fork_pid = fork();
-  if (fork_pid == -1) {
-    ALOGE("debuggerd: failed to fork: %s\n", strerror(errno));
-  } else if (fork_pid == 0) {
-    worker_process(fd, request);
-  } else {
-    monitor_worker_process(fork_pid, request);
-  }
-}
-
-static int do_server() {
-  // debuggerd crashes can't be reported to debuggerd.
-  // Reset all of the crash handlers.
-  signal(SIGABRT, SIG_DFL);
-  signal(SIGBUS, SIG_DFL);
-  signal(SIGFPE, SIG_DFL);
-  signal(SIGILL, SIG_DFL);
-  signal(SIGSEGV, SIG_DFL);
-#ifdef SIGSTKFLT
-  signal(SIGSTKFLT, SIG_DFL);
-#endif
-  signal(SIGTRAP, SIG_DFL);
-
-  // Ignore failed writes to closed sockets
-  signal(SIGPIPE, SIG_IGN);
-
-  // Block SIGCHLD so we can sigtimedwait for it.
-  sigset_t sigchld;
-  sigemptyset(&sigchld);
-  sigaddset(&sigchld, SIGCHLD);
-  sigprocmask(SIG_SETMASK, &sigchld, nullptr);
-
-  int s = socket_local_server(SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
-                              SOCK_STREAM | SOCK_CLOEXEC);
-  if (s == -1) return 1;
-
-  // Fork a process that stays root, and listens on a pipe to pause and resume the target.
-  if (!start_signal_sender()) {
-    ALOGE("debuggerd: failed to fork signal sender");
-    return 1;
-  }
-
-  ALOGI("debuggerd: starting\n");
-
-  for (;;) {
-    sockaddr_storage ss;
-    sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
-    socklen_t alen = sizeof(ss);
-
-    ALOGV("waiting for connection\n");
-    int fd = accept4(s, addrp, &alen, SOCK_CLOEXEC);
-    if (fd == -1) {
-      ALOGE("accept failed: %s\n", strerror(errno));
-      continue;
-    }
-
-    handle_request(fd);
-  }
-  return 0;
-}
-
-static int do_explicit_dump(pid_t tid, bool dump_backtrace) {
-  fprintf(stdout, "Sending request to dump task %d.\n", tid);
-
-  if (dump_backtrace) {
-    fflush(stdout);
-    if (dump_backtrace_to_file(tid, fileno(stdout)) < 0) {
-      fputs("Error dumping backtrace.\n", stderr);
-      return 1;
-    }
-  } else {
-    char tombstone_path[PATH_MAX];
-    if (dump_tombstone(tid, tombstone_path, sizeof(tombstone_path)) < 0) {
-      fputs("Error dumping tombstone.\n", stderr);
-      return 1;
-    }
-    fprintf(stderr, "Tombstone written to: %s\n", tombstone_path);
-  }
-  return 0;
-}
-
-static void usage() {
-  fputs("Usage: -b [<tid>]\n"
-        "  -b dump backtrace to console, otherwise dump full tombstone file\n"
-        "\n"
-        "If tid specified, sends a request to debuggerd to dump that task.\n"
-        "Otherwise, starts the debuggerd server.\n", stderr);
-}
-
-int main(int argc, char** argv) {
-  union selinux_callback cb;
-  if (argc == 1) {
-    cb.func_audit = audit_callback;
-    selinux_set_callback(SELINUX_CB_AUDIT, cb);
-    cb.func_log = selinux_log_callback;
-    selinux_set_callback(SELINUX_CB_LOG, cb);
-    return do_server();
-  }
-
-  bool dump_backtrace = false;
-  bool have_tid = false;
-  pid_t tid = 0;
-  for (int i = 1; i < argc; i++) {
-    if (!strcmp(argv[i], "-b")) {
-      dump_backtrace = true;
-    } else if (!have_tid) {
-      tid = atoi(argv[i]);
-      have_tid = true;
-    } else {
-      usage();
-      return 1;
-    }
-  }
-  if (!have_tid) {
-    usage();
-    return 1;
-  }
-  return do_explicit_dump(tid, dump_backtrace);
-}
diff --git a/debuggerd/debuggerd.rc b/debuggerd/debuggerd.rc
deleted file mode 100644
index 1c6b9ff..0000000
--- a/debuggerd/debuggerd.rc
+++ /dev/null
@@ -1,3 +0,0 @@
-service debuggerd /system/bin/debuggerd
-    group root readproc
-    writepid /dev/cpuset/system-background/tasks
diff --git a/debuggerd/debuggerd64.rc b/debuggerd/debuggerd64.rc
deleted file mode 100644
index 3e8847a..0000000
--- a/debuggerd/debuggerd64.rc
+++ /dev/null
@@ -1,3 +0,0 @@
-service debuggerd64 /system/bin/debuggerd64
-    group root readproc
-    writepid /dev/cpuset/system-background/tasks
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
new file mode 100644
index 0000000..fa0626b
--- /dev/null
+++ b/debuggerd/debuggerd_test.cpp
@@ -0,0 +1,685 @@
+/*
+ * Copyright 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 <err.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <sys/types.h>
+
+#include <chrono>
+#include <regex>
+#include <thread>
+
+#include <android/set_abort_message.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/parseint.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+#include <debuggerd/handler.h>
+#include <debuggerd/protocol.h>
+#include <debuggerd/tombstoned.h>
+#include <debuggerd/util.h>
+#include <gtest/gtest.h>
+
+using namespace std::chrono_literals;
+using android::base::unique_fd;
+
+#if defined(__LP64__)
+#define ARCH_SUFFIX "64"
+#else
+#define ARCH_SUFFIX ""
+#endif
+
+constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
+
+#define TIMEOUT(seconds, expr)                                     \
+  [&]() {                                                          \
+    struct sigaction old_sigaction;                                \
+    struct sigaction new_sigaction = {};                           \
+    new_sigaction.sa_handler = [](int) {};                         \
+    if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
+      err(1, "sigaction failed");                                  \
+    }                                                              \
+    alarm(seconds);                                                \
+    auto value = expr;                                             \
+    int saved_errno = errno;                                       \
+    if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) {        \
+      err(1, "sigaction failed");                                  \
+    }                                                              \
+    alarm(0);                                                      \
+    errno = saved_errno;                                           \
+    return value;                                                  \
+  }()
+
+#define ASSERT_MATCH(str, pattern)                                              \
+  do {                                                                          \
+    std::regex r((pattern));                                                    \
+    if (!std::regex_search((str), r)) {                                         \
+      FAIL() << "regex mismatch: expected " << (pattern) << " in: \n" << (str); \
+    }                                                                           \
+  } while (0)
+
+#define ASSERT_NOT_MATCH(str, pattern)                                                      \
+  do {                                                                                      \
+    std::regex r((pattern));                                                                \
+    if (std::regex_search((str), r)) {                                                      \
+      FAIL() << "regex mismatch: expected to not find " << (pattern) << " in: \n" << (str); \
+    }                                                                                       \
+  } while (0)
+
+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);
+  }
+
+  ASSERT_GE(pipe_buffer_size, 1024 * 1024);
+
+  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;
+  bool previous_wait_for_gdb;
+  unique_fd crasher_pipe;
+  unique_fd intercept_fd;
+
+  CrasherTest();
+  ~CrasherTest();
+
+  void StartIntercept(unique_fd* output_fd);
+
+  // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
+  void FinishIntercept(int* result);
+
+  void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
+  void StartCrasher(const std::string& crash_type);
+  void FinishCrasher();
+  void AssertDeath(int signo);
+};
+
+CrasherTest::CrasherTest() {
+  previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
+  android::base::SetProperty(kWaitForGdbKey, "0");
+}
+
+CrasherTest::~CrasherTest() {
+  if (crasher_pid != -1) {
+    kill(crasher_pid, SIGKILL);
+    int status;
+    waitpid(crasher_pid, &status, WUNTRACED);
+  }
+
+  android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
+}
+
+void CrasherTest::StartIntercept(unique_fd* output_fd) {
+  if (crasher_pid == -1) {
+    FAIL() << "crasher hasn't been started";
+  }
+
+  tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd);
+}
+
+void CrasherTest::FinishIntercept(int* result) {
+  InterceptResponse response;
+
+  // Timeout for tombstoned intercept is 10 seconds.
+  ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
+  if (rc == -1) {
+    FAIL() << "failed to read response from tombstoned: " << strerror(errno);
+  } else if (rc == 0) {
+    *result = -1;
+  } else if (rc != sizeof(response)) {
+    FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
+           << ", received " << rc;
+  } else {
+    *result = response.status == InterceptStatus::kStarted ? 1 : 0;
+  }
+}
+
+void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
+  unique_fd read_pipe;
+  unique_fd crasher_read_pipe;
+  if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
+    FAIL() << "failed to create pipe: " << strerror(errno);
+  }
+
+  crasher_pid = forker();
+  if (crasher_pid == -1) {
+    FAIL() << "fork failed: " << strerror(errno);
+  } else if (crasher_pid == 0) {
+    char dummy;
+    crasher_pipe.reset();
+    TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
+    function();
+    _exit(0);
+  }
+}
+
+void CrasherTest::FinishCrasher() {
+  if (crasher_pipe == -1) {
+    FAIL() << "crasher pipe uninitialized";
+  }
+
+  ssize_t rc = write(crasher_pipe.get(), "\n", 1);
+  if (rc == -1) {
+    FAIL() << "failed to write to crasher pipe: " << strerror(errno);
+  } else if (rc == 0) {
+    FAIL() << "crasher pipe was closed";
+  }
+}
+
+void CrasherTest::AssertDeath(int signo) {
+  int status;
+  pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
+  if (pid != crasher_pid) {
+    FAIL() << "failed to wait for crasher: " << strerror(errno);
+  }
+
+  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));
+  }
+  crasher_pid = -1;
+}
+
+static void ConsumeFd(unique_fd fd, std::string* output) {
+  constexpr size_t read_length = PAGE_SIZE;
+  std::string result;
+
+  while (true) {
+    size_t offset = result.size();
+    result.resize(result.size() + PAGE_SIZE);
+    ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
+    if (rc == -1) {
+      FAIL() << "read failed: " << strerror(errno);
+    } else if (rc == 0) {
+      result.resize(result.size() - PAGE_SIZE);
+      break;
+    }
+
+    result.resize(result.size() - PAGE_SIZE + rc);
+  }
+
+  *output = std::move(result);
+}
+
+TEST_F(CrasherTest, smoke) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    *reinterpret_cast<volatile char*>(0xdead) = '1';
+  });
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGSEGV);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
+}
+
+TEST_F(CrasherTest, abort) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    abort();
+  });
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX R"(/libc.so \(tgkill)");
+}
+
+TEST_F(CrasherTest, signal) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    abort();
+  });
+  StartIntercept(&output_fd);
+
+  // Wait for a bit, or we might end up killing the process before the signal
+  // handler even gets a chance to be registered.
+  std::this_thread::sleep_for(100ms);
+  ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
+
+  AssertDeath(SIGSEGV);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER\), fault addr --------)");
+  ASSERT_MATCH(result, R"(backtrace:)");
+}
+
+TEST_F(CrasherTest, abort_message) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    android_set_abort_message("abort message goes here");
+    abort();
+  });
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  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;
+  StartProcess([]() {
+    abort();
+  });
+  StartIntercept(&output_fd);
+
+  // Don't let crasher finish until we timeout.
+  FinishIntercept(&intercept_result);
+
+  ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
+                                 << intercept_result << ")";
+
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+}
+
+TEST_F(CrasherTest, wait_for_gdb) {
+  if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
+    FAIL() << "failed to enable wait_for_gdb";
+  }
+  sleep(1);
+
+  StartProcess([]() {
+    abort();
+  });
+  FinishCrasher();
+
+  int status;
+  ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
+  ASSERT_TRUE(WIFSTOPPED(status));
+  ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
+
+  ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
+
+  AssertDeath(SIGABRT);
+}
+
+// wait_for_gdb shouldn't trigger on manually sent signals.
+TEST_F(CrasherTest, wait_for_gdb_signal) {
+  if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
+    FAIL() << "failed to enable wait_for_gdb";
+  }
+
+  StartProcess([]() {
+    abort();
+  });
+  ASSERT_EQ(0, kill(crasher_pid, SIGSEGV)) << strerror(errno);
+  AssertDeath(SIGSEGV);
+}
+
+TEST_F(CrasherTest, backtrace) {
+  std::string result;
+  int intercept_result;
+  unique_fd output_fd;
+
+  StartProcess([]() {
+    abort();
+  });
+  StartIntercept(&output_fd);
+
+  std::this_thread::sleep_for(500ms);
+
+  sigval val;
+  val.sival_int = 1;
+  ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
+  FinishIntercept(&intercept_result);
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+  /system/lib)" ARCH_SUFFIX R"(/libc.so \(read\+)");
+
+  int status;
+  ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  FinishIntercept(&intercept_result);
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX R"(/libc.so \(tgkill)");
+}
+
+TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    prctl(PR_SET_DUMPABLE, 0);
+    abort();
+  });
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGABRT);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX R"(/libc.so \(tgkill)");
+}
+
+TEST_F(CrasherTest, capabilities) {
+  ASSERT_EQ(0U, getuid()) << "capability test requires root";
+
+  StartProcess([]() {
+    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
+      err(1, "failed to set PR_SET_KEEPCAPS");
+    }
+
+    if (setresuid(1, 1, 1) != 0) {
+      err(1, "setresuid failed");
+    }
+
+    __user_cap_header_struct capheader;
+    __user_cap_data_struct capdata[2];
+    memset(&capheader, 0, sizeof(capheader));
+    memset(&capdata, 0, sizeof(capdata));
+
+    capheader.version = _LINUX_CAPABILITY_VERSION_3;
+    capheader.pid = 0;
+
+    // Turn on every third capability.
+    static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
+    for (int i = 0; i < CAP_LAST_CAP; i += 3) {
+      capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
+      capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
+    }
+
+    // Make sure CAP_SYS_PTRACE is off.
+    capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
+    capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
+
+    if (capset(&capheader, &capdata[0]) != 0) {
+      err(1, "capset failed");
+    }
+
+    if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
+      err(1, "failed to drop ambient capabilities");
+    }
+
+    pthread_setname_np(pthread_self(), "thread_name");
+    raise(SIGSYS);
+  });
+
+  unique_fd output_fd;
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGSYS);
+
+  std::string result;
+  int intercept_result;
+  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_F(CrasherTest, fake_pid) {
+  int intercept_result;
+  unique_fd output_fd;
+
+  // Prime the getpid/gettid caches.
+  UNUSED(getpid());
+  UNUSED(gettid());
+
+  std::function<pid_t()> clone_fn = []() {
+    return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
+  };
+  StartProcess(
+      []() {
+        ASSERT_NE(getpid(), syscall(__NR_getpid));
+        ASSERT_NE(gettid(), syscall(__NR_gettid));
+        raise(SIGSEGV);
+      },
+      clone_fn);
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGSEGV);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX R"(/libc.so \(tgkill)");
+}
+
+TEST(crash_dump, zombie) {
+  pid_t forkpid = fork();
+
+  pid_t rc;
+  int status;
+
+  if (forkpid == 0) {
+    errno = 0;
+    rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
+    if (rc != -1 || errno != ECHILD) {
+      errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
+    }
+
+    raise(DEBUGGER_SIGNAL);
+
+    errno = 0;
+    rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
+    if (rc != -1 || errno != ECHILD) {
+      errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
+    }
+    _exit(0);
+  } else {
+    rc = waitpid(forkpid, &status, 0);
+    ASSERT_EQ(forkpid, rc);
+    ASSERT_TRUE(WIFEXITED(status));
+    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/elf_utils.cpp b/debuggerd/elf_utils.cpp
deleted file mode 100644
index 9959f2e..0000000
--- a/debuggerd/elf_utils.cpp
+++ /dev/null
@@ -1,121 +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.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include <elf.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <string>
-
-#include <backtrace/Backtrace.h>
-#include <android-base/stringprintf.h>
-#include <log/log.h>
-
-#include "elf_utils.h"
-
-#define NOTE_ALIGN(size)  ((size + 3) & ~3)
-
-template <typename HdrType, typename PhdrType, typename NhdrType>
-static bool get_build_id(
-    Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) {
-  HdrType hdr;
-
-  memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT);
-
-  // First read the rest of the header.
-  if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT,
-                      sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) {
-    return false;
-  }
-
-  for (size_t i = 0; i < hdr.e_phnum; i++) {
-    PhdrType phdr;
-    if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize,
-                        reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) {
-      return false;
-    }
-    // Looking for the .note.gnu.build-id note.
-    if (phdr.p_type == PT_NOTE) {
-      size_t hdr_size = phdr.p_filesz;
-      uintptr_t addr = base_addr + phdr.p_offset;
-      while (hdr_size >= sizeof(NhdrType)) {
-        NhdrType nhdr;
-        if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) {
-          return false;
-        }
-        addr += sizeof(nhdr);
-        if (nhdr.n_type == NT_GNU_BUILD_ID) {
-          // Skip the name (which is the owner and should be "GNU").
-          addr += NOTE_ALIGN(nhdr.n_namesz);
-          uint8_t build_id_data[160];
-          if (nhdr.n_descsz > sizeof(build_id_data)) {
-            ALOGE("Possible corrupted note, desc size value is too large: %u",
-                  nhdr.n_descsz);
-            return false;
-          }
-          if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) {
-            return false;
-          }
-
-          build_id->clear();
-          for (size_t bytes = 0; bytes < nhdr.n_descsz; bytes++) {
-            *build_id += android::base::StringPrintf("%02x", build_id_data[bytes]);
-          }
-
-          return true;
-        } else {
-          // Move past the extra note data.
-          hdr_size -= sizeof(nhdr);
-          size_t skip_bytes = NOTE_ALIGN(nhdr.n_namesz) + NOTE_ALIGN(nhdr.n_descsz);
-          addr += skip_bytes;
-          if (hdr_size < skip_bytes) {
-            break;
-          }
-          hdr_size -= skip_bytes;
-        }
-      }
-    }
-  }
-  return false;
-}
-
-bool elf_get_build_id(Backtrace* backtrace, uintptr_t addr, std::string* build_id) {
-  // Read and verify the elf magic number first.
-  uint8_t e_ident[EI_NIDENT];
-  if (backtrace->Read(addr, e_ident, SELFMAG) != SELFMAG) {
-    return false;
-  }
-
-  if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
-    return false;
-  }
-
-  // Read the rest of EI_NIDENT.
-  if (backtrace->Read(addr + SELFMAG, e_ident + SELFMAG, EI_NIDENT - SELFMAG) != EI_NIDENT - SELFMAG) {
-    return false;
-  }
-
-  if (e_ident[EI_CLASS] == ELFCLASS32) {
-    return get_build_id<Elf32_Ehdr, Elf32_Phdr, Elf32_Nhdr>(backtrace, addr, e_ident, build_id);
-  } else if (e_ident[EI_CLASS] == ELFCLASS64) {
-    return get_build_id<Elf64_Ehdr, Elf64_Phdr, Elf64_Nhdr>(backtrace, addr, e_ident, build_id);
-  }
-
-  return false;
-}
diff --git a/debuggerd/getevent.cpp b/debuggerd/getevent.cpp
deleted file mode 100644
index 751c4fb..0000000
--- a/debuggerd/getevent.cpp
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * 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.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/inotify.h>
-#include <sys/limits.h>
-#include <sys/poll.h>
-#include <linux/input.h>
-#include <errno.h>
-#include <cutils/log.h>
-
-static struct pollfd* ufds;
-static char** device_names;
-static int nfds;
-
-static int open_device(const char* device) {
-  int version;
-  int fd;
-  struct pollfd* new_ufds;
-  char** new_device_names;
-  char name[80];
-  char location[80];
-  char idstr[80];
-  struct input_id id;
-
-  fd = open(device, O_RDWR);
-  if (fd < 0) {
-    return -1;
-  }
-
-  if (ioctl(fd, EVIOCGVERSION, &version)) {
-    return -1;
-  }
-  if (ioctl(fd, EVIOCGID, &id)) {
-    return -1;
-  }
-  name[sizeof(name) - 1] = '\0';
-  location[sizeof(location) - 1] = '\0';
-  idstr[sizeof(idstr) - 1] = '\0';
-  if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
-    name[0] = '\0';
-  }
-  if (ioctl(fd, EVIOCGPHYS(sizeof(location) - 1), &location) < 1) {
-    location[0] = '\0';
-  }
-  if (ioctl(fd, EVIOCGUNIQ(sizeof(idstr) - 1), &idstr) < 1) {
-    idstr[0] = '\0';
-  }
-
-  new_ufds = reinterpret_cast<pollfd*>(realloc(ufds, sizeof(ufds[0]) * (nfds + 1)));
-  if (new_ufds == NULL) {
-    fprintf(stderr, "out of memory\n");
-    return -1;
-  }
-  ufds = new_ufds;
-  new_device_names = reinterpret_cast<char**>(realloc(
-      device_names, sizeof(device_names[0]) * (nfds + 1)));
-  if (new_device_names == NULL) {
-    fprintf(stderr, "out of memory\n");
-    return -1;
-  }
-  device_names = new_device_names;
-  ufds[nfds].fd = fd;
-  ufds[nfds].events = POLLIN;
-  device_names[nfds] = strdup(device);
-  nfds++;
-
-  return 0;
-}
-
-int close_device(const char* device) {
-  int i;
-  for (i = 1; i < nfds; i++) {
-    if (strcmp(device_names[i], device) == 0) {
-      int count = nfds - i - 1;
-      free(device_names[i]);
-      memmove(device_names + i, device_names + i + 1, sizeof(device_names[0]) * count);
-      memmove(ufds + i, ufds + i + 1, sizeof(ufds[0]) * count);
-      nfds--;
-      return 0;
-    }
-  }
-  return -1;
-}
-
-static int read_notify(const char* dirname, int nfd) {
-  int res;
-  char devname[PATH_MAX];
-  char* filename;
-  char event_buf[512];
-  int event_size;
-  int event_pos = 0;
-  struct inotify_event *event;
-
-  res = read(nfd, event_buf, sizeof(event_buf));
-  if (res < (int)sizeof(*event)) {
-    if (errno == EINTR)
-      return 0;
-    fprintf(stderr, "could not get event, %s\n", strerror(errno));
-    return 1;
-  }
-
-  strcpy(devname, dirname);
-  filename = devname + strlen(devname);
-  *filename++ = '/';
-
-  while (res >= (int)sizeof(*event)) {
-    event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);
-    if (event->len) {
-      strcpy(filename, event->name);
-      if (event->mask & IN_CREATE) {
-        open_device(devname);
-      } else {
-        close_device(devname);
-      }
-    }
-    event_size = sizeof(*event) + event->len;
-    res -= event_size;
-    event_pos += event_size;
-  }
-  return 0;
-}
-
-static int scan_dir(const char* dirname) {
-  char devname[PATH_MAX];
-  char* filename;
-  DIR* dir;
-  struct dirent* de;
-  dir = opendir(dirname);
-  if (dir == NULL)
-    return -1;
-  strcpy(devname, dirname);
-  filename = devname + strlen(devname);
-  *filename++ = '/';
-  while ((de = readdir(dir))) {
-    if ((de->d_name[0] == '.' && de->d_name[1] == '\0') ||
-        (de->d_name[1] == '.' && de->d_name[2] == '\0'))
-      continue;
-    strcpy(filename, de->d_name);
-    open_device(devname);
-  }
-  closedir(dir);
-  return 0;
-}
-
-int init_getevent() {
-  int res;
-  const char* device_path = "/dev/input";
-
-  nfds = 1;
-  ufds = reinterpret_cast<pollfd*>(calloc(1, sizeof(ufds[0])));
-  ufds[0].fd = inotify_init();
-  ufds[0].events = POLLIN;
-
-  res = inotify_add_watch(ufds[0].fd, device_path, IN_DELETE | IN_CREATE);
-  if (res < 0) {
-    return 1;
-  }
-  res = scan_dir(device_path);
-  if (res < 0) {
-    return 1;
-  }
-  return 0;
-}
-
-void uninit_getevent() {
-  int i;
-  for (i = 0; i < nfds; i++) {
-    close(ufds[i].fd);
-  }
-  free(ufds);
-  ufds = 0;
-  nfds = 0;
-}
-
-int get_event(struct input_event* event, int timeout) {
-  int res;
-  int i;
-  int pollres;
-  const char* device_path = "/dev/input";
-  while (1) {
-    pollres = poll(ufds, nfds, timeout);
-    if (pollres == 0) {
-      return 1;
-    }
-    if (ufds[0].revents & POLLIN) {
-      read_notify(device_path, ufds[0].fd);
-    }
-    for (i = 1; i < nfds; i++) {
-      if (ufds[i].revents) {
-        if (ufds[i].revents & POLLIN) {
-          res = read(ufds[i].fd, event, sizeof(*event));
-          if (res < static_cast<int>(sizeof(event))) {
-            fprintf(stderr, "could not get event\n");
-            return -1;
-          }
-          return 0;
-        }
-      }
-    }
-  }
-  return 0;
-}
diff --git a/debuggerd/getevent.h b/debuggerd/getevent.h
deleted file mode 100644
index 426139d..0000000
--- a/debuggerd/getevent.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DEBUGGERD_GETEVENT_H
-#define _DEBUGGERD_GETEVENT_H
-
-int init_getevent();
-void uninit_getevent();
-int get_event(struct input_event* event, int timeout);
-
-#endif // _DEBUGGERD_GETEVENT_H
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
new file mode 100644
index 0000000..5c6c59c
--- /dev/null
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -0,0 +1,231 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stddef.h>
+#include <sys/ucontext.h>
+#include <syscall.h>
+#include <unistd.h>
+
+#include <atomic>
+
+#include <android-base/file.h>
+#include <android-base/unique_fd.h>
+
+#include "debuggerd/handler.h"
+#include "debuggerd/tombstoned.h"
+#include "debuggerd/util.h"
+
+#include "backtrace.h"
+#include "tombstone.h"
+
+#include "private/libc_logging.h"
+
+using android::base::unique_fd;
+
+extern "C" void __linker_enable_fallback_allocator();
+extern "C" void __linker_disable_fallback_allocator();
+
+// This is incredibly sketchy to do inside of a signal handler, especially when libbacktrace
+// uses the C++ standard library throughout, but this code runs in the linker, so we'll be using
+// the linker's malloc instead of the libc one. Switch it out for a replacement, just in case.
+//
+// This isn't the default method of dumping because it can fail in cases such as address space
+// exhaustion.
+static void debuggerd_fallback_trace(int output_fd, ucontext_t* ucontext) {
+  __linker_enable_fallback_allocator();
+  dump_backtrace_ucontext(output_fd, ucontext);
+  __linker_disable_fallback_allocator();
+}
+
+static void debuggerd_fallback_tombstone(int output_fd, ucontext_t* ucontext, siginfo_t* siginfo,
+                                         void* abort_message) {
+  __linker_enable_fallback_allocator();
+  engrave_tombstone_ucontext(output_fd, reinterpret_cast<uintptr_t>(abort_message), siginfo,
+                             ucontext);
+  __linker_disable_fallback_allocator();
+}
+
+static void iterate_siblings(bool (*callback)(pid_t, int), int output_fd) {
+  pid_t current_tid = gettid();
+  char buf[BUFSIZ];
+  snprintf(buf, sizeof(buf), "/proc/%d/task", current_tid);
+  DIR* dir = opendir(buf);
+
+  if (!dir) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to open %s: %s", buf, strerror(errno));
+    return;
+  }
+
+  struct dirent* ent;
+  while ((ent = readdir(dir))) {
+    char* end;
+    long tid = strtol(ent->d_name, &end, 10);
+    if (end == ent->d_name || *end != '\0') {
+      continue;
+    }
+
+    if (tid != current_tid) {
+      callback(tid, output_fd);
+    }
+  }
+  closedir(dir);
+}
+
+static bool forward_output(int src_fd, int dst_fd) {
+  // Make sure the thread actually got the signal.
+  struct pollfd pfd = {
+    .fd = src_fd, .events = POLLIN,
+  };
+
+  // Wait for up to a second for output to start flowing.
+  if (poll(&pfd, 1, 1000) != 1) {
+    return false;
+  }
+
+  while (true) {
+    char buf[512];
+    ssize_t rc = TEMP_FAILURE_RETRY(read(src_fd, buf, sizeof(buf)));
+    if (rc == 0) {
+      return true;
+    } else if (rc < 0) {
+      return false;
+    }
+
+    if (!android::base::WriteFully(dst_fd, buf, rc)) {
+      // We failed to write to tombstoned, but there's not much we can do.
+      // Keep reading from src_fd to keep things going.
+      continue;
+    }
+  }
+}
+
+static void trace_handler(siginfo_t* info, ucontext_t* ucontext) {
+  static std::atomic<int> trace_output_fd(-1);
+
+  if (info->si_value.sival_int == ~0) {
+    // Asked to dump by the original signal recipient.
+    debuggerd_fallback_trace(trace_output_fd, ucontext);
+
+    int tmp = trace_output_fd.load();
+    trace_output_fd.store(-1);
+    close(tmp);
+    return;
+  }
+
+  // Only allow one thread to perform a trace at a time.
+  static pthread_mutex_t trace_mutex = PTHREAD_MUTEX_INITIALIZER;
+  int ret = pthread_mutex_trylock(&trace_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_try_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  // Fetch output fd from tombstoned.
+  unique_fd tombstone_socket, output_fd;
+  if (!tombstoned_connect(getpid(), &tombstone_socket, &output_fd)) {
+    goto exit;
+  }
+
+  dump_backtrace_header(output_fd.get());
+
+  // Dump our own stack.
+  debuggerd_fallback_trace(output_fd.get(), ucontext);
+
+  // Send a signal to all of our siblings, asking them to dump their stack.
+  iterate_siblings(
+    [](pid_t tid, int output_fd) {
+      // Use a pipe, to be able to detect situations where the thread gracefully exits before
+      // receiving our signal.
+      unique_fd pipe_read, pipe_write;
+      if (!Pipe(&pipe_read, &pipe_write)) {
+        __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to create pipe: %s", strerror(errno));
+        return false;
+      }
+
+      trace_output_fd.store(pipe_write.get());
+
+      siginfo_t siginfo = {};
+      siginfo.si_code = SI_QUEUE;
+      siginfo.si_value.sival_int = ~0;
+      siginfo.si_pid = getpid();
+      siginfo.si_uid = getuid();
+
+      if (syscall(__NR_rt_tgsigqueueinfo, getpid(), tid, DEBUGGER_SIGNAL, &siginfo) != 0) {
+        __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to send trace signal to %d: %s", tid,
+                          strerror(errno));
+        return false;
+      }
+
+      bool success = forward_output(pipe_read.get(), output_fd);
+      if (success) {
+        // The signaled thread has closed trace_output_fd already.
+        (void)pipe_write.release();
+      } else {
+        trace_output_fd.store(-1);
+      }
+
+      return true;
+    },
+    output_fd.get());
+
+  dump_backtrace_footer(output_fd.get());
+  tombstoned_notify_completion(tombstone_socket.get());
+
+exit:
+  pthread_mutex_unlock(&trace_mutex);
+}
+
+static void crash_handler(siginfo_t* info, ucontext_t* ucontext, void* abort_message) {
+  // Only allow one thread to handle a crash.
+  static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
+  int ret = pthread_mutex_lock(&crash_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  unique_fd tombstone_socket, output_fd;
+  bool tombstoned_connected = tombstoned_connect(getpid(), &tombstone_socket, &output_fd);
+  debuggerd_fallback_tombstone(output_fd.get(), ucontext, info, abort_message);
+  if (tombstoned_connected) {
+    tombstoned_notify_completion(tombstone_socket.get());
+  }
+}
+
+extern "C" void debuggerd_fallback_handler(siginfo_t* info, ucontext_t* ucontext,
+                                           void* abort_message) {
+  if (info->si_signo == DEBUGGER_SIGNAL) {
+    return trace_handler(info, ucontext);
+  } else {
+    return crash_handler(info, ucontext, abort_message);
+  }
+}
diff --git a/debuggerd/handler/debuggerd_fallback_nop.cpp b/debuggerd/handler/debuggerd_fallback_nop.cpp
new file mode 100644
index 0000000..331301f
--- /dev/null
+++ b/debuggerd/handler/debuggerd_fallback_nop.cpp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+extern "C" void debuggerd_fallback_handler(struct siginfo_t*, struct ucontext_t*, void*) {
+}
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
new file mode 100644
index 0000000..d58c73d
--- /dev/null
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -0,0 +1,491 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "debuggerd/handler.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <linux/futex.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/capability.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/syscall.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "private/bionic_futex.h"
+#include "private/libc_logging.h"
+
+// see man(2) prctl, specifically the section about PR_GET_NAME
+#define MAX_TASK_NAME_LEN (16)
+
+#if defined(__LP64__)
+#define CRASH_DUMP_NAME "crash_dump64"
+#else
+#define CRASH_DUMP_NAME "crash_dump32"
+#endif
+
+#define CRASH_DUMP_PATH "/system/bin/" CRASH_DUMP_NAME
+
+// Wrappers that directly invoke the respective syscalls, in case the cached values are invalid.
+#pragma GCC poison getpid gettid
+static pid_t __getpid() {
+  return syscall(__NR_getpid);
+}
+
+static pid_t __gettid() {
+  return syscall(__NR_gettid);
+}
+
+class ErrnoRestorer {
+ public:
+  ErrnoRestorer() : saved_errno_(errno) {
+  }
+
+  ~ErrnoRestorer() {
+    errno = saved_errno_;
+  }
+
+ private:
+  int saved_errno_;
+};
+
+extern "C" void debuggerd_fallback_handler(siginfo_t*, ucontext_t*, void*);
+
+static debuggerd_callbacks_t g_callbacks;
+
+// Mutex to ensure only one crashing thread dumps itself.
+static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+// Don't use __libc_fatal because it exits via abort, which might put us back into a signal handler.
+static void __noreturn __printflike(1, 2) fatal(const char* fmt, ...) {
+  va_list args;
+  va_start(args, fmt);
+  __libc_format_log_va_list(ANDROID_LOG_FATAL, "libc", fmt, args);
+  _exit(1);
+}
+
+static void __noreturn __printflike(1, 2) fatal_errno(const char* fmt, ...) {
+  int err = errno;
+  va_list args;
+  va_start(args, fmt);
+
+  char buf[4096];
+  __libc_format_buffer_va_list(buf, sizeof(buf), fmt, args);
+  fatal("%s: %s", buf, strerror(err));
+}
+
+/*
+ * Writes a summary of the signal to the log file.  We do this so that, if
+ * for some reason we're not able to contact debuggerd, there is still some
+ * indication of the failure in the log.
+ *
+ * We could be here as a result of native heap corruption, or while a
+ * mutex is being held, so we don't want to use any libc functions that
+ * could allocate memory or hold a lock.
+ */
+static void log_signal_summary(int signum, const siginfo_t* info) {
+  char thread_name[MAX_TASK_NAME_LEN + 1];  // one more for termination
+  if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(thread_name), 0, 0, 0) != 0) {
+    strcpy(thread_name, "<name unknown>");
+  } else {
+    // short names are null terminated by prctl, but the man page
+    // implies that 16 byte names are not.
+    thread_name[MAX_TASK_NAME_LEN] = 0;
+  }
+
+  if (signum == DEBUGGER_SIGNAL) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "Requested dump for tid %d (%s)", __gettid(),
+                      thread_name);
+    return;
+  }
+
+  const char* signal_name = "???";
+  bool has_address = false;
+  switch (signum) {
+    case SIGABRT:
+      signal_name = "SIGABRT";
+      break;
+    case SIGBUS:
+      signal_name = "SIGBUS";
+      has_address = true;
+      break;
+    case SIGFPE:
+      signal_name = "SIGFPE";
+      has_address = true;
+      break;
+    case SIGILL:
+      signal_name = "SIGILL";
+      has_address = true;
+      break;
+    case SIGSEGV:
+      signal_name = "SIGSEGV";
+      has_address = true;
+      break;
+#if defined(SIGSTKFLT)
+    case SIGSTKFLT:
+      signal_name = "SIGSTKFLT";
+      break;
+#endif
+    case SIGSYS:
+      signal_name = "SIGSYS";
+      break;
+    case SIGTRAP:
+      signal_name = "SIGTRAP";
+      break;
+  }
+
+  // "info" will be null if the siginfo_t information was not available.
+  // Many signals don't have an address or a code.
+  char code_desc[32];  // ", code -6"
+  char addr_desc[32];  // ", fault addr 0x1234"
+  addr_desc[0] = code_desc[0] = 0;
+  if (info != nullptr) {
+    __libc_format_buffer(code_desc, sizeof(code_desc), ", code %d", info->si_code);
+    if (has_address) {
+      __libc_format_buffer(addr_desc, sizeof(addr_desc), ", fault addr %p", info->si_addr);
+    }
+  }
+
+  __libc_format_log(ANDROID_LOG_FATAL, "libc", "Fatal signal %d (%s)%s%s in tid %d (%s)", signum,
+                    signal_name, code_desc, addr_desc, __gettid(), thread_name);
+}
+
+/*
+ * Returns true if the handler for signal "signum" has SA_SIGINFO set.
+ */
+static bool have_siginfo(int signum) {
+  struct sigaction old_action;
+  if (sigaction(signum, nullptr, &old_action) < 0) {
+    __libc_format_log(ANDROID_LOG_WARN, "libc", "Failed testing for SA_SIGINFO: %s",
+                      strerror(errno));
+    return false;
+  }
+  return (old_action.sa_flags & SA_SIGINFO) != 0;
+}
+
+static void raise_caps() {
+  // Raise CapInh to match CapPrm, so that we can set the ambient bits.
+  __user_cap_header_struct capheader;
+  memset(&capheader, 0, sizeof(capheader));
+  capheader.version = _LINUX_CAPABILITY_VERSION_3;
+  capheader.pid = 0;
+
+  __user_cap_data_struct capdata[2];
+  if (capget(&capheader, &capdata[0]) == -1) {
+    fatal_errno("capget failed");
+  }
+
+  if (capdata[0].permitted != capdata[0].inheritable ||
+      capdata[1].permitted != capdata[1].inheritable) {
+    capdata[0].inheritable = capdata[0].permitted;
+    capdata[1].inheritable = capdata[1].permitted;
+
+    if (capset(&capheader, &capdata[0]) == -1) {
+      __libc_format_log(ANDROID_LOG_ERROR, "libc", "capset failed: %s", strerror(errno));
+    }
+  }
+
+  // Set the ambient capability bits so that crash_dump gets all of our caps and can ptrace us.
+  uint64_t capmask = capdata[0].inheritable;
+  capmask |= static_cast<uint64_t>(capdata[1].inheritable) << 32;
+  for (unsigned long i = 0; i < 64; ++i) {
+    if (capmask & (1ULL << i)) {
+      if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) != 0) {
+        __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to raise ambient capability %lu: %s",
+                          i, strerror(errno));
+      }
+    }
+  }
+}
+
+struct debugger_thread_info {
+  bool crash_dump_started;
+  pid_t crashing_tid;
+  pid_t pseudothread_tid;
+  int signal_number;
+  siginfo_t* info;
+};
+
+// Logging and contacting debuggerd requires free file descriptors, which we might not have.
+// Work around this by spawning a "thread" that shares its parent's address space, but not its file
+// descriptor table, so that we can close random file descriptors without affecting the original
+// process. Note that this doesn't go through pthread_create, so TLS is shared with the spawning
+// process.
+static void* pseudothread_stack;
+
+static int debuggerd_dispatch_pseudothread(void* arg) {
+  debugger_thread_info* thread_info = static_cast<debugger_thread_info*>(arg);
+
+  for (int i = 0; i < 1024; ++i) {
+    close(i);
+  }
+
+  int devnull = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
+
+  // devnull will be 0.
+  TEMP_FAILURE_RETRY(dup2(devnull, STDOUT_FILENO));
+  TEMP_FAILURE_RETRY(dup2(devnull, STDERR_FILENO));
+
+  int pipefds[2];
+  if (pipe(pipefds) != 0) {
+    fatal_errno("failed to create pipe");
+  }
+
+  // Don't use fork(2) to avoid calling pthread_atfork handlers.
+  int forkpid = clone(nullptr, nullptr, 0, nullptr);
+  if (forkpid == -1) {
+    __libc_format_log(ANDROID_LOG_FATAL, "libc", "failed to fork in debuggerd signal handler: %s",
+                      strerror(errno));
+  } else if (forkpid == 0) {
+    TEMP_FAILURE_RETRY(dup2(pipefds[1], STDOUT_FILENO));
+    close(pipefds[0]);
+    close(pipefds[1]);
+
+    raise_caps();
+
+    char main_tid[10];
+    char pseudothread_tid[10];
+    __libc_format_buffer(main_tid, sizeof(main_tid), "%d", thread_info->crashing_tid);
+    __libc_format_buffer(pseudothread_tid, sizeof(pseudothread_tid), "%d", thread_info->pseudothread_tid);
+
+    execl(CRASH_DUMP_PATH, CRASH_DUMP_NAME, main_tid, pseudothread_tid, nullptr);
+
+    fatal_errno("exec failed");
+  } else {
+    close(pipefds[1]);
+    char buf[4];
+    ssize_t rc = TEMP_FAILURE_RETRY(read(pipefds[0], &buf, sizeof(buf)));
+    if (rc == -1) {
+      __libc_format_log(ANDROID_LOG_FATAL, "libc", "read of IPC pipe failed: %s", strerror(errno));
+    } else if (rc == 0) {
+      __libc_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper failed to exec");
+    } else if (rc != 1) {
+      __libc_format_log(ANDROID_LOG_FATAL, "libc",
+                        "read of IPC pipe returned unexpected value: %zd", rc);
+    } else {
+      if (buf[0] != '\1') {
+        __libc_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper reported failure");
+      } else {
+        thread_info->crash_dump_started = true;
+      }
+    }
+    close(pipefds[0]);
+
+    // Don't leave a zombie child.
+    int status;
+    if (TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0)) == -1) {
+      __libc_format_log(ANDROID_LOG_FATAL, "libc", "failed to wait for crash_dump helper: %s",
+                        strerror(errno));
+    } else if (WIFSTOPPED(status) || WIFSIGNALED(status)) {
+      __libc_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper crashed or stopped");
+      thread_info->crash_dump_started = false;
+    }
+  }
+
+  syscall(__NR_exit, 0);
+  return 0;
+}
+
+static void resend_signal(siginfo_t* info, bool crash_dump_started) {
+  // Signals can either be fatal or nonfatal.
+  // For fatal signals, crash_dump will send us the signal we crashed with
+  // before resuming us, so that processes using waitpid on us will see that we
+  // exited with the correct exit status (e.g. so that sh will report
+  // "Segmentation fault" instead of "Killed"). For this to work, we need
+  // to deregister our signal handler for that signal before continuing.
+  if (info->si_signo != DEBUGGER_SIGNAL) {
+    signal(info->si_signo, SIG_DFL);
+  }
+
+  // We need to return from our signal handler so that crash_dump can see the
+  // signal via ptrace and dump the thread that crashed. However, returning
+  // does not guarantee that the signal will be thrown again, even for SIGSEGV
+  // and friends, since the signal could have been sent manually. We blocked
+  // all signals when registering the handler, so resending the signal (using
+  // rt_tgsigqueueinfo(2) to preserve SA_SIGINFO) will cause it to be delivered
+  // when our signal handler returns.
+  if (crash_dump_started || info->si_signo != DEBUGGER_SIGNAL) {
+    int rc = syscall(SYS_rt_tgsigqueueinfo, __getpid(), __gettid(), info->si_signo, info);
+    if (rc != 0) {
+      fatal_errno("failed to resend signal during crash");
+    }
+  }
+}
+
+// Handler that does crash dumping by forking and doing the processing in the child.
+// Do this by ptracing the relevant thread, and then execing debuggerd to do the actual dump.
+static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void* context) {
+  // Make sure we don't change the value of errno, in case a signal comes in between the process
+  // making a syscall and checking errno.
+  ErrnoRestorer restorer;
+
+  // It's possible somebody cleared the SA_SIGINFO flag, which would mean
+  // our "info" arg holds an undefined value.
+  if (!have_siginfo(signal_number)) {
+    info = nullptr;
+  }
+
+  struct siginfo si = {};
+  if (!info) {
+    memset(&si, 0, sizeof(si));
+    si.si_signo = signal_number;
+    si.si_code = SI_USER;
+    si.si_pid = __getpid();
+    si.si_uid = getuid();
+    info = &si;
+  } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
+    // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
+    // that contain commit 66dd34a (3.9+). The manpage claims to only allow
+    // negative si_code values that are not SI_TKILL, but 66dd34a changed the
+    // check to allow all si_code values in calls coming from inside the house.
+  }
+
+  void* abort_message = nullptr;
+  if (g_callbacks.get_abort_message) {
+    abort_message = g_callbacks.get_abort_message();
+  }
+
+  if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
+    // This check might be racy if another thread sets NO_NEW_PRIVS, but this should be unlikely,
+    // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
+    // ANR trace.
+    debuggerd_fallback_handler(info, static_cast<ucontext_t*>(context), abort_message);
+    resend_signal(info, false);
+    return;
+  }
+
+  // Only allow one thread to handle a signal at a time.
+  int ret = pthread_mutex_lock(&crash_mutex);
+  if (ret != 0) {
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
+    return;
+  }
+
+  log_signal_summary(signal_number, info);
+
+  // If this was a fatal crash, populate si_value with the abort message address if possible.
+  // Note that applications can set an abort message without aborting.
+  if (abort_message && signal_number != DEBUGGER_SIGNAL) {
+    info->si_value.sival_ptr = abort_message;
+  }
+
+  debugger_thread_info thread_info = {
+    .crash_dump_started = false,
+    .pseudothread_tid = -1,
+    .crashing_tid = __gettid(),
+    .signal_number = signal_number,
+    .info = info
+  };
+
+  // Set PR_SET_DUMPABLE to 1, so that crash_dump can ptrace us.
+  int orig_dumpable = prctl(PR_GET_DUMPABLE);
+  if (prctl(PR_SET_DUMPABLE, 1) != 0) {
+    fatal_errno("failed to set dumpable");
+  }
+
+  // Essentially pthread_create without CLONE_FILES (see debuggerd_dispatch_pseudothread).
+  pid_t child_pid =
+    clone(debuggerd_dispatch_pseudothread, pseudothread_stack,
+          CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID,
+          &thread_info, nullptr, nullptr, &thread_info.pseudothread_tid);
+  if (child_pid == -1) {
+    fatal_errno("failed to spawn debuggerd dispatch thread");
+  }
+
+  // Wait for the child to start...
+  __futex_wait(&thread_info.pseudothread_tid, -1, nullptr);
+
+  // and then wait for it to finish.
+  __futex_wait(&thread_info.pseudothread_tid, child_pid, nullptr);
+
+  // Restore PR_SET_DUMPABLE to its original value.
+  if (prctl(PR_SET_DUMPABLE, orig_dumpable) != 0) {
+    fatal_errno("failed to restore dumpable");
+  }
+
+  // Signals can either be fatal or nonfatal.
+  // For fatal signals, crash_dump will PTRACE_CONT us with the signal we
+  // crashed with, so that processes using waitpid on us will see that we
+  // exited with the correct exit status (e.g. so that sh will report
+  // "Segmentation fault" instead of "Killed"). For this to work, we need
+  // to deregister our signal handler for that signal before continuing.
+  if (signal_number != DEBUGGER_SIGNAL) {
+    signal(signal_number, SIG_DFL);
+  }
+
+  resend_signal(info, thread_info.crash_dump_started);
+  if (info->si_signo == DEBUGGER_SIGNAL) {
+    // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
+    // starting to dump right before our death.
+    pthread_mutex_unlock(&crash_mutex);
+  }
+}
+
+void debuggerd_init(debuggerd_callbacks_t* callbacks) {
+  if (callbacks) {
+    g_callbacks = *callbacks;
+  }
+
+  void* thread_stack_allocation =
+    mmap(nullptr, PAGE_SIZE * 3, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+  if (thread_stack_allocation == MAP_FAILED) {
+    fatal_errno("failed to allocate debuggerd thread stack");
+  }
+
+  char* stack = static_cast<char*>(thread_stack_allocation) + PAGE_SIZE;
+  if (mprotect(stack, PAGE_SIZE, PROT_READ | PROT_WRITE) != 0) {
+    fatal_errno("failed to mprotect debuggerd thread stack");
+  }
+
+  // Stack grows negatively, set it to the last byte in the page...
+  stack = (stack + PAGE_SIZE - 1);
+  // and align it.
+  stack -= 15;
+  pseudothread_stack = stack;
+
+  struct sigaction action;
+  memset(&action, 0, sizeof(action));
+  sigfillset(&action.sa_mask);
+  action.sa_sigaction = debuggerd_signal_handler;
+  action.sa_flags = SA_RESTART | SA_SIGINFO;
+
+  // Use the alternate signal stack if available so we can catch stack overflows.
+  action.sa_flags |= SA_ONSTACK;
+  debuggerd_register_handlers(&action);
+}
diff --git a/debuggerd/include/debuggerd/client.h b/debuggerd/include/debuggerd/client.h
new file mode 100644
index 0000000..01de57b
--- /dev/null
+++ b/debuggerd/include/debuggerd/client.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright 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.
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <sys/cdefs.h>
+#include <unistd.h>
+
+#include <android-base/unique_fd.h>
+
+enum DebuggerdDumpType {
+  kDebuggerdBacktrace,
+  kDebuggerdTombstone,
+};
+
+// Trigger a dump of specified process to output_fd.
+// 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, 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/handler.h b/debuggerd/include/debuggerd/handler.h
new file mode 100644
index 0000000..7196e0a
--- /dev/null
+++ b/debuggerd/include/debuggerd/handler.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright 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.
+ */
+
+#pragma once
+
+#include <signal.h>
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+__BEGIN_DECLS
+
+// These callbacks are called in a signal handler, and thus must be async signal safe.
+// If null, the callbacks will not be called.
+typedef struct {
+  struct abort_msg_t* (*get_abort_message)();
+  void (*post_dump)();
+} debuggerd_callbacks_t;
+
+void debuggerd_init(debuggerd_callbacks_t* callbacks);
+
+// DEBUGGER_ACTION_DUMP_TOMBSTONE and DEBUGGER_ACTION_DUMP_BACKTRACE are both
+// triggered via DEBUGGER_SIGNAL. The debugger_action_t is sent via si_value
+// using sigqueue(2) or equivalent. If no si_value is specified (e.g. if the
+// signal is sent by kill(2)), the default behavior is to print the backtrace
+// to the log.
+#define DEBUGGER_SIGNAL (__SIGRTMIN + 3)
+
+static void __attribute__((__unused__)) debuggerd_register_handlers(struct sigaction* action) {
+  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);
+  sigaction(DEBUGGER_SIGNAL, action, nullptr);
+}
+
+__END_DECLS
diff --git a/debuggerd/include/debuggerd/protocol.h b/debuggerd/include/debuggerd/protocol.h
new file mode 100644
index 0000000..0756876
--- /dev/null
+++ b/debuggerd/include/debuggerd/protocol.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright 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.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+// Sockets in the ANDROID_SOCKET_NAMESPACE_RESERVED namespace.
+// Both sockets are SOCK_SEQPACKET sockets, so no explicit length field is needed.
+constexpr char kTombstonedCrashSocketName[] = "tombstoned_crash";
+constexpr char kTombstonedInterceptSocketName[] = "tombstoned_intercept";
+
+enum class CrashPacketType : uint8_t {
+  // Initial request from crash_dump.
+  kDumpRequest = 0,
+
+  // Notification of a completed crash dump.
+  // Sent after a dump is completed and the process has been untraced, but
+  // before it has been resumed with SIGCONT.
+  kCompletedDump,
+
+  // Responses to kRequest.
+  // kPerformDump sends along an output fd via cmsg(3).
+  kPerformDump = 128,
+  kAbortDump,
+};
+
+struct DumpRequest {
+  int32_t pid;
+};
+
+// The full packet must always be written, regardless of whether the union is used.
+struct TombstonedCrashPacket {
+  CrashPacketType packet_type;
+  union {
+    DumpRequest dump_request;
+  } packet;
+};
+
+// Comes with a file descriptor via SCM_RIGHTS.
+// This packet should be sent before an actual dump happens.
+struct InterceptRequest {
+  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 {
+  InterceptStatus status;
+  char error_message[127];  // always null-terminated
+};
diff --git a/debuggerd/include/debuggerd/tombstoned.h b/debuggerd/include/debuggerd/tombstoned.h
new file mode 100644
index 0000000..d158d50
--- /dev/null
+++ b/debuggerd/include/debuggerd/tombstoned.h
@@ -0,0 +1,26 @@
+#pragma once
+
+/*
+ * 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 <sys/types.h>
+
+#include <android-base/unique_fd.h>
+
+bool tombstoned_connect(pid_t pid, android::base::unique_fd* tombstoned_socket,
+                        android::base::unique_fd* output_fd);
+
+bool tombstoned_notify_completion(int tombstoned_socket);
diff --git a/debuggerd/include/debuggerd/util.h b/debuggerd/include/debuggerd/util.h
new file mode 100644
index 0000000..6051714
--- /dev/null
+++ b/debuggerd/include/debuggerd/util.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 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.
+ */
+
+#pragma once
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <android-base/unique_fd.h>
+
+// *** WARNING ***
+// tombstoned's sockets are SOCK_SEQPACKET sockets.
+// Short reads are treated as errors and short writes are assumed to not happen.
+
+// Sends a packet with an attached fd.
+ssize_t send_fd(int sockfd, const void* _Nonnull data, size_t len, android::base::unique_fd fd);
+
+// Receives a packet and optionally, its attached fd.
+// If out_fd is non-null, packets can optionally have an attached fd.
+// If out_fd is null, received packets must not have an attached fd.
+//
+// Errors:
+//   EOVERFLOW: sockfd is SOCK_DGRAM or SOCK_SEQPACKET and buffer is too small.
+//              The first len bytes of the packet are stored in data, but the
+//              rest of the packet is dropped.
+//   ERANGE:    too many file descriptors were attached to the packet.
+//   ENOMSG:    not enough file descriptors were attached to the packet.
+//
+//   plus any errors returned by the underlying recvmsg.
+ssize_t recv_fd(int sockfd, void* _Nonnull data, size_t len,
+                android::base::unique_fd* _Nullable out_fd);
+
+bool Pipe(android::base::unique_fd* read, android::base::unique_fd* write);
diff --git a/debuggerd/libdebuggerd/arm/machine.cpp b/debuggerd/libdebuggerd/arm/machine.cpp
new file mode 100644
index 0000000..ac833ae
--- /dev/null
+++ b/debuggerd/libdebuggerd/arm/machine.cpp
@@ -0,0 +1,90 @@
+/*
+ *
+ * Copyright 2006, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <errno.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/ptrace.h>
+
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+#include "machine.h"
+#include "utility.h"
+
+void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
+  pt_regs regs;
+  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &regs)) {
+    ALOGE("cannot get registers: %s\n", strerror(errno));
+    return;
+  }
+
+  static const char reg_names[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";
+
+  for (int reg = 0; reg < 14; reg++) {
+    dump_memory(log, backtrace, regs.uregs[reg], "memory near %.2s:", &reg_names[reg * 2]);
+  }
+
+  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_pc), "code around pc:");
+
+  if (regs.ARM_pc != regs.ARM_lr) {
+    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_lr), "code around lr:");
+  }
+}
+
+#define DUMP_GP_REGISTERS(log, reg_prefix)                                             \
+  _LOG(log, logtype::REGISTERS, "    r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",            \
+       static_cast<uint32_t>(reg_prefix##r0), static_cast<uint32_t>(reg_prefix##r1),   \
+       static_cast<uint32_t>(reg_prefix##r2), static_cast<uint32_t>(reg_prefix##r3));  \
+  _LOG(log, logtype::REGISTERS, "    r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",            \
+       static_cast<uint32_t>(reg_prefix##r4), static_cast<uint32_t>(reg_prefix##r5),   \
+       static_cast<uint32_t>(reg_prefix##r6), static_cast<uint32_t>(reg_prefix##r7));  \
+  _LOG(log, logtype::REGISTERS, "    r8 %08x  r9 %08x  sl %08x  fp %08x\n",            \
+       static_cast<uint32_t>(reg_prefix##r8), static_cast<uint32_t>(reg_prefix##r9),   \
+       static_cast<uint32_t>(reg_prefix##r10), static_cast<uint32_t>(reg_prefix##fp)); \
+  _LOG(log, logtype::REGISTERS, "    ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n", \
+       static_cast<uint32_t>(reg_prefix##ip), static_cast<uint32_t>(reg_prefix##sp),   \
+       static_cast<uint32_t>(reg_prefix##lr), static_cast<uint32_t>(reg_prefix##pc),   \
+       static_cast<uint32_t>(reg_prefix##cpsr))
+
+void dump_registers(log_t* log, pid_t tid) {
+  pt_regs r;
+  if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
+    ALOGE("cannot get registers: %s\n", strerror(errno));
+    return;
+  }
+
+  DUMP_GP_REGISTERS(log, r.ARM_);
+
+  user_vfp vfp_regs;
+  if (ptrace(PTRACE_GETVFPREGS, tid, 0, &vfp_regs)) {
+    ALOGE("cannot get FP registers: %s\n", strerror(errno));
+    return;
+  }
+
+  for (size_t i = 0; i < 32; i += 2) {
+    _LOG(log, logtype::FP_REGISTERS, "    d%-2d %016llx  d%-2d %016llx\n",
+         i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
+  }
+  _LOG(log, logtype::FP_REGISTERS, "    scr %08lx\n", vfp_regs.fpscr);
+}
+
+void dump_registers(log_t* log, const ucontext_t* uc) {
+  DUMP_GP_REGISTERS(log, uc->uc_mcontext.arm_);
+}
diff --git a/debuggerd/libdebuggerd/arm64/machine.cpp b/debuggerd/libdebuggerd/arm64/machine.cpp
new file mode 100644
index 0000000..fa73c99
--- /dev/null
+++ b/debuggerd/libdebuggerd/arm64/machine.cpp
@@ -0,0 +1,104 @@
+/*
+ *
+ * Copyright 2014, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <elf.h>
+#include <errno.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/uio.h>
+
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+#include "machine.h"
+#include "utility.h"
+
+void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
+  struct user_pt_regs regs;
+  struct iovec io;
+  io.iov_base = &regs;
+  io.iov_len = sizeof(regs);
+
+  if (ptrace(PTRACE_GETREGSET, backtrace->Tid(), reinterpret_cast<void*>(NT_PRSTATUS), &io) == -1) {
+    ALOGE("ptrace failed to get registers: %s", strerror(errno));
+    return;
+  }
+
+  for (int reg = 0; reg < 31; reg++) {
+    dump_memory(log, backtrace, regs.regs[reg], "memory near x%d:", reg);
+  }
+
+  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.pc), "code around pc:");
+
+  if (regs.pc != regs.sp) {
+    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.sp), "code around sp:");
+  }
+}
+
+#define DUMP_GP_REGISTERS(log)                                                                   \
+  for (int i = 0; i < 28; i += 4) {                                                              \
+    const char* fmt = "    x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx\n";    \
+    _LOG(log, logtype::REGISTERS, fmt, i, r.regs[i], i + 1, r.regs[i + 1], i + 2, r.regs[i + 2], \
+         i + 3, r.regs[i + 3]);                                                                  \
+  }                                                                                              \
+  _LOG(log, logtype::REGISTERS, "    x28  %016llx  x29  %016llx  x30  %016llx\n", r.regs[28],    \
+       r.regs[29], r.regs[30]);                                                                  \
+  _LOG(log, logtype::REGISTERS, "    sp   %016llx  pc   %016llx  pstate %016llx\n", r.sp, r.pc,  \
+       r.pstate)
+
+void dump_registers(log_t* log, pid_t tid) {
+  struct user_pt_regs r;
+  struct iovec io;
+  io.iov_base = &r;
+  io.iov_len = sizeof(r);
+
+  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRSTATUS, (void*) &io) == -1) {
+    ALOGE("ptrace error: %s\n", strerror(errno));
+    return;
+  }
+
+  DUMP_GP_REGISTERS(log);
+
+  struct user_fpsimd_state f;
+  io.iov_base = &f;
+  io.iov_len = sizeof(f);
+
+  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRFPREG, (void*) &io) == -1) {
+    ALOGE("ptrace error: %s\n", strerror(errno));
+    return;
+  }
+
+  for (int i = 0; i < 32; i += 2) {
+    _LOG(log, logtype::FP_REGISTERS,
+         "    v%-2d  %016" PRIx64 "%016" PRIx64 "  v%-2d  %016" PRIx64 "%016" PRIx64 "\n",
+         i,
+         static_cast<uint64_t>(f.vregs[i] >> 64),
+         static_cast<uint64_t>(f.vregs[i]),
+         i+1,
+         static_cast<uint64_t>(f.vregs[i+1] >> 64),
+         static_cast<uint64_t>(f.vregs[i+1]));
+  }
+  _LOG(log, logtype::FP_REGISTERS, "    fpsr %08x  fpcr %08x\n", f.fpsr, f.fpcr);
+}
+
+void dump_registers(log_t* log, const ucontext_t* ucontext) {
+  const mcontext_t& r = ucontext->uc_mcontext;
+  DUMP_GP_REGISTERS(log);
+}
diff --git a/debuggerd/libdebuggerd/backtrace.cpp b/debuggerd/libdebuggerd/backtrace.cpp
new file mode 100644
index 0000000..334d97f
--- /dev/null
+++ b/debuggerd/libdebuggerd/backtrace.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <errno.h>
+#include <dirent.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <memory>
+#include <string>
+
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+#include "backtrace.h"
+
+#include "utility.h"
+
+static void dump_process_header(log_t* log, pid_t pid, const char* process_name) {
+  time_t t = time(NULL);
+  struct tm tm;
+  localtime_r(&t, &tm);
+  char timestr[64];
+  strftime(timestr, sizeof(timestr), "%F %T", &tm);
+  _LOG(log, logtype::BACKTRACE, "\n\n----- pid %d at %s -----\n", pid, timestr);
+
+  if (process_name) {
+    _LOG(log, logtype::BACKTRACE, "Cmd line: %s\n", process_name);
+  }
+  _LOG(log, logtype::BACKTRACE, "ABI: '%s'\n", ABI_STRING);
+}
+
+static void dump_process_footer(log_t* log, pid_t pid) {
+  _LOG(log, logtype::BACKTRACE, "\n----- end %d -----\n", pid);
+}
+
+static void log_thread_name(log_t* log, pid_t tid, const char* thread_name) {
+  _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", thread_name, tid);
+}
+
+static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid,
+                        const std::string& thread_name) {
+  log_thread_name(log, tid, thread_name.c_str());
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
+  if (backtrace->Unwind(0)) {
+    dump_backtrace_to_log(backtrace.get(), log, "  ");
+  } else {
+    ALOGE("Unwind failed: tid = %d: %s", tid,
+          backtrace->GetErrorString(backtrace->GetError()).c_str());
+  }
+}
+
+void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
+                    const std::map<pid_t, std::string>& threads, std::string* amfd_data) {
+  log_t log;
+  log.tfd = fd;
+  log.amfd_data = amfd_data;
+
+  dump_process_header(&log, pid, process_name.c_str());
+  dump_thread(&log, map, pid, tid, threads.find(tid)->second.c_str());
+
+  for (const auto& it : threads) {
+    pid_t thread_tid = it.first;
+    const std::string& thread_name = it.second;
+    if (thread_tid != tid) {
+      dump_thread(&log, map, pid, thread_tid, thread_name.c_str());
+    }
+  }
+
+  dump_process_footer(&log, pid);
+}
+
+void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext) {
+  pid_t pid = getpid();
+  pid_t tid = gettid();
+
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  char thread_name[16];
+  read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
+  log_thread_name(&log, tid, thread_name);
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
+  if (backtrace->Unwind(0, ucontext)) {
+    dump_backtrace_to_log(backtrace.get(), &log, "  ");
+  } else {
+    ALOGE("Unwind failed: tid = %d: %s", tid,
+          backtrace->GetErrorString(backtrace->GetError()).c_str());
+  }
+}
+
+void dump_backtrace_header(int output_fd) {
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  char process_name[128];
+  read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
+  dump_process_header(&log, getpid(), process_name);
+}
+
+void dump_backtrace_footer(int output_fd) {
+  log_t log;
+  log.tfd = output_fd;
+  log.amfd_data = nullptr;
+
+  dump_process_footer(&log, getpid());
+}
+
+void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix) {
+  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
+    _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, backtrace->FormatFrameData(i).c_str());
+  }
+}
diff --git a/debuggerd/libdebuggerd/elf_utils.cpp b/debuggerd/libdebuggerd/elf_utils.cpp
new file mode 100644
index 0000000..4e798e2
--- /dev/null
+++ b/debuggerd/libdebuggerd/elf_utils.cpp
@@ -0,0 +1,121 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <elf.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+#include "elf_utils.h"
+
+#define NOTE_ALIGN(size)  (((size) + 3) & ~3)
+
+template <typename HdrType, typename PhdrType, typename NhdrType>
+static bool get_build_id(
+    Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) {
+  HdrType hdr;
+
+  memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT);
+
+  // First read the rest of the header.
+  if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT,
+                      sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) {
+    return false;
+  }
+
+  for (size_t i = 0; i < hdr.e_phnum; i++) {
+    PhdrType phdr;
+    if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize,
+                        reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) {
+      return false;
+    }
+    // Looking for the .note.gnu.build-id note.
+    if (phdr.p_type == PT_NOTE) {
+      size_t hdr_size = phdr.p_filesz;
+      uintptr_t addr = base_addr + phdr.p_offset;
+      while (hdr_size >= sizeof(NhdrType)) {
+        NhdrType nhdr;
+        if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) {
+          return false;
+        }
+        addr += sizeof(nhdr);
+        if (nhdr.n_type == NT_GNU_BUILD_ID) {
+          // Skip the name (which is the owner and should be "GNU").
+          addr += NOTE_ALIGN(nhdr.n_namesz);
+          uint8_t build_id_data[160];
+          if (nhdr.n_descsz > sizeof(build_id_data)) {
+            ALOGE("Possible corrupted note, desc size value is too large: %u",
+                  nhdr.n_descsz);
+            return false;
+          }
+          if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) {
+            return false;
+          }
+
+          build_id->clear();
+          for (size_t bytes = 0; bytes < nhdr.n_descsz; bytes++) {
+            *build_id += android::base::StringPrintf("%02x", build_id_data[bytes]);
+          }
+
+          return true;
+        } else {
+          // Move past the extra note data.
+          hdr_size -= sizeof(nhdr);
+          size_t skip_bytes = NOTE_ALIGN(nhdr.n_namesz) + NOTE_ALIGN(nhdr.n_descsz);
+          addr += skip_bytes;
+          if (hdr_size < skip_bytes) {
+            break;
+          }
+          hdr_size -= skip_bytes;
+        }
+      }
+    }
+  }
+  return false;
+}
+
+bool elf_get_build_id(Backtrace* backtrace, uintptr_t addr, std::string* build_id) {
+  // Read and verify the elf magic number first.
+  uint8_t e_ident[EI_NIDENT];
+  if (backtrace->Read(addr, e_ident, SELFMAG) != SELFMAG) {
+    return false;
+  }
+
+  if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
+    return false;
+  }
+
+  // Read the rest of EI_NIDENT.
+  if (backtrace->Read(addr + SELFMAG, e_ident + SELFMAG, EI_NIDENT - SELFMAG) != EI_NIDENT - SELFMAG) {
+    return false;
+  }
+
+  if (e_ident[EI_CLASS] == ELFCLASS32) {
+    return get_build_id<Elf32_Ehdr, Elf32_Phdr, Elf32_Nhdr>(backtrace, addr, e_ident, build_id);
+  } else if (e_ident[EI_CLASS] == ELFCLASS64) {
+    return get_build_id<Elf64_Ehdr, Elf64_Phdr, Elf64_Nhdr>(backtrace, addr, e_ident, build_id);
+  }
+
+  return false;
+}
diff --git a/debuggerd/libdebuggerd/include/backtrace.h b/debuggerd/libdebuggerd/include/backtrace.h
new file mode 100644
index 0000000..fe738f1
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/backtrace.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _DEBUGGERD_BACKTRACE_H
+#define _DEBUGGERD_BACKTRACE_H
+
+#include <sys/types.h>
+#include <sys/ucontext.h>
+
+#include <map>
+#include <string>
+
+#include "utility.h"
+
+class Backtrace;
+class BacktraceMap;
+
+// Dumps a backtrace using a format similar to what Dalvik uses so that the result
+// can be intermixed in a bug report.
+void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
+                    const std::map<pid_t, std::string>& threads, std::string* amfd_data);
+
+/* Dumps the backtrace in the backtrace data structure to the log. */
+void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix);
+
+void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext);
+void dump_backtrace_header(int output_fd);
+void dump_backtrace_footer(int output_fd);
+
+#endif // _DEBUGGERD_BACKTRACE_H
diff --git a/debuggerd/elf_utils.h b/debuggerd/libdebuggerd/include/elf_utils.h
similarity index 100%
rename from debuggerd/elf_utils.h
rename to debuggerd/libdebuggerd/include/elf_utils.h
diff --git a/debuggerd/libdebuggerd/include/machine.h b/debuggerd/libdebuggerd/include/machine.h
new file mode 100644
index 0000000..5e56682
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/machine.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _DEBUGGERD_MACHINE_H
+#define _DEBUGGERD_MACHINE_H
+
+#include <sys/types.h>
+
+#include <backtrace/Backtrace.h>
+
+#include "utility.h"
+
+void dump_memory_and_code(log_t* log, Backtrace* backtrace);
+void dump_registers(log_t* log, pid_t tid);
+void dump_registers(log_t* log, const ucontext_t* uc);
+
+#endif // _DEBUGGERD_MACHINE_H
diff --git a/debuggerd/libdebuggerd/include/open_files_list.h b/debuggerd/libdebuggerd/include/open_files_list.h
new file mode 100644
index 0000000..b37228d
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/open_files_list.h
@@ -0,0 +1,36 @@
+/*
+ * 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 _DEBUGGERD_OPEN_FILES_LIST_H
+#define _DEBUGGERD_OPEN_FILES_LIST_H
+
+#include <sys/types.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "utility.h"
+
+typedef std::vector<std::pair<int, std::string>> OpenFilesList;
+
+/* Populates the given list with open files for the given process. */
+void populate_open_files_list(pid_t pid, OpenFilesList* list);
+
+/* Dumps the open files list to the log. */
+void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix);
+
+#endif // _DEBUGGERD_OPEN_FILES_LIST_H
diff --git a/debuggerd/libdebuggerd/include/tombstone.h b/debuggerd/libdebuggerd/include/tombstone.h
new file mode 100644
index 0000000..79743b6
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/tombstone.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _DEBUGGERD_TOMBSTONE_H
+#define _DEBUGGERD_TOMBSTONE_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <sys/types.h>
+
+#include <map>
+#include <string>
+
+#include "open_files_list.h"
+
+class BacktraceMap;
+
+/* Create and open a tombstone file for writing.
+ * Returns a writable file descriptor, or -1 with errno set appropriately.
+ * If out_path is non-null, *out_path is set to the path of the tombstone file.
+ */
+int open_tombstone(std::string* path);
+
+/* Creates a tombstone file and writes the crash dump to it. */
+void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
+                       pid_t pid, pid_t tid, const std::string& process_name,
+                       const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
+                       std::string* amfd_data);
+
+void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+                                ucontext_t* ucontext);
+
+// Compatibility shim.
+__attribute__((__unused__))
+static void engrave_tombstone_ucontext(int tombstone_fd, pid_t, pid_t, uintptr_t abort_msg_address,
+                                       siginfo_t* siginfo, ucontext_t* ucontext) {
+  engrave_tombstone_ucontext(tombstone_fd, abort_msg_address, siginfo, ucontext);
+}
+
+#endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/include/utility.h b/debuggerd/libdebuggerd/include/utility.h
new file mode 100644
index 0000000..e5e5106
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/utility.h
@@ -0,0 +1,88 @@
+/* system/debuggerd/utility.h
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef _DEBUGGERD_UTILITY_H
+#define _DEBUGGERD_UTILITY_H
+
+#include <signal.h>
+#include <stdbool.h>
+#include <sys/types.h>
+
+#include <string>
+
+#include <backtrace/Backtrace.h>
+
+// Figure out the abi based on defined macros.
+#if defined(__arm__)
+#define ABI_STRING "arm"
+#elif defined(__aarch64__)
+#define ABI_STRING "arm64"
+#elif defined(__mips__) && !defined(__LP64__)
+#define ABI_STRING "mips"
+#elif defined(__mips__) && defined(__LP64__)
+#define ABI_STRING "mips64"
+#elif defined(__i386__)
+#define ABI_STRING "x86"
+#elif defined(__x86_64__)
+#define ABI_STRING "x86_64"
+#else
+#error "Unsupported ABI"
+#endif
+
+
+struct log_t{
+    // Tombstone file descriptor.
+    int tfd;
+    // Data to be sent to the Activity Manager.
+    std::string* amfd_data;
+    // The tid of the thread that crashed.
+    pid_t crashed_tid;
+    // The tid of the thread we are currently working with.
+    pid_t current_tid;
+    // logd daemon crash, can block asking for logcat data, allow suppression.
+    bool should_retrieve_logcat;
+
+    log_t()
+        : tfd(-1), amfd_data(nullptr), crashed_tid(-1), current_tid(-1),
+          should_retrieve_logcat(true) {}
+};
+
+// List of types of logs to simplify the logging decision in _LOG
+enum logtype {
+  HEADER,
+  THREAD,
+  REGISTERS,
+  FP_REGISTERS,
+  BACKTRACE,
+  MAPS,
+  MEMORY,
+  STACK,
+  LOGS,
+  OPEN_FILES
+};
+
+// Log information onto the tombstone.
+void _LOG(log_t* log, logtype ltype, const char *fmt, ...)
+        __attribute__ ((format(printf, 3, 4)));
+
+bool wait_for_signal(pid_t tid, siginfo_t* siginfo);
+
+void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...);
+
+void read_with_default(const char* path, char* buf, size_t len, const char* default_value);
+
+#endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/mips/machine.cpp b/debuggerd/libdebuggerd/mips/machine.cpp
similarity index 100%
rename from debuggerd/mips/machine.cpp
rename to debuggerd/libdebuggerd/mips/machine.cpp
diff --git a/debuggerd/mips64/machine.cpp b/debuggerd/libdebuggerd/mips64/machine.cpp
similarity index 100%
rename from debuggerd/mips64/machine.cpp
rename to debuggerd/libdebuggerd/mips64/machine.cpp
diff --git a/debuggerd/libdebuggerd/open_files_list.cpp b/debuggerd/libdebuggerd/open_files_list.cpp
new file mode 100644
index 0000000..5c7ea70
--- /dev/null
+++ b/debuggerd/libdebuggerd/open_files_list.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <dirent.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <android-base/file.h>
+#include <log/log.h>
+
+#include "open_files_list.h"
+
+#include "utility.h"
+
+void populate_open_files_list(pid_t pid, OpenFilesList* list) {
+  std::string fd_dir_name = "/proc/" + std::to_string(pid) + "/fd";
+  std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(fd_dir_name.c_str()), closedir);
+  if (dir == nullptr) {
+    ALOGE("failed to open directory %s: %s", fd_dir_name.c_str(), strerror(errno));
+    return;
+  }
+
+  struct dirent* de;
+  while ((de = readdir(dir.get())) != nullptr) {
+    if (*de->d_name == '.') {
+      continue;
+    }
+
+    int fd = atoi(de->d_name);
+    std::string path = fd_dir_name + "/" + std::string(de->d_name);
+    std::string target;
+    if (android::base::Readlink(path, &target)) {
+      list->emplace_back(fd, target);
+    } else {
+      ALOGE("failed to readlink %s: %s", path.c_str(), strerror(errno));
+      list->emplace_back(fd, "???");
+    }
+  }
+}
+
+void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix) {
+  for (auto& file : files) {
+    _LOG(log, logtype::OPEN_FILES, "%sfd %i: %s\n", prefix, file.first, file.second.c_str());
+  }
+}
+
diff --git a/debuggerd/libdebuggerd/test/BacktraceMock.h b/debuggerd/libdebuggerd/test/BacktraceMock.h
new file mode 100644
index 0000000..6104f7e
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/BacktraceMock.h
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+#ifndef _DEBUGGERD_TEST_BACKTRACE_MOCK_H
+#define _DEBUGGERD_TEST_BACKTRACE_MOCK_H
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ucontext.h>
+
+#include <string>
+#include <vector>
+
+#include <backtrace/Backtrace.h>
+#include <backtrace/BacktraceMap.h>
+
+class BacktraceMapMock : public BacktraceMap {
+ public:
+  BacktraceMapMock() : BacktraceMap(0) {}
+  virtual ~BacktraceMapMock() {}
+
+  void AddMap(backtrace_map_t& map) {
+    maps_.push_back(map);
+  }
+};
+
+
+class BacktraceMock : public Backtrace {
+ public:
+  explicit BacktraceMock(BacktraceMapMock* map) : Backtrace(0, 0, map) {
+    if (map_ == nullptr) {
+      abort();
+    }
+  }
+  virtual ~BacktraceMock() {}
+
+  virtual bool Unwind(size_t, ucontext_t*) { return false; }
+  virtual bool ReadWord(uintptr_t, word_t*) { return false;}
+
+  virtual std::string GetFunctionNameRaw(uintptr_t, uintptr_t*) { return ""; }
+
+  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
+    size_t offset = 0;
+    if (last_read_addr_ > 0) {
+      offset = addr - last_read_addr_;
+    }
+    size_t bytes_available = buffer_.size() - offset;
+
+    if (do_partial_read_) {
+      // Do a partial read.
+      if (bytes > bytes_partial_read_) {
+        bytes = bytes_partial_read_;
+      }
+      bytes_partial_read_ -= bytes;
+      // Only support a single partial read.
+      do_partial_read_ = false;
+    } else if (bytes > bytes_available) {
+      bytes = bytes_available;
+    }
+
+    if (bytes > 0) {
+      memcpy(buffer, buffer_.data() + offset, bytes);
+    }
+
+    last_read_addr_ = addr;
+    return bytes;
+  }
+
+  void SetReadData(uint8_t* buffer, size_t bytes) {
+    buffer_.resize(bytes);
+    memcpy(buffer_.data(), buffer, bytes);
+    bytes_partial_read_ = 0;
+    do_partial_read_ = false;
+    last_read_addr_ = 0;
+  }
+
+  void SetPartialReadAmount(size_t bytes) {
+    if (bytes > buffer_.size()) {
+      abort();
+    }
+    bytes_partial_read_ = bytes;
+    do_partial_read_ = true;
+  }
+
+ private:
+  std::vector<uint8_t> buffer_;
+  size_t bytes_partial_read_ = 0;
+  uintptr_t last_read_addr_ = 0;
+  bool do_partial_read_ = false;
+};
+
+#endif //  _DEBUGGERD_TEST_BACKTRACE_MOCK_H
diff --git a/debuggerd/test/dump_memory_test.cpp b/debuggerd/libdebuggerd/test/dump_memory_test.cpp
similarity index 100%
rename from debuggerd/test/dump_memory_test.cpp
rename to debuggerd/libdebuggerd/test/dump_memory_test.cpp
diff --git a/debuggerd/test/elf_fake.cpp b/debuggerd/libdebuggerd/test/elf_fake.cpp
similarity index 100%
rename from debuggerd/test/elf_fake.cpp
rename to debuggerd/libdebuggerd/test/elf_fake.cpp
diff --git a/debuggerd/test/elf_fake.h b/debuggerd/libdebuggerd/test/elf_fake.h
similarity index 100%
rename from debuggerd/test/elf_fake.h
rename to debuggerd/libdebuggerd/test/elf_fake.h
diff --git a/debuggerd/libdebuggerd/test/host_signal_fixup.h b/debuggerd/libdebuggerd/test/host_signal_fixup.h
new file mode 100644
index 0000000..762bae5
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/host_signal_fixup.h
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+#ifndef _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
+#define _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
+
+#include <signal.h>
+
+#if !defined(__BIONIC__)
+
+// In order to compile parts of debuggerd for the host, we need to
+// define these values.
+
+#if !defined(NSIGILL)
+#define NSIGILL ILL_BADSTK
+#endif
+
+#if !defined(BUS_MCEERR_AR)
+#define BUS_MCEERR_AR 4
+#endif
+#if !defined(BUS_MCEERR_AO)
+#define BUS_MCEERR_AO 5
+#endif
+#if !defined(NSIGBUS)
+#define NSIGBUS BUS_MCEERR_AO
+#endif
+
+#if !defined(NSIGFPE)
+#define NSIGFPE FPE_FLTSUB
+#endif
+
+#if !defined(NSIGSEGV)
+#define NSIGSEGV SEGV_ACCERR
+#endif
+
+#if !defined(TRAP_BRANCH)
+#define TRAP_BRANCH 3
+#endif
+#if !defined(TRAP_HWBKPT)
+#define TRAP_HWBKPT 4
+#endif
+#if !defined(NSIGTRAP)
+#define NSIGTRAP TRAP_HWBKPT
+#endif
+
+#if !defined(SI_DETHREAD)
+#define SI_DETHREAD (-7)
+#endif
+
+#endif
+
+#endif // _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
diff --git a/debuggerd/libdebuggerd/test/log_fake.cpp b/debuggerd/libdebuggerd/test/log_fake.cpp
new file mode 100644
index 0000000..3336bcb
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/log_fake.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <stdarg.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <log/log.h>
+
+// Forward declarations.
+class Backtrace;
+struct EventTagMap;
+struct AndroidLogEntry;
+
+std::string g_fake_log_buf;
+
+std::string g_fake_log_print;
+
+void resetLogs() {
+  g_fake_log_buf = "";
+  g_fake_log_print = "";
+}
+
+std::string getFakeLogBuf() {
+  return g_fake_log_buf;
+}
+
+std::string getFakeLogPrint() {
+  return g_fake_log_print;
+}
+
+extern "C" int __android_log_buf_write(int bufId, int prio, const char* tag, const char* msg) {
+  g_fake_log_buf += std::to_string(bufId) + ' ' + std::to_string(prio) + ' ';
+  g_fake_log_buf += tag;
+  g_fake_log_buf += ' ';
+  g_fake_log_buf += msg;
+  return 1;
+}
+
+extern "C" int __android_log_print(int prio, const char* tag, const char* fmt, ...) {
+  g_fake_log_print += std::to_string(prio) + ' ';
+  g_fake_log_print += tag;
+  g_fake_log_print += ' ';
+
+  va_list ap;
+  va_start(ap, fmt);
+  android::base::StringAppendV(&g_fake_log_print, fmt, ap);
+  va_end(ap);
+
+  g_fake_log_print += '\n';
+
+  return 1;
+}
+
+extern "C" log_id_t android_name_to_log_id(const char*) {
+  return LOG_ID_SYSTEM;
+}
+
+extern "C" struct logger_list* android_logger_list_open(log_id_t, int, unsigned int, pid_t) {
+  errno = EACCES;
+  return nullptr;
+}
+
+extern "C" int android_logger_list_read(struct logger_list*, struct log_msg*) {
+  return 0;
+}
+
+extern "C" EventTagMap* android_openEventTagMap(const char*) {
+  return nullptr;
+}
+
+extern "C" int android_log_processBinaryLogBuffer(
+    struct logger_entry*,
+    AndroidLogEntry*, const EventTagMap*, char*, int) {
+  return 0;
+}
+
+extern "C" void android_logger_list_free(struct logger_list*) {
+}
diff --git a/debuggerd/test/log_fake.h b/debuggerd/libdebuggerd/test/log_fake.h
similarity index 100%
rename from debuggerd/test/log_fake.h
rename to debuggerd/libdebuggerd/test/log_fake.h
diff --git a/debuggerd/libdebuggerd/test/open_files_list_test.cpp b/debuggerd/libdebuggerd/test/open_files_list_test.cpp
new file mode 100644
index 0000000..85e0695
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/open_files_list_test.cpp
@@ -0,0 +1,49 @@
+/*
+ * 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 <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <gtest/gtest.h>
+
+#include "android-base/test_utils.h"
+
+#include "open_files_list.h"
+
+// Check that we can produce a list of open files for the current process, and
+// that it includes a known open file.
+TEST(OpenFilesListTest, BasicTest) {
+  // Open a temporary file that we can check for in the list of open files.
+  TemporaryFile tf;
+
+  // Get the list of open files for this process.
+  OpenFilesList list;
+  populate_open_files_list(getpid(), &list);
+
+  // Verify our open file is in the list.
+  bool found = false;
+  for (auto&  file : list) {
+    if (file.first == tf.fd) {
+      EXPECT_EQ(file.second, std::string(tf.path));
+      found = true;
+      break;
+    }
+  }
+  EXPECT_TRUE(found);
+}
diff --git a/debuggerd/test/property_fake.cpp b/debuggerd/libdebuggerd/test/property_fake.cpp
similarity index 100%
rename from debuggerd/test/property_fake.cpp
rename to debuggerd/libdebuggerd/test/property_fake.cpp
diff --git a/debuggerd/test/ptrace_fake.cpp b/debuggerd/libdebuggerd/test/ptrace_fake.cpp
similarity index 100%
rename from debuggerd/test/ptrace_fake.cpp
rename to debuggerd/libdebuggerd/test/ptrace_fake.cpp
diff --git a/debuggerd/test/ptrace_fake.h b/debuggerd/libdebuggerd/test/ptrace_fake.h
similarity index 100%
rename from debuggerd/test/ptrace_fake.h
rename to debuggerd/libdebuggerd/test/ptrace_fake.h
diff --git a/debuggerd/libdebuggerd/test/sys/system_properties.h b/debuggerd/libdebuggerd/test/sys/system_properties.h
new file mode 100644
index 0000000..1f4f58a
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/sys/system_properties.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
+#define _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
+
+// This is just enough to get the property code to compile on
+// the host.
+
+#define PROP_VALUE_MAX  92
+
+#endif // _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
new file mode 100644
index 0000000..325210d
--- /dev/null
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -0,0 +1,645 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+
+#include <memory>
+#include <string>
+
+#include <gtest/gtest.h>
+#include <android-base/file.h>
+
+#include "utility.h"
+
+#include "BacktraceMock.h"
+#include "elf_fake.h"
+#include "host_signal_fixup.h"
+#include "log_fake.h"
+#include "ptrace_fake.h"
+
+// In order to test this code, we need to include the tombstone.cpp code.
+// Including it, also allows us to override the ptrace function.
+#define ptrace ptrace_fake
+
+#include "tombstone.cpp"
+
+void dump_registers(log_t*, pid_t) {
+}
+
+void dump_memory_and_code(log_t*, Backtrace*) {
+}
+
+void dump_backtrace_to_log(Backtrace*, log_t*, char const*) {
+}
+
+class TombstoneTest : public ::testing::Test {
+ protected:
+  virtual void SetUp() {
+    map_mock_.reset(new BacktraceMapMock());
+    backtrace_mock_.reset(new BacktraceMock(map_mock_.get()));
+
+    char tmp_file[256];
+    const char data_template[] = "/data/local/tmp/debuggerd_memory_testXXXXXX";
+    memcpy(tmp_file, data_template, sizeof(data_template));
+    int tombstone_fd = mkstemp(tmp_file);
+    if (tombstone_fd == -1) {
+      const char tmp_template[] = "/tmp/debuggerd_memory_testXXXXXX";
+      memcpy(tmp_file, tmp_template, sizeof(tmp_template));
+      tombstone_fd = mkstemp(tmp_file);
+      if (tombstone_fd == -1) {
+        abort();
+      }
+    }
+    if (unlink(tmp_file) == -1) {
+      abort();
+    }
+
+    log_.tfd = tombstone_fd;
+    amfd_data_.clear();
+    log_.amfd_data = &amfd_data_;
+    log_.crashed_tid = 12;
+    log_.current_tid = 12;
+    log_.should_retrieve_logcat = false;
+
+    resetLogs();
+    elf_set_fake_build_id("");
+    siginfo_t si;
+    memset(&si, 0, sizeof(si));
+    si.si_signo = SIGABRT;
+    si.si_code = SI_KERNEL;
+    ptrace_set_fake_getsiginfo(si);
+  }
+
+  virtual void TearDown() {
+    if (log_.tfd >= 0) {
+      close(log_.tfd);
+    }
+  }
+
+  std::unique_ptr<BacktraceMapMock> map_mock_;
+  std::unique_ptr<BacktraceMock> backtrace_mock_;
+
+  log_t log_;
+  std::string amfd_data_;
+};
+
+TEST_F(TombstoneTest, single_map) {
+  backtrace_map_t map;
+#if defined(__LP64__)
+  map.start = 0x123456789abcd000UL;
+  map.end = 0x123456789abdf000UL;
+#else
+  map.start = 0x1234000;
+  map.end = 0x1235000;
+#endif
+  map_mock_->AddMap(map);
+
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    12345678'9abcd000-12345678'9abdefff ---         0     12000\n";
+#else
+"    01234000-01234fff ---         0      1000\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, single_map_elf_build_id) {
+  backtrace_map_t map;
+#if defined(__LP64__)
+  map.start = 0x123456789abcd000UL;
+  map.end = 0x123456789abdf000UL;
+#else
+  map.start = 0x1234000;
+  map.end = 0x1235000;
+#endif
+  map.flags = PROT_READ;
+  map.name = "/system/lib/libfake.so";
+  map_mock_->AddMap(map);
+
+  elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    12345678'9abcd000-12345678'9abdefff r--         0     12000  /system/lib/libfake.so (BuildId: abcdef1234567890abcdef1234567890)\n";
+#else
+"    01234000-01234fff r--         0      1000  /system/lib/libfake.so (BuildId: abcdef1234567890abcdef1234567890)\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+// Even though build id is present, it should not be printed in either of
+// these cases.
+TEST_F(TombstoneTest, single_map_no_build_id) {
+  backtrace_map_t map;
+#if defined(__LP64__)
+  map.start = 0x123456789abcd000UL;
+  map.end = 0x123456789abdf000UL;
+#else
+  map.start = 0x1234000;
+  map.end = 0x1235000;
+#endif
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.name = "/system/lib/libfake.so";
+  map_mock_->AddMap(map);
+
+  elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    12345678'9abcd000-12345678'9abdefff -w-         0     12000\n"
+"    12345678'9abcd000-12345678'9abdefff -w-         0     12000  /system/lib/libfake.so\n";
+#else
+"    01234000-01234fff -w-         0      1000\n"
+"    01234000-01234fff -w-         0      1000  /system/lib/libfake.so\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps) {
+  backtrace_map_t map;
+
+  map.start = 0xa234000;
+  map.end = 0xa235000;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa334000;
+  map.end = 0xa335000;
+  map.offset = 0xf000;
+  map.flags = PROT_READ;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa534000;
+  map.end = 0xa535000;
+  map.offset = 0x3000;
+  map.load_base = 0x2000;
+  map.flags = PROT_EXEC;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa634000;
+  map.end = 0xa635000;
+  map.offset = 0;
+  map.load_base = 0;
+  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
+  map.name = "/system/lib/fake.so";
+  map_mock_->AddMap(map);
+
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    00000000'0a234000-00000000'0a234fff ---         0      1000\n"
+"    00000000'0a334000-00000000'0a334fff r--      f000      1000\n"
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#else
+"    0a234000-0a234fff ---         0      1000\n"
+"    0a334000-0a334fff r--      f000      1000\n"
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_fault_address_before) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa534000;
+  map.end = 0xa535000;
+  map.offset = 0x3000;
+  map.load_base = 0x2000;
+  map.flags = PROT_EXEC;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa634000;
+  map.end = 0xa635000;
+  map.offset = 0;
+  map.load_base = 0;
+  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
+  map.name = "/system/lib/fake.so";
+  map_mock_->AddMap(map);
+
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  si.si_signo = SIGBUS;
+  si.si_code = SI_KERNEL;
+  si.si_addr = reinterpret_cast<void*>(0x1000);
+  ptrace_set_fake_getsiginfo(si);
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map: (fault address prefixed with --->)\n"
+#if defined(__LP64__)
+"--->Fault address falls at 00000000'00001000 before any mapped regions\n"
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#else
+"--->Fault address falls at 00001000 before any mapped regions\n"
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_fault_address_between) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa534000;
+  map.end = 0xa535000;
+  map.offset = 0x3000;
+  map.load_base = 0x2000;
+  map.flags = PROT_EXEC;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa634000;
+  map.end = 0xa635000;
+  map.offset = 0;
+  map.load_base = 0;
+  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
+  map.name = "/system/lib/fake.so";
+  map_mock_->AddMap(map);
+
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  si.si_signo = SIGBUS;
+  si.si_code = SI_KERNEL;
+  si.si_addr = reinterpret_cast<void*>(0xa533000);
+  ptrace_set_fake_getsiginfo(si);
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map: (fault address prefixed with --->)\n"
+#if defined(__LP64__)
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"--->Fault address falls at 00000000'0a533000 between mapped regions\n"
+"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#else
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"--->Fault address falls at 0a533000 between mapped regions\n"
+"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_fault_address_in_map) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa534000;
+  map.end = 0xa535000;
+  map.offset = 0x3000;
+  map.load_base = 0x2000;
+  map.flags = PROT_EXEC;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa634000;
+  map.end = 0xa635000;
+  map.offset = 0;
+  map.load_base = 0;
+  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
+  map.name = "/system/lib/fake.so";
+  map_mock_->AddMap(map);
+
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  si.si_signo = SIGBUS;
+  si.si_code = SI_KERNEL;
+  si.si_addr = reinterpret_cast<void*>(0xa534040);
+  ptrace_set_fake_getsiginfo(si);
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map: (fault address prefixed with --->)\n"
+#if defined(__LP64__)
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"--->00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#else
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"--->0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_fault_address_after) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa534000;
+  map.end = 0xa535000;
+  map.offset = 0x3000;
+  map.load_base = 0x2000;
+  map.flags = PROT_EXEC;
+  map_mock_->AddMap(map);
+
+  map.start = 0xa634000;
+  map.end = 0xa635000;
+  map.offset = 0;
+  map.load_base = 0;
+  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
+  map.name = "/system/lib/fake.so";
+  map_mock_->AddMap(map);
+
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  si.si_signo = SIGBUS;
+  si.si_code = SI_KERNEL;
+#if defined(__LP64__)
+  si.si_addr = reinterpret_cast<void*>(0x12345a534040UL);
+#else
+  si.si_addr = reinterpret_cast<void*>(0xf534040UL);
+#endif
+  ptrace_set_fake_getsiginfo(si);
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map: (fault address prefixed with --->)\n"
+#if defined(__LP64__)
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n"
+"--->Fault address falls at 00001234'5a534040 after any mapped regions\n";
+#else
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
+"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
+"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n"
+"--->Fault address falls at 0f534040 after any mapped regions\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_getsiginfo_fail) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.offset = 0x1000;
+  map.load_base = 0xd000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  ptrace_set_fake_getsiginfo(si);
+  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n";
+#else
+"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n";
+#endif
+  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+
+  // Verify that the log buf is empty, and no error messages.
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("6 DEBUG Cannot get siginfo for 100: Bad address\n\n", getFakeLogPrint().c_str());
+}
+
+TEST_F(TombstoneTest, multiple_maps_check_signal_has_si_addr) {
+  backtrace_map_t map;
+
+  map.start = 0xa434000;
+  map.end = 0xa435000;
+  map.flags = PROT_WRITE;
+  map_mock_->AddMap(map);
+
+  for (int i = 1; i < 255; i++) {
+    ASSERT_TRUE(ftruncate(log_.tfd, 0) == 0);
+    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+
+    siginfo_t si;
+    memset(&si, 0, sizeof(si));
+    si.si_signo = i;
+    si.si_code = SI_KERNEL;
+    si.si_addr = reinterpret_cast<void*>(0x1000);
+    ptrace_set_fake_getsiginfo(si);
+    dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+
+    std::string tombstone_contents;
+    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+    ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+    bool has_addr = false;
+    switch (si.si_signo) {
+    case SIGBUS:
+    case SIGFPE:
+    case SIGILL:
+    case SIGSEGV:
+    case SIGTRAP:
+      has_addr = true;
+      break;
+    }
+
+    const char* expected_addr_dump = \
+"\nmemory map: (fault address prefixed with --->)\n"
+#if defined(__LP64__)
+"--->Fault address falls at 00000000'00001000 before any mapped regions\n"
+"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
+#else
+"--->Fault address falls at 00001000 before any mapped regions\n"
+"    0a434000-0a434fff -w-         0      1000\n";
+#endif
+    const char* expected_dump = \
+"\nmemory map:\n"
+#if defined(__LP64__)
+"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
+#else
+"    0a434000-0a434fff -w-         0      1000\n";
+#endif
+    if (has_addr) {
+      ASSERT_STREQ(expected_addr_dump, tombstone_contents.c_str())
+        << "Signal " << si.si_signo << " expected to include an address.";
+    } else {
+      ASSERT_STREQ(expected_dump, tombstone_contents.c_str())
+        << "Signal " << si.si_signo << " is not expected to include an address.";
+    }
+
+    ASSERT_STREQ("", amfd_data_.c_str());
+
+    // Verify that the log buf is empty, and no error messages.
+    ASSERT_STREQ("", getFakeLogBuf().c_str());
+    ASSERT_STREQ("", getFakeLogPrint().c_str());
+  }
+}
+
+TEST_F(TombstoneTest, dump_signal_info_error) {
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  ptrace_set_fake_getsiginfo(si);
+
+  dump_signal_info(&log_, 123);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  ASSERT_STREQ("", tombstone_contents.c_str());
+
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("6 DEBUG cannot get siginfo: Bad address\n\n", getFakeLogPrint().c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+}
+
+TEST_F(TombstoneTest, dump_log_file_error) {
+  log_.should_retrieve_logcat = true;
+  dump_log_file(&log_, 123, "/fake/filename", 10);
+
+  std::string tombstone_contents;
+  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
+  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
+  ASSERT_STREQ("", tombstone_contents.c_str());
+
+  ASSERT_STREQ("", getFakeLogBuf().c_str());
+  ASSERT_STREQ("6 DEBUG Unable to open /fake/filename: Permission denied\n\n",
+               getFakeLogPrint().c_str());
+
+  ASSERT_STREQ("", amfd_data_.c_str());
+}
+
+TEST_F(TombstoneTest, dump_header_info) {
+  dump_header_info(&log_);
+
+  std::string expected = "Build fingerprint: 'unknown'\nRevision: 'unknown'\n";
+  expected += android::base::StringPrintf("ABI: '%s'\n", ABI_STRING);
+  ASSERT_STREQ(expected.c_str(), amfd_data_.c_str());
+}
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
new file mode 100644
index 0000000..edc7be5
--- /dev/null
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -0,0 +1,772 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <time.h>
+
+#include <memory>
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <android/log.h>
+#include <backtrace/Backtrace.h>
+#include <backtrace/BacktraceMap.h>
+#include <cutils/properties.h>
+#include <log/log.h>
+#include <log/logprint.h>
+#include <private/android_filesystem_config.h>
+
+#include "debuggerd/handler.h"
+
+#include "backtrace.h"
+#include "elf_utils.h"
+#include "machine.h"
+#include "open_files_list.h"
+#include "tombstone.h"
+
+using android::base::StringPrintf;
+
+#define STACK_WORDS 16
+
+#define MAX_TOMBSTONES  10
+#define TOMBSTONE_DIR   "/data/tombstones"
+#define TOMBSTONE_TEMPLATE (TOMBSTONE_DIR"/tombstone_%02d")
+
+static bool signal_has_si_addr(int si_signo, int si_code) {
+  // Manually sent signals won't have si_addr.
+  if (si_code == SI_USER || si_code == SI_QUEUE || si_code == SI_TKILL) {
+    return false;
+  }
+
+  switch (si_signo) {
+    case SIGBUS:
+    case SIGFPE:
+    case SIGILL:
+    case SIGSEGV:
+    case SIGTRAP:
+      return true;
+    default:
+      return false;
+  }
+}
+
+static const char* get_signame(int sig) {
+  switch (sig) {
+    case SIGABRT: return "SIGABRT";
+    case SIGBUS: return "SIGBUS";
+    case SIGFPE: return "SIGFPE";
+    case SIGILL: return "SIGILL";
+    case SIGSEGV: return "SIGSEGV";
+#if defined(SIGSTKFLT)
+    case SIGSTKFLT: return "SIGSTKFLT";
+#endif
+    case SIGSTOP: return "SIGSTOP";
+    case SIGSYS: return "SIGSYS";
+    case SIGTRAP: return "SIGTRAP";
+    case DEBUGGER_SIGNAL: return "<debuggerd signal>";
+    default: return "?";
+  }
+}
+
+static const char* get_sigcode(int signo, int code) {
+  // Try the signal-specific codes...
+  switch (signo) {
+    case SIGILL:
+      switch (code) {
+        case ILL_ILLOPC: return "ILL_ILLOPC";
+        case ILL_ILLOPN: return "ILL_ILLOPN";
+        case ILL_ILLADR: return "ILL_ILLADR";
+        case ILL_ILLTRP: return "ILL_ILLTRP";
+        case ILL_PRVOPC: return "ILL_PRVOPC";
+        case ILL_PRVREG: return "ILL_PRVREG";
+        case ILL_COPROC: return "ILL_COPROC";
+        case ILL_BADSTK: return "ILL_BADSTK";
+      }
+      static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code");
+      break;
+    case SIGBUS:
+      switch (code) {
+        case BUS_ADRALN: return "BUS_ADRALN";
+        case BUS_ADRERR: return "BUS_ADRERR";
+        case BUS_OBJERR: return "BUS_OBJERR";
+        case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
+        case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
+      }
+      static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
+      break;
+    case SIGFPE:
+      switch (code) {
+        case FPE_INTDIV: return "FPE_INTDIV";
+        case FPE_INTOVF: return "FPE_INTOVF";
+        case FPE_FLTDIV: return "FPE_FLTDIV";
+        case FPE_FLTOVF: return "FPE_FLTOVF";
+        case FPE_FLTUND: return "FPE_FLTUND";
+        case FPE_FLTRES: return "FPE_FLTRES";
+        case FPE_FLTINV: return "FPE_FLTINV";
+        case FPE_FLTSUB: return "FPE_FLTSUB";
+      }
+      static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code");
+      break;
+    case SIGSEGV:
+      switch (code) {
+        case SEGV_MAPERR: return "SEGV_MAPERR";
+        case SEGV_ACCERR: return "SEGV_ACCERR";
+#if defined(SEGV_BNDERR)
+        case SEGV_BNDERR: return "SEGV_BNDERR";
+#endif
+#if defined(SEGV_PKUERR)
+        case SEGV_PKUERR: return "SEGV_PKUERR";
+#endif
+      }
+#if defined(SEGV_PKUERR)
+      static_assert(NSIGSEGV == SEGV_PKUERR, "missing SEGV_* si_code");
+#elif defined(SEGV_BNDERR)
+      static_assert(NSIGSEGV == SEGV_BNDERR, "missing SEGV_* si_code");
+#else
+      static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code");
+#endif
+      break;
+#if defined(SYS_SECCOMP) // Our glibc is too old, and we build this for the host too.
+    case SIGSYS:
+      switch (code) {
+        case SYS_SECCOMP: return "SYS_SECCOMP";
+      }
+      static_assert(NSIGSYS == SYS_SECCOMP, "missing SYS_* si_code");
+      break;
+#endif
+    case SIGTRAP:
+      switch (code) {
+        case TRAP_BRKPT: return "TRAP_BRKPT";
+        case TRAP_TRACE: return "TRAP_TRACE";
+        case TRAP_BRANCH: return "TRAP_BRANCH";
+        case TRAP_HWBKPT: return "TRAP_HWBKPT";
+      }
+      static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code");
+      break;
+  }
+  // Then the other codes...
+  switch (code) {
+    case SI_USER: return "SI_USER";
+    case SI_KERNEL: return "SI_KERNEL";
+    case SI_QUEUE: return "SI_QUEUE";
+    case SI_TIMER: return "SI_TIMER";
+    case SI_MESGQ: return "SI_MESGQ";
+    case SI_ASYNCIO: return "SI_ASYNCIO";
+    case SI_SIGIO: return "SI_SIGIO";
+    case SI_TKILL: return "SI_TKILL";
+    case SI_DETHREAD: return "SI_DETHREAD";
+  }
+  // Then give up...
+  return "?";
+}
+
+static void dump_header_info(log_t* log) {
+  char fingerprint[PROPERTY_VALUE_MAX];
+  char revision[PROPERTY_VALUE_MAX];
+
+  property_get("ro.build.fingerprint", fingerprint, "unknown");
+  property_get("ro.revision", revision, "unknown");
+
+  _LOG(log, logtype::HEADER, "Build fingerprint: '%s'\n", fingerprint);
+  _LOG(log, logtype::HEADER, "Revision: '%s'\n", revision);
+  _LOG(log, logtype::HEADER, "ABI: '%s'\n", ABI_STRING);
+}
+
+static void dump_probable_cause(log_t* log, const siginfo_t& si) {
+  std::string cause;
+  if (si.si_signo == SIGSEGV && si.si_code == SEGV_MAPERR) {
+    if (si.si_addr < reinterpret_cast<void*>(4096)) {
+      cause = StringPrintf("null pointer dereference");
+    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
+      cause = "call to kuser_helper_version";
+    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
+      cause = "call to kuser_get_tls";
+    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
+      cause = "call to kuser_cmpxchg";
+    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
+      cause = "call to kuser_memory_barrier";
+    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0f60)) {
+      cause = "call to kuser_cmpxchg64";
+    }
+  } else if (si.si_signo == SIGSYS && si.si_code == SYS_SECCOMP) {
+    cause = StringPrintf("seccomp prevented call to disallowed %s system call %d",
+                         ABI_STRING, si.si_syscall);
+  }
+
+  if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
+}
+
+static void dump_signal_info(log_t* log, const siginfo_t* siginfo) {
+  const siginfo_t& si = *siginfo;
+  char addr_desc[32]; // ", fault addr 0x1234"
+  if (signal_has_si_addr(si.si_signo, si.si_code)) {
+    snprintf(addr_desc, sizeof(addr_desc), "%p", si.si_addr);
+  } else {
+    snprintf(addr_desc, sizeof(addr_desc), "--------");
+  }
+
+  _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s), fault addr %s\n", si.si_signo,
+       get_signame(si.si_signo), si.si_code, get_sigcode(si.si_signo, si.si_code), addr_desc);
+
+  dump_probable_cause(log, si);
+}
+
+static void dump_signal_info(log_t* log, pid_t tid) {
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) == -1) {
+    ALOGE("cannot get siginfo: %s\n", strerror(errno));
+    return;
+  }
+
+  dump_signal_info(log, &si);
+}
+
+static void dump_thread_info(log_t* log, pid_t pid, pid_t tid, const char* process_name,
+                             const char* thread_name) {
+  // Blacklist logd, logd.reader, logd.writer, logd.auditd, logd.control ...
+  // TODO: Why is this controlled by thread name?
+  if (strcmp(thread_name, "logd") == 0 || strncmp(thread_name, "logd.", 4) == 0) {
+    log->should_retrieve_logcat = false;
+  }
+
+  _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s  >>> %s <<<\n", pid, tid, thread_name,
+       process_name);
+}
+
+static void dump_stack_segment(
+    Backtrace* backtrace, log_t* log, uintptr_t* sp, size_t words, int label) {
+  // Read the data all at once.
+  word_t stack_data[words];
+  size_t bytes_read = backtrace->Read(*sp, reinterpret_cast<uint8_t*>(&stack_data[0]), sizeof(word_t) * words);
+  words = bytes_read / sizeof(word_t);
+  std::string line;
+  for (size_t i = 0; i < words; i++) {
+    line = "    ";
+    if (i == 0 && label >= 0) {
+      // Print the label once.
+      line += StringPrintf("#%02d  ", label);
+    } else {
+      line += "     ";
+    }
+    line += StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, stack_data[i]);
+
+    backtrace_map_t map;
+    backtrace->FillInMap(stack_data[i], &map);
+    if (BacktraceMap::IsValid(map) && !map.name.empty()) {
+      line += "  " + map.name;
+      uintptr_t offset = 0;
+      std::string func_name(backtrace->GetFunctionName(stack_data[i], &offset, &map));
+      if (!func_name.empty()) {
+        line += " (" + func_name;
+        if (offset) {
+          line += StringPrintf("+%" PRIuPTR, offset);
+        }
+        line += ')';
+      }
+    }
+    _LOG(log, logtype::STACK, "%s\n", line.c_str());
+
+    *sp += sizeof(word_t);
+  }
+}
+
+static void dump_stack(Backtrace* backtrace, log_t* log) {
+  size_t first = 0, last;
+  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
+    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
+    if (frame->sp) {
+      if (!first) {
+        first = i+1;
+      }
+      last = i;
+    }
+  }
+  if (!first) {
+    return;
+  }
+  first--;
+
+  // Dump a few words before the first frame.
+  word_t sp = backtrace->GetFrame(first)->sp - STACK_WORDS * sizeof(word_t);
+  dump_stack_segment(backtrace, log, &sp, STACK_WORDS, -1);
+
+  // Dump a few words from all successive frames.
+  // Only log the first 3 frames, put the rest in the tombstone.
+  for (size_t i = first; i <= last; i++) {
+    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
+    if (sp != frame->sp) {
+      _LOG(log, logtype::STACK, "         ........  ........\n");
+      sp = frame->sp;
+    }
+    if (i == last) {
+      dump_stack_segment(backtrace, log, &sp, STACK_WORDS, i);
+      if (sp < frame->sp + frame->stack_size) {
+        _LOG(log, logtype::STACK, "         ........  ........\n");
+      }
+    } else {
+      size_t words = frame->stack_size / sizeof(word_t);
+      if (words == 0) {
+        words = 1;
+      } else if (words > STACK_WORDS) {
+        words = STACK_WORDS;
+      }
+      dump_stack_segment(backtrace, log, &sp, words, i);
+    }
+  }
+}
+
+static std::string get_addr_string(uintptr_t addr) {
+  std::string addr_str;
+#if defined(__LP64__)
+  addr_str = StringPrintf("%08x'%08x",
+                          static_cast<uint32_t>(addr >> 32),
+                          static_cast<uint32_t>(addr & 0xffffffff));
+#else
+  addr_str = StringPrintf("%08x", addr);
+#endif
+  return addr_str;
+}
+
+static void dump_abort_message(Backtrace* backtrace, log_t* log, uintptr_t address) {
+  if (address == 0) {
+    return;
+  }
+
+  address += sizeof(size_t);  // Skip the buffer length.
+
+  char msg[512];
+  memset(msg, 0, sizeof(msg));
+  char* p = &msg[0];
+  while (p < &msg[sizeof(msg)]) {
+    word_t data;
+    size_t len = sizeof(word_t);
+    if (!backtrace->ReadWord(address, &data)) {
+      break;
+    }
+    address += sizeof(word_t);
+
+    while (len > 0 && (*p++ = (data >> (sizeof(word_t) - len) * 8) & 0xff) != 0) {
+      len--;
+    }
+  }
+  msg[sizeof(msg) - 1] = '\0';
+
+  _LOG(log, logtype::HEADER, "Abort message: '%s'\n", msg);
+}
+
+static void dump_all_maps(Backtrace* backtrace, BacktraceMap* map, log_t* log, pid_t tid) {
+  bool print_fault_address_marker = false;
+  uintptr_t addr = 0;
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) != -1) {
+    print_fault_address_marker = signal_has_si_addr(si.si_signo, si.si_code);
+    addr = reinterpret_cast<uintptr_t>(si.si_addr);
+  } else {
+    ALOGE("Cannot get siginfo for %d: %s\n", tid, strerror(errno));
+  }
+
+  ScopedBacktraceMapIteratorLock lock(map);
+  _LOG(log, logtype::MAPS, "\n");
+  if (!print_fault_address_marker) {
+    _LOG(log, logtype::MAPS, "memory map:\n");
+  } else {
+    _LOG(log, logtype::MAPS, "memory map: (fault address prefixed with --->)\n");
+    if (map->begin() != map->end() && addr < map->begin()->start) {
+      _LOG(log, logtype::MAPS, "--->Fault address falls at %s before any mapped regions\n",
+           get_addr_string(addr).c_str());
+      print_fault_address_marker = false;
+    }
+  }
+
+  std::string line;
+  for (BacktraceMap::const_iterator it = map->begin(); it != map->end(); ++it) {
+    line = "    ";
+    if (print_fault_address_marker) {
+      if (addr < it->start) {
+        _LOG(log, logtype::MAPS, "--->Fault address falls at %s between mapped regions\n",
+             get_addr_string(addr).c_str());
+        print_fault_address_marker = false;
+      } else if (addr >= it->start && addr < it->end) {
+        line = "--->";
+        print_fault_address_marker = false;
+      }
+    }
+    line += get_addr_string(it->start) + '-' + get_addr_string(it->end - 1) + ' ';
+    if (it->flags & PROT_READ) {
+      line += 'r';
+    } else {
+      line += '-';
+    }
+    if (it->flags & PROT_WRITE) {
+      line += 'w';
+    } else {
+      line += '-';
+    }
+    if (it->flags & PROT_EXEC) {
+      line += 'x';
+    } else {
+      line += '-';
+    }
+    line += StringPrintf("  %8" PRIxPTR "  %8" PRIxPTR, it->offset, it->end - it->start);
+    bool space_needed = true;
+    if (it->name.length() > 0) {
+      space_needed = false;
+      line += "  " + it->name;
+      std::string build_id;
+      if ((it->flags & PROT_READ) && elf_get_build_id(backtrace, it->start, &build_id)) {
+        line += " (BuildId: " + build_id + ")";
+      }
+    }
+    if (it->load_base != 0) {
+      if (space_needed) {
+        line += ' ';
+      }
+      line += StringPrintf(" (load base 0x%" PRIxPTR ")", it->load_base);
+    }
+    _LOG(log, logtype::MAPS, "%s\n", line.c_str());
+  }
+  if (print_fault_address_marker) {
+    _LOG(log, logtype::MAPS, "--->Fault address falls at %s after any mapped regions\n",
+         get_addr_string(addr).c_str());
+  }
+}
+
+static void dump_backtrace_and_stack(Backtrace* backtrace, log_t* log) {
+  if (backtrace->NumFrames()) {
+    _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
+    dump_backtrace_to_log(backtrace, log, "    ");
+
+    _LOG(log, logtype::STACK, "\nstack:\n");
+    dump_stack(backtrace, log);
+  }
+}
+
+// Weak noop implementation, real implementations are in <arch>/machine.cpp.
+__attribute__((weak)) void dump_registers(log_t* log, const ucontext_t*) {
+  _LOG(log, logtype::REGISTERS, "    register dumping unimplemented on this architecture");
+}
+
+static void dump_thread(log_t* log, pid_t pid, pid_t tid, const std::string& process_name,
+                        const std::string& thread_name, BacktraceMap* map,
+                        uintptr_t abort_msg_address, bool primary_thread) {
+  log->current_tid = tid;
+  if (!primary_thread) {
+    _LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
+  }
+  dump_thread_info(log, pid, tid, process_name.c_str(), thread_name.c_str());
+  dump_signal_info(log, tid);
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
+  if (primary_thread) {
+    dump_abort_message(backtrace.get(), log, abort_msg_address);
+  }
+  dump_registers(log, tid);
+  if (backtrace->Unwind(0)) {
+    dump_backtrace_and_stack(backtrace.get(), log);
+  } else {
+    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
+  }
+
+  if (primary_thread) {
+    dump_memory_and_code(log, backtrace.get());
+    if (map) {
+      dump_all_maps(backtrace.get(), map, log, tid);
+    }
+  }
+
+  log->current_tid = log->crashed_tid;
+}
+
+// Reads the contents of the specified log device, filters out the entries
+// that don't match the specified pid, and writes them to the tombstone file.
+//
+// If "tail" is non-zero, log the last "tail" number of lines.
+static EventTagMap* g_eventTagMap = NULL;
+
+static void dump_log_file(
+    log_t* log, pid_t pid, const char* filename, unsigned int tail) {
+  bool first = true;
+  struct logger_list* logger_list;
+
+  if (!log->should_retrieve_logcat) {
+    return;
+  }
+
+  logger_list = android_logger_list_open(
+      android_name_to_log_id(filename), ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, tail, pid);
+
+  if (!logger_list) {
+    ALOGE("Unable to open %s: %s\n", filename, strerror(errno));
+    return;
+  }
+
+  struct log_msg log_entry;
+
+  while (true) {
+    ssize_t actual = android_logger_list_read(logger_list, &log_entry);
+    struct logger_entry* entry;
+
+    if (actual < 0) {
+      if (actual == -EINTR) {
+        // interrupted by signal, retry
+        continue;
+      } else if (actual == -EAGAIN) {
+        // non-blocking EOF; we're done
+        break;
+      } else {
+        ALOGE("Error while reading log: %s\n", strerror(-actual));
+        break;
+      }
+    } else if (actual == 0) {
+      ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
+      break;
+    }
+
+    // NOTE: if you ALOGV something here, this will spin forever,
+    // because you will be writing as fast as you're reading.  Any
+    // high-frequency debug diagnostics should just be written to
+    // the tombstone file.
+
+    entry = &log_entry.entry_v1;
+
+    if (first) {
+      _LOG(log, logtype::LOGS, "--------- %slog %s\n",
+        tail ? "tail end of " : "", filename);
+      first = false;
+    }
+
+    // Msg format is: <priority:1><tag:N>\0<message:N>\0
+    //
+    // We want to display it in the same format as "logcat -v threadtime"
+    // (although in this case the pid is redundant).
+    static const char* kPrioChars = "!.VDIWEFS";
+    unsigned hdr_size = log_entry.entry.hdr_size;
+    if (!hdr_size) {
+      hdr_size = sizeof(log_entry.entry_v1);
+    }
+    if ((hdr_size < sizeof(log_entry.entry_v1)) ||
+        (hdr_size > sizeof(log_entry.entry))) {
+      continue;
+    }
+    char* msg = reinterpret_cast<char*>(log_entry.buf) + hdr_size;
+
+    char timeBuf[32];
+    time_t sec = static_cast<time_t>(entry->sec);
+    struct tm tmBuf;
+    struct tm* ptm;
+    ptm = localtime_r(&sec, &tmBuf);
+    strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
+
+    if (log_entry.id() == LOG_ID_EVENTS) {
+      if (!g_eventTagMap) {
+        g_eventTagMap = android_openEventTagMap(NULL);
+      }
+      AndroidLogEntry e;
+      char buf[512];
+      android_log_processBinaryLogBuffer(entry, &e, g_eventTagMap, buf, sizeof(buf));
+      _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8.*s: %s\n",
+         timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
+         'I', (int)e.tagLen, e.tag, e.message);
+      continue;
+    }
+
+    unsigned char prio = msg[0];
+    char* tag = msg + 1;
+    msg = tag + strlen(tag) + 1;
+
+    // consume any trailing newlines
+    char* nl = msg + strlen(msg) - 1;
+    while (nl >= msg && *nl == '\n') {
+      *nl-- = '\0';
+    }
+
+    char prioChar = (prio < strlen(kPrioChars) ? kPrioChars[prio] : '?');
+
+    // Look for line breaks ('\n') and display each text line
+    // on a separate line, prefixed with the header, like logcat does.
+    do {
+      nl = strchr(msg, '\n');
+      if (nl) {
+        *nl = '\0';
+        ++nl;
+      }
+
+      _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8s: %s\n",
+         timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
+         prioChar, tag, msg);
+    } while ((msg = nl));
+  }
+
+  android_logger_list_free(logger_list);
+}
+
+// Dumps the logs generated by the specified pid to the tombstone, from both
+// "system" and "main" log devices.  Ideally we'd interleave the output.
+static void dump_logs(log_t* log, pid_t pid, unsigned int tail) {
+  dump_log_file(log, pid, "system", tail);
+  dump_log_file(log, pid, "main", tail);
+}
+
+// Dumps all information about the specified pid to the tombstone.
+static void dump_crash(log_t* log, BacktraceMap* map, const OpenFilesList* open_files, pid_t pid,
+                       pid_t tid, const std::string& process_name,
+                       const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address) {
+  // don't copy log messages to tombstone unless this is a dev device
+  char value[PROPERTY_VALUE_MAX];
+  property_get("ro.debuggable", value, "0");
+  bool want_logs = (value[0] == '1');
+
+  _LOG(log, logtype::HEADER,
+       "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+  dump_header_info(log);
+  dump_thread(log, pid, tid, process_name, threads.find(tid)->second, map, abort_msg_address, true);
+  if (want_logs) {
+    dump_logs(log, pid, 5);
+  }
+
+  for (const auto& it : threads) {
+    pid_t thread_tid = it.first;
+    const std::string& thread_name = it.second;
+
+    if (thread_tid != tid) {
+      dump_thread(log, pid, thread_tid, process_name, thread_name, map, 0, false);
+    }
+  }
+
+  if (open_files) {
+    _LOG(log, logtype::OPEN_FILES, "\nopen files:\n");
+    dump_open_files_list_to_log(*open_files, log, "    ");
+  }
+
+  if (want_logs) {
+    dump_logs(log, pid, 0);
+  }
+}
+
+// open_tombstone - find an available tombstone slot, if any, of the
+// form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
+// file is available, we reuse the least-recently-modified file.
+int open_tombstone(std::string* out_path) {
+  // In a single pass, find an available slot and, in case none
+  // exist, find and record the least-recently-modified file.
+  char path[128];
+  int fd = -1;
+  int oldest = -1;
+  struct stat oldest_sb;
+  for (int i = 0; i < MAX_TOMBSTONES; i++) {
+    snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, i);
+
+    struct stat sb;
+    if (stat(path, &sb) == 0) {
+      if (oldest < 0 || sb.st_mtime < oldest_sb.st_mtime) {
+        oldest = i;
+        oldest_sb.st_mtime = sb.st_mtime;
+      }
+      continue;
+    }
+    if (errno != ENOENT) continue;
+
+    fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
+    if (fd < 0) continue;  // raced ?
+
+    if (out_path) {
+      *out_path = path;
+    }
+    fchown(fd, AID_SYSTEM, AID_SYSTEM);
+    return fd;
+  }
+
+  if (oldest < 0) {
+    ALOGE("debuggerd: failed to find a valid tombstone, default to using tombstone 0.\n");
+    oldest = 0;
+  }
+
+  // we didn't find an available file, so we clobber the oldest one
+  snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, oldest);
+  fd = open(path, O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
+  if (fd < 0) {
+    ALOGE("debuggerd: failed to open tombstone file '%s': %s\n", path, strerror(errno));
+    return -1;
+  }
+
+  if (out_path) {
+    *out_path = path;
+  }
+  fchown(fd, AID_SYSTEM, AID_SYSTEM);
+  return fd;
+}
+
+void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
+                       pid_t pid, pid_t tid, const std::string& process_name,
+                       const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
+                       std::string* amfd_data) {
+  log_t log;
+  log.current_tid = tid;
+  log.crashed_tid = tid;
+  log.tfd = tombstone_fd;
+  log.amfd_data = amfd_data;
+  dump_crash(&log, map, open_files, pid, tid, process_name, threads, abort_msg_address);
+}
+
+void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+                                ucontext_t* ucontext) {
+  pid_t pid = getpid();
+  pid_t tid = gettid();
+
+  log_t log;
+  log.current_tid = tid;
+  log.crashed_tid = tid;
+  log.tfd = tombstone_fd;
+  log.amfd_data = nullptr;
+
+  char thread_name[16];
+  char process_name[128];
+
+  read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
+  read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
+
+  _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+  dump_header_info(&log);
+  dump_thread_info(&log, pid, tid, thread_name, process_name);
+  dump_signal_info(&log, siginfo);
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
+  dump_abort_message(backtrace.get(), &log, abort_msg_address);
+  dump_registers(&log, ucontext);
+
+  // TODO: Dump registers from the ucontext.
+  if (backtrace->Unwind(0, ucontext)) {
+    dump_backtrace_and_stack(backtrace.get(), &log);
+  } else {
+    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
+  }
+}
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
new file mode 100644
index 0000000..22fde5e
--- /dev/null
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -0,0 +1,222 @@
+/*
+ * Copyright 2008, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include "utility.h"
+
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+// Whitelist output desired in the logcat output.
+bool is_allowed_in_logcat(enum logtype ltype) {
+  if ((ltype == HEADER)
+   || (ltype == REGISTERS)
+   || (ltype == BACKTRACE)) {
+    return true;
+  }
+  return false;
+}
+
+__attribute__((__weak__, visibility("default")))
+void _LOG(log_t* log, enum logtype ltype, const char* fmt, ...) {
+  bool write_to_tombstone = (log->tfd != -1);
+  bool write_to_logcat = is_allowed_in_logcat(ltype)
+                      && log->crashed_tid != -1
+                      && log->current_tid != -1
+                      && (log->crashed_tid == log->current_tid);
+
+  char buf[512];
+  va_list ap;
+  va_start(ap, fmt);
+  vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
+
+  size_t len = strlen(buf);
+  if (len <= 0) {
+    return;
+  }
+
+  if (write_to_tombstone) {
+    TEMP_FAILURE_RETRY(write(log->tfd, buf, len));
+  }
+
+  if (write_to_logcat) {
+    __android_log_buf_write(LOG_ID_CRASH, ANDROID_LOG_FATAL, LOG_TAG, buf);
+    if (log->amfd_data != nullptr) {
+      *log->amfd_data += buf;
+    }
+  }
+}
+
+bool wait_for_signal(pid_t tid, siginfo_t* siginfo) {
+  while (true) {
+    int status;
+    pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL));
+    if (n == -1) {
+      ALOGE("waitpid failed: tid %d, %s", tid, strerror(errno));
+      return false;
+    } else if (n == tid) {
+      if (WIFSTOPPED(status)) {
+        if (ptrace(PTRACE_GETSIGINFO, tid, nullptr, siginfo) != 0) {
+          ALOGE("PTRACE_GETSIGINFO failed: %s", strerror(errno));
+          return false;
+        }
+        return true;
+      } else {
+        ALOGE("unexpected waitpid response: n=%d, status=%08x\n", n, status);
+        // This is the only circumstance under which we can allow a detach
+        // to fail with ESRCH, which indicates the tid has exited.
+        return false;
+      }
+    }
+  }
+}
+
+#define MEMORY_BYTES_TO_DUMP 256
+#define MEMORY_BYTES_PER_LINE 16
+
+void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...) {
+  std::string log_msg;
+  va_list ap;
+  va_start(ap, fmt);
+  android::base::StringAppendV(&log_msg, fmt, ap);
+  va_end(ap);
+
+  // Align the address to sizeof(long) and start 32 bytes before the address.
+  addr &= ~(sizeof(long) - 1);
+  if (addr >= 4128) {
+    addr -= 32;
+  }
+
+  // Don't bother if the address looks too low, or looks too high.
+  if (addr < 4096 ||
+#if defined(__LP64__)
+      addr > 0x4000000000000000UL - MEMORY_BYTES_TO_DUMP) {
+#else
+      addr > 0xffff0000 - MEMORY_BYTES_TO_DUMP) {
+#endif
+    return;
+  }
+
+  _LOG(log, logtype::MEMORY, "\n%s\n", log_msg.c_str());
+
+  // Dump 256 bytes
+  uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
+  memset(data, 0, MEMORY_BYTES_TO_DUMP);
+  size_t bytes = backtrace->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
+  if (bytes % sizeof(uintptr_t) != 0) {
+    // This should never happen, but just in case.
+    ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
+    bytes &= ~(sizeof(uintptr_t) - 1);
+  }
+
+  uintptr_t start = 0;
+  bool skip_2nd_read = false;
+  if (bytes == 0) {
+    // In this case, we might want to try another read at the beginning of
+    // the next page only if it's within the amount of memory we would have
+    // read.
+    size_t page_size = sysconf(_SC_PAGE_SIZE);
+    start = ((addr + (page_size - 1)) & ~(page_size - 1)) - addr;
+    if (start == 0 || start >= MEMORY_BYTES_TO_DUMP) {
+      skip_2nd_read = true;
+    }
+  }
+
+  if (bytes < MEMORY_BYTES_TO_DUMP && !skip_2nd_read) {
+    // Try to do one more read. This could happen if a read crosses a map,
+    // but the maps do not have any break between them. Or it could happen
+    // if reading from an unreadable map, but the read would cross back
+    // into a readable map. Only requires one extra read because a map has
+    // to contain at least one page, and the total number of bytes to dump
+    // is smaller than a page.
+    size_t bytes2 = backtrace->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
+                                    sizeof(data) - bytes - start);
+    bytes += bytes2;
+    if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
+      // This should never happen, but we'll try and continue any way.
+      ALOGE("Bytes after second read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
+      bytes &= ~(sizeof(uintptr_t) - 1);
+    }
+  }
+
+  // Dump the code around memory as:
+  //  addr             contents                           ascii
+  //  0000000000008d34 ef000000e8bd0090 e1b00000512fff1e  ............../Q
+  //  0000000000008d44 ea00b1f9e92d0090 e3a070fcef000000  ......-..p......
+  // On 32-bit machines, there are still 16 bytes per line but addresses and
+  // words are of course presented differently.
+  uintptr_t* data_ptr = data;
+  size_t current = 0;
+  size_t total_bytes = start + bytes;
+  for (size_t line = 0; line < MEMORY_BYTES_TO_DUMP / MEMORY_BYTES_PER_LINE; line++) {
+    std::string logline;
+    android::base::StringAppendF(&logline, "    %" PRIPTR, addr);
+
+    addr += MEMORY_BYTES_PER_LINE;
+    std::string ascii;
+    for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
+      if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
+        android::base::StringAppendF(&logline, " %" PRIPTR, *data_ptr);
+
+        // Fill out the ascii string from the data.
+        uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr);
+        for (size_t val = 0; val < sizeof(uintptr_t); val++, ptr++) {
+          if (*ptr >= 0x20 && *ptr < 0x7f) {
+            ascii += *ptr;
+          } else {
+            ascii += '.';
+          }
+        }
+        data_ptr++;
+      } else {
+        logline += ' ' + std::string(sizeof(uintptr_t) * 2, '-');
+        ascii += std::string(sizeof(uintptr_t), '.');
+      }
+      current += sizeof(uintptr_t);
+    }
+    _LOG(log, logtype::MEMORY, "%s  %s\n", logline.c_str(), ascii.c_str());
+  }
+}
+
+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));
+  if (fd != -1) {
+    int rc = TEMP_FAILURE_RETRY(read(fd.get(), buf, len - 1));
+    if (rc != -1) {
+      buf[rc] = '\0';
+
+      // Trim trailing newlines.
+      if (rc > 0 && buf[rc - 1] == '\n') {
+        buf[rc - 1] = '\0';
+      }
+      return;
+    }
+  }
+  strcpy(buf, default_value);
+}
diff --git a/debuggerd/x86/machine.cpp b/debuggerd/libdebuggerd/x86/machine.cpp
similarity index 100%
rename from debuggerd/x86/machine.cpp
rename to debuggerd/libdebuggerd/x86/machine.cpp
diff --git a/debuggerd/libdebuggerd/x86_64/machine.cpp b/debuggerd/libdebuggerd/x86_64/machine.cpp
new file mode 100644
index 0000000..bf2c2b4
--- /dev/null
+++ b/debuggerd/libdebuggerd/x86_64/machine.cpp
@@ -0,0 +1,67 @@
+/*
+** Copyright 2013, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#define LOG_TAG "DEBUG"
+
+#include <errno.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/user.h>
+
+#include <backtrace/Backtrace.h>
+#include <log/log.h>
+
+#include "machine.h"
+#include "utility.h"
+
+void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
+  struct user_regs_struct r;
+  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r) == -1) {
+    ALOGE("cannot get registers: %s\n", strerror(errno));
+    return;
+  }
+
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rax), "memory near rax:");
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rbx), "memory near rbx:");
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rcx), "memory near rcx:");
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdx), "memory near rdx:");
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rsi), "memory near rsi:");
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdi), "memory near rdi:");
+
+  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rip), "code around rip:");
+}
+
+void dump_registers(log_t* log, pid_t tid) {
+  struct user_regs_struct r;
+  if (ptrace(PTRACE_GETREGS, tid, 0, &r) == -1) {
+    ALOGE("cannot get registers: %s\n", strerror(errno));
+    return;
+  }
+
+  _LOG(log, logtype::REGISTERS, "    rax %016lx  rbx %016lx  rcx %016lx  rdx %016lx\n",
+       r.rax, r.rbx, r.rcx, r.rdx);
+  _LOG(log, logtype::REGISTERS, "    rsi %016lx  rdi %016lx\n",
+       r.rsi, r.rdi);
+  _LOG(log, logtype::REGISTERS, "    r8  %016lx  r9  %016lx  r10 %016lx  r11 %016lx\n",
+       r.r8, r.r9, r.r10, r.r11);
+  _LOG(log, logtype::REGISTERS, "    r12 %016lx  r13 %016lx  r14 %016lx  r15 %016lx\n",
+       r.r12, r.r13, r.r14, r.r15);
+  _LOG(log, logtype::REGISTERS, "    cs  %016lx  ss  %016lx\n",
+       r.cs, r.ss);
+  _LOG(log, logtype::REGISTERS, "    rip %016lx  rbp %016lx  rsp %016lx  eflags %016lx\n",
+       r.rip, r.rbp, r.rsp, r.eflags);
+}
diff --git a/debuggerd/machine.h b/debuggerd/machine.h
deleted file mode 100644
index e65b147..0000000
--- a/debuggerd/machine.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DEBUGGERD_MACHINE_H
-#define _DEBUGGERD_MACHINE_H
-
-#include <sys/types.h>
-
-#include <backtrace/Backtrace.h>
-
-#include "utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace);
-void dump_registers(log_t* log, pid_t tid);
-
-#endif // _DEBUGGERD_MACHINE_H
diff --git a/debuggerd/signal_sender.cpp b/debuggerd/signal_sender.cpp
index 4be7e6e..42a8e77 100644
--- a/debuggerd/signal_sender.cpp
+++ b/debuggerd/signal_sender.cpp
@@ -14,7 +14,10 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "debuggerd-signal"
+
 #include <errno.h>
+#include <pthread.h>
 #include <signal.h>
 #include <stdlib.h>
 #include <string.h>
@@ -24,7 +27,7 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <log/logger.h>
+#include <log/log.h>
 
 #include "signal_sender.h"
 
diff --git a/debuggerd/signal_sender.h b/debuggerd/signal_sender.h
deleted file mode 100644
index 0443272..0000000
--- a/debuggerd/signal_sender.h
+++ /dev/null
@@ -1,30 +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 _DEBUGGERD_SIGNAL_SENDER_H
-#define _DEBUGGERD_SIGNAL_SENDER_H
-
-#include <sys/types.h>
-
-bool start_signal_sender();
-bool stop_signal_sender();
-
-// Sends a signal to a target process or thread.
-// If tid is greater than zero, this performs tgkill(pid, tid, signal).
-// Otherwise, it performs kill(pid, signal).
-bool send_signal(pid_t pid, pid_t tid, int signal);
-
-#endif
diff --git a/debuggerd/test/BacktraceMock.h b/debuggerd/test/BacktraceMock.h
deleted file mode 100644
index f75534e..0000000
--- a/debuggerd/test/BacktraceMock.h
+++ /dev/null
@@ -1,106 +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.
- */
-
-#ifndef _DEBUGGERD_TEST_BACKTRACE_MOCK_H
-#define _DEBUGGERD_TEST_BACKTRACE_MOCK_H
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ucontext.h>
-
-#include <string>
-#include <vector>
-
-#include <backtrace/Backtrace.h>
-#include <backtrace/BacktraceMap.h>
-
-class BacktraceMapMock : public BacktraceMap {
- public:
-  BacktraceMapMock() : BacktraceMap(0) {}
-  virtual ~BacktraceMapMock() {}
-
-  void AddMap(backtrace_map_t& map) {
-    maps_.push_back(map);
-  }
-};
-
-
-class BacktraceMock : public Backtrace {
- public:
-  BacktraceMock(BacktraceMapMock* map) : Backtrace(0, 0, map) {
-    if (map_ == nullptr) {
-      abort();
-    }
-  }
-  virtual ~BacktraceMock() {}
-
-  virtual bool Unwind(size_t, ucontext_t*) { return false; }
-  virtual bool ReadWord(uintptr_t, word_t*) { return false;}
-
-  virtual std::string GetFunctionNameRaw(uintptr_t, uintptr_t*) { return ""; }
-
-  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
-    size_t offset = 0;
-    if (last_read_addr_ > 0) {
-      offset = addr - last_read_addr_;
-    }
-    size_t bytes_available = buffer_.size() - offset;
-
-    if (do_partial_read_) {
-      // Do a partial read.
-      if (bytes > bytes_partial_read_) {
-        bytes = bytes_partial_read_;
-      }
-      bytes_partial_read_ -= bytes;
-      // Only support a single partial read.
-      do_partial_read_ = false;
-    } else if (bytes > bytes_available) {
-      bytes = bytes_available;
-    }
-
-    if (bytes > 0) {
-      memcpy(buffer, buffer_.data() + offset, bytes);
-    }
-
-    last_read_addr_ = addr;
-    return bytes;
-  }
-
-  void SetReadData(uint8_t* buffer, size_t bytes) {
-    buffer_.resize(bytes);
-    memcpy(buffer_.data(), buffer, bytes);
-    bytes_partial_read_ = 0;
-    do_partial_read_ = false;
-    last_read_addr_ = 0;
-  }
-
-  void SetPartialReadAmount(size_t bytes) {
-    if (bytes > buffer_.size()) {
-      abort();
-    }
-    bytes_partial_read_ = bytes;
-    do_partial_read_ = true;
-  }
-
- private:
-  std::vector<uint8_t> buffer_;
-  size_t bytes_partial_read_ = 0;
-  uintptr_t last_read_addr_ = 0;
-  bool do_partial_read_ = false;
-};
-
-#endif //  _DEBUGGERD_TEST_BACKTRACE_MOCK_H
diff --git a/debuggerd/test/host_signal_fixup.h b/debuggerd/test/host_signal_fixup.h
deleted file mode 100644
index c7796ef..0000000
--- a/debuggerd/test/host_signal_fixup.h
+++ /dev/null
@@ -1,65 +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.
- */
-
-#ifndef _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
-#define _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
-
-#include <signal.h>
-
-#if !defined(__BIONIC__)
-
-// In order to compile parts of debuggerd for the host, we need to
-// define these values.
-
-#if !defined(NSIGILL)
-#define NSIGILL ILL_BADSTK
-#endif
-
-#if !defined(BUS_MCEERR_AR)
-#define BUS_MCEERR_AR 4
-#endif
-#if !defined(BUS_MCEERR_AO)
-#define BUS_MCEERR_AO 5
-#endif
-#if !defined(NSIGBUS)
-#define NSIGBUS BUS_MCEERR_AO
-#endif
-
-#if !defined(NSIGFPE)
-#define NSIGFPE FPE_FLTSUB
-#endif
-
-#if !defined(NSIGSEGV)
-#define NSIGSEGV SEGV_ACCERR
-#endif
-
-#if !defined(TRAP_BRANCH)
-#define TRAP_BRANCH 3
-#endif
-#if !defined(TRAP_HWBKPT)
-#define TRAP_HWBKPT 4
-#endif
-#if !defined(NSIGTRAP)
-#define NSIGTRAP TRAP_HWBKPT
-#endif
-
-#if !defined(SI_DETHREAD)
-#define SI_DETHREAD -7
-#endif
-
-#endif
-
-#endif // _DEBUGGERD_TEST_HOST_SIGNAL_FIXUP_H
diff --git a/debuggerd/test/log_fake.cpp b/debuggerd/test/log_fake.cpp
deleted file mode 100644
index e27e9f6..0000000
--- a/debuggerd/test/log_fake.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <stdarg.h>
-
-#include <string>
-
-#include <android-base/stringprintf.h>
-#include <log/log.h>
-#include <log/logger.h>
-
-// Forward declarations.
-class Backtrace;
-struct EventTagMap;
-struct AndroidLogEntry;
-
-std::string g_fake_log_buf;
-
-std::string g_fake_log_print;
-
-void resetLogs() {
-  g_fake_log_buf = "";
-  g_fake_log_print = "";
-}
-
-std::string getFakeLogBuf() {
-  return g_fake_log_buf;
-}
-
-std::string getFakeLogPrint() {
-  return g_fake_log_print;
-}
-
-extern "C" int __android_log_buf_write(int bufId, int prio, const char* tag, const char* msg) {
-  g_fake_log_buf += std::to_string(bufId) + ' ' + std::to_string(prio) + ' ';
-  g_fake_log_buf += tag;
-  g_fake_log_buf += ' ';
-  g_fake_log_buf += msg;
-  return 1;
-}
-
-extern "C" int __android_log_print(int prio, const char* tag, const char* fmt, ...) {
-  g_fake_log_print += std::to_string(prio) + ' ';
-  g_fake_log_print += tag;
-  g_fake_log_print += ' ';
-
-  va_list ap;
-  va_start(ap, fmt);
-  android::base::StringAppendV(&g_fake_log_print, fmt, ap);
-  va_end(ap);
-
-  g_fake_log_print += '\n';
-
-  return 1;
-}
-
-extern "C" log_id_t android_name_to_log_id(const char*) {
-  return LOG_ID_SYSTEM;
-}
-
-extern "C" struct logger_list* android_logger_list_open(log_id_t, int, unsigned int, pid_t) {
-  errno = EACCES;
-  return nullptr;
-}
-
-extern "C" int android_logger_list_read(struct logger_list*, struct log_msg*) {
-  return 0;
-}
-
-extern "C" EventTagMap* android_openEventTagMap(const char*) {
-  return nullptr;
-}
-
-extern "C" int android_log_processBinaryLogBuffer(
-    struct logger_entry*,
-    AndroidLogEntry*, const EventTagMap*, char*, int) {
-  return 0;
-}
-
-extern "C" void android_logger_list_free(struct logger_list*) {
-}
diff --git a/debuggerd/test/selinux/android.h b/debuggerd/test/selinux/android.h
deleted file mode 100644
index abed087..0000000
--- a/debuggerd/test/selinux/android.h
+++ /dev/null
@@ -1,17 +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.
- */
-
-extern "C" int selinux_android_restorecon(const char*, unsigned int);
diff --git a/debuggerd/test/selinux_fake.cpp b/debuggerd/test/selinux_fake.cpp
deleted file mode 100644
index acdd0a9..0000000
--- a/debuggerd/test/selinux_fake.cpp
+++ /dev/null
@@ -1,19 +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.
- */
-
-extern "C" int selinux_android_restorecon(const char*, unsigned int) {
-  return 0;
-}
diff --git a/debuggerd/test/sys/system_properties.h b/debuggerd/test/sys/system_properties.h
deleted file mode 100644
index 9d44345..0000000
--- a/debuggerd/test/sys/system_properties.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
-#define _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
-
-// This is just enough to get the property code to compile on
-// the host.
-
-#define PROP_NAME_MAX   32
-#define PROP_VALUE_MAX  92
-
-#endif // _DEBUGGERD_TEST_SYS_SYSTEM_PROPERTIES_H
diff --git a/debuggerd/test/tombstone_test.cpp b/debuggerd/test/tombstone_test.cpp
deleted file mode 100644
index 58d640e..0000000
--- a/debuggerd/test/tombstone_test.cpp
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-
-#include <memory>
-#include <string>
-
-#include <gtest/gtest.h>
-#include <android-base/file.h>
-
-#include "utility.h"
-
-#include "BacktraceMock.h"
-#include "elf_fake.h"
-#include "host_signal_fixup.h"
-#include "log_fake.h"
-#include "ptrace_fake.h"
-
-// In order to test this code, we need to include the tombstone.cpp code.
-// Including it, also allows us to override the ptrace function.
-#define ptrace ptrace_fake
-
-#include "tombstone.cpp"
-
-void dump_registers(log_t*, pid_t) {
-}
-
-void dump_memory_and_code(log_t*, Backtrace*) {
-}
-
-void dump_backtrace_to_log(Backtrace*, log_t*, char const*) {
-}
-
-class TombstoneTest : public ::testing::Test {
- protected:
-  virtual void SetUp() {
-    map_mock_.reset(new BacktraceMapMock());
-    backtrace_mock_.reset(new BacktraceMock(map_mock_.get()));
-
-    char tmp_file[256];
-    const char data_template[] = "/data/local/tmp/debuggerd_memory_testXXXXXX";
-    memcpy(tmp_file, data_template, sizeof(data_template));
-    int tombstone_fd = mkstemp(tmp_file);
-    if (tombstone_fd == -1) {
-      const char tmp_template[] = "/tmp/debuggerd_memory_testXXXXXX";
-      memcpy(tmp_file, tmp_template, sizeof(tmp_template));
-      tombstone_fd = mkstemp(tmp_file);
-      if (tombstone_fd == -1) {
-        abort();
-      }
-    }
-    if (unlink(tmp_file) == -1) {
-      abort();
-    }
-
-    log_.tfd = tombstone_fd;
-    amfd_data_.clear();
-    log_.amfd_data = &amfd_data_;
-    log_.crashed_tid = 12;
-    log_.current_tid = 12;
-    log_.should_retrieve_logcat = false;
-
-    resetLogs();
-    elf_set_fake_build_id("");
-    siginfo_t si;
-    si.si_signo = SIGABRT;
-    ptrace_set_fake_getsiginfo(si);
-  }
-
-  virtual void TearDown() {
-    if (log_.tfd >= 0) {
-      close(log_.tfd);
-    }
-  }
-
-  std::unique_ptr<BacktraceMapMock> map_mock_;
-  std::unique_ptr<BacktraceMock> backtrace_mock_;
-
-  log_t log_;
-  std::string amfd_data_;
-};
-
-TEST_F(TombstoneTest, single_map) {
-  backtrace_map_t map;
-#if defined(__LP64__)
-  map.start = 0x123456789abcd000UL;
-  map.end = 0x123456789abdf000UL;
-#else
-  map.start = 0x1234000;
-  map.end = 0x1235000;
-#endif
-  map_mock_->AddMap(map);
-
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    12345678'9abcd000-12345678'9abdefff ---         0     12000\n";
-#else
-"    01234000-01234fff ---         0      1000\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, single_map_elf_build_id) {
-  backtrace_map_t map;
-#if defined(__LP64__)
-  map.start = 0x123456789abcd000UL;
-  map.end = 0x123456789abdf000UL;
-#else
-  map.start = 0x1234000;
-  map.end = 0x1235000;
-#endif
-  map.flags = PROT_READ;
-  map.name = "/system/lib/libfake.so";
-  map_mock_->AddMap(map);
-
-  elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    12345678'9abcd000-12345678'9abdefff r--         0     12000  /system/lib/libfake.so (BuildId: abcdef1234567890abcdef1234567890)\n";
-#else
-"    01234000-01234fff r--         0      1000  /system/lib/libfake.so (BuildId: abcdef1234567890abcdef1234567890)\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-// Even though build id is present, it should not be printed in either of
-// these cases.
-TEST_F(TombstoneTest, single_map_no_build_id) {
-  backtrace_map_t map;
-#if defined(__LP64__)
-  map.start = 0x123456789abcd000UL;
-  map.end = 0x123456789abdf000UL;
-#else
-  map.start = 0x1234000;
-  map.end = 0x1235000;
-#endif
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.name = "/system/lib/libfake.so";
-  map_mock_->AddMap(map);
-
-  elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    12345678'9abcd000-12345678'9abdefff -w-         0     12000\n"
-"    12345678'9abcd000-12345678'9abdefff -w-         0     12000  /system/lib/libfake.so\n";
-#else
-"    01234000-01234fff -w-         0      1000\n"
-"    01234000-01234fff -w-         0      1000  /system/lib/libfake.so\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps) {
-  backtrace_map_t map;
-
-  map.start = 0xa234000;
-  map.end = 0xa235000;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa334000;
-  map.end = 0xa335000;
-  map.offset = 0xf000;
-  map.flags = PROT_READ;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa534000;
-  map.end = 0xa535000;
-  map.offset = 0x3000;
-  map.load_base = 0x2000;
-  map.flags = PROT_EXEC;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa634000;
-  map.end = 0xa635000;
-  map.offset = 0;
-  map.load_base = 0;
-  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
-  map.name = "/system/lib/fake.so";
-  map_mock_->AddMap(map);
-
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    00000000'0a234000-00000000'0a234fff ---         0      1000\n"
-"    00000000'0a334000-00000000'0a334fff r--      f000      1000\n"
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#else
-"    0a234000-0a234fff ---         0      1000\n"
-"    0a334000-0a334fff r--      f000      1000\n"
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_fault_address_before) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa534000;
-  map.end = 0xa535000;
-  map.offset = 0x3000;
-  map.load_base = 0x2000;
-  map.flags = PROT_EXEC;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa634000;
-  map.end = 0xa635000;
-  map.offset = 0;
-  map.load_base = 0;
-  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
-  map.name = "/system/lib/fake.so";
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  si.si_signo = SIGBUS;
-  si.si_addr = reinterpret_cast<void*>(0x1000);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map: (fault address prefixed with --->)\n"
-#if defined(__LP64__)
-"--->Fault address falls at 00000000'00001000 before any mapped regions\n"
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#else
-"--->Fault address falls at 00001000 before any mapped regions\n"
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_fault_address_between) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa534000;
-  map.end = 0xa535000;
-  map.offset = 0x3000;
-  map.load_base = 0x2000;
-  map.flags = PROT_EXEC;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa634000;
-  map.end = 0xa635000;
-  map.offset = 0;
-  map.load_base = 0;
-  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
-  map.name = "/system/lib/fake.so";
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  si.si_signo = SIGBUS;
-  si.si_addr = reinterpret_cast<void*>(0xa533000);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map: (fault address prefixed with --->)\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"--->Fault address falls at 00000000'0a533000 between mapped regions\n"
-"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#else
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"--->Fault address falls at 0a533000 between mapped regions\n"
-"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_fault_address_in_map) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa534000;
-  map.end = 0xa535000;
-  map.offset = 0x3000;
-  map.load_base = 0x2000;
-  map.flags = PROT_EXEC;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa634000;
-  map.end = 0xa635000;
-  map.offset = 0;
-  map.load_base = 0;
-  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
-  map.name = "/system/lib/fake.so";
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  si.si_signo = SIGBUS;
-  si.si_addr = reinterpret_cast<void*>(0xa534040);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map: (fault address prefixed with --->)\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"--->00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#else
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"--->0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_fault_address_after) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa534000;
-  map.end = 0xa535000;
-  map.offset = 0x3000;
-  map.load_base = 0x2000;
-  map.flags = PROT_EXEC;
-  map_mock_->AddMap(map);
-
-  map.start = 0xa634000;
-  map.end = 0xa635000;
-  map.offset = 0;
-  map.load_base = 0;
-  map.flags = PROT_READ | PROT_WRITE | PROT_EXEC;
-  map.name = "/system/lib/fake.so";
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  si.si_signo = SIGBUS;
-#if defined(__LP64__)
-  si.si_addr = reinterpret_cast<void*>(0x12345a534040UL);
-#else
-  si.si_addr = reinterpret_cast<void*>(0xf534040UL);
-#endif
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map: (fault address prefixed with --->)\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    00000000'0a534000-00000000'0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    00000000'0a634000-00000000'0a634fff rwx         0      1000  /system/lib/fake.so\n"
-"--->Fault address falls at 00001234'5a534040 after any mapped regions\n";
-#else
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n"
-"    0a534000-0a534fff --x      3000      1000  (load base 0x2000)\n"
-"    0a634000-0a634fff rwx         0      1000  /system/lib/fake.so\n"
-"--->Fault address falls at 0f534040 after any mapped regions\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_getsiginfo_fail) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_base = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  si.si_signo = 0;
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load base 0xd000)\n";
-#else
-"    0a434000-0a434fff -w-      1000      1000  (load base 0xd000)\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("6 DEBUG Cannot get siginfo for 100: Bad address\n\n", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_check_signal_has_si_addr) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  for (int i = 1; i < 255; i++) {
-    ASSERT_TRUE(ftruncate(log_.tfd, 0) == 0);
-    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-
-    siginfo_t si;
-    si.si_signo = i;
-    si.si_addr = reinterpret_cast<void*>(0x1000);
-    ptrace_set_fake_getsiginfo(si);
-    dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-    std::string tombstone_contents;
-    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-    ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-    bool has_addr = false;
-    switch (si.si_signo) {
-    case SIGBUS:
-    case SIGFPE:
-    case SIGILL:
-    case SIGSEGV:
-    case SIGTRAP:
-      has_addr = true;
-      break;
-    }
-
-    const char* expected_addr_dump = \
-"\nmemory map: (fault address prefixed with --->)\n"
-#if defined(__LP64__)
-"--->Fault address falls at 00000000'00001000 before any mapped regions\n"
-"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
-#else
-"--->Fault address falls at 00001000 before any mapped regions\n"
-"    0a434000-0a434fff -w-         0      1000\n";
-#endif
-    const char* expected_dump = \
-"\nmemory map:\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
-#else
-"    0a434000-0a434fff -w-         0      1000\n";
-#endif
-    if (has_addr) {
-      ASSERT_STREQ(expected_addr_dump, tombstone_contents.c_str())
-        << "Signal " << si.si_signo << " expected to include an address.";
-    } else {
-      ASSERT_STREQ(expected_dump, tombstone_contents.c_str())
-        << "Signal " << si.si_signo << " is not expected to include an address.";
-    }
-
-    ASSERT_STREQ("", amfd_data_.c_str());
-
-    // Verify that the log buf is empty, and no error messages.
-    ASSERT_STREQ("", getFakeLogBuf().c_str());
-    ASSERT_STREQ("", getFakeLogPrint().c_str());
-  }
-}
-
-TEST_F(TombstoneTest, dump_signal_info_error) {
-  siginfo_t si;
-  si.si_signo = 0;
-  ptrace_set_fake_getsiginfo(si);
-
-  dump_signal_info(&log_, 123, SIGSEGV, 10);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  ASSERT_STREQ("", tombstone_contents.c_str());
-
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("6 DEBUG cannot get siginfo: Bad address\n\n", getFakeLogPrint().c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-}
-
-TEST_F(TombstoneTest, dump_log_file_error) {
-  log_.should_retrieve_logcat = true;
-  dump_log_file(&log_, 123, "/fake/filename", 10);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  ASSERT_STREQ("", tombstone_contents.c_str());
-
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("6 DEBUG Unable to open /fake/filename: Permission denied\n\n",
-               getFakeLogPrint().c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-}
-
-TEST_F(TombstoneTest, dump_header_info) {
-  dump_header_info(&log_);
-
-  std::string expected = "Build fingerprint: 'unknown'\nRevision: 'unknown'\n";
-  expected += android::base::StringPrintf("ABI: '%s'\n", ABI_STRING);
-  ASSERT_STREQ(expected.c_str(), amfd_data_.c_str());
-}
diff --git a/debuggerd/tombstone.cpp b/debuggerd/tombstone.cpp
deleted file mode 100644
index dfdf29c..0000000
--- a/debuggerd/tombstone.cpp
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * Copyright (C) 2012-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <signal.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <sys/ptrace.h>
-#include <sys/stat.h>
-
-#include <memory>
-#include <string>
-
-#include <private/android_filesystem_config.h>
-
-#include <android-base/stringprintf.h>
-#include <cutils/properties.h>
-#include <log/log.h>
-#include <log/logger.h>
-#include <log/logprint.h>
-
-#include <backtrace/Backtrace.h>
-#include <backtrace/BacktraceMap.h>
-
-#include <selinux/android.h>
-
-#include "backtrace.h"
-#include "elf_utils.h"
-#include "machine.h"
-#include "tombstone.h"
-
-#define STACK_WORDS 16
-
-#define MAX_TOMBSTONES  10
-#define TOMBSTONE_DIR   "/data/tombstones"
-#define TOMBSTONE_TEMPLATE (TOMBSTONE_DIR"/tombstone_%02d")
-
-static bool signal_has_si_addr(int sig) {
-  switch (sig) {
-    case SIGBUS:
-    case SIGFPE:
-    case SIGILL:
-    case SIGSEGV:
-    case SIGTRAP:
-      return true;
-    default:
-      return false;
-  }
-}
-
-static const char* get_signame(int sig) {
-  switch(sig) {
-    case SIGABRT: return "SIGABRT";
-    case SIGBUS: return "SIGBUS";
-    case SIGFPE: return "SIGFPE";
-    case SIGILL: return "SIGILL";
-    case SIGSEGV: return "SIGSEGV";
-#if defined(SIGSTKFLT)
-    case SIGSTKFLT: return "SIGSTKFLT";
-#endif
-    case SIGSTOP: return "SIGSTOP";
-    case SIGTRAP: return "SIGTRAP";
-    default: return "?";
-  }
-}
-
-static const char* get_sigcode(int signo, int code) {
-  // Try the signal-specific codes...
-  switch (signo) {
-    case SIGILL:
-      switch (code) {
-        case ILL_ILLOPC: return "ILL_ILLOPC";
-        case ILL_ILLOPN: return "ILL_ILLOPN";
-        case ILL_ILLADR: return "ILL_ILLADR";
-        case ILL_ILLTRP: return "ILL_ILLTRP";
-        case ILL_PRVOPC: return "ILL_PRVOPC";
-        case ILL_PRVREG: return "ILL_PRVREG";
-        case ILL_COPROC: return "ILL_COPROC";
-        case ILL_BADSTK: return "ILL_BADSTK";
-      }
-      static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code");
-      break;
-    case SIGBUS:
-      switch (code) {
-        case BUS_ADRALN: return "BUS_ADRALN";
-        case BUS_ADRERR: return "BUS_ADRERR";
-        case BUS_OBJERR: return "BUS_OBJERR";
-        case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
-        case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
-      }
-      static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
-      break;
-    case SIGFPE:
-      switch (code) {
-        case FPE_INTDIV: return "FPE_INTDIV";
-        case FPE_INTOVF: return "FPE_INTOVF";
-        case FPE_FLTDIV: return "FPE_FLTDIV";
-        case FPE_FLTOVF: return "FPE_FLTOVF";
-        case FPE_FLTUND: return "FPE_FLTUND";
-        case FPE_FLTRES: return "FPE_FLTRES";
-        case FPE_FLTINV: return "FPE_FLTINV";
-        case FPE_FLTSUB: return "FPE_FLTSUB";
-      }
-      static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code");
-      break;
-    case SIGSEGV:
-      switch (code) {
-        case SEGV_MAPERR: return "SEGV_MAPERR";
-        case SEGV_ACCERR: return "SEGV_ACCERR";
-#if defined(SEGV_BNDERR)
-        case SEGV_BNDERR: return "SEGV_BNDERR";
-#endif
-      }
-#if defined(SEGV_BNDERR)
-      static_assert(NSIGSEGV == SEGV_BNDERR, "missing SEGV_* si_code");
-#else
-      static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code");
-#endif
-      break;
-    case SIGTRAP:
-      switch (code) {
-        case TRAP_BRKPT: return "TRAP_BRKPT";
-        case TRAP_TRACE: return "TRAP_TRACE";
-        case TRAP_BRANCH: return "TRAP_BRANCH";
-        case TRAP_HWBKPT: return "TRAP_HWBKPT";
-      }
-      static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code");
-      break;
-  }
-  // Then the other codes...
-  switch (code) {
-    case SI_USER: return "SI_USER";
-    case SI_KERNEL: return "SI_KERNEL";
-    case SI_QUEUE: return "SI_QUEUE";
-    case SI_TIMER: return "SI_TIMER";
-    case SI_MESGQ: return "SI_MESGQ";
-    case SI_ASYNCIO: return "SI_ASYNCIO";
-    case SI_SIGIO: return "SI_SIGIO";
-    case SI_TKILL: return "SI_TKILL";
-    case SI_DETHREAD: return "SI_DETHREAD";
-  }
-  // Then give up...
-  return "?";
-}
-
-static void dump_header_info(log_t* log) {
-  char fingerprint[PROPERTY_VALUE_MAX];
-  char revision[PROPERTY_VALUE_MAX];
-
-  property_get("ro.build.fingerprint", fingerprint, "unknown");
-  property_get("ro.revision", revision, "unknown");
-
-  _LOG(log, logtype::HEADER, "Build fingerprint: '%s'\n", fingerprint);
-  _LOG(log, logtype::HEADER, "Revision: '%s'\n", revision);
-  _LOG(log, logtype::HEADER, "ABI: '%s'\n", ABI_STRING);
-}
-
-static void dump_signal_info(log_t* log, pid_t tid, int signal, int si_code) {
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) == -1) {
-    ALOGE("cannot get siginfo: %s\n", strerror(errno));
-    return;
-  }
-
-  // bionic has to re-raise some signals, which overwrites the si_code with SI_TKILL.
-  si.si_code = si_code;
-
-  char addr_desc[32]; // ", fault addr 0x1234"
-  if (signal_has_si_addr(signal)) {
-    snprintf(addr_desc, sizeof(addr_desc), "%p", si.si_addr);
-  } else {
-    snprintf(addr_desc, sizeof(addr_desc), "--------");
-  }
-
-  _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s), fault addr %s\n",
-       signal, get_signame(signal), si.si_code, get_sigcode(signal, si.si_code), addr_desc);
-}
-
-static void dump_thread_info(log_t* log, pid_t pid, pid_t tid) {
-  char path[64];
-  char threadnamebuf[1024];
-  char* threadname = nullptr;
-  FILE *fp;
-
-  snprintf(path, sizeof(path), "/proc/%d/comm", tid);
-  if ((fp = fopen(path, "r"))) {
-    threadname = fgets(threadnamebuf, sizeof(threadnamebuf), fp);
-    fclose(fp);
-    if (threadname) {
-      size_t len = strlen(threadname);
-      if (len && threadname[len - 1] == '\n') {
-        threadname[len - 1] = '\0';
-      }
-    }
-  }
-  // Blacklist logd, logd.reader, logd.writer, logd.auditd, logd.control ...
-  static const char logd[] = "logd";
-  if (threadname != nullptr && !strncmp(threadname, logd, sizeof(logd) - 1)
-      && (!threadname[sizeof(logd) - 1] || (threadname[sizeof(logd) - 1] == '.'))) {
-    log->should_retrieve_logcat = false;
-  }
-
-  char procnamebuf[1024];
-  char* procname = nullptr;
-
-  snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
-  if ((fp = fopen(path, "r"))) {
-    procname = fgets(procnamebuf, sizeof(procnamebuf), fp);
-    fclose(fp);
-  }
-
-  _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s  >>> %s <<<\n", pid, tid,
-       threadname ? threadname : "UNKNOWN", procname ? procname : "UNKNOWN");
-}
-
-static void dump_stack_segment(
-    Backtrace* backtrace, log_t* log, uintptr_t* sp, size_t words, int label) {
-  // Read the data all at once.
-  word_t stack_data[words];
-  size_t bytes_read = backtrace->Read(*sp, reinterpret_cast<uint8_t*>(&stack_data[0]), sizeof(word_t) * words);
-  words = bytes_read / sizeof(word_t);
-  std::string line;
-  for (size_t i = 0; i < words; i++) {
-    line = "    ";
-    if (i == 0 && label >= 0) {
-      // Print the label once.
-      line += android::base::StringPrintf("#%02d  ", label);
-    } else {
-      line += "     ";
-    }
-    line += android::base::StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, stack_data[i]);
-
-    backtrace_map_t map;
-    backtrace->FillInMap(stack_data[i], &map);
-    if (BacktraceMap::IsValid(map) && !map.name.empty()) {
-      line += "  " + map.name;
-      uintptr_t offset = 0;
-      std::string func_name(backtrace->GetFunctionName(stack_data[i], &offset));
-      if (!func_name.empty()) {
-        line += " (" + func_name;
-        if (offset) {
-          line += android::base::StringPrintf("+%" PRIuPTR, offset);
-        }
-        line += ')';
-      }
-    }
-    _LOG(log, logtype::STACK, "%s\n", line.c_str());
-
-    *sp += sizeof(word_t);
-  }
-}
-
-static void dump_stack(Backtrace* backtrace, log_t* log) {
-  size_t first = 0, last;
-  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
-    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
-    if (frame->sp) {
-      if (!first) {
-        first = i+1;
-      }
-      last = i;
-    }
-  }
-  if (!first) {
-    return;
-  }
-  first--;
-
-  // Dump a few words before the first frame.
-  word_t sp = backtrace->GetFrame(first)->sp - STACK_WORDS * sizeof(word_t);
-  dump_stack_segment(backtrace, log, &sp, STACK_WORDS, -1);
-
-  // Dump a few words from all successive frames.
-  // Only log the first 3 frames, put the rest in the tombstone.
-  for (size_t i = first; i <= last; i++) {
-    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
-    if (sp != frame->sp) {
-      _LOG(log, logtype::STACK, "         ........  ........\n");
-      sp = frame->sp;
-    }
-    if (i == last) {
-      dump_stack_segment(backtrace, log, &sp, STACK_WORDS, i);
-      if (sp < frame->sp + frame->stack_size) {
-        _LOG(log, logtype::STACK, "         ........  ........\n");
-      }
-    } else {
-      size_t words = frame->stack_size / sizeof(word_t);
-      if (words == 0) {
-        words = 1;
-      } else if (words > STACK_WORDS) {
-        words = STACK_WORDS;
-      }
-      dump_stack_segment(backtrace, log, &sp, words, i);
-    }
-  }
-}
-
-static std::string get_addr_string(uintptr_t addr) {
-  std::string addr_str;
-#if defined(__LP64__)
-  addr_str = android::base::StringPrintf("%08x'%08x",
-                                         static_cast<uint32_t>(addr >> 32),
-                                         static_cast<uint32_t>(addr & 0xffffffff));
-#else
-  addr_str = android::base::StringPrintf("%08x", addr);
-#endif
-  return addr_str;
-}
-
-static void dump_abort_message(Backtrace* backtrace, log_t* log, uintptr_t address) {
-  if (address == 0) {
-    return;
-  }
-
-  address += sizeof(size_t);  // Skip the buffer length.
-
-  char msg[512];
-  memset(msg, 0, sizeof(msg));
-  char* p = &msg[0];
-  while (p < &msg[sizeof(msg)]) {
-    word_t data;
-    size_t len = sizeof(word_t);
-    if (!backtrace->ReadWord(address, &data)) {
-      break;
-    }
-    address += sizeof(word_t);
-
-    while (len > 0 && (*p++ = (data >> (sizeof(word_t) - len) * 8) & 0xff) != 0) {
-      len--;
-    }
-  }
-  msg[sizeof(msg) - 1] = '\0';
-
-  _LOG(log, logtype::HEADER, "Abort message: '%s'\n", msg);
-}
-
-static void dump_all_maps(Backtrace* backtrace, BacktraceMap* map, log_t* log, pid_t tid) {
-  bool print_fault_address_marker = false;
-  uintptr_t addr = 0;
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) != -1) {
-    print_fault_address_marker = signal_has_si_addr(si.si_signo);
-    addr = reinterpret_cast<uintptr_t>(si.si_addr);
-  } else {
-    ALOGE("Cannot get siginfo for %d: %s\n", tid, strerror(errno));
-  }
-
-  ScopedBacktraceMapIteratorLock lock(map);
-  _LOG(log, logtype::MAPS, "\n");
-  if (!print_fault_address_marker) {
-    _LOG(log, logtype::MAPS, "memory map:\n");
-  } else {
-    _LOG(log, logtype::MAPS, "memory map: (fault address prefixed with --->)\n");
-    if (map->begin() != map->end() && addr < map->begin()->start) {
-      _LOG(log, logtype::MAPS, "--->Fault address falls at %s before any mapped regions\n",
-           get_addr_string(addr).c_str());
-      print_fault_address_marker = false;
-    }
-  }
-
-  std::string line;
-  for (BacktraceMap::const_iterator it = map->begin(); it != map->end(); ++it) {
-    line = "    ";
-    if (print_fault_address_marker) {
-      if (addr < it->start) {
-        _LOG(log, logtype::MAPS, "--->Fault address falls at %s between mapped regions\n",
-             get_addr_string(addr).c_str());
-        print_fault_address_marker = false;
-      } else if (addr >= it->start && addr < it->end) {
-        line = "--->";
-        print_fault_address_marker = false;
-      }
-    }
-    line += get_addr_string(it->start) + '-' + get_addr_string(it->end - 1) + ' ';
-    if (it->flags & PROT_READ) {
-      line += 'r';
-    } else {
-      line += '-';
-    }
-    if (it->flags & PROT_WRITE) {
-      line += 'w';
-    } else {
-      line += '-';
-    }
-    if (it->flags & PROT_EXEC) {
-      line += 'x';
-    } else {
-      line += '-';
-    }
-    line += android::base::StringPrintf("  %8" PRIxPTR "  %8" PRIxPTR,
-                                        it->offset, it->end - it->start);
-    bool space_needed = true;
-    if (it->name.length() > 0) {
-      space_needed = false;
-      line += "  " + it->name;
-      std::string build_id;
-      if ((it->flags & PROT_READ) && elf_get_build_id(backtrace, it->start, &build_id)) {
-        line += " (BuildId: " + build_id + ")";
-      }
-    }
-    if (it->load_base != 0) {
-      if (space_needed) {
-        line += ' ';
-      }
-      line += android::base::StringPrintf(" (load base 0x%" PRIxPTR ")", it->load_base);
-    }
-    _LOG(log, logtype::MAPS, "%s\n", line.c_str());
-  }
-  if (print_fault_address_marker) {
-    _LOG(log, logtype::MAPS, "--->Fault address falls at %s after any mapped regions\n",
-         get_addr_string(addr).c_str());
-  }
-}
-
-static void dump_backtrace_and_stack(Backtrace* backtrace, log_t* log) {
-  if (backtrace->NumFrames()) {
-    _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
-    dump_backtrace_to_log(backtrace, log, "    ");
-
-    _LOG(log, logtype::STACK, "\nstack:\n");
-    dump_stack(backtrace, log);
-  }
-}
-
-static void dump_thread(log_t* log, pid_t pid, pid_t tid, BacktraceMap* map, int signal,
-                        int si_code, uintptr_t abort_msg_address, bool primary_thread) {
-  log->current_tid = tid;
-  if (!primary_thread) {
-    _LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
-  }
-  dump_thread_info(log, pid, tid);
-
-  if (signal) {
-    dump_signal_info(log, tid, signal, si_code);
-  }
-
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
-  if (primary_thread) {
-    dump_abort_message(backtrace.get(), log, abort_msg_address);
-  }
-  dump_registers(log, tid);
-  if (backtrace->Unwind(0)) {
-    dump_backtrace_and_stack(backtrace.get(), log);
-  } else {
-    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
-  }
-
-  if (primary_thread) {
-    dump_memory_and_code(log, backtrace.get());
-    if (map) {
-      dump_all_maps(backtrace.get(), map, log, tid);
-    }
-  }
-
-  log->current_tid = log->crashed_tid;
-}
-
-// Reads the contents of the specified log device, filters out the entries
-// that don't match the specified pid, and writes them to the tombstone file.
-//
-// If "tail" is non-zero, log the last "tail" number of lines.
-static EventTagMap* g_eventTagMap = NULL;
-
-static void dump_log_file(
-    log_t* log, pid_t pid, const char* filename, unsigned int tail) {
-  bool first = true;
-  struct logger_list* logger_list;
-
-  if (!log->should_retrieve_logcat) {
-    return;
-  }
-
-  logger_list = android_logger_list_open(
-      android_name_to_log_id(filename), ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, tail, pid);
-
-  if (!logger_list) {
-    ALOGE("Unable to open %s: %s\n", filename, strerror(errno));
-    return;
-  }
-
-  struct log_msg log_entry;
-
-  while (true) {
-    ssize_t actual = android_logger_list_read(logger_list, &log_entry);
-    struct logger_entry* entry;
-
-    if (actual < 0) {
-      if (actual == -EINTR) {
-        // interrupted by signal, retry
-        continue;
-      } else if (actual == -EAGAIN) {
-        // non-blocking EOF; we're done
-        break;
-      } else {
-        ALOGE("Error while reading log: %s\n", strerror(-actual));
-        break;
-      }
-    } else if (actual == 0) {
-      ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
-      break;
-    }
-
-    // NOTE: if you ALOGV something here, this will spin forever,
-    // because you will be writing as fast as you're reading.  Any
-    // high-frequency debug diagnostics should just be written to
-    // the tombstone file.
-
-    entry = &log_entry.entry_v1;
-
-    if (first) {
-      _LOG(log, logtype::LOGS, "--------- %slog %s\n",
-        tail ? "tail end of " : "", filename);
-      first = false;
-    }
-
-    // Msg format is: <priority:1><tag:N>\0<message:N>\0
-    //
-    // We want to display it in the same format as "logcat -v threadtime"
-    // (although in this case the pid is redundant).
-    static const char* kPrioChars = "!.VDIWEFS";
-    unsigned hdr_size = log_entry.entry.hdr_size;
-    if (!hdr_size) {
-      hdr_size = sizeof(log_entry.entry_v1);
-    }
-    char* msg = reinterpret_cast<char*>(log_entry.buf) + hdr_size;
-
-    char timeBuf[32];
-    time_t sec = static_cast<time_t>(entry->sec);
-    struct tm tmBuf;
-    struct tm* ptm;
-    ptm = localtime_r(&sec, &tmBuf);
-    strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
-
-    if (log_entry.id() == LOG_ID_EVENTS) {
-      if (!g_eventTagMap) {
-        g_eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
-      }
-      AndroidLogEntry e;
-      char buf[512];
-      android_log_processBinaryLogBuffer(entry, &e, g_eventTagMap, buf, sizeof(buf));
-      _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8s: %s\n",
-         timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
-         'I', e.tag, e.message);
-      continue;
-    }
-
-    unsigned char prio = msg[0];
-    char* tag = msg + 1;
-    msg = tag + strlen(tag) + 1;
-
-    // consume any trailing newlines
-    char* nl = msg + strlen(msg) - 1;
-    while (nl >= msg && *nl == '\n') {
-      *nl-- = '\0';
-    }
-
-    char prioChar = (prio < strlen(kPrioChars) ? kPrioChars[prio] : '?');
-
-    // Look for line breaks ('\n') and display each text line
-    // on a separate line, prefixed with the header, like logcat does.
-    do {
-      nl = strchr(msg, '\n');
-      if (nl) {
-        *nl = '\0';
-        ++nl;
-      }
-
-      _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8s: %s\n",
-         timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
-         prioChar, tag, msg);
-    } while ((msg = nl));
-  }
-
-  android_logger_list_free(logger_list);
-}
-
-// Dumps the logs generated by the specified pid to the tombstone, from both
-// "system" and "main" log devices.  Ideally we'd interleave the output.
-static void dump_logs(log_t* log, pid_t pid, unsigned int tail) {
-  dump_log_file(log, pid, "system", tail);
-  dump_log_file(log, pid, "main", tail);
-}
-
-// Dumps all information about the specified pid to the tombstone.
-static void dump_crash(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, int signal, int si_code,
-                       uintptr_t abort_msg_address) {
-  // don't copy log messages to tombstone unless this is a dev device
-  char value[PROPERTY_VALUE_MAX];
-  property_get("ro.debuggable", value, "0");
-  bool want_logs = (value[0] == '1');
-
-  _LOG(log, logtype::HEADER,
-       "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
-  dump_header_info(log);
-  dump_thread(log, pid, tid, map, signal, si_code, abort_msg_address, true);
-  if (want_logs) {
-    dump_logs(log, pid, 5);
-  }
-
-  if (!siblings.empty()) {
-    for (pid_t sibling : siblings) {
-      dump_thread(log, pid, sibling, map, 0, 0, 0, false);
-    }
-  }
-
-  if (want_logs) {
-    dump_logs(log, pid, 0);
-  }
-}
-
-// open_tombstone - find an available tombstone slot, if any, of the
-// form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
-// file is available, we reuse the least-recently-modified file.
-int open_tombstone(std::string* out_path) {
-  // In a single pass, find an available slot and, in case none
-  // exist, find and record the least-recently-modified file.
-  char path[128];
-  int fd = -1;
-  int oldest = -1;
-  struct stat oldest_sb;
-  for (int i = 0; i < MAX_TOMBSTONES; i++) {
-    snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, i);
-
-    struct stat sb;
-    if (stat(path, &sb) == 0) {
-      if (oldest < 0 || sb.st_mtime < oldest_sb.st_mtime) {
-        oldest = i;
-        oldest_sb.st_mtime = sb.st_mtime;
-      }
-      continue;
-    }
-    if (errno != ENOENT) continue;
-
-    fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
-    if (fd < 0) continue;  // raced ?
-
-    if (out_path) {
-      *out_path = path;
-    }
-    fchown(fd, AID_SYSTEM, AID_SYSTEM);
-    return fd;
-  }
-
-  if (oldest < 0) {
-    ALOGE("debuggerd: failed to find a valid tombstone, default to using tombstone 0.\n");
-    oldest = 0;
-  }
-
-  // we didn't find an available file, so we clobber the oldest one
-  snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, oldest);
-  fd = open(path, O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
-  if (fd < 0) {
-    ALOGE("debuggerd: failed to open tombstone file '%s': %s\n", path, strerror(errno));
-    return -1;
-  }
-
-  if (out_path) {
-    *out_path = path;
-  }
-  fchown(fd, AID_SYSTEM, AID_SYSTEM);
-  return fd;
-}
-
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, int signal, int original_si_code,
-                       uintptr_t abort_msg_address, std::string* amfd_data) {
-  log_t log;
-  log.current_tid = tid;
-  log.crashed_tid = tid;
-
-  if (tombstone_fd < 0) {
-    ALOGE("debuggerd: skipping tombstone write, nothing to do.\n");
-    return;
-  }
-
-  log.tfd = tombstone_fd;
-  log.amfd_data = amfd_data;
-  dump_crash(&log, map, pid, tid, siblings, signal, original_si_code, abort_msg_address);
-}
diff --git a/debuggerd/tombstone.h b/debuggerd/tombstone.h
deleted file mode 100644
index 487d950..0000000
--- a/debuggerd/tombstone.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DEBUGGERD_TOMBSTONE_H
-#define _DEBUGGERD_TOMBSTONE_H
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <sys/types.h>
-#include <set>
-#include <string>
-
-class BacktraceMap;
-
-/* Create and open a tombstone file for writing.
- * Returns a writable file descriptor, or -1 with errno set appropriately.
- * If out_path is non-null, *out_path is set to the path of the tombstone file.
- */
-int open_tombstone(std::string* path);
-
-/* Creates a tombstone file and writes the crash dump to it. */
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, int signal, int original_si_code,
-                       uintptr_t abort_msg_address, std::string* amfd_data);
-
-#endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/tombstoned/intercept_manager.cpp b/debuggerd/tombstoned/intercept_manager.cpp
new file mode 100644
index 0000000..dff942c
--- /dev/null
+++ b/debuggerd/tombstoned/intercept_manager.cpp
@@ -0,0 +1,193 @@
+/*
+ * Copyright 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 "intercept_manager.h"
+
+#include <inttypes.h>
+#include <sys/types.h>
+
+#include <unordered_map>
+
+#include <event2/event.h>
+#include <event2/listener.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+
+#include "debuggerd/protocol.h"
+#include "debuggerd/util.h"
+
+using android::base::unique_fd;
+
+static void intercept_close_cb(evutil_socket_t sockfd, short event, void* arg) {
+  auto intercept = reinterpret_cast<Intercept*>(arg);
+  InterceptManager* intercept_manager = intercept->intercept_manager;
+
+  CHECK_EQ(sockfd, intercept->sockfd.get());
+
+  // If we can read, either we received unexpected data from the other side, or the other side
+  // closed their end of the socket. Either way, kill the intercept.
+
+  // Ownership of intercept differs based on whether we've registered it with InterceptManager.
+  if (!intercept->registered) {
+    delete intercept;
+  } else {
+    auto it = intercept_manager->intercepts.find(intercept->intercept_pid);
+    if (it == intercept_manager->intercepts.end()) {
+      LOG(FATAL) << "intercept close callback called after intercept was already removed?";
+    }
+    if (it->second.get() != intercept) {
+      LOG(FATAL) << "intercept close callback has different Intercept from InterceptManager?";
+    }
+
+    const char* reason;
+    if ((event & EV_TIMEOUT) != 0) {
+      reason = "due to timeout";
+    } else {
+      reason = "due to input";
+    }
+
+    LOG(INFO) << "intercept for pid " << intercept->intercept_pid << " terminated " << reason;
+    intercept_manager->intercepts.erase(it);
+  }
+}
+
+static void intercept_request_cb(evutil_socket_t sockfd, short ev, void* arg) {
+  auto intercept = reinterpret_cast<Intercept*>(arg);
+  InterceptManager* intercept_manager = intercept->intercept_manager;
+
+  CHECK_EQ(sockfd, intercept->sockfd.get());
+
+  if ((ev & EV_TIMEOUT) != 0) {
+    LOG(WARNING) << "tombstoned didn't receive InterceptRequest before timeout";
+    goto fail;
+  } else if ((ev & EV_READ) == 0) {
+    LOG(WARNING) << "tombstoned received unexpected event on intercept socket";
+    goto fail;
+  }
+
+  {
+    unique_fd rcv_fd;
+    InterceptRequest intercept_request;
+    ssize_t result = recv_fd(sockfd, &intercept_request, sizeof(intercept_request), &rcv_fd);
+
+    if (result == -1) {
+      PLOG(WARNING) << "failed to read from intercept socket";
+      goto fail;
+    } else if (result != sizeof(intercept_request)) {
+      LOG(WARNING) << "intercept socket received short read of length " << result << " (expected "
+                   << sizeof(intercept_request) << ")";
+      goto fail;
+    }
+
+    // Move the received FD to the upper half, in order to more easily notice FD leaks.
+    int moved_fd = fcntl(rcv_fd.get(), F_DUPFD, 512);
+    if (moved_fd == -1) {
+      LOG(WARNING) << "failed to move received fd (" << rcv_fd.get() << ")";
+      goto fail;
+    }
+    rcv_fd.reset(moved_fd);
+
+    // 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)));
+      goto fail;
+    }
+
+    intercept->intercept_pid = intercept_request.pid;
+
+    // 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)));
+      LOG(WARNING) << response.error_message;
+      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;
+
+    LOG(INFO) << "tombstoned registered intercept for pid " << intercept_request.pid;
+
+    // Register a different read event on the socket so that we can remove intercepts if the socket
+    // closes (e.g. if a user CTRL-C's the process that requested the intercept).
+    event_assign(intercept->intercept_event, intercept_manager->base, sockfd, EV_READ | EV_TIMEOUT,
+                 intercept_close_cb, arg);
+
+    struct timeval timeout = { .tv_sec = 10, .tv_usec = 0 };
+    event_add(intercept->intercept_event, &timeout);
+  }
+
+  return;
+
+fail:
+  delete intercept;
+}
+
+static void intercept_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
+                                void* arg) {
+  Intercept* intercept = new Intercept();
+  intercept->intercept_manager = static_cast<InterceptManager*>(arg);
+  intercept->sockfd.reset(sockfd);
+
+  struct timeval timeout = { 1, 0 };
+  event_base* base = evconnlistener_get_base(listener);
+  event* intercept_event =
+    event_new(base, sockfd, EV_TIMEOUT | EV_READ, intercept_request_cb, intercept);
+  intercept->intercept_event = intercept_event;
+  event_add(intercept_event, &timeout);
+}
+
+InterceptManager::InterceptManager(event_base* base, int intercept_socket) : base(base) {
+  this->listener = evconnlistener_new(base, intercept_accept_cb, this, -1, LEV_OPT_CLOSE_ON_FREE,
+                                      intercept_socket);
+}
+
+bool InterceptManager::GetIntercept(pid_t pid, android::base::unique_fd* out_fd) {
+  auto it = this->intercepts.find(pid);
+  if (it == this->intercepts.end()) {
+    return false;
+  }
+
+  auto intercept = std::move(it->second);
+  this->intercepts.erase(it);
+
+  LOG(INFO) << "found intercept fd " << intercept->output_fd.get() << " for pid " << pid;
+  InterceptResponse response = {};
+  response.status = InterceptStatus::kStarted;
+  TEMP_FAILURE_RETRY(write(intercept->sockfd, &response, sizeof(response)));
+  *out_fd = std::move(intercept->output_fd);
+
+  return true;
+}
diff --git a/debuggerd/tombstoned/intercept_manager.h b/debuggerd/tombstoned/intercept_manager.h
new file mode 100644
index 0000000..cb5db62
--- /dev/null
+++ b/debuggerd/tombstoned/intercept_manager.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright 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.
+ */
+
+#pragma once
+
+#include <sys/types.h>
+
+#include <unordered_map>
+
+#include <event2/event.h>
+#include <event2/listener.h>
+
+#include <android-base/unique_fd.h>
+
+struct InterceptManager;
+
+struct Intercept {
+  ~Intercept() {
+    event_free(intercept_event);
+  }
+
+  InterceptManager* intercept_manager = nullptr;
+  event* intercept_event = nullptr;
+  android::base::unique_fd sockfd;
+
+  pid_t intercept_pid = -1;
+  android::base::unique_fd output_fd;
+  bool registered = false;
+};
+
+struct InterceptManager {
+  event_base* base;
+  std::unordered_map<pid_t, std::unique_ptr<Intercept>> intercepts;
+  evconnlistener* listener = nullptr;
+
+  InterceptManager(event_base* _Nonnull base, int intercept_socket);
+  InterceptManager(InterceptManager& copy) = delete;
+  InterceptManager(InterceptManager&& move) = delete;
+
+  bool GetIntercept(pid_t pid, android::base::unique_fd* out_fd);
+};
diff --git a/debuggerd/tombstoned/tombstoned.cpp b/debuggerd/tombstoned/tombstoned.cpp
new file mode 100644
index 0000000..0e5dcef
--- /dev/null
+++ b/debuggerd/tombstoned/tombstoned.cpp
@@ -0,0 +1,308 @@
+/*
+ * Copyright 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 <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <array>
+#include <deque>
+#include <unordered_map>
+
+#include <event2/event.h>
+#include <event2/listener.h>
+#include <event2/thread.h>
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+
+#include "debuggerd/handler.h"
+#include "debuggerd/protocol.h"
+#include "debuggerd/util.h"
+
+#include "intercept_manager.h"
+
+using android::base::StringPrintf;
+using android::base::unique_fd;
+
+static InterceptManager* intercept_manager;
+
+enum CrashStatus {
+  kCrashStatusRunning,
+  kCrashStatusQueued,
+};
+
+// Ownership of Crash is a bit messy.
+// It's either owned by an active event that must have a timeout, or owned by
+// queued_requests, in the case that multiple crashes come in at the same time.
+struct Crash {
+  ~Crash() {
+    event_free(crash_event);
+  }
+
+  unique_fd crash_fd;
+  pid_t crash_pid;
+  event* crash_event = nullptr;
+  std::string crash_path;
+};
+
+static constexpr char kTombstoneDirectory[] = "/data/tombstones/";
+static constexpr size_t kTombstoneCount = 10;
+static int tombstone_directory_fd = -1;
+static int next_tombstone = 0;
+
+static constexpr size_t kMaxConcurrentDumps = 1;
+static size_t num_concurrent_dumps = 0;
+
+static std::deque<Crash*> queued_requests;
+
+// Forward declare the callbacks so they can be placed in a sensible order.
+static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int, void*);
+static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg);
+static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg);
+
+static void find_oldest_tombstone() {
+  size_t oldest_tombstone = 0;
+  time_t oldest_time = std::numeric_limits<time_t>::max();
+
+  for (size_t i = 0; i < kTombstoneCount; ++i) {
+    std::string path = android::base::StringPrintf("%stombstone_%02zu", kTombstoneDirectory, i);
+    struct stat st;
+    if (stat(path.c_str(), &st) != 0) {
+      if (errno == ENOENT) {
+        oldest_tombstone = i;
+        break;
+      } else {
+        PLOG(ERROR) << "failed to stat " << path;
+        continue;
+      }
+    }
+
+    if (st.st_mtime < oldest_time) {
+      oldest_tombstone = i;
+      oldest_time = st.st_mtime;
+    }
+  }
+
+  next_tombstone = oldest_tombstone;
+}
+
+static std::pair<unique_fd, std::string> get_tombstone() {
+  // If kMaxConcurrentDumps is greater than 1, then theoretically the same
+  // filename could be handed out to multiple processes. Unlink and create the
+  // file, instead of using O_TRUNC, to avoid two processes interleaving their
+  // output.
+  unique_fd result;
+  std::string file_name = StringPrintf("tombstone_%02d", next_tombstone);
+  if (unlinkat(tombstone_directory_fd, file_name.c_str(), 0) != 0 && errno != ENOENT) {
+    PLOG(FATAL) << "failed to unlink tombstone at " << kTombstoneDirectory << "/" << file_name;
+  }
+
+  result.reset(openat(tombstone_directory_fd, file_name.c_str(),
+                      O_CREAT | O_EXCL | O_WRONLY | O_APPEND | O_CLOEXEC, 0640));
+  if (result == -1) {
+    PLOG(FATAL) << "failed to create tombstone at " << kTombstoneDirectory << "/" << file_name;
+  }
+
+  next_tombstone = (next_tombstone + 1) % kTombstoneCount;
+  return {std::move(result), std::string(kTombstoneDirectory) + "/" + file_name};
+}
+
+static void perform_request(Crash* crash) {
+  unique_fd output_fd;
+  if (!intercept_manager->GetIntercept(crash->crash_pid, &output_fd)) {
+    std::tie(output_fd, crash->crash_path) = get_tombstone();
+  }
+
+  TombstonedCrashPacket response = {
+    .packet_type = CrashPacketType::kPerformDump
+  };
+  ssize_t rc = send_fd(crash->crash_fd, &response, sizeof(response), std::move(output_fd));
+  if (rc == -1) {
+    PLOG(WARNING) << "failed to send response to CrashRequest";
+    goto fail;
+  } else if (rc != sizeof(response)) {
+    PLOG(WARNING) << "crash socket write returned short";
+    goto fail;
+  } else {
+    // TODO: Make this configurable by the interceptor?
+    struct timeval timeout = { 10, 0 };
+
+    event_base* base = event_get_base(crash->crash_event);
+    event_assign(crash->crash_event, base, crash->crash_fd, EV_TIMEOUT | EV_READ,
+                 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);
+  Crash* crash = new Crash();
+
+  struct timeval timeout = { 1, 0 };
+  event* crash_event = event_new(base, sockfd, EV_TIMEOUT | EV_READ, crash_request_cb, crash);
+  crash->crash_fd.reset(sockfd);
+  crash->crash_event = crash_event;
+  event_add(crash_event, &timeout);
+}
+
+static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg) {
+  ssize_t rc;
+  Crash* crash = static_cast<Crash*>(arg);
+  TombstonedCrashPacket request = {};
+
+  if ((ev & EV_TIMEOUT) != 0) {
+    LOG(WARNING) << "crash request timed out";
+    goto fail;
+  } else if ((ev & EV_READ) == 0) {
+    LOG(WARNING) << "tombstoned received unexpected event from crash socket";
+    goto fail;
+  }
+
+  rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
+  if (rc == -1) {
+    PLOG(WARNING) << "failed to read from crash socket";
+    goto fail;
+  } else if (rc != sizeof(request)) {
+    LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
+                 << sizeof(request) << ")";
+    goto fail;
+  }
+
+  if (request.packet_type != CrashPacketType::kDumpRequest) {
+    LOG(WARNING) << "unexpected crash packet type, expected kDumpRequest, received  "
+                 << StringPrintf("%#2hhX", request.packet_type);
+    goto fail;
+  }
+
+  crash->crash_pid = request.packet.dump_request.pid;
+  LOG(INFO) << "received crash request for pid " << crash->crash_pid;
+
+  if (num_concurrent_dumps == kMaxConcurrentDumps) {
+    LOG(INFO) << "enqueueing crash request for pid " << crash->crash_pid;
+    queued_requests.push_back(crash);
+  } else {
+    perform_request(crash);
+  }
+
+  return;
+
+fail:
+  delete crash;
+}
+
+static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg) {
+  ssize_t rc;
+  Crash* crash = static_cast<Crash*>(arg);
+  TombstonedCrashPacket request = {};
+
+  --num_concurrent_dumps;
+
+  if ((ev & EV_READ) == 0) {
+    goto fail;
+  }
+
+  rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
+  if (rc == -1) {
+    PLOG(WARNING) << "failed to read from crash socket";
+    goto fail;
+  } else if (rc != sizeof(request)) {
+    LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
+                 << sizeof(request) << ")";
+    goto fail;
+  }
+
+  if (request.packet_type != CrashPacketType::kCompletedDump) {
+    LOG(WARNING) << "unexpected crash packet type, expected kCompletedDump, received "
+                 << uint32_t(request.packet_type);
+    goto fail;
+  }
+
+  if (!crash->crash_path.empty()) {
+    LOG(ERROR) << "Tombstone written to: " << crash->crash_path;
+  }
+
+fail:
+  delete crash;
+
+  // If there's something queued up, let them proceed.
+  dequeue_requests();
+}
+
+int main(int, char* []) {
+  umask(0137);
+
+  // Don't try to connect to ourselves if we crash.
+  struct sigaction action = {};
+  action.sa_handler = [](int signal) {
+    LOG(ERROR) << "received fatal signal " << signal;
+    _exit(1);
+  };
+  debuggerd_register_handlers(&action);
+
+  tombstone_directory_fd = open(kTombstoneDirectory, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
+  if (tombstone_directory_fd == -1) {
+    PLOG(FATAL) << "failed to open tombstone directory";
+  }
+
+  find_oldest_tombstone();
+
+  int intercept_socket = android_get_control_socket(kTombstonedInterceptSocketName);
+  int crash_socket = android_get_control_socket(kTombstonedCrashSocketName);
+
+  if (intercept_socket == -1 || crash_socket == -1) {
+    PLOG(FATAL) << "failed to get socket from init";
+  }
+
+  evutil_make_socket_nonblocking(intercept_socket);
+  evutil_make_socket_nonblocking(crash_socket);
+
+  event_base* base = event_base_new();
+  if (!base) {
+    LOG(FATAL) << "failed to create event_base";
+  }
+
+  intercept_manager = new InterceptManager(base, intercept_socket);
+
+  evconnlistener* listener =
+    evconnlistener_new(base, crash_accept_cb, nullptr, -1, LEV_OPT_CLOSE_ON_FREE, crash_socket);
+  if (!listener) {
+    LOG(FATAL) << "failed to create evconnlistener";
+  }
+
+  LOG(INFO) << "tombstoned successfully initialized";
+  event_base_dispatch(base);
+}
diff --git a/debuggerd/tombstoned/tombstoned.rc b/debuggerd/tombstoned/tombstoned.rc
new file mode 100644
index 0000000..b8345ca
--- /dev/null
+++ b/debuggerd/tombstoned/tombstoned.rc
@@ -0,0 +1,10 @@
+service tombstoned /system/bin/tombstoned
+    user tombstoned
+    group system
+
+    # Don't start tombstoned until after the real /data is mounted.
+    class late_start
+
+    socket tombstoned_crash seqpacket 0666 system system
+    socket tombstoned_intercept seqpacket 0666 system system
+    writepid /dev/cpuset/system-background/tasks
diff --git a/debuggerd/tombstoned_client.cpp b/debuggerd/tombstoned_client.cpp
new file mode 100644
index 0000000..03b4a20
--- /dev/null
+++ b/debuggerd/tombstoned_client.cpp
@@ -0,0 +1,86 @@
+/*
+ * 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/tombstoned.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <utility>
+
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+
+#include "debuggerd/protocol.h"
+#include "debuggerd/util.h"
+#include "private/libc_logging.h"
+
+using android::base::unique_fd;
+
+bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
+  unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
+                                       ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
+  if (sockfd == -1) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to connect to tombstoned: %s",
+                      strerror(errno));
+    return false;
+  }
+
+  TombstonedCrashPacket packet = {};
+  packet.packet_type = CrashPacketType::kDumpRequest;
+  packet.packet.dump_request.pid = pid;
+  if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to write DumpRequest packet: %s",
+                      strerror(errno));
+    return false;
+  }
+
+  unique_fd tmp_output_fd;
+  ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
+  if (rc == -1) {
+    __libc_format_log(ANDROID_LOG_ERROR, "libc",
+                      "failed to read response to DumpRequest packet: %s", strerror(errno));
+    return false;
+  } else if (rc != sizeof(packet)) {
+    __libc_format_log(
+      ANDROID_LOG_ERROR, "libc",
+      "received DumpRequest response packet of incorrect length (expected %zu, got %zd)",
+      sizeof(packet), rc);
+    return false;
+  }
+
+  // Make the fd O_APPEND so that our output is guaranteed to be at the end of a file.
+  // (This also makes selinux rules consistent, because selinux distinguishes between writing to
+  // a regular fd, and writing to an fd with O_APPEND).
+  int flags = fcntl(tmp_output_fd.get(), F_GETFL);
+  if (fcntl(tmp_output_fd.get(), F_SETFL, flags | O_APPEND) != 0) {
+    __libc_format_log(ANDROID_LOG_WARN, "libc", "failed to set output fd flags: %s",
+                      strerror(errno));
+  }
+
+  *tombstoned_socket = std::move(sockfd);
+  *output_fd = std::move(tmp_output_fd);
+  return true;
+}
+
+bool tombstoned_notify_completion(int tombstoned_socket) {
+  TombstonedCrashPacket packet = {};
+  packet.packet_type = CrashPacketType::kCompletedDump;
+  if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
+    return false;
+  }
+  return true;
+}
diff --git a/debuggerd/util.cpp b/debuggerd/util.cpp
new file mode 100644
index 0000000..4c015d7
--- /dev/null
+++ b/debuggerd/util.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright 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 "debuggerd/util.h"
+
+#include <sys/socket.h>
+
+#include <utility>
+
+#include <android-base/unique_fd.h>
+#include <cutils/sockets.h>
+#include <debuggerd/protocol.h>
+
+#include "private/libc_logging.h"
+
+using android::base::unique_fd;
+
+ssize_t send_fd(int sockfd, const void* data, size_t len, unique_fd fd) {
+  char cmsg_buf[CMSG_SPACE(sizeof(int))];
+
+  iovec iov = { .iov_base = const_cast<void*>(data), .iov_len = len };
+  msghdr msg = {
+    .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cmsg_buf, .msg_controllen = sizeof(cmsg_buf),
+  };
+  auto cmsg = CMSG_FIRSTHDR(&msg);
+  cmsg->cmsg_level = SOL_SOCKET;
+  cmsg->cmsg_type = SCM_RIGHTS;
+  cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+  *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = fd.get();
+
+  return TEMP_FAILURE_RETRY(sendmsg(sockfd, &msg, 0));
+}
+
+ssize_t recv_fd(int sockfd, void* _Nonnull data, size_t len, unique_fd* _Nullable out_fd) {
+  char cmsg_buf[CMSG_SPACE(sizeof(int))];
+
+  iovec iov = { .iov_base = const_cast<void*>(data), .iov_len = len };
+  msghdr msg = {
+    .msg_iov = &iov,
+    .msg_iovlen = 1,
+    .msg_control = cmsg_buf,
+    .msg_controllen = sizeof(cmsg_buf),
+    .msg_flags = 0,
+  };
+  auto cmsg = CMSG_FIRSTHDR(&msg);
+  cmsg->cmsg_level = SOL_SOCKET;
+  cmsg->cmsg_type = SCM_RIGHTS;
+  cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+
+  ssize_t result = TEMP_FAILURE_RETRY(recvmsg(sockfd, &msg, 0));
+  if (result == -1) {
+    return -1;
+  }
+
+  unique_fd fd;
+  bool received_fd = msg.msg_controllen == sizeof(cmsg_buf);
+  if (received_fd) {
+    fd.reset(*reinterpret_cast<int*>(CMSG_DATA(cmsg)));
+  }
+
+  if ((msg.msg_flags & MSG_TRUNC) != 0) {
+    errno = EFBIG;
+    return -1;
+  } else if ((msg.msg_flags & MSG_CTRUNC) != 0) {
+    errno = ERANGE;
+    return -1;
+  }
+
+  if (out_fd) {
+    *out_fd = std::move(fd);
+  } else if (received_fd) {
+    errno = ERANGE;
+    return -1;
+  }
+
+  return result;
+}
+
+bool Pipe(unique_fd* read, unique_fd* write) {
+  int pipefds[2];
+  if (pipe(pipefds) != 0) {
+    return false;
+  }
+  read->reset(pipefds[0]);
+  write->reset(pipefds[1]);
+  return true;
+}
diff --git a/debuggerd/utility.cpp b/debuggerd/utility.cpp
deleted file mode 100644
index bd06095..0000000
--- a/debuggerd/utility.cpp
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright 2008, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "utility.h"
-
-#include <errno.h>
-#include <signal.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/ptrace.h>
-#include <sys/wait.h>
-
-#include <string>
-
-#include <android-base/stringprintf.h>
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-constexpr int SLEEP_TIME_USEC = 50000;          // 0.05 seconds
-constexpr int MAX_TOTAL_SLEEP_USEC = 10000000;  // 10 seconds
-
-// Whitelist output desired in the logcat output.
-bool is_allowed_in_logcat(enum logtype ltype) {
-  if ((ltype == HEADER)
-   || (ltype == REGISTERS)
-   || (ltype == BACKTRACE)) {
-    return true;
-  }
-  return false;
-}
-
-void _LOG(log_t* log, enum logtype ltype, const char* fmt, ...) {
-  bool write_to_tombstone = (log->tfd != -1);
-  bool write_to_logcat = is_allowed_in_logcat(ltype)
-                      && log->crashed_tid != -1
-                      && log->current_tid != -1
-                      && (log->crashed_tid == log->current_tid);
-
-  char buf[512];
-  va_list ap;
-  va_start(ap, fmt);
-  vsnprintf(buf, sizeof(buf), fmt, ap);
-  va_end(ap);
-
-  size_t len = strlen(buf);
-  if (len <= 0) {
-    return;
-  }
-
-  if (write_to_tombstone) {
-    TEMP_FAILURE_RETRY(write(log->tfd, buf, len));
-  }
-
-  if (write_to_logcat) {
-    __android_log_buf_write(LOG_ID_CRASH, ANDROID_LOG_FATAL, LOG_TAG, buf);
-    if (log->amfd_data != nullptr) {
-      *log->amfd_data += buf;
-    }
-  }
-}
-
-int wait_for_signal(pid_t tid, int* total_sleep_time_usec) {
-  while (true) {
-    int status;
-    pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL | WNOHANG));
-    if (n == -1) {
-      ALOGE("waitpid failed: tid %d, %s", tid, strerror(errno));
-      return -1;
-    } else if (n == tid) {
-      if (WIFSTOPPED(status)) {
-        return WSTOPSIG(status);
-      } else {
-        ALOGE("unexpected waitpid response: n=%d, status=%08x\n", n, status);
-        // This is the only circumstance under which we can allow a detach
-        // to fail with ESRCH, which indicates the tid has exited.
-        return -1;
-      }
-    }
-
-    if (*total_sleep_time_usec > MAX_TOTAL_SLEEP_USEC) {
-      ALOGE("timed out waiting for stop signal: tid=%d", tid);
-      return -1;
-    }
-
-    usleep(SLEEP_TIME_USEC);
-    *total_sleep_time_usec += SLEEP_TIME_USEC;
-  }
-}
-
-#define MEMORY_BYTES_TO_DUMP 256
-#define MEMORY_BYTES_PER_LINE 16
-
-void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...) {
-  std::string log_msg;
-  va_list ap;
-  va_start(ap, fmt);
-  android::base::StringAppendV(&log_msg, fmt, ap);
-  va_end(ap);
-
-  // Align the address to sizeof(long) and start 32 bytes before the address.
-  addr &= ~(sizeof(long) - 1);
-  if (addr >= 4128) {
-    addr -= 32;
-  }
-
-  // Don't bother if the address looks too low, or looks too high.
-  if (addr < 4096 ||
-#if defined(__LP64__)
-      addr > 0x4000000000000000UL - MEMORY_BYTES_TO_DUMP) {
-#else
-      addr > 0xffff0000 - MEMORY_BYTES_TO_DUMP) {
-#endif
-    return;
-  }
-
-  _LOG(log, logtype::MEMORY, "\n%s\n", log_msg.c_str());
-
-  // Dump 256 bytes
-  uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
-  memset(data, 0, MEMORY_BYTES_TO_DUMP);
-  size_t bytes = backtrace->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
-  if (bytes % sizeof(uintptr_t) != 0) {
-    // This should never happen, but just in case.
-    ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
-    bytes &= ~(sizeof(uintptr_t) - 1);
-  }
-
-  uintptr_t start = 0;
-  bool skip_2nd_read = false;
-  if (bytes == 0) {
-    // In this case, we might want to try another read at the beginning of
-    // the next page only if it's within the amount of memory we would have
-    // read.
-    size_t page_size = sysconf(_SC_PAGE_SIZE);
-    start = ((addr + (page_size - 1)) & ~(page_size - 1)) - addr;
-    if (start == 0 || start >= MEMORY_BYTES_TO_DUMP) {
-      skip_2nd_read = true;
-    }
-  }
-
-  if (bytes < MEMORY_BYTES_TO_DUMP && !skip_2nd_read) {
-    // Try to do one more read. This could happen if a read crosses a map,
-    // but the maps do not have any break between them. Or it could happen
-    // if reading from an unreadable map, but the read would cross back
-    // into a readable map. Only requires one extra read because a map has
-    // to contain at least one page, and the total number of bytes to dump
-    // is smaller than a page.
-    size_t bytes2 = backtrace->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
-                                    sizeof(data) - bytes - start);
-    bytes += bytes2;
-    if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
-      // This should never happen, but we'll try and continue any way.
-      ALOGE("Bytes after second read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
-      bytes &= ~(sizeof(uintptr_t) - 1);
-    }
-  }
-
-  // Dump the code around memory as:
-  //  addr             contents                           ascii
-  //  0000000000008d34 ef000000e8bd0090 e1b00000512fff1e  ............../Q
-  //  0000000000008d44 ea00b1f9e92d0090 e3a070fcef000000  ......-..p......
-  // On 32-bit machines, there are still 16 bytes per line but addresses and
-  // words are of course presented differently.
-  uintptr_t* data_ptr = data;
-  size_t current = 0;
-  size_t total_bytes = start + bytes;
-  for (size_t line = 0; line < MEMORY_BYTES_TO_DUMP / MEMORY_BYTES_PER_LINE; line++) {
-    std::string logline;
-    android::base::StringAppendF(&logline, "    %" PRIPTR, addr);
-
-    addr += MEMORY_BYTES_PER_LINE;
-    std::string ascii;
-    for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
-      if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
-        android::base::StringAppendF(&logline, " %" PRIPTR, *data_ptr);
-
-        // Fill out the ascii string from the data.
-        uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr);
-        for (size_t val = 0; val < sizeof(uintptr_t); val++, ptr++) {
-          if (*ptr >= 0x20 && *ptr < 0x7f) {
-            ascii += *ptr;
-          } else {
-            ascii += '.';
-          }
-        }
-        data_ptr++;
-      } else {
-        logline += ' ' + std::string(sizeof(uintptr_t) * 2, '-');
-        ascii += std::string(sizeof(uintptr_t), '.');
-      }
-      current += sizeof(uintptr_t);
-    }
-    _LOG(log, logtype::MEMORY, "%s  %s\n", logline.c_str(), ascii.c_str());
-  }
-}
diff --git a/debuggerd/utility.h b/debuggerd/utility.h
deleted file mode 100644
index cd01188..0000000
--- a/debuggerd/utility.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/* system/debuggerd/utility.h
-**
-** Copyright 2008, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#ifndef _DEBUGGERD_UTILITY_H
-#define _DEBUGGERD_UTILITY_H
-
-#include <stdbool.h>
-#include <sys/types.h>
-
-#include <string>
-
-#include <backtrace/Backtrace.h>
-
-// Figure out the abi based on defined macros.
-#if defined(__arm__)
-#define ABI_STRING "arm"
-#elif defined(__aarch64__)
-#define ABI_STRING "arm64"
-#elif defined(__mips__) && !defined(__LP64__)
-#define ABI_STRING "mips"
-#elif defined(__mips__) && defined(__LP64__)
-#define ABI_STRING "mips64"
-#elif defined(__i386__)
-#define ABI_STRING "x86"
-#elif defined(__x86_64__)
-#define ABI_STRING "x86_64"
-#else
-#error "Unsupported ABI"
-#endif
-
-
-struct log_t{
-    // Tombstone file descriptor.
-    int tfd;
-    // Data to be sent to the Activity Manager.
-    std::string* amfd_data;
-    // The tid of the thread that crashed.
-    pid_t crashed_tid;
-    // The tid of the thread we are currently working with.
-    pid_t current_tid;
-    // logd daemon crash, can block asking for logcat data, allow suppression.
-    bool should_retrieve_logcat;
-
-    log_t()
-        : tfd(-1), amfd_data(nullptr), crashed_tid(-1), current_tid(-1),
-          should_retrieve_logcat(true) {}
-};
-
-// List of types of logs to simplify the logging decision in _LOG
-enum logtype {
-  HEADER,
-  THREAD,
-  REGISTERS,
-  FP_REGISTERS,
-  BACKTRACE,
-  MAPS,
-  MEMORY,
-  STACK,
-  LOGS
-};
-
-// Log information onto the tombstone.
-void _LOG(log_t* log, logtype ltype, const char *fmt, ...)
-        __attribute__ ((format(printf, 3, 4)));
-
-int wait_for_signal(pid_t tid, int* total_sleep_time_usec);
-
-void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...);
-
-#endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/x86_64/machine.cpp b/debuggerd/x86_64/machine.cpp
deleted file mode 100644
index fc86bc2..0000000
--- a/debuggerd/x86_64/machine.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-** Copyright 2013, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "DEBUG"
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/ptrace.h>
-#include <string.h>
-#include <sys/user.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "machine.h"
-#include "utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  struct user_regs_struct r;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rax), "memory near rax:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rbx), "memory near rbx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rcx), "memory near rcx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdx), "memory near rdx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rsi), "memory near rsi:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdi), "memory near rdi:");
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rip), "code around rip:");
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  struct user_regs_struct r;
-  if (ptrace(PTRACE_GETREGS, tid, 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, "    rax %016lx  rbx %016lx  rcx %016lx  rdx %016lx\n",
-       r.rax, r.rbx, r.rcx, r.rdx);
-  _LOG(log, logtype::REGISTERS, "    rsi %016lx  rdi %016lx\n",
-       r.rsi, r.rdi);
-  _LOG(log, logtype::REGISTERS, "    r8  %016lx  r9  %016lx  r10 %016lx  r11 %016lx\n",
-       r.r8, r.r9, r.r10, r.r11);
-  _LOG(log, logtype::REGISTERS, "    r12 %016lx  r13 %016lx  r14 %016lx  r15 %016lx\n",
-       r.r12, r.r13, r.r14, r.r15);
-  _LOG(log, logtype::REGISTERS, "    cs  %016lx  ss  %016lx\n",
-       r.cs, r.ss);
-  _LOG(log, logtype::REGISTERS, "    rip %016lx  rbp %016lx  rsp %016lx  eflags %016lx\n",
-       r.rip, r.rbp, r.rsp, r.eflags);
-}
diff --git a/demangle/.clang-format b/demangle/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/demangle/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/demangle/Android.bp b/demangle/Android.bp
new file mode 100644
index 0000000..96ab57d
--- /dev/null
+++ b/demangle/Android.bp
@@ -0,0 +1,74 @@
+//
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_defaults {
+    name: "libdemangle_defaults",
+
+    host_supported: true,
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+}
+
+cc_library {
+    name: "libdemangle",
+    defaults: ["libdemangle_defaults"],
+
+    srcs: [
+        "Demangler.cpp",
+    ],
+
+    local_include_dirs: [
+       "include",
+    ],
+
+    export_include_dirs: [
+       "include",
+    ],
+}
+
+cc_binary {
+    name: "demangle",
+    defaults: ["libdemangle_defaults"],
+    srcs: ["demangle.cpp"],
+    host_supported: true,
+
+    shared_libs: ["libdemangle"],
+}
+
+//-------------------------------------------------------------------------
+// Unit Tests
+//-------------------------------------------------------------------------
+cc_test {
+    name: "libdemangle_test",
+    defaults: ["libdemangle_defaults"],
+
+    srcs: [
+        "DemangleTest.cpp",
+    ],
+
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+
+    shared_libs: [
+        "libdemangle",
+    ],
+}
diff --git a/demangle/DemangleTest.cpp b/demangle/DemangleTest.cpp
new file mode 100644
index 0000000..fb68119
--- /dev/null
+++ b/demangle/DemangleTest.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 <stdlib.h>
+
+#include <gtest/gtest.h>
+
+#include <demangle.h>
+
+#include "Demangler.h"
+
+TEST(DemangleTest, VoidArgumentTest) {
+  Demangler demangler;
+
+  ASSERT_EQ("func()", demangler.Parse("_ZN4funcEv"));
+  ASSERT_EQ("func(void&)", demangler.Parse("_ZN4funcERv"));
+  ASSERT_EQ("func(void, void)", demangler.Parse("_ZN4funcEvv"));
+  ASSERT_EQ("func(void*)", demangler.Parse("_ZN4funcEPv"));
+  ASSERT_EQ("func(void const)", demangler.Parse("_ZN4funcEKv"));
+  ASSERT_EQ("func(void volatile)", demangler.Parse("_ZN4funcEVv"));
+}
+
+TEST(DemangleTest, ArgumentModifiers) {
+  Demangler demangler;
+
+  ASSERT_EQ("func(char)", demangler.Parse("_ZN4funcEc"));
+  ASSERT_EQ("func(char*)", demangler.Parse("_ZN4funcEPc"));
+  ASSERT_EQ("func(char**)", demangler.Parse("_ZN4funcEPPc"));
+  ASSERT_EQ("func(char***)", demangler.Parse("_ZN4funcEPPPc"));
+  ASSERT_EQ("func(char&)", demangler.Parse("_ZN4funcERc"));
+  ASSERT_EQ("func(char*&)", demangler.Parse("_ZN4funcERPc"));
+  ASSERT_EQ("func(char&)", demangler.Parse("_ZN4funcERRc"));
+  ASSERT_EQ("func(char*&*)", demangler.Parse("_ZN4funcEPRPc"));
+  ASSERT_EQ("func(char**&)", demangler.Parse("_ZN4funcERRPPc"));
+  ASSERT_EQ("func(char const)", demangler.Parse("_ZN4funcEKc"));
+  ASSERT_EQ("func(char volatile)", demangler.Parse("_ZN4funcEVc"));
+  ASSERT_EQ("func(char volatile const)", demangler.Parse("_ZN4funcEKVc"));
+  ASSERT_EQ("func(char const volatile)", demangler.Parse("_ZN4funcEVKc"));
+  ASSERT_EQ("func(char const* volatile&)", demangler.Parse("_ZN4funcERVPKc"));
+  ASSERT_EQ("func(void, char, short)", demangler.Parse("_ZN4funcEvcs"));
+  ASSERT_EQ("func(void*, char&, short&*)", demangler.Parse("_ZN4funcEPvRcPRs"));
+}
+
+TEST(DemangleTest, FunctionModifiers) {
+  Demangler demangler;
+
+  ASSERT_EQ("func() const", demangler.Parse("_ZNK4funcEv"));
+  ASSERT_EQ("func() volatile", demangler.Parse("_ZNV4funcEv"));
+  ASSERT_EQ("func() volatile const", demangler.Parse("_ZNKV4funcEv"));
+  ASSERT_EQ("func() const volatile", demangler.Parse("_ZNVK4funcEv"));
+}
+
+TEST(DemangleTest, MultiplePartsInName) {
+  Demangler demangler;
+
+  ASSERT_EQ("one::two()", demangler.Parse("_ZN3one3twoEv"));
+  ASSERT_EQ("one::two::three()", demangler.Parse("_ZN3one3two5threeEv"));
+  ASSERT_EQ("one::two::three::four()", demangler.Parse("_ZN3one3two5three4fourEv"));
+  ASSERT_EQ("one::two::three::four::five()", demangler.Parse("_ZN3one3two5three4four4fiveEv"));
+  ASSERT_EQ("one(two::three::four::five)", demangler.Parse("_ZN3oneEN3two5three4four4fiveE"));
+}
+
+TEST(DemangleTest, AnonymousNamespace) {
+  Demangler demangler;
+
+  ASSERT_EQ("(anonymous namespace)::two()", demangler.Parse("_ZN12_GLOBAL__N_13twoEv"));
+  ASSERT_EQ("one::two((anonymous namespace))", demangler.Parse("_ZN3one3twoE12_GLOBAL__N_1"));
+}
+
+TEST(DemangleTest, DestructorValues) {
+  Demangler demangler;
+
+  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD0Ev"));
+  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD1Ev"));
+  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD2Ev"));
+  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD5Ev"));
+  ASSERT_EQ("one::two::three::~three()", demangler.Parse("_ZN3one3two5threeD0Ev"));
+
+  ASSERT_EQ("_ZN3one3twoD3Ev", demangler.Parse("_ZN3one3twoD3Ev"));
+  ASSERT_EQ("_ZN3one3twoD4Ev", demangler.Parse("_ZN3one3twoD4Ev"));
+  ASSERT_EQ("_ZN3one3twoD6Ev", demangler.Parse("_ZN3one3twoD6Ev"));
+  ASSERT_EQ("_ZN3one3twoD7Ev", demangler.Parse("_ZN3one3twoD7Ev"));
+  ASSERT_EQ("_ZN3one3twoD8Ev", demangler.Parse("_ZN3one3twoD8Ev"));
+  ASSERT_EQ("_ZN3one3twoD9Ev", demangler.Parse("_ZN3one3twoD9Ev"));
+
+  ASSERT_EQ("one::two<three::four>::~two()", demangler.Parse("_ZN3one3twoIN5three4fourEED2Ev"));
+}
+
+TEST(DemangleTest, ConstructorValues) {
+  Demangler demangler;
+
+  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC1Ev"));
+  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC2Ev"));
+  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC3Ev"));
+  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC5Ev"));
+  ASSERT_EQ("one::two::three::three()", demangler.Parse("_ZN3one3two5threeC1Ev"));
+
+  ASSERT_EQ("_ZN3one3twoC0Ev", demangler.Parse("_ZN3one3twoC0Ev"));
+  ASSERT_EQ("_ZN3one3twoC4Ev", demangler.Parse("_ZN3one3twoC4Ev"));
+  ASSERT_EQ("_ZN3one3twoC6Ev", demangler.Parse("_ZN3one3twoC6Ev"));
+  ASSERT_EQ("_ZN3one3twoC7Ev", demangler.Parse("_ZN3one3twoC7Ev"));
+  ASSERT_EQ("_ZN3one3twoC8Ev", demangler.Parse("_ZN3one3twoC8Ev"));
+  ASSERT_EQ("_ZN3one3twoC9Ev", demangler.Parse("_ZN3one3twoC9Ev"));
+
+  ASSERT_EQ("one::two<three::four>::two()", demangler.Parse("_ZN3one3twoIN5three4fourEEC1Ev"));
+}
+
+TEST(DemangleTest, OperatorValues) {
+  Demangler demangler;
+
+  ASSERT_EQ("operator&&()", demangler.Parse("_Zaav"));
+  ASSERT_EQ("operator&()", demangler.Parse("_Zadv"));
+  ASSERT_EQ("operator&()", demangler.Parse("_Zanv"));
+  ASSERT_EQ("operator&=()", demangler.Parse("_ZaNv"));
+  ASSERT_EQ("operator=()", demangler.Parse("_ZaSv"));
+  ASSERT_EQ("operator()()", demangler.Parse("_Zclv"));
+  ASSERT_EQ("operator,()", demangler.Parse("_Zcmv"));
+  ASSERT_EQ("operator~()", demangler.Parse("_Zcov"));
+  ASSERT_EQ("operator delete[]()", demangler.Parse("_Zdav"));
+  ASSERT_EQ("operator*()", demangler.Parse("_Zdev"));
+  ASSERT_EQ("operator delete()", demangler.Parse("_Zdlv"));
+  ASSERT_EQ("operator/()", demangler.Parse("_Zdvv"));
+  ASSERT_EQ("operator/=()", demangler.Parse("_ZdVv"));
+  ASSERT_EQ("operator^()", demangler.Parse("_Zeov"));
+  ASSERT_EQ("operator^=()", demangler.Parse("_ZeOv"));
+  ASSERT_EQ("operator==()", demangler.Parse("_Zeqv"));
+  ASSERT_EQ("operator>=()", demangler.Parse("_Zgev"));
+  ASSERT_EQ("operator>()", demangler.Parse("_Zgtv"));
+  ASSERT_EQ("operator[]()", demangler.Parse("_Zixv"));
+  ASSERT_EQ("operator<=()", demangler.Parse("_Zlev"));
+  ASSERT_EQ("operator<<()", demangler.Parse("_Zlsv"));
+  ASSERT_EQ("operator<<=()", demangler.Parse("_ZlSv"));
+  ASSERT_EQ("operator<()", demangler.Parse("_Zltv"));
+  ASSERT_EQ("operator-()", demangler.Parse("_Zmiv"));
+  ASSERT_EQ("operator-=()", demangler.Parse("_ZmIv"));
+  ASSERT_EQ("operator*()", demangler.Parse("_Zmlv"));
+  ASSERT_EQ("operator*=()", demangler.Parse("_ZmLv"));
+  ASSERT_EQ("operator--()", demangler.Parse("_Zmmv"));
+  ASSERT_EQ("operator new[]()", demangler.Parse("_Znav"));
+  ASSERT_EQ("operator!=()", demangler.Parse("_Znev"));
+  ASSERT_EQ("operator-()", demangler.Parse("_Zngv"));
+  ASSERT_EQ("operator!()", demangler.Parse("_Zntv"));
+  ASSERT_EQ("operator new()", demangler.Parse("_Znwv"));
+  ASSERT_EQ("operator||()", demangler.Parse("_Zoov"));
+  ASSERT_EQ("operator|()", demangler.Parse("_Zorv"));
+  ASSERT_EQ("operator|=()", demangler.Parse("_ZoRv"));
+  ASSERT_EQ("operator->*()", demangler.Parse("_Zpmv"));
+  ASSERT_EQ("operator+()", demangler.Parse("_Zplv"));
+  ASSERT_EQ("operator+=()", demangler.Parse("_ZpLv"));
+  ASSERT_EQ("operator++()", demangler.Parse("_Zppv"));
+  ASSERT_EQ("operator+()", demangler.Parse("_Zpsv"));
+  ASSERT_EQ("operator->()", demangler.Parse("_Zptv"));
+  ASSERT_EQ("operator?()", demangler.Parse("_Zquv"));
+  ASSERT_EQ("operator%()", demangler.Parse("_Zrmv"));
+  ASSERT_EQ("operator%=()", demangler.Parse("_ZrMv"));
+  ASSERT_EQ("operator>>()", demangler.Parse("_Zrsv"));
+  ASSERT_EQ("operator>>=()", demangler.Parse("_ZrSv"));
+
+  // Spot check using an operator as part of function name.
+  ASSERT_EQ("operator&&()", demangler.Parse("_ZNaaEv"));
+  ASSERT_EQ("operator++()", demangler.Parse("_ZNppEv"));
+  ASSERT_EQ("one::operator++()", demangler.Parse("_ZN3oneppEv"));
+
+  // Spot check using an operator in an argument name.
+  ASSERT_EQ("operator+(operator|=)", demangler.Parse("_ZNpsENoRE"));
+  ASSERT_EQ("operator==()", demangler.Parse("_Zeqv"));
+  ASSERT_EQ("one(arg1::operator|=, arg2::operator==)",
+            demangler.Parse("_ZN3oneEN4arg1oREN4arg2eqE"));
+}
+
+TEST(DemangleTest, FunctionStartsWithNumber) {
+  Demangler demangler;
+
+  ASSERT_EQ("value(char, int)", demangler.Parse("_Z5valueci"));
+  ASSERT_EQ("abcdefjklmn(signed char)", demangler.Parse("_Z11abcdefjklmna"));
+  ASSERT_EQ("value(one, signed char)", demangler.Parse("_Z5value3onea"));
+}
+
+TEST(DemangleTest, StdTypes) {
+  Demangler demangler;
+
+  ASSERT_EQ("std::one", demangler.Parse("_ZNSt3oneE"));
+  ASSERT_EQ("std::one(std::two)", demangler.Parse("_ZNSt3oneESt3two"));
+  ASSERT_EQ("std::std::one(std::two)", demangler.Parse("_ZNStSt3oneESt3two"));
+  ASSERT_EQ("std()", demangler.Parse("_ZNStEv"));
+  ASSERT_EQ("one::std::std::two::~two(one::std::std::two)",
+            demangler.Parse("_ZN3oneStSt3twoD0ES0_"));
+
+  ASSERT_EQ("std::allocator", demangler.Parse("_ZNSaE"));
+  ASSERT_EQ("std::basic_string", demangler.Parse("_ZNSbE"));
+  ASSERT_EQ("_ZNScE", demangler.Parse("_ZNScE"));
+  ASSERT_EQ("std::iostream", demangler.Parse("_ZNSdE"));
+  ASSERT_EQ("_ZNSeE", demangler.Parse("_ZNSeE"));
+  ASSERT_EQ("_ZNSfE", demangler.Parse("_ZNSfE"));
+  ASSERT_EQ("_ZNSgE", demangler.Parse("_ZNSgE"));
+  ASSERT_EQ("_ZNShE", demangler.Parse("_ZNShE"));
+  ASSERT_EQ("std::istream", demangler.Parse("_ZNSiE"));
+  ASSERT_EQ("_ZNSjE", demangler.Parse("_ZNSjE"));
+  ASSERT_EQ("_ZNSkE", demangler.Parse("_ZNSkE"));
+  ASSERT_EQ("_ZNSlE", demangler.Parse("_ZNSlE"));
+  ASSERT_EQ("_ZNSmE", demangler.Parse("_ZNSmE"));
+  ASSERT_EQ("_ZNSnE", demangler.Parse("_ZNSnE"));
+  ASSERT_EQ("std::ostream", demangler.Parse("_ZNSoE"));
+  ASSERT_EQ("_ZNSpE", demangler.Parse("_ZNSpE"));
+  ASSERT_EQ("_ZNSqE", demangler.Parse("_ZNSqE"));
+  ASSERT_EQ("_ZNSrE", demangler.Parse("_ZNSrE"));
+  ASSERT_EQ("std::string", demangler.Parse("_ZNSsE"));
+  ASSERT_EQ("_ZNSuE", demangler.Parse("_ZNSuE"));
+  ASSERT_EQ("_ZNSvE", demangler.Parse("_ZNSvE"));
+  ASSERT_EQ("_ZNSwE", demangler.Parse("_ZNSwE"));
+  ASSERT_EQ("_ZNSxE", demangler.Parse("_ZNSxE"));
+  ASSERT_EQ("_ZNSyE", demangler.Parse("_ZNSyE"));
+  ASSERT_EQ("_ZNSzE", demangler.Parse("_ZNSzE"));
+}
+
+TEST(DemangleTest, SingleLetterArguments) {
+  Demangler demangler;
+
+  ASSERT_EQ("func(signed char)", demangler.Parse("_ZN4funcEa"));
+  ASSERT_EQ("func(bool)", demangler.Parse("_ZN4funcEb"));
+  ASSERT_EQ("func(char)", demangler.Parse("_ZN4funcEc"));
+  ASSERT_EQ("func(double)", demangler.Parse("_ZN4funcEd"));
+  ASSERT_EQ("func(long double)", demangler.Parse("_ZN4funcEe"));
+  ASSERT_EQ("func(float)", demangler.Parse("_ZN4funcEf"));
+  ASSERT_EQ("func(__float128)", demangler.Parse("_ZN4funcEg"));
+  ASSERT_EQ("func(unsigned char)", demangler.Parse("_ZN4funcEh"));
+  ASSERT_EQ("func(int)", demangler.Parse("_ZN4funcEi"));
+  ASSERT_EQ("func(unsigned int)", demangler.Parse("_ZN4funcEj"));
+  ASSERT_EQ("_ZN4funcEk", demangler.Parse("_ZN4funcEk"));
+  ASSERT_EQ("func(long)", demangler.Parse("_ZN4funcEl"));
+  ASSERT_EQ("func(unsigned long)", demangler.Parse("_ZN4funcEm"));
+  ASSERT_EQ("func(__int128)", demangler.Parse("_ZN4funcEn"));
+  ASSERT_EQ("func(unsigned __int128)", demangler.Parse("_ZN4funcEo"));
+  ASSERT_EQ("_ZN4funcEp", demangler.Parse("_ZN4funcEp"));
+  ASSERT_EQ("_ZN4funcEq", demangler.Parse("_ZN4funcEq"));
+  ASSERT_EQ("_ZN4funcEr", demangler.Parse("_ZN4funcEr"));
+  ASSERT_EQ("func(short)", demangler.Parse("_ZN4funcEs"));
+  ASSERT_EQ("func(unsigned short)", demangler.Parse("_ZN4funcEt"));
+  ASSERT_EQ("_ZN4funcEu", demangler.Parse("_ZN4funcEu"));
+  ASSERT_EQ("func()", demangler.Parse("_ZN4funcEv"));
+  ASSERT_EQ("func(wchar_t)", demangler.Parse("_ZN4funcEw"));
+  ASSERT_EQ("func(long long)", demangler.Parse("_ZN4funcEx"));
+  ASSERT_EQ("func(unsigned long long)", demangler.Parse("_ZN4funcEy"));
+  ASSERT_EQ("func(...)", demangler.Parse("_ZN4funcEz"));
+}
+
+TEST(DemangleTest, DArguments) {
+  Demangler demangler;
+
+  ASSERT_EQ("func(auto)", demangler.Parse("_ZN4funcEDa"));
+  ASSERT_EQ("_ZN4funcEDb", demangler.Parse("_ZN4funcEDb"));
+  ASSERT_EQ("_ZN4funcEDc", demangler.Parse("_ZN4funcEDc"));
+  ASSERT_EQ("func(decimal64)", demangler.Parse("_ZN4funcEDd"));
+  ASSERT_EQ("func(decimal128)", demangler.Parse("_ZN4funcEDe"));
+  ASSERT_EQ("func(decimal32)", demangler.Parse("_ZN4funcEDf"));
+  ASSERT_EQ("_ZN4funcEDg", demangler.Parse("_ZN4funcEDg"));
+  ASSERT_EQ("func(half)", demangler.Parse("_ZN4funcEDh"));
+  ASSERT_EQ("func(char32_t)", demangler.Parse("_ZN4funcEDi"));
+  ASSERT_EQ("_ZN4funcEDj", demangler.Parse("_ZN4funcEDj"));
+  ASSERT_EQ("_ZN4funcEDk", demangler.Parse("_ZN4funcEDk"));
+  ASSERT_EQ("_ZN4funcEDl", demangler.Parse("_ZN4funcEDl"));
+  ASSERT_EQ("_ZN4funcEDm", demangler.Parse("_ZN4funcEDm"));
+  ASSERT_EQ("func(decltype(nullptr))", demangler.Parse("_ZN4funcEDn"));
+  ASSERT_EQ("_ZN4funcEDo", demangler.Parse("_ZN4funcEDo"));
+  ASSERT_EQ("_ZN4funcEDp", demangler.Parse("_ZN4funcEDp"));
+  ASSERT_EQ("_ZN4funcEDq", demangler.Parse("_ZN4funcEDq"));
+  ASSERT_EQ("_ZN4funcEDr", demangler.Parse("_ZN4funcEDr"));
+  ASSERT_EQ("func(char16_t)", demangler.Parse("_ZN4funcEDs"));
+  ASSERT_EQ("_ZN4funcEDt", demangler.Parse("_ZN4funcEDt"));
+  ASSERT_EQ("_ZN4funcEDu", demangler.Parse("_ZN4funcEDu"));
+  ASSERT_EQ("_ZN4funcEDv", demangler.Parse("_ZN4funcEDv"));
+  ASSERT_EQ("_ZN4funcEDw", demangler.Parse("_ZN4funcEDw"));
+  ASSERT_EQ("_ZN4funcEDx", demangler.Parse("_ZN4funcEDx"));
+  ASSERT_EQ("_ZN4funcEDy", demangler.Parse("_ZN4funcEDy"));
+  ASSERT_EQ("_ZN4funcEDz", demangler.Parse("_ZN4funcEDz"));
+}
+
+TEST(DemangleTest, FunctionArguments) {
+  Demangler demangler;
+
+  ASSERT_EQ("func(char ())", demangler.Parse("_ZN4funcEFcvE"));
+  ASSERT_EQ("func(char (*)())", demangler.Parse("_ZN4funcEPFcvE"));
+  ASSERT_EQ("func(char (&)())", demangler.Parse("_ZN4funcERFcvE"));
+  ASSERT_EQ("func(char (&)())", demangler.Parse("_ZN4funcERFcvE"));
+  ASSERT_EQ("func(char (*&)())", demangler.Parse("_ZN4funcERPFcvE"));
+  ASSERT_EQ("func(char (*)(int) const)", demangler.Parse("_ZN4funcEPKFciE"));
+  ASSERT_EQ("func(char (&)() const)", demangler.Parse("_ZN4funcERKFcvE"));
+  ASSERT_EQ("func(char (&)() volatile)", demangler.Parse("_ZN4funcERVFcvE"));
+  ASSERT_EQ("func(char (&)() volatile const)", demangler.Parse("_ZN4funcERKVFcvE"));
+  ASSERT_EQ("func(char (&)() const volatile)", demangler.Parse("_ZN4funcERVKFcvE"));
+  ASSERT_EQ("func(char (&)(int, signed char) const)", demangler.Parse("_ZN4funcERKFciaE"));
+  ASSERT_EQ("fake(char (&* volatile const)(void, void, signed char), signed char)",
+            demangler.Parse("_ZN4fakeEKVPRFcvvaEa"));
+}
+
+TEST(DemangleTest, TemplateFunction) {
+  Demangler demangler;
+
+  ASSERT_EQ("one<char>", demangler.Parse("_ZN3oneIcEE"));
+  ASSERT_EQ("one<void>", demangler.Parse("_ZN3oneIvEE"));
+  ASSERT_EQ("one<void*>", demangler.Parse("_ZN3oneIPvEE"));
+  ASSERT_EQ("one<void const>", demangler.Parse("_ZN3oneIKvEE"));
+  ASSERT_EQ("one<char, int, bool>", demangler.Parse("_ZN3oneIcibEE"));
+  ASSERT_EQ("one::two<three>", demangler.Parse("_ZN3one3twoIN5threeEEE"));
+  ASSERT_EQ("one<char, int, two::three>", demangler.Parse("_ZN3oneIciN3two5threeEEE"));
+  // Template within templates.
+  ASSERT_EQ("one::two<three<char, int>>", demangler.Parse("_ZN3one3twoIN5threeIciEEEE"));
+  ASSERT_EQ("one::two<three<char, four<int>>>", demangler.Parse("_ZN3one3twoIN5threeIcN4fourIiEEEEEE"));
+}
+
+TEST(DemangleTest, TemplateArguments) {
+  Demangler demangler;
+
+  ASSERT_EQ("one(two<char>)", demangler.Parse("_ZN3oneE3twoIcE"));
+  ASSERT_EQ("one(two<char, void>)", demangler.Parse("_ZN3oneE3twoIcvE"));
+  ASSERT_EQ("one(two<char, void, three<four, int>>)",
+            demangler.Parse("_ZN3oneE3twoIcv5threeI4fouriEE"));
+}
+
+TEST(DemangleTest, SubstitutionUnderscore) {
+  Demangler demangler;
+
+  ASSERT_EQ("a::a", demangler.Parse("_ZN1aS_E"));
+  ASSERT_EQ("one::one", demangler.Parse("_ZN3oneS_E"));
+  ASSERT_EQ("one::two::one", demangler.Parse("_ZN3one3twoS_E"));
+  ASSERT_EQ("one::two::three::one", demangler.Parse("_ZN3one3two5threeS_E"));
+  ASSERT_EQ("one::two(one)", demangler.Parse("_ZN3one3twoES_"));
+  ASSERT_EQ("one::two(three::one)", demangler.Parse("_ZN3one3twoEN5threeS_E"));
+
+  // Special case that St is part of the saved value used in the substitution.
+  ASSERT_EQ("std::one::std::one", demangler.Parse("_ZNSt3oneS_E"));
+
+  // Multiple substitutions in the string.
+  ASSERT_EQ("one::one(one, one)", demangler.Parse("_ZN3oneS_ES_S_"));
+  ASSERT_EQ("std::one::two::std::one(std::one)", demangler.Parse("_ZNSt3one3twoS_ES_"));
+}
+
+TEST(DemangleTest, SubstitutionByNumber) {
+  Demangler demangler;
+
+  // Basic substitution.
+  ASSERT_EQ("a::b::c(a::b)", demangler.Parse("_ZN1a1b1cES0_"));
+  ASSERT_EQ("_ZN1a1b1cES1_", demangler.Parse("_ZN1a1b1cES1_"));
+  ASSERT_EQ("a::b::c::d(a::b::c)", demangler.Parse("_ZN1a1b1c1dES1_"));
+  ASSERT_EQ("a::b::c::d::e::f::g::h::i::j::k::l::m::n::o::p::q(a::b::c::d::e::f::g::h::i::j::k::l)",
+            demangler.Parse("_ZN1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1qESA_"));
+  ASSERT_EQ("a::b::c::d::e::f::g::h::i::j::k::l::m::n::o::p::q(a::b::c::d::e::f::g::h::i::j::k::l::m)",
+            demangler.Parse("_ZN1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1qESB_"));
+
+  // Verify argument modifiers are included in substitution list.
+  ASSERT_EQ("one::two(char&* volatile const, char&)", demangler.Parse("_ZN3one3twoEKVPRcS0_"));
+  ASSERT_EQ("one::two(char&* volatile const, char&*)", demangler.Parse("_ZN3one3twoEKVPRcS1_"));
+  ASSERT_EQ("one::two(char&* volatile const, char&* volatile const)",
+            demangler.Parse("_ZN3one3twoEKVPRcS2_"));
+  ASSERT_EQ("one::two(int&* volatile* const, int&)", demangler.Parse("_ZN3one3twoEKPVPRiS0_"));
+  ASSERT_EQ("one::two(int&* volatile const, int&*)", demangler.Parse("_ZN3one3twoEKVPRiS1_"));
+  ASSERT_EQ("one::two(int&* volatile const, int&* volatile const)",
+            demangler.Parse("_ZN3one3twoEKVPRiS2_"));
+
+  // Verify Constructor/Destructor does properly save from function name.
+  ASSERT_EQ("_ZN1a1bES0_", demangler.Parse("_ZN1a1bES0_"));
+  ASSERT_EQ("a::b::b(a::b)", demangler.Parse("_ZN1a1bC1ES0_"));
+  ASSERT_EQ("a::b::~b(a::b)", demangler.Parse("_ZN1a1bD0ES0_"));
+
+  // Make sure substitution values are not saved.
+  ASSERT_EQ("a::b::b(a::b, char*, char*)", demangler.Parse("_ZN1a1bC1ES0_PcS1_"));
+}
+
+TEST(DemangleTest, ComplexSubstitution) {
+  Demangler demangler;
+
+  ASSERT_EQ("one::two<one::three>::two()", demangler.Parse("_ZN3one3twoINS_5threeEEC1Ev"));
+  ASSERT_EQ("one::two::two(one::two const&, bool, one::three*)",
+            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE"));
+  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two*)",
+            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS0_"));
+  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two::three*)",
+            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS1_"));
+  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two::three::four*)",
+            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS2_"));
+  ASSERT_EQ("one::two::three::four<one::five>::~four(one::five*)",
+            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS3_"));
+}
+
+TEST(DemangleTest, StringTooLong) {
+  Demangler demangler;
+
+  ASSERT_EQ("_ZN3one3twoC2ERKS0_bPNS_5threeE",
+            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 10));
+  ASSERT_EQ("_ZN3one3twoC2ERKS0_bPNS_5threeE",
+            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 30));
+  ASSERT_EQ("one::two::two(one::two const&, bool, one::three*)",
+            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 31));
+
+  // Check the length check only occurs after the two letter value
+  // has been processed.
+  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 15));
+  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 14));
+  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 13));
+  ASSERT_EQ("_ZN3one3twoEDa", demangler.Parse("_ZN3one3twoEDa", 12));
+}
+
+TEST(DemangleTest, demangle) {
+  std::string str;
+
+  str = demangle("_ZN1a1b1cES0_");
+  ASSERT_EQ("a::b::c(a::b)", str);
+
+  str = demangle("_");
+  ASSERT_EQ("_", str);
+
+  str = demangle("_Z");
+  ASSERT_EQ("_Z", str);
+
+  str = demangle("_Za");
+  ASSERT_EQ("_Za", str);
+
+  str = demangle("_Zaa");
+  ASSERT_EQ("operator&&", str);
+
+  str = demangle("Xa");
+  ASSERT_EQ("Xa", str);
+}
diff --git a/demangle/Demangler.cpp b/demangle/Demangler.cpp
new file mode 100644
index 0000000..77cfd3b
--- /dev/null
+++ b/demangle/Demangler.cpp
@@ -0,0 +1,746 @@
+/*
+ * 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 <cctype>
+#include <stack>
+#include <string>
+#include <vector>
+
+#include "Demangler.h"
+
+constexpr const char* Demangler::kTypes[];
+constexpr const char* Demangler::kDTypes[];
+constexpr const char* Demangler::kSTypes[];
+
+void Demangler::Save(const std::string& str, bool is_name) {
+  saves_.push_back(str);
+  last_save_name_ = is_name;
+}
+
+std::string Demangler::GetArgumentsString() {
+  size_t num_args = cur_state_.args.size();
+  std::string arg_str;
+  if (num_args > 0) {
+    arg_str = cur_state_.args[0];
+    for (size_t i = 1; i < num_args; i++) {
+      arg_str += ", " + cur_state_.args[i];
+    }
+  }
+  return arg_str;
+}
+
+const char* Demangler::AppendOperatorString(const char* name) {
+  const char* oper = nullptr;
+  switch (*name) {
+  case 'a':
+    name++;
+    switch (*name) {
+    case 'a':
+      oper = "operator&&";
+      break;
+    case 'd':
+    case 'n':
+      oper = "operator&";
+      break;
+    case 'N':
+      oper = "operator&=";
+      break;
+    case 'S':
+      oper = "operator=";
+      break;
+    }
+    break;
+  case 'c':
+    name++;
+    switch (*name) {
+    case 'l':
+      oper = "operator()";
+      break;
+    case 'm':
+      oper = "operator,";
+      break;
+    case 'o':
+      oper = "operator~";
+      break;
+    }
+    break;
+  case 'd':
+    name++;
+    switch (*name) {
+    case 'a':
+      oper = "operator delete[]";
+      break;
+    case 'e':
+      oper = "operator*";
+      break;
+    case 'l':
+      oper = "operator delete";
+      break;
+    case 'v':
+      oper = "operator/";
+      break;
+    case 'V':
+      oper = "operator/=";
+      break;
+    }
+    break;
+  case 'e':
+    name++;
+    switch (*name) {
+    case 'o':
+      oper = "operator^";
+      break;
+    case 'O':
+      oper = "operator^=";
+      break;
+    case 'q':
+      oper = "operator==";
+      break;
+    }
+    break;
+  case 'g':
+    name++;
+    switch (*name) {
+    case 'e':
+      oper = "operator>=";
+      break;
+    case 't':
+      oper = "operator>";
+      break;
+    }
+    break;
+  case 'i':
+    name++;
+    switch (*name) {
+    case 'x':
+      oper = "operator[]";
+      break;
+    }
+    break;
+  case 'l':
+    name++;
+    switch (*name) {
+    case 'e':
+      oper = "operator<=";
+      break;
+    case 's':
+      oper = "operator<<";
+      break;
+    case 'S':
+      oper = "operator<<=";
+      break;
+    case 't':
+      oper = "operator<";
+      break;
+    }
+    break;
+  case 'm':
+    name++;
+    switch (*name) {
+    case 'i':
+      oper = "operator-";
+      break;
+    case 'I':
+      oper = "operator-=";
+      break;
+    case 'l':
+      oper = "operator*";
+      break;
+    case 'L':
+      oper = "operator*=";
+      break;
+    case 'm':
+      oper = "operator--";
+      break;
+    }
+    break;
+  case 'n':
+    name++;
+    switch (*name) {
+    case 'a':
+      oper = "operator new[]";
+      break;
+    case 'e':
+      oper = "operator!=";
+      break;
+    case 'g':
+      oper = "operator-";
+      break;
+    case 't':
+      oper = "operator!";
+      break;
+    case 'w':
+      oper = "operator new";
+      break;
+    }
+    break;
+  case 'o':
+    name++;
+    switch (*name) {
+    case 'o':
+      oper = "operator||";
+      break;
+    case 'r':
+      oper = "operator|";
+      break;
+    case 'R':
+      oper = "operator|=";
+      break;
+    }
+    break;
+  case 'p':
+    name++;
+    switch (*name) {
+    case 'm':
+      oper = "operator->*";
+      break;
+    case 'l':
+      oper = "operator+";
+      break;
+    case 'L':
+      oper = "operator+=";
+      break;
+    case 'p':
+      oper = "operator++";
+      break;
+    case 's':
+      oper = "operator+";
+      break;
+    case 't':
+      oper = "operator->";
+      break;
+    }
+    break;
+  case 'q':
+    name++;
+    switch (*name) {
+    case 'u':
+      oper = "operator?";
+      break;
+    }
+    break;
+  case 'r':
+    name++;
+    switch (*name) {
+    case 'm':
+      oper = "operator%";
+      break;
+    case 'M':
+      oper = "operator%=";
+      break;
+    case 's':
+      oper = "operator>>";
+      break;
+    case 'S':
+      oper = "operator>>=";
+      break;
+    }
+    break;
+  }
+  if (oper == nullptr) {
+    return nullptr;
+  }
+  AppendCurrent(oper);
+  cur_state_.last_save = oper;
+  return name + 1;
+}
+
+const char* Demangler::GetStringFromLength(const char* name, std::string* str) {
+  assert(std::isdigit(*name));
+
+  size_t length = *name - '0';
+  name++;
+  while (*name != '\0' && std::isdigit(*name)) {
+    length = length * 10 + *name - '0';
+    name++;
+  }
+
+  std::string read_str;
+  while (*name != '\0' && length != 0) {
+    read_str += *name;
+    name++;
+    length--;
+  }
+  if (length != 0) {
+    return nullptr;
+  }
+  // Special replacement of _GLOBAL__N_1 to (anonymous namespace).
+  if (read_str == "_GLOBAL__N_1") {
+    *str += "(anonymous namespace)";
+  } else {
+    *str += read_str;
+  }
+  return name;
+}
+
+void Demangler::AppendCurrent(const std::string& str) {
+  if (!cur_state_.str.empty()) {
+    cur_state_.str += "::";
+  }
+  cur_state_.str += str;
+}
+
+void Demangler::AppendCurrent(const char* str) {
+  if (!cur_state_.str.empty()) {
+    cur_state_.str += "::";
+  }
+  cur_state_.str += str;
+}
+
+const char* Demangler::ParseS(const char* name) {
+  if (std::islower(*name)) {
+    const char* type = kSTypes[*name - 'a'];
+    if (type == nullptr) {
+      return nullptr;
+    }
+    AppendCurrent(type);
+    return name + 1;
+  }
+
+  if (saves_.empty()) {
+    return nullptr;
+  }
+
+  if (*name == '_') {
+    last_save_name_ = false;
+    AppendCurrent(saves_[0]);
+    return name + 1;
+  }
+
+  bool isdigit = std::isdigit(*name);
+  if (!isdigit && !std::isupper(*name)) {
+    return nullptr;
+  }
+
+  size_t index;
+  if (isdigit) {
+    index = *name - '0' + 1;
+  } else {
+    index = *name - 'A' + 11;
+  }
+  name++;
+  if (*name != '_') {
+    return nullptr;
+  }
+
+  if (index >= saves_.size()) {
+    return nullptr;
+  }
+
+  last_save_name_ = false;
+  AppendCurrent(saves_[index]);
+  return name + 1;
+}
+
+const char* Demangler::ParseFunctionName(const char* name) {
+  if (*name == 'E') {
+    if (parse_funcs_.empty()) {
+      return nullptr;
+    }
+    parse_func_ = parse_funcs_.back();
+    parse_funcs_.pop_back();
+
+    // Remove the last saved part so that the full function name is not saved.
+    // But only if the last save was not something like a substitution.
+    if (!saves_.empty() && last_save_name_) {
+      saves_.pop_back();
+    }
+
+    function_name_ = cur_state_.str;
+    while (!cur_state_.suffixes.empty()) {
+      function_suffix_ += cur_state_.suffixes.back();
+      cur_state_.suffixes.pop_back();
+    }
+    cur_state_.Clear();
+
+    return name + 1;
+  }
+
+  return ParseComplexString(name);
+}
+
+const char* Demangler::ParseComplexArgument(const char* name) {
+  if (*name == 'E') {
+    if (parse_funcs_.empty()) {
+      return nullptr;
+    }
+    parse_func_ = parse_funcs_.back();
+    parse_funcs_.pop_back();
+
+    AppendArgument(cur_state_.str);
+    cur_state_.str.clear();
+
+    return name + 1;
+  }
+
+  return ParseComplexString(name);
+}
+
+void Demangler::FinalizeTemplate() {
+  std::string arg_str(GetArgumentsString());
+  cur_state_ = state_stack_.top();
+  state_stack_.pop();
+  cur_state_.str += '<' + arg_str + '>';
+}
+
+const char* Demangler::ParseComplexString(const char* name) {
+  if (*name == 'S') {
+    name++;
+    if (*name == 't') {
+      AppendCurrent("std");
+      return name + 1;
+    }
+    return ParseS(name);
+  }
+  if (*name == 'L') {
+    name++;
+    if (!std::isdigit(*name)) {
+      return nullptr;
+    }
+  }
+  if (std::isdigit(*name)) {
+    std::string str;
+    name = GetStringFromLength(name, &str);
+    if (name == nullptr) {
+      return name;
+    }
+    AppendCurrent(str);
+    Save(cur_state_.str, true);
+    cur_state_.last_save = std::move(str);
+    return name;
+  }
+  if (*name == 'D') {
+    name++;
+    if (saves_.empty() || (*name != '0' && *name != '1' && *name != '2'
+        && *name != '5')) {
+      return nullptr;
+    }
+    last_save_name_ = false;
+    AppendCurrent("~" + cur_state_.last_save);
+    return name + 1;
+  }
+  if (*name == 'C') {
+    name++;
+    if (saves_.empty() || (*name != '1' && *name != '2' && *name != '3'
+        && *name != '5')) {
+      return nullptr;
+    }
+    last_save_name_ = false;
+    AppendCurrent(cur_state_.last_save);
+    return name + 1;
+  }
+  if (*name == 'K') {
+    cur_state_.suffixes.push_back(" const");
+    return name + 1;
+  }
+  if (*name == 'V') {
+    cur_state_.suffixes.push_back(" volatile");
+    return name + 1;
+  }
+  if (*name == 'I') {
+    // Save the current argument state.
+    state_stack_.push(cur_state_);
+    cur_state_.Clear();
+
+    parse_funcs_.push_back(parse_func_);
+    parse_func_ = &Demangler::ParseTemplateArgumentsComplex;
+    return name + 1;
+  }
+  name = AppendOperatorString(name);
+  if (name != nullptr) {
+    Save(cur_state_.str, true);
+  }
+  return name;
+}
+
+void Demangler::AppendArgument(const std::string& str) {
+  std::string arg(str);
+  while (!cur_state_.suffixes.empty()) {
+    arg += cur_state_.suffixes.back();
+    cur_state_.suffixes.pop_back();
+    Save(arg, false);
+  }
+  cur_state_.args.push_back(arg);
+}
+
+const char* Demangler::ParseFunctionArgument(const char* name) {
+  if (*name == 'E') {
+    // The first argument is the function modifier.
+    // The second argument is the function type.
+    // The third argument is the return type of the function.
+    // The rest of the arguments are the function arguments.
+    size_t num_args = cur_state_.args.size();
+    if (num_args < 4) {
+      return nullptr;
+    }
+    std::string function_modifier = cur_state_.args[0];
+    std::string function_type = cur_state_.args[1];
+
+    std::string str = cur_state_.args[2] + ' ';
+    if (!cur_state_.args[1].empty()) {
+      str += '(' + cur_state_.args[1] + ')';
+    }
+
+    if (num_args == 4 && cur_state_.args[3] == "void") {
+      str += "()";
+    } else {
+      str += '(' + cur_state_.args[3];
+      for (size_t i = 4; i < num_args; i++) {
+        str += ", " + cur_state_.args[i];
+      }
+      str += ')';
+    }
+    str += cur_state_.args[0];
+
+    cur_state_ = state_stack_.top();
+    state_stack_.pop();
+    cur_state_.args.emplace_back(std::move(str));
+
+    parse_func_ = parse_funcs_.back();
+    parse_funcs_.pop_back();
+    return name + 1;
+  }
+  return ParseArguments(name);
+}
+
+const char* Demangler::ParseArguments(const char* name) {
+  switch (*name) {
+  case 'P':
+    cur_state_.suffixes.push_back("*");
+    return name + 1;
+
+  case 'R':
+    // This should always be okay because the string is guaranteed to have
+    // at least two characters before this. A mangled string always starts
+    // with _Z.
+    if (name[-1] != 'R') {
+      // Multiple 'R's in a row only add a single &.
+      cur_state_.suffixes.push_back("&");
+    }
+    return name + 1;
+
+  case 'K':
+  case 'V': {
+    const char* suffix;
+    if (*name == 'K') {
+      suffix = " const";
+    } else {
+      suffix = " volatile";
+    }
+    if (name[-1] == 'K' || name[-1] == 'V') {
+      // Special case, const/volatile apply as a single entity.
+      assert(!cur_state_.suffixes.empty());
+      size_t index = cur_state_.suffixes.size();
+      cur_state_.suffixes[index-1].insert(0, suffix);
+    } else {
+      cur_state_.suffixes.push_back(suffix);
+    }
+    return name + 1;
+  }
+
+  case 'F': {
+    std::string function_modifier;
+    std::string function_type;
+    if (!cur_state_.suffixes.empty()) {
+      // If the first element starts with a ' ', then this modifies the
+      // function itself.
+      if (cur_state_.suffixes.back()[0] == ' ') {
+        function_modifier = cur_state_.suffixes.back();
+        cur_state_.suffixes.pop_back();
+      }
+      while (!cur_state_.suffixes.empty()) {
+        function_type += cur_state_.suffixes.back();
+        cur_state_.suffixes.pop_back();
+      }
+    }
+
+    state_stack_.push(cur_state_);
+
+    cur_state_.Clear();
+
+    // The function parameter has this format:
+    //   First argument is the function modifier.
+    //   Second argument is the function type.
+    //   Third argument will be the return function type but has not
+    //     been parsed yet.
+    //   Any other parameters are the arguments to the function. There
+    //     must be at least one or this isn't valid.
+    cur_state_.args.push_back(function_modifier);
+    cur_state_.args.push_back(function_type);
+
+    parse_funcs_.push_back(parse_func_);
+    parse_func_ = &Demangler::ParseFunctionArgument;
+    return name + 1;
+  }
+
+  case 'N':
+    parse_funcs_.push_back(parse_func_);
+    parse_func_ = &Demangler::ParseComplexArgument;
+    return name + 1;
+
+  case 'S':
+    name++;
+    if (*name == 't') {
+      cur_state_.str = "std::";
+      return name + 1;
+    }
+    name = ParseS(name);
+    if (name == nullptr) {
+      return nullptr;
+    }
+    AppendArgument(cur_state_.str);
+    cur_state_.str.clear();
+    return name;
+
+  case 'D':
+    name++;
+    if (*name >= 'a' && *name <= 'z') {
+      const char* arg = Demangler::kDTypes[*name - 'a'];
+      if (arg == nullptr) {
+        return nullptr;
+      }
+      AppendArgument(arg);
+      return name + 1;
+    }
+    return nullptr;
+
+  case 'I':
+    // Save the current argument state.
+    state_stack_.push(cur_state_);
+    cur_state_.Clear();
+
+    parse_funcs_.push_back(parse_func_);
+    parse_func_ = &Demangler::ParseTemplateArguments;
+    return name + 1;
+
+  case 'v':
+    AppendArgument("void");
+    return name + 1;
+
+  default:
+    if (*name >= 'a' && *name <= 'z') {
+      const char* arg = Demangler::kTypes[*name - 'a'];
+      if (arg == nullptr) {
+        return nullptr;
+      }
+      AppendArgument(arg);
+      return name + 1;
+    } else if (std::isdigit(*name)) {
+      std::string arg = cur_state_.str;
+      name = GetStringFromLength(name, &arg);
+      if (name == nullptr) {
+        return nullptr;
+      }
+      Save(arg, true);
+      if (*name == 'I') {
+        // There is one case where this argument is not complete, and that's
+        // where this is a template argument.
+        cur_state_.str = arg;
+      } else {
+        AppendArgument(arg);
+        cur_state_.str.clear();
+      }
+      return name;
+    }
+  }
+  return nullptr;
+}
+
+const char* Demangler::ParseTemplateArgumentsComplex(const char* name) {
+  if (*name == 'E') {
+    if (parse_funcs_.empty()) {
+      return nullptr;
+    }
+    parse_func_ = parse_funcs_.back();
+    parse_funcs_.pop_back();
+    FinalizeTemplate();
+    Save(cur_state_.str, false);
+    return name + 1;
+  }
+  return ParseArguments(name);
+}
+
+const char* Demangler::ParseTemplateArguments(const char* name) {
+  if (*name == 'E') {
+    if (parse_funcs_.empty()) {
+      return nullptr;
+    }
+    parse_func_ = parse_funcs_.back();
+    parse_funcs_.pop_back();
+    FinalizeTemplate();
+    AppendArgument(cur_state_.str);
+    cur_state_.str.clear();
+    return name + 1;
+  }
+  return ParseArguments(name);
+}
+
+const char* Demangler::FindFunctionName(const char* name) {
+  if (*name == 'N') {
+    parse_funcs_.push_back(&Demangler::ParseArguments);
+    parse_func_ = &Demangler::ParseFunctionName;
+    return name + 1;
+  }
+
+  if (std::isdigit(*name)) {
+    name = GetStringFromLength(name, &function_name_);
+  } else {
+    name = AppendOperatorString(name);
+    function_name_ = cur_state_.str;
+  }
+  parse_func_ = &Demangler::ParseArguments;
+  cur_state_.Clear();
+  return name;
+}
+
+std::string Demangler::Parse(const char* name, size_t max_length) {
+  if (name[0] == '\0' || name[0] != '_' || name[1] == '\0' || name[1] != 'Z') {
+    // Name is not mangled.
+    return name;
+  }
+
+  Clear();
+
+  parse_func_ = &Demangler::FindFunctionName;
+  parse_funcs_.push_back(&Demangler::Fail);
+  const char* cur_name = name + 2;
+  while (cur_name != nullptr && *cur_name != '\0'
+      && static_cast<size_t>(cur_name - name) < max_length) {
+    cur_name = (this->*parse_func_)(cur_name);
+  }
+  if (cur_name == nullptr || *cur_name != '\0' || function_name_.empty()) {
+    return name;
+  }
+
+  std::string arg_str;
+  if (cur_state_.args.size() == 1 && cur_state_.args[0] == "void") {
+    // If the only argument is void, then don't print any args.
+    arg_str = "()";
+  } else {
+    arg_str = GetArgumentsString();
+    if (!arg_str.empty()) {
+      arg_str = '(' + arg_str + ')';
+    }
+  }
+  return function_name_ + arg_str + function_suffix_;
+}
+
+std::string demangle(const char* name) {
+  Demangler demangler;
+  return demangler.Parse(name);
+}
diff --git a/demangle/Demangler.h b/demangle/Demangler.h
new file mode 100644
index 0000000..3bd4f3c
--- /dev/null
+++ b/demangle/Demangler.h
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __LIB_DEMANGLE_DEMANGLER_H
+#define __LIB_DEMANGLE_DEMANGLER_H
+
+#include <assert.h>
+
+#include <stack>
+#include <string>
+#include <vector>
+
+class Demangler {
+ public:
+  Demangler() = default;
+
+  // NOTE: The max_length is not guaranteed to be the absolute max length
+  // of a string that will be rejected. Under certain circumstances the
+  // length check will not occur until after the second letter of a pair
+  // is checked.
+  std::string Parse(const char* name, size_t max_length = kMaxDefaultLength);
+
+  void AppendCurrent(const std::string& str);
+  void AppendCurrent(const char* str);
+  void AppendArgument(const std::string& str);
+  std::string GetArgumentsString();
+  void FinalizeTemplate();
+  const char* ParseS(const char* name);
+  const char* AppendOperatorString(const char* name);
+  void Save(const std::string& str, bool is_name);
+
+ private:
+  void Clear() {
+    parse_funcs_.clear();
+    function_name_.clear();
+    function_suffix_.clear();
+    first_save_.clear();
+    cur_state_.Clear();
+    saves_.clear();
+    while (!state_stack_.empty()) {
+      state_stack_.pop();
+    }
+    last_save_name_ = false;
+  }
+
+  using parse_func_type = const char* (Demangler::*)(const char*);
+  parse_func_type parse_func_;
+  std::vector<parse_func_type> parse_funcs_;
+  std::vector<std::string> saves_;
+  bool last_save_name_;
+
+  std::string function_name_;
+  std::string function_suffix_;
+
+  struct StateData {
+    void Clear() {
+      str.clear();
+      args.clear();
+      prefix.clear();
+      suffixes.clear();
+      last_save.clear();
+    }
+
+    std::string str;
+    std::vector<std::string> args;
+    std::string prefix;
+    std::vector<std::string> suffixes;
+    std::string last_save;
+  };
+  std::stack<StateData> state_stack_;
+  std::string first_save_;
+  StateData cur_state_;
+
+  static const char* GetStringFromLength(const char* name, std::string* str);
+
+  // Parsing functions.
+  const char* ParseComplexString(const char* name);
+  const char* ParseComplexArgument(const char* name);
+  const char* ParseArguments(const char* name);
+  const char* ParseTemplateArguments(const char* name);
+  const char* ParseTemplateArgumentsComplex(const char* name);
+  const char* ParseFunctionArgument(const char* name);
+  const char* ParseFunctionName(const char* name);
+  const char* FindFunctionName(const char* name);
+  const char* Fail(const char*) { return nullptr; }
+
+  // The default maximum string length string to process.
+  static constexpr size_t kMaxDefaultLength = 2048;
+
+  static constexpr const char* kTypes[] = {
+    "signed char",        // a
+    "bool",               // b
+    "char",               // c
+    "double",             // d
+    "long double",        // e
+    "float",              // f
+    "__float128",         // g
+    "unsigned char",      // h
+    "int",                // i
+    "unsigned int",       // j
+    nullptr,              // k
+    "long",               // l
+    "unsigned long",      // m
+    "__int128",           // n
+    "unsigned __int128",  // o
+    nullptr,              // p
+    nullptr,              // q
+    nullptr,              // r
+    "short",              // s
+    "unsigned short",     // t
+    nullptr,              // u
+    "void",               // v
+    "wchar_t",            // w
+    "long long",          // x
+    "unsigned long long", // y
+    "...",                // z
+  };
+
+  static constexpr const char* kDTypes[] = {
+    "auto",               // a
+    nullptr,              // b
+    nullptr,              // c
+    "decimal64",          // d
+    "decimal128",         // e
+    "decimal32",          // f
+    nullptr,              // g
+    "half",               // h
+    "char32_t",           // i
+    nullptr,              // j
+    nullptr,              // k
+    nullptr,              // l
+    nullptr,              // m
+    "decltype(nullptr)",  // n
+    nullptr,              // o
+    nullptr,              // p
+    nullptr,              // q
+    nullptr,              // r
+    "char16_t",           // s
+    nullptr,              // t
+    nullptr,              // u
+    nullptr,              // v
+    nullptr,              // w
+    nullptr,              // x
+    nullptr,              // y
+    nullptr,              // z
+  };
+
+  static constexpr const char* kSTypes[] = {
+    "std::allocator",     // a
+    "std::basic_string",  // b
+    nullptr,              // c
+    "std::iostream",      // d
+    nullptr,              // e
+    nullptr,              // f
+    nullptr,              // g
+    nullptr,              // h
+    "std::istream",       // i
+    nullptr,              // j
+    nullptr,              // k
+    nullptr,              // l
+    nullptr,              // m
+    nullptr,              // n
+    "std::ostream",       // o
+    nullptr,              // p
+    nullptr,              // q
+    nullptr,              // r
+    "std::string",        // s
+    nullptr,              // t
+    nullptr,              // u
+    nullptr,              // v
+    nullptr,              // w
+    nullptr,              // x
+    nullptr,              // y
+    nullptr,              // z
+  };
+};
+
+#endif  // __LIB_DEMANGLE_DEMANGLER_H
diff --git a/demangle/demangle.cpp b/demangle/demangle.cpp
new file mode 100644
index 0000000..be4d2dd
--- /dev/null
+++ b/demangle/demangle.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <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");
+}
+
+std::string DemangleWithCxa(const char* name) {
+  const char* cxa_demangle = __cxa_demangle(name, nullptr, nullptr, nullptr);
+
+  if (cxa_demangle == nullptr) {
+    return name;
+  }
+
+  // The format of our demangler is slightly different from the cxa demangler
+  // so modify the cxa demangler output. Specifically, for templates, remove
+  // the spaces between '>' and '>'.
+  std::string demangled_str;
+  for (size_t i = 0; i < strlen(cxa_demangle); i++) {
+    if (i > 2 && cxa_demangle[i] == '>' && std::isspace(cxa_demangle[i - 1]) &&
+        cxa_demangle[i - 2] == '>') {
+      demangled_str.resize(demangled_str.size() - 1);
+    }
+    demangled_str += cxa_demangle[i];
+  }
+  return demangled_str;
+}
+
+int main(int argc, char** argv) {
+#ifdef __BIONIC__
+  const char* prog_name = getprogname();
+#else
+  const char* prog_name = argv[0];
+#endif
+
+  bool compare = false;
+  int opt_char;
+  while ((opt_char = getopt(argc, argv, "c")) != -1) {
+    if (opt_char == 'c') {
+      compare = true;
+    } else {
+      usage(prog_name);
+      return 1;
+    }
+  }
+  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);
+
+  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");
+    }
+  }
+  return 0;
+}
diff --git a/demangle/include/demangle.h b/demangle/include/demangle.h
new file mode 100644
index 0000000..01f1b80
--- /dev/null
+++ b/demangle/include/demangle.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __LIB_DEMANGLE_H_
+#define __LIB_DEMANGLE_H_
+
+#include <string>
+
+// If the name cannot be demangled, the original name will be returned as
+// a std::string. If the name can be demangled, then the demangled name
+// will be returned as a std::string.
+std::string demangle(const char* name);
+
+#endif  // __LIB_DEMANGLE_H_
diff --git a/fastboot/.clang-format b/fastboot/.clang-format
deleted file mode 100644
index bcb8d8a..0000000
--- a/fastboot/.clang-format
+++ /dev/null
@@ -1,15 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: Inline
-
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-ContinuationIndentWidth: 8
-ConstructorInitializerIndentWidth: 8
-AccessModifierOffset: -2
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/fastboot/.clang-format b/fastboot/.clang-format
new file mode 120000
index 0000000..1af4f51
--- /dev/null
+++ b/fastboot/.clang-format
@@ -0,0 +1 @@
+../.clang-format-4
\ No newline at end of file
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 1b4ecbe..5610cc0 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -21,7 +21,6 @@
 LOCAL_C_INCLUDES := \
   $(LOCAL_PATH)/../adb \
   $(LOCAL_PATH)/../mkbootimg \
-  $(LOCAL_PATH)/../../extras/ext4_utils \
   $(LOCAL_PATH)/../../extras/f2fs_utils \
 
 LOCAL_SRC_FILES := \
@@ -38,29 +37,28 @@
 LOCAL_MODULE := fastboot
 LOCAL_MODULE_TAGS := debug
 LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_CONLYFLAGS += -std=gnu99
 LOCAL_CFLAGS += -Wall -Wextra -Werror -Wunreachable-code
 
 LOCAL_CFLAGS += -DFASTBOOT_REVISION='"$(fastboot_version)"'
 
-LOCAL_SRC_FILES_linux := usb_linux.cpp util_linux.cpp
+LOCAL_SRC_FILES_linux := usb_linux.cpp
 LOCAL_STATIC_LIBRARIES_linux := libselinux
 
-LOCAL_SRC_FILES_darwin := usb_osx.cpp util_osx.cpp
+LOCAL_SRC_FILES_darwin := usb_osx.cpp
 LOCAL_STATIC_LIBRARIES_darwin := libselinux
 LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
 LOCAL_CFLAGS_darwin := -Wno-unused-parameter
 
-LOCAL_SRC_FILES_windows := usb_windows.cpp util_windows.cpp
+LOCAL_SRC_FILES_windows := usb_windows.cpp
 LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
 LOCAL_REQUIRED_MODULES_windows := AdbWinApi
 LOCAL_LDLIBS_windows := -lws2_32
 LOCAL_C_INCLUDES_windows := development/host/windows/usb/api
 
 LOCAL_STATIC_LIBRARIES := \
-    libziparchive-host \
-    libext4_utils_host \
-    libsparse_host \
+    libziparchive \
+    libext4_utils \
+    libsparse \
     libutils \
     liblog \
     libz \
diff --git a/fastboot/README.md b/fastboot/README.md
new file mode 100644
index 0000000..022d34b
--- /dev/null
+++ b/fastboot/README.md
@@ -0,0 +1,453 @@
+Fastboot
+--------
+
+The fastboot protocol is a mechanism for communicating with bootloaders
+over USB or ethernet.  It is designed to be very straightforward to implement,
+to allow it to be used across a wide range of devices and from hosts running
+Linux, macOS, or Windows.
+
+
+## Basic Requirements
+
+* USB
+  * Two bulk endpoints (in, out) are required
+  * Max packet size must be 64 bytes for full-speed, 512 bytes for
+    high-speed and 1024 bytes for Super Speed USB.
+  * The protocol is entirely host-driven and synchronous (unlike the
+    multi-channel, bi-directional, asynchronous ADB protocol)
+
+* TCP or UDP
+  * Device must be reachable via IP.
+  * Device will act as the server, fastboot will be the client.
+  * Fastboot data is wrapped in a simple protocol; see below for details.
+
+
+## Transport and Framing
+
+1. Host sends a command, which is an ascii string in a single
+   packet no greater than 64 bytes.
+
+2. Client response with a single packet no greater than 64 bytes.
+   The first four bytes of the response are "OKAY", "FAIL", "DATA",
+   or "INFO".  Additional bytes may contain an (ascii) informative
+   message.
+
+   a. INFO -> the remaining 60 bytes are an informative message
+      (providing progress or diagnostic messages).  They should
+      be displayed and then step #2 repeats
+
+   b. FAIL -> the requested command failed.  The remaining 60 bytes
+      of the response (if present) provide a textual failure message
+      to present to the user.  Stop.
+
+   c. OKAY -> the requested command completed successfully.  Go to #5
+
+   d. DATA -> the requested command is ready for the data phase.
+      A DATA response packet will be 12 bytes long, in the form of
+      DATA00000000 where the 8 digit hexadecimal number represents
+      the total data size to transfer.
+
+3. Data phase.  Depending on the command, the host or client will
+   send the indicated amount of data.  Short packets are always
+   acceptable and zero-length packets are ignored.  This phase continues
+   until the client has sent or received the number of bytes indicated
+   in the "DATA" response above.
+
+4. Client responds with a single packet no greater than 64 bytes.
+   The first four bytes of the response are "OKAY", "FAIL", or "INFO".
+   Similar to #2:
+
+   a. INFO -> display the remaining 60 bytes and return to #4
+
+   b. FAIL -> display the remaining 60 bytes (if present) as a failure
+      reason and consider the command failed.  Stop.
+
+   c. OKAY -> success.  Go to #5
+
+5. Success.  Stop.
+
+
+## Example Session
+
+    Host:    "getvar:version"        request version variable
+
+    Client:  "OKAY0.4"               return version "0.4"
+
+    Host:    "getvar:nonexistant"    request some undefined variable
+
+    Client:  "FAILUnknown variable"  getvar failure; see getvar details below
+
+    Host:    "download:00001234"     request to send 0x1234 bytes of data
+
+    Client:  "DATA00001234"          ready to accept data
+
+    Host:    < 0x1234 bytes >        send data
+
+    Client:  "OKAY"                  success
+
+    Host:    "flash:bootloader"      request to flash the data to the bootloader
+
+    Client:  "INFOerasing flash"     indicate status / progress
+             "INFOwriting flash"
+             "OKAY"                  indicate success
+
+    Host:    "powerdown"             send a command
+
+    Client:  "FAILunknown command"   indicate failure
+
+
+## Command Reference
+
+* Command parameters are indicated by printf-style escape sequences.
+
+* Commands are ascii strings and sent without the quotes (which are
+  for illustration only here) and without a trailing 0 byte.
+
+* Commands that begin with a lowercase letter are reserved for this
+  specification.  OEM-specific commands should not begin with a
+  lowercase letter, to prevent incompatibilities with future specs.
+
+The various currently defined commands are:
+
+    getvar:%s          Read a config/version variable from the bootloader.
+                       The variable contents will be returned after the
+                       OKAY response. If the variable is unknown, the bootloader
+                       should return a FAIL response, optionally with an error
+                       message.
+
+                       Previous versions of this document indicated that getvar
+                       should return an empty OKAY response for unknown
+                       variables, so older devices might exhibit this behavior,
+                       but new implementations should return FAIL instead.
+
+    download:%08x      Write data to memory which will be later used
+                       by "boot", "ramdisk", "flash", etc.  The client
+                       will reply with "DATA%08x" if it has enough
+                       space in RAM or "FAIL" if not.  The size of
+                       the download is remembered.
+
+    verify:%08x        Send a digital signature to verify the downloaded
+                       data.  Required if the bootloader is "secure"
+                       otherwise "flash" and "boot" will be ignored.
+
+    flash:%s           Write the previously downloaded image to the
+                       named partition (if possible).
+
+    erase:%s           Erase the indicated partition (clear to 0xFFs)
+
+    boot               The previously downloaded data is a boot.img
+                       and should be booted according to the normal
+                       procedure for a boot.img
+
+    continue           Continue booting as normal (if possible)
+
+    reboot             Reboot the device.
+
+    reboot-bootloader
+                       Reboot back into the bootloader.
+                       Useful for upgrade processes that require upgrading
+                       the bootloader and then upgrading other partitions
+                       using the new bootloader.
+
+    powerdown          Power off the device.
+
+
+
+## Client Variables
+
+The "getvar:%s" command is used to read client variables which
+represent various information about the device and the software
+on it.
+
+The various currently defined names are:
+
+    version             Version of FastBoot protocol supported.
+                        It should be "0.4" for this document.
+
+    version-bootloader  Version string for the Bootloader.
+
+    version-baseband    Version string of the Baseband Software
+
+    product             Name of the product
+
+    serialno            Product serial number
+
+    secure              If the value is "yes", this is a secure
+                        bootloader requiring a signature before
+                        it will install or boot images.
+
+Names starting with a lowercase character are reserved by this
+specification.  OEM-specific names should not start with lowercase
+characters.
+
+
+## TCP Protocol v1
+
+The TCP protocol is designed to be a simple way to use the fastboot protocol
+over ethernet if USB is not available.
+
+The device will open a TCP server on port 5554 and wait for a fastboot client
+to connect.
+
+### Handshake
+Upon connecting, both sides will send a 4-byte handshake message to ensure they
+are speaking the same protocol. This consists of the ASCII characters "FB"
+followed by a 2-digit base-10 ASCII version number. For example, the version 1
+handshake message will be [FB01].
+
+If either side detects a malformed handshake, it should disconnect.
+
+The protocol version to use must be the minimum of the versions sent by each
+side; if either side cannot speak this protocol version, it should disconnect.
+
+### Fastboot Data
+Once the handshake is complete, fastboot data will be sent as follows:
+
+    [data_size][data]
+
+Where data\_size is an unsigned 8-byte big-endian binary value, and data is the
+fastboot packet. The 8-byte length is intended to provide future-proofing even
+though currently fastboot packets have a 4-byte maximum length.
+
+### Example
+In this example the fastboot host queries the device for two variables,
+"version" and "none".
+
+    Host    <connect to the device on port 5555>
+    Host    FB01
+    Device  FB01
+    Host    [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x0E]getvar:version
+    Device  [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x07]OKAY0.4
+    Host    [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x0B]getvar:none
+    Device  [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x14]FAILUnknown variable
+    Host    <disconnect>
+
+
+## UDP Protocol v1
+
+The UDP protocol is more complex than TCP since we must implement reliability
+to ensure no packets are lost, but the general concept of wrapping the fastboot
+protocol is the same.
+
+Overview:
+  1. As with TCP, the device will listen on UDP port 5554.
+  2. Maximum UDP packet size is negotiated during initialization.
+  3. The host drives all communication; the device may only send a packet as a
+     response to a host packet.
+  4. If the host does not receive a response in 500ms it will re-transmit.
+
+### UDP Packet format
+
+    +----------+----+-------+-------+--------------------+
+    | Byte #   | 0  |   1   | 2 - 3 |  4+                |
+    +----------+----+-------+-------+--------------------+
+    | Contents | ID | Flags | Seq # | Data               |
+    +----------+----+-------+-------+--------------------+
+
+    ID      Packet ID:
+              0x00: Error.
+              0x01: Query.
+              0x02: Initialization.
+              0x03: Fastboot.
+
+            Packet types are described in more detail below.
+
+    Flags   Packet flags: 0 0 0 0 0 0 0 C
+              C=1 indicates a continuation packet; the data is too large and will
+                  continue in the next packet.
+
+              Remaining bits are reserved for future use and must be set to 0.
+
+    Seq #   2-byte packet sequence number (big-endian). The host will increment
+            this by 1 with each new packet, and the device must provide the
+            corresponding sequence number in the response packets.
+
+    Data    Packet data, not present in all packets.
+
+### Packet Types
+
+    Query
+          The host sends a query packet once on startup to sync with the device.
+          The host will not know the current sequence number, so the device must
+          respond to all query packets regardless of sequence number.
+
+          The response data field should contain a 2-byte big-endian value
+          giving the next expected sequence number.
+
+    Init
+          The host sends an init packet once the query response is returned. The
+          device must abort any in-progress operation and prepare for a new
+          fastboot session. This message is meant to allow recovery if a
+          previous session failed, e.g. due to network error or user Ctrl+C.
+
+          The data field contains two big-endian 2-byte values, a protocol
+          version and the max UDP packet size (including the 4-byte header).
+          Both the host and device will send these values, and in each case
+          the minimum of the sent values must be used.
+
+    Fastboot
+          These packets wrap the fastboot protocol. To write, the host will
+          send a packet with fastboot data, and the device will reply with an
+          empty packet as an ACK. To read, the host will send an empty packet,
+          and the device will reply with fastboot data. The device may not give
+          any data in the ACK packet.
+
+    Error
+          The device may respond to any packet with an error packet to indicate
+          a UDP protocol error. The data field should contain an ASCII string
+          describing the error. This is the only case where a device is allowed
+          to return a packet ID other than the one sent by the host.
+
+### Packet Size
+The maximum packet size is negotiated by the host and device in the Init packet.
+Devices must support at least 512-byte packets, but packet size has a direct
+correlation with download speed, so devices are strongly suggested to support at
+least 1024-byte packets. On a local network with 0.5ms round-trip time this will
+provide transfer rates of ~2MB/s. Over WiFi it will likely be significantly
+less.
+
+Query and Initialization packets, which are sent before size negotiation is
+complete, must always be 512 bytes or less.
+
+### Packet Re-Transmission
+The host will re-transmit any packet that does not receive a response. The
+requirement of exactly one device response packet per host packet is how we
+achieve reliability and in-order delivery of packets.
+
+For simplicity of implementation, there is no windowing of multiple
+unacknowledged packets in this version of the protocol. The host will continue
+to send the same packet until a response is received. Windowing functionality
+may be implemented in future versions if necessary to increase performance.
+
+The first Query packet will only be attempted a small number of times, but
+subsequent packets will attempt to retransmit for at least 1 minute before
+giving up. This means a device may safely ignore host UDP packets for up to 1
+minute during long operations, e.g. writing to flash.
+
+### Continuation Packets
+Any packet may set the continuation flag to indicate that the data is
+incomplete. Large data such as downloading an image may require many
+continuation packets. The receiver should respond to a continuation packet with
+an empty packet to acknowledge receipt. See examples below.
+
+### Summary
+The host starts with a Query packet, then an Initialization packet, after
+which only Fastboot packets are sent. Fastboot packets may contain data from
+the host for writes, or from the device for reads, but not both.
+
+Given a next expected sequence number S and a received packet P, the device
+behavior should be:
+
+    if P is a Query packet:
+      * respond with a Query packet with S in the data field
+    else if P has sequence == S:
+      * process P and take any required action
+      * create a response packet R with the same ID and sequence as P, containing
+        any response data required.
+      * transmit R and save it in case of re-transmission
+      * increment S
+    else if P has sequence == S - 1:
+      * re-transmit the saved response packet R from above
+    else:
+      * ignore the packet
+
+### Examples
+
+In the examples below, S indicates the starting client sequence number.
+
+    Host                                    Client
+    ======================================================================
+    [Initialization, S = 0x55AA]
+    [Host: version 1, 2048-byte packets. Client: version 2, 1024-byte packets.]
+    [Resulting values to use: version = 1, max packet size = 1024]
+    ID   Flag SeqH SeqL Data                ID   Flag SeqH SeqL Data
+    ----------------------------------------------------------------------
+    0x01 0x00 0x00 0x00
+                                            0x01 0x00 0x00 0x00 0x55 0xAA
+    0x02 0x00 0x55 0xAA 0x00 0x01 0x08 0x00
+                                            0x02 0x00 0x55 0xAA 0x00 0x02 0x04 0x00
+
+    ----------------------------------------------------------------------
+    [fastboot "getvar" commands, S = 0x0001]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x03  0x00  0x00  0x01  getvar:version
+                                            0x03  0x00  0x00  0x01
+    0x03  0x00  0x00  0x02
+                                            0x03  0x00  0x00  0x02  OKAY0.4
+    0x03  0x00  0x00  0x03  getvar:none
+                                            0x03  0x00  0x00  0x03
+    0x03  0x00  0x00  0x04
+                                            0x03  0x00  0x00  0x04  FAILUnknown var
+
+    ----------------------------------------------------------------------
+    [fastboot "INFO" responses, S = 0x0000]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x03  0x00  0x00  0x00  <command>
+                                            0x03  0x00  0x00  0x00
+    0x03  0x00  0x00  0x01
+                                            0x03  0x00  0x00  0x01  INFOWait1
+    0x03  0x00  0x00  0x02
+                                            0x03  0x00  0x00  0x02  INFOWait2
+    0x03  0x00  0x00  0x03
+                                            0x03  0x00  0x00  0x03  OKAY
+
+    ----------------------------------------------------------------------
+    [Chunking 2100 bytes of data, max packet size = 1024, S = 0xFFFF]
+    ID   Flag SeqH SeqL Data                ID   Flag SeqH SeqL Data
+    ----------------------------------------------------------------------
+    0x03 0x00 0xFF 0xFF download:0000834
+                                            0x03 0x00 0xFF 0xFF
+    0x03 0x00 0x00 0x00
+                                            0x03 0x00 0x00 0x00 DATA0000834
+    0x03 0x01 0x00 0x01 <1020 bytes>
+                                            0x03 0x00 0x00 0x01
+    0x03 0x01 0x00 0x02 <1020 bytes>
+                                            0x03 0x00 0x00 0x02
+    0x03 0x00 0x00 0x03 <60 bytes>
+                                            0x03 0x00 0x00 0x03
+    0x03 0x00 0x00 0x04
+                                            0x03 0x00 0x00 0x04 OKAY
+
+    ----------------------------------------------------------------------
+    [Unknown ID error, S = 0x0000]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x10  0x00  0x00  0x00
+                                            0x00  0x00  0x00  0x00  <error message>
+
+    ----------------------------------------------------------------------
+    [Host packet loss and retransmission, S = 0x0000]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x03  0x00  0x00  0x00  getvar:version [lost]
+    0x03  0x00  0x00  0x00  getvar:version [lost]
+    0x03  0x00  0x00  0x00  getvar:version
+                                            0x03  0x00  0x00  0x00
+    0x03  0x00  0x00  0x01
+                                            0x03  0x00  0x00  0x01  OKAY0.4
+
+    ----------------------------------------------------------------------
+    [Client packet loss and retransmission, S = 0x0000]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x03  0x00  0x00  0x00  getvar:version
+                                            0x03  0x00  0x00  0x00 [lost]
+    0x03  0x00  0x00  0x00  getvar:version
+                                            0x03  0x00  0x00  0x00 [lost]
+    0x03  0x00  0x00  0x00  getvar:version
+                                            0x03  0x00  0x00  0x00
+    0x03  0x00  0x00  0x01
+                                            0x03  0x00  0x00  0x01  OKAY0.4
+
+    ----------------------------------------------------------------------
+    [Host packet delayed, S = 0x0000]
+    ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
+    ----------------------------------------------------------------------
+    0x03  0x00  0x00  0x00  getvar:version [delayed]
+    0x03  0x00  0x00  0x00  getvar:version
+                                            0x03  0x00  0x00  0x00
+    0x03  0x00  0x00  0x01
+                                            0x03  0x00  0x00  0x01  OKAY0.4
+    0x03  0x00  0x00  0x00  getvar:version [arrives late with old seq#, is ignored]
diff --git a/fastboot/engine.cpp b/fastboot/engine.cpp
index 47567c0..728dcb8 100644
--- a/fastboot/engine.cpp
+++ b/fastboot/engine.cpp
@@ -38,8 +38,6 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
-
 #define OP_DOWNLOAD   1
 #define OP_COMMAND    2
 #define OP_QUERY      3
@@ -351,21 +349,21 @@
         }
         if (a->op == OP_DOWNLOAD) {
             status = fb_download_data(transport, a->data, a->size);
-            status = a->func(a, status, status ? fb_get_error() : "");
+            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() : "");
+            status = a->func(a, status, status ? fb_get_error().c_str() : "");
             if (status) break;
         } else if (a->op == OP_QUERY) {
             status = fb_command_response(transport, a->cmd, resp);
-            status = a->func(a, status, status ? fb_get_error() : resp);
+            status = a->func(a, status, status ? fb_get_error().c_str() : resp);
             if (status) break;
         } else if (a->op == OP_NOTICE) {
             fprintf(stderr,"%s\n",(char*)a->data);
         } else if (a->op == OP_DOWNLOAD_SPARSE) {
             status = fb_download_data_sparse(transport, reinterpret_cast<sparse_file*>(a->data));
-            status = a->func(a, status, status ? fb_get_error() : "");
+            status = a->func(a, status, status ? fb_get_error().c_str() : "");
             if (status) break;
         } else if (a->op == OP_WAIT_FOR_DISCONNECT) {
             transport->WaitForDisconnect();
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 2b6cad1..2927b16 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -43,10 +43,14 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <chrono>
 #include <functional>
+#include <thread>
 #include <utility>
 #include <vector>
 
+#include <android-base/file.h>
+#include <android-base/macros.h>
 #include <android-base/parseint.h>
 #include <android-base/parsenetaddress.h>
 #include <android-base/stringprintf.h>
@@ -67,8 +71,6 @@
 #define O_BINARY 0
 #endif
 
-#define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))
-
 char cur_product[FB_RESPONSE_SZ + 1];
 
 static const char* serial = nullptr;
@@ -116,11 +118,8 @@
 };
 
 static std::string find_item_given_name(const char* img_name, const char* product) {
-    char path_c_str[PATH_MAX + 128];
-
     if(product) {
-        get_my_path(path_c_str);
-        std::string path = path_c_str;
+        std::string path = android::base::GetExecutablePath();
         path.erase(path.find_last_of('/'));
         return android::base::StringPrintf("%s/../../../target/product/%s/%s",
                                            path.c_str(), product, img_name);
@@ -137,7 +136,7 @@
 std::string find_item(const char* item, const char* product) {
     const char *fn;
 
-    if(!strcmp(item,"boot")) {
+    if (!strcmp(item,"boot")) {
         fn = "boot.img";
     } else if(!strcmp(item,"recovery")) {
         fn = "recovery.img";
@@ -189,8 +188,8 @@
     return 0;
 }
 
-static void* load_file(const char* fn, int64_t* sz) {
-    int fd = open(fn, O_RDONLY | O_BINARY);
+static void* load_file(const std::string& path, int64_t* sz) {
+    int fd = open(path.c_str(), O_RDONLY | O_BINARY);
     if (fd == -1) return nullptr;
     return load_fd(fd, sz);
 }
@@ -304,7 +303,7 @@
             announce = false;
             fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
         }
-        usleep(1000);
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
     }
 }
 
@@ -359,7 +358,7 @@
             "  devices [-l]                             List all connected devices [with\n"
             "                                           device paths].\n"
             "  continue                                 Continue with autoboot.\n"
-            "  reboot [bootloader]                      Reboot device [into bootloader].\n"
+            "  reboot [bootloader|emergency]            Reboot device [into bootloader or emergency mode].\n"
             "  reboot-bootloader                        Reboot device into bootloader.\n"
             "  help                                     Show this help message.\n"
             "\n"
@@ -400,12 +399,14 @@
             "  -a, --set-active[=<slot>]                Sets the active slot. If no slot is\n"
             "                                           provided, this will default to the value\n"
             "                                           given by --slot. If slots are not\n"
-            "                                           supported, this sets the current slot\n"
-            "                                           to be active. This will run after all\n"
-            "                                           non-reboot commands.\n"
+            "                                           supported, this does nothing. This will\n"
+            "                                           run after all non-reboot commands.\n"
             "  --skip-secondary                         Will not flash secondary slots when\n"
             "                                           performing a flashall or update. This\n"
             "                                           will preserve data on other slots.\n"
+            "  --skip-reboot                            Will not reboot the device when\n"
+            "                                           performing commands that normally\n"
+            "                                           trigger a reboot.\n"
 #if !defined(_WIN32)
             "  --wipe-and-use-fbe                       On devices which support it,\n"
             "                                           erase userdata and cache, and\n"
@@ -602,6 +603,7 @@
     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;
     }
 
@@ -609,10 +611,12 @@
     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;
 }
 
@@ -753,7 +757,7 @@
     max_download_size = android::base::Trim(max_download_size);
 
     uint64_t limit;
-    if (!android::base::ParseUint(max_download_size.c_str(), &limit)) {
+    if (!android::base::ParseUint(max_download_size, &limit)) {
         fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
         return 0;
     }
@@ -799,10 +803,10 @@
     return partition_type == "ext4";
 }
 
-static int load_buf_fd(Transport* transport, int fd, struct fastboot_buffer* buf) {
+static bool load_buf_fd(Transport* transport, int fd, struct fastboot_buffer* buf) {
     int64_t sz = get_file_size(fd);
     if (sz == -1) {
-        return -1;
+        return false;
     }
 
     lseek64(fd, 0, SEEK_SET);
@@ -810,7 +814,7 @@
     if (limit) {
         sparse_file** s = load_sparse_files(fd, limit);
         if (s == nullptr) {
-            return -1;
+            return false;
         }
         buf->type = FB_BUFFER_SPARSE;
         buf->data = s;
@@ -822,18 +826,14 @@
         buf->sz = sz;
     }
 
-    return 0;
+    return true;
 }
 
-static int load_buf(Transport* transport, const char *fname, struct fastboot_buffer *buf)
-{
-    int fd;
-
-    fd = open(fname, O_RDONLY | O_BINARY);
-    if (fd < 0) {
-        return -1;
+static bool load_buf(Transport* transport, const char* fname, struct fastboot_buffer* buf) {
+    int fd = open(fname, O_RDONLY | O_BINARY);
+    if (fd == -1) {
+        return false;
     }
-
     return load_buf_fd(transport, fd, buf);
 }
 
@@ -905,7 +905,7 @@
     if (!fb_getvar(transport, "slot-count", &var)) {
         if (supports_AB_obsolete(transport)) return 2; // Legacy support
     }
-    if (!android::base::ParseInt(var.c_str(), &count)) return 0;
+    if (!android::base::ParseInt(var, &count)) return 0;
     return count;
 }
 
@@ -976,7 +976,7 @@
 }
 
 static void do_for_partition(Transport* transport, const std::string& part, const std::string& slot,
-                             std::function<void(const std::string&)> func, bool force_slot) {
+                             const std::function<void(const std::string&)>& func, bool force_slot) {
     std::string has_slot;
     std::string current_slot;
 
@@ -1009,7 +1009,7 @@
  * partition does not support slots.
  */
 static void do_for_partitions(Transport* transport, const std::string& part, const std::string& slot,
-                              std::function<void(const std::string&)> func, bool force_slot) {
+                              const std::function<void(const std::string&)>& func, bool force_slot) {
     std::string has_slot;
 
     if (slot == "all") {
@@ -1031,8 +1031,8 @@
 static void do_flash(Transport* transport, const char* pname, const char* fname) {
     struct fastboot_buffer buf;
 
-    if (load_buf(transport, fname, &buf)) {
-        die("cannot load '%s'", fname);
+    if (!load_buf(transport, fname, &buf)) {
+        die("cannot load '%s': %s", fname, strerror(errno));
     }
     flash_buf(pname, &buf);
 }
@@ -1101,7 +1101,7 @@
             skip_secondary = true;
         }
     }
-    for (size_t i = 0; i < ARRAY_SIZE(images); ++i) {
+    for (size_t i = 0; i < arraysize(images); ++i) {
         const char* slot = slot_override.c_str();
         if (images[i].is_secondary) {
             if (!skip_secondary) {
@@ -1120,8 +1120,9 @@
             exit(1); // unzip_to_file already explained why.
         }
         fastboot_buffer buf;
-        int rc = load_buf_fd(transport, fd, &buf);
-        if (rc) die("cannot load %s from flash", images[i].img_name);
+        if (!load_buf_fd(transport, fd, &buf)) {
+            die("cannot load %s from flash: %s", images[i].img_name, strerror(errno));
+        }
 
         auto update = [&](const std::string &partition) {
             do_update_signature(zip, images[i].sig_name);
@@ -1154,6 +1155,7 @@
     int64_t sz;
     void* data = load_file(fs_sig.c_str(), &sz);
     if (data == nullptr) return;
+
     fb_queue_download("signature", data, sz);
     fb_queue_command("signature", "installing signature");
 }
@@ -1165,7 +1167,7 @@
     fb_queue_query_save("product", cur_product, sizeof(cur_product));
 
     fname = find_item("info", product);
-    if (fname == "") die("cannot find android-info.txt");
+    if (fname.empty()) die("cannot find android-info.txt");
 
     int64_t sz;
     void* data = load_file(fname.c_str(), &sz);
@@ -1188,7 +1190,7 @@
         }
     }
 
-    for (size_t i = 0; i < ARRAY_SIZE(images); i++) {
+    for (size_t i = 0; i < arraysize(images); i++) {
         const char* slot = NULL;
         if (images[i].is_secondary) {
             if (!skip_secondary) slot = secondary.c_str();
@@ -1198,13 +1200,13 @@
         if (!slot) continue;
         fname = find_item_given_name(images[i].img_name, product);
         fastboot_buffer buf;
-        if (load_buf(transport, fname.c_str(), &buf)) {
+        if (!load_buf(transport, fname.c_str(), &buf)) {
             if (images[i].is_optional) continue;
-            die("could not load %s\n", images[i].img_name);
+            die("could not load '%s': %s\n", images[i].img_name, strerror(errno));
         }
 
         auto flashall = [&](const std::string &partition) {
-            do_send_signature(fname);
+            do_send_signature(fname.c_str());
             if (erase_first && needs_erase(transport, partition.c_str())) {
                 fb_queue_erase(partition.c_str());
             }
@@ -1243,20 +1245,17 @@
     return 0;
 }
 
-static int do_oem_command(int argc, char **argv)
-{
-    char command[256];
+static int do_oem_command(int argc, char** argv) {
     if (argc <= 1) return 0;
 
-    command[0] = 0;
-    while(1) {
-        strcat(command,*argv);
+    std::string command;
+    while (argc > 0) {
+        command += *argv;
         skip(1);
-        if(argc == 0) break;
-        strcat(command," ");
+        if (argc != 0) command += " ";
     }
 
-    fb_queue_command(command,"");
+    fb_queue_command(command.c_str(), "");
     return 0;
 }
 
@@ -1301,6 +1300,36 @@
     return num;
 }
 
+static std::string fb_fix_numeric_var(std::string var) {
+    // Some bootloaders (angler, for example), send spurious leading whitespace.
+    var = android::base::Trim(var);
+    // Some bootloaders (hammerhead, for example) use implicit hex.
+    // This code used to use strtol with base 16.
+    if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
+    return var;
+}
+
+static unsigned fb_get_flash_block_size(Transport* transport, std::string name) {
+    std::string sizeString;
+    if (!fb_getvar(transport, name.c_str(), &sizeString)) {
+        /* This device does not report flash block sizes, so return 0 */
+        return 0;
+    }
+    sizeString = fb_fix_numeric_var(sizeString);
+
+    unsigned size;
+    if (!android::base::ParseUint(sizeString, &size)) {
+        fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
+        return 0;
+    }
+    if (size < 4096 || (size & (size - 1)) != 0) {
+        fprintf(stderr, "Invalid %s %u: must be a power of 2 and at least 4096.\n",
+                name.c_str(), size);
+        return 0;
+    }
+    return size;
+}
+
 static void fb_perform_format(Transport* transport,
                               const char* partition, int skip_if_not_supported,
                               const char* type_override, const char* size_override,
@@ -1343,11 +1372,7 @@
         }
         partition_size = size_override;
     }
-    // Some bootloaders (angler, for example), send spurious leading whitespace.
-    partition_size = android::base::Trim(partition_size);
-    // Some bootloaders (hammerhead, for example) use implicit hex.
-    // This code used to use strtol with base 16.
-    if (!android::base::StartsWith(partition_size, "0x")) partition_size = "0x" + partition_size;
+    partition_size = fb_fix_numeric_var(partition_size);
 
     gen = fs_get_generator(partition_type);
     if (!gen) {
@@ -1362,19 +1387,24 @@
     }
 
     int64_t size;
-    if (!android::base::ParseInt(partition_size.c_str(), &size)) {
+    if (!android::base::ParseInt(partition_size, &size)) {
         fprintf(stderr, "Couldn't parse partition size '%s'.\n", partition_size.c_str());
         return;
     }
 
     fd = fileno(tmpfile());
-    if (fs_generator_generate(gen, fd, size, initial_dir)) {
+
+    unsigned eraseBlkSize, logicalBlkSize;
+    eraseBlkSize = fb_get_flash_block_size(transport, "erase-block-size");
+    logicalBlkSize = fb_get_flash_block_size(transport, "logical-block-size");
+
+    if (fs_generator_generate(gen, fd, size, initial_dir, eraseBlkSize, logicalBlkSize)) {
         fprintf(stderr, "Cannot generate image: %s\n", strerror(errno));
         close(fd);
         return;
     }
 
-    if (load_buf_fd(transport, fd, &buf)) {
+    if (!load_buf_fd(transport, fd, &buf)) {
         fprintf(stderr, "Cannot read image: %s\n", strerror(errno));
         close(fd);
         return;
@@ -1387,7 +1417,7 @@
         fprintf(stderr, "Erase successful, but not automatically formatting.\n");
         if (errMsg) fprintf(stderr, "%s", errMsg);
     }
-    fprintf(stderr,"FAILED (%s)\n", fb_get_error());
+    fprintf(stderr, "FAILED (%s)\n", fb_get_error().c_str());
 }
 
 int main(int argc, char **argv)
@@ -1395,6 +1425,8 @@
     bool wants_wipe = false;
     bool wants_reboot = false;
     bool wants_reboot_bootloader = false;
+    bool wants_reboot_emergency = false;
+    bool skip_reboot = false;
     bool wants_set_active = false;
     bool skip_secondary = false;
     bool erase_first = true;
@@ -1422,6 +1454,7 @@
         {"set_active", optional_argument, 0, 'a'},
         {"set-active", optional_argument, 0, 'a'},
         {"skip-secondary", no_argument, 0, 0},
+        {"skip-reboot", no_argument, 0, 0},
 #if !defined(_WIN32)
         {"wipe-and-use-fbe", no_argument, 0, 0},
 #endif
@@ -1508,6 +1541,8 @@
                 slot_override = std::string(optarg);
             } else if (strcmp("skip-secondary", longopts[longindex].name) == 0 ) {
                 skip_secondary = true;
+            } else if (strcmp("skip-reboot", longopts[longindex].name) == 0 ) {
+                skip_reboot = true;
 #if !defined(_WIN32)
             } else if (strcmp("wipe-and-use-fbe", longopts[longindex].name) == 0) {
                 wants_wipe = true;
@@ -1641,6 +1676,10 @@
                     wants_reboot = false;
                     wants_reboot_bootloader = true;
                     skip(1);
+                } else if (!strcmp(*argv, "emergency")) {
+                    wants_reboot = false;
+                    wants_reboot_emergency = true;
+                    skip(1);
                 }
             }
             require(0);
@@ -1672,7 +1711,7 @@
             fb_queue_download("boot.img", data, sz);
             fb_queue_command("boot", "booting");
         } else if(!strcmp(*argv, "flash")) {
-            char *pname = argv[1];
+            char* pname = argv[1];
             std::string fname;
             require(2);
             if (argc > 2) {
@@ -1682,7 +1721,7 @@
                 fname = find_item(pname, product);
                 skip(2);
             }
-            if (fname == "") die("cannot determine image filename for '%s'", pname);
+            if (fname.empty()) die("cannot determine image filename for '%s'", pname);
 
             auto flash = [&](const std::string &partition) {
                 if (erase_first && needs_erase(transport, partition.c_str())) {
@@ -1732,10 +1771,18 @@
                 do_update(transport, "update.zip", slot_override, erase_first, skip_secondary || slot_all);
                 skip(1);
             }
-            wants_reboot = 1;
+            wants_reboot = true;
         } else if(!strcmp(*argv, "set_active")) {
             require(2);
             std::string slot = verify_slot(transport, std::string(argv[1]), false);
+            // Legacy support: verify_slot() removes leading underscores, we need to put them back
+            // in for old bootloaders. Legacy bootloaders do not have the slot-count variable but
+            // do have slot-suffixes.
+            std::string var;
+            if (!fb_getvar(transport, "slot-count", &var) &&
+                    fb_getvar(transport, "slot-suffixes", &var)) {
+                slot = "_" + slot;
+            }
             fb_set_active(slot.c_str());
             skip(2);
         } else if(!strcmp(*argv, "oem")) {
@@ -1787,12 +1834,15 @@
     if (wants_set_active) {
         fb_set_active(next_active.c_str());
     }
-    if (wants_reboot) {
+    if (wants_reboot && !skip_reboot) {
         fb_queue_reboot();
         fb_queue_wait_for_disconnect();
     } else if (wants_reboot_bootloader) {
         fb_queue_command("reboot-bootloader", "rebooting into bootloader");
         fb_queue_wait_for_disconnect();
+    } else if (wants_reboot_emergency) {
+        fb_queue_command("reboot-emergency", "rebooting into emergency download (EDL) mode");
+        fb_queue_wait_for_disconnect();
     }
 
     return fb_execute_queue(transport) ? EXIT_FAILURE : EXIT_SUCCESS;
diff --git a/fastboot/fastboot.h b/fastboot/fastboot.h
index 1932bab..6699b6a 100644
--- a/fastboot/fastboot.h
+++ b/fastboot/fastboot.h
@@ -43,7 +43,7 @@
 int fb_command_response(Transport* transport, const char* cmd, char* response);
 int fb_download_data(Transport* transport, const void* data, uint32_t size);
 int fb_download_data_sparse(Transport* transport, struct sparse_file* s);
-char *fb_get_error(void);
+const std::string fb_get_error();
 
 #define FB_COMMAND_SZ 64
 #define FB_RESPONSE_SZ 64
@@ -72,8 +72,6 @@
 char *mkmsg(const char *fmt, ...);
 __attribute__((__noreturn__)) void die(const char *fmt, ...);
 
-void get_my_path(char *path);
-
 /* Current product */
 extern char cur_product[FB_RESPONSE_SZ + 1];
 
diff --git a/fastboot/fastboot_protocol.txt b/fastboot/fastboot_protocol.txt
deleted file mode 100644
index 2801703..0000000
--- a/fastboot/fastboot_protocol.txt
+++ /dev/null
@@ -1,442 +0,0 @@
-FastBoot  Version  0.4
-----------------------
-
-The fastboot protocol is a mechanism for communicating with bootloaders
-over USB or ethernet.  It is designed to be very straightforward to implement,
-to allow it to be used across a wide range of devices and from hosts running
-Linux, Windows, or OSX.
-
-
-Basic Requirements
-------------------
-
-* USB
-  * Two bulk endpoints (in, out) are required
-  * Max packet size must be 64 bytes for full-speed, 512 bytes for
-    high-speed and 1024 bytes for Super Speed USB.
-  * The protocol is entirely host-driven and synchronous (unlike the
-    multi-channel, bi-directional, asynchronous ADB protocol)
-
-* TCP or UDP
-  * Device must be reachable via IP.
-  * Device will act as the server, fastboot will be the client.
-  * Fastboot data is wrapped in a simple protocol; see below for details.
-
-
-Transport and Framing
----------------------
-
-1. Host sends a command, which is an ascii string in a single
-   packet no greater than 64 bytes.
-
-2. Client response with a single packet no greater than 64 bytes.
-   The first four bytes of the response are "OKAY", "FAIL", "DATA", 
-   or "INFO".  Additional bytes may contain an (ascii) informative
-   message.
-
-   a. INFO -> the remaining 60 bytes are an informative message
-      (providing progress or diagnostic messages).  They should 
-      be displayed and then step #2 repeats
-
-   b. FAIL -> the requested command failed.  The remaining 60 bytes 
-      of the response (if present) provide a textual failure message 
-      to present to the user.  Stop.
-
-   c. OKAY -> the requested command completed successfully.  Go to #5
-
-   d. DATA -> the requested command is ready for the data phase.
-      A DATA response packet will be 12 bytes long, in the form of
-      DATA00000000 where the 8 digit hexadecimal number represents
-      the total data size to transfer.
-
-3. Data phase.  Depending on the command, the host or client will 
-   send the indicated amount of data.  Short packets are always 
-   acceptable and zero-length packets are ignored.  This phase continues
-   until the client has sent or received the number of bytes indicated
-   in the "DATA" response above.
-
-4. Client responds with a single packet no greater than 64 bytes.  
-   The first four bytes of the response are "OKAY", "FAIL", or "INFO".  
-   Similar to #2:
-
-   a. INFO -> display the remaining 60 bytes and return to #4
-   
-   b. FAIL -> display the remaining 60 bytes (if present) as a failure
-      reason and consider the command failed.  Stop.
-
-   c. OKAY -> success.  Go to #5
-
-5. Success.  Stop.
-
-
-Example Session
----------------
-
-Host:    "getvar:version"        request version variable
-
-Client:  "OKAY0.4"               return version "0.4"
-
-Host:    "getvar:nonexistant"    request some undefined variable
-
-Client:  "OKAY"                  return value ""
-
-Host:    "download:00001234"     request to send 0x1234 bytes of data
-
-Client:  "DATA00001234"          ready to accept data
-
-Host:    < 0x1234 bytes >        send data
-
-Client:  "OKAY"                  success
-
-Host:    "flash:bootloader"      request to flash the data to the bootloader
-
-Client:  "INFOerasing flash"     indicate status / progress
-         "INFOwriting flash"
-         "OKAY"                  indicate success
-
-Host:    "powerdown"             send a command
-
-Client:  "FAILunknown command"   indicate failure
-
-
-Command Reference
------------------
-
-* Command parameters are indicated by printf-style escape sequences.
-
-* Commands are ascii strings and sent without the quotes (which are
-  for illustration only here) and without a trailing 0 byte.
-
-* Commands that begin with a lowercase letter are reserved for this
-  specification.  OEM-specific commands should not begin with a 
-  lowercase letter, to prevent incompatibilities with future specs.
-
- "getvar:%s"           Read a config/version variable from the bootloader.
-                       The variable contents will be returned after the
-                       OKAY response.
-
- "download:%08x"       Write data to memory which will be later used
-                       by "boot", "ramdisk", "flash", etc.  The client
-                       will reply with "DATA%08x" if it has enough 
-                       space in RAM or "FAIL" if not.  The size of
-                       the download is remembered.
-
-  "verify:%08x"        Send a digital signature to verify the downloaded
-                       data.  Required if the bootloader is "secure"
-                       otherwise "flash" and "boot" will be ignored.
-
-  "flash:%s"           Write the previously downloaded image to the
-                       named partition (if possible).
-
-  "erase:%s"           Erase the indicated partition (clear to 0xFFs)
-
-  "boot"               The previously downloaded data is a boot.img
-                       and should be booted according to the normal
-                       procedure for a boot.img
-
-  "continue"           Continue booting as normal (if possible)
-
-  "reboot"             Reboot the device.
-
-  "reboot-bootloader"  Reboot back into the bootloader.
-                       Useful for upgrade processes that require upgrading
-                       the bootloader and then upgrading other partitions
-                       using the new bootloader.
-
-  "powerdown"          Power off the device.
-
-
-
-Client Variables
-----------------
-
-The "getvar:%s" command is used to read client variables which
-represent various information about the device and the software
-on it.
-
-The various currently defined names are:
-
-  version             Version of FastBoot protocol supported.
-                      It should be "0.4" for this document.
-
-  version-bootloader  Version string for the Bootloader.
-
-  version-baseband    Version string of the Baseband Software
-
-  product             Name of the product
-
-  serialno            Product serial number
-
-  secure              If the value is "yes", this is a secure
-                      bootloader requiring a signature before
-                      it will install or boot images.
-
-Names starting with a lowercase character are reserved by this
-specification.  OEM-specific names should not start with lowercase
-characters.
-
-
-TCP Protocol v1
----------------
-
-The TCP protocol is designed to be a simple way to use the fastboot protocol
-over ethernet if USB is not available.
-
-The device will open a TCP server on port 5554 and wait for a fastboot client
-to connect.
-
--- Handshake --
-Upon connecting, both sides will send a 4-byte handshake message to ensure they
-are speaking the same protocol. This consists of the ASCII characters "FB"
-followed by a 2-digit base-10 ASCII version number. For example, the version 1
-handshake message will be [FB01].
-
-If either side detects a malformed handshake, it should disconnect.
-
-The protocol version to use must be the minimum of the versions sent by each
-side; if either side cannot speak this protocol version, it should disconnect.
-
--- Fastboot Data --
-Once the handshake is complete, fastboot data will be sent as follows:
-
-  [data_size][data]
-
-Where data_size is an unsigned 8-byte big-endian binary value, and data is the
-fastboot packet. The 8-byte length is intended to provide future-proofing even
-though currently fastboot packets have a 4-byte maximum length.
-
--- Example --
-In this example the fastboot host queries the device for two variables,
-"version" and "none".
-
-Host    <connect to the device on port 5555>
-Host    FB01
-Device  FB01
-Host    [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x0E]getvar:version
-Device  [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x07]OKAY0.4
-Host    [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x0B]getvar:none
-Device  [0x00][0x00][0x00][0x00][0x00][0x00][0x00][0x04]OKAY
-Host    <disconnect>
-
-
-UDP Protocol v1
----------------
-
-The UDP protocol is more complex than TCP since we must implement reliability
-to ensure no packets are lost, but the general concept of wrapping the fastboot
-protocol is the same.
-
-Overview:
-  1. As with TCP, the device will listen on UDP port 5554.
-  2. Maximum UDP packet size is negotiated during initialization.
-  3. The host drives all communication; the device may only send a packet as a
-     response to a host packet.
-  4. If the host does not receive a response in 500ms it will re-transmit.
-
--- UDP Packet format --
-  +----------+----+-------+-------+--------------------+
-  | Byte #   | 0  |   1   | 2 - 3 |  4+                |
-  +----------+----+-------+-------+--------------------+
-  | Contents | ID | Flags | Seq # | Data               |
-  +----------+----+-------+-------+--------------------+
-
-  ID      Packet ID:
-            0x00: Error.
-            0x01: Query.
-            0x02: Initialization.
-            0x03: Fastboot.
-
-          Packet types are described in more detail below.
-
-  Flags   Packet flags: 0 0 0 0 0 0 0 C
-            C=1 indicates a continuation packet; the data is too large and will
-                continue in the next packet.
-
-            Remaining bits are reserved for future use and must be set to 0.
-
-  Seq #   2-byte packet sequence number (big-endian). The host will increment
-          this by 1 with each new packet, and the device must provide the
-          corresponding sequence number in the response packets.
-
-  Data    Packet data, not present in all packets.
-
--- Packet Types --
-Query     The host sends a query packet once on startup to sync with the device.
-          The host will not know the current sequence number, so the device must
-          respond to all query packets regardless of sequence number.
-
-          The response data field should contain a 2-byte big-endian value
-          giving the next expected sequence number.
-
-Init      The host sends an init packet once the query response is returned. The
-          device must abort any in-progress operation and prepare for a new
-          fastboot session. This message is meant to allow recovery if a
-          previous session failed, e.g. due to network error or user Ctrl+C.
-
-          The data field contains two big-endian 2-byte values, a protocol
-          version and the max UDP packet size (including the 4-byte header).
-          Both the host and device will send these values, and in each case
-          the minimum of the sent values must be used.
-
-Fastboot  These packets wrap the fastboot protocol. To write, the host will
-          send a packet with fastboot data, and the device will reply with an
-          empty packet as an ACK. To read, the host will send an empty packet,
-          and the device will reply with fastboot data. The device may not give
-          any data in the ACK packet.
-
-Error     The device may respond to any packet with an error packet to indicate
-          a UDP protocol error. The data field should contain an ASCII string
-          describing the error. This is the only case where a device is allowed
-          to return a packet ID other than the one sent by the host.
-
--- Packet Size --
-The maximum packet size is negotiated by the host and device in the Init packet.
-Devices must support at least 512-byte packets, but packet size has a direct
-correlation with download speed, so devices are strongly suggested to support at
-least 1024-byte packets. On a local network with 0.5ms round-trip time this will
-provide transfer rates of ~2MB/s. Over WiFi it will likely be significantly
-less.
-
-Query and Initialization packets, which are sent before size negotiation is
-complete, must always be 512 bytes or less.
-
--- Packet Re-Transmission --
-The host will re-transmit any packet that does not receive a response. The
-requirement of exactly one device response packet per host packet is how we
-achieve reliability and in-order delivery of packets.
-
-For simplicity of implementation, there is no windowing of multiple
-unacknowledged packets in this version of the protocol. The host will continue
-to send the same packet until a response is received. Windowing functionality
-may be implemented in future versions if necessary to increase performance.
-
-The first Query packet will only be attempted a small number of times, but
-subsequent packets will attempt to retransmit for at least 1 minute before
-giving up. This means a device may safely ignore host UDP packets for up to 1
-minute during long operations, e.g. writing to flash.
-
--- Continuation Packets --
-Any packet may set the continuation flag to indicate that the data is
-incomplete. Large data such as downloading an image may require many
-continuation packets. The receiver should respond to a continuation packet with
-an empty packet to acknowledge receipt. See examples below.
-
--- Summary --
-The host starts with a Query packet, then an Initialization packet, after
-which only Fastboot packets are sent. Fastboot packets may contain data from
-the host for writes, or from the device for reads, but not both.
-
-Given a next expected sequence number S and a received packet P, the device
-behavior should be:
-  if P is a Query packet:
-    * respond with a Query packet with S in the data field
-  else if P has sequence == S:
-    * process P and take any required action
-    * create a response packet R with the same ID and sequence as P, containing
-      any response data required.
-    * transmit R and save it in case of re-transmission
-    * increment S
-  else if P has sequence == S - 1:
-    * re-transmit the saved response packet R from above
-  else:
-    * ignore the packet
-
--- Examples --
-In the examples below, S indicates the starting client sequence number.
-
-Host                                    Client
-======================================================================
-[Initialization, S = 0x55AA]
-[Host: version 1, 2048-byte packets. Client: version 2, 1024-byte packets.]
-[Resulting values to use: version = 1, max packet size = 1024]
-ID   Flag SeqH SeqL Data                ID   Flag SeqH SeqL Data
-----------------------------------------------------------------------
-0x01 0x00 0x00 0x00
-                                        0x01 0x00 0x00 0x00 0x55 0xAA
-0x02 0x00 0x55 0xAA 0x00 0x01 0x08 0x00
-                                        0x02 0x00 0x55 0xAA 0x00 0x02 0x04 0x00
-
-----------------------------------------------------------------------
-[fastboot "getvar" commands, S = 0x0001]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x03  0x00  0x00  0x01  getvar:version
-                                        0x03  0x00  0x00  0x01
-0x03  0x00  0x00  0x02
-                                        0x03  0x00  0x00  0x02  OKAY0.4
-0x03  0x00  0x00  0x03  getvar:foo
-                                        0x03  0x00  0x00  0x03
-0x03  0x00  0x00  0x04
-                                        0x03  0x00  0x00  0x04  OKAY
-
-----------------------------------------------------------------------
-[fastboot "INFO" responses, S = 0x0000]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x03  0x00  0x00  0x00  <command>
-                                        0x03  0x00  0x00  0x00
-0x03  0x00  0x00  0x01
-                                        0x03  0x00  0x00  0x01  INFOWait1
-0x03  0x00  0x00  0x02
-                                        0x03  0x00  0x00  0x02  INFOWait2
-0x03  0x00  0x00  0x03
-                                        0x03  0x00  0x00  0x03  OKAY
-
-----------------------------------------------------------------------
-[Chunking 2100 bytes of data, max packet size = 1024, S = 0xFFFF]
-ID   Flag SeqH SeqL Data                ID   Flag SeqH SeqL Data
-----------------------------------------------------------------------
-0x03 0x00 0xFF 0xFF download:0000834
-                                        0x03 0x00 0xFF 0xFF
-0x03 0x00 0x00 0x00
-                                        0x03 0x00 0x00 0x00 DATA0000834
-0x03 0x01 0x00 0x01 <1020 bytes>
-                                        0x03 0x00 0x00 0x01
-0x03 0x01 0x00 0x02 <1020 bytes>
-                                        0x03 0x00 0x00 0x02
-0x03 0x00 0x00 0x03 <60 bytes>
-                                        0x03 0x00 0x00 0x03
-0x03 0x00 0x00 0x04
-                                        0x03 0x00 0x00 0x04 OKAY
-
-----------------------------------------------------------------------
-[Unknown ID error, S = 0x0000]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x10  0x00  0x00  0x00
-                                        0x00  0x00  0x00  0x00  <error message>
-
-----------------------------------------------------------------------
-[Host packet loss and retransmission, S = 0x0000]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x03  0x00  0x00  0x00  getvar:version [lost]
-0x03  0x00  0x00  0x00  getvar:version [lost]
-0x03  0x00  0x00  0x00  getvar:version
-                                        0x03  0x00  0x00  0x00
-0x03  0x00  0x00  0x01
-                                        0x03  0x00  0x00  0x01  OKAY0.4
-
-----------------------------------------------------------------------
-[Client packet loss and retransmission, S = 0x0000]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x03  0x00  0x00  0x00  getvar:version
-                                        0x03  0x00  0x00  0x00 [lost]
-0x03  0x00  0x00  0x00  getvar:version
-                                        0x03  0x00  0x00  0x00 [lost]
-0x03  0x00  0x00  0x00  getvar:version
-                                        0x03  0x00  0x00  0x00
-0x03  0x00  0x00  0x01
-                                        0x03  0x00  0x00  0x01  OKAY0.4
-
-----------------------------------------------------------------------
-[Host packet delayed, S = 0x0000]
-ID    Flags SeqH  SeqL  Data            ID    Flags SeqH  SeqL  Data
-----------------------------------------------------------------------
-0x03  0x00  0x00  0x00  getvar:version [delayed]
-0x03  0x00  0x00  0x00  getvar:version
-                                        0x03  0x00  0x00  0x00
-0x03  0x00  0x00  0x01
-                                        0x03  0x00  0x00  0x01  OKAY0.4
-0x03  0x00  0x00  0x00  getvar:version [arrives late with old seq#, is ignored]
diff --git a/fastboot/fs.cpp b/fastboot/fs.cpp
index 8539e23..5d9ccfe 100644
--- a/fastboot/fs.cpp
+++ b/fastboot/fs.cpp
@@ -1,7 +1,6 @@
 #include "fs.h"
 
 #include "fastboot.h"
-#include "make_ext4fs.h"
 #include "make_f2fs.h"
 
 #include <errno.h>
@@ -12,20 +11,24 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <ext4_utils/make_ext4fs.h>
 #include <sparse/sparse.h>
 
-static int generate_ext4_image(int fd, long long partSize, const std::string& initial_dir)
+static int generate_ext4_image(int fd, long long partSize, const std::string& initial_dir,
+                                       unsigned eraseBlkSize, unsigned logicalBlkSize)
 {
     if (initial_dir.empty()) {
-        make_ext4fs_sparse_fd(fd, partSize, NULL, NULL);
+        make_ext4fs_sparse_fd_align(fd, partSize, NULL, NULL, eraseBlkSize, logicalBlkSize);
     } else {
-        make_ext4fs_sparse_fd_directory(fd, partSize, NULL, NULL, initial_dir.c_str());
+        make_ext4fs_sparse_fd_directory_align(fd, partSize, NULL, NULL, initial_dir.c_str(),
+                                              eraseBlkSize, logicalBlkSize);
     }
     return 0;
 }
 
 #ifdef USE_F2FS
-static int generate_f2fs_image(int fd, long long partSize, const std::string& initial_dir)
+static int generate_f2fs_image(int fd, long long partSize, const std::string& initial_dir,
+                               unsigned /* unused */, unsigned /* unused */)
 {
     if (!initial_dir.empty()) {
         fprintf(stderr, "Unable to set initial directory on F2FS filesystem\n");
@@ -39,7 +42,8 @@
     const char* fs_type;  //must match what fastboot reports for partition type
 
     //returns 0 or error value
-    int (*generate)(int fd, long long partSize, const std::string& initial_dir);
+    int (*generate)(int fd, long long partSize, const std::string& initial_dir,
+                    unsigned eraseBlkSize, unsigned logicalBlkSize);
 
 } generators[] = {
     { "ext4", generate_ext4_image},
@@ -58,7 +62,7 @@
 }
 
 int fs_generator_generate(const struct fs_generator* gen, int tmpFileNo, long long partSize,
-    const std::string& initial_dir)
+    const std::string& initial_dir, unsigned eraseBlkSize, unsigned logicalBlkSize)
 {
-    return gen->generate(tmpFileNo, partSize, initial_dir);
+    return gen->generate(tmpFileNo, partSize, initial_dir, eraseBlkSize, logicalBlkSize);
 }
diff --git a/fastboot/fs.h b/fastboot/fs.h
index 0a68507..0a5f5a4 100644
--- a/fastboot/fs.h
+++ b/fastboot/fs.h
@@ -8,6 +8,6 @@
 
 const struct fs_generator* fs_get_generator(const std::string& fs_type);
 int fs_generator_generate(const struct fs_generator* gen, int tmpFileNo, long long partSize,
-    const std::string& initial_dir);
+    const std::string& initial_dir, unsigned eraseBlkSize = 0, unsigned logicalBlkSize = 0);
 
 #endif
diff --git a/fastboot/protocol.cpp b/fastboot/protocol.cpp
index 4850b4a..bfa83b0 100644
--- a/fastboot/protocol.cpp
+++ b/fastboot/protocol.cpp
@@ -36,16 +36,16 @@
 
 #include <algorithm>
 
+#include <android-base/stringprintf.h>
 #include <sparse/sparse.h>
 
 #include "fastboot.h"
 #include "transport.h"
 
-static char ERROR[128];
+static std::string g_error;
 
-char *fb_get_error(void)
-{
-    return ERROR;
+const std::string fb_get_error() {
+    return g_error;
 }
 
 static int check_response(Transport* transport, uint32_t size, char* response) {
@@ -54,14 +54,14 @@
     while (true) {
         int r = transport->Read(status, 64);
         if (r < 0) {
-            sprintf(ERROR, "status read failed (%s)", strerror(errno));
+            g_error = android::base::StringPrintf("status read failed (%s)", strerror(errno));
             transport->Close();
             return -1;
         }
         status[r] = 0;
 
         if (r < 4) {
-            sprintf(ERROR, "status malformed (%d bytes)", r);
+            g_error = android::base::StringPrintf("status malformed (%d bytes)", r);
             transport->Close();
             return -1;
         }
@@ -80,9 +80,9 @@
 
         if (!memcmp(status, "FAIL", 4)) {
             if (r > 4) {
-                sprintf(ERROR, "remote: %s", status + 4);
+                g_error = android::base::StringPrintf("remote: %s", status + 4);
             } else {
-                strcpy(ERROR, "remote failure");
+                g_error = "remote failure";
             }
             return -1;
         }
@@ -90,14 +90,14 @@
         if (!memcmp(status, "DATA", 4) && size > 0){
             uint32_t dsize = strtol(status + 4, 0, 16);
             if (dsize > size) {
-                strcpy(ERROR, "data size too large");
+                g_error = android::base::StringPrintf("data size too large (%d)", dsize);
                 transport->Close();
                 return -1;
             }
             return dsize;
         }
 
-        strcpy(ERROR,"unknown status code");
+        g_error = "unknown status code";
         transport->Close();
         break;
     }
@@ -108,7 +108,7 @@
 static int _command_start(Transport* transport, const char* cmd, uint32_t size, char* response) {
     size_t cmdsize = strlen(cmd);
     if (cmdsize > 64) {
-        sprintf(ERROR, "command too large");
+        g_error = android::base::StringPrintf("command too large (%zu)", cmdsize);
         return -1;
     }
 
@@ -117,7 +117,7 @@
     }
 
     if (transport->Write(cmd, cmdsize) != static_cast<int>(cmdsize)) {
-        sprintf(ERROR, "command write failed (%s)", strerror(errno));
+        g_error = android::base::StringPrintf("command write failed (%s)", strerror(errno));
         transport->Close();
         return -1;
     }
@@ -128,12 +128,12 @@
 static int _command_data(Transport* transport, const void* data, uint32_t size) {
     int r = transport->Write(data, size);
     if (r < 0) {
-        sprintf(ERROR, "data transfer failure (%s)", strerror(errno));
+        g_error = android::base::StringPrintf("data transfer failure (%s)", strerror(errno));
         transport->Close();
         return -1;
     }
     if (r != ((int) size)) {
-        sprintf(ERROR, "data transfer failure (short transfer)");
+        g_error = "data transfer failure (short transfer)";
         transport->Close();
         return -1;
     }
@@ -182,7 +182,7 @@
 
 int fb_download_data(Transport* transport, const void* data, uint32_t size) {
     char cmd[64];
-    sprintf(cmd, "download:%08x", size);
+    snprintf(cmd, sizeof(cmd), "download:%08x", size);
     return _command_send(transport, cmd, data, size, 0) < 0 ? -1 : 0;
 }
 
@@ -216,7 +216,7 @@
 
     if (len > TRANSPORT_BUF_SIZE) {
         if (transport_buf_len > 0) {
-            sprintf(ERROR, "internal error: transport_buf not empty\n");
+            g_error = "internal error: transport_buf not empty";
             return -1;
         }
         to_write = round_down(len, TRANSPORT_BUF_SIZE);
@@ -230,7 +230,7 @@
 
     if (len > 0) {
         if (len > TRANSPORT_BUF_SIZE) {
-            sprintf(ERROR, "internal error: too much left for transport_buf\n");
+            g_error = "internal error: too much left for transport_buf";
             return -1;
         }
         memcpy(transport_buf, ptr, len);
@@ -257,7 +257,7 @@
     }
 
     char cmd[64];
-    sprintf(cmd, "download:%08x", size);
+    snprintf(cmd, sizeof(cmd), "download:%08x", size);
     int r = _command_start(transport, cmd, size, 0);
     if (r < 0) {
         return -1;
diff --git a/fastboot/socket.cpp b/fastboot/socket.cpp
index 14ecd93..e56ffcf 100644
--- a/fastboot/socket.cpp
+++ b/fastboot/socket.cpp
@@ -167,7 +167,7 @@
 // Implements the Socket interface for TCP.
 class TcpSocket : public Socket {
   public:
-    TcpSocket(cutils_socket_t sock) : Socket(sock) {}
+    explicit TcpSocket(cutils_socket_t sock) : Socket(sock) {}
 
     bool Send(const void* data, size_t length) override;
     bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
diff --git a/fastboot/socket.h b/fastboot/socket.h
index de543db..7eaa0ab 100644
--- a/fastboot/socket.h
+++ b/fastboot/socket.h
@@ -104,7 +104,7 @@
 
   protected:
     // Protected constructor to force factory function use.
-    Socket(cutils_socket_t sock);
+    explicit Socket(cutils_socket_t sock);
 
     // Blocks up to |timeout_ms| until a read is possible on |sock_|, and sets |receive_timed_out_|
     // as appropriate to help distinguish between normal timeouts and fatal errors. Returns true if
diff --git a/fastboot/socket_test.cpp b/fastboot/socket_test.cpp
index affbdfd..373abc3 100644
--- a/fastboot/socket_test.cpp
+++ b/fastboot/socket_test.cpp
@@ -34,7 +34,7 @@
 // Creates connected sockets |server| and |client|. Returns true on success.
 bool MakeConnectedSockets(Socket::Protocol protocol, std::unique_ptr<Socket>* server,
                           std::unique_ptr<Socket>* client,
-                          const std::string hostname = "localhost") {
+                          const std::string& hostname = "localhost") {
     *server = Socket::NewServer(protocol, 0);
     if (*server == nullptr) {
         ADD_FAILURE() << "Failed to create server.";
diff --git a/fastboot/tcp.cpp b/fastboot/tcp.cpp
index e42c4e1..dd6fbf8 100644
--- a/fastboot/tcp.cpp
+++ b/fastboot/tcp.cpp
@@ -66,7 +66,7 @@
     int Close() override;
 
   private:
-    TcpTransport(std::unique_ptr<Socket> sock) : socket_(std::move(sock)) {}
+    explicit TcpTransport(std::unique_ptr<Socket> sock) : socket_(std::move(sock)) {}
 
     // Connects to the device and performs the initial handshake. Returns false and fills |error|
     // on failure.
diff --git a/fastboot/udp.cpp b/fastboot/udp.cpp
index b36bd60..53fb347 100644
--- a/fastboot/udp.cpp
+++ b/fastboot/udp.cpp
@@ -111,7 +111,7 @@
     int Close() override;
 
   private:
-    UdpTransport(std::unique_ptr<Socket> socket) : socket_(std::move(socket)) {}
+    explicit UdpTransport(std::unique_ptr<Socket> socket) : socket_(std::move(socket)) {}
 
     // Performs the UDP initialization procedure. Returns true on success.
     bool InitializeProtocol(std::string* error);
diff --git a/fastboot/usb_linux.cpp b/fastboot/usb_linux.cpp
index 02ffcd9..cdab4f1 100644
--- a/fastboot/usb_linux.cpp
+++ b/fastboot/usb_linux.cpp
@@ -43,11 +43,15 @@
 #include <linux/version.h>
 #include <linux/usb/ch9.h>
 
+#include <chrono>
 #include <memory>
+#include <thread>
 
 #include "fastboot.h"
 #include "usb.h"
 
+using namespace std::chrono_literals;
+
 #define MAX_RETRIES 5
 
 /* Timeout in seconds for usb_wait_for_disconnect.
@@ -89,7 +93,7 @@
 
 class LinuxUsbTransport : public Transport {
   public:
-    LinuxUsbTransport(std::unique_ptr<usb_handle> handle) : handle_(std::move(handle)) {}
+    explicit LinuxUsbTransport(std::unique_ptr<usb_handle> handle) : handle_(std::move(handle)) {}
     ~LinuxUsbTransport() override = default;
 
     ssize_t Read(void* data, size_t len) override;
@@ -145,7 +149,7 @@
     int in, out;
     unsigned i;
     unsigned e;
-    
+
     if (check(ptr, len, USB_DT_DEVICE, USB_DT_DEVICE_SIZE))
         return -1;
     dev = (struct usb_device_descriptor *)ptr;
@@ -333,15 +337,14 @@
     char desc[1024];
     int n, in, out, ifc;
 
-    DIR *busdir;
     struct dirent *de;
     int fd;
     int writable;
 
-    busdir = opendir(base);
+    std::unique_ptr<DIR, decltype(&closedir)> busdir(opendir(base), closedir);
     if (busdir == 0) return 0;
 
-    while ((de = readdir(busdir)) && (usb == nullptr)) {
+    while ((de = readdir(busdir.get())) && (usb == nullptr)) {
         if (badname(de->d_name)) continue;
 
         if (!convert_to_devfs_name(de->d_name, devname, sizeof(devname))) {
@@ -377,7 +380,6 @@
             }
         }
     }
-    closedir(busdir);
 
     return usb;
 }
@@ -428,7 +430,7 @@
         return -1;
     }
 
-    while(len > 0) {
+    while (len > 0) {
         int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
 
         bulk.ep = handle_->ep_in;
@@ -437,18 +439,17 @@
         bulk.timeout = 0;
         retry = 0;
 
-        do{
-           DBG("[ usb read %d fd = %d], fname=%s\n", xfer, handle_->desc, handle_->fname);
-           n = ioctl(handle_->desc, USBDEVFS_BULK, &bulk);
-           DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, handle_->fname, retry);
+        do {
+            DBG("[ usb read %d fd = %d], fname=%s\n", xfer, handle_->desc, handle_->fname);
+            n = ioctl(handle_->desc, USBDEVFS_BULK, &bulk);
+            DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, handle_->fname, retry);
 
-           if( n < 0 ) {
-            DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
-            if ( ++retry > MAX_RETRIES ) return -1;
-            sleep( 1 );
-           }
-        }
-        while( n < 0 );
+            if (n < 0) {
+                DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
+                if (++retry > MAX_RETRIES) return -1;
+                std::this_thread::sleep_for(1s);
+            }
+        } while (n < 0);
 
         count += n;
         len -= n;
@@ -490,9 +491,8 @@
 {
   double deadline = now() + WAIT_FOR_DISCONNECT_TIMEOUT;
   while (now() < deadline) {
-    if (access(handle_->fname, F_OK))
-      return 0;
-    usleep(50000);
+    if (access(handle_->fname, F_OK)) return 0;
+    std::this_thread::sleep_for(50ms);
   }
   return -1;
 }
diff --git a/fastboot/usb_osx.cpp b/fastboot/usb_osx.cpp
index ee5d575..9069baa 100644
--- a/fastboot/usb_osx.cpp
+++ b/fastboot/usb_osx.cpp
@@ -92,7 +92,6 @@
     HRESULT result;
     SInt32 score;
     UInt8 interfaceNumEndpoints;
-    UInt8 configuration;
 
     // Placing the constant KIOUSBFindInterfaceDontCare into the following
     // fields of the IOUSBFindInterfaceRequest structure will allow us to
@@ -102,13 +101,6 @@
     request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
     request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
 
-    // SetConfiguration will kill an existing UMS connection, so let's
-    // not do this if not necessary.
-    configuration = 0;
-    (*dev)->GetConfiguration(dev, &configuration);
-    if (configuration != 1)
-        (*dev)->SetConfiguration(dev, 1);
-
     // Get an iterator for the interfaces on the device
     kr = (*dev)->CreateInterfaceIterator(dev, &request, &iterator);
 
@@ -310,13 +302,6 @@
 
     // So, we have a device, finally. Grab its vitals.
 
-
-    kr = (*dev)->USBDeviceOpen(dev);
-    if (kr != 0) {
-        WARN("USBDeviceOpen");
-        goto out;
-    }
-
     kr = (*dev)->GetDeviceVendor(dev, &handle->info.dev_vendor);
     if (kr != 0) {
         ERR("GetDeviceVendor");
@@ -389,16 +374,12 @@
         goto error;
     }
 
-    out:
-
-    (*dev)->USBDeviceClose(dev);
     (*dev)->Release(dev);
     return 0;
 
     error:
 
     if (dev != NULL) {
-        (*dev)->USBDeviceClose(dev);
         (*dev)->Release(dev);
     }
 
diff --git a/fastboot/usb_windows.cpp b/fastboot/usb_windows.cpp
index 1cdeb32..3dab5ac 100644
--- a/fastboot/usb_windows.cpp
+++ b/fastboot/usb_windows.cpp
@@ -362,9 +362,3 @@
     std::unique_ptr<usb_handle> handle = find_usb_device(callback);
     return handle ? new WindowsUsbTransport(std::move(handle)) : nullptr;
 }
-
-// called from fastboot.c
-void sleep(int seconds)
-{
-    Sleep(seconds * 1000);
-}
diff --git a/fastboot/util_linux.cpp b/fastboot/util_linux.cpp
deleted file mode 100644
index b788199..0000000
--- a/fastboot/util_linux.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "fastboot.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <limits.h>
-
-void get_my_path(char *path)
-{
-    char proc[64];
-    char *x;
-
-    sprintf(proc, "/proc/%d/exe", getpid());
-    int err = readlink(proc, path, PATH_MAX - 1);
-
-    if(err <= 0) {
-        path[0] = 0;
-    } else {
-        path[err] = 0;
-        x = strrchr(path,'/');
-        if(x) x[1] = 0;
-    }
-}
diff --git a/fastboot/util_osx.cpp b/fastboot/util_osx.cpp
deleted file mode 100644
index ae0b024..0000000
--- a/fastboot/util_osx.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "fastboot.h"
-
-#import <Carbon/Carbon.h>
-#include <unistd.h>
-
-void get_my_path(char s[PATH_MAX])
-{
-    CFBundleRef mainBundle = CFBundleGetMainBundle();
-    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
-    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
-    CFRelease(executableURL);
-
-    CFStringGetFileSystemRepresentation(executablePathString, s, PATH_MAX-1);
-    CFRelease(executablePathString);
-
-	char *x;
-    x = strrchr(s, '/');
-    if(x) x[1] = 0;
-}
-
-
diff --git a/fastboot/util_windows.cpp b/fastboot/util_windows.cpp
deleted file mode 100644
index ec52f39..0000000
--- a/fastboot/util_windows.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "fastboot.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <limits.h>
-
-#include <windows.h>
-
-void get_my_path(char exe[PATH_MAX])
-{
-	char*  r;
-
-	GetModuleFileName( NULL, exe, PATH_MAX-1 );
-	exe[PATH_MAX-1] = 0;
-	r = strrchr( exe, '\\' );
-	if (r)
-		*r = 0;
-}
-
diff --git a/fingerprintd/Android.mk b/fingerprintd/Android.mk
deleted file mode 100644
index 48b9525..0000000
--- a/fingerprintd/Android.mk
+++ /dev/null
@@ -1,33 +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_CFLAGS := -Wall -Wextra -Werror -Wunused
-LOCAL_SRC_FILES := \
-	FingerprintDaemonProxy.cpp \
-	IFingerprintDaemon.cpp \
-	IFingerprintDaemonCallback.cpp \
-	fingerprintd.cpp
-LOCAL_MODULE := fingerprintd
-LOCAL_SHARED_LIBRARIES := \
-	libbinder \
-	liblog \
-	libhardware \
-	libutils \
-	libkeystore_binder
-include $(BUILD_EXECUTABLE)
diff --git a/fingerprintd/FingerprintDaemonProxy.cpp b/fingerprintd/FingerprintDaemonProxy.cpp
deleted file mode 100644
index b3c0cd7..0000000
--- a/fingerprintd/FingerprintDaemonProxy.cpp
+++ /dev/null
@@ -1,268 +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.
- */
-
-#define LOG_TAG "fingerprintd"
-
-#include <binder/IServiceManager.h>
-#include <hardware/hardware.h>
-#include <hardware/fingerprint.h>
-#include <hardware/hw_auth_token.h>
-#include <keystore/IKeystoreService.h>
-#include <keystore/keystore.h> // for error codes
-#include <utils/Log.h>
-
-#include "FingerprintDaemonProxy.h"
-
-namespace android {
-
-FingerprintDaemonProxy* FingerprintDaemonProxy::sInstance = NULL;
-
-// Supported fingerprint HAL version
-static const uint16_t kVersion = HARDWARE_MODULE_API_VERSION(2, 1);
-
-FingerprintDaemonProxy::FingerprintDaemonProxy() : mModule(NULL), mDevice(NULL), mCallback(NULL) {
-
-}
-
-FingerprintDaemonProxy::~FingerprintDaemonProxy() {
-    closeHal();
-}
-
-void FingerprintDaemonProxy::hal_notify_callback(const fingerprint_msg_t *msg) {
-    FingerprintDaemonProxy* instance = FingerprintDaemonProxy::getInstance();
-    const sp<IFingerprintDaemonCallback> callback = instance->mCallback;
-    if (callback == NULL) {
-        ALOGE("Invalid callback object");
-        return;
-    }
-    const int64_t device = (int64_t) instance->mDevice;
-    switch (msg->type) {
-        case FINGERPRINT_ERROR:
-            ALOGD("onError(%d)", msg->data.error);
-            callback->onError(device, msg->data.error);
-            break;
-        case FINGERPRINT_ACQUIRED:
-            ALOGD("onAcquired(%d)", msg->data.acquired.acquired_info);
-            callback->onAcquired(device, msg->data.acquired.acquired_info);
-            break;
-        case FINGERPRINT_AUTHENTICATED:
-            ALOGD("onAuthenticated(fid=%d, gid=%d)",
-                    msg->data.authenticated.finger.fid,
-                    msg->data.authenticated.finger.gid);
-            if (msg->data.authenticated.finger.fid != 0) {
-                const uint8_t* hat = reinterpret_cast<const uint8_t *>(&msg->data.authenticated.hat);
-                instance->notifyKeystore(hat, sizeof(msg->data.authenticated.hat));
-            }
-            callback->onAuthenticated(device,
-                    msg->data.authenticated.finger.fid,
-                    msg->data.authenticated.finger.gid);
-            break;
-        case FINGERPRINT_TEMPLATE_ENROLLING:
-            ALOGD("onEnrollResult(fid=%d, gid=%d, rem=%d)",
-                    msg->data.enroll.finger.fid,
-                    msg->data.enroll.finger.gid,
-                    msg->data.enroll.samples_remaining);
-            callback->onEnrollResult(device,
-                    msg->data.enroll.finger.fid,
-                    msg->data.enroll.finger.gid,
-                    msg->data.enroll.samples_remaining);
-            break;
-        case FINGERPRINT_TEMPLATE_REMOVED:
-            ALOGD("onRemove(fid=%d, gid=%d)",
-                    msg->data.removed.finger.fid,
-                    msg->data.removed.finger.gid);
-            callback->onRemoved(device,
-                    msg->data.removed.finger.fid,
-                    msg->data.removed.finger.gid);
-            break;
-        case FINGERPRINT_TEMPLATE_ENUMERATING:
-            ALOGD("onEnumerate(fid=%d, gid=%d, rem=%d)",
-                    msg->data.enumerated.finger.fid,
-                    msg->data.enumerated.finger.gid,
-                    msg->data.enumerated.remaining_templates);
-            callback->onEnumerate(device,
-                    msg->data.enumerated.finger.fid,
-                    msg->data.enumerated.finger.gid,
-                    msg->data.enumerated.remaining_templates);
-            break;
-        default:
-            ALOGE("invalid msg type: %d", msg->type);
-            return;
-    }
-}
-
-void FingerprintDaemonProxy::notifyKeystore(const uint8_t *auth_token, const size_t auth_token_length) {
-    if (auth_token != NULL && auth_token_length > 0) {
-        // TODO: cache service?
-        sp < IServiceManager > sm = defaultServiceManager();
-        sp < IBinder > binder = sm->getService(String16("android.security.keystore"));
-        sp < IKeystoreService > service = interface_cast < IKeystoreService > (binder);
-        if (service != NULL) {
-            status_t ret = service->addAuthToken(auth_token, auth_token_length);
-            if (ret != ResponseCode::NO_ERROR) {
-                ALOGE("Falure sending auth token to KeyStore: %d", ret);
-            }
-        } else {
-            ALOGE("Unable to communicate with KeyStore");
-        }
-    }
-}
-
-void FingerprintDaemonProxy::init(const sp<IFingerprintDaemonCallback>& callback) {
-    if (mCallback != NULL && IInterface::asBinder(callback) != IInterface::asBinder(mCallback)) {
-        IInterface::asBinder(mCallback)->unlinkToDeath(this);
-    }
-    IInterface::asBinder(callback)->linkToDeath(this);
-    mCallback = callback;
-}
-
-int32_t FingerprintDaemonProxy::enroll(const uint8_t* token, ssize_t tokenSize, int32_t groupId,
-        int32_t timeout) {
-    ALOG(LOG_VERBOSE, LOG_TAG, "enroll(gid=%d, timeout=%d)\n", groupId, timeout);
-    if (tokenSize != sizeof(hw_auth_token_t) ) {
-        ALOG(LOG_VERBOSE, LOG_TAG, "enroll() : invalid token size %zu\n", tokenSize);
-        return -1;
-    }
-    const hw_auth_token_t* authToken = reinterpret_cast<const hw_auth_token_t*>(token);
-    return mDevice->enroll(mDevice, authToken, groupId, timeout);
-}
-
-uint64_t FingerprintDaemonProxy::preEnroll() {
-    return mDevice->pre_enroll(mDevice);
-}
-
-int32_t FingerprintDaemonProxy::postEnroll() {
-    return mDevice->post_enroll(mDevice);
-}
-
-int32_t FingerprintDaemonProxy::stopEnrollment() {
-    ALOG(LOG_VERBOSE, LOG_TAG, "stopEnrollment()\n");
-    return mDevice->cancel(mDevice);
-}
-
-int32_t FingerprintDaemonProxy::authenticate(uint64_t sessionId, uint32_t groupId) {
-    ALOG(LOG_VERBOSE, LOG_TAG, "authenticate(sid=%" PRId64 ", gid=%d)\n", sessionId, groupId);
-    return mDevice->authenticate(mDevice, sessionId, groupId);
-}
-
-int32_t FingerprintDaemonProxy::stopAuthentication() {
-    ALOG(LOG_VERBOSE, LOG_TAG, "stopAuthentication()\n");
-    return mDevice->cancel(mDevice);
-}
-
-int32_t FingerprintDaemonProxy::remove(int32_t fingerId, int32_t groupId) {
-    ALOG(LOG_VERBOSE, LOG_TAG, "remove(fid=%d, gid=%d)\n", fingerId, groupId);
-    return mDevice->remove(mDevice, groupId, fingerId);
-}
-
-int32_t FingerprintDaemonProxy::enumerate() {
-    ALOG(LOG_VERBOSE, LOG_TAG, "enumerate()\n");
-    return mDevice->enumerate(mDevice);
-}
-
-uint64_t FingerprintDaemonProxy::getAuthenticatorId() {
-    return mDevice->get_authenticator_id(mDevice);
-}
-
-int32_t FingerprintDaemonProxy::setActiveGroup(int32_t groupId, const uint8_t* path,
-        ssize_t pathlen) {
-    if (pathlen >= PATH_MAX || pathlen <= 0) {
-        ALOGE("Bad path length: %zd", pathlen);
-        return -1;
-    }
-    // Convert to null-terminated string
-    char path_name[PATH_MAX];
-    memcpy(path_name, path, pathlen);
-    path_name[pathlen] = '\0';
-    ALOG(LOG_VERBOSE, LOG_TAG, "setActiveGroup(%d, %s, %zu)", groupId, path_name, pathlen);
-    return mDevice->set_active_group(mDevice, groupId, path_name);
-}
-
-int64_t FingerprintDaemonProxy::openHal() {
-    ALOG(LOG_VERBOSE, LOG_TAG, "nativeOpenHal()\n");
-    int err;
-    const hw_module_t *hw_module = NULL;
-    if (0 != (err = hw_get_module(FINGERPRINT_HARDWARE_MODULE_ID, &hw_module))) {
-        ALOGE("Can't open fingerprint HW Module, error: %d", err);
-        return 0;
-    }
-    if (NULL == hw_module) {
-        ALOGE("No valid fingerprint module");
-        return 0;
-    }
-
-    mModule = reinterpret_cast<const fingerprint_module_t*>(hw_module);
-
-    if (mModule->common.methods->open == NULL) {
-        ALOGE("No valid open method");
-        return 0;
-    }
-
-    hw_device_t *device = NULL;
-
-    if (0 != (err = mModule->common.methods->open(hw_module, NULL, &device))) {
-        ALOGE("Can't open fingerprint methods, error: %d", err);
-        return 0;
-    }
-
-    if (kVersion != device->version) {
-        ALOGE("Wrong fp version. Expected %d, got %d", kVersion, device->version);
-        // return 0; // FIXME
-    }
-
-    mDevice = reinterpret_cast<fingerprint_device_t*>(device);
-    err = mDevice->set_notify(mDevice, hal_notify_callback);
-    if (err < 0) {
-        ALOGE("Failed in call to set_notify(), err=%d", err);
-        return 0;
-    }
-
-    // Sanity check - remove
-    if (mDevice->notify != hal_notify_callback) {
-        ALOGE("NOTIFY not set properly: %p != %p", mDevice->notify, hal_notify_callback);
-    }
-
-    ALOG(LOG_VERBOSE, LOG_TAG, "fingerprint HAL successfully initialized");
-    return reinterpret_cast<int64_t>(mDevice); // This is just a handle
-}
-
-int32_t FingerprintDaemonProxy::closeHal() {
-    ALOG(LOG_VERBOSE, LOG_TAG, "nativeCloseHal()\n");
-    if (mDevice == NULL) {
-        ALOGE("No valid device");
-        return -ENOSYS;
-    }
-    int err;
-    if (0 != (err = mDevice->common.close(reinterpret_cast<hw_device_t*>(mDevice)))) {
-        ALOGE("Can't close fingerprint module, error: %d", err);
-        return err;
-    }
-    mDevice = NULL;
-    return 0;
-}
-
-void FingerprintDaemonProxy::binderDied(const wp<IBinder>& who) {
-    ALOGD("binder died");
-    int err;
-    if (0 != (err = closeHal())) {
-        ALOGE("Can't close fingerprint device, error: %d", err);
-    }
-    if (IInterface::asBinder(mCallback) == who) {
-        mCallback = NULL;
-    }
-}
-
-}
diff --git a/fingerprintd/FingerprintDaemonProxy.h b/fingerprintd/FingerprintDaemonProxy.h
deleted file mode 100644
index 145b4c9..0000000
--- a/fingerprintd/FingerprintDaemonProxy.h
+++ /dev/null
@@ -1,64 +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.
- */
-
-#ifndef FINGERPRINT_DAEMON_PROXY_H_
-#define FINGERPRINT_DAEMON_PROXY_H_
-
-#include "IFingerprintDaemon.h"
-#include "IFingerprintDaemonCallback.h"
-
-namespace android {
-
-class FingerprintDaemonProxy : public BnFingerprintDaemon {
-    public:
-        static FingerprintDaemonProxy* getInstance() {
-            if (sInstance == NULL) {
-                sInstance = new FingerprintDaemonProxy();
-            }
-            return sInstance;
-        }
-
-        // These reflect binder methods.
-        virtual void init(const sp<IFingerprintDaemonCallback>& callback);
-        virtual int32_t enroll(const uint8_t* token, ssize_t tokenLength, int32_t groupId, int32_t timeout);
-        virtual uint64_t preEnroll();
-        virtual int32_t postEnroll();
-        virtual int32_t stopEnrollment();
-        virtual int32_t authenticate(uint64_t sessionId, uint32_t groupId);
-        virtual int32_t stopAuthentication();
-        virtual int32_t remove(int32_t fingerId, int32_t groupId);
-        virtual int32_t enumerate();
-        virtual uint64_t getAuthenticatorId();
-        virtual int32_t setActiveGroup(int32_t groupId, const uint8_t* path, ssize_t pathLen);
-        virtual int64_t openHal();
-        virtual int32_t closeHal();
-
-    private:
-        FingerprintDaemonProxy();
-        virtual ~FingerprintDaemonProxy();
-        void binderDied(const wp<IBinder>& who);
-        void notifyKeystore(const uint8_t *auth_token, const size_t auth_token_length);
-        static void hal_notify_callback(const fingerprint_msg_t *msg);
-
-        static FingerprintDaemonProxy* sInstance;
-        fingerprint_module_t const* mModule;
-        fingerprint_device_t* mDevice;
-        sp<IFingerprintDaemonCallback> mCallback;
-};
-
-} // namespace android
-
-#endif // FINGERPRINT_DAEMON_PROXY_H_
diff --git a/fingerprintd/IFingerprintDaemon.cpp b/fingerprintd/IFingerprintDaemon.cpp
deleted file mode 100644
index bc4af56..0000000
--- a/fingerprintd/IFingerprintDaemon.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright 2015, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-*/
-
-#include <inttypes.h>
-
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <binder/PermissionCache.h>
-#include <utils/String16.h>
-#include <utils/Looper.h>
-#include <keystore/IKeystoreService.h>
-#include <keystore/keystore.h> // for error code
-#include <hardware/hardware.h>
-#include <hardware/fingerprint.h>
-#include <hardware/hw_auth_token.h>
-#include "IFingerprintDaemon.h"
-#include "IFingerprintDaemonCallback.h"
-
-namespace android {
-
-static const String16 USE_FINGERPRINT_PERMISSION("android.permission.USE_FINGERPRINT");
-static const String16 MANAGE_FINGERPRINT_PERMISSION("android.permission.MANAGE_FINGERPRINT");
-static const String16 HAL_FINGERPRINT_PERMISSION("android.permission.MANAGE_FINGERPRINT"); // TODO
-static const String16 DUMP_PERMISSION("android.permission.DUMP");
-
-const android::String16
-IFingerprintDaemon::descriptor("android.hardware.fingerprint.IFingerprintDaemon");
-
-const android::String16&
-IFingerprintDaemon::getInterfaceDescriptor() const {
-    return IFingerprintDaemon::descriptor;
-}
-
-status_t BnFingerprintDaemon::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
-        uint32_t flags) {
-    switch(code) {
-        case AUTHENTICATE: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const uint64_t sessionId = data.readInt64();
-            const uint32_t groupId = data.readInt32();
-            const int32_t ret = authenticate(sessionId, groupId);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        };
-        case CANCEL_AUTHENTICATION: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t ret = stopAuthentication();
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case ENROLL: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const ssize_t tokenSize = data.readInt32();
-            const uint8_t* token = static_cast<const uint8_t *>(data.readInplace(tokenSize));
-            const int32_t groupId = data.readInt32();
-            const int32_t timeout = data.readInt32();
-            const int32_t ret = enroll(token, tokenSize, groupId, timeout);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case CANCEL_ENROLLMENT: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t ret = stopEnrollment();
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case PRE_ENROLL: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const uint64_t ret = preEnroll();
-            reply->writeNoException();
-            reply->writeInt64(ret);
-            return NO_ERROR;
-        }
-        case POST_ENROLL: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t ret = postEnroll();
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case REMOVE: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t fingerId = data.readInt32();
-            const int32_t groupId = data.readInt32();
-            const int32_t ret = remove(fingerId, groupId);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case ENUMERATE: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t ret = enumerate();
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case GET_AUTHENTICATOR_ID: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const uint64_t ret = getAuthenticatorId();
-            reply->writeNoException();
-            reply->writeInt64(ret);
-            return NO_ERROR;
-        }
-        case SET_ACTIVE_GROUP: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t group = data.readInt32();
-            const ssize_t pathSize = data.readInt32();
-            const uint8_t* path = static_cast<const uint8_t *>(data.readInplace(pathSize));
-            const int32_t ret = setActiveGroup(group, path, pathSize);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case OPEN_HAL: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int64_t ret = openHal();
-            reply->writeNoException();
-            reply->writeInt64(ret);
-            return NO_ERROR;
-        }
-        case CLOSE_HAL: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            const int32_t ret = closeHal();
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case INIT: {
-            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
-            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
-                return PERMISSION_DENIED;
-            }
-            sp<IFingerprintDaemonCallback> callback =
-                    interface_cast<IFingerprintDaemonCallback>(data.readStrongBinder());
-            init(callback);
-            reply->writeNoException();
-            return NO_ERROR;
-        }
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-};
-
-bool BnFingerprintDaemon::checkPermission(const String16& permission) {
-    const IPCThreadState* ipc = IPCThreadState::self();
-    const int calling_pid = ipc->getCallingPid();
-    const int calling_uid = ipc->getCallingUid();
-    return PermissionCache::checkPermission(permission, calling_pid, calling_uid);
-}
-
-
-}; // namespace android
diff --git a/fingerprintd/IFingerprintDaemon.h b/fingerprintd/IFingerprintDaemon.h
deleted file mode 100644
index 23c36ff..0000000
--- a/fingerprintd/IFingerprintDaemon.h
+++ /dev/null
@@ -1,88 +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.
- */
-
-#ifndef IFINGERPRINT_DAEMON_H_
-#define IFINGERPRINT_DAEMON_H_
-
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-
-namespace android {
-
-class IFingerprintDaemonCallback;
-
-/*
-* Abstract base class for native implementation of FingerprintService.
-*
-* Note: This must be kept manually in sync with IFingerprintDaemon.aidl
-*/
-class IFingerprintDaemon : public IInterface, public IBinder::DeathRecipient {
-    public:
-        enum {
-           AUTHENTICATE = IBinder::FIRST_CALL_TRANSACTION + 0,
-           CANCEL_AUTHENTICATION = IBinder::FIRST_CALL_TRANSACTION + 1,
-           ENROLL = IBinder::FIRST_CALL_TRANSACTION + 2,
-           CANCEL_ENROLLMENT = IBinder::FIRST_CALL_TRANSACTION + 3,
-           PRE_ENROLL = IBinder::FIRST_CALL_TRANSACTION + 4,
-           REMOVE = IBinder::FIRST_CALL_TRANSACTION + 5,
-           GET_AUTHENTICATOR_ID = IBinder::FIRST_CALL_TRANSACTION + 6,
-           SET_ACTIVE_GROUP = IBinder::FIRST_CALL_TRANSACTION + 7,
-           OPEN_HAL = IBinder::FIRST_CALL_TRANSACTION + 8,
-           CLOSE_HAL = IBinder::FIRST_CALL_TRANSACTION + 9,
-           INIT = IBinder::FIRST_CALL_TRANSACTION + 10,
-           POST_ENROLL = IBinder::FIRST_CALL_TRANSACTION + 11,
-           ENUMERATE = IBinder::FIRST_CALL_TRANSACTION + 12,
-        };
-
-        IFingerprintDaemon() { }
-        virtual ~IFingerprintDaemon() { }
-        virtual const android::String16& getInterfaceDescriptor() const;
-
-        // Binder interface methods
-        virtual void init(const sp<IFingerprintDaemonCallback>& callback) = 0;
-        virtual int32_t enroll(const uint8_t* token, ssize_t tokenLength, int32_t groupId,
-                int32_t timeout) = 0;
-        virtual uint64_t preEnroll() = 0;
-        virtual int32_t postEnroll() = 0;
-        virtual int32_t stopEnrollment() = 0;
-        virtual int32_t authenticate(uint64_t sessionId, uint32_t groupId) = 0;
-        virtual int32_t stopAuthentication() = 0;
-        virtual int32_t remove(int32_t fingerId, int32_t groupId) = 0;
-        virtual int32_t enumerate() = 0;
-        virtual uint64_t getAuthenticatorId() = 0;
-        virtual int32_t setActiveGroup(int32_t groupId, const uint8_t* path, ssize_t pathLen) = 0;
-        virtual int64_t openHal() = 0;
-        virtual int32_t closeHal() = 0;
-
-        // DECLARE_META_INTERFACE - C++ client interface not needed
-        static const android::String16 descriptor;
-        static void hal_notify_callback(const fingerprint_msg_t *msg);
-};
-
-// ----------------------------------------------------------------------------
-
-class BnFingerprintDaemon: public BnInterface<IFingerprintDaemon> {
-    public:
-       virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
-               uint32_t flags = 0);
-    private:
-       bool checkPermission(const String16& permission);
-};
-
-} // namespace android
-
-#endif // IFINGERPRINT_DAEMON_H_
-
diff --git a/fingerprintd/IFingerprintDaemonCallback.cpp b/fingerprintd/IFingerprintDaemonCallback.cpp
deleted file mode 100644
index 19838c9..0000000
--- a/fingerprintd/IFingerprintDaemonCallback.cpp
+++ /dev/null
@@ -1,91 +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.
- */
-
-#define LOG_TAG "IFingerprintDaemonCallback"
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/Log.h>
-#include <binder/Parcel.h>
-
-#include "IFingerprintDaemonCallback.h"
-
-namespace android {
-
-class BpFingerprintDaemonCallback : public BpInterface<IFingerprintDaemonCallback>
-{
-public:
-    BpFingerprintDaemonCallback(const sp<IBinder>& impl) :
-            BpInterface<IFingerprintDaemonCallback>(impl) {
-    }
-    virtual status_t onEnrollResult(int64_t devId, int32_t fpId, int32_t gpId, int32_t rem) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(fpId);
-        data.writeInt32(gpId);
-        data.writeInt32(rem);
-        return remote()->transact(ON_ENROLL_RESULT, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    virtual status_t onAcquired(int64_t devId, int32_t acquiredInfo) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(acquiredInfo);
-        return remote()->transact(ON_ACQUIRED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    virtual status_t onAuthenticated(int64_t devId, int32_t fpId, int32_t gpId) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(fpId);
-        data.writeInt32(gpId);
-        return remote()->transact(ON_AUTHENTICATED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    virtual status_t onError(int64_t devId, int32_t error) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(error);
-        return remote()->transact(ON_ERROR, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    virtual status_t onRemoved(int64_t devId, int32_t fpId, int32_t gpId) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(fpId);
-        data.writeInt32(gpId);
-        return remote()->transact(ON_REMOVED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    virtual status_t onEnumerate(int64_t devId, int32_t fpId, int32_t gpId, int32_t rem) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor());
-        data.writeInt64(devId);
-        data.writeInt32(fpId);
-        data.writeInt32(gpId);
-        data.writeInt32(rem);
-        return remote()->transact(ON_ENUMERATE, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(FingerprintDaemonCallback,
-        "android.hardware.fingerprint.IFingerprintDaemonCallback");
-
-}; // namespace android
diff --git a/fingerprintd/IFingerprintDaemonCallback.h b/fingerprintd/IFingerprintDaemonCallback.h
deleted file mode 100644
index e343cb4..0000000
--- a/fingerprintd/IFingerprintDaemonCallback.h
+++ /dev/null
@@ -1,54 +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.
- */
-
-#ifndef IFINGERPRINT_DAEMON_CALLBACK_H_
-#define IFINGERPRINT_DAEMON_CALLBACK_H_
-
-#include <inttypes.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-
-namespace android {
-
-/*
-* Communication channel back to FingerprintService.java
-*/
-class IFingerprintDaemonCallback : public IInterface {
-    public:
-        // must be kept in sync with IFingerprintService.aidl
-        enum {
-            ON_ENROLL_RESULT = IBinder::FIRST_CALL_TRANSACTION + 0,
-            ON_ACQUIRED = IBinder::FIRST_CALL_TRANSACTION + 1,
-            ON_AUTHENTICATED = IBinder::FIRST_CALL_TRANSACTION + 2,
-            ON_ERROR = IBinder::FIRST_CALL_TRANSACTION + 3,
-            ON_REMOVED = IBinder::FIRST_CALL_TRANSACTION + 4,
-            ON_ENUMERATE = IBinder::FIRST_CALL_TRANSACTION + 5,
-        };
-
-        virtual status_t onEnrollResult(int64_t devId, int32_t fpId, int32_t gpId, int32_t rem) = 0;
-        virtual status_t onAcquired(int64_t devId, int32_t acquiredInfo) = 0;
-        virtual status_t onAuthenticated(int64_t devId, int32_t fingerId, int32_t groupId) = 0;
-        virtual status_t onError(int64_t devId, int32_t error) = 0;
-        virtual status_t onRemoved(int64_t devId, int32_t fingerId, int32_t groupId) = 0;
-        virtual status_t onEnumerate(int64_t devId, int32_t fingerId, int32_t groupId, int32_t rem) = 0;
-
-        DECLARE_META_INTERFACE(FingerprintDaemonCallback);
-};
-
-}; // namespace android
-
-#endif // IFINGERPRINT_DAEMON_CALLBACK_H_
diff --git a/fingerprintd/fingerprintd.cpp b/fingerprintd/fingerprintd.cpp
deleted file mode 100644
index 8fa7ed1..0000000
--- a/fingerprintd/fingerprintd.cpp
+++ /dev/null
@@ -1,55 +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.
- */
-
-#define LOG_TAG "fingerprintd"
-
-#include <cutils/log.h>
-#include <utils/Log.h>
-
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <binder/PermissionCache.h>
-#include <utils/String16.h>
-
-#include <keystore/IKeystoreService.h>
-#include <keystore/keystore.h> // for error codes
-
-#include <hardware/hardware.h>
-#include <hardware/fingerprint.h>
-#include <hardware/hw_auth_token.h>
-
-#include "FingerprintDaemonProxy.h"
-
-int main() {
-    ALOGI("Starting " LOG_TAG);
-    android::sp<android::IServiceManager> serviceManager = android::defaultServiceManager();
-    android::sp<android::FingerprintDaemonProxy> proxy =
-            android::FingerprintDaemonProxy::getInstance();
-    android::status_t ret = serviceManager->addService(
-            android::FingerprintDaemonProxy::descriptor, proxy);
-    if (ret != android::OK) {
-        ALOGE("Couldn't register " LOG_TAG " binder service!");
-        return -1;
-    }
-
-    /*
-     * We're the only thread in existence, so we're just going to process
-     * Binder transaction as a single-threaded program.
-     */
-    android::IPCThreadState::self()->joinThreadPool();
-    ALOGI("Done");
-    return 0;
-}
diff --git a/fs_mgr/.clang-format b/fs_mgr/.clang-format
new file mode 120000
index 0000000..4e6d9dd
--- /dev/null
+++ b/fs_mgr/.clang-format
@@ -0,0 +1 @@
+../init/.clang-format
\ No newline at end of file
diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk
index 28fff3f..2863a26 100644
--- a/fs_mgr/Android.mk
+++ b/fs_mgr/Android.mk
@@ -7,26 +7,30 @@
     libfec \
     libfec_rs \
     libbase \
-    libmincrypt \
-    libcrypto_static \
-    libext4_utils_static \
-    libsquashfs_utils
+    libcrypto_utils \
+    libcrypto \
+    libext4_utils \
+    libsquashfs_utils \
+    libselinux \
+    libavb
 
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
 LOCAL_SANITIZE := integer
 LOCAL_SRC_FILES:= \
-    fs_mgr.c \
-    fs_mgr_format.c \
-    fs_mgr_fstab.c \
-    fs_mgr_slotselect.c \
-    fs_mgr_verity.cpp
+    fs_mgr.cpp \
+    fs_mgr_dm_ioctl.cpp \
+    fs_mgr_format.cpp \
+    fs_mgr_fstab.cpp \
+    fs_mgr_slotselect.cpp \
+    fs_mgr_verity.cpp \
+    fs_mgr_avb.cpp \
+    fs_mgr_avb_ops.cpp \
+    fs_mgr_boot_config.cpp
 LOCAL_C_INCLUDES := \
     $(LOCAL_PATH)/include \
     system/vold \
-    system/extras/ext4_utils \
-    external/openssl/include \
-    bootable/recovery
+    system/extras/ext4_utils
 LOCAL_MODULE:= libfs_mgr
 LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
@@ -34,12 +38,15 @@
 ifneq (,$(filter userdebug,$(TARGET_BUILD_VARIANT)))
 LOCAL_CFLAGS += -DALLOW_ADBD_DISABLE_VERITY=1
 endif
+ifneq (,$(filter eng,$(TARGET_BUILD_VARIANT)))
+LOCAL_CFLAGS += -DALLOW_SKIP_SECURE_CHECK=1
+endif
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
 LOCAL_SANITIZE := integer
-LOCAL_SRC_FILES:= fs_mgr_main.c
+LOCAL_SRC_FILES:= fs_mgr_main.cpp
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
 LOCAL_MODULE:= fs_mgr
 LOCAL_MODULE_TAGS := optional
@@ -51,7 +58,7 @@
     libcutils \
     liblog \
     libc \
-    libsparse_static \
+    libsparse \
     libz \
     libselinux
 LOCAL_CXX_STL := libc++_static
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c
deleted file mode 100644
index 387f708..0000000
--- a/fs_mgr/fs_mgr.c
+++ /dev/null
@@ -1,901 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <ctype.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <libgen.h>
-#include <time.h>
-#include <sys/swap.h>
-#include <dirent.h>
-#include <ext4.h>
-#include <ext4_sb.h>
-#include <ext4_crypt_init_extensions.h>
-
-#include <linux/loop.h>
-#include <private/android_filesystem_config.h>
-#include <cutils/android_reboot.h>
-#include <cutils/partition_utils.h>
-#include <cutils/properties.h>
-#include <logwrap/logwrap.h>
-
-#include "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-#include "mincrypt/sha256.h"
-
-#include "ext4_utils.h"
-#include "wipe.h"
-
-#include "fs_mgr_priv.h"
-#include "fs_mgr_priv_verity.h"
-
-#define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
-#define KEY_IN_FOOTER  "footer"
-
-#define E2FSCK_BIN      "/system/bin/e2fsck"
-#define F2FS_FSCK_BIN  "/system/bin/fsck.f2fs"
-#define MKSWAP_BIN      "/system/bin/mkswap"
-
-#define FSCK_LOG_FILE   "/dev/fscklogs/log"
-
-#define ZRAM_CONF_DEV   "/sys/block/zram0/disksize"
-
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
-
-/*
- * gettime() - returns the time in seconds of the system's monotonic clock or
- * zero on error.
- */
-static time_t gettime(void)
-{
-    struct timespec ts;
-    int ret;
-
-    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
-    if (ret < 0) {
-        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
-        return 0;
-    }
-
-    return ts.tv_sec;
-}
-
-static int wait_for_file(const char *filename, int timeout)
-{
-    struct stat info;
-    time_t timeout_time = gettime() + timeout;
-    int ret = -1;
-
-    while (gettime() < timeout_time && ((ret = stat(filename, &info)) < 0))
-        usleep(10000);
-
-    return ret;
-}
-
-static void check_fs(char *blk_device, char *fs_type, char *target)
-{
-    int status;
-    int ret;
-    long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
-    char tmpmnt_opts[64] = "errors=remount-ro";
-    char *e2fsck_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")) {
-        /*
-         * First try to mount and unmount the filesystem.  We do this because
-         * the kernel is more efficient than e2fsck in running the journal and
-         * processing orphaned inodes, and on at least one device with a
-         * performance issue in the emmc firmware, it can take e2fsck 2.5 minutes
-         * to do what the kernel does in about a second.
-         *
-         * After mounting and unmounting the filesystem, run e2fsck, and if an
-         * error is recorded in the filesystem superblock, e2fsck will do a full
-         * check.  Otherwise, it does nothing.  If the kernel cannot mount the
-         * 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);
-        INFO("%s(): mount(%s,%s,%s)=%d: %s\n",
-             __func__, blk_device, target, fs_type, ret, strerror(errno));
-        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) {
-                    INFO("%s(): unmount(%s) succeeded\n", __func__, target);
-                    break;
-                }
-                ERROR("%s(): umount(%s)=%d: %s\n", __func__, target, result, strerror(errno));
-                sleep(1);
-            }
-        }
-
-        /*
-         * Some system images do not have e2fsck for licensing reasons
-         * (e.g. recent SDK system images). Detect these and skip the check.
-         */
-        if (access(E2FSCK_BIN, X_OK)) {
-            INFO("Not running %s on %s (executable not in system image)\n",
-                 E2FSCK_BIN, blk_device);
-        } else {
-            INFO("Running %s on %s\n", E2FSCK_BIN, blk_device);
-
-            ret = android_fork_execvp_ext(ARRAY_SIZE(e2fsck_argv), e2fsck_argv,
-                                          &status, true, LOG_KLOG | LOG_FILE,
-                                          true, FSCK_LOG_FILE, NULL, 0);
-
-            if (ret < 0) {
-                /* No need to check for error in fork, we can't really handle it now */
-                ERROR("Failed trying to run %s\n", E2FSCK_BIN);
-            }
-        }
-    } else if (!strcmp(fs_type, "f2fs")) {
-            char *f2fs_fsck_argv[] = {
-                    F2FS_FSCK_BIN,
-                    "-a",
-                    blk_device
-            };
-        INFO("Running %s -a %s\n", F2FS_FSCK_BIN, blk_device);
-
-        ret = android_fork_execvp_ext(ARRAY_SIZE(f2fs_fsck_argv), f2fs_fsck_argv,
-                                      &status, true, LOG_KLOG | LOG_FILE,
-                                      true, FSCK_LOG_FILE, NULL, 0);
-        if (ret < 0) {
-            /* No need to check for error in fork, we can't really handle it now */
-            ERROR("Failed trying to run %s\n", F2FS_FSCK_BIN);
-        }
-    }
-
-    return;
-}
-
-static void remove_trailing_slashes(char *n)
-{
-    int len;
-
-    len = strlen(n) - 1;
-    while ((*(n + len) == '/') && len) {
-      *(n + len) = '\0';
-      len--;
-    }
-}
-
-/*
- * Mark the given block device as read-only, using the BLKROSET ioctl.
- * Return 0 on success, and -1 on error.
- */
-int fs_mgr_set_blk_ro(const char *blockdev)
-{
-    int fd;
-    int rc = -1;
-    int ON = 1;
-
-    fd = TEMP_FAILURE_RETRY(open(blockdev, O_RDONLY | O_CLOEXEC));
-    if (fd < 0) {
-        // should never happen
-        return rc;
-    }
-
-    rc = ioctl(fd, BLKROSET, &ON);
-    close(fd);
-
-    return rc;
-}
-
-/*
- * __mount(): wrapper around the mount() system call which also
- * sets the underlying block device to read-only if the mount is read-only.
- * See "man 2 mount" for return values.
- */
-static int __mount(const char *source, const char *target, const struct fstab_rec *rec)
-{
-    unsigned long mountflags = rec->flags;
-    int ret;
-    int save_errno;
-
-    /* We need this because sometimes we have legacy symlinks
-     * that are lingering around and need cleaning up.
-     */
-    struct stat info;
-    if (!lstat(target, &info))
-        if ((info.st_mode & S_IFMT) == S_IFLNK)
-            unlink(target);
-    mkdir(target, 0755);
-    ret = mount(source, target, rec->fs_type, mountflags, rec->fs_options);
-    save_errno = errno;
-    INFO("%s(source=%s,target=%s,type=%s)=%d\n", __func__, source, target, rec->fs_type, ret);
-    if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
-        fs_mgr_set_blk_ro(source);
-    }
-    errno = save_errno;
-    return ret;
-}
-
-static int fs_match(char *in1, char *in2)
-{
-    char *n1;
-    char *n2;
-    int ret;
-
-    n1 = strdup(in1);
-    n2 = strdup(in2);
-
-    remove_trailing_slashes(n1);
-    remove_trailing_slashes(n2);
-
-    ret = !strcmp(n1, n2);
-
-    free(n1);
-    free(n2);
-
-    return ret;
-}
-
-static int device_is_debuggable() {
-    int ret = -1;
-    char value[PROP_VALUE_MAX];
-    ret = __system_property_get("ro.debuggable", value);
-    if (ret < 0)
-        return ret;
-    return strcmp(value, "1") ? 0 : 1;
-}
-
-static int device_is_secure() {
-    int ret = -1;
-    char value[PROP_VALUE_MAX];
-    ret = __system_property_get("ro.secure", value);
-    /* If error, we want to fail secure */
-    if (ret < 0)
-        return 1;
-    return strcmp(value, "0") ? 1 : 0;
-}
-
-static int device_is_force_encrypted() {
-    int ret = -1;
-    char value[PROP_VALUE_MAX];
-    ret = __system_property_get("ro.vold.forceencryption", value);
-    if (ret < 0)
-        return 0;
-    return strcmp(value, "1") ? 0 : 1;
-}
-
-/*
- * Tries to mount any of the consecutive fstab entries that match
- * the mountpoint of the one given by fstab->recs[start_idx].
- *
- * end_idx: On return, will be the last rec that was looked at.
- * attempted_idx: On return, will indicate which fstab rec
- *     succeeded. In case of failure, it will be the start_idx.
- * Returns
- *   -1 on failure with errno set to match the 1st mount failure.
- *   0 on success.
- */
-static int mount_with_alternatives(struct fstab *fstab, int start_idx, int *end_idx, int *attempted_idx)
-{
-    int i;
-    int mount_errno = 0;
-    int mounted = 0;
-
-    if (!end_idx || !attempted_idx || start_idx >= fstab->num_entries) {
-      errno = EINVAL;
-      if (end_idx) *end_idx = start_idx;
-      if (attempted_idx) *end_idx = start_idx;
-      return -1;
-    }
-
-    /* Hunt down an fstab entry for the same mount point that might succeed */
-    for (i = start_idx;
-         /* We required that fstab entries for the same mountpoint be consecutive */
-         i < fstab->num_entries && !strcmp(fstab->recs[start_idx].mount_point, fstab->recs[i].mount_point);
-         i++) {
-            /*
-             * Don't try to mount/encrypt the same mount point again.
-             * Deal with alternate entries for the same point which are required to be all following
-             * each other.
-             */
-            if (mounted) {
-                ERROR("%s(): skipping fstab dup mountpoint=%s rec[%d].fs_type=%s already mounted as %s.\n", __func__,
-                     fstab->recs[i].mount_point, i, fstab->recs[i].fs_type, fstab->recs[*attempted_idx].fs_type);
-                continue;
-            }
-
-            if (fstab->recs[i].fs_mgr_flags & MF_CHECK) {
-                check_fs(fstab->recs[i].blk_device, fstab->recs[i].fs_type,
-                         fstab->recs[i].mount_point);
-            }
-            if (!__mount(fstab->recs[i].blk_device, fstab->recs[i].mount_point, &fstab->recs[i])) {
-                *attempted_idx = i;
-                mounted = 1;
-                if (i != start_idx) {
-                    ERROR("%s(): Mounted %s on %s with fs_type=%s instead of %s\n", __func__,
-                         fstab->recs[i].blk_device, fstab->recs[i].mount_point, fstab->recs[i].fs_type,
-                         fstab->recs[start_idx].fs_type);
-                }
-            } else {
-                /* back up errno for crypto decisions */
-                mount_errno = errno;
-            }
-    }
-
-    /* Adjust i for the case where it was still withing the recs[] */
-    if (i < fstab->num_entries) --i;
-
-    *end_idx = i;
-    if (!mounted) {
-        *attempted_idx = start_idx;
-        errno = mount_errno;
-        return -1;
-    }
-    return 0;
-}
-
-static int translate_ext_labels(struct fstab_rec *rec)
-{
-    DIR *blockdir = NULL;
-    struct dirent *ent;
-    char *label;
-    size_t label_len;
-    int ret = -1;
-
-    if (strncmp(rec->blk_device, "LABEL=", 6))
-        return 0;
-
-    label = rec->blk_device + 6;
-    label_len = strlen(label);
-
-    if (label_len > 16) {
-        ERROR("FS label is longer than allowed by filesystem\n");
-        goto out;
-    }
-
-
-    blockdir = opendir("/dev/block");
-    if (!blockdir) {
-        ERROR("couldn't open /dev/block\n");
-        goto out;
-    }
-
-    while ((ent = readdir(blockdir))) {
-        int fd;
-        char super_buf[1024];
-        struct ext4_super_block *sb;
-
-        if (ent->d_type != DT_BLK)
-            continue;
-
-        fd = openat(dirfd(blockdir), ent->d_name, O_RDONLY);
-        if (fd < 0) {
-            ERROR("Cannot open block device /dev/block/%s\n", ent->d_name);
-            goto out;
-        }
-
-        if (TEMP_FAILURE_RETRY(lseek(fd, 1024, SEEK_SET)) < 0 ||
-            TEMP_FAILURE_RETRY(read(fd, super_buf, 1024)) != 1024) {
-            /* Probably a loopback device or something else without a readable
-             * superblock.
-             */
-            close(fd);
-            continue;
-        }
-
-        sb = (struct ext4_super_block *)super_buf;
-        if (sb->s_magic != EXT4_SUPER_MAGIC) {
-            INFO("/dev/block/%s not ext{234}\n", ent->d_name);
-            continue;
-        }
-
-        if (!strncmp(label, sb->s_volume_name, label_len)) {
-            char *new_blk_device;
-
-            if (asprintf(&new_blk_device, "/dev/block/%s", ent->d_name) < 0) {
-                ERROR("Could not allocate block device string\n");
-                goto out;
-            }
-
-            INFO("resolved label %s to %s\n", rec->blk_device, new_blk_device);
-
-            free(rec->blk_device);
-            rec->blk_device = new_blk_device;
-            ret = 0;
-            break;
-        }
-    }
-
-out:
-    closedir(blockdir);
-    return ret;
-}
-
-static bool needs_block_encryption(const struct fstab_rec* rec)
-{
-    if (device_is_force_encrypted() && fs_mgr_is_encryptable(rec)) return true;
-    if (rec->fs_mgr_flags & MF_FORCECRYPT) return true;
-    if (rec->fs_mgr_flags & MF_CRYPT) {
-        /* Check for existence of convert_fde breadcrumb file */
-        char convert_fde_name[PATH_MAX];
-        snprintf(convert_fde_name, sizeof(convert_fde_name),
-                 "%s/misc/vold/convert_fde", rec->mount_point);
-        if (access(convert_fde_name, F_OK) == 0) return true;
-    }
-    if (rec->fs_mgr_flags & MF_FORCEFDEORFBE) {
-        /* Check for absence of convert_fbe breadcrumb file */
-        char convert_fbe_name[PATH_MAX];
-        snprintf(convert_fbe_name, sizeof(convert_fbe_name),
-                 "%s/convert_fbe", rec->mount_point);
-        if (access(convert_fbe_name, F_OK) != 0) return true;
-    }
-    return false;
-}
-
-// Check to see if a mountable volume has encryption requirements
-static int handle_encryptable(const struct fstab_rec* rec)
-{
-    /* If this is block encryptable, need to trigger encryption */
-    if (needs_block_encryption(rec)) {
-        if (umount(rec->mount_point) == 0) {
-            return FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION;
-        } else {
-            WARNING("Could not umount %s (%s) - allow continue unencrypted\n",
-                    rec->mount_point, strerror(errno));
-            return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
-        }
-    } else if (rec->fs_mgr_flags & (MF_FILEENCRYPTION | MF_FORCEFDEORFBE)) {
-    // Deal with file level encryption
-        INFO("%s is file encrypted\n", rec->mount_point);
-        return FS_MGR_MNTALL_DEV_FILE_ENCRYPTED;
-    } else if (fs_mgr_is_encryptable(rec)) {
-        return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
-    } else {
-        return FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
-    }
-}
-
-/* When multiple fstab records share the same mount_point, it will
- * try to mount each one in turn, and ignore any duplicates after a
- * first successful mount.
- * Returns -1 on error, and  FS_MGR_MNTALL_* otherwise.
- */
-int fs_mgr_mount_all(struct fstab *fstab, int mount_mode)
-{
-    int i = 0;
-    int encryptable = FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
-    int error_count = 0;
-    int mret = -1;
-    int mount_errno = 0;
-    int attempted_idx = -1;
-
-    if (!fstab) {
-        return -1;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        /* Don't mount entries that are managed by vold or not for the mount mode*/
-        if ((fstab->recs[i].fs_mgr_flags & (MF_VOLDMANAGED | MF_RECOVERYONLY)) ||
-             ((mount_mode == MOUNT_MODE_LATE) && !fs_mgr_is_latemount(&fstab->recs[i])) ||
-             ((mount_mode == MOUNT_MODE_EARLY) && fs_mgr_is_latemount(&fstab->recs[i]))) {
-            continue;
-        }
-
-        /* Skip swap and raw partition entries such as boot, recovery, etc */
-        if (!strcmp(fstab->recs[i].fs_type, "swap") ||
-            !strcmp(fstab->recs[i].fs_type, "emmc") ||
-            !strcmp(fstab->recs[i].fs_type, "mtd")) {
-            continue;
-        }
-
-        /* Skip mounting the root partition, as it will already have been mounted */
-        if (!strcmp(fstab->recs[i].mount_point, "/")) {
-            if ((fstab->recs[i].fs_mgr_flags & MS_RDONLY) != 0) {
-                fs_mgr_set_blk_ro(fstab->recs[i].blk_device);
-            }
-            continue;
-        }
-
-        /* Translate LABEL= file system labels into block devices */
-        if (!strcmp(fstab->recs[i].fs_type, "ext2") ||
-            !strcmp(fstab->recs[i].fs_type, "ext3") ||
-            !strcmp(fstab->recs[i].fs_type, "ext4")) {
-            int tret = translate_ext_labels(&fstab->recs[i]);
-            if (tret < 0) {
-                ERROR("Could not translate label to block device\n");
-                continue;
-            }
-        }
-
-        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
-            wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
-        }
-
-        if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) {
-            int rc = fs_mgr_setup_verity(&fstab->recs[i]);
-            if (device_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
-                INFO("Verity disabled");
-            } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
-                ERROR("Could not set up verified partition, skipping!\n");
-                continue;
-            }
-        }
-        int last_idx_inspected;
-        int top_idx = i;
-
-        mret = mount_with_alternatives(fstab, i, &last_idx_inspected, &attempted_idx);
-        i = last_idx_inspected;
-        mount_errno = errno;
-
-        /* Deal with encryptability. */
-        if (!mret) {
-            int status = handle_encryptable(&fstab->recs[attempted_idx]);
-
-            if (status == FS_MGR_MNTALL_FAIL) {
-                /* Fatal error - no point continuing */
-                return status;
-            }
-
-            if (status != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
-                if (encryptable != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
-                    // Log and continue
-                    ERROR("Only one encryptable/encrypted partition supported\n");
-                }
-                encryptable = status;
-            }
-
-            /* Success!  Go get the next one */
-            continue;
-        }
-
-        /* mount(2) returned an error, handle the encryptable/formattable case */
-        bool wiped = partition_wiped(fstab->recs[top_idx].blk_device);
-        if (mret && mount_errno != EBUSY && mount_errno != EACCES &&
-            fs_mgr_is_formattable(&fstab->recs[top_idx]) && wiped) {
-            /* top_idx and attempted_idx point at the same partition, but sometimes
-             * at two different lines in the fstab.  Use the top one for formatting
-             * as that is the preferred one.
-             */
-            ERROR("%s(): %s is wiped and %s %s is formattable. Format it.\n", __func__,
-                  fstab->recs[top_idx].blk_device, fstab->recs[top_idx].mount_point,
-                  fstab->recs[top_idx].fs_type);
-            if (fs_mgr_is_encryptable(&fstab->recs[top_idx]) &&
-                strcmp(fstab->recs[top_idx].key_loc, KEY_IN_FOOTER)) {
-                int fd = open(fstab->recs[top_idx].key_loc, O_WRONLY, 0644);
-                if (fd >= 0) {
-                    INFO("%s(): also wipe %s\n", __func__, fstab->recs[top_idx].key_loc);
-                    wipe_block_device(fd, get_file_size(fd));
-                    close(fd);
-                } else {
-                    ERROR("%s(): %s wouldn't open (%s)\n", __func__,
-                          fstab->recs[top_idx].key_loc, strerror(errno));
-                }
-            }
-            if (fs_mgr_do_format(&fstab->recs[top_idx]) == 0) {
-                /* Let's replay the mount actions. */
-                i = top_idx - 1;
-                continue;
-            } else {
-                ERROR("%s(): Format failed. Suggest recovery...\n", __func__);
-                encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
-                continue;
-            }
-        }
-        if (mret && mount_errno != EBUSY && mount_errno != EACCES &&
-            fs_mgr_is_encryptable(&fstab->recs[attempted_idx])) {
-            if (wiped) {
-                ERROR("%s(): %s is wiped and %s %s is encryptable. Suggest recovery...\n", __func__,
-                      fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
-                      fstab->recs[attempted_idx].fs_type);
-                encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
-                continue;
-            } else {
-                /* Need to mount a tmpfs at this mountpoint for now, and set
-                 * properties that vold will query later for decrypting
-                 */
-                ERROR("%s(): possibly an encryptable blkdev %s for mount %s type %s )\n", __func__,
-                      fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
-                      fstab->recs[attempted_idx].fs_type);
-                if (fs_mgr_do_tmpfs_mount(fstab->recs[attempted_idx].mount_point) < 0) {
-                    ++error_count;
-                    continue;
-                }
-            }
-            encryptable = FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED;
-        } else {
-            if (fs_mgr_is_nofail(&fstab->recs[attempted_idx])) {
-                ERROR("Ignoring failure to mount an un-encryptable or wiped partition on"
-                       "%s at %s options: %s error: %s\n",
-                       fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
-                       fstab->recs[attempted_idx].fs_options, strerror(mount_errno));
-            } else {
-                ERROR("Failed to mount an un-encryptable or wiped partition on"
-                       "%s at %s options: %s error: %s\n",
-                       fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
-                       fstab->recs[attempted_idx].fs_options, strerror(mount_errno));
-                ++error_count;
-            }
-            continue;
-        }
-    }
-
-    if (error_count) {
-        return -1;
-    } else {
-        return encryptable;
-    }
-}
-
-/* If tmp_mount_point is non-null, mount the filesystem there.  This is for the
- * tmp mount we do to check the user password
- * If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
- * in turn, and stop on 1st success, or no more match.
- */
-int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device,
-                    char *tmp_mount_point)
-{
-    int i = 0;
-    int ret = FS_MGR_DOMNT_FAILED;
-    int mount_errors = 0;
-    int first_mount_errno = 0;
-    char *m;
-
-    if (!fstab) {
-        return ret;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        if (!fs_match(fstab->recs[i].mount_point, n_name)) {
-            continue;
-        }
-
-        /* We found our match */
-        /* If this swap or a raw partition, report an error */
-        if (!strcmp(fstab->recs[i].fs_type, "swap") ||
-            !strcmp(fstab->recs[i].fs_type, "emmc") ||
-            !strcmp(fstab->recs[i].fs_type, "mtd")) {
-            ERROR("Cannot mount filesystem of type %s on %s\n",
-                  fstab->recs[i].fs_type, n_blk_device);
-            goto out;
-        }
-
-        /* First check the filesystem if requested */
-        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
-            wait_for_file(n_blk_device, WAIT_TIMEOUT);
-        }
-
-        if (fstab->recs[i].fs_mgr_flags & MF_CHECK) {
-            check_fs(n_blk_device, fstab->recs[i].fs_type,
-                     fstab->recs[i].mount_point);
-        }
-
-        if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) {
-            int rc = fs_mgr_setup_verity(&fstab->recs[i]);
-            if (device_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
-                INFO("Verity disabled");
-            } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
-                ERROR("Could not set up verified partition, skipping!\n");
-                continue;
-            }
-        }
-
-        /* Now mount it where requested */
-        if (tmp_mount_point) {
-            m = tmp_mount_point;
-        } else {
-            m = fstab->recs[i].mount_point;
-        }
-        if (__mount(n_blk_device, m, &fstab->recs[i])) {
-            if (!first_mount_errno) first_mount_errno = errno;
-            mount_errors++;
-            continue;
-        } else {
-            ret = 0;
-            goto out;
-        }
-    }
-    if (mount_errors) {
-        ERROR("Cannot mount filesystem on %s at %s. error: %s\n",
-            n_blk_device, m, strerror(first_mount_errno));
-        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 */
-        ERROR("Cannot find mount point %s in fstab\n", fstab->recs[i].mount_point);
-    }
-
-out:
-    return ret;
-}
-
-/*
- * mount a tmpfs filesystem at the given point.
- * return 0 on success, non-zero on failure.
- */
-int fs_mgr_do_tmpfs_mount(char *n_name)
-{
-    int ret;
-
-    ret = mount("tmpfs", n_name, "tmpfs",
-                MS_NOATIME | MS_NOSUID | MS_NODEV, CRYPTO_TMPFS_OPTIONS);
-    if (ret < 0) {
-        ERROR("Cannot mount tmpfs filesystem at %s\n", n_name);
-        return -1;
-    }
-
-    /* Success */
-    return 0;
-}
-
-int fs_mgr_unmount_all(struct fstab *fstab)
-{
-    int i = 0;
-    int ret = 0;
-
-    if (!fstab) {
-        return -1;
-    }
-
-    while (fstab->recs[i].blk_device) {
-        if (umount(fstab->recs[i].mount_point)) {
-            ERROR("Cannot unmount filesystem at %s\n", fstab->recs[i].mount_point);
-            ret = -1;
-        }
-        i++;
-    }
-
-    return ret;
-}
-
-/* This must be called after mount_all, because the mkswap command needs to be
- * available.
- */
-int fs_mgr_swapon_all(struct fstab *fstab)
-{
-    int i = 0;
-    int flags = 0;
-    int err = 0;
-    int ret = 0;
-    int status;
-    char *mkswap_argv[2] = {
-        MKSWAP_BIN,
-        NULL
-    };
-
-    if (!fstab) {
-        return -1;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        /* Skip non-swap entries */
-        if (strcmp(fstab->recs[i].fs_type, "swap")) {
-            continue;
-        }
-
-        if (fstab->recs[i].zram_size > 0) {
-            /* A zram_size was specified, so we need to configure the
-             * device.  There is no point in having multiple zram devices
-             * on a system (all the memory comes from the same pool) so
-             * we can assume the device number is 0.
-             */
-            FILE *zram_fp;
-
-            zram_fp = fopen(ZRAM_CONF_DEV, "r+");
-            if (zram_fp == NULL) {
-                ERROR("Unable to open zram conf device %s\n", ZRAM_CONF_DEV);
-                ret = -1;
-                continue;
-            }
-            fprintf(zram_fp, "%d\n", fstab->recs[i].zram_size);
-            fclose(zram_fp);
-        }
-
-        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
-            wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
-        }
-
-        /* Initialize the swap area */
-        mkswap_argv[1] = fstab->recs[i].blk_device;
-        err = android_fork_execvp_ext(ARRAY_SIZE(mkswap_argv), mkswap_argv,
-                                      &status, true, LOG_KLOG, false, NULL,
-                                      NULL, 0);
-        if (err) {
-            ERROR("mkswap failed for %s\n", fstab->recs[i].blk_device);
-            ret = -1;
-            continue;
-        }
-
-        /* If -1, then no priority was specified in fstab, so don't set
-         * SWAP_FLAG_PREFER or encode the priority */
-        if (fstab->recs[i].swap_prio >= 0) {
-            flags = (fstab->recs[i].swap_prio << SWAP_FLAG_PRIO_SHIFT) &
-                    SWAP_FLAG_PRIO_MASK;
-            flags |= SWAP_FLAG_PREFER;
-        } else {
-            flags = 0;
-        }
-        err = swapon(fstab->recs[i].blk_device, flags);
-        if (err) {
-            ERROR("swapon failed for %s\n", fstab->recs[i].blk_device);
-            ret = -1;
-        }
-    }
-
-    return ret;
-}
-
-/*
- * key_loc must be at least PROPERTY_VALUE_MAX bytes long
- *
- * real_blk_device must be at least PROPERTY_VALUE_MAX bytes long
- */
-int fs_mgr_get_crypt_info(struct fstab *fstab, char *key_loc, char *real_blk_device, int size)
-{
-    int i = 0;
-
-    if (!fstab) {
-        return -1;
-    }
-    /* Initialize return values to null strings */
-    if (key_loc) {
-        *key_loc = '\0';
-    }
-    if (real_blk_device) {
-        *real_blk_device = '\0';
-    }
-
-    /* Look for the encryptable partition to find the data */
-    for (i = 0; i < fstab->num_entries; i++) {
-        /* Don't deal with vold managed enryptable partitions here */
-        if (fstab->recs[i].fs_mgr_flags & MF_VOLDMANAGED) {
-            continue;
-        }
-        if (!(fstab->recs[i].fs_mgr_flags
-              & (MF_CRYPT | MF_FORCECRYPT | MF_FORCEFDEORFBE))) {
-            continue;
-        }
-
-        /* We found a match */
-        if (key_loc) {
-            strlcpy(key_loc, fstab->recs[i].key_loc, size);
-        }
-        if (real_blk_device) {
-            strlcpy(real_blk_device, fstab->recs[i].blk_device, size);
-        }
-        break;
-    }
-
-    return 0;
-}
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
new file mode 100644
index 0000000..803b894
--- /dev/null
+++ b/fs_mgr/fs_mgr.cpp
@@ -0,0 +1,1386 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/swap.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#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>
+#include <cutils/partition_utils.h>
+#include <cutils/properties.h>
+#include <ext4_utils/ext4.h>
+#include <ext4_utils/ext4_crypt_init_extensions.h>
+#include <ext4_utils/ext4_sb.h>
+#include <ext4_utils/ext4_utils.h>
+#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 "fs_mgr.h"
+#include "fs_mgr_avb.h"
+#include "fs_mgr_priv.h"
+#include "fs_mgr_priv_dm_ioctl.h"
+
+#define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
+#define KEY_IN_FOOTER  "footer"
+
+#define E2FSCK_BIN      "/system/bin/e2fsck"
+#define F2FS_FSCK_BIN   "/system/bin/fsck.f2fs"
+#define MKSWAP_BIN      "/system/bin/mkswap"
+#define TUNE2FS_BIN     "/system/bin/tune2fs"
+
+#define FSCK_LOG_FILE   "/dev/fscklogs/log"
+
+#define ZRAM_CONF_DEV   "/sys/block/zram0/disksize"
+#define ZRAM_CONF_MCS   "/sys/block/zram0/max_comp_streams"
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
+
+// record fs stat
+enum FsStatFlags {
+    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_RO_UNMOUNT_FAILED = 0x0080,
+    FS_STAT_FULL_MOUNT_FAILED = 0x0100,
+    FS_STAT_E2FSCK_FAILED = 0x0200,
+    FS_STAT_E2FSCK_FS_FIXED = 0x0400,
+    FS_STAT_EXT4_INVALID_MAGIC = 0x0800,
+};
+
+/*
+ * gettime() - returns the time in seconds of the system's monotonic clock or
+ * zero on error.
+ */
+static time_t gettime(void)
+{
+    struct timespec ts;
+    int ret;
+
+    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
+    if (ret < 0) {
+        PERROR << "clock_gettime(CLOCK_MONOTONIC) failed";
+        return 0;
+    }
+
+    return ts.tv_sec;
+}
+
+static int wait_for_file(const char *filename, int timeout)
+{
+    struct stat info;
+    time_t timeout_time = gettime() + timeout;
+    int ret = -1;
+
+    while (gettime() < timeout_time && ((ret = stat(filename, &info)) < 0))
+        usleep(10000);
+
+    return ret;
+}
+
+static void log_fs_stat(const char* blk_device, int fs_stat)
+{
+    if ((fs_stat & FS_STAT_IS_EXT4) == 0) return; // only log ext4
+    std::string msg = android::base::StringPrintf("\nfs_stat,%s,0x%x\n", blk_device, fs_stat);
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(FSCK_LOG_FILE, O_WRONLY | O_CLOEXEC |
+                                                        O_APPEND | O_CREAT, 0664)));
+    if (fd == -1 || !android::base::WriteStringToFd(msg, fd)) {
+        LWARNING << __FUNCTION__ << "() cannot log " << msg;
+    }
+}
+
+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, "-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
+         * processing orphaned inodes, and on at least one device with a
+         * performance issue in the emmc firmware, it can take e2fsck 2.5 minutes
+         * to do what the kernel does in about a second.
+         *
+         * After mounting and unmounting the filesystem, run e2fsck, and if an
+         * error is recorded in the filesystem superblock, e2fsck will do a full
+         * check.  Otherwise, it does nothing.  If the kernel cannot mount the
+         * filesytsem due to an error, e2fsck is still run to do a full check
+         * fix the filesystem.
+         */
+        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));
+            }
+            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;
+            }
+        }
+
+        /*
+         * Some system images do not have e2fsck for licensing reasons
+         * (e.g. recent SDK system images). Detect these and skip the check.
+         */
+        if (access(E2FSCK_BIN, X_OK)) {
+            LINFO << "Not running " << E2FSCK_BIN << " on " << blk_device
+                  << " (executable not in system image)";
+        } else {
+            LINFO << "Running " << E2FSCK_BIN << " on " << blk_device;
+            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 */
+                LERROR << "Failed trying to run " << E2FSCK_BIN;
+                *fs_stat |= FS_STAT_E2FSCK_FAILED;
+            } else if (status != 0) {
+                LINFO << "e2fsck returned status 0x" << std::hex << status;
+                *fs_stat |= FS_STAT_E2FSCK_FS_FIXED;
+            }
+        }
+    } else if (!strcmp(fs_type, "f2fs")) {
+            const char *f2fs_fsck_argv[] = {
+                    F2FS_FSCK_BIN,
+                    "-a",
+                    blk_device
+            };
+        LINFO << "Running " << F2FS_FSCK_BIN << " -a " << blk_device;
+
+        ret = android_fork_execvp_ext(ARRAY_SIZE(f2fs_fsck_argv),
+                                      const_cast<char **>(f2fs_fsck_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 */
+            LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
+        }
+    }
+
+    return;
+}
+
+/* Function to read the primary superblock */
+static int read_super_block(int fd, struct ext4_super_block *sb)
+{
+    off64_t ret;
+
+    ret = lseek64(fd, 1024, SEEK_SET);
+    if (ret < 0)
+        return ret;
+
+    ret = read(fd, sb, sizeof(*sb));
+    if (ret < 0)
+        return ret;
+    if (ret != sizeof(*sb))
+        return ret;
+
+    return 0;
+}
+
+static ext4_fsblk_t ext4_blocks_count(struct ext4_super_block *es)
+{
+    return ((ext4_fsblk_t)le32_to_cpu(es->s_blocks_count_hi) << 32) |
+            le32_to_cpu(es->s_blocks_count_lo);
+}
+
+static ext4_fsblk_t ext4_r_blocks_count(struct ext4_super_block *es)
+{
+    return ((ext4_fsblk_t)le32_to_cpu(es->s_r_blocks_count_hi) << 32) |
+            le32_to_cpu(es->s_r_blocks_count_lo);
+}
+
+static int do_quota_with_shutdown_check(char *blk_device, char *fs_type,
+                                        struct fstab_rec *rec, int *fs_stat)
+{
+    int force_check = 0;
+    if (!strcmp(fs_type, "ext4")) {
+        /*
+         * Some system images do not have tune2fs for licensing reasons
+         * Detect these and skip reserve blocks.
+         */
+        if (access(TUNE2FS_BIN, X_OK)) {
+            LERROR << "Not running " << TUNE2FS_BIN << " on "
+                   << blk_device << " (executable not in system image)";
+        } else {
+            const char* arg1 = nullptr;
+            const char* arg2 = nullptr;
+            int status = 0;
+            int ret = 0;
+            android::base::unique_fd fd(
+                TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC)));
+            if (fd >= 0) {
+                struct ext4_super_block sb;
+                ret = read_super_block(fd, &sb);
+                if (ret < 0) {
+                    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;
+                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:"
+                          << std::hex << sb.s_state
+                          << "incompat flag:" << std::hex << sb.s_feature_incompat;
+                    force_check = 1;
+                    *fs_stat |= FS_STAT_UNCLEAN_SHUTDOWN;
+                }
+                int has_quota = (sb.s_feature_ro_compat
+                        & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_QUOTA)) != 0;
+                int want_quota = fs_mgr_is_quota(rec) != 0;
+
+                if (has_quota == want_quota) {
+                    LINFO << "Requested quota status is match on " << blk_device;
+                    return force_check;
+                } else if (want_quota) {
+                    LINFO << "Enabling quota on " << blk_device;
+                    arg1 = "-Oquota";
+                    arg2 = "-Qusrquota,grpquota";
+                    force_check = 1;
+                    *fs_stat |= FS_STAT_QUOTA_ENABLED;
+                } else {
+                    LINFO << "Disabling quota on " << blk_device;
+                    arg1 = "-Q^usrquota,^grpquota";
+                    arg2 = "-O^quota";
+                }
+            } else {
+                PERROR << "Failed to open '" << blk_device << "'";
+                return force_check;
+            }
+
+            const char *tune2fs_argv[] = {
+                TUNE2FS_BIN,
+                arg1,
+                arg2,
+                blk_device,
+            };
+            ret = android_fork_execvp_ext(ARRAY_SIZE(tune2fs_argv),
+                                          const_cast<char **>(tune2fs_argv),
+                                          &status, true, LOG_KLOG | LOG_FILE,
+                                          true, NULL, NULL, 0);
+            if (ret < 0) {
+                /* No need to check for error in fork, we can't really handle it now */
+                LERROR << "Failed trying to run " << TUNE2FS_BIN;
+                *fs_stat |= FS_STAT_TUNE2FS_FAILED;
+            }
+        }
+    }
+    return force_check;
+}
+
+static void do_reserved_size(char *blk_device, char *fs_type, struct fstab_rec *rec, int *fs_stat)
+{
+    /* Check for the types of filesystems we know how to check */
+    if (!strcmp(fs_type, "ext2") || !strcmp(fs_type, "ext3") || !strcmp(fs_type, "ext4")) {
+        /*
+         * Some system images do not have tune2fs for licensing reasons
+         * Detect these and skip reserve blocks.
+         */
+        if (access(TUNE2FS_BIN, X_OK)) {
+            LERROR << "Not running " << TUNE2FS_BIN << " on "
+                   << blk_device << " (executable not in system image)";
+        } else {
+            LINFO << "Running " << TUNE2FS_BIN << " on " << blk_device;
+
+            int status = 0;
+            int ret = 0;
+            unsigned long reserved_blocks = 0;
+            android::base::unique_fd fd(
+                TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC)));
+            if (fd >= 0) {
+                struct ext4_super_block sb;
+                ret = read_super_block(fd, &sb);
+                if (ret < 0) {
+                    PERROR << "Can't read '" << blk_device << "' super block";
+                    return;
+                }
+                reserved_blocks = rec->reserved_size / EXT4_BLOCK_SIZE(&sb);
+                unsigned long reserved_threshold = ext4_blocks_count(&sb) * 0.02;
+                if (reserved_threshold < reserved_blocks) {
+                    LWARNING << "Reserved blocks " << reserved_blocks
+                             << " is too large";
+                    reserved_blocks = reserved_threshold;
+                }
+
+                if (ext4_r_blocks_count(&sb) == reserved_blocks) {
+                    LINFO << "Have reserved same blocks";
+                    return;
+                }
+            } else {
+                PERROR << "Failed to open '" << blk_device << "'";
+                return;
+            }
+
+            char buf[16] = {0};
+            snprintf(buf, sizeof (buf), "-r %lu", reserved_blocks);
+            const char *tune2fs_argv[] = {
+                TUNE2FS_BIN,
+                buf,
+                blk_device,
+            };
+
+            ret = android_fork_execvp_ext(ARRAY_SIZE(tune2fs_argv),
+                                          const_cast<char **>(tune2fs_argv),
+                                          &status, true, LOG_KLOG | LOG_FILE,
+                                          true, NULL, NULL, 0);
+
+            if (ret < 0) {
+                /* No need to check for error in fork, we can't really handle it now */
+                LERROR << "Failed trying to run " << TUNE2FS_BIN;
+                *fs_stat |= FS_STAT_TUNE2FS_FAILED;
+            }
+        }
+    }
+}
+
+static void remove_trailing_slashes(char *n)
+{
+    int len;
+
+    len = strlen(n) - 1;
+    while ((*(n + len) == '/') && len) {
+      *(n + len) = '\0';
+      len--;
+    }
+}
+
+/*
+ * Mark the given block device as read-only, using the BLKROSET ioctl.
+ * Return 0 on success, and -1 on error.
+ */
+int fs_mgr_set_blk_ro(const char *blockdev)
+{
+    int fd;
+    int rc = -1;
+    int ON = 1;
+
+    fd = TEMP_FAILURE_RETRY(open(blockdev, O_RDONLY | O_CLOEXEC));
+    if (fd < 0) {
+        // should never happen
+        return rc;
+    }
+
+    rc = ioctl(fd, BLKROSET, &ON);
+    close(fd);
+
+    return rc;
+}
+
+/*
+ * __mount(): wrapper around the mount() system call which also
+ * sets the underlying block device to read-only if the mount is read-only.
+ * See "man 2 mount" for return values.
+ */
+static int __mount(const char *source, const char *target, const struct fstab_rec *rec)
+{
+    unsigned long mountflags = rec->flags;
+    int ret;
+    int save_errno;
+
+    /* We need this because sometimes we have legacy symlinks
+     * that are lingering around and need cleaning up.
+     */
+    struct stat info;
+    if (!lstat(target, &info))
+        if ((info.st_mode & S_IFMT) == S_IFLNK)
+            unlink(target);
+    mkdir(target, 0755);
+    ret = mount(source, target, rec->fs_type, mountflags, rec->fs_options);
+    save_errno = errno;
+    LINFO << __FUNCTION__ << "(source=" << source << ",target="
+          << target << ",type=" << rec->fs_type << ")=" << ret;
+    if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
+        fs_mgr_set_blk_ro(source);
+    }
+    errno = save_errno;
+    return ret;
+}
+
+static int fs_match(const char *in1, const char *in2)
+{
+    char *n1;
+    char *n2;
+    int ret;
+
+    n1 = strdup(in1);
+    n2 = strdup(in2);
+
+    remove_trailing_slashes(n1);
+    remove_trailing_slashes(n2);
+
+    ret = !strcmp(n1, n2);
+
+    free(n1);
+    free(n2);
+
+    return ret;
+}
+
+static int device_is_force_encrypted() {
+    int ret = -1;
+    char value[PROP_VALUE_MAX];
+    ret = __system_property_get("ro.vold.forceencryption", value);
+    if (ret < 0)
+        return 0;
+    return strcmp(value, "1") ? 0 : 1;
+}
+
+/*
+ * Tries to mount any of the consecutive fstab entries that match
+ * the mountpoint of the one given by fstab->recs[start_idx].
+ *
+ * end_idx: On return, will be the last rec that was looked at.
+ * attempted_idx: On return, will indicate which fstab rec
+ *     succeeded. In case of failure, it will be the start_idx.
+ * Returns
+ *   -1 on failure with errno set to match the 1st mount failure.
+ *   0 on success.
+ */
+static int mount_with_alternatives(struct fstab *fstab, int start_idx, int *end_idx, int *attempted_idx)
+{
+    int i;
+    int mount_errno = 0;
+    int mounted = 0;
+
+    if (!end_idx || !attempted_idx || start_idx >= fstab->num_entries) {
+      errno = EINVAL;
+      if (end_idx) *end_idx = start_idx;
+      if (attempted_idx) *attempted_idx = start_idx;
+      return -1;
+    }
+
+    /* Hunt down an fstab entry for the same mount point that might succeed */
+    for (i = start_idx;
+         /* We required that fstab entries for the same mountpoint be consecutive */
+         i < fstab->num_entries && !strcmp(fstab->recs[start_idx].mount_point, fstab->recs[i].mount_point);
+         i++) {
+            /*
+             * Don't try to mount/encrypt the same mount point again.
+             * Deal with alternate entries for the same point which are required to be all following
+             * each other.
+             */
+            if (mounted) {
+                LERROR << __FUNCTION__ << "(): skipping fstab dup mountpoint="
+                       << fstab->recs[i].mount_point << " rec[" << i
+                       << "].fs_type=" << fstab->recs[i].fs_type
+                       << " already mounted as "
+                       << fstab->recs[*attempted_idx].fs_type;
+                continue;
+            }
+
+            int fs_stat = 0;
+            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);
+            }
+
+            if (fstab->recs[i].fs_mgr_flags & MF_RESERVEDSIZE) {
+                do_reserved_size(fstab->recs[i].blk_device, fstab->recs[i].fs_type,
+                                 &fstab->recs[i], &fs_stat);
+            }
+
+            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);
+    }
+
+    /* Adjust i for the case where it was still withing the recs[] */
+    if (i < fstab->num_entries) --i;
+
+    *end_idx = i;
+    if (!mounted) {
+        *attempted_idx = start_idx;
+        errno = mount_errno;
+        return -1;
+    }
+    return 0;
+}
+
+static int translate_ext_labels(struct fstab_rec *rec)
+{
+    DIR *blockdir = NULL;
+    struct dirent *ent;
+    char *label;
+    size_t label_len;
+    int ret = -1;
+
+    if (strncmp(rec->blk_device, "LABEL=", 6))
+        return 0;
+
+    label = rec->blk_device + 6;
+    label_len = strlen(label);
+
+    if (label_len > 16) {
+        LERROR << "FS label is longer than allowed by filesystem";
+        goto out;
+    }
+
+
+    blockdir = opendir("/dev/block");
+    if (!blockdir) {
+        LERROR << "couldn't open /dev/block";
+        goto out;
+    }
+
+    while ((ent = readdir(blockdir))) {
+        int fd;
+        char super_buf[1024];
+        struct ext4_super_block *sb;
+
+        if (ent->d_type != DT_BLK)
+            continue;
+
+        fd = openat(dirfd(blockdir), ent->d_name, O_RDONLY);
+        if (fd < 0) {
+            LERROR << "Cannot open block device /dev/block/" << ent->d_name;
+            goto out;
+        }
+
+        if (TEMP_FAILURE_RETRY(lseek(fd, 1024, SEEK_SET)) < 0 ||
+            TEMP_FAILURE_RETRY(read(fd, super_buf, 1024)) != 1024) {
+            /* Probably a loopback device or something else without a readable
+             * superblock.
+             */
+            close(fd);
+            continue;
+        }
+
+        sb = (struct ext4_super_block *)super_buf;
+        if (sb->s_magic != EXT4_SUPER_MAGIC) {
+            LINFO << "/dev/block/" << ent->d_name << " not ext{234}";
+            continue;
+        }
+
+        if (!strncmp(label, sb->s_volume_name, label_len)) {
+            char *new_blk_device;
+
+            if (asprintf(&new_blk_device, "/dev/block/%s", ent->d_name) < 0) {
+                LERROR << "Could not allocate block device string";
+                goto out;
+            }
+
+            LINFO << "resolved label " << rec->blk_device << " to "
+                  << new_blk_device;
+
+            free(rec->blk_device);
+            rec->blk_device = new_blk_device;
+            ret = 0;
+            break;
+        }
+    }
+
+out:
+    closedir(blockdir);
+    return ret;
+}
+
+static bool needs_block_encryption(const struct fstab_rec* rec)
+{
+    if (device_is_force_encrypted() && fs_mgr_is_encryptable(rec)) return true;
+    if (rec->fs_mgr_flags & MF_FORCECRYPT) return true;
+    if (rec->fs_mgr_flags & MF_CRYPT) {
+        /* Check for existence of convert_fde breadcrumb file */
+        char convert_fde_name[PATH_MAX];
+        snprintf(convert_fde_name, sizeof(convert_fde_name),
+                 "%s/misc/vold/convert_fde", rec->mount_point);
+        if (access(convert_fde_name, F_OK) == 0) return true;
+    }
+    if (rec->fs_mgr_flags & MF_FORCEFDEORFBE) {
+        /* Check for absence of convert_fbe breadcrumb file */
+        char convert_fbe_name[PATH_MAX];
+        snprintf(convert_fbe_name, sizeof(convert_fbe_name),
+                 "%s/convert_fbe", rec->mount_point);
+        if (access(convert_fbe_name, F_OK) != 0) return true;
+    }
+    return false;
+}
+
+// Check to see if a mountable volume has encryption requirements
+static int handle_encryptable(const struct fstab_rec* rec)
+{
+    /* If this is block encryptable, need to trigger encryption */
+    if (needs_block_encryption(rec)) {
+        if (umount(rec->mount_point) == 0) {
+            return FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION;
+        } else {
+            PWARNING << "Could not umount " << rec->mount_point
+                     << " - allow continue unencrypted";
+            return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
+        }
+    } else if (rec->fs_mgr_flags & (MF_FILEENCRYPTION | MF_FORCEFDEORFBE)) {
+        // Deal with file level encryption
+        LINFO << rec->mount_point << " is file encrypted";
+        return FS_MGR_MNTALL_DEV_FILE_ENCRYPTED;
+    } else if (fs_mgr_is_encryptable(rec)) {
+        return FS_MGR_MNTALL_DEV_NOT_ENCRYPTED;
+    } else {
+        return FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
+    }
+}
+
+// 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) {
+    int tries = 25;
+    while (tries--) {
+        if (!access(device, F_OK) || errno != ENOENT) {
+            return 0;
+        }
+        usleep(40 * 1000);
+    }
+    return -1;
+}
+
+bool is_device_secure() {
+    int ret = -1;
+    char value[PROP_VALUE_MAX];
+    ret = __system_property_get("ro.secure", value);
+    if (ret == 0) {
+#ifdef ALLOW_SKIP_SECURE_CHECK
+        // Allow eng builds to skip this check if the property
+        // is not readable (happens during early mount)
+        return false;
+#else
+        // If error and not an 'eng' build, we want to fail secure.
+        return true;
+#endif
+    }
+    return strcmp(value, "0") ? true : false;
+}
+
+/* When multiple fstab records share the same mount_point, it will
+ * try to mount each one in turn, and ignore any duplicates after a
+ * first successful mount.
+ * Returns -1 on error, and  FS_MGR_MNTALL_* otherwise.
+ */
+int fs_mgr_mount_all(struct fstab *fstab, int mount_mode)
+{
+    int i = 0;
+    int encryptable = FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE;
+    int error_count = 0;
+    int mret = -1;
+    int mount_errno = 0;
+    int attempted_idx = -1;
+    FsManagerAvbUniquePtr avb_handle(nullptr);
+
+    if (!fstab) {
+        return -1;
+    }
+
+    for (i = 0; i < fstab->num_entries; i++) {
+        /* Don't mount entries that are managed by vold or not for the mount mode*/
+        if ((fstab->recs[i].fs_mgr_flags & (MF_VOLDMANAGED | MF_RECOVERYONLY)) ||
+             ((mount_mode == MOUNT_MODE_LATE) && !fs_mgr_is_latemount(&fstab->recs[i])) ||
+             ((mount_mode == MOUNT_MODE_EARLY) && fs_mgr_is_latemount(&fstab->recs[i]))) {
+            continue;
+        }
+
+        /* Skip swap and raw partition entries such as boot, recovery, etc */
+        if (!strcmp(fstab->recs[i].fs_type, "swap") ||
+            !strcmp(fstab->recs[i].fs_type, "emmc") ||
+            !strcmp(fstab->recs[i].fs_type, "mtd")) {
+            continue;
+        }
+
+        /* Skip mounting the root partition, as it will already have been mounted */
+        if (!strcmp(fstab->recs[i].mount_point, "/")) {
+            if ((fstab->recs[i].fs_mgr_flags & MS_RDONLY) != 0) {
+                fs_mgr_set_blk_ro(fstab->recs[i].blk_device);
+            }
+            continue;
+        }
+
+        /* Translate LABEL= file system labels into block devices */
+        if (!strcmp(fstab->recs[i].fs_type, "ext2") ||
+            !strcmp(fstab->recs[i].fs_type, "ext3") ||
+            !strcmp(fstab->recs[i].fs_type, "ext4")) {
+            int tret = translate_ext_labels(&fstab->recs[i]);
+            if (tret < 0) {
+                LERROR << "Could not translate label to block device";
+                continue;
+            }
+        }
+
+        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
+            wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
+        }
+
+        if (fstab->recs[i].fs_mgr_flags & MF_AVB) {
+            if (!avb_handle) {
+                avb_handle = FsManagerAvbHandle::Open(*fstab);
+                if (!avb_handle) {
+                    LERROR << "Failed to open FsManagerAvbHandle";
+                    return -1;
+                }
+            }
+            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. */
+                continue;
+            }
+        } else if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && is_device_secure()) {
+            int rc = fs_mgr_setup_verity(&fstab->recs[i], true);
+            if (__android_log_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
+                LINFO << "Verity disabled";
+            } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
+                LERROR << "Could not set up verified partition, skipping!";
+                continue;
+            }
+        }
+
+        int last_idx_inspected;
+        int top_idx = i;
+
+        mret = mount_with_alternatives(fstab, i, &last_idx_inspected, &attempted_idx);
+        i = last_idx_inspected;
+        mount_errno = errno;
+
+        /* Deal with encryptability. */
+        if (!mret) {
+            int status = handle_encryptable(&fstab->recs[attempted_idx]);
+
+            if (status == FS_MGR_MNTALL_FAIL) {
+                /* Fatal error - no point continuing */
+                return status;
+            }
+
+            if (status != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
+                if (encryptable != FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
+                    // Log and continue
+                    LERROR << "Only one encryptable/encrypted partition supported";
+                }
+                encryptable = status;
+            }
+
+            /* Success!  Go get the next one */
+            continue;
+        }
+
+        /* mount(2) returned an error, handle the encryptable/formattable case */
+        bool wiped = partition_wiped(fstab->recs[top_idx].blk_device);
+        bool crypt_footer = false;
+        if (mret && mount_errno != EBUSY && mount_errno != EACCES &&
+            fs_mgr_is_formattable(&fstab->recs[top_idx]) && wiped) {
+            /* top_idx and attempted_idx point at the same partition, but sometimes
+             * at two different lines in the fstab.  Use the top one for formatting
+             * as that is the preferred one.
+             */
+            LERROR << __FUNCTION__ << "(): " << fstab->recs[top_idx].blk_device
+                   << " is wiped and " << fstab->recs[top_idx].mount_point
+                   << " " << fstab->recs[top_idx].fs_type
+                   << " is formattable. Format it.";
+            if (fs_mgr_is_encryptable(&fstab->recs[top_idx]) &&
+                strcmp(fstab->recs[top_idx].key_loc, KEY_IN_FOOTER)) {
+                int fd = open(fstab->recs[top_idx].key_loc, O_WRONLY);
+                if (fd >= 0) {
+                    LINFO << __FUNCTION__ << "(): also wipe "
+                          << fstab->recs[top_idx].key_loc;
+                    wipe_block_device(fd, get_file_size(fd));
+                    close(fd);
+                } else {
+                    PERROR << __FUNCTION__ << "(): "
+                           << fstab->recs[top_idx].key_loc << " wouldn't open";
+                }
+            } else if (fs_mgr_is_encryptable(&fstab->recs[top_idx]) &&
+                !strcmp(fstab->recs[top_idx].key_loc, KEY_IN_FOOTER)) {
+                crypt_footer = true;
+            }
+            if (fs_mgr_do_format(&fstab->recs[top_idx], crypt_footer) == 0) {
+                /* Let's replay the mount actions. */
+                i = top_idx - 1;
+                continue;
+            } else {
+                LERROR << __FUNCTION__ << "(): Format failed. "
+                       << "Suggest recovery...";
+                encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
+                continue;
+            }
+        }
+        if (mret && mount_errno != EBUSY && mount_errno != EACCES &&
+            fs_mgr_is_encryptable(&fstab->recs[attempted_idx])) {
+            if (wiped) {
+                LERROR << __FUNCTION__ << "(): "
+                       << fstab->recs[attempted_idx].blk_device
+                       << " is wiped and "
+                       << fstab->recs[attempted_idx].mount_point << " "
+                       << fstab->recs[attempted_idx].fs_type
+                       << " is encryptable. Suggest recovery...";
+                encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
+                continue;
+            } else {
+                /* Need to mount a tmpfs at this mountpoint for now, and set
+                 * properties that vold will query later for decrypting
+                 */
+                LERROR << __FUNCTION__ << "(): possibly an encryptable blkdev "
+                       << fstab->recs[attempted_idx].blk_device
+                       << " for mount " << fstab->recs[attempted_idx].mount_point
+                       << " type " << fstab->recs[attempted_idx].fs_type;
+                if (fs_mgr_do_tmpfs_mount(fstab->recs[attempted_idx].mount_point) < 0) {
+                    ++error_count;
+                    continue;
+                }
+            }
+            encryptable = FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED;
+        } else {
+            // fs_options might be null so we cannot use PERROR << directly.
+            // Use StringPrintf to output "(null)" instead.
+            if (fs_mgr_is_nofail(&fstab->recs[attempted_idx])) {
+                PERROR << android::base::StringPrintf(
+                    "Ignoring failure to mount an un-encryptable or wiped "
+                    "partition on %s at %s options: %s",
+                    fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
+                    fstab->recs[attempted_idx].fs_options);
+            } else {
+                PERROR << android::base::StringPrintf(
+                    "Failed to mount an un-encryptable or wiped partition "
+                    "on %s at %s options: %s",
+                    fstab->recs[attempted_idx].blk_device, fstab->recs[attempted_idx].mount_point,
+                    fstab->recs[attempted_idx].fs_options);
+                ++error_count;
+            }
+            continue;
+        }
+    }
+
+    if (error_count) {
+        return -1;
+    } else {
+        return encryptable;
+    }
+}
+
+/* wrapper to __mount() and expects a fully prepared fstab_rec,
+ * unlike fs_mgr_do_mount which does more things with avb / verity
+ * etc.
+ */
+int fs_mgr_do_mount_one(struct fstab_rec *rec)
+{
+    if (!rec) {
+        return FS_MGR_DOMNT_FAILED;
+    }
+
+    int ret = __mount(rec->blk_device, rec->mount_point, rec);
+    if (ret) {
+      ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
+    }
+
+    return ret;
+}
+
+/* If tmp_mount_point is non-null, mount the filesystem there.  This is for the
+ * tmp mount we do to check the user password
+ * If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
+ * in turn, and stop on 1st success, or no more match.
+ */
+int fs_mgr_do_mount(struct fstab *fstab, const char *n_name, char *n_blk_device,
+                    char *tmp_mount_point)
+{
+    int i = 0;
+    int ret = FS_MGR_DOMNT_FAILED;
+    int mount_errors = 0;
+    int first_mount_errno = 0;
+    char *m;
+    FsManagerAvbUniquePtr avb_handle(nullptr);
+
+    if (!fstab) {
+        return ret;
+    }
+
+    for (i = 0; i < fstab->num_entries; i++) {
+        if (!fs_match(fstab->recs[i].mount_point, n_name)) {
+            continue;
+        }
+
+        /* We found our match */
+        /* If this swap or a raw partition, report an error */
+        if (!strcmp(fstab->recs[i].fs_type, "swap") ||
+            !strcmp(fstab->recs[i].fs_type, "emmc") ||
+            !strcmp(fstab->recs[i].fs_type, "mtd")) {
+            LERROR << "Cannot mount filesystem of type "
+                   << fstab->recs[i].fs_type << " on " << n_blk_device;
+            goto out;
+        }
+
+        /* First check the filesystem if requested */
+        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
+            wait_for_file(n_blk_device, WAIT_TIMEOUT);
+        }
+
+        int fs_stat = 0;
+        int force_check = do_quota_with_shutdown_check(n_blk_device, fstab->recs[i].fs_type,
+                                                       &fstab->recs[i], &fs_stat);
+
+        if ((fstab->recs[i].fs_mgr_flags & MF_CHECK) || force_check) {
+            check_fs(n_blk_device, fstab->recs[i].fs_type,
+                     fstab->recs[i].mount_point, &fs_stat);
+        }
+
+        if (fstab->recs[i].fs_mgr_flags & MF_RESERVEDSIZE) {
+            do_reserved_size(n_blk_device, fstab->recs[i].fs_type, &fstab->recs[i], &fs_stat);
+        }
+
+        if (fstab->recs[i].fs_mgr_flags & MF_AVB) {
+            if (!avb_handle) {
+                avb_handle = FsManagerAvbHandle::Open(*fstab);
+                if (!avb_handle) {
+                    LERROR << "Failed to open FsManagerAvbHandle";
+                    return -1;
+                }
+            }
+            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. */
+                continue;
+            }
+        } else if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && is_device_secure()) {
+            int rc = fs_mgr_setup_verity(&fstab->recs[i], true);
+            if (__android_log_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
+                LINFO << "Verity disabled";
+            } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
+                LERROR << "Could not set up verified partition, skipping!";
+                continue;
+            }
+        }
+
+        /* Now mount it where requested */
+        if (tmp_mount_point) {
+            m = tmp_mount_point;
+        } else {
+            m = fstab->recs[i].mount_point;
+        }
+        int retry_count = 2;
+        while (retry_count-- > 0) {
+            if (!__mount(n_blk_device, m, &fstab->recs[i])) {
+                ret = 0;
+                fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
+                goto out;
+            } 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);
+            }
+        }
+        log_fs_stat(fstab->recs[i].blk_device, 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";
+    }
+
+out:
+    return ret;
+}
+
+/*
+ * mount a tmpfs filesystem at the given point.
+ * return 0 on success, non-zero on failure.
+ */
+int fs_mgr_do_tmpfs_mount(const char *n_name)
+{
+    int ret;
+
+    ret = mount("tmpfs", n_name, "tmpfs",
+                MS_NOATIME | MS_NOSUID | MS_NODEV, CRYPTO_TMPFS_OPTIONS);
+    if (ret < 0) {
+        LERROR << "Cannot mount tmpfs filesystem at " << n_name;
+        return -1;
+    }
+
+    /* Success */
+    return 0;
+}
+
+int fs_mgr_unmount_all(struct fstab *fstab)
+{
+    int i = 0;
+    int ret = 0;
+
+    if (!fstab) {
+        return -1;
+    }
+
+    while (fstab->recs[i].blk_device) {
+        if (umount(fstab->recs[i].mount_point)) {
+            LERROR << "Cannot unmount filesystem at "
+                   << fstab->recs[i].mount_point;
+            ret = -1;
+        }
+        i++;
+    }
+
+    return ret;
+}
+
+/* This must be called after mount_all, because the mkswap command needs to be
+ * available.
+ */
+int fs_mgr_swapon_all(struct fstab *fstab)
+{
+    int i = 0;
+    int flags = 0;
+    int err = 0;
+    int ret = 0;
+    int status;
+    const char *mkswap_argv[2] = {
+        MKSWAP_BIN,
+        nullptr
+    };
+
+    if (!fstab) {
+        return -1;
+    }
+
+    for (i = 0; i < fstab->num_entries; i++) {
+        /* Skip non-swap entries */
+        if (strcmp(fstab->recs[i].fs_type, "swap")) {
+            continue;
+        }
+
+        if (fstab->recs[i].zram_size > 0) {
+            /* A zram_size was specified, so we need to configure the
+             * device.  There is no point in having multiple zram devices
+             * on a system (all the memory comes from the same pool) so
+             * we can assume the device number is 0.
+             */
+            FILE *zram_fp;
+            FILE *zram_mcs_fp;
+
+            if (fstab->recs[i].max_comp_streams >= 0) {
+               zram_mcs_fp = fopen(ZRAM_CONF_MCS, "r+");
+              if (zram_mcs_fp == NULL) {
+                LERROR << "Unable to open zram conf comp device "
+                       << ZRAM_CONF_MCS;
+                ret = -1;
+                continue;
+              }
+              fprintf(zram_mcs_fp, "%d\n", fstab->recs[i].max_comp_streams);
+              fclose(zram_mcs_fp);
+            }
+
+            zram_fp = fopen(ZRAM_CONF_DEV, "r+");
+            if (zram_fp == NULL) {
+                LERROR << "Unable to open zram conf device " << ZRAM_CONF_DEV;
+                ret = -1;
+                continue;
+            }
+            fprintf(zram_fp, "%d\n", fstab->recs[i].zram_size);
+            fclose(zram_fp);
+        }
+
+        if (fstab->recs[i].fs_mgr_flags & MF_WAIT) {
+            wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
+        }
+
+        /* Initialize the swap area */
+        mkswap_argv[1] = fstab->recs[i].blk_device;
+        err = android_fork_execvp_ext(ARRAY_SIZE(mkswap_argv),
+                                      const_cast<char **>(mkswap_argv),
+                                      &status, true, LOG_KLOG, false, NULL,
+                                      NULL, 0);
+        if (err) {
+            LERROR << "mkswap failed for " << fstab->recs[i].blk_device;
+            ret = -1;
+            continue;
+        }
+
+        /* If -1, then no priority was specified in fstab, so don't set
+         * SWAP_FLAG_PREFER or encode the priority */
+        if (fstab->recs[i].swap_prio >= 0) {
+            flags = (fstab->recs[i].swap_prio << SWAP_FLAG_PRIO_SHIFT) &
+                    SWAP_FLAG_PRIO_MASK;
+            flags |= SWAP_FLAG_PREFER;
+        } else {
+            flags = 0;
+        }
+        err = swapon(fstab->recs[i].blk_device, flags);
+        if (err) {
+            LERROR << "swapon failed for " << fstab->recs[i].blk_device;
+            ret = -1;
+        }
+    }
+
+    return ret;
+}
+
+/*
+ * key_loc must be at least PROPERTY_VALUE_MAX bytes long
+ *
+ * real_blk_device must be at least PROPERTY_VALUE_MAX bytes long
+ */
+int fs_mgr_get_crypt_info(struct fstab *fstab, char *key_loc, char *real_blk_device, int size)
+{
+    int i = 0;
+
+    if (!fstab) {
+        return -1;
+    }
+    /* Initialize return values to null strings */
+    if (key_loc) {
+        *key_loc = '\0';
+    }
+    if (real_blk_device) {
+        *real_blk_device = '\0';
+    }
+
+    /* Look for the encryptable partition to find the data */
+    for (i = 0; i < fstab->num_entries; i++) {
+        /* Don't deal with vold managed enryptable partitions here */
+        if (fstab->recs[i].fs_mgr_flags & MF_VOLDMANAGED) {
+            continue;
+        }
+        if (!(fstab->recs[i].fs_mgr_flags
+              & (MF_CRYPT | MF_FORCECRYPT | MF_FORCEFDEORFBE))) {
+            continue;
+        }
+
+        /* We found a match */
+        if (key_loc) {
+            strlcpy(key_loc, fstab->recs[i].key_loc, size);
+        }
+        if (real_blk_device) {
+            strlcpy(real_blk_device, fstab->recs[i].blk_device, size);
+        }
+        break;
+    }
+
+    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
new file mode 100644
index 0000000..36883e6
--- /dev/null
+++ b/fs_mgr/fs_mgr_avb.cpp
@@ -0,0 +1,578 @@
+/*
+ * 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 "fs_mgr_avb.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <vector>
+
+#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>
+#include <libavb/libavb.h>
+#include <openssl/sha.h>
+#include <sys/ioctl.h>
+#include <utils/Compat.h>
+
+#include "fs_mgr.h"
+#include "fs_mgr_priv.h"
+#include "fs_mgr_priv_avb_ops.h"
+#include "fs_mgr_priv_dm_ioctl.h"
+#include "fs_mgr_priv_sha.h"
+
+/* The format of dm-verity construction parameters:
+ *     <version> <dev> <hash_dev> <data_block_size> <hash_block_size>
+ *     <num_data_blocks> <hash_start_block> <algorithm> <digest> <salt>
+ */
+#define VERITY_TABLE_FORMAT \
+    "%u %s %s %u %u "       \
+    "%" PRIu64 " %" PRIu64 " %s %s %s "
+
+#define VERITY_TABLE_PARAMS(hashtree_desc, blk_device, digest, salt)                        \
+    hashtree_desc.dm_verity_version, blk_device, blk_device, hashtree_desc.data_block_size, \
+        hashtree_desc.hash_block_size,                                                      \
+        hashtree_desc.image_size / hashtree_desc.data_block_size,  /* num_data_blocks. */   \
+        hashtree_desc.tree_offset / hashtree_desc.hash_block_size, /* hash_start_block. */  \
+        (char*)hashtree_desc.hash_algorithm, digest, salt
+
+#define VERITY_TABLE_OPT_RESTART "restart_on_corruption"
+#define VERITY_TABLE_OPT_IGNZERO "ignore_zero_blocks"
+
+/* The default format of dm-verity optional parameters:
+ *     <#opt_params> ignore_zero_blocks restart_on_corruption
+ */
+#define VERITY_TABLE_OPT_DEFAULT_FORMAT "2 %s %s"
+#define VERITY_TABLE_OPT_DEFAULT_PARAMS VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART
+
+/* The FEC (forward error correction) format of dm-verity optional parameters:
+ *     <#opt_params> use_fec_from_device <fec_dev>
+ *     fec_roots <num> fec_blocks <num> fec_start <offset>
+ *     ignore_zero_blocks restart_on_corruption
+ */
+#define VERITY_TABLE_OPT_FEC_FORMAT \
+    "10 use_fec_from_device %s fec_roots %u fec_blocks %" PRIu64 " fec_start %" PRIu64 " %s %s"
+
+/* Note that fec_blocks is the size that FEC covers, *not* the
+ * size of the FEC data. Since we use FEC for everything up until
+ * the FEC data, it's the same as the offset (fec_start).
+ */
+#define VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device)                     \
+    blk_device, hashtree_desc.fec_num_roots,                                       \
+        hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_blocks */ \
+        hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_start */  \
+        VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART
+
+static inline bool nibble_value(const char& c, uint8_t* value) {
+    FS_MGR_CHECK(value != nullptr);
+
+    switch (c) {
+        case '0' ... '9':
+            *value = c - '0';
+            break;
+        case 'a' ... 'f':
+            *value = c - 'a' + 10;
+            break;
+        case 'A' ... 'F':
+            *value = c - 'A' + 10;
+            break;
+        default:
+            return false;
+    }
+
+    return true;
+}
+
+static bool hex_to_bytes(uint8_t* bytes, size_t bytes_len, const std::string& hex) {
+    FS_MGR_CHECK(bytes != nullptr);
+
+    if (hex.size() % 2 != 0) {
+        return false;
+    }
+    if (hex.size() / 2 > bytes_len) {
+        return false;
+    }
+    for (size_t i = 0, j = 0, n = hex.size(); i < n; i += 2, ++j) {
+        uint8_t high;
+        if (!nibble_value(hex[i], &high)) {
+            return false;
+        }
+        uint8_t low;
+        if (!nibble_value(hex[i + 1], &low)) {
+            return false;
+        }
+        bytes[j] = (high << 4) | low;
+    }
+    return true;
+}
+
+static std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) {
+    FS_MGR_CHECK(bytes != nullptr);
+
+    static const char* hex_digits = "0123456789abcdef";
+    std::string hex;
+
+    for (size_t i = 0; i < bytes_len; i++) {
+        hex.push_back(hex_digits[(bytes[i] & 0xF0) >> 4]);
+        hex.push_back(hex_digits[bytes[i] & 0x0F]);
+    }
+    return hex;
+}
+
+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;
+    if (!android::base::ReadFileToString("/proc/cmdline", &cmdline)) {
+        LERROR << "Failed to read /proc/cmdline";
+        return nullptr;
+    }
+
+    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") {
+            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(), &avb_verifier->vbmeta_size_)) {
+                return nullptr;
+            }
+        } else if (key == "androidboot.vbmeta.digest") {
+            digest = value;
+        }
+    }
+
+    // Reads hash algorithm.
+    size_t expected_digest_size = 0;
+    if (hash_alg == "sha256") {
+        expected_digest_size = SHA256_DIGEST_LENGTH * 2;
+        avb_verifier->hash_alg_ = kSHA256;
+    } else if (hash_alg == "sha512") {
+        expected_digest_size = SHA512_DIGEST_LENGTH * 2;
+        avb_verifier->hash_alg_ = kSHA512;
+    } else {
+        LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
+        return nullptr;
+    }
+
+    // Reads digest.
+    if (digest.size() != expected_digest_size) {
+        LERROR << "Unexpected digest size: " << digest.size()
+               << " (expected: " << expected_digest_size << ")";
+        return nullptr;
+    }
+
+    if (!hex_to_bytes(avb_verifier->digest_, sizeof(avb_verifier->digest_), digest)) {
+        LERROR << "Hash digest contains non-hexidecimal character: " << digest.c_str();
+        return nullptr;
+    }
+
+    return avb_verifier;
+}
+
+bool FsManagerAvbVerifier::VerifyVbmetaImages(const AvbSlotVerifyData& verify_data) {
+    if (verify_data.num_vbmeta_images == 0) {
+        LERROR << "No vbmeta images";
+        return false;
+    }
+
+    size_t total_size = 0;
+    bool digest_matched = false;
+
+    if (hash_alg_ == kSHA256) {
+        std::tie(total_size, digest_matched) =
+            verify_vbmeta_digest<SHA256Hasher>(verify_data, digest_);
+    } else if (hash_alg_ == kSHA512) {
+        std::tie(total_size, digest_matched) =
+            verify_vbmeta_digest<SHA512Hasher>(verify_data, digest_);
+    }
+
+    if (total_size != vbmeta_size_) {
+        LERROR << "total vbmeta size mismatch: " << total_size << " (expected: " << vbmeta_size_
+               << ")";
+        return false;
+    }
+
+    if (!digest_matched) {
+        LERROR << "vbmeta digest mismatch";
+        return false;
+    }
+
+    return true;
+}
+
+static bool hashtree_load_verity_table(struct dm_ioctl* io, const std::string& dm_device_name,
+                                       int fd, const std::string& blk_device,
+                                       const AvbHashtreeDescriptor& hashtree_desc,
+                                       const std::string& salt, const std::string& root_digest) {
+    fs_mgr_verity_ioctl_init(io, dm_device_name, DM_STATUS_TABLE_FLAG);
+
+    // The buffer consists of [dm_ioctl][dm_target_spec][verity_params].
+    char* buffer = (char*)io;
+
+    // Builds the dm_target_spec arguments.
+    struct dm_target_spec* dm_target = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
+    io->target_count = 1;
+    dm_target->status = 0;
+    dm_target->sector_start = 0;
+    dm_target->length = hashtree_desc.image_size / 512;
+    strcpy(dm_target->target_type, "verity");
+
+    // Builds the verity params.
+    char* verity_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
+    size_t bufsize = DM_BUF_SIZE - (verity_params - buffer);
+
+    int res = 0;
+    if (hashtree_desc.fec_size > 0) {
+        res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_FEC_FORMAT,
+                       VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(),
+                                           salt.c_str()),
+                       VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device.c_str()));
+    } else {
+        res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_DEFAULT_FORMAT,
+                       VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(),
+                                           salt.c_str()),
+                       VERITY_TABLE_OPT_DEFAULT_PARAMS);
+    }
+
+    if (res < 0 || (size_t)res >= bufsize) {
+        LERROR << "Error building verity table; insufficient buffer size?";
+        return false;
+    }
+
+    LINFO << "Loading verity table: '" << verity_params << "'";
+
+    // Sets ext target boundary.
+    verity_params += strlen(verity_params) + 1;
+    verity_params = (char*)(((unsigned long)verity_params + 7) & ~7);
+    dm_target->next = verity_params - buffer;
+
+    // Sends the ioctl to load the verity table.
+    if (ioctl(fd, DM_TABLE_LOAD, io)) {
+        PERROR << "Error loading verity table";
+        return false;
+    }
+
+    return true;
+}
+
+static bool hashtree_dm_verity_setup(struct fstab_rec* fstab_entry,
+                                     const AvbHashtreeDescriptor& hashtree_desc,
+                                     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) {
+        PERROR << "Error opening device mapper";
+        return false;
+    }
+
+    // Creates the device.
+    alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
+    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
+    const std::string mount_point(basename(fstab_entry->mount_point));
+    if (!fs_mgr_create_verity_device(io, mount_point, fd)) {
+        LERROR << "Couldn't create verity device!";
+        return false;
+    }
+
+    // Gets the name of the device file.
+    std::string verity_blk_name;
+    if (!fs_mgr_get_verity_device_name(io, mount_point, fd, &verity_blk_name)) {
+        LERROR << "Couldn't get verity device number!";
+        return false;
+    }
+
+    // Loads the verity mapping table.
+    if (!hashtree_load_verity_table(io, mount_point, fd, std::string(fstab_entry->blk_device),
+                                    hashtree_desc, salt, root_digest)) {
+        LERROR << "Couldn't load verity table!";
+        return false;
+    }
+
+    // Activates the device.
+    if (!fs_mgr_resume_verity_table(io, mount_point, fd)) {
+        return false;
+    }
+
+    // Marks the underlying block device as read-only.
+    fs_mgr_set_blk_ro(fstab_entry->blk_device);
+
+    // 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 (wait_for_verity_dev && fs_mgr_test_access(verity_blk_name.c_str()) < 0) {
+        return false;
+    }
+
+    return true;
+}
+
+static bool get_hashtree_descriptor(const std::string& partition_name,
+                                    const AvbSlotVerifyData& verify_data,
+                                    AvbHashtreeDescriptor* out_hashtree_desc, std::string* out_salt,
+                                    std::string* out_digest) {
+    bool found = false;
+    const uint8_t* desc_partition_name;
+
+    for (size_t i = 0; i < verify_data.num_vbmeta_images && !found; i++) {
+        // Get descriptors from vbmeta_images[i].
+        size_t num_descriptors;
+        std::unique_ptr<const AvbDescriptor* [], decltype(&avb_free)> descriptors(
+            avb_descriptor_get_all(verify_data.vbmeta_images[i].vbmeta_data,
+                                   verify_data.vbmeta_images[i].vbmeta_size, &num_descriptors),
+            avb_free);
+
+        if (!descriptors || num_descriptors < 1) {
+            continue;
+        }
+
+        // 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 != "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;
+        }
+
+        for (size_t j = 0; j < num_descriptors && !found; j++) {
+            AvbDescriptor desc;
+            if (!avb_descriptor_validate_and_byteswap(descriptors[j], &desc)) {
+                LWARNING << "Descriptor[" << j << "] is invalid";
+                continue;
+            }
+            if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) {
+                desc_partition_name = (const uint8_t*)descriptors[j] + sizeof(AvbHashtreeDescriptor);
+                if (!avb_hashtree_descriptor_validate_and_byteswap(
+                        (AvbHashtreeDescriptor*)descriptors[j], out_hashtree_desc)) {
+                    continue;
+                }
+                if (out_hashtree_desc->partition_name_len != partition_name.length()) {
+                    continue;
+                }
+                // Notes that desc_partition_name is not NUL-terminated.
+                std::string hashtree_partition_name((const char*)desc_partition_name,
+                                                    out_hashtree_desc->partition_name_len);
+                if (hashtree_partition_name == partition_name) {
+                    found = true;
+                }
+            }
+        }
+    }
+
+    if (!found) {
+        LERROR << "Partition descriptor not found: " << partition_name.c_str();
+        return false;
+    }
+
+    const uint8_t* desc_salt = desc_partition_name + out_hashtree_desc->partition_name_len;
+    *out_salt = bytes_to_hex(desc_salt, out_hashtree_desc->salt_len);
+
+    const uint8_t* desc_digest = desc_salt + out_hashtree_desc->salt_len;
+    *out_digest = bytes_to_hex(desc_digest, out_hashtree_desc->root_digest_len);
+
+    return true;
+}
+
+FsManagerAvbUniquePtr FsManagerAvbHandle::Open(const fstab& fstab) {
+    FsManagerAvbOps avb_ops(fstab);
+    return DoOpen(&avb_ops);
+}
+
+FsManagerAvbUniquePtr FsManagerAvbHandle::Open(ByNameSymlinkMap&& by_name_symlink_map) {
+    if (by_name_symlink_map.empty()) {
+        LERROR << "Empty by_name_symlink_map when opening FsManagerAvbHandle";
+        return nullptr;
+    }
+    FsManagerAvbOps avb_ops(std::move(by_name_symlink_map));
+    return DoOpen(&avb_ops);
+}
+
+FsManagerAvbUniquePtr FsManagerAvbHandle::DoOpen(FsManagerAvbOps* avb_ops) {
+    // 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;
+    }
+
+    FsManagerAvbUniquePtr avb_handle(new FsManagerAvbHandle());
+    if (!avb_handle) {
+        LERROR << "Failed to allocate FsManagerAvbHandle";
+        return nullptr;
+    }
+
+    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 the device is UNLOCKED, i.e., |allow_verification_error| is true for
+    //     AvbSlotVerify(), then the following return values are all non-fatal:
+    //       * AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION
+    //       * AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED
+    //       * AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
+    //     The latter two results were checked by bootloader prior to start fs_mgr so
+    //     we just need to handle the first result here. See *dummy* operations in
+    //     FsManagerAvbOps and the comments in external/avb/libavb/avb_slot_verify.h
+    //     for more details.
+    switch (verify_result) {
+        case AVB_SLOT_VERIFY_RESULT_OK:
+            avb_handle->status_ = kFsManagerAvbHandleSuccess;
+            break;
+        case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
+            if (!avb_verifier->IsDeviceUnlocked()) {
+                LERROR << "ERROR_VERIFICATION isn't allowed when the device is LOCKED";
+                return nullptr;
+            }
+            avb_handle->status_ = kFsManagerAvbHandleErrorVerification;
+            break;
+        default:
+            LERROR << "avb_slot_verify failed, result: " << verify_result;
+            return nullptr;
+    }
+
+    // Verifies vbmeta images against the digest passed from bootloader.
+    if (!avb_verifier->VerifyVbmetaImages(*avb_handle->avb_slot_data_)) {
+        LERROR << "VerifyVbmetaImages failed";
+        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);
+
+    // Checks whether FLAGS_HASHTREE_DISABLED is set.
+    AvbVBMetaImageHeader vbmeta_header;
+    avb_vbmeta_image_header_to_host_byte_order(
+        (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) {
+        avb_handle->status_ = kFsManagerAvbHandleHashtreeDisabled;
+    }
+
+    LINFO << "Returning avb_handle with status: " << avb_handle->status_;
+    return avb_handle;
+}
+
+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 (status_ == kFsManagerAvbHandleUninitialized) return false;
+    if (status_ == kFsManagerAvbHandleHashtreeDisabled) {
+        LINFO << "AVB HASHTREE disabled on:" << fstab_entry->mount_point;
+        return true;
+    }
+
+    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 false;
+    }
+
+    AvbHashtreeDescriptor hashtree_descriptor;
+    std::string salt;
+    std::string root_digest;
+    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,
+                                  wait_for_verity_dev)) {
+        return false;
+    }
+    return true;
+}
diff --git a/fs_mgr/fs_mgr_avb_ops.cpp b/fs_mgr/fs_mgr_avb_ops.cpp
new file mode 100644
index 0000000..47df861
--- /dev/null
+++ b/fs_mgr/fs_mgr_avb_ops.cpp
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "fs_mgr_priv_avb_ops.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <string>
+
+#include <android-base/macros.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <libavb/libavb.h>
+#include <utils/Compat.h>
+
+#include "fs_mgr.h"
+#include "fs_mgr_priv.h"
+
+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,
+                                             size_t rollback_index_location ATTRIBUTE_UNUSED,
+                                             uint64_t* out_rollback_index) {
+    // rollback_index has been checked in bootloader phase.
+    // In user-space, returns the smallest value 0 to pass the check.
+    *out_rollback_index = 0;
+    return AVB_IO_RESULT_OK;
+}
+
+static AvbIOResult dummy_validate_vbmeta_public_key(
+    AvbOps* ops ATTRIBUTE_UNUSED, const uint8_t* public_key_data ATTRIBUTE_UNUSED,
+    size_t public_key_length ATTRIBUTE_UNUSED, const uint8_t* public_key_metadata ATTRIBUTE_UNUSED,
+    size_t public_key_metadata_length ATTRIBUTE_UNUSED, bool* out_is_trusted) {
+    // vbmeta public key has been checked in bootloader phase.
+    // In user-space, returns true to pass the check.
+    //
+    // 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;
+}
+
+static AvbIOResult dummy_read_is_device_unlocked(AvbOps* ops ATTRIBUTE_UNUSED,
+                                                 bool* out_is_unlocked) {
+    // The function is for bootloader to update the value into
+    // androidboot.vbmeta.device_state in kernel cmdline.
+    // In user-space, returns true as we don't need to update it anymore.
+    *out_is_unlocked = true;
+    return AVB_IO_RESULT_OK;
+}
+
+static AvbIOResult dummy_get_unique_guid_for_partition(AvbOps* ops ATTRIBUTE_UNUSED,
+                                                       const char* partition ATTRIBUTE_UNUSED,
+                                                       char* guid_buf, size_t guid_buf_size) {
+    // The function is for bootloader to set the correct UUID
+    // for a given partition in kernel cmdline.
+    // In user-space, returns a faking one as we don't need to update
+    // it anymore.
+    snprintf(guid_buf, guid_buf_size, "1234-fake-guid-for:%s", partition);
+    return AVB_IO_RESULT_OK;
+}
+
+void FsManagerAvbOps::InitializeAvbOps() {
+    // 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.
+    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;
+
+    // Sets user_data for GetInstanceFromAvbOps() to convert it back to FsManagerAvbOps.
+    avb_ops_.user_data = this;
+}
+
+FsManagerAvbOps::FsManagerAvbOps(std::map<std::string, std::string>&& by_name_symlink_map)
+    : by_name_symlink_map_(std::move(by_name_symlink_map)) {
+    InitializeAvbOps();
+}
+
+FsManagerAvbOps::FsManagerAvbOps(const fstab& fstab) {
+    // Constructs the by-name symlink map for each fstab record.
+    // /dev/block/platform/soc.0/7824900.sdhci/by-name/system_a =>
+    // by_name_symlink_map_["system_a"] = "/dev/block/platform/soc.0/7824900.sdhci/by-name/system_a"
+    for (int i = 0; i < fstab.num_entries; i++) {
+        std::string partition_name = basename(fstab.recs[i].blk_device);
+        by_name_symlink_map_[partition_name] = fstab.recs[i].blk_device;
+    }
+    InitializeAvbOps();
+}
+
+AvbIOResult FsManagerAvbOps::ReadFromPartition(const char* partition, int64_t offset,
+                                               size_t num_bytes, void* buffer,
+                                               size_t* out_num_read) {
+    const auto iter = by_name_symlink_map_.find(partition);
+    if (iter == by_name_symlink_map_.end()) {
+        LERROR << "by-name symlink not found for partition: '" << partition << "'";
+        return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
+    }
+    std::string path = iter->second;
+
+    // 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;
+        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 << " 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_boot_config.cpp b/fs_mgr/fs_mgr_boot_config.cpp
new file mode 100644
index 0000000..cffa6ce
--- /dev/null
+++ b/fs_mgr/fs_mgr_boot_config.cpp
@@ -0,0 +1,63 @@
+/*
+ * 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/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/properties.h>
+
+#include "fs_mgr_priv.h"
+
+// Tries to get the boot config value in properties, kernel cmdline and
+// device tree (in that order).  returns 'true' if successfully found, 'false'
+// otherwise
+bool fs_mgr_get_boot_config(const std::string& key, std::string* out_val) {
+    FS_MGR_CHECK(out_val != nullptr);
+
+    // first check if we have "ro.boot" property already
+    *out_val = android::base::GetProperty("ro.boot." + key, "");
+    if (!out_val->empty()) {
+        return true;
+    }
+
+    // fallback to kernel cmdline, properties may not be ready yet
+    std::string cmdline;
+    std::string cmdline_key("androidboot." + key);
+    if (android::base::ReadFileToString("/proc/cmdline", &cmdline)) {
+        for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
+            std::vector<std::string> pieces = android::base::Split(entry, "=");
+            if (pieces.size() == 2) {
+                if (pieces[0] == cmdline_key) {
+                    *out_val = pieces[1];
+                    return true;
+                }
+            }
+        }
+    }
+
+    // lastly, check the device tree
+    if (is_dt_compatible()) {
+        std::string file_name = kAndroidDtDir + "/" + key;
+        // DT entries terminate with '\0' but so do the properties
+        if (android::base::ReadFileToString(file_name, out_val)) {
+            return true;
+        }
+
+        LINFO << "Error finding '" << key << "' in device tree";
+    }
+
+    return false;
+}
diff --git a/fs_mgr/fs_mgr_dm_ioctl.cpp b/fs_mgr/fs_mgr_dm_ioctl.cpp
new file mode 100644
index 0000000..4cbd5a8
--- /dev/null
+++ b/fs_mgr/fs_mgr_dm_ioctl.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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 <string.h>
+
+#include <android-base/logging.h>
+#include <sys/ioctl.h>
+
+#include "fs_mgr_priv.h"
+#include "fs_mgr_priv_dm_ioctl.h"
+
+void fs_mgr_verity_ioctl_init(struct dm_ioctl* io, const std::string& name, unsigned flags) {
+    memset(io, 0, DM_BUF_SIZE);
+    io->data_size = DM_BUF_SIZE;
+    io->data_start = sizeof(struct dm_ioctl);
+    io->version[0] = 4;
+    io->version[1] = 0;
+    io->version[2] = 0;
+    io->flags = flags | DM_READONLY_FLAG;
+    if (!name.empty()) {
+        strlcpy(io->name, name.c_str(), sizeof(io->name));
+    }
+}
+
+bool fs_mgr_create_verity_device(struct dm_ioctl* io, const std::string& name, int fd) {
+    fs_mgr_verity_ioctl_init(io, name, 1);
+    if (ioctl(fd, DM_DEV_CREATE, io)) {
+        PERROR << "Error creating device mapping";
+        return false;
+    }
+    return true;
+}
+
+bool fs_mgr_destroy_verity_device(struct dm_ioctl* io, const std::string& name, int fd) {
+    fs_mgr_verity_ioctl_init(io, name, 0);
+    if (ioctl(fd, DM_DEV_REMOVE, io)) {
+        PERROR << "Error removing device mapping";
+        return false;
+    }
+    return true;
+}
+
+bool fs_mgr_get_verity_device_name(struct dm_ioctl* io, const std::string& name, int fd,
+                                   std::string* out_dev_name) {
+    FS_MGR_CHECK(out_dev_name != nullptr);
+
+    fs_mgr_verity_ioctl_init(io, name, 0);
+    if (ioctl(fd, DM_DEV_STATUS, io)) {
+        PERROR << "Error fetching verity device number";
+        return false;
+    }
+
+    int dev_num = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
+    *out_dev_name = "/dev/block/dm-" + std::to_string(dev_num);
+
+    return true;
+}
+
+bool fs_mgr_resume_verity_table(struct dm_ioctl* io, const std::string& name, int fd) {
+    fs_mgr_verity_ioctl_init(io, name, 0);
+    if (ioctl(fd, DM_DEV_SUSPEND, io)) {
+        PERROR << "Error activating verity device";
+        return false;
+    }
+    return true;
+}
diff --git a/fs_mgr/fs_mgr_format.c b/fs_mgr/fs_mgr_format.c
deleted file mode 100644
index f8df081..0000000
--- a/fs_mgr/fs_mgr_format.c
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <sys/wait.h>
-#include <errno.h>
-#include <cutils/partition_utils.h>
-#include <sys/mount.h>
-#include "ext4_utils.h"
-#include "ext4.h"
-#include "make_ext4fs.h"
-#include "fs_mgr_priv.h"
-
-extern struct fs_info info;     /* magic global from ext4_utils */
-extern void reset_ext4fs_info();
-
-static int format_ext4(char *fs_blkdev, char *fs_mnt_point)
-{
-    unsigned int nr_sec;
-    int fd, rc = 0;
-
-    if ((fd = open(fs_blkdev, O_WRONLY, 0644)) < 0) {
-        ERROR("Cannot open block device.  %s\n", strerror(errno));
-        return -1;
-    }
-
-    if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
-        ERROR("Cannot get block device size.  %s\n", strerror(errno));
-        close(fd);
-        return -1;
-    }
-
-    /* Format the partition using the calculated length */
-    reset_ext4fs_info();
-    info.len = ((off64_t)nr_sec * 512);
-
-    /* Use make_ext4fs_internal to avoid wiping an already-wiped partition. */
-    rc = make_ext4fs_internal(fd, NULL, NULL, fs_mnt_point, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL);
-    if (rc) {
-        ERROR("make_ext4fs returned %d.\n", rc);
-    }
-    close(fd);
-
-    return rc;
-}
-
-static int format_f2fs(char *fs_blkdev)
-{
-    char * args[3];
-    int pid;
-    int rc = 0;
-
-    args[0] = (char *)"/sbin/mkfs.f2fs";
-    args[1] = fs_blkdev;
-    args[2] = (char *)0;
-
-    pid = fork();
-    if (pid < 0) {
-       return pid;
-    }
-    if (!pid) {
-        /* This doesn't return */
-        execv("/sbin/mkfs.f2fs", args);
-        exit(1);
-    }
-    for(;;) {
-        pid_t p = waitpid(pid, &rc, 0);
-        if (p != pid) {
-            ERROR("Error waiting for child process - %d\n", p);
-            rc = -1;
-            break;
-        }
-        if (WIFEXITED(rc)) {
-            rc = WEXITSTATUS(rc);
-            INFO("%s done, status %d\n", args[0], rc);
-            if (rc) {
-                rc = -1;
-            }
-            break;
-        }
-        ERROR("Still waiting for %s...\n", args[0]);
-    }
-
-    return rc;
-}
-
-int fs_mgr_do_format(struct fstab_rec *fstab)
-{
-    int rc = -EINVAL;
-
-    ERROR("%s: Format %s as '%s'.\n", __func__, fstab->blk_device, fstab->fs_type);
-
-    if (!strncmp(fstab->fs_type, "f2fs", 4)) {
-        rc = format_f2fs(fstab->blk_device);
-    } else if (!strncmp(fstab->fs_type, "ext4", 4)) {
-        rc = format_ext4(fstab->blk_device, fstab->mount_point);
-    } else {
-        ERROR("File system type '%s' is not supported\n", fstab->fs_type);
-    }
-
-    return rc;
-}
diff --git a/fs_mgr/fs_mgr_format.cpp b/fs_mgr/fs_mgr_format.cpp
new file mode 100644
index 0000000..5705f93
--- /dev/null
+++ b/fs_mgr/fs_mgr_format.cpp
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/wait.h>
+#include <errno.h>
+#include <cutils/partition_utils.h>
+#include <sys/mount.h>
+
+#include <ext4_utils/ext4_utils.h>
+#include <ext4_utils/ext4.h>
+#include <ext4_utils/make_ext4fs.h>
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#include <selinux/android.h>
+
+#include "fs_mgr_priv.h"
+#include "cryptfs.h"
+
+extern "C" {
+extern struct fs_info info;     /* magic global from ext4_utils */
+extern void reset_ext4fs_info();
+}
+
+static int format_ext4(char *fs_blkdev, char *fs_mnt_point, bool crypt_footer)
+{
+    uint64_t dev_sz;
+    int fd, rc = 0;
+
+    if ((fd = open(fs_blkdev, O_WRONLY)) < 0) {
+        PERROR << "Cannot open block device";
+        return -1;
+    }
+
+    if ((ioctl(fd, BLKGETSIZE64, &dev_sz)) == -1) {
+        PERROR << "Cannot get block device size";
+        close(fd);
+        return -1;
+    }
+
+    struct selabel_handle *sehandle = selinux_android_file_context_handle();
+    if (!sehandle) {
+        /* libselinux logs specific error */
+        LERROR << "Cannot initialize android file_contexts";
+        close(fd);
+        return -1;
+    }
+
+    /* Format the partition using the calculated length */
+    reset_ext4fs_info();
+    info.len = (off64_t)dev_sz;
+    if (crypt_footer) {
+        info.len -= CRYPT_FOOTER_OFFSET;
+    }
+
+    /* Use make_ext4fs_internal to avoid wiping an already-wiped partition. */
+    rc = make_ext4fs_internal(fd, NULL, NULL, fs_mnt_point, 0, 0, 0, 0, 0, 0, sehandle, 0, 0, NULL, NULL, NULL);
+    if (rc) {
+        LERROR << "make_ext4fs returned " << rc;
+    }
+    close(fd);
+
+    if (sehandle) {
+        selabel_close(sehandle);
+    }
+
+    return rc;
+}
+
+static int format_f2fs(char *fs_blkdev)
+{
+    char * args[3];
+    int pid;
+    int rc = 0;
+
+    args[0] = (char *)"/sbin/mkfs.f2fs";
+    args[1] = fs_blkdev;
+    args[2] = (char *)0;
+
+    pid = fork();
+    if (pid < 0) {
+       return pid;
+    }
+    if (!pid) {
+        /* This doesn't return */
+        execv("/sbin/mkfs.f2fs", args);
+        exit(1);
+    }
+    for(;;) {
+        pid_t p = waitpid(pid, &rc, 0);
+        if (p != pid) {
+            LERROR << "Error waiting for child process - " << p;
+            rc = -1;
+            break;
+        }
+        if (WIFEXITED(rc)) {
+            rc = WEXITSTATUS(rc);
+            LINFO << args[0] << " done, status " << rc;
+            if (rc) {
+                rc = -1;
+            }
+            break;
+        }
+        LERROR << "Still waiting for " << args[0] << "...";
+    }
+
+    return rc;
+}
+
+int fs_mgr_do_format(struct fstab_rec *fstab, bool crypt_footer)
+{
+    int rc = -EINVAL;
+
+    LERROR << __FUNCTION__ << ": Format " << fstab->blk_device
+           << " as '" << fstab->fs_type << "'";
+
+    if (!strncmp(fstab->fs_type, "f2fs", 4)) {
+        rc = format_f2fs(fstab->blk_device);
+    } else if (!strncmp(fstab->fs_type, "ext4", 4)) {
+        rc = format_ext4(fstab->blk_device, fstab->mount_point, crypt_footer);
+    } else {
+        LERROR << "File system type '" << fstab->fs_type << "' is not supported";
+    }
+
+    return rc;
+}
diff --git a/fs_mgr/fs_mgr_fstab.c b/fs_mgr/fs_mgr_fstab.c
deleted file mode 100644
index 9225d34..0000000
--- a/fs_mgr/fs_mgr_fstab.c
+++ /dev/null
@@ -1,554 +0,0 @@
-/*
- * 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.
- */
-
-#include <ctype.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mount.h>
-#include <unistd.h>
-
-#include "fs_mgr_priv.h"
-
-struct fs_mgr_flag_values {
-    char *key_loc;
-    char *verity_loc;
-    long long part_length;
-    char *label;
-    int partnum;
-    int swap_prio;
-    unsigned int zram_size;
-    unsigned int file_encryption_mode;
-};
-
-struct flag_list {
-    const char *name;
-    unsigned int flag;
-};
-
-static struct flag_list mount_flags[] = {
-    { "noatime",    MS_NOATIME },
-    { "noexec",     MS_NOEXEC },
-    { "nosuid",     MS_NOSUID },
-    { "nodev",      MS_NODEV },
-    { "nodiratime", MS_NODIRATIME },
-    { "ro",         MS_RDONLY },
-    { "rw",         0 },
-    { "remount",    MS_REMOUNT },
-    { "bind",       MS_BIND },
-    { "rec",        MS_REC },
-    { "unbindable", MS_UNBINDABLE },
-    { "private",    MS_PRIVATE },
-    { "slave",      MS_SLAVE },
-    { "shared",     MS_SHARED },
-    { "defaults",   0 },
-    { 0,            0 },
-};
-
-static struct flag_list fs_mgr_flags[] = {
-    { "wait",        MF_WAIT },
-    { "check",       MF_CHECK },
-    { "encryptable=",MF_CRYPT },
-    { "forceencrypt=",MF_FORCECRYPT },
-    { "fileencryption=",MF_FILEENCRYPTION },
-    { "forcefdeorfbe=",MF_FORCEFDEORFBE },
-    { "nonremovable",MF_NONREMOVABLE },
-    { "voldmanaged=",MF_VOLDMANAGED},
-    { "length=",     MF_LENGTH },
-    { "recoveryonly",MF_RECOVERYONLY },
-    { "swapprio=",   MF_SWAPPRIO },
-    { "zramsize=",   MF_ZRAMSIZE },
-    { "verifyatboot", MF_VERIFYATBOOT },
-    { "verify",      MF_VERIFY },
-    { "noemulatedsd", MF_NOEMULATEDSD },
-    { "notrim",       MF_NOTRIM },
-    { "formattable", MF_FORMATTABLE },
-    { "slotselect",  MF_SLOTSELECT },
-    { "nofail",      MF_NOFAIL },
-    { "latemount",   MF_LATEMOUNT },
-    { "defaults",    0 },
-    { 0,             0 },
-};
-
-#define EM_SOFTWARE 1
-#define EM_ICE      2
-
-static struct flag_list encryption_modes[] = {
-    {"software", EM_SOFTWARE},
-    {"ice", EM_ICE},
-    {0, 0}
-};
-
-static uint64_t calculate_zram_size(unsigned int percentage)
-{
-    uint64_t total;
-
-    total  = sysconf(_SC_PHYS_PAGES);
-    total *= percentage;
-    total /= 100;
-
-    total *= sysconf(_SC_PAGESIZE);
-
-    return total;
-}
-
-static int parse_flags(char *flags, struct flag_list *fl,
-                       struct fs_mgr_flag_values *flag_vals,
-                       char *fs_options, int fs_options_len)
-{
-    int f = 0;
-    int i;
-    char *p;
-    char *savep;
-
-    /* initialize flag values.  If we find a relevant flag, we'll
-     * update the value */
-    if (flag_vals) {
-        memset(flag_vals, 0, sizeof(*flag_vals));
-        flag_vals->partnum = -1;
-        flag_vals->swap_prio = -1; /* negative means it wasn't specified. */
-    }
-
-    /* initialize fs_options to the null string */
-    if (fs_options && (fs_options_len > 0)) {
-        fs_options[0] = '\0';
-    }
-
-    p = strtok_r(flags, ",", &savep);
-    while (p) {
-        /* Look for the flag "p" in the flag list "fl"
-         * If not found, the loop exits with fl[i].name being null.
-         */
-        for (i = 0; fl[i].name; i++) {
-            if (!strncmp(p, fl[i].name, strlen(fl[i].name))) {
-                f |= fl[i].flag;
-                if ((fl[i].flag == MF_CRYPT) && flag_vals) {
-                    /* The encryptable flag is followed by an = and the
-                     * location of the keys.  Get it and return it.
-                     */
-                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
-                } else if ((fl[i].flag == MF_VERIFY) && flag_vals) {
-                    /* If the verify flag is followed by an = and the
-                     * location for the verity state,  get it and return it.
-                     */
-                    char *start = strchr(p, '=');
-                    if (start) {
-                        flag_vals->verity_loc = strdup(start + 1);
-                    }
-                } else if ((fl[i].flag == MF_FORCECRYPT) && flag_vals) {
-                    /* The forceencrypt flag is followed by an = and the
-                     * location of the keys.  Get it and return it.
-                     */
-                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
-                } else if ((fl[i].flag == MF_FORCEFDEORFBE) && flag_vals) {
-                    /* The forcefdeorfbe flag is followed by an = and the
-                     * location of the keys.  Get it and return it.
-                     */
-                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
-                    flag_vals->file_encryption_mode = EM_SOFTWARE;
-                } else if ((fl[i].flag == MF_FILEENCRYPTION) && flag_vals) {
-                    /* The fileencryption flag is followed by an = and the
-                     * type of the encryption.  Get it and return it.
-                     */
-                    const struct flag_list *j;
-                    const char *mode = strchr(p, '=') + 1;
-                    for (j = encryption_modes; j->name; ++j) {
-                        if (!strcmp(mode, j->name)) {
-                            flag_vals->file_encryption_mode = j->flag;
-                        }
-                    }
-                    if (flag_vals->file_encryption_mode == 0) {
-                        ERROR("Unknown file encryption mode: %s\n", mode);
-                    }
-                } else if ((fl[i].flag == MF_LENGTH) && flag_vals) {
-                    /* The length flag is followed by an = and the
-                     * size of the partition.  Get it and return it.
-                     */
-                    flag_vals->part_length = strtoll(strchr(p, '=') + 1, NULL, 0);
-                } else if ((fl[i].flag == MF_VOLDMANAGED) && flag_vals) {
-                    /* The voldmanaged flag is followed by an = and the
-                     * label, a colon and the partition number or the
-                     * word "auto", e.g.
-                     *   voldmanaged=sdcard:3
-                     * Get and return them.
-                     */
-                    char *label_start;
-                    char *label_end;
-                    char *part_start;
-
-                    label_start = strchr(p, '=') + 1;
-                    label_end = strchr(p, ':');
-                    if (label_end) {
-                        flag_vals->label = strndup(label_start,
-                                                   (int) (label_end - label_start));
-                        part_start = strchr(p, ':') + 1;
-                        if (!strcmp(part_start, "auto")) {
-                            flag_vals->partnum = -1;
-                        } else {
-                            flag_vals->partnum = strtol(part_start, NULL, 0);
-                        }
-                    } else {
-                        ERROR("Warning: voldmanaged= flag malformed\n");
-                    }
-                } else if ((fl[i].flag == MF_SWAPPRIO) && flag_vals) {
-                    flag_vals->swap_prio = strtoll(strchr(p, '=') + 1, NULL, 0);
-                } else if ((fl[i].flag == MF_ZRAMSIZE) && flag_vals) {
-                    int is_percent = !!strrchr(p, '%');
-                    unsigned int val = strtoll(strchr(p, '=') + 1, NULL, 0);
-                    if (is_percent)
-                        flag_vals->zram_size = calculate_zram_size(val);
-                    else
-                        flag_vals->zram_size = val;
-                }
-                break;
-            }
-        }
-
-        if (!fl[i].name) {
-            if (fs_options) {
-                /* It's not a known flag, so it must be a filesystem specific
-                 * option.  Add it to fs_options if it was passed in.
-                 */
-                strlcat(fs_options, p, fs_options_len);
-                strlcat(fs_options, ",", fs_options_len);
-            } else {
-                /* fs_options was not passed in, so if the flag is unknown
-                 * it's an error.
-                 */
-                ERROR("Warning: unknown flag %s\n", p);
-            }
-        }
-        p = strtok_r(NULL, ",", &savep);
-    }
-
-    if (fs_options && fs_options[0]) {
-        /* remove the last trailing comma from the list of options */
-        fs_options[strlen(fs_options) - 1] = '\0';
-    }
-
-    return f;
-}
-
-struct fstab *fs_mgr_read_fstab(const char *fstab_path)
-{
-    FILE *fstab_file;
-    int cnt, entries;
-    ssize_t len;
-    size_t alloc_len = 0;
-    char *line = NULL;
-    const char *delim = " \t";
-    char *save_ptr, *p;
-    struct fstab *fstab = NULL;
-    struct fs_mgr_flag_values flag_vals;
-#define FS_OPTIONS_LEN 1024
-    char tmp_fs_options[FS_OPTIONS_LEN];
-
-    fstab_file = fopen(fstab_path, "r");
-    if (!fstab_file) {
-        ERROR("Cannot open file %s\n", fstab_path);
-        return 0;
-    }
-
-    entries = 0;
-    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
-        /* if the last character is a newline, shorten the string by 1 byte */
-        if (line[len - 1] == '\n') {
-            line[len - 1] = '\0';
-        }
-        /* Skip any leading whitespace */
-        p = line;
-        while (isspace(*p)) {
-            p++;
-        }
-        /* ignore comments or empty lines */
-        if (*p == '#' || *p == '\0')
-            continue;
-        entries++;
-    }
-
-    if (!entries) {
-        ERROR("No entries found in fstab\n");
-        goto err;
-    }
-
-    /* Allocate and init the fstab structure */
-    fstab = calloc(1, sizeof(struct fstab));
-    fstab->num_entries = entries;
-    fstab->fstab_filename = strdup(fstab_path);
-    fstab->recs = calloc(fstab->num_entries, sizeof(struct fstab_rec));
-
-    fseek(fstab_file, 0, SEEK_SET);
-
-    cnt = 0;
-    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
-        /* if the last character is a newline, shorten the string by 1 byte */
-        if (line[len - 1] == '\n') {
-            line[len - 1] = '\0';
-        }
-
-        /* Skip any leading whitespace */
-        p = line;
-        while (isspace(*p)) {
-            p++;
-        }
-        /* ignore comments or empty lines */
-        if (*p == '#' || *p == '\0')
-            continue;
-
-        /* If a non-comment entry is greater than the size we allocated, give an
-         * error and quit.  This can happen in the unlikely case the file changes
-         * between the two reads.
-         */
-        if (cnt >= entries) {
-            ERROR("Tried to process more entries than counted\n");
-            break;
-        }
-
-        if (!(p = strtok_r(line, delim, &save_ptr))) {
-            ERROR("Error parsing mount source\n");
-            goto err;
-        }
-        fstab->recs[cnt].blk_device = strdup(p);
-
-        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing mount_point\n");
-            goto err;
-        }
-        fstab->recs[cnt].mount_point = strdup(p);
-
-        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing fs_type\n");
-            goto err;
-        }
-        fstab->recs[cnt].fs_type = strdup(p);
-
-        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing mount_flags\n");
-            goto err;
-        }
-        tmp_fs_options[0] = '\0';
-        fstab->recs[cnt].flags = parse_flags(p, mount_flags, NULL,
-                                       tmp_fs_options, FS_OPTIONS_LEN);
-
-        /* fs_options are optional */
-        if (tmp_fs_options[0]) {
-            fstab->recs[cnt].fs_options = strdup(tmp_fs_options);
-        } else {
-            fstab->recs[cnt].fs_options = NULL;
-        }
-
-        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing fs_mgr_options\n");
-            goto err;
-        }
-        fstab->recs[cnt].fs_mgr_flags = parse_flags(p, fs_mgr_flags,
-                                                    &flag_vals, NULL, 0);
-        fstab->recs[cnt].key_loc = flag_vals.key_loc;
-        fstab->recs[cnt].verity_loc = flag_vals.verity_loc;
-        fstab->recs[cnt].length = flag_vals.part_length;
-        fstab->recs[cnt].label = flag_vals.label;
-        fstab->recs[cnt].partnum = flag_vals.partnum;
-        fstab->recs[cnt].swap_prio = flag_vals.swap_prio;
-        fstab->recs[cnt].zram_size = flag_vals.zram_size;
-        fstab->recs[cnt].file_encryption_mode = flag_vals.file_encryption_mode;
-        cnt++;
-    }
-    /* If an A/B partition, modify block device to be the real block device */
-    if (fs_mgr_update_for_slotselect(fstab) != 0) {
-        ERROR("Error updating for slotselect\n");
-        goto err;
-    }
-    fclose(fstab_file);
-    free(line);
-    return fstab;
-
-err:
-    fclose(fstab_file);
-    free(line);
-    if (fstab)
-        fs_mgr_free_fstab(fstab);
-    return NULL;
-}
-
-void fs_mgr_free_fstab(struct fstab *fstab)
-{
-    int i;
-
-    if (!fstab) {
-        return;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        /* Free the pointers return by strdup(3) */
-        free(fstab->recs[i].blk_device);
-        free(fstab->recs[i].mount_point);
-        free(fstab->recs[i].fs_type);
-        free(fstab->recs[i].fs_options);
-        free(fstab->recs[i].key_loc);
-        free(fstab->recs[i].label);
-    }
-
-    /* Free the fstab_recs array created by calloc(3) */
-    free(fstab->recs);
-
-    /* Free the fstab filename */
-    free(fstab->fstab_filename);
-
-    /* Free fstab */
-    free(fstab);
-}
-
-/* Add an entry to the fstab, and return 0 on success or -1 on error */
-int fs_mgr_add_entry(struct fstab *fstab,
-                     const char *mount_point, const char *fs_type,
-                     const char *blk_device)
-{
-    struct fstab_rec *new_fstab_recs;
-    int n = fstab->num_entries;
-
-    new_fstab_recs = (struct fstab_rec *)
-                     realloc(fstab->recs, sizeof(struct fstab_rec) * (n + 1));
-
-    if (!new_fstab_recs) {
-        return -1;
-    }
-
-    /* A new entry was added, so initialize it */
-     memset(&new_fstab_recs[n], 0, sizeof(struct fstab_rec));
-     new_fstab_recs[n].mount_point = strdup(mount_point);
-     new_fstab_recs[n].fs_type = strdup(fs_type);
-     new_fstab_recs[n].blk_device = strdup(blk_device);
-     new_fstab_recs[n].length = 0;
-
-     /* Update the fstab struct */
-     fstab->recs = new_fstab_recs;
-     fstab->num_entries++;
-
-     return 0;
-}
-
-/*
- * Returns the 1st matching fstab_rec that follows the start_rec.
- * start_rec is the result of a previous search or NULL.
- */
-struct fstab_rec *fs_mgr_get_entry_for_mount_point_after(struct fstab_rec *start_rec, struct fstab *fstab, const char *path)
-{
-    int i;
-    if (!fstab) {
-        return NULL;
-    }
-
-    if (start_rec) {
-        for (i = 0; i < fstab->num_entries; i++) {
-            if (&fstab->recs[i] == start_rec) {
-                i++;
-                break;
-            }
-        }
-    } else {
-        i = 0;
-    }
-    for (; i < fstab->num_entries; i++) {
-        int len = strlen(fstab->recs[i].mount_point);
-        if (strncmp(path, fstab->recs[i].mount_point, len) == 0 &&
-            (path[len] == '\0' || path[len] == '/')) {
-            return &fstab->recs[i];
-        }
-    }
-    return NULL;
-}
-
-/*
- * Returns the 1st matching mount point.
- * There might be more. To look for others, use fs_mgr_get_entry_for_mount_point_after()
- * and give the fstab_rec from the previous search.
- */
-struct fstab_rec *fs_mgr_get_entry_for_mount_point(struct fstab *fstab, const char *path)
-{
-    return fs_mgr_get_entry_for_mount_point_after(NULL, fstab, path);
-}
-
-int fs_mgr_is_voldmanaged(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_VOLDMANAGED;
-}
-
-int fs_mgr_is_nonremovable(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_NONREMOVABLE;
-}
-
-int fs_mgr_is_verified(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_VERIFY;
-}
-
-int fs_mgr_is_encryptable(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & (MF_CRYPT | MF_FORCECRYPT | MF_FORCEFDEORFBE);
-}
-
-int fs_mgr_is_file_encrypted(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_FILEENCRYPTION;
-}
-
-const char* fs_mgr_get_file_encryption_mode(const struct fstab_rec *fstab)
-{
-    const struct flag_list *j;
-    for (j = encryption_modes; j->name; ++j) {
-        if (fstab->file_encryption_mode == j->flag) {
-            return j->name;
-        }
-    }
-    return NULL;
-}
-
-int fs_mgr_is_convertible_to_fbe(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_FORCEFDEORFBE;
-}
-
-int fs_mgr_is_noemulatedsd(const struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_NOEMULATEDSD;
-}
-
-int fs_mgr_is_notrim(struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_NOTRIM;
-}
-
-int fs_mgr_is_formattable(struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & (MF_FORMATTABLE);
-}
-
-int fs_mgr_is_slotselect(struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_SLOTSELECT;
-}
-
-int fs_mgr_is_nofail(struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_NOFAIL;
-}
-
-int fs_mgr_is_latemount(struct fstab_rec *fstab)
-{
-    return fstab->fs_mgr_flags & MF_LATEMOUNT;
-}
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
new file mode 100644
index 0000000..7d09d01
--- /dev/null
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -0,0 +1,894 @@
+/*
+ * 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.
+ */
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <unistd.h>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "fs_mgr_priv.h"
+
+struct fs_mgr_flag_values {
+    char *key_loc;
+    char *verity_loc;
+    long long part_length;
+    char *label;
+    int partnum;
+    int swap_prio;
+    int max_comp_streams;
+    unsigned int zram_size;
+    uint64_t reserved_size;
+    unsigned int file_contents_mode;
+    unsigned int file_names_mode;
+    unsigned int erase_blk_size;
+    unsigned int logical_blk_size;
+};
+
+struct flag_list {
+    const char *name;
+    unsigned int flag;
+};
+
+static struct flag_list mount_flags[] = {
+    { "noatime",    MS_NOATIME },
+    { "noexec",     MS_NOEXEC },
+    { "nosuid",     MS_NOSUID },
+    { "nodev",      MS_NODEV },
+    { "nodiratime", MS_NODIRATIME },
+    { "ro",         MS_RDONLY },
+    { "rw",         0 },
+    { "remount",    MS_REMOUNT },
+    { "bind",       MS_BIND },
+    { "rec",        MS_REC },
+    { "unbindable", MS_UNBINDABLE },
+    { "private",    MS_PRIVATE },
+    { "slave",      MS_SLAVE },
+    { "shared",     MS_SHARED },
+    { "defaults",   0 },
+    { 0,            0 },
+};
+
+static struct flag_list fs_mgr_flags[] = {
+    { "wait",               MF_WAIT },
+    { "check",              MF_CHECK },
+    { "encryptable=",       MF_CRYPT },
+    { "forceencrypt=",      MF_FORCECRYPT },
+    { "fileencryption=",    MF_FILEENCRYPTION },
+    { "forcefdeorfbe=",     MF_FORCEFDEORFBE },
+    { "nonremovable",       MF_NONREMOVABLE },
+    { "voldmanaged=",       MF_VOLDMANAGED},
+    { "length=",            MF_LENGTH },
+    { "recoveryonly",       MF_RECOVERYONLY },
+    { "swapprio=",          MF_SWAPPRIO },
+    { "zramsize=",          MF_ZRAMSIZE },
+    { "max_comp_streams=",  MF_MAX_COMP_STREAMS },
+    { "verifyatboot",       MF_VERIFYATBOOT },
+    { "verify",             MF_VERIFY },
+    { "avb",                MF_AVB },
+    { "noemulatedsd",       MF_NOEMULATEDSD },
+    { "notrim",             MF_NOTRIM },
+    { "formattable",        MF_FORMATTABLE },
+    { "slotselect",         MF_SLOTSELECT },
+    { "nofail",             MF_NOFAIL },
+    { "latemount",          MF_LATEMOUNT },
+    { "reservedsize=",      MF_RESERVEDSIZE },
+    { "quota",              MF_QUOTA },
+    { "eraseblk=",          MF_ERASEBLKSIZE },
+    { "logicalblk=",        MF_LOGICALBLKSIZE },
+    { "defaults",           0 },
+    { 0,                    0 },
+};
+
+#define EM_AES_256_XTS  1
+#define EM_ICE          2
+#define EM_AES_256_CTS  3
+#define EM_AES_256_HEH  4
+
+static const struct flag_list file_contents_encryption_modes[] = {
+    {"aes-256-xts", EM_AES_256_XTS},
+    {"software", EM_AES_256_XTS}, /* alias for backwards compatibility */
+    {"ice", EM_ICE}, /* hardware-specific inline cryptographic engine */
+    {0, 0},
+};
+
+static const struct flag_list file_names_encryption_modes[] = {
+    {"aes-256-cts", EM_AES_256_CTS},
+    {"aes-256-heh", EM_AES_256_HEH},
+    {0, 0},
+};
+
+static unsigned int encryption_mode_to_flag(const struct flag_list *list,
+                                            const char *mode, const char *type)
+{
+    const struct flag_list *j;
+
+    for (j = list; j->name; ++j) {
+        if (!strcmp(mode, j->name)) {
+            return j->flag;
+        }
+    }
+    LERROR << "Unknown " << type << " encryption mode: " << mode;
+    return 0;
+}
+
+static const char *flag_to_encryption_mode(const struct flag_list *list,
+                                           unsigned int flag)
+{
+    const struct flag_list *j;
+
+    for (j = list; j->name; ++j) {
+        if (flag == j->flag) {
+            return j->name;
+        }
+    }
+    return nullptr;
+}
+
+static uint64_t calculate_zram_size(unsigned int percentage)
+{
+    uint64_t total;
+
+    total  = sysconf(_SC_PHYS_PAGES);
+    total *= percentage;
+    total /= 100;
+
+    total *= sysconf(_SC_PAGESIZE);
+
+    return total;
+}
+
+static uint64_t parse_size(const char *arg)
+{
+    char *endptr;
+    uint64_t size = strtoull(arg, &endptr, 10);
+    if (*endptr == 'k' || *endptr == 'K')
+        size *= 1024LL;
+    else if (*endptr == 'm' || *endptr == 'M')
+        size *= 1024LL * 1024LL;
+    else if (*endptr == 'g' || *endptr == 'G')
+        size *= 1024LL * 1024LL * 1024LL;
+
+    return size;
+}
+
+/* fills 'dt_value' with the underlying device tree value string without
+ * the trailing '\0'. Returns true if 'dt_value' has a valid string, 'false'
+ * otherwise.
+ */
+static bool read_dt_file(const std::string& file_name, std::string* dt_value)
+{
+    if (android::base::ReadFileToString(file_name, dt_value)) {
+        if (!dt_value->empty()) {
+            // trim the trailing '\0' out, otherwise the comparison
+            // will produce false-negatives.
+            dt_value->resize(dt_value->size() - 1);
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static int parse_flags(char *flags, struct flag_list *fl,
+                       struct fs_mgr_flag_values *flag_vals,
+                       char *fs_options, int fs_options_len)
+{
+    int f = 0;
+    int i;
+    char *p;
+    char *savep;
+
+    /* initialize flag values.  If we find a relevant flag, we'll
+     * update the value */
+    if (flag_vals) {
+        memset(flag_vals, 0, sizeof(*flag_vals));
+        flag_vals->partnum = -1;
+        flag_vals->swap_prio = -1; /* negative means it wasn't specified. */
+    }
+
+    /* initialize fs_options to the null string */
+    if (fs_options && (fs_options_len > 0)) {
+        fs_options[0] = '\0';
+    }
+
+    p = strtok_r(flags, ",", &savep);
+    while (p) {
+        /* Look for the flag "p" in the flag list "fl"
+         * If not found, the loop exits with fl[i].name being null.
+         */
+        for (i = 0; fl[i].name; i++) {
+            if (!strncmp(p, fl[i].name, strlen(fl[i].name))) {
+                f |= fl[i].flag;
+                if ((fl[i].flag == MF_CRYPT) && flag_vals) {
+                    /* The encryptable flag is followed by an = and the
+                     * location of the keys.  Get it and return it.
+                     */
+                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
+                } else if ((fl[i].flag == MF_VERIFY) && flag_vals) {
+                    /* If the verify flag is followed by an = and the
+                     * location for the verity state,  get it and return it.
+                     */
+                    char *start = strchr(p, '=');
+                    if (start) {
+                        flag_vals->verity_loc = strdup(start + 1);
+                    }
+                } else if ((fl[i].flag == MF_FORCECRYPT) && flag_vals) {
+                    /* The forceencrypt flag is followed by an = and the
+                     * location of the keys.  Get it and return it.
+                     */
+                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
+                } else if ((fl[i].flag == MF_FORCEFDEORFBE) && flag_vals) {
+                    /* The forcefdeorfbe flag is followed by an = and the
+                     * location of the keys.  Get it and return it.
+                     */
+                    flag_vals->key_loc = strdup(strchr(p, '=') + 1);
+                    flag_vals->file_contents_mode = EM_AES_256_XTS;
+                    flag_vals->file_names_mode = EM_AES_256_CTS;
+                } else if ((fl[i].flag == MF_FILEENCRYPTION) && flag_vals) {
+                    /* The fileencryption flag is followed by an = and
+                     * the mode of contents encryption, then optionally a
+                     * : and the mode of filenames encryption (defaults
+                     * to aes-256-cts).  Get it and return it.
+                     */
+                    char *mode = strchr(p, '=') + 1;
+                    char *colon = strchr(mode, ':');
+                    if (colon) {
+                        *colon = '\0';
+                    }
+                    flag_vals->file_contents_mode =
+                        encryption_mode_to_flag(file_contents_encryption_modes,
+                                                mode, "file contents");
+                    if (colon) {
+                        flag_vals->file_names_mode =
+                            encryption_mode_to_flag(file_names_encryption_modes,
+                                                    colon + 1, "file names");
+                    } else {
+                        flag_vals->file_names_mode = EM_AES_256_CTS;
+                    }
+                } else if ((fl[i].flag == MF_LENGTH) && flag_vals) {
+                    /* The length flag is followed by an = and the
+                     * size of the partition.  Get it and return it.
+                     */
+                    flag_vals->part_length = strtoll(strchr(p, '=') + 1, NULL, 0);
+                } else if ((fl[i].flag == MF_VOLDMANAGED) && flag_vals) {
+                    /* The voldmanaged flag is followed by an = and the
+                     * label, a colon and the partition number or the
+                     * word "auto", e.g.
+                     *   voldmanaged=sdcard:3
+                     * Get and return them.
+                     */
+                    char *label_start;
+                    char *label_end;
+                    char *part_start;
+
+                    label_start = strchr(p, '=') + 1;
+                    label_end = strchr(p, ':');
+                    if (label_end) {
+                        flag_vals->label = strndup(label_start,
+                                                   (int) (label_end - label_start));
+                        part_start = strchr(p, ':') + 1;
+                        if (!strcmp(part_start, "auto")) {
+                            flag_vals->partnum = -1;
+                        } else {
+                            flag_vals->partnum = strtol(part_start, NULL, 0);
+                        }
+                    } else {
+                        LERROR << "Warning: voldmanaged= flag malformed";
+                    }
+                } else if ((fl[i].flag == MF_SWAPPRIO) && flag_vals) {
+                    flag_vals->swap_prio = strtoll(strchr(p, '=') + 1, NULL, 0);
+                } else if ((fl[i].flag == MF_MAX_COMP_STREAMS) && flag_vals) {
+                    flag_vals->max_comp_streams = strtoll(strchr(p, '=') + 1, NULL, 0);
+                } else if ((fl[i].flag == MF_ZRAMSIZE) && flag_vals) {
+                    int is_percent = !!strrchr(p, '%');
+                    unsigned int val = strtoll(strchr(p, '=') + 1, NULL, 0);
+                    if (is_percent)
+                        flag_vals->zram_size = calculate_zram_size(val);
+                    else
+                        flag_vals->zram_size = val;
+                } else if ((fl[i].flag == MF_RESERVEDSIZE) && flag_vals) {
+                    /* The reserved flag is followed by an = and the
+                     * reserved size of the partition.  Get it and return it.
+                     */
+                    flag_vals->reserved_size = parse_size(strchr(p, '=') + 1);
+                } else if ((fl[i].flag == MF_ERASEBLKSIZE) && flag_vals) {
+                    /* The erase block size flag is followed by an = and the flash
+                     * erase block size. Get it, check that it is a power of 2 and
+                     * at least 4096, and return it.
+                     */
+                    unsigned int val = strtoul(strchr(p, '=') + 1, NULL, 0);
+                    if (val >= 4096 && (val & (val - 1)) == 0)
+                        flag_vals->erase_blk_size = val;
+                } else if ((fl[i].flag == MF_LOGICALBLKSIZE) && flag_vals) {
+                    /* The logical block size flag is followed by an = and the flash
+                     * logical block size. Get it, check that it is a power of 2 and
+                     * at least 4096, and return it.
+                     */
+                    unsigned int val = strtoul(strchr(p, '=') + 1, NULL, 0);
+                    if (val >= 4096 && (val & (val - 1)) == 0)
+                        flag_vals->logical_blk_size = val;
+                }
+                break;
+            }
+        }
+
+        if (!fl[i].name) {
+            if (fs_options) {
+                /* It's not a known flag, so it must be a filesystem specific
+                 * option.  Add it to fs_options if it was passed in.
+                 */
+                strlcat(fs_options, p, fs_options_len);
+                strlcat(fs_options, ",", fs_options_len);
+            } else {
+                /* fs_options was not passed in, so if the flag is unknown
+                 * it's an error.
+                 */
+                LERROR << "Warning: unknown flag " << p;
+            }
+        }
+        p = strtok_r(NULL, ",", &savep);
+    }
+
+    if (fs_options && fs_options[0]) {
+        /* remove the last trailing comma from the list of options */
+        fs_options[strlen(fs_options) - 1] = '\0';
+    }
+
+    return f;
+}
+
+static bool is_dt_fstab_compatible() {
+    std::string dt_value;
+    std::string file_name = kAndroidDtDir + "/fstab/compatible";
+    if (read_dt_file(file_name, &dt_value)) {
+        if (dt_value == "android,fstab") {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static std::string read_fstab_from_dt() {
+    std::string fstab;
+    if (!is_dt_compatible() || !is_dt_fstab_compatible()) {
+        return fstab;
+    }
+
+    std::string fstabdir_name = kAndroidDtDir + "/fstab";
+    std::unique_ptr<DIR, int (*)(DIR*)> fstabdir(opendir(fstabdir_name.c_str()), closedir);
+    if (!fstabdir) return fstab;
+
+    dirent* dp;
+    while ((dp = readdir(fstabdir.get())) != NULL) {
+        // skip over name and compatible
+        if (dp->d_type != DT_DIR) {
+            continue;
+        }
+
+        // skip if its not 'vendor', 'odm' or 'system'
+        if (strcmp(dp->d_name, "odm") && strcmp(dp->d_name, "system") &&
+            strcmp(dp->d_name, "vendor")) {
+            continue;
+        }
+
+        // create <dev> <mnt_point>  <type>  <mnt_flags>  <fsmgr_flags>\n
+        std::vector<std::string> fstab_entry;
+        std::string file_name;
+        std::string value;
+        // skip a partition entry if the status property is present and not set to ok
+        file_name = android::base::StringPrintf("%s/%s/status", fstabdir_name.c_str(), dp->d_name);
+        if (read_dt_file(file_name, &value)) {
+            if (value != "okay" && value != "ok") {
+                LINFO << "dt_fstab: Skip disabled entry for partition " << dp->d_name;
+                continue;
+            }
+        }
+
+        file_name = android::base::StringPrintf("%s/%s/dev", fstabdir_name.c_str(), dp->d_name);
+        if (!read_dt_file(file_name, &value)) {
+            LERROR << "dt_fstab: Failed to find device for partition " << dp->d_name;
+            fstab.clear();
+            break;
+        }
+        fstab_entry.push_back(value);
+        fstab_entry.push_back(android::base::StringPrintf("/%s", dp->d_name));
+
+        file_name = android::base::StringPrintf("%s/%s/type", fstabdir_name.c_str(), dp->d_name);
+        if (!read_dt_file(file_name, &value)) {
+            LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
+            fstab.clear();
+            break;
+        }
+        fstab_entry.push_back(value);
+
+        file_name = android::base::StringPrintf("%s/%s/mnt_flags", fstabdir_name.c_str(), dp->d_name);
+        if (!read_dt_file(file_name, &value)) {
+            LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
+            fstab.clear();
+            break;
+        }
+        fstab_entry.push_back(value);
+
+        file_name = android::base::StringPrintf("%s/%s/fsmgr_flags", fstabdir_name.c_str(), dp->d_name);
+        if (!read_dt_file(file_name, &value)) {
+            LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
+            fstab.clear();
+            break;
+        }
+        fstab_entry.push_back(value);
+
+        fstab += android::base::Join(fstab_entry, " ");
+        fstab += '\n';
+    }
+
+    return fstab;
+}
+
+bool is_dt_compatible() {
+    std::string file_name = kAndroidDtDir + "/compatible";
+    std::string dt_value;
+    if (read_dt_file(file_name, &dt_value)) {
+        if (dt_value == "android,firmware") {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static struct fstab *fs_mgr_read_fstab_file(FILE *fstab_file)
+{
+    int cnt, entries;
+    ssize_t len;
+    size_t alloc_len = 0;
+    char *line = NULL;
+    const char *delim = " \t";
+    char *save_ptr, *p;
+    struct fstab *fstab = NULL;
+    struct fs_mgr_flag_values flag_vals;
+#define FS_OPTIONS_LEN 1024
+    char tmp_fs_options[FS_OPTIONS_LEN];
+
+    entries = 0;
+    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
+        /* if the last character is a newline, shorten the string by 1 byte */
+        if (line[len - 1] == '\n') {
+            line[len - 1] = '\0';
+        }
+        /* Skip any leading whitespace */
+        p = line;
+        while (isspace(*p)) {
+            p++;
+        }
+        /* ignore comments or empty lines */
+        if (*p == '#' || *p == '\0')
+            continue;
+        entries++;
+    }
+
+    if (!entries) {
+        LERROR << "No entries found in fstab";
+        goto err;
+    }
+
+    /* Allocate and init the fstab structure */
+    fstab = static_cast<struct fstab *>(calloc(1, sizeof(struct fstab)));
+    fstab->num_entries = entries;
+    fstab->recs = static_cast<struct fstab_rec *>(
+        calloc(fstab->num_entries, sizeof(struct fstab_rec)));
+
+    fseek(fstab_file, 0, SEEK_SET);
+
+    cnt = 0;
+    while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
+        /* if the last character is a newline, shorten the string by 1 byte */
+        if (line[len - 1] == '\n') {
+            line[len - 1] = '\0';
+        }
+
+        /* Skip any leading whitespace */
+        p = line;
+        while (isspace(*p)) {
+            p++;
+        }
+        /* ignore comments or empty lines */
+        if (*p == '#' || *p == '\0')
+            continue;
+
+        /* If a non-comment entry is greater than the size we allocated, give an
+         * error and quit.  This can happen in the unlikely case the file changes
+         * between the two reads.
+         */
+        if (cnt >= entries) {
+            LERROR << "Tried to process more entries than counted";
+            break;
+        }
+
+        if (!(p = strtok_r(line, delim, &save_ptr))) {
+            LERROR << "Error parsing mount source";
+            goto err;
+        }
+        fstab->recs[cnt].blk_device = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            LERROR << "Error parsing mount_point";
+            goto err;
+        }
+        fstab->recs[cnt].mount_point = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            LERROR << "Error parsing fs_type";
+            goto err;
+        }
+        fstab->recs[cnt].fs_type = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            LERROR << "Error parsing mount_flags";
+            goto err;
+        }
+        tmp_fs_options[0] = '\0';
+        fstab->recs[cnt].flags = parse_flags(p, mount_flags, NULL,
+                                       tmp_fs_options, FS_OPTIONS_LEN);
+
+        /* fs_options are optional */
+        if (tmp_fs_options[0]) {
+            fstab->recs[cnt].fs_options = strdup(tmp_fs_options);
+        } else {
+            fstab->recs[cnt].fs_options = NULL;
+        }
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            LERROR << "Error parsing fs_mgr_options";
+            goto err;
+        }
+        fstab->recs[cnt].fs_mgr_flags = parse_flags(p, fs_mgr_flags,
+                                                    &flag_vals, NULL, 0);
+        fstab->recs[cnt].key_loc = flag_vals.key_loc;
+        fstab->recs[cnt].verity_loc = flag_vals.verity_loc;
+        fstab->recs[cnt].length = flag_vals.part_length;
+        fstab->recs[cnt].label = flag_vals.label;
+        fstab->recs[cnt].partnum = flag_vals.partnum;
+        fstab->recs[cnt].swap_prio = flag_vals.swap_prio;
+        fstab->recs[cnt].max_comp_streams = flag_vals.max_comp_streams;
+        fstab->recs[cnt].zram_size = flag_vals.zram_size;
+        fstab->recs[cnt].reserved_size = flag_vals.reserved_size;
+        fstab->recs[cnt].file_contents_mode = flag_vals.file_contents_mode;
+        fstab->recs[cnt].file_names_mode = flag_vals.file_names_mode;
+        fstab->recs[cnt].erase_blk_size = flag_vals.erase_blk_size;
+        fstab->recs[cnt].logical_blk_size = flag_vals.logical_blk_size;
+        cnt++;
+    }
+    /* If an A/B partition, modify block device to be the real block device */
+    if (!fs_mgr_update_for_slotselect(fstab)) {
+        LERROR << "Error updating for slotselect";
+        goto err;
+    }
+    free(line);
+    return fstab;
+
+err:
+    free(line);
+    if (fstab)
+        fs_mgr_free_fstab(fstab);
+    return NULL;
+}
+
+/* merges fstab entries from both a and b, then returns the merged result.
+ * note that the caller should only manage the return pointer without
+ * doing further memory management for the two inputs, i.e. only need to
+ * frees up memory of the return value without touching a and b. */
+static struct fstab *in_place_merge(struct fstab *a, struct fstab *b)
+{
+    if (!a) return b;
+    if (!b) return a;
+
+    int total_entries = a->num_entries + b->num_entries;
+    a->recs = static_cast<struct fstab_rec *>(realloc(
+        a->recs, total_entries * (sizeof(struct fstab_rec))));
+    if (!a->recs) {
+        LERROR << __FUNCTION__ << "(): failed to allocate fstab recs";
+        // If realloc() fails the original block is left untouched;
+        // it is not freed or moved. So we have to free both a and b here.
+        fs_mgr_free_fstab(a);
+        fs_mgr_free_fstab(b);
+        return nullptr;
+    }
+
+    for (int i = a->num_entries, j = 0; i < total_entries; i++, j++) {
+        // copy the pointer directly *without* malloc and memcpy
+        a->recs[i] = b->recs[j];
+    }
+
+    // Frees up b, but don't free b->recs[X] to make sure they are
+    // accessible through a->recs[X].
+    free(b->fstab_filename);
+    free(b);
+
+    a->num_entries = total_entries;
+    return a;
+}
+
+struct fstab *fs_mgr_read_fstab(const char *fstab_path)
+{
+    FILE *fstab_file;
+    struct fstab *fstab;
+
+    fstab_file = fopen(fstab_path, "r");
+    if (!fstab_file) {
+        PERROR << __FUNCTION__<< "(): cannot open file: '" << fstab_path << "'";
+        return nullptr;
+    }
+
+    fstab = fs_mgr_read_fstab_file(fstab_file);
+    if (fstab) {
+        fstab->fstab_filename = strdup(fstab_path);
+    } else {
+        LERROR << __FUNCTION__ << "(): failed to load fstab from : '" << fstab_path << "'";
+    }
+
+    fclose(fstab_file);
+    return fstab;
+}
+
+/* Returns fstab entries parsed from the device tree if they
+ * exist
+ */
+struct fstab *fs_mgr_read_fstab_dt()
+{
+    std::string fstab_buf = read_fstab_from_dt();
+    if (fstab_buf.empty()) {
+        LINFO << __FUNCTION__ << "(): failed to read fstab from dt";
+        return nullptr;
+    }
+
+    std::unique_ptr<FILE, decltype(&fclose)> fstab_file(
+        fmemopen(static_cast<void*>(const_cast<char*>(fstab_buf.c_str())),
+                 fstab_buf.length(), "r"), fclose);
+    if (!fstab_file) {
+        PERROR << __FUNCTION__ << "(): failed to create a file stream for fstab dt";
+        return nullptr;
+    }
+
+    struct fstab *fstab = fs_mgr_read_fstab_file(fstab_file.get());
+    if (!fstab) {
+        LERROR << __FUNCTION__ << "(): failed to load fstab from kernel:"
+               << std::endl << fstab_buf;
+    }
+
+    return 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
+ * in from device tree.
+ */
+struct fstab *fs_mgr_read_fstab_default()
+{
+    std::string hw;
+    std::string default_fstab;
+
+    // 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;
+        }
+    } else {
+        LWARNING << __FUNCTION__ << "(): failed to find device hardware name";
+    }
+
+    // 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)
+{
+    int i;
+
+    if (!fstab) {
+        return;
+    }
+
+    for (i = 0; i < fstab->num_entries; i++) {
+        /* Free the pointers return by strdup(3) */
+        free(fstab->recs[i].blk_device);
+        free(fstab->recs[i].mount_point);
+        free(fstab->recs[i].fs_type);
+        free(fstab->recs[i].fs_options);
+        free(fstab->recs[i].key_loc);
+        free(fstab->recs[i].label);
+    }
+
+    /* Free the fstab_recs array created by calloc(3) */
+    free(fstab->recs);
+
+    /* Free the fstab filename */
+    free(fstab->fstab_filename);
+
+    /* Free fstab */
+    free(fstab);
+}
+
+/* Add an entry to the fstab, and return 0 on success or -1 on error */
+int fs_mgr_add_entry(struct fstab *fstab,
+                     const char *mount_point, const char *fs_type,
+                     const char *blk_device)
+{
+    struct fstab_rec *new_fstab_recs;
+    int n = fstab->num_entries;
+
+    new_fstab_recs = (struct fstab_rec *)
+                     realloc(fstab->recs, sizeof(struct fstab_rec) * (n + 1));
+
+    if (!new_fstab_recs) {
+        return -1;
+    }
+
+    /* A new entry was added, so initialize it */
+     memset(&new_fstab_recs[n], 0, sizeof(struct fstab_rec));
+     new_fstab_recs[n].mount_point = strdup(mount_point);
+     new_fstab_recs[n].fs_type = strdup(fs_type);
+     new_fstab_recs[n].blk_device = strdup(blk_device);
+     new_fstab_recs[n].length = 0;
+
+     /* Update the fstab struct */
+     fstab->recs = new_fstab_recs;
+     fstab->num_entries++;
+
+     return 0;
+}
+
+/*
+ * Returns the 1st matching fstab_rec that follows the start_rec.
+ * start_rec is the result of a previous search or NULL.
+ */
+struct fstab_rec *fs_mgr_get_entry_for_mount_point_after(struct fstab_rec *start_rec, struct fstab *fstab, const char *path)
+{
+    int i;
+    if (!fstab) {
+        return NULL;
+    }
+
+    if (start_rec) {
+        for (i = 0; i < fstab->num_entries; i++) {
+            if (&fstab->recs[i] == start_rec) {
+                i++;
+                break;
+            }
+        }
+    } else {
+        i = 0;
+    }
+    for (; i < fstab->num_entries; i++) {
+        int len = strlen(fstab->recs[i].mount_point);
+        if (strncmp(path, fstab->recs[i].mount_point, len) == 0 &&
+            (path[len] == '\0' || path[len] == '/')) {
+            return &fstab->recs[i];
+        }
+    }
+    return NULL;
+}
+
+/*
+ * Returns the 1st matching mount point.
+ * There might be more. To look for others, use fs_mgr_get_entry_for_mount_point_after()
+ * and give the fstab_rec from the previous search.
+ */
+struct fstab_rec *fs_mgr_get_entry_for_mount_point(struct fstab *fstab, const char *path)
+{
+    return fs_mgr_get_entry_for_mount_point_after(NULL, fstab, path);
+}
+
+int fs_mgr_is_voldmanaged(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_VOLDMANAGED;
+}
+
+int fs_mgr_is_nonremovable(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_NONREMOVABLE;
+}
+
+int fs_mgr_is_verified(const struct fstab_rec *fstab)
+{
+    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;
+}
+
+int fs_mgr_is_encryptable(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & (MF_CRYPT | MF_FORCECRYPT | MF_FORCEFDEORFBE);
+}
+
+int fs_mgr_is_file_encrypted(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_FILEENCRYPTION;
+}
+
+void fs_mgr_get_file_encryption_modes(const struct fstab_rec *fstab,
+                                      const char **contents_mode_ret,
+                                      const char **filenames_mode_ret)
+{
+    *contents_mode_ret = flag_to_encryption_mode(file_contents_encryption_modes,
+                                                 fstab->file_contents_mode);
+    *filenames_mode_ret = flag_to_encryption_mode(file_names_encryption_modes,
+                                                  fstab->file_names_mode);
+}
+
+int fs_mgr_is_convertible_to_fbe(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_FORCEFDEORFBE;
+}
+
+int fs_mgr_is_noemulatedsd(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_NOEMULATEDSD;
+}
+
+int fs_mgr_is_notrim(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_NOTRIM;
+}
+
+int fs_mgr_is_formattable(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & (MF_FORMATTABLE);
+}
+
+int fs_mgr_is_slotselect(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_SLOTSELECT;
+}
+
+int fs_mgr_is_nofail(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_NOFAIL;
+}
+
+int fs_mgr_is_latemount(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_LATEMOUNT;
+}
+
+int fs_mgr_is_quota(struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_QUOTA;
+}
diff --git a/fs_mgr/fs_mgr_main.c b/fs_mgr/fs_mgr_main.c
deleted file mode 100644
index 776c13e..0000000
--- a/fs_mgr/fs_mgr_main.c
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <libgen.h>
-#include "fs_mgr_priv.h"
-
-char *me = "";
-
-static void usage(void)
-{
-    ERROR("%s: usage: %s <-a | -n mnt_point blk_dev | -u> <fstab_file>\n", me, me);
-    exit(1);
-}
-
-/* Parse the command line.  If an error is encountered, print an error message
- * and exit the program, do not return to the caller.
- * Return the number of argv[] entries consumed.
- */
-static void parse_options(int argc, char *argv[], int *a_flag, int *u_flag, int *n_flag,
-                     char **n_name, char **n_blk_dev)
-{
-    me = basename(strdup(argv[0]));
-
-    if (argc <= 1) {
-        usage();
-    }
-
-    if (!strcmp(argv[1], "-a")) {
-        if (argc != 3) {
-            usage();
-        }
-        *a_flag = 1;
-    }
-    if (!strcmp(argv[1], "-n")) {
-        if (argc != 5) {
-            usage();
-        }
-        *n_flag = 1;
-        *n_name = argv[2];
-        *n_blk_dev = argv[3];
-    }
-    if (!strcmp(argv[1], "-u")) {
-        if (argc != 3) {
-            usage();
-        }
-        *u_flag = 1;
-    }
-
-    /* If no flag is specified, it's an error */
-    if (!(*a_flag | *n_flag | *u_flag)) {
-        usage();
-    }
-
-    /* If more than one flag is specified, it's an error */
-    if ((*a_flag + *n_flag + *u_flag) > 1) {
-        usage();
-    }
-
-    return;
-}
-
-int main(int argc, char *argv[])
-{
-    int a_flag=0;
-    int u_flag=0;
-    int n_flag=0;
-    char *n_name=NULL;
-    char *n_blk_dev=NULL;
-    char *fstab_file=NULL;
-    struct fstab *fstab=NULL;
-
-    klog_init();
-    klog_set_level(6);
-
-    parse_options(argc, argv, &a_flag, &u_flag, &n_flag, &n_name, &n_blk_dev);
-
-    /* The name of the fstab file is last, after the option */
-    fstab_file = argv[argc - 1];
-
-    fstab = fs_mgr_read_fstab(fstab_file);
-
-    if (a_flag) {
-        return fs_mgr_mount_all(fstab, MOUNT_MODE_DEFAULT);
-    } else if (n_flag) {
-        return fs_mgr_do_mount(fstab, n_name, n_blk_dev, 0);
-    } else if (u_flag) {
-        return fs_mgr_unmount_all(fstab);
-    } else {
-        ERROR("%s: Internal error, unknown option\n", me);
-        exit(1);
-    }
-
-    fs_mgr_free_fstab(fstab);
-
-    /* Should not get here */
-    exit(1);
-}
-
diff --git a/fs_mgr/fs_mgr_main.cpp b/fs_mgr/fs_mgr_main.cpp
new file mode 100644
index 0000000..f3919d9
--- /dev/null
+++ b/fs_mgr/fs_mgr_main.cpp
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "fs_mgr_priv.h"
+
+#ifdef _LIBGEN_H
+#warning "libgen.h must not be included"
+#endif
+
+char *me = nullptr;
+
+static void usage(void)
+{
+    LERROR << me << ": usage: " << me
+           << " <-a | -n mnt_point blk_dev | -u> <fstab_file>";
+    exit(1);
+}
+
+/* Parse the command line.  If an error is encountered, print an error message
+ * and exit the program, do not return to the caller.
+ * Return the number of argv[] entries consumed.
+ */
+static void parse_options(int argc, char * const argv[], int *a_flag, int *u_flag, int *n_flag,
+                     const char **n_name, const char **n_blk_dev)
+{
+    me = basename(argv[0]);
+
+    if (argc <= 1) {
+        usage();
+    }
+
+    if (!strcmp(argv[1], "-a")) {
+        if (argc != 3) {
+            usage();
+        }
+        *a_flag = 1;
+    }
+    if (!strcmp(argv[1], "-n")) {
+        if (argc != 5) {
+            usage();
+        }
+        *n_flag = 1;
+        *n_name = argv[2];
+        *n_blk_dev = argv[3];
+    }
+    if (!strcmp(argv[1], "-u")) {
+        if (argc != 3) {
+            usage();
+        }
+        *u_flag = 1;
+    }
+
+    /* If no flag is specified, it's an error */
+    if (!(*a_flag | *n_flag | *u_flag)) {
+        usage();
+    }
+
+    /* If more than one flag is specified, it's an error */
+    if ((*a_flag + *n_flag + *u_flag) > 1) {
+        usage();
+    }
+
+    return;
+}
+
+int main(int argc, char * const argv[])
+{
+    int a_flag=0;
+    int u_flag=0;
+    int n_flag=0;
+    const char *n_name=NULL;
+    const char *n_blk_dev=NULL;
+    const char *fstab_file=NULL;
+    struct fstab *fstab=NULL;
+
+    setenv("ANDROID_LOG_TAGS", "*:i", 1); // Set log level to INFO
+    android::base::InitLogging(
+        const_cast<char **>(argv), &android::base::KernelLogger);
+
+    parse_options(argc, argv, &a_flag, &u_flag, &n_flag, &n_name, &n_blk_dev);
+
+    /* The name of the fstab file is last, after the option */
+    fstab_file = argv[argc - 1];
+
+    fstab = fs_mgr_read_fstab(fstab_file);
+
+    if (a_flag) {
+        return fs_mgr_mount_all(fstab, MOUNT_MODE_DEFAULT);
+    } else if (n_flag) {
+        return fs_mgr_do_mount(fstab, n_name, (char *)n_blk_dev, 0);
+    } else if (u_flag) {
+        return fs_mgr_unmount_all(fstab);
+    } else {
+        LERROR << me << ": Internal error, unknown option";
+        exit(1);
+    }
+
+    fs_mgr_free_fstab(fstab);
+
+    /* Should not get here */
+    exit(1);
+}
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
index 120ec5a..c985462 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -17,14 +17,29 @@
 #ifndef __CORE_FS_MGR_PRIV_H
 #define __CORE_FS_MGR_PRIV_H
 
-#include <cutils/klog.h>
+#include <android-base/logging.h>
 #include <fs_mgr.h>
+#include "fs_mgr_priv_boot_config.h"
 
-__BEGIN_DECLS
+/* The CHECK() in logging.h will use program invocation name as the tag.
+ * Thus, the log will have prefix "init: " when libfs_mgr is statically
+ * linked in the init process. This might be opaque when debugging.
+ * Appends "in libfs_mgr" at the end of the abort message to explicitly
+ * indicate the check happens in fs_mgr.
+ */
+#define FS_MGR_CHECK(x) CHECK(x) << "in libfs_mgr "
 
-#define INFO(x...)    KLOG_INFO("fs_mgr", x)
-#define WARNING(x...) KLOG_WARNING("fs_mgr", x)
-#define ERROR(x...)   KLOG_ERROR("fs_mgr", x)
+#define FS_MGR_TAG "[libfs_mgr]"
+
+// Logs a message to kernel
+#define LINFO    LOG(INFO) << FS_MGR_TAG
+#define LWARNING LOG(WARNING) << FS_MGR_TAG
+#define LERROR   LOG(ERROR) << FS_MGR_TAG
+
+// Logs a message with strerror(errno) at the end
+#define PINFO    PLOG(INFO) << FS_MGR_TAG
+#define PWARNING PLOG(WARNING) << FS_MGR_TAG
+#define PERROR   PLOG(ERROR) << FS_MGR_TAG
 
 #define CRYPTO_TMPFS_OPTIONS "size=256m,mode=0771,uid=1000,gid=1000"
 
@@ -65,33 +80,41 @@
  *
  */
 
-#define MF_WAIT         0x1
-#define MF_CHECK        0x2
-#define MF_CRYPT        0x4
-#define MF_NONREMOVABLE 0x8
-#define MF_VOLDMANAGED  0x10
-#define MF_LENGTH       0x20
-#define MF_RECOVERYONLY 0x40
-#define MF_SWAPPRIO     0x80
-#define MF_ZRAMSIZE     0x100
-#define MF_VERIFY       0x200
-#define MF_FORCECRYPT   0x400
-#define MF_NOEMULATEDSD 0x800 /* no emulated sdcard daemon, sd card is the only
-                                 external storage */
-#define MF_NOTRIM       0x1000
-#define MF_FILEENCRYPTION 0x2000
-#define MF_FORMATTABLE  0x4000
-#define MF_SLOTSELECT   0x8000
-#define MF_FORCEFDEORFBE 0x10000
-#define MF_LATEMOUNT    0x20000
-#define MF_NOFAIL       0x40000
-#define MF_VERIFYATBOOT 0x80000
+#define MF_WAIT                  0x1
+#define MF_CHECK                 0x2
+#define MF_CRYPT                 0x4
+#define MF_NONREMOVABLE          0x8
+#define MF_VOLDMANAGED          0x10
+#define MF_LENGTH               0x20
+#define MF_RECOVERYONLY         0x40
+#define MF_SWAPPRIO             0x80
+#define MF_ZRAMSIZE            0x100
+#define MF_VERIFY              0x200
+#define MF_FORCECRYPT          0x400
+#define MF_NOEMULATEDSD        0x800 /* no emulated sdcard daemon, sd card is the only
+                                        external storage */
+#define MF_NOTRIM             0x1000
+#define MF_FILEENCRYPTION     0x2000
+#define MF_FORMATTABLE        0x4000
+#define MF_SLOTSELECT         0x8000
+#define MF_FORCEFDEORFBE     0x10000
+#define MF_LATEMOUNT         0x20000
+#define MF_NOFAIL            0x40000
+#define MF_VERIFYATBOOT      0x80000
+#define MF_MAX_COMP_STREAMS 0x100000
+#define MF_RESERVEDSIZE     0x200000
+#define MF_QUOTA            0x400000
+#define MF_ERASEBLKSIZE     0x800000
+#define MF_LOGICALBLKSIZE  0X1000000
+#define MF_AVB             0X2000000
 
 #define DM_BUF_SIZE 4096
 
 int fs_mgr_set_blk_ro(const char *blockdev);
-int fs_mgr_update_for_slotselect(struct fstab *fstab);
-
-__END_DECLS
+int fs_mgr_test_access(const char *device);
+bool fs_mgr_update_for_slotselect(struct fstab *fstab);
+bool is_dt_compatible();
+bool is_device_secure();
+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_ops.h b/fs_mgr/fs_mgr_priv_avb_ops.h
new file mode 100644
index 0000000..a6b52e4
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_avb_ops.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use, copy,
+ * modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef __CORE_FS_MGR_PRIV_AVB_OPS_H
+#define __CORE_FS_MGR_PRIV_AVB_OPS_H
+
+#include <map>
+#include <string>
+
+#include <libavb/libavb.h>
+
+#include "fs_mgr.h"
+
+// 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 fstab& fstab);
+    FsManagerAvbOps(std::map<std::string, std::string>&& by_name_symlink_map);
+
+    static FsManagerAvbOps* GetInstanceFromAvbOps(AvbOps* ops) {
+        return reinterpret_cast<FsManagerAvbOps*>(ops->user_data);
+    }
+
+    AvbIOResult ReadFromPartition(const char* partition, int64_t offset, size_t num_bytes,
+                                  void* buffer, size_t* out_num_read);
+
+    AvbSlotVerifyResult AvbSlotVerify(const std::string& ab_suffix, bool allow_verification_error,
+                                      AvbSlotVerifyData** out_data);
+
+  private:
+    void InitializeAvbOps();
+
+    AvbOps avb_ops_;
+    std::map<std::string, std::string> by_name_symlink_map_;
+};
+#endif /* __CORE_FS_MGR_PRIV_AVB_OPS_H */
diff --git a/fs_mgr/fs_mgr_priv_boot_config.h b/fs_mgr/fs_mgr_priv_boot_config.h
new file mode 100644
index 0000000..8773d33
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_boot_config.h
@@ -0,0 +1,27 @@
+/*
+ * 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_PRIV_BOOTCONFIG_H
+#define __CORE_FS_MGR_PRIV_BOOTCONFIG_H
+
+#include <sys/cdefs.h>
+#include <string>
+
+const std::string kAndroidDtDir("/proc/device-tree/firmware/android");
+
+bool fs_mgr_get_boot_config(const std::string& key, std::string* out_val);
+
+#endif /* __CORE_FS_MGR_PRIV_BOOTCONFIG_H */
diff --git a/fs_mgr/fs_mgr_priv_dm_ioctl.h b/fs_mgr/fs_mgr_priv_dm_ioctl.h
new file mode 100644
index 0000000..a00a9c1
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_dm_ioctl.h
@@ -0,0 +1,34 @@
+/*
+ * 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_DM_IOCTL_H
+#define __CORE_FS_MGR_PRIV_DM_IOCTL_H
+
+#include <linux/dm-ioctl.h>
+#include <string>
+
+void fs_mgr_verity_ioctl_init(struct dm_ioctl* io, const std::string& name, unsigned flags);
+
+bool fs_mgr_create_verity_device(struct dm_ioctl* io, const std::string& name, int fd);
+
+bool fs_mgr_destroy_verity_device(struct dm_ioctl* io, const std::string& name, int fd);
+
+bool fs_mgr_get_verity_device_name(struct dm_ioctl* io, const std::string& name, int fd,
+                                   std::string* out_dev_name);
+
+bool fs_mgr_resume_verity_table(struct dm_ioctl* io, const std::string& name, int fd);
+
+#endif /* __CORE_FS_MGR_PRIV_DM_IOCTL_H */
diff --git a/fs_mgr/fs_mgr_priv_sha.h b/fs_mgr/fs_mgr_priv_sha.h
new file mode 100644
index 0000000..5b53eea
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_sha.h
@@ -0,0 +1,62 @@
+/*
+ * 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_SHA_H
+#define __CORE_FS_MGR_PRIV_SHA_H
+
+#include <openssl/sha.h>
+
+class SHA256Hasher {
+  private:
+    SHA256_CTX sha256_ctx;
+    uint8_t hash[SHA256_DIGEST_LENGTH];
+
+  public:
+    enum { DIGEST_SIZE = SHA256_DIGEST_LENGTH };
+
+    SHA256Hasher() { SHA256_Init(&sha256_ctx); }
+
+    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);
+        return hash;
+    }
+};
+
+class SHA512Hasher {
+  private:
+    SHA512_CTX sha512_ctx;
+    uint8_t hash[SHA512_DIGEST_LENGTH];
+
+  public:
+    enum { DIGEST_SIZE = SHA512_DIGEST_LENGTH };
+
+    SHA512Hasher() { SHA512_Init(&sha512_ctx); }
+
+    void update(const uint8_t* data, size_t data_size) {
+        SHA512_Update(&sha512_ctx, data, data_size);
+    }
+
+    const uint8_t* finalize() {
+        SHA512_Final(hash, &sha512_ctx);
+        return hash;
+    }
+};
+
+#endif /* __CORE_FS_MGR_PRIV_SHA_H */
diff --git a/fs_mgr/fs_mgr_priv_verity.h b/fs_mgr/fs_mgr_priv_verity.h
deleted file mode 100644
index cd673f3..0000000
--- a/fs_mgr/fs_mgr_priv_verity.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <sys/cdefs.h>
-
-#define FS_MGR_SETUP_VERITY_DISABLED -2
-#define FS_MGR_SETUP_VERITY_FAIL -1
-#define FS_MGR_SETUP_VERITY_SUCCESS 0
-
-__BEGIN_DECLS
-
-int fs_mgr_setup_verity(struct fstab_rec *fstab);
-
-__END_DECLS
diff --git a/fs_mgr/fs_mgr_slotselect.c b/fs_mgr/fs_mgr_slotselect.c
deleted file mode 100644
index ca07b18..0000000
--- a/fs_mgr/fs_mgr_slotselect.c
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <ctype.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <cutils/properties.h>
-
-#include "fs_mgr.h"
-#include "fs_mgr_priv.h"
-
-#include "bootloader.h"
-
-// Copies slot_suffix from misc into |out_suffix|. Returns 0 on
-// success, -1 on error or if there is no non-empty slot_suffix.
-static int get_active_slot_suffix_from_misc(struct fstab *fstab,
-                                            char *out_suffix,
-                                            size_t suffix_len)
-{
-    int n;
-    int misc_fd;
-    ssize_t num_read;
-    struct bootloader_message msg;
-
-    misc_fd = -1;
-    for (n = 0; n < fstab->num_entries; n++) {
-        if (strcmp(fstab->recs[n].mount_point, "/misc") == 0) {
-            misc_fd = open(fstab->recs[n].blk_device, O_RDONLY);
-            if (misc_fd == -1) {
-                ERROR("Error opening misc partition \"%s\" (%s)\n",
-                      fstab->recs[n].blk_device,
-                      strerror(errno));
-                return -1;
-            } else {
-                break;
-            }
-        }
-    }
-
-    if (misc_fd == -1) {
-        ERROR("Error finding misc partition\n");
-        return -1;
-    }
-
-    num_read = TEMP_FAILURE_RETRY(read(misc_fd, &msg, sizeof(msg)));
-    // Linux will never return partial reads when reading from block
-    // devices so no need to worry about them.
-    if (num_read != sizeof(msg)) {
-        ERROR("Error reading bootloader_message (%s)\n", strerror(errno));
-        close(misc_fd);
-        return -1;
-    }
-    close(misc_fd);
-    if (msg.slot_suffix[0] == '\0')
-        return -1;
-    strncpy(out_suffix, msg.slot_suffix, suffix_len);
-    return 0;
-}
-
-// Gets slot_suffix from either the kernel cmdline / firmware or the
-// misc partition. Sets |out_suffix| on success and returns 0. Returns
-// -1 if slot_suffix could not be determined.
-static int get_active_slot_suffix(struct fstab *fstab, char *out_suffix,
-                                  size_t suffix_len)
-{
-    char propbuf[PROPERTY_VALUE_MAX];
-
-    // Get the suffix from the kernel commandline (note that we don't
-    // allow the empty suffix). On bootloaders natively supporting A/B
-    // we'll hit this path every time so don't bother logging it.
-    property_get("ro.boot.slot_suffix", propbuf, "");
-    if (propbuf[0] != '\0') {
-        strncpy(out_suffix, propbuf, suffix_len);
-        return 0;
-    }
-
-    // If we couldn't get the suffix from the kernel cmdline, try the
-    // the misc partition.
-    if (get_active_slot_suffix_from_misc(fstab, out_suffix, suffix_len) == 0) {
-        INFO("Using slot suffix \"%s\" from misc\n", out_suffix);
-        return 0;
-    }
-
-    ERROR("Error determining slot_suffix\n");
-
-    return -1;
-}
-
-// Updates |fstab| for slot_suffix. Returns 0 on success, -1 on error.
-int fs_mgr_update_for_slotselect(struct fstab *fstab)
-{
-    int n;
-    char suffix[PROPERTY_VALUE_MAX];
-    int got_suffix = 0;
-
-    for (n = 0; n < fstab->num_entries; n++) {
-        if (fstab->recs[n].fs_mgr_flags & MF_SLOTSELECT) {
-            char *tmp;
-
-            if (!got_suffix) {
-                memset(suffix, '\0', sizeof(suffix));
-                if (get_active_slot_suffix(fstab, suffix,
-                                           sizeof(suffix) - 1) != 0) {
-                  return -1;
-                }
-                got_suffix = 1;
-            }
-
-            if (asprintf(&tmp, "%s%s", fstab->recs[n].blk_device,
-                         suffix) > 0) {
-                free(fstab->recs[n].blk_device);
-                fstab->recs[n].blk_device = tmp;
-            } else {
-                return -1;
-            }
-        }
-    }
-    return 0;
-}
diff --git a/fs_mgr/fs_mgr_slotselect.cpp b/fs_mgr/fs_mgr_slotselect.cpp
new file mode 100644
index 0000000..9ca15e2
--- /dev/null
+++ b/fs_mgr/fs_mgr_slotselect.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+
+#include <string>
+
+#include "fs_mgr.h"
+#include "fs_mgr_priv.h"
+
+// 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;
+    std::string ab_suffix;
+
+    for (n = 0; n < fstab->num_entries; n++) {
+        if (fstab->recs[n].fs_mgr_flags & MF_SLOTSELECT) {
+            char *tmp;
+            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, ab_suffix.c_str()) > 0) {
+                free(fstab->recs[n].blk_device);
+                fstab->recs[n].blk_device = tmp;
+            } else {
+                return false;
+            }
+        }
+    }
+    return true;
+}
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index aa00520..5fa10bc 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -14,38 +14,37 @@
  * limitations under the License.
  */
 
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
 #include <inttypes.h>
+#include <libgen.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <ctype.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
-#include <errno.h>
 #include <sys/types.h>
 #include <sys/wait.h>
-#include <libgen.h>
 #include <time.h>
+#include <unistd.h>
 
 #include <android-base/file.h>
+#include <android-base/properties.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
+#include <crypto_utils/android_pubkey.h>
 #include <cutils/properties.h>
 #include <logwrap/logwrap.h>
-
-#include "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-#include "mincrypt/sha256.h"
+#include <openssl/obj_mac.h>
+#include <openssl/rsa.h>
+#include <openssl/sha.h>
 
 #include "fec/io.h"
 
 #include "fs_mgr.h"
 #include "fs_mgr_priv.h"
-#include "fs_mgr_priv_verity.h"
-
-#define FSTAB_PREFIX "/fstab."
+#include "fs_mgr_priv_dm_ioctl.h"
 
 #define VERITY_TABLE_RSA_KEY "/verity_key"
 #define VERITY_TABLE_HASH_IDX 8
@@ -86,79 +85,70 @@
 
 extern struct fs_info info;
 
-static RSAPublicKey *load_key(const char *path)
+static RSA *load_key(const char *path)
 {
-    RSAPublicKey* key = static_cast<RSAPublicKey*>(malloc(sizeof(RSAPublicKey)));
-    if (!key) {
-        ERROR("Can't malloc key\n");
-        return NULL;
-    }
+    uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
 
     FILE* f = fopen(path, "r");
     if (!f) {
-        ERROR("Can't open '%s'\n", path);
-        free(key);
+        LERROR << "Can't open " << path;
         return NULL;
     }
 
-    if (!fread(key, sizeof(*key), 1, f)) {
-        ERROR("Could not read key!\n");
+    if (!fread(key_data, sizeof(key_data), 1, f)) {
+        LERROR << "Could not read key!";
         fclose(f);
-        free(key);
-        return NULL;
-    }
-
-    if (key->len != RSANUMWORDS) {
-        ERROR("Invalid key length %d\n", key->len);
-        fclose(f);
-        free(key);
         return NULL;
     }
 
     fclose(f);
+
+    RSA* key = NULL;
+    if (!android_pubkey_decode(key_data, sizeof(key_data), &key)) {
+        LERROR << "Could not parse key!";
+        return NULL;
+    }
+
     return key;
 }
 
-static int verify_table(const uint8_t *signature, const char *table,
-        uint32_t table_length)
+static int verify_table(const uint8_t *signature, size_t signature_size,
+        const char *table, uint32_t table_length)
 {
-    RSAPublicKey *key;
-    uint8_t hash_buf[SHA256_DIGEST_SIZE];
+    RSA *key;
+    uint8_t hash_buf[SHA256_DIGEST_LENGTH];
     int retval = -1;
 
     // Hash the table
-    SHA256_hash((uint8_t*)table, table_length, hash_buf);
+    SHA256((uint8_t*)table, table_length, hash_buf);
 
     // Now get the public key from the keyfile
     key = load_key(VERITY_TABLE_RSA_KEY);
     if (!key) {
-        ERROR("Couldn't load verity keys\n");
+        LERROR << "Couldn't load verity keys";
         goto out;
     }
 
     // verify the result
-    if (!RSA_verify(key,
-                    signature,
-                    RSANUMBYTES,
-                    (uint8_t*) hash_buf,
-                    SHA256_DIGEST_SIZE)) {
-        ERROR("Couldn't verify table\n");
+    if (!RSA_verify(NID_sha256, hash_buf, sizeof(hash_buf), signature,
+                    signature_size, key)) {
+        LERROR << "Couldn't verify table";
         goto out;
     }
 
     retval = 0;
 
 out:
-    free(key);
+    RSA_free(key);
     return retval;
 }
 
 static int verify_verity_signature(const struct fec_verity_metadata& verity)
 {
-    if (verify_table(verity.signature, verity.table,
-            verity.table_length) == 0 ||
-        verify_table(verity.ecc_signature, verity.table,
-            verity.table_length) == 0) {
+    if (verify_table(verity.signature, sizeof(verity.signature),
+            verity.table, verity.table_length) == 0 ||
+        verify_table(verity.ecc_signature, sizeof(verity.ecc_signature),
+            verity.table, verity.table_length) == 0) {
         return 0;
     }
 
@@ -192,55 +182,6 @@
     return -1;
 }
 
-static void verity_ioctl_init(struct dm_ioctl *io, const char *name, unsigned flags)
-{
-    memset(io, 0, DM_BUF_SIZE);
-    io->data_size = DM_BUF_SIZE;
-    io->data_start = sizeof(struct dm_ioctl);
-    io->version[0] = 4;
-    io->version[1] = 0;
-    io->version[2] = 0;
-    io->flags = flags | DM_READONLY_FLAG;
-    if (name) {
-        strlcpy(io->name, name, sizeof(io->name));
-    }
-}
-
-static int create_verity_device(struct dm_ioctl *io, char *name, int fd)
-{
-    verity_ioctl_init(io, name, 1);
-    if (ioctl(fd, DM_DEV_CREATE, io)) {
-        ERROR("Error creating device mapping (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-static int destroy_verity_device(struct dm_ioctl *io, char *name, int fd)
-{
-    verity_ioctl_init(io, name, 0);
-    if (ioctl(fd, DM_DEV_REMOVE, io)) {
-        ERROR("Error removing device mapping (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-static int get_verity_device_name(struct dm_ioctl *io, char *name, int fd, char **dev_name)
-{
-    verity_ioctl_init(io, name, 0);
-    if (ioctl(fd, DM_DEV_STATUS, io)) {
-        ERROR("Error fetching verity device number (%s)", strerror(errno));
-        return -1;
-    }
-    int dev_num = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
-    if (asprintf(dev_name, "/dev/block/dm-%u", dev_num) < 0) {
-        ERROR("Error getting verity block device name (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
 struct verity_table_params {
     char *table;
     int mode;
@@ -283,7 +224,7 @@
     }
 
     if (res < 0 || (size_t)res >= bufsize) {
-        ERROR("Error building verity table; insufficient buffer size?\n");
+        LERROR << "Error building verity table; insufficient buffer size?";
         return false;
     }
 
@@ -302,21 +243,22 @@
     }
 
     if (res < 0 || (size_t)res >= bufsize) {
-        ERROR("Error building verity table; insufficient buffer size?\n");
+        LERROR << "Error building verity table; insufficient buffer size?";
         return false;
     }
 
     return true;
 }
 
-static int load_verity_table(struct dm_ioctl *io, char *name, uint64_t device_size, int fd,
+static int load_verity_table(struct dm_ioctl *io, const std::string &name,
+                             uint64_t device_size, int fd,
         const struct verity_table_params *params, format_verity_table_func format)
 {
     char *verity_params;
     char *buffer = (char*) io;
     size_t bufsize;
 
-    verity_ioctl_init(io, name, DM_STATUS_TABLE_FLAG);
+    fs_mgr_verity_ioctl_init(io, name, DM_STATUS_TABLE_FLAG);
 
     struct dm_target_spec *tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
 
@@ -332,47 +274,26 @@
     bufsize = DM_BUF_SIZE - (verity_params - buffer);
 
     if (!format(verity_params, bufsize, params)) {
-        ERROR("Failed to format verity parameters\n");
+        LERROR << "Failed to format verity parameters";
         return -1;
     }
 
-    INFO("loading verity table: '%s'", verity_params);
+    LINFO << "loading verity table: '" << verity_params << "'";
 
     // set next target boundary
     verity_params += strlen(verity_params) + 1;
-    verity_params = (char*)(((unsigned long)verity_params + 7) & ~8);
+    verity_params = (char*)(((uintptr_t)verity_params + 7) & ~7);
     tgt->next = verity_params - buffer;
 
     // send the ioctl to load the verity table
     if (ioctl(fd, DM_TABLE_LOAD, io)) {
-        ERROR("Error loading verity table (%s)\n", strerror(errno));
+        PERROR << "Error loading verity table";
         return -1;
     }
 
     return 0;
 }
 
-static int resume_verity_table(struct dm_ioctl *io, char *name, int fd)
-{
-    verity_ioctl_init(io, name, 0);
-    if (ioctl(fd, DM_DEV_SUSPEND, io)) {
-        ERROR("Error activating verity device (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-static int test_access(char *device) {
-    int tries = 25;
-    while (tries--) {
-        if (!access(device, F_OK) || errno != ENOENT) {
-            return 0;
-        }
-        usleep(40 * 1000);
-    }
-    return -1;
-}
-
 static int check_verity_restart(const char *fname)
 {
     char buffer[VERITY_KMSG_BUFSIZE + 1];
@@ -385,13 +306,13 @@
 
     if (fd == -1) {
         if (errno != ENOENT) {
-            ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
+            PERROR << "Failed to open " << fname;
         }
         goto out;
     }
 
     if (fstat(fd, &s) == -1) {
-        ERROR("Failed to fstat %s (%s)\n", fname, strerror(errno));
+        PERROR << "Failed to fstat " << fname;
         goto out;
     }
 
@@ -402,14 +323,12 @@
     }
 
     if (lseek(fd, s.st_size - size, SEEK_SET) == -1) {
-        ERROR("Failed to lseek %jd %s (%s)\n", (intmax_t)(s.st_size - size), fname,
-            strerror(errno));
+        PERROR << "Failed to lseek " << (intmax_t)(s.st_size - size) << " " << fname;
         goto out;
     }
 
     if (!android::base::ReadFully(fd, buffer, size)) {
-        ERROR("Failed to read %zd bytes from %s (%s)\n", size, fname,
-            strerror(errno));
+        PERROR << "Failed to read " << size << " bytes from " << fname;
         goto out;
     }
 
@@ -481,14 +400,14 @@
     fp = fopen(fname, "r+");
 
     if (!fp) {
-        ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
+        PERROR << "Failed to open " << fname;
         goto out;
     }
 
     /* check magic */
     if (fseek(fp, start, SEEK_SET) < 0 ||
         fread(&magic, sizeof(magic), 1, fp) != 1) {
-        ERROR("Failed to read magic from %s (%s)\n", fname, strerror(errno));
+        PERROR << "Failed to read magic from " << fname;
         goto out;
     }
 
@@ -497,13 +416,13 @@
 
         if (fseek(fp, start, SEEK_SET) < 0 ||
             fwrite(&magic, sizeof(magic), 1, fp) != 1) {
-            ERROR("Failed to write magic to %s (%s)\n", fname, strerror(errno));
+            PERROR << "Failed to write magic to " << fname;
             goto out;
         }
 
         rc = metadata_add(fp, start + sizeof(magic), stag, slength, offset);
         if (rc < 0) {
-            ERROR("Failed to add metadata to %s: %s\n", fname, strerror(errno));
+            PERROR << "Failed to add metadata to " << fname;
         }
 
         goto out;
@@ -528,14 +447,13 @@
             start += length;
 
             if (fseek(fp, length, SEEK_CUR) < 0) {
-                ERROR("Failed to seek %s (%s)\n", fname, strerror(errno));
+                PERROR << "Failed to seek " << fname;
                 goto out;
             }
         } else {
             rc = metadata_add(fp, start, stag, slength, offset);
             if (rc < 0) {
-                ERROR("Failed to write metadata to %s: %s\n", fname,
-                    strerror(errno));
+                PERROR << "Failed to write metadata to " << fname;
             }
             goto out;
         }
@@ -559,13 +477,13 @@
     fd = TEMP_FAILURE_RETRY(open(fname, O_WRONLY | O_SYNC | O_CLOEXEC));
 
     if (fd == -1) {
-        ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
+        PERROR << "Failed to open " << fname;
         goto out;
     }
 
     if (TEMP_FAILURE_RETRY(pwrite64(fd, &s, sizeof(s), offset)) != sizeof(s)) {
-        ERROR("Failed to write %zu bytes to %s to offset %" PRIu64 " (%s)\n",
-            sizeof(s), fname, offset, strerror(errno));
+        PERROR << "Failed to write " << sizeof(s) << " bytes to " << fname
+               << " to offset " << offset;
         goto out;
     }
 
@@ -588,13 +506,13 @@
     fd = TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_CLOEXEC));
 
     if (fd == -1) {
-        ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
+        PERROR << "Failed to open " << fname;
         goto out;
     }
 
     if (TEMP_FAILURE_RETRY(pread64(fd, &s, sizeof(s), offset)) != sizeof(s)) {
-        ERROR("Failed to read %zu bytes from %s offset %" PRIu64 " (%s)\n",
-            sizeof(s), fname, offset, strerror(errno));
+        PERROR << "Failed to read " <<  sizeof(s) << " bytes from " << fname
+               << " offset " << offset;
         goto out;
     }
 
@@ -606,13 +524,13 @@
     }
 
     if (s.version != VERITY_STATE_VERSION) {
-        ERROR("Unsupported verity state version (%u)\n", s.version);
+        LERROR << "Unsupported verity state version (" << s.version << ")";
         goto out;
     }
 
     if (s.mode < VERITY_MODE_EIO ||
         s.mode > VERITY_MODE_LAST) {
-        ERROR("Unsupported verity mode (%u)\n", s.mode);
+        LERROR << "Unsupported verity mode (" << s.mode << ")";
         goto out;
     }
 
@@ -634,15 +552,14 @@
     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC)));
 
     if (fd == -1) {
-        ERROR("Failed to open %s: %s\n", path, strerror(errno));
+        PERROR << "Failed to open " << path;
         return -errno;
     }
 
     while (size) {
         size_read = TEMP_FAILURE_RETRY(read(fd, buf, READ_BUF_SIZE));
         if (size_read == -1) {
-            ERROR("Error in reading partition %s: %s\n", path,
-                  strerror(errno));
+            PERROR << "Error in reading partition " << path;
             return -errno;
         }
         size -= size_read;
@@ -659,34 +576,32 @@
     off64_t offset = 0;
     struct fec_handle *f = NULL;
     struct fec_verity_metadata verity;
-    uint8_t curr[SHA256_DIGEST_SIZE];
-    uint8_t prev[SHA256_DIGEST_SIZE];
+    uint8_t curr[SHA256_DIGEST_LENGTH];
+    uint8_t prev[SHA256_DIGEST_LENGTH];
 
     *match = 1;
 
     if (fec_open(&f, fstab->blk_device, O_RDONLY, FEC_VERITY_DISABLE,
             FEC_DEFAULT_ROOTS) == -1) {
-        ERROR("Failed to open '%s' (%s)\n", fstab->blk_device,
-            strerror(errno));
+        PERROR << "Failed to open '" << fstab->blk_device << "'";
         return rc;
     }
 
     // read verity metadata
     if (fec_verity_get_metadata(f, &verity) == -1) {
-        ERROR("Failed to get verity metadata '%s' (%s)\n", fstab->blk_device,
-            strerror(errno));
+        PERROR << "Failed to get verity metadata '" << fstab->blk_device << "'";
         goto out;
     }
 
-    SHA256_hash(verity.signature, RSANUMBYTES, curr);
+    SHA256(verity.signature, sizeof(verity.signature), curr);
 
     if (snprintf(tag, sizeof(tag), VERITY_LASTSIG_TAG "_%s",
             basename(fstab->mount_point)) >= (int)sizeof(tag)) {
-        ERROR("Metadata tag name too long for %s\n", fstab->mount_point);
+        LERROR << "Metadata tag name too long for " << fstab->mount_point;
         goto out;
     }
 
-    if (metadata_find(fstab->verity_loc, tag, SHA256_DIGEST_SIZE,
+    if (metadata_find(fstab->verity_loc, tag, SHA256_DIGEST_LENGTH,
             &offset) < 0) {
         goto out;
     }
@@ -694,25 +609,25 @@
     fd = TEMP_FAILURE_RETRY(open(fstab->verity_loc, O_RDWR | O_SYNC | O_CLOEXEC));
 
     if (fd == -1) {
-        ERROR("Failed to open %s: %s\n", fstab->verity_loc, strerror(errno));
+        PERROR << "Failed to open " << fstab->verity_loc;
         goto out;
     }
 
     if (TEMP_FAILURE_RETRY(pread64(fd, prev, sizeof(prev),
             offset)) != sizeof(prev)) {
-        ERROR("Failed to read %zu bytes from %s offset %" PRIu64 " (%s)\n",
-            sizeof(prev), fstab->verity_loc, offset, strerror(errno));
+        PERROR << "Failed to read " << sizeof(prev) << " bytes from "
+               << fstab->verity_loc << " offset " << offset;
         goto out;
     }
 
-    *match = !memcmp(curr, prev, SHA256_DIGEST_SIZE);
+    *match = !memcmp(curr, prev, SHA256_DIGEST_LENGTH);
 
     if (!*match) {
         /* update current signature hash */
         if (TEMP_FAILURE_RETRY(pwrite64(fd, curr, sizeof(curr),
                 offset)) != sizeof(curr)) {
-            ERROR("Failed to write %zu bytes to %s offset %" PRIu64 " (%s)\n",
-                sizeof(curr), fstab->verity_loc, offset, strerror(errno));
+            PERROR << "Failed to write " << sizeof(curr) << " bytes to "
+                   << fstab->verity_loc << " offset " << offset;
             goto out;
         }
     }
@@ -730,7 +645,7 @@
 
     if (snprintf(tag, sizeof(tag), VERITY_STATE_TAG "_%s",
             basename(fstab->mount_point)) >= (int)sizeof(tag)) {
-        ERROR("Metadata tag name too long for %s\n", fstab->mount_point);
+        LERROR << "Metadata tag name too long for " << fstab->mount_point;
         return -1;
     }
 
@@ -738,9 +653,7 @@
                 offset);
 }
 
-static int load_verity_state(struct fstab_rec *fstab, int *mode)
-{
-    char propbuf[PROPERTY_VALUE_MAX];
+int load_verity_state(struct fstab_rec* fstab, int* mode) {
     int match = 0;
     off64_t offset = 0;
 
@@ -748,10 +661,9 @@
     *mode = VERITY_MODE_EIO;
 
     /* use the kernel parameter if set */
-    property_get("ro.boot.veritymode", propbuf, "");
-
-    if (*propbuf != '\0') {
-        if (!strcmp(propbuf, "enforcing")) {
+    std::string veritymode;
+    if (fs_mgr_get_boot_config("veritymode", &veritymode)) {
+        if (veritymode == "enforcing") {
             *mode = VERITY_MODE_DEFAULT;
         }
         return 0;
@@ -777,148 +689,12 @@
     return read_verity_state(fstab->verity_loc, offset, mode);
 }
 
-int fs_mgr_load_verity_state(int *mode)
-{
-    char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
-    char propbuf[PROPERTY_VALUE_MAX];
-    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;
-
-    property_get("ro.hardware", propbuf, "");
-    snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
-
-    fstab = fs_mgr_read_fstab(fstab_filename);
-
-    if (!fstab) {
-        ERROR("Failed to read %s\n", fstab_filename);
-        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;
-    char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
-    const char *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) {
-        ERROR("Error opening device mapper (%s)\n", strerror(errno));
-        goto out;
-    }
-
-    property_get("ro.hardware", propbuf, "");
-    snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
-
-    property_get("ro.build.system_root_image", propbuf, "");
-    system_root = !strcmp(propbuf, "true");
-
-    fstab = fs_mgr_read_fstab(fstab_filename);
-
-    if (!fstab) {
-        ERROR("Failed to read %s\n", fstab_filename);
-        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);
-        }
-
-        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 {
-                ERROR("Failed to query DM_TABLE_STATUS for %s (%s)\n", mount_point,
-                      strerror(errno));
-                continue;
-            }
-        }
-
-        status = &buffer[io->data_start + sizeof(struct dm_target_spec)];
-
-        if (*status == 'C' || *status == 'V') {
-            callback(&fstab->recs[i], mount_point, 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;
     auto tokens = android::base::Split(*table, " ");
 
-    for (const auto token : tokens) {
+    for (const auto& token : tokens) {
         if (android::base::StartsWith(token, "/dev/block/") &&
             android::base::StartsWith(blk_device, token.c_str())) {
             word = blk_device;
@@ -941,38 +717,51 @@
     *table = strdup(result.c_str());
 }
 
-int fs_mgr_setup_verity(struct fstab_rec *fstab)
+// prepares the verity enabled (MF_VERIFY / MF_VERIFYATBOOT) fstab record for
+// mount. The 'wait_for_verity_dev' parameter makes this function wait for the
+// verity device to get created before return
+int fs_mgr_setup_verity(struct fstab_rec *fstab, bool wait_for_verity_dev)
 {
     int retval = FS_MGR_SETUP_VERITY_FAIL;
     int fd = -1;
-    char *verity_blk_name = NULL;
+    std::string verity_blk_name;
     struct fec_handle *f = NULL;
     struct fec_verity_metadata verity;
     struct verity_table_params params = { .table = NULL };
 
     alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
     struct dm_ioctl *io = (struct dm_ioctl *) buffer;
-    char *mount_point = basename(fstab->mount_point);
+    const std::string mount_point(basename(fstab->mount_point));
     bool verified_at_boot = false;
 
+    // This is a public API and so deserves its own check to see if verity
+    // setup is needed at all.
+    if (!is_device_secure()) {
+        LINFO << "Verity setup skipped for " << mount_point;
+        return FS_MGR_SETUP_VERITY_SUCCESS;
+    }
+
     if (fec_open(&f, fstab->blk_device, O_RDONLY, FEC_VERITY_DISABLE,
             FEC_DEFAULT_ROOTS) < 0) {
-        ERROR("Failed to open '%s' (%s)\n", fstab->blk_device,
-            strerror(errno));
+        PERROR << "Failed to open '" << fstab->blk_device << "'";
         return retval;
     }
 
     // read verity metadata
     if (fec_verity_get_metadata(f, &verity) < 0) {
-        ERROR("Failed to get verity metadata '%s' (%s)\n", fstab->blk_device,
-            strerror(errno));
+        PERROR << "Failed to get verity metadata '" << fstab->blk_device << "'";
+        // Allow verity disabled when the device is unlocked without metadata
+        if ("0" == android::base::GetProperty("ro.boot.flash.locked", "")) {
+            retval = FS_MGR_SETUP_VERITY_DISABLED;
+            LWARNING << "Allow invalid metadata when the device is unlocked";
+        }
         goto out;
     }
 
 #ifdef ALLOW_ADBD_DISABLE_VERITY
     if (verity.disabled) {
         retval = FS_MGR_SETUP_VERITY_DISABLED;
-        INFO("Attempt to cleanly disable verity - only works in USERDEBUG\n");
+        LINFO << "Attempt to cleanly disable verity - only works in USERDEBUG";
         goto out;
     }
 #endif
@@ -986,19 +775,19 @@
 
     // get the device mapper fd
     if ((fd = open("/dev/device-mapper", O_RDWR)) < 0) {
-        ERROR("Error opening device mapper (%s)\n", strerror(errno));
+        PERROR << "Error opening device mapper";
         goto out;
     }
 
     // create the device
-    if (create_verity_device(io, mount_point, fd) < 0) {
-        ERROR("Couldn't create verity device!\n");
+    if (!fs_mgr_create_verity_device(io, mount_point, fd)) {
+        LERROR << "Couldn't create verity device!";
         goto out;
     }
 
     // get the name of the device file
-    if (get_verity_device_name(io, mount_point, fd, &verity_blk_name) < 0) {
-        ERROR("Couldn't get verity device number!\n");
+    if (!fs_mgr_get_verity_device_name(io, mount_point, fd, &verity_blk_name)) {
+        LERROR << "Couldn't get verity device number!";
         goto out;
     }
 
@@ -1033,7 +822,8 @@
         }
     }
 
-    INFO("Enabling dm-verity for %s (mode %d)\n", mount_point, params.mode);
+    LINFO << "Enabling dm-verity for " << mount_point.c_str()
+          << " (mode " << params.mode << ")";
 
     if (fstab->fs_mgr_flags & MF_SLOTSELECT) {
         // Update the verity params using the actual block device path
@@ -1048,7 +838,7 @@
 
     if (params.ecc.valid) {
         // kernel may not support error correction, try without
-        INFO("Disabling error correction for %s\n", mount_point);
+        LINFO << "Disabling error correction for " << mount_point.c_str();
         params.ecc.valid = false;
 
         if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
@@ -1065,7 +855,7 @@
 
     if (params.mode != VERITY_MODE_EIO) {
         // as a last resort, EIO mode should always be supported
-        INFO("Falling back to EIO mode for %s\n", mount_point);
+        LINFO << "Falling back to EIO mode for " << mount_point.c_str();
         params.mode = VERITY_MODE_EIO;
 
         if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
@@ -1074,13 +864,13 @@
         }
     }
 
-    ERROR("Failed to load verity table for %s\n", mount_point);
+    LERROR << "Failed to load verity table for " << mount_point.c_str();
     goto out;
 
 loaded:
 
     // activate the device
-    if (resume_verity_table(io, mount_point, fd) < 0) {
+    if (!fs_mgr_resume_verity_table(io, mount_point, fd)) {
         goto out;
     }
 
@@ -1090,10 +880,11 @@
     // Verify the entire partition in one go
     // If there is an error, allow it to mount as a normal verity partition.
     if (fstab->fs_mgr_flags & MF_VERIFYATBOOT) {
-        INFO("Verifying partition %s at boot\n", fstab->blk_device);
-        int err = read_partition(verity_blk_name, verity.data_size);
+        LINFO << "Verifying partition " << fstab->blk_device << " at boot";
+        int err = read_partition(verity_blk_name.c_str(), verity.data_size);
         if (!err) {
-            INFO("Verified verity partition %s at boot\n", fstab->blk_device);
+            LINFO << "Verified verity partition "
+                  << fstab->blk_device << " at boot";
             verified_at_boot = true;
         }
     }
@@ -1101,15 +892,14 @@
     // assign the new verity block device as the block device
     if (!verified_at_boot) {
         free(fstab->blk_device);
-        fstab->blk_device = verity_blk_name;
-        verity_blk_name = 0;
-    } else if (destroy_verity_device(io, mount_point, fd) < 0) {
-        ERROR("Failed to remove verity device %s\n", mount_point);
+        fstab->blk_device = strdup(verity_blk_name.c_str());
+    } else if (!fs_mgr_destroy_verity_device(io, mount_point, fd)) {
+        LERROR << "Failed to remove verity device " << mount_point.c_str();
         goto out;
     }
 
     // make sure we've set everything up properly
-    if (test_access(fstab->blk_device) < 0) {
+    if (wait_for_verity_dev && fs_mgr_test_access(fstab->blk_device) < 0) {
         goto out;
     }
 
@@ -1122,7 +912,6 @@
 
     fec_close(f);
     free(params.table);
-    free(verity_blk_name);
 
     return retval;
 }
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index 7565965..fd63dfd 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -17,9 +17,17 @@
 #ifndef __CORE_FS_MGR_H
 #define __CORE_FS_MGR_H
 
+#include <stdio.h>
 #include <stdint.h>
+#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
 
@@ -27,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 {
@@ -71,14 +77,21 @@
     char *label;
     int partnum;
     int swap_prio;
+    int max_comp_streams;
     unsigned int zram_size;
-    unsigned int file_encryption_mode;
+    uint64_t reserved_size;
+    unsigned int file_contents_mode;
+    unsigned int file_names_mode;
+    unsigned int erase_blk_size;
+    unsigned int logical_blk_size;
 };
 
 // Callback function for verity status
 typedef void (*fs_mgr_verity_state_callback)(struct fstab_rec *fstab,
         const char *mount_point, int mode, int status);
 
+struct fstab *fs_mgr_read_fstab_default();
+struct fstab *fs_mgr_read_fstab_dt();
 struct fstab *fs_mgr_read_fstab(const char *fstab_path);
 void fs_mgr_free_fstab(struct fstab *fstab);
 
@@ -88,20 +101,21 @@
 #define FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED 2
 #define FS_MGR_MNTALL_DEV_NOT_ENCRYPTED 1
 #define FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE 0
-#define FS_MGR_MNTALL_FAIL -1
+#define FS_MGR_MNTALL_FAIL (-1)
 int fs_mgr_mount_all(struct fstab *fstab, int mount_mode);
 
-#define FS_MGR_DOMNT_FAILED -1
-#define FS_MGR_DOMNT_BUSY -2
+#define FS_MGR_DOMNT_FAILED (-1)
+#define FS_MGR_DOMNT_BUSY (-2)
 
-int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device,
+int fs_mgr_do_mount(struct fstab *fstab, const char *n_name, char *n_blk_device,
                     char *tmp_mount_point);
-int fs_mgr_do_tmpfs_mount(char *n_name);
+int fs_mgr_do_mount_one(struct fstab_rec *rec);
+int fs_mgr_do_tmpfs_mount(const char *n_name);
 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);
@@ -109,21 +123,36 @@
 int fs_mgr_is_voldmanaged(const struct fstab_rec *fstab);
 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);
+void fs_mgr_get_file_encryption_modes(const struct fstab_rec *fstab,
+                                      const char **contents_mode_ret,
+                                      const char **filenames_mode_ret);
 int fs_mgr_is_convertible_to_fbe(const struct fstab_rec *fstab);
 int fs_mgr_is_noemulatedsd(const struct fstab_rec *fstab);
 int fs_mgr_is_notrim(struct fstab_rec *fstab);
 int fs_mgr_is_formattable(struct fstab_rec *fstab);
+int fs_mgr_is_slotselect(struct fstab_rec *fstab);
 int fs_mgr_is_nofail(struct fstab_rec *fstab);
 int fs_mgr_is_latemount(struct fstab_rec *fstab);
+int fs_mgr_is_quota(struct fstab_rec *fstab);
 int fs_mgr_swapon_all(struct fstab *fstab);
 
-int fs_mgr_do_format(struct fstab_rec *fstab);
+int fs_mgr_do_format(struct fstab_rec *fstab, bool reserve_footer);
 
+#define FS_MGR_SETUP_VERITY_DISABLED (-2)
+#define FS_MGR_SETUP_VERITY_FAIL (-1)
+#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..bbafe1a
--- /dev/null
+++ b/fs_mgr/include/fs_mgr_avb.h
@@ -0,0 +1,113 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <string>
+
+#include <libavb/libavb.h>
+
+#include "fs_mgr.h"
+
+enum FsManagerAvbHandleStatus {
+    kFsManagerAvbHandleUninitialized = -1,
+    kFsManagerAvbHandleSuccess = 0,
+    kFsManagerAvbHandleHashtreeDisabled = 1,
+    kFsManagerAvbHandleErrorVerification = 2,
+};
+
+class FsManagerAvbOps;
+
+class FsManagerAvbHandle;
+using FsManagerAvbUniquePtr = std::unique_ptr<FsManagerAvbHandle>;
+
+using ByNameSymlinkMap = std::map<std::string, std::string>;
+
+// 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();
+    //
+    // There are two overloaded Open() functions with a single parameter.
+    // The argument can be a ByNameSymlinkMap describing the mapping from partition
+    // name to by-name symlink, or a fstab file to which the ByNameSymlinkMap is
+    // constructed from. e.g.,
+    //   - /dev/block/platform/soc.0/7824900.sdhci/by-name/system_a ->
+    //   - ByNameSymlinkMap["system_a"] = "/dev/block/platform/soc.0/7824900.sdhci/by-name/system_a"
+    //
+    // 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 fstab& fstab);
+    static FsManagerAvbUniquePtr Open(ByNameSymlinkMap&& by_name_symlink_map);
+
+    // 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_);
+        }
+    };
+
+  private:
+    FsManagerAvbHandle() : avb_slot_data_(nullptr), status_(kFsManagerAvbHandleUninitialized) {}
+    static FsManagerAvbUniquePtr DoOpen(FsManagerAvbOps* avb_ops);
+
+    AvbSlotVerifyData* avb_slot_data_;
+    FsManagerAvbHandleStatus status_;
+    std::string avb_version_;
+};
+
+#endif /* __CORE_FS_MGR_AVB_H */
diff --git a/gatekeeperd/Android.mk b/gatekeeperd/Android.mk
index 3f78955..0dfd9d8 100644
--- a/gatekeeperd/Android.mk
+++ b/gatekeeperd/Android.mk
@@ -33,7 +33,12 @@
 	libbase \
 	libutils \
 	libcrypto \
-	libkeystore_binder
+	libkeystore_binder \
+	libhidlbase \
+	libhidltransport \
+	libhwbinder \
+	android.hardware.gatekeeper@1.0 \
+
 LOCAL_STATIC_LIBRARIES := libscrypt_static
 LOCAL_C_INCLUDES := external/scrypt/lib/crypto
 LOCAL_INIT_RC := gatekeeperd.rc
diff --git a/gatekeeperd/IUserManager.cpp b/gatekeeperd/IUserManager.cpp
index 8645fc2..8167d19 100644
--- a/gatekeeperd/IUserManager.cpp
+++ b/gatekeeperd/IUserManager.cpp
@@ -27,7 +27,7 @@
 class BpUserManager : public BpInterface<IUserManager>
 {
 public:
-    BpUserManager(const sp<IBinder>& impl) :
+    explicit BpUserManager(const sp<IBinder>& impl) :
             BpInterface<IUserManager>(impl) {
     }
     virtual int32_t getCredentialOwnerProfile(int32_t user_id) {
diff --git a/gatekeeperd/SoftGateKeeper.h b/gatekeeperd/SoftGateKeeper.h
index 8b15d72..cb02a6f 100644
--- a/gatekeeperd/SoftGateKeeper.h
+++ b/gatekeeperd/SoftGateKeeper.h
@@ -152,7 +152,7 @@
     }
 
     bool DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
-        uint64_t user_id = android::base::get_unaligned(&expected_handle->user_id);
+        uint64_t user_id = android::base::get_unaligned<secure_id_t>(&expected_handle->user_id);
         FastHashMap::const_iterator it = fast_hash_map_.find(user_id);
         if (it != fast_hash_map_.end() && VerifyFast(it->second, password)) {
             return true;
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index 1cec0fa..e6eb3bc 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -19,29 +19,35 @@
 #include "IGateKeeperService.h"
 
 #include <errno.h>
-#include <stdint.h>
-#include <inttypes.h>
 #include <fcntl.h>
+#include <inttypes.h>
+#include <stdint.h>
 #include <unistd.h>
 
-#include <cutils/log.h>
-#include <utils/Log.h>
-
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
 #include <binder/PermissionCache.h>
-#include <utils/String16.h>
-#include <utils/Log.h>
-
-#include <keystore/IKeystoreService.h>
-#include <keystore/keystore.h> // For error code
 #include <gatekeeper/password_handle.h> // for password_handle_t
 #include <hardware/gatekeeper.h>
 #include <hardware/hw_auth_token.h>
+#include <keystore/IKeystoreService.h>
+#include <keystore/keystore.h> // For error code
+#include <log/log.h>
+#include <utils/Log.h>
+#include <utils/String16.h>
 
 #include "SoftGateKeeperDevice.h"
 #include "IUserManager.h"
 
+#include <hidl/HidlSupport.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+
+using android::sp;
+using android::hardware::gatekeeper::V1_0::IGatekeeper;
+using android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
+using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
+using android::hardware::Return;
+
 namespace android {
 
 static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
@@ -50,33 +56,27 @@
 class GateKeeperProxy : public BnGateKeeperService {
 public:
     GateKeeperProxy() {
-        int ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &module);
-        device = NULL;
+        hw_device = IGatekeeper::getService();
 
-        if (ret < 0) {
+        if (hw_device == nullptr) {
             ALOGW("falling back to software GateKeeper");
             soft_device.reset(new SoftGateKeeperDevice());
-        } else {
-            ret = gatekeeper_open(module, &device);
-            if (ret < 0)
-                LOG_ALWAYS_FATAL_IF(ret < 0, "Unable to open GateKeeper HAL");
         }
 
         if (mark_cold_boot()) {
             ALOGI("cold boot: clearing state");
-            if (device != NULL && device->delete_all_users != NULL) {
-                device->delete_all_users(device);
+            if (hw_device != nullptr) {
+                hw_device->deleteAllUsers([](const GatekeeperResponse &){});
             }
         }
     }
 
     virtual ~GateKeeperProxy() {
-        if (device) gatekeeper_close(device);
     }
 
     void store_sid(uint32_t uid, uint64_t sid) {
         char filename[21];
-        sprintf(filename, "%u", uid);
+        snprintf(filename, sizeof(filename), "%u", uid);
         int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
         if (fd < 0) {
             ALOGE("could not open file: %s: %s", filename, strerror(errno));
@@ -102,7 +102,7 @@
 
     void maybe_store_sid(uint32_t uid, uint64_t sid) {
         char filename[21];
-        sprintf(filename, "%u", uid);
+        snprintf(filename, sizeof(filename), "%u", uid);
         if (access(filename, F_OK) == -1) {
             store_sid(uid, sid);
         }
@@ -111,7 +111,7 @@
     uint64_t read_sid(uint32_t uid) {
         char filename[21];
         uint64_t sid;
-        sprintf(filename, "%u", uid);
+        snprintf(filename, sizeof(filename), "%u", uid);
         int fd = open(filename, O_RDONLY);
         if (fd < 0) return 0;
         read(fd, &sid, sizeof(sid));
@@ -121,7 +121,7 @@
 
     void clear_sid(uint32_t uid) {
         char filename[21];
-        sprintf(filename, "%u", uid);
+        snprintf(filename, sizeof(filename), "%u", uid);
         if (remove(filename) < 0) {
             ALOGE("%s: could not remove file [%s], attempting 0 write", __func__, strerror(errno));
             store_sid(uid, 0);
@@ -144,7 +144,7 @@
         if (desired_password_length == 0) return -EINVAL;
 
         int ret;
-        if (device) {
+        if (hw_device != nullptr) {
             const gatekeeper::password_handle_t *handle =
                     reinterpret_cast<const gatekeeper::password_handle_t *>(current_password_handle);
 
@@ -157,10 +157,37 @@
                 current_password_length = 0;
             }
 
-            ret = device->enroll(device, uid, current_password_handle, current_password_handle_length,
-                    current_password, current_password_length,
-                    desired_password, desired_password_length,
-                    enrolled_password_handle, enrolled_password_handle_length);
+            android::hardware::hidl_vec<uint8_t> curPwdHandle;
+            curPwdHandle.setToExternal(const_cast<uint8_t*>(current_password_handle),
+                                       current_password_handle_length);
+            android::hardware::hidl_vec<uint8_t> curPwd;
+            curPwd.setToExternal(const_cast<uint8_t*>(current_password),
+                                 current_password_length);
+            android::hardware::hidl_vec<uint8_t> newPwd;
+            newPwd.setToExternal(const_cast<uint8_t*>(desired_password),
+                                 desired_password_length);
+
+            Return<void> hwRes = hw_device->enroll(uid, curPwdHandle, curPwd, newPwd,
+                              [&ret, enrolled_password_handle, enrolled_password_handle_length]
+                                   (const GatekeeperResponse &rsp) {
+                ret = static_cast<int>(rsp.code); // propagate errors
+                if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+                    if (enrolled_password_handle != nullptr &&
+                        enrolled_password_handle_length != nullptr) {
+                        *enrolled_password_handle = new uint8_t[rsp.data.size()];
+                        *enrolled_password_handle_length = rsp.data.size();
+                        memcpy(*enrolled_password_handle, rsp.data.data(),
+                               *enrolled_password_handle_length);
+                    }
+                    ret = 0; // all success states are reported as 0
+                } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
+                    ret = rsp.timeout;
+                }
+            });
+            if (!hwRes.isOk()) {
+                ALOGE("enroll transaction failed\n");
+                ret = -1;
+            }
         } else {
             ret = soft_device->enroll(uid,
                     current_password_handle, current_password_handle_length,
@@ -217,16 +244,40 @@
             return -EINVAL;
 
         int ret;
-        if (device) {
+        if (hw_device != nullptr) {
             const gatekeeper::password_handle_t *handle =
                     reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
             // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
             // a HAL if there was none before
             if (handle->version == 0 || handle->hardware_backed) {
-                ret = device->verify(device, uid, challenge,
-                    enrolled_password_handle, enrolled_password_handle_length,
-                    provided_password, provided_password_length, auth_token, auth_token_length,
-                    request_reenroll);
+                android::hardware::hidl_vec<uint8_t> curPwdHandle;
+                curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolled_password_handle),
+                                           enrolled_password_handle_length);
+                android::hardware::hidl_vec<uint8_t> enteredPwd;
+                enteredPwd.setToExternal(const_cast<uint8_t*>(provided_password),
+                                         provided_password_length);
+                Return<void> hwRes = hw_device->verify(uid, challenge, curPwdHandle, enteredPwd,
+                                        [&ret, request_reenroll, auth_token, auth_token_length]
+                                             (const GatekeeperResponse &rsp) {
+                    ret = static_cast<int>(rsp.code); // propagate errors
+                    if (auth_token != nullptr && auth_token_length != nullptr &&
+                        rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+                        *auth_token = new uint8_t[rsp.data.size()];
+                        *auth_token_length = rsp.data.size();
+                        memcpy(*auth_token, rsp.data.data(), *auth_token_length);
+                        if (request_reenroll != nullptr) {
+                            *request_reenroll = (rsp.code == GatekeeperStatusCode::STATUS_REENROLL);
+                        }
+                        ret = 0; // all success states are reported as 0
+                    } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
+                               rsp.timeout > 0) {
+                        ret = rsp.timeout;
+                    }
+                });
+                if (!hwRes.isOk()) {
+                    ALOGE("verify transaction failed\n");
+                    ret = -1;
+                }
             } else {
                 // upgrade scenario, a HAL has been added to this device where there was none before
                 SoftGateKeeperDevice soft_dev;
@@ -253,9 +304,9 @@
             sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
             sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
             if (service != NULL) {
-                status_t ret = service->addAuthToken(*auth_token, *auth_token_length);
-                if (ret != ResponseCode::NO_ERROR) {
-                    ALOGE("Falure sending auth token to KeyStore: %d", ret);
+                auto ret = service->addAuthToken(*auth_token, *auth_token_length);
+                if (!ret.isOk()) {
+                    ALOGE("Failure sending auth token to KeyStore: %" PRId32, int32_t(ret));
                 }
             } else {
                 ALOGE("Unable to communicate with KeyStore");
@@ -298,8 +349,8 @@
         }
         clear_sid(uid);
 
-        if (device != NULL && device->delete_user != NULL) {
-            device->delete_user(device, uid);
+        if (hw_device != nullptr) {
+            hw_device->deleteUser(uid, [] (const GatekeeperResponse &){});
         }
     }
 
@@ -311,7 +362,7 @@
             return PERMISSION_DENIED;
         }
 
-        if (device == NULL) {
+        if (hw_device == NULL) {
             const char *result = "Device not available";
             write(fd, result, strlen(result) + 1);
         } else {
@@ -323,9 +374,8 @@
     }
 
 private:
-    gatekeeper_device_t *device;
+    sp<IGatekeeper> hw_device;
     UniquePtr<SoftGateKeeperDevice> soft_device;
-    const hw_module_t *module;
 };
 }// namespace android
 
diff --git a/healthd/Android.mk b/healthd/Android.mk
index 1390962..8b59964 100644
--- a/healthd/Android.mk
+++ b/healthd/Android.mk
@@ -3,42 +3,55 @@
 LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
-LOCAL_SRC_FILES := healthd_board_default.cpp
-LOCAL_MODULE := libhealthd.default
-LOCAL_CFLAGS := -Werror
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
 LOCAL_SRC_FILES := BatteryMonitor.cpp
 LOCAL_MODULE := libbatterymonitor
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := libutils
+LOCAL_STATIC_LIBRARIES := libutils libbase libbinder
 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 \
-    AnimationParser.cpp \
-    BatteryPropertiesRegistrar.cpp \
+    BatteryPropertiesRegistrar.cpp
 
-LOCAL_MODULE := libhealthd_internal
-LOCAL_C_INCLUDES := bootable/recovery
+LOCAL_MODULE := libhealthd_android
 LOCAL_EXPORT_C_INCLUDE_DIRS := \
     $(LOCAL_PATH) \
-    $(LOCAL_PATH)/include \
+    $(LOCAL_PATH)/include
 
 LOCAL_STATIC_LIBRARIES := \
     libbatterymonitor \
     libbatteryservice \
-    libbinder \
+    libutils \
+    libbase \
+    libcutils \
+    liblog \
+    libc \
+
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_CFLAGS := -Werror
+ifeq ($(strip $(BOARD_CHARGER_DISABLE_INIT_BLANK)),true)
+LOCAL_CFLAGS += -DCHARGER_DISABLE_INIT_BLANK
+endif
+ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
+LOCAL_CFLAGS += -DCHARGER_ENABLE_SUSPEND
+endif
+
+LOCAL_SRC_FILES := \
+    healthd_mode_charger.cpp \
+    AnimationParser.cpp
+
+LOCAL_MODULE := libhealthd_charger
+LOCAL_C_INCLUDES := bootable/recovery $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := \
+    $(LOCAL_PATH) \
+    $(LOCAL_PATH)/include
+
+LOCAL_STATIC_LIBRARIES := \
     libminui \
     libpng \
     libz \
@@ -49,53 +62,60 @@
     libm \
     libc \
 
+ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
+LOCAL_STATIC_LIBRARIES += libsuspend
+endif
+
 include $(BUILD_STATIC_LIBRARY)
 
-
+### charger ###
 include $(CLEAR_VARS)
+ifeq ($(strip $(BOARD_CHARGER_NO_UI)),true)
+LOCAL_CHARGER_NO_UI := true
+endif
+ifdef BRILLO
+LOCAL_CHARGER_NO_UI := true
+endif
 
 LOCAL_SRC_FILES := \
-    healthd.cpp \
+    healthd_common.cpp \
+    charger.cpp \
 
-LOCAL_MODULE := healthd
+LOCAL_MODULE := charger
 LOCAL_MODULE_TAGS := optional
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN)
 LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED)
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
 
-LOCAL_CFLAGS := -D__STDC_LIMIT_MACROS -Werror
-
-ifeq ($(strip $(BOARD_CHARGER_DISABLE_INIT_BLANK)),true)
-LOCAL_CFLAGS += -DCHARGER_DISABLE_INIT_BLANK
+LOCAL_CFLAGS := -Werror
+ifeq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
+LOCAL_CFLAGS += -DCHARGER_NO_UI
 endif
-
-ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
-LOCAL_CFLAGS += -DCHARGER_ENABLE_SUSPEND
-endif
-
 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_C_INCLUDES := bootable/recovery
 
 LOCAL_STATIC_LIBRARIES := \
-    libhealthd_internal \
+    libhealthd_charger \
     libbatterymonitor \
-    libbatteryservice \
-    libbinder \
-    libminui \
-    libpng \
-    libz \
-    libutils \
     libbase \
+    libutils \
     libcutils \
     liblog \
     libm \
-    libc
+    libc \
+
+ifneq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
+LOCAL_STATIC_LIBRARIES += \
+    libminui \
+    libpng \
+    libz \
+
+endif
 
 ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
 LOCAL_STATIC_LIBRARIES += libsuspend
@@ -103,13 +123,13 @@
 
 LOCAL_HAL_STATIC_LIBRARIES := libhealthd
 
-# Symlink /charger to /sbin/healthd
+# Symlink /charger to /sbin/charger
 LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT) \
-    && ln -sf /sbin/healthd $(TARGET_ROOT_OUT)/charger
+    && ln -sf /sbin/charger $(TARGET_ROOT_OUT)/charger
 
 include $(BUILD_EXECUTABLE)
 
-
+ifneq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
 define _add-charger-image
 include $$(CLEAR_VARS)
 LOCAL_MODULE := system_core_charger_res_images_$(notdir $(1))
@@ -135,3 +155,42 @@
 
 _add-charger-image :=
 _img_modules :=
+endif # LOCAL_CHARGER_NO_UI
+
+### healthd ###
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+    healthd_common.cpp \
+    healthd.cpp \
+
+LOCAL_MODULE := healthd
+LOCAL_MODULE_TAGS := optional
+LOCAL_C_INCLUDES := $(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_android \
+    libbatterymonitor \
+    libbatteryservice \
+    android.hardware.health@1.0-convert \
+
+LOCAL_SHARED_LIBRARIES := \
+    libbinder \
+    libbase \
+    libutils \
+    libcutils \
+    liblog \
+    libm \
+    libc \
+    libhidlbase \
+    libhidltransport \
+    android.hardware.health@1.0 \
+
+include $(BUILD_EXECUTABLE)
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 54d45e6..d26530b 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -26,7 +26,11 @@
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
+#include <memory>
 
+#include <android-base/file.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
 #include <batteryservice/BatteryService.h>
 #include <cutils/klog.h>
 #include <cutils/properties.h>
@@ -124,34 +128,15 @@
     return ret;
 }
 
-int BatteryMonitor::readFromFile(const String8& path, char* buf, size_t size) {
-    char *cp = NULL;
-
-    if (path.isEmpty())
-        return -1;
-    int fd = open(path.string(), O_RDONLY, 0);
-    if (fd == -1) {
-        KLOG_ERROR(LOG_TAG, "Could not open '%s'\n", path.string());
-        return -1;
+int BatteryMonitor::readFromFile(const String8& path, std::string* buf) {
+    if (android::base::ReadFileToString(path.c_str(), buf)) {
+        *buf = android::base::Trim(*buf);
     }
-
-    ssize_t count = TEMP_FAILURE_RETRY(read(fd, buf, size));
-    if (count > 0)
-            cp = (char *)memrchr(buf, '\n', count);
-
-    if (cp)
-        *cp = '\0';
-    else
-        buf[0] = '\0';
-
-    close(fd);
-    return count;
+    return buf->length();
 }
 
 BatteryMonitor::PowerSupplyType BatteryMonitor::readPowerSupplyType(const String8& path) {
-    const int SIZE = 128;
-    char buf[SIZE];
-    int length = readFromFile(path, buf, SIZE);
+    std::string buf;
     BatteryMonitor::PowerSupplyType ret;
     struct sysfsStringEnumMap supplyTypeMap[] = {
             { "Unknown", ANDROID_POWER_SUPPLY_TYPE_UNKNOWN },
@@ -170,12 +155,12 @@
             { NULL, 0 },
     };
 
-    if (length <= 0)
+    if (readFromFile(path, &buf) <= 0)
         return ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;
 
-    ret = (BatteryMonitor::PowerSupplyType)mapSysfsString(buf, supplyTypeMap);
+    ret = (BatteryMonitor::PowerSupplyType)mapSysfsString(buf.c_str(), supplyTypeMap);
     if (ret < 0) {
-        KLOG_WARNING(LOG_TAG, "Unknown power supply type '%s'\n", buf);
+        KLOG_WARNING(LOG_TAG, "Unknown power supply type '%s'\n", buf.c_str());
         ret = ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;
     }
 
@@ -183,27 +168,23 @@
 }
 
 bool BatteryMonitor::getBooleanField(const String8& path) {
-    const int SIZE = 16;
-    char buf[SIZE];
-
+    std::string buf;
     bool value = false;
-    if (readFromFile(path, buf, SIZE) > 0) {
-        if (buf[0] != '0') {
+
+    if (readFromFile(path, &buf) > 0)
+        if (buf[0] != '0')
             value = true;
-        }
-    }
 
     return value;
 }
 
 int BatteryMonitor::getIntField(const String8& path) {
-    const int SIZE = 128;
-    char buf[SIZE];
-
+    std::string buf;
     int value = 0;
-    if (readFromFile(path, buf, SIZE) > 0) {
-        value = strtol(buf, NULL, 0);
-    }
+
+    if (readFromFile(path, &buf) > 0)
+        android::base::ParseInt(buf, &value);
+
     return value;
 }
 
@@ -247,18 +228,16 @@
         props.batteryHealth = BATTERY_HEALTH_GOOD;
     }
 
-    const int SIZE = 128;
-    char buf[SIZE];
-    String8 btech;
+    std::string buf;
 
-    if (readFromFile(mHealthdConfig->batteryStatusPath, buf, SIZE) > 0)
-        props.batteryStatus = getBatteryStatus(buf);
+    if (readFromFile(mHealthdConfig->batteryStatusPath, &buf) > 0)
+        props.batteryStatus = getBatteryStatus(buf.c_str());
 
-    if (readFromFile(mHealthdConfig->batteryHealthPath, buf, SIZE) > 0)
-        props.batteryHealth = getBatteryHealth(buf);
+    if (readFromFile(mHealthdConfig->batteryHealthPath, &buf) > 0)
+        props.batteryHealth = getBatteryHealth(buf.c_str());
 
-    if (readFromFile(mHealthdConfig->batteryTechnologyPath, buf, SIZE) > 0)
-        props.batteryTechnology = String8(buf);
+    if (readFromFile(mHealthdConfig->batteryTechnologyPath, &buf) > 0)
+        props.batteryTechnology = String8(buf.c_str());
 
     unsigned int i;
     double MaxPower = 0;
@@ -267,47 +246,44 @@
         String8 path;
         path.appendFormat("%s/%s/online", POWER_SUPPLY_SYSFS_PATH,
                           mChargerNames[i].string());
-
-        if (readFromFile(path, buf, SIZE) > 0) {
-            if (buf[0] != '0') {
-                path.clear();
-                path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH,
-                                  mChargerNames[i].string());
-                switch(readPowerSupplyType(path)) {
-                case ANDROID_POWER_SUPPLY_TYPE_AC:
-                    props.chargerAcOnline = true;
-                    break;
-                case ANDROID_POWER_SUPPLY_TYPE_USB:
-                    props.chargerUsbOnline = true;
-                    break;
-                case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:
-                    props.chargerWirelessOnline = true;
-                    break;
-                default:
-                    KLOG_WARNING(LOG_TAG, "%s: Unknown power supply type\n",
-                                 mChargerNames[i].string());
-                }
-                path.clear();
-                path.appendFormat("%s/%s/current_max", POWER_SUPPLY_SYSFS_PATH,
-                                  mChargerNames[i].string());
-                int ChargingCurrent =
+        if (getIntField(path)) {
+            path.clear();
+            path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH,
+                              mChargerNames[i].string());
+            switch(readPowerSupplyType(path)) {
+            case ANDROID_POWER_SUPPLY_TYPE_AC:
+                props.chargerAcOnline = true;
+                break;
+            case ANDROID_POWER_SUPPLY_TYPE_USB:
+                props.chargerUsbOnline = true;
+                break;
+            case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:
+                props.chargerWirelessOnline = true;
+                break;
+            default:
+                KLOG_WARNING(LOG_TAG, "%s: Unknown power supply type\n",
+                             mChargerNames[i].string());
+            }
+            path.clear();
+            path.appendFormat("%s/%s/current_max", POWER_SUPPLY_SYSFS_PATH,
+                              mChargerNames[i].string());
+            int ChargingCurrent =
                     (access(path.string(), R_OK) == 0) ? getIntField(path) : 0;
 
-                path.clear();
-                path.appendFormat("%s/%s/voltage_max", POWER_SUPPLY_SYSFS_PATH,
-                                  mChargerNames[i].string());
+            path.clear();
+            path.appendFormat("%s/%s/voltage_max", POWER_SUPPLY_SYSFS_PATH,
+                              mChargerNames[i].string());
 
-                int ChargingVoltage =
-                    (access(path.string(), R_OK) == 0) ? getIntField(path) :
-                    DEFAULT_VBUS_VOLTAGE;
+            int ChargingVoltage =
+                (access(path.string(), R_OK) == 0) ? getIntField(path) :
+                DEFAULT_VBUS_VOLTAGE;
 
-                double power = ((double)ChargingCurrent / MILLION) *
-                        ((double)ChargingVoltage / MILLION);
-                if (MaxPower < power) {
-                    props.maxChargingCurrent = ChargingCurrent;
-                    props.maxChargingVoltage = ChargingVoltage;
-                    MaxPower = power;
-                }
+            double power = ((double)ChargingCurrent / MILLION) *
+                           ((double)ChargingVoltage / MILLION);
+            if (MaxPower < power) {
+                props.maxChargingCurrent = ChargingCurrent;
+                props.maxChargingVoltage = ChargingVoltage;
+                MaxPower = power;
             }
         }
     }
@@ -342,11 +318,10 @@
                                 " cc=%d", props.batteryCycleCount);
             }
         } else {
-            snprintf(dmesgline, sizeof(dmesgline),
+            len = snprintf(dmesgline, sizeof(dmesgline),
                  "battery none");
         }
 
-        len = strlen(dmesgline);
         snprintf(dmesgline + len, sizeof(dmesgline) - len, " chg=%s%s%s",
                  props.chargerAcOnline ? "a" : "",
                  props.chargerUsbOnline ? "u" : "",
@@ -363,16 +338,16 @@
 int BatteryMonitor::getChargeStatus() {
     int result = BATTERY_STATUS_UNKNOWN;
     if (!mHealthdConfig->batteryStatusPath.isEmpty()) {
-        char buf[128];
-        if (readFromFile(mHealthdConfig->batteryStatusPath, buf, sizeof(buf)) > 0) {
-            result = getBatteryStatus(buf);
-        }
+        std::string buf;
+        if (readFromFile(mHealthdConfig->batteryStatusPath, &buf) > 0)
+            result = getBatteryStatus(buf.c_str());
     }
     return result;
 }
 
 status_t BatteryMonitor::getProperty(int id, struct BatteryProperty *val) {
     status_t ret = BAD_VALUE;
+    std::string buf;
 
     val->valueInt64 = LONG_MIN;
 
@@ -425,6 +400,15 @@
         }
         break;
 
+    case BATTERY_PROP_BATTERY_STATUS:
+        if (mAlwaysPluggedDevice) {
+            val->valueInt64 = BATTERY_STATUS_CHARGING;
+        } else {
+            val->valueInt64 = getChargeStatus();
+        }
+        ret = NO_ERROR;
+        break;
+
     default:
         break;
     }
@@ -488,13 +472,13 @@
     char pval[PROPERTY_VALUE_MAX];
 
     mHealthdConfig = hc;
-    DIR* dir = opendir(POWER_SUPPLY_SYSFS_PATH);
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(POWER_SUPPLY_SYSFS_PATH), closedir);
     if (dir == NULL) {
         KLOG_ERROR(LOG_TAG, "Could not open %s\n", POWER_SUPPLY_SYSFS_PATH);
     } else {
         struct dirent* entry;
 
-        while ((entry = readdir(dir))) {
+        while ((entry = readdir(dir.get()))) {
             const char* name = entry->d_name;
 
             if (!strcmp(name, ".") || !strcmp(name, ".."))
@@ -632,7 +616,6 @@
                 break;
             }
         }
-        closedir(dir);
     }
 
     // Typically the case for devices which do not have a battery and
diff --git a/healthd/BatteryPropertiesRegistrar.cpp b/healthd/BatteryPropertiesRegistrar.cpp
index 5d1fa52..e51a06d 100644
--- a/healthd/BatteryPropertiesRegistrar.cpp
+++ b/healthd/BatteryPropertiesRegistrar.cpp
@@ -35,10 +35,20 @@
     defaultServiceManager()->addService(String16("batteryproperties"), service);
 }
 
-void BatteryPropertiesRegistrar::notifyListeners(struct BatteryProperties props) {
-    Mutex::Autolock _l(mRegistrationLock);
-    for (size_t i = 0; i < mListeners.size(); i++) {
-        mListeners[i]->batteryPropertiesChanged(props);
+void BatteryPropertiesRegistrar::notifyListeners(const struct BatteryProperties& props) {
+    Vector<sp<IBatteryPropertiesListener> > listenersCopy;
+
+    // Binder currently may service an incoming oneway transaction whenever an
+    // outbound oneway call is made (if there is already a pending incoming
+    // oneway call waiting).  This is considered a bug and may change in the
+    // future.  For now, avoid recursive mutex lock while making outbound
+    // calls by making a local copy of the current list of listeners.
+    {
+        Mutex::Autolock _l(mRegistrationLock);
+        listenersCopy = mListeners;
+    }
+    for (size_t i = 0; i < listenersCopy.size(); i++) {
+        listenersCopy[i]->batteryPropertiesChanged(props);
     }
 }
 
@@ -77,6 +87,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 d17e4a3..14e9145 100644
--- a/healthd/BatteryPropertiesRegistrar.h
+++ b/healthd/BatteryPropertiesRegistrar.h
@@ -31,7 +31,8 @@
                                    public IBinder::DeathRecipient {
 public:
     void publish(const sp<BatteryPropertiesRegistrar>& service);
-    void notifyListeners(struct BatteryProperties props);
+    void notifyListeners(const struct BatteryProperties& props);
+    void scheduleUpdate();
 
 private:
     Mutex mRegistrationLock;
diff --git a/healthd/charger.cpp b/healthd/charger.cpp
new file mode 100644
index 0000000..5a8fe1a
--- /dev/null
+++ b/healthd/charger.cpp
@@ -0,0 +1,102 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "charger"
+#define KLOG_LEVEL 6
+
+#include <healthd/healthd.h>
+
+#include <stdlib.h>
+#include <string.h>
+#include <cutils/klog.h>
+
+using namespace android;
+
+// main healthd loop
+extern int healthd_main(void);
+
+// Charger mode
+
+extern void healthd_mode_charger_init(struct healthd_config *config);
+extern int healthd_mode_charger_preparetowait(void);
+extern void healthd_mode_charger_heartbeat(void);
+extern void healthd_mode_charger_battery_update(
+    struct android::BatteryProperties *props);
+
+// NOPs for modes that need no special action
+
+static void healthd_mode_nop_init(struct healthd_config *config);
+static int healthd_mode_nop_preparetowait(void);
+static void healthd_mode_nop_heartbeat(void);
+static void healthd_mode_nop_battery_update(
+    struct android::BatteryProperties *props);
+
+static struct healthd_mode_ops healthd_nops = {
+    .init = healthd_mode_nop_init,
+    .preparetowait = healthd_mode_nop_preparetowait,
+    .heartbeat = healthd_mode_nop_heartbeat,
+    .battery_update = healthd_mode_nop_battery_update,
+};
+
+#ifdef CHARGER_NO_UI
+static struct healthd_mode_ops charger_ops = healthd_nops;
+#else
+static struct healthd_mode_ops charger_ops = {
+    .init = healthd_mode_charger_init,
+    .preparetowait = healthd_mode_charger_preparetowait,
+    .heartbeat = healthd_mode_charger_heartbeat,
+    .battery_update = healthd_mode_charger_battery_update,
+};
+#endif
+
+static void healthd_mode_nop_init(struct healthd_config* /*config*/) {
+}
+
+static int healthd_mode_nop_preparetowait(void) {
+    return -1;
+}
+
+static void healthd_mode_nop_heartbeat(void) {
+}
+
+static void healthd_mode_nop_battery_update(
+    struct android::BatteryProperties* /*props*/) {
+}
+
+int main(int argc, char **argv) {
+    int ch;
+
+    healthd_mode_ops = &charger_ops;
+
+    while ((ch = getopt(argc, argv, "cr")) != -1) {
+        switch (ch) {
+            case 'c':
+                // -c is now a noop
+                break;
+            case 'r':
+                // force nops for recovery
+                healthd_mode_ops = &healthd_nops;
+                break;
+            case '?':
+            default:
+                KLOG_ERROR(LOG_TAG, "Unrecognized charger option: %c\n",
+                        optopt);
+                exit(1);
+        }
+    }
+
+    return healthd_main();
+}
diff --git a/healthd/healthd.cpp b/healthd/healthd.cpp
index 1c144b3..ed1971a 100644
--- a/healthd/healthd.cpp
+++ b/healthd/healthd.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 The Android Open Source Project
+ * 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.
@@ -18,362 +18,106 @@
 #define KLOG_LEVEL 6
 
 #include <healthd/healthd.h>
-#include <healthd/BatteryMonitor.h>
 
-#include <errno.h>
-#include <libgen.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
 #include <unistd.h>
-#include <batteryservice/BatteryService.h>
 #include <cutils/klog.h>
-#include <cutils/uevent.h>
-#include <sys/epoll.h>
-#include <sys/timerfd.h>
-#include <utils/Errors.h>
+
+#include <android/hardware/health/1.0/IHealth.h>
+#include <android/hardware/health/1.0/types.h>
+#include <hal_conversion.h>
 
 using namespace android;
 
-#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
+using IHealth = ::android::hardware::health::V1_0::IHealth;
+using Result = ::android::hardware::health::V1_0::Result;
+using HealthConfig = ::android::hardware::health::V1_0::HealthConfig;
+using HealthInfo = ::android::hardware::health::V1_0::HealthInfo;
 
-#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
+using ::android::hardware::health::V1_0::hal_conversion::convertToHealthConfig;
+using ::android::hardware::health::V1_0::hal_conversion::convertFromHealthConfig;
+using ::android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
+using ::android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
 
-static struct healthd_config healthd_config = {
-    .periodic_chores_interval_fast = DEFAULT_PERIODIC_CHORES_INTERVAL_FAST,
-    .periodic_chores_interval_slow = DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW,
-    .batteryStatusPath = String8(String8::kEmptyString),
-    .batteryHealthPath = String8(String8::kEmptyString),
-    .batteryPresentPath = String8(String8::kEmptyString),
-    .batteryCapacityPath = String8(String8::kEmptyString),
-    .batteryVoltagePath = String8(String8::kEmptyString),
-    .batteryTemperaturePath = String8(String8::kEmptyString),
-    .batteryTechnologyPath = String8(String8::kEmptyString),
-    .batteryCurrentNowPath = String8(String8::kEmptyString),
-    .batteryCurrentAvgPath = String8(String8::kEmptyString),
-    .batteryChargeCounterPath = String8(String8::kEmptyString),
-    .batteryFullChargePath = String8(String8::kEmptyString),
-    .batteryCycleCountPath = String8(String8::kEmptyString),
-    .energyCounter = NULL,
-    .boot_min_cap = 0,
-    .screen_on = NULL,
-};
+// device specific hal interface;
+static sp<IHealth> gHealth;
 
-static int eventct;
-static int epollfd;
-
-#define POWER_SUPPLY_SUBSYSTEM "power_supply"
-
-// epoll_create() parameter is actually unused
-#define MAX_EPOLL_EVENTS 40
-static int uevent_fd;
-static int wakealarm_fd;
-
-// -1 for no epoll timeout
-static int awake_poll_interval = -1;
-
-static int wakealarm_wake_interval = DEFAULT_PERIODIC_CHORES_INTERVAL_FAST;
-
-static BatteryMonitor* gBatteryMonitor;
-
-struct healthd_mode_ops *healthd_mode_ops;
+// main healthd loop
+extern int healthd_main(void);
 
 // Android mode
-
 extern void healthd_mode_android_init(struct healthd_config *config);
 extern int healthd_mode_android_preparetowait(void);
+extern void healthd_mode_android_heartbeat(void);
 extern void healthd_mode_android_battery_update(
     struct android::BatteryProperties *props);
 
-// Charger mode
-
-extern void healthd_mode_charger_init(struct healthd_config *config);
-extern int healthd_mode_charger_preparetowait(void);
-extern void healthd_mode_charger_heartbeat(void);
-extern void healthd_mode_charger_battery_update(
-    struct android::BatteryProperties *props);
-
-// NOPs for modes that need no special action
-
-static void healthd_mode_nop_init(struct healthd_config *config);
-static int healthd_mode_nop_preparetowait(void);
-static void healthd_mode_nop_heartbeat(void);
-static void healthd_mode_nop_battery_update(
-    struct android::BatteryProperties *props);
-
 static struct healthd_mode_ops android_ops = {
     .init = healthd_mode_android_init,
     .preparetowait = healthd_mode_android_preparetowait,
-    .heartbeat = healthd_mode_nop_heartbeat,
+    .heartbeat = healthd_mode_android_heartbeat,
     .battery_update = healthd_mode_android_battery_update,
 };
 
-static struct healthd_mode_ops charger_ops = {
-    .init = healthd_mode_charger_init,
-    .preparetowait = healthd_mode_charger_preparetowait,
-    .heartbeat = healthd_mode_charger_heartbeat,
-    .battery_update = healthd_mode_charger_battery_update,
-};
+// default energy counter property redirect to talk to device
+// HAL
+static int healthd_board_get_energy_counter(int64_t *energy) {
 
-static struct healthd_mode_ops recovery_ops = {
-    .init = healthd_mode_nop_init,
-    .preparetowait = healthd_mode_nop_preparetowait,
-    .heartbeat = healthd_mode_nop_heartbeat,
-    .battery_update = healthd_mode_nop_battery_update,
-};
-
-static void healthd_mode_nop_init(struct healthd_config* /*config*/) {
-}
-
-static int healthd_mode_nop_preparetowait(void) {
-    return -1;
-}
-
-static void healthd_mode_nop_heartbeat(void) {
-}
-
-static void healthd_mode_nop_battery_update(
-    struct android::BatteryProperties* /*props*/) {
-}
-
-int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup) {
-    struct epoll_event ev;
-
-    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,
-                   "epoll_ctl failed; errno=%d\n", errno);
-        return -1;
+    if (gHealth == nullptr) {
+        return NAME_NOT_FOUND;
     }
 
-    eventct++;
-    return 0;
+    Result result = Result::NOT_SUPPORTED;
+    gHealth->energyCounter([=, &result] (Result ret, int64_t energyOut) {
+                result = ret;
+                *energy = energyOut;
+            });
+
+    return result == Result::SUCCESS ? OK : NAME_NOT_FOUND;
 }
 
-static void wakealarm_set_interval(int interval) {
-    struct itimerspec itval;
+void healthd_board_init(struct healthd_config *config) {
 
-    if (wakealarm_fd == -1)
-            return;
+    // Initialize the board HAL - Equivalent of healthd_board_init(config)
+    // in charger/recovery mode.
 
-    wakealarm_wake_interval = interval;
-
-    if (interval == -1)
-        interval = 0;
-
-    itval.it_interval.tv_sec = interval;
-    itval.it_interval.tv_nsec = 0;
-    itval.it_value.tv_sec = interval;
-    itval.it_value.tv_nsec = 0;
-
-    if (timerfd_settime(wakealarm_fd, 0, &itval, NULL) == -1)
-        KLOG_ERROR(LOG_TAG, "wakealarm_set_interval: timerfd_settime failed\n");
-}
-
-status_t healthd_get_property(int id, struct BatteryProperty *val) {
-    return gBatteryMonitor->getProperty(id, val);
-}
-
-void healthd_battery_update(void) {
-    // Fast wake interval when on charger (watch for overheat);
-    // slow wake interval when on battery (watch for drained battery).
-
-   int new_wake_interval = gBatteryMonitor->update() ?
-       healthd_config.periodic_chores_interval_fast :
-           healthd_config.periodic_chores_interval_slow;
-
-    if (new_wake_interval != wakealarm_wake_interval)
-            wakealarm_set_interval(new_wake_interval);
-
-    // During awake periods poll at fast rate.  If wake alarm is set at fast
-    // rate then just use the alarm; if wake alarm is set at slow rate then
-    // poll at fast rate while awake and let alarm wake up at slow rate when
-    // asleep.
-
-    if (healthd_config.periodic_chores_interval_fast == -1)
-        awake_poll_interval = -1;
-    else
-        awake_poll_interval =
-            new_wake_interval == healthd_config.periodic_chores_interval_fast ?
-                -1 : healthd_config.periodic_chores_interval_fast * 1000;
-}
-
-void healthd_dump_battery_state(int fd) {
-    gBatteryMonitor->dumpState(fd);
-    fsync(fd);
-}
-
-static void periodic_chores() {
-    healthd_battery_update();
-}
-
-#define UEVENT_MSG_LEN 2048
-static void uevent_event(uint32_t /*epevents*/) {
-    char msg[UEVENT_MSG_LEN+2];
-    char *cp;
-    int n;
-
-    n = uevent_kernel_multicast_recv(uevent_fd, msg, UEVENT_MSG_LEN);
-    if (n <= 0)
-        return;
-    if (n >= UEVENT_MSG_LEN)   /* overflow -- discard */
-        return;
-
-    msg[n] = '\0';
-    msg[n+1] = '\0';
-    cp = msg;
-
-    while (*cp) {
-        if (!strcmp(cp, "SUBSYSTEM=" POWER_SUPPLY_SUBSYSTEM)) {
-            healthd_battery_update();
-            break;
-        }
-
-        /* advance to after the next \0 */
-        while (*cp++)
-            ;
-    }
-}
-
-static void uevent_init(void) {
-    uevent_fd = uevent_open_socket(64*1024, true);
-
-    if (uevent_fd < 0) {
-        KLOG_ERROR(LOG_TAG, "uevent_init: uevent_open_socket failed\n");
+    gHealth = IHealth::getService();
+    if (gHealth == nullptr) {
+        KLOG_WARNING(LOG_TAG, "unable to get HAL interface, using defaults\n");
         return;
     }
 
-    fcntl(uevent_fd, F_SETFL, O_NONBLOCK);
-    if (healthd_register_event(uevent_fd, uevent_event, EVENT_WAKEUP_FD))
-        KLOG_ERROR(LOG_TAG,
-                   "register for uevent events failed\n");
+    HealthConfig halConfig;
+    convertToHealthConfig(config, halConfig);
+    gHealth->init(halConfig, [=] (const auto &halConfigOut) {
+            convertFromHealthConfig(halConfigOut, config);
+            // always redirect energy counter queries
+            config->energyCounter = healthd_board_get_energy_counter;
+            });
 }
 
-static void wakealarm_event(uint32_t /*epevents*/) {
-    unsigned long long wakeups;
+int healthd_board_battery_update(struct android::BatteryProperties *props) {
+    int logthis = 0;
 
-    if (read(wakealarm_fd, &wakeups, sizeof(wakeups)) == -1) {
-        KLOG_ERROR(LOG_TAG, "wakealarm_event: read wakealarm fd failed\n");
-        return;
+    if (gHealth == nullptr) {
+        return logthis;
     }
 
-    periodic_chores();
+    HealthInfo info;
+    convertToHealthInfo(props, info);
+    gHealth->update(info,
+            [=, &logthis] (int32_t ret, const auto &infoOut) {
+                logthis = ret;
+                convertFromHealthInfo(infoOut, props);
+            });
+
+    return logthis;
 }
 
-static void wakealarm_init(void) {
-    wakealarm_fd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK);
-    if (wakealarm_fd == -1) {
-        KLOG_ERROR(LOG_TAG, "wakealarm_init: timerfd_create failed\n");
-        return;
-    }
+int main(int /*argc*/, char ** /*argv*/) {
 
-    if (healthd_register_event(wakealarm_fd, wakealarm_event, EVENT_WAKEUP_FD))
-        KLOG_ERROR(LOG_TAG,
-                   "Registration of wakealarm event failed\n");
-
-    wakealarm_set_interval(healthd_config.periodic_chores_interval_fast);
-}
-
-static void healthd_mainloop(void) {
-    int nevents = 0;
-    while (1) {
-        struct epoll_event events[eventct];
-        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;
-            KLOG_ERROR(LOG_TAG, "healthd_mainloop: epoll_wait failed\n");
-            break;
-        }
-
-        for (int n = 0; n < nevents; ++n) {
-            if (events[n].data.ptr)
-                (*(void (*)(int))events[n].data.ptr)(events[n].events);
-        }
-    }
-
-    return;
-}
-
-static int healthd_init() {
-    epollfd = epoll_create(MAX_EPOLL_EVENTS);
-    if (epollfd == -1) {
-        KLOG_ERROR(LOG_TAG,
-                   "epoll_create failed; errno=%d\n",
-                   errno);
-        return -1;
-    }
-
-    healthd_board_init(&healthd_config);
-    healthd_mode_ops->init(&healthd_config);
-    wakealarm_init();
-    uevent_init();
-    gBatteryMonitor = new BatteryMonitor();
-    gBatteryMonitor->init(&healthd_config);
-    return 0;
-}
-
-int main(int argc, char **argv) {
-    int ch;
-    int ret;
-
-    klog_set_level(KLOG_LEVEL);
     healthd_mode_ops = &android_ops;
 
-    if (!strcmp(basename(argv[0]), "charger")) {
-        healthd_mode_ops = &charger_ops;
-    } else {
-        while ((ch = getopt(argc, argv, "cr")) != -1) {
-            switch (ch) {
-            case 'c':
-                healthd_mode_ops = &charger_ops;
-                break;
-            case 'r':
-                healthd_mode_ops = &recovery_ops;
-                break;
-            case '?':
-            default:
-                KLOG_ERROR(LOG_TAG, "Unrecognized healthd option: %c\n",
-                           optopt);
-                exit(1);
-            }
-        }
-    }
-
-    ret = healthd_init();
-    if (ret) {
-        KLOG_ERROR("Initialization failed, exiting\n");
-        exit(2);
-    }
-
-    healthd_mainloop();
-    KLOG_ERROR("Main loop terminated, exiting\n");
-    return 3;
+    return healthd_main();
 }
diff --git a/healthd/healthd_board_default.cpp b/healthd/healthd_board_default.cpp
deleted file mode 100644
index eb55773..0000000
--- a/healthd/healthd_board_default.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <healthd/healthd.h>
-
-void healthd_board_init(struct healthd_config*)
-{
-    // use defaults
-}
-
-
-int healthd_board_battery_update(struct android::BatteryProperties*)
-{
-    // return 0 to log periodic polled battery status to kernel log
-    return 0;
-}
diff --git a/healthd/healthd_common.cpp b/healthd/healthd_common.cpp
new file mode 100644
index 0000000..6599919
--- /dev/null
+++ b/healthd/healthd_common.cpp
@@ -0,0 +1,304 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "healthd-common"
+#define KLOG_LEVEL 6
+
+#include <healthd/healthd.h>
+#include <healthd/BatteryMonitor.h>
+
+#include <errno.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <batteryservice/BatteryService.h>
+#include <cutils/klog.h>
+#include <cutils/uevent.h>
+#include <sys/epoll.h>
+#include <sys/timerfd.h>
+#include <utils/Errors.h>
+
+using namespace android;
+
+#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,
+    .periodic_chores_interval_slow = DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW,
+    .batteryStatusPath = String8(String8::kEmptyString),
+    .batteryHealthPath = String8(String8::kEmptyString),
+    .batteryPresentPath = String8(String8::kEmptyString),
+    .batteryCapacityPath = String8(String8::kEmptyString),
+    .batteryVoltagePath = String8(String8::kEmptyString),
+    .batteryTemperaturePath = String8(String8::kEmptyString),
+    .batteryTechnologyPath = String8(String8::kEmptyString),
+    .batteryCurrentNowPath = String8(String8::kEmptyString),
+    .batteryCurrentAvgPath = String8(String8::kEmptyString),
+    .batteryChargeCounterPath = String8(String8::kEmptyString),
+    .batteryFullChargePath = String8(String8::kEmptyString),
+    .batteryCycleCountPath = String8(String8::kEmptyString),
+    .energyCounter = NULL,
+    .boot_min_cap = 0,
+    .screen_on = NULL,
+};
+
+static int eventct;
+static int epollfd;
+
+#define POWER_SUPPLY_SUBSYSTEM "power_supply"
+
+// epoll_create() parameter is actually unused
+#define MAX_EPOLL_EVENTS 40
+static int uevent_fd;
+static int wakealarm_fd;
+
+// -1 for no epoll timeout
+static int awake_poll_interval = -1;
+
+static int wakealarm_wake_interval = DEFAULT_PERIODIC_CHORES_INTERVAL_FAST;
+
+static BatteryMonitor* gBatteryMonitor;
+
+struct healthd_mode_ops *healthd_mode_ops;
+
+int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup) {
+    struct epoll_event ev;
+
+    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,
+                   "epoll_ctl failed; errno=%d\n", errno);
+        return -1;
+    }
+
+    eventct++;
+    return 0;
+}
+
+static void wakealarm_set_interval(int interval) {
+    struct itimerspec itval;
+
+    if (wakealarm_fd == -1)
+            return;
+
+    wakealarm_wake_interval = interval;
+
+    if (interval == -1)
+        interval = 0;
+
+    itval.it_interval.tv_sec = interval;
+    itval.it_interval.tv_nsec = 0;
+    itval.it_value.tv_sec = interval;
+    itval.it_value.tv_nsec = 0;
+
+    if (timerfd_settime(wakealarm_fd, 0, &itval, NULL) == -1)
+        KLOG_ERROR(LOG_TAG, "wakealarm_set_interval: timerfd_settime failed\n");
+}
+
+status_t healthd_get_property(int id, struct BatteryProperty *val) {
+    return gBatteryMonitor->getProperty(id, val);
+}
+
+void healthd_battery_update(void) {
+    // Fast wake interval when on charger (watch for overheat);
+    // slow wake interval when on battery (watch for drained battery).
+
+   int new_wake_interval = gBatteryMonitor->update() ?
+       healthd_config.periodic_chores_interval_fast :
+           healthd_config.periodic_chores_interval_slow;
+
+    if (new_wake_interval != wakealarm_wake_interval)
+            wakealarm_set_interval(new_wake_interval);
+
+    // During awake periods poll at fast rate.  If wake alarm is set at fast
+    // rate then just use the alarm; if wake alarm is set at slow rate then
+    // poll at fast rate while awake and let alarm wake up at slow rate when
+    // asleep.
+
+    if (healthd_config.periodic_chores_interval_fast == -1)
+        awake_poll_interval = -1;
+    else
+        awake_poll_interval =
+            new_wake_interval == healthd_config.periodic_chores_interval_fast ?
+                -1 : healthd_config.periodic_chores_interval_fast * 1000;
+}
+
+void healthd_dump_battery_state(int fd) {
+    gBatteryMonitor->dumpState(fd);
+    fsync(fd);
+}
+
+static void periodic_chores() {
+    healthd_battery_update();
+}
+
+#define UEVENT_MSG_LEN 2048
+static void uevent_event(uint32_t /*epevents*/) {
+    char msg[UEVENT_MSG_LEN+2];
+    char *cp;
+    int n;
+
+    n = uevent_kernel_multicast_recv(uevent_fd, msg, UEVENT_MSG_LEN);
+    if (n <= 0)
+        return;
+    if (n >= UEVENT_MSG_LEN)   /* overflow -- discard */
+        return;
+
+    msg[n] = '\0';
+    msg[n+1] = '\0';
+    cp = msg;
+
+    while (*cp) {
+        if (!strcmp(cp, "SUBSYSTEM=" POWER_SUPPLY_SUBSYSTEM)) {
+            healthd_battery_update();
+            break;
+        }
+
+        /* advance to after the next \0 */
+        while (*cp++)
+            ;
+    }
+}
+
+static void uevent_init(void) {
+    uevent_fd = uevent_open_socket(64*1024, true);
+
+    if (uevent_fd < 0) {
+        KLOG_ERROR(LOG_TAG, "uevent_init: uevent_open_socket failed\n");
+        return;
+    }
+
+    fcntl(uevent_fd, F_SETFL, O_NONBLOCK);
+    if (healthd_register_event(uevent_fd, uevent_event, EVENT_WAKEUP_FD))
+        KLOG_ERROR(LOG_TAG,
+                   "register for uevent events failed\n");
+}
+
+static void wakealarm_event(uint32_t /*epevents*/) {
+    unsigned long long wakeups;
+
+    if (read(wakealarm_fd, &wakeups, sizeof(wakeups)) == -1) {
+        KLOG_ERROR(LOG_TAG, "wakealarm_event: read wakealarm fd failed\n");
+        return;
+    }
+
+    periodic_chores();
+}
+
+static void wakealarm_init(void) {
+    wakealarm_fd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK);
+    if (wakealarm_fd == -1) {
+        KLOG_ERROR(LOG_TAG, "wakealarm_init: timerfd_create failed\n");
+        return;
+    }
+
+    if (healthd_register_event(wakealarm_fd, wakealarm_event, EVENT_WAKEUP_FD))
+        KLOG_ERROR(LOG_TAG,
+                   "Registration of wakealarm event failed\n");
+
+    wakealarm_set_interval(healthd_config.periodic_chores_interval_fast);
+}
+
+static void healthd_mainloop(void) {
+    int nevents = 0;
+    while (1) {
+        struct epoll_event events[eventct];
+        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;
+            KLOG_ERROR(LOG_TAG, "healthd_mainloop: epoll_wait failed\n");
+            break;
+        }
+
+        for (int n = 0; n < nevents; ++n) {
+            if (events[n].data.ptr)
+                (*(void (*)(int))events[n].data.ptr)(events[n].events);
+        }
+    }
+
+    return;
+}
+
+static int healthd_init() {
+    epollfd = epoll_create(MAX_EPOLL_EVENTS);
+    if (epollfd == -1) {
+        KLOG_ERROR(LOG_TAG,
+                   "epoll_create failed; errno=%d\n",
+                   errno);
+        return -1;
+    }
+
+    healthd_board_init(&healthd_config);
+    healthd_mode_ops->init(&healthd_config);
+    wakealarm_init();
+    uevent_init();
+    gBatteryMonitor = new BatteryMonitor();
+    gBatteryMonitor->init(&healthd_config);
+    return 0;
+}
+
+int healthd_main() {
+    int ret;
+
+    klog_set_level(KLOG_LEVEL);
+
+    if (!healthd_mode_ops) {
+        KLOG_ERROR("healthd ops not set, exiting\n");
+        exit(1);
+    }
+
+    ret = healthd_init();
+    if (ret) {
+        KLOG_ERROR("Initialization failed, exiting\n");
+        exit(2);
+    }
+
+    healthd_mainloop();
+    KLOG_ERROR("Main loop terminated, exiting\n");
+    return 3;
+}
diff --git a/healthd/healthd_mode_android.cpp b/healthd/healthd_mode_android.cpp
index 323ef52..c612313 100644
--- a/healthd/healthd_mode_android.cpp
+++ b/healthd/healthd_mode_android.cpp
@@ -42,6 +42,9 @@
     return -1;
 }
 
+void healthd_mode_android_heartbeat(void) {
+}
+
 static void binder_event(uint32_t /*epevents*/) {
     IPCThreadState::self()->handlePolledCommands();
 }
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index ccf948b..49a534c 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -30,6 +30,8 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <functional>
+
 #include <android-base/file.h>
 #include <android-base/stringprintf.h>
 
@@ -37,11 +39,12 @@
 #include <linux/netlink.h>
 
 #include <batteryservice/BatteryService.h>
-#include <cutils/android_reboot.h>
 #include <cutils/klog.h>
 #include <cutils/misc.h>
 #include <cutils/uevent.h>
 #include <cutils/properties.h>
+#include <minui/minui.h>
+#include <sys/reboot.h>
 
 #ifdef CHARGER_ENABLE_SUSPEND
 #include <suspend/autosuspend.h>
@@ -49,7 +52,6 @@
 
 #include "animation.h"
 #include "AnimationParser.h"
-#include "minui/minui.h"
 
 #include <healthd/healthd.h>
 
@@ -65,7 +67,7 @@
 #define min(a,b) ((a) < (b) ? (a) : (b))
 #endif
 
-#define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
+#define ARRAY_SIZE(x)           (sizeof(x)/sizeof((x)[0]))
 
 #define MSEC_PER_SEC            (1000LL)
 #define NSEC_PER_MSEC           (1000000LL)
@@ -568,9 +570,8 @@
     }
 }
 
-static int set_key_callback(int code, int value, void *data)
+static int set_key_callback(struct charger *charger, int code, int value)
 {
-    struct charger *charger = (struct charger *)data;
     int64_t now = curr_time_ms();
     int down = !!value;
 
@@ -605,7 +606,7 @@
 {
     if (ev->type != EV_KEY)
         return;
-    set_key_callback(ev->code, ev->value, charger);
+    set_key_callback(charger, ev->code, ev->value);
 }
 
 static void set_next_key_check(struct charger *charger,
@@ -635,7 +636,7 @@
                 } else {
                     if (charger->batt_anim->cur_level >= charger->boot_min_cap) {
                         LOGW("[%" PRId64 "] rebooting\n", now);
-                        android_reboot(ANDROID_RB_RESTART, 0, 0);
+                        reboot(RB_AUTOBOOT);
                     } else {
                         LOGV("[%" PRId64 "] ignore power-button press, battery level "
                             "less than minimum\n", now);
@@ -690,7 +691,7 @@
                  now, (int64_t)UNPLUGGED_SHUTDOWN_TIME, charger->next_pwr_check);
         } else if (now >= charger->next_pwr_check) {
             LOGW("[%" PRId64 "] shutting down\n", now);
-            android_reboot(ANDROID_RB_POWEROFF, 0, 0);
+            reboot(RB_POWER_OFF);
         } else {
             /* otherwise we already have a shutdown timer scheduled */
         }
@@ -762,9 +763,8 @@
    return (int)timeout;
 }
 
-static int input_callback(int fd, unsigned int epevents, void *data)
+static int input_callback(struct charger *charger, int fd, unsigned int epevents)
 {
-    struct charger *charger = (struct charger *)data;
     struct input_event ev;
     int ret;
 
@@ -841,7 +841,8 @@
 
     LOGW("--------------- STARTING CHARGER MODE ---------------\n");
 
-    ret = ev_init(input_callback, charger);
+    ret = ev_init(std::bind(&input_callback, charger, std::placeholders::_1,
+                            std::placeholders::_2));
     if (!ret) {
         epollfd = ev_get_epollfd();
         healthd_register_event(epollfd, charger_event_handler, EVENT_WAKEUP_FD);
@@ -880,7 +881,8 @@
             anim->frames[i].surface = scale_frames[i];
         }
     }
-    ev_sync_key_state(set_key_callback, charger);
+    ev_sync_key_state(std::bind(&set_key_callback, charger, std::placeholders::_1,
+                                std::placeholders::_2));
 
     charger->next_screen_transition = -1;
     charger->next_key_check = -1;
diff --git a/healthd/include/healthd/BatteryMonitor.h b/healthd/include/healthd/BatteryMonitor.h
index 440f2e4..8865a7d 100644
--- a/healthd/include/healthd/BatteryMonitor.h
+++ b/healthd/include/healthd/BatteryMonitor.h
@@ -55,7 +55,7 @@
 
     int getBatteryStatus(const char* status);
     int getBatteryHealth(const char* status);
-    int readFromFile(const String8& path, char* buf, size_t size);
+    int readFromFile(const String8& path, std::string* buf);
     PowerSupplyType readPowerSupplyType(const String8& path);
     bool getBooleanField(const String8& path);
     int getIntField(const String8& path);
diff --git a/include/android/log.h b/include/android/log.h
deleted file mode 100644
index 391c826..0000000
--- a/include/android/log.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (C) 2009 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_LOG_H
-#define _ANDROID_LOG_H
-
-/******************************************************************
- *
- * IMPORTANT NOTICE:
- *
- *   This file is part of Android's set of stable system headers
- *   exposed by the Android NDK (Native Development Kit) since
- *   platform release 1.5
- *
- *   Third-party source AND binary code relies on the definitions
- *   here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
- *
- *   - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
- *   - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
- *   - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
- *   - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
- */
-
-/*
- * Support routines to send messages to the Android in-kernel log buffer,
- * which can later be accessed through the 'logcat' utility.
- *
- * Each log message must have
- *   - a priority
- *   - a log tag
- *   - some text
- *
- * The tag normally corresponds to the component that emits the log message,
- * and should be reasonably small.
- *
- * Log message text may be truncated to less than an implementation-specific
- * limit (e.g. 1023 characters max).
- *
- * Note that a newline character ("\n") will be appended automatically to your
- * log message, if not already there. It is not possible to send several messages
- * and have them appear on a single line in logcat.
- *
- * PLEASE USE LOGS WITH MODERATION:
- *
- *  - Sending log messages eats CPU and slow down your application and the
- *    system.
- *
- *  - The circular log buffer is pretty small (<64KB), sending many messages
- *    might push off other important log messages from the rest of the system.
- *
- *  - In release builds, only send log messages to account for exceptional
- *    conditions.
- *
- * NOTE: These functions MUST be implemented by /system/lib/liblog.so
- */
-
-#include <stdarg.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Android log priority values, in ascending priority order.
- */
-typedef enum android_LogPriority {
-    ANDROID_LOG_UNKNOWN = 0,
-    ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
-    ANDROID_LOG_VERBOSE,
-    ANDROID_LOG_DEBUG,
-    ANDROID_LOG_INFO,
-    ANDROID_LOG_WARN,
-    ANDROID_LOG_ERROR,
-    ANDROID_LOG_FATAL,
-    ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
-} android_LogPriority;
-
-/*
- * Release any logger resources (a new log write will immediately re-acquire)
- */
-void __android_log_close();
-
-/*
- * Send a simple string to the log.
- */
-int __android_log_write(int prio, const char *tag, const char *text);
-
-/*
- * Send a formatted string to the log, used like printf(fmt,...)
- */
-int __android_log_print(int prio, const char *tag,  const char *fmt, ...)
-#if defined(__GNUC__)
-#ifdef __USE_MINGW_ANSI_STDIO
-#if __USE_MINGW_ANSI_STDIO
-    __attribute__ ((format(gnu_printf, 3, 4)))
-#else
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-#else
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-#endif
-    ;
-
-/*
- * A variant of __android_log_print() that takes a va_list to list
- * additional parameters.
- */
-int __android_log_vprint(int prio, const char *tag,
-                         const char *fmt, va_list ap);
-
-/*
- * Log an assertion failure and abort the process to have a chance
- * to inspect it if a debugger is attached. This uses the FATAL priority.
- */
-void __android_log_assert(const char *cond, const char *tag,
-                          const char *fmt, ...)
-#if defined(__GNUC__)
-    __attribute__ ((noreturn))
-#ifdef __USE_MINGW_ANSI_STDIO
-#if __USE_MINGW_ANSI_STDIO
-    __attribute__ ((format(gnu_printf, 3, 4)))
-#else
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-#else
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-#endif
-    ;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _ANDROID_LOG_H */
diff --git a/include/android/log.h b/include/android/log.h
new file mode 120000
index 0000000..736c448
--- /dev/null
+++ b/include/android/log.h
@@ -0,0 +1 @@
+../../liblog/include/android/log.h
\ No newline at end of file
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/backtrace/Backtrace.h b/include/backtrace/Backtrace.h
deleted file mode 100644
index c896ab8..0000000
--- a/include/backtrace/Backtrace.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BACKTRACE_BACKTRACE_H
-#define _BACKTRACE_BACKTRACE_H
-
-#include <inttypes.h>
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include <backtrace/backtrace_constants.h>
-#include <backtrace/BacktraceMap.h>
-
-#if __LP64__
-#define PRIPTR "016" PRIxPTR
-typedef uint64_t word_t;
-#else
-#define PRIPTR "08" PRIxPTR
-typedef uint32_t word_t;
-#endif
-
-enum BacktraceUnwindError : uint32_t {
-  BACKTRACE_UNWIND_NO_ERROR,
-  // Something failed while trying to perform the setup to begin the unwind.
-  BACKTRACE_UNWIND_ERROR_SETUP_FAILED,
-  // There is no map information to use with the unwind.
-  BACKTRACE_UNWIND_ERROR_MAP_MISSING,
-  // An error occurred that indicates a programming error.
-  BACKTRACE_UNWIND_ERROR_INTERNAL,
-  // The thread to unwind has disappeared before the unwind can begin.
-  BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST,
-  // The thread to unwind has not responded to a signal in a timely manner.
-  BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT,
-  // Attempt to do an unsupported operation.
-  BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION,
-  // Attempt to do an offline unwind without a context.
-  BACKTRACE_UNWIND_ERROR_NO_CONTEXT,
-};
-
-struct backtrace_frame_data_t {
-  size_t num;             // The current fame number.
-  uintptr_t pc;           // The absolute pc.
-  uintptr_t sp;           // The top of the stack.
-  size_t stack_size;      // The size of the stack, zero indicate an unknown stack size.
-  backtrace_map_t map;    // The map associated with the given pc.
-  std::string func_name;  // The function name associated with this pc, NULL if not found.
-  uintptr_t func_offset;  // pc relative to the start of the function, only valid if func_name is not NULL.
-};
-
-#if defined(__APPLE__)
-struct __darwin_ucontext;
-typedef __darwin_ucontext ucontext_t;
-#else
-struct ucontext;
-typedef ucontext ucontext_t;
-#endif
-
-struct backtrace_stackinfo_t {
-  uint64_t start;
-  uint64_t end;
-  const uint8_t* data;
-};
-
-class Backtrace {
-public:
-  // Create the correct Backtrace object based on what is to be unwound.
-  // If pid < 0 or equals the current pid, then the Backtrace object
-  // corresponds to the current process.
-  // If pid < 0 or equals the current pid and tid >= 0, then the Backtrace
-  // object corresponds to a thread in the current process.
-  // If pid >= 0 and tid < 0, then the Backtrace object corresponds to a
-  // different process.
-  // Tracing a thread in a different process is not supported.
-  // If map is NULL, then create the map and manage it internally.
-  // If map is not NULL, the map is still owned by the caller.
-  static Backtrace* Create(pid_t pid, pid_t tid, BacktraceMap* map = NULL);
-
-  // Create an offline Backtrace object that can be used to do an unwind without a process
-  // that is still running. If cache_file is set to true, then elf information will be cached
-  // for this call. The cached information survives until the calling process ends. This means
-  // that subsequent calls to create offline Backtrace objects will continue to use the same
-  // cache. It also assumes that the elf files used for each offline unwind are the same.
-  static Backtrace* CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
-                                  const backtrace_stackinfo_t& stack, bool cache_file = false);
-
-  virtual ~Backtrace();
-
-  // Get the current stack trace and store in the backtrace_ structure.
-  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);
-
-  // Fill in the map data associated with the given pc.
-  virtual void FillInMap(uintptr_t pc, backtrace_map_t* map);
-
-  // Read the data at a specific address.
-  virtual bool ReadWord(uintptr_t ptr, word_t* out_value) = 0;
-
-  // Read arbitrary data from a specific address. If a read request would
-  // span from one map to another, this call only reads up until the end
-  // of the current map.
-  // Returns the total number of bytes actually read.
-  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) = 0;
-
-  // Create a string representing the formatted line of backtrace information
-  // for a single frame.
-  virtual std::string FormatFrameData(size_t frame_num);
-  virtual std::string FormatFrameData(const backtrace_frame_data_t* frame);
-
-  pid_t Pid() const { return pid_; }
-  pid_t Tid() const { return tid_; }
-  size_t NumFrames() const { return frames_.size(); }
-
-  const backtrace_frame_data_t* GetFrame(size_t frame_num) {
-    if (frame_num >= frames_.size()) {
-      return NULL;
-    }
-    return &frames_[frame_num];
-  }
-
-  typedef std::vector<backtrace_frame_data_t>::iterator iterator;
-  iterator begin() { return frames_.begin(); }
-  iterator end() { return frames_.end(); }
-
-  typedef std::vector<backtrace_frame_data_t>::const_iterator const_iterator;
-  const_iterator begin() const { return frames_.begin(); }
-  const_iterator end() const { return frames_.end(); }
-
-  BacktraceMap* GetMap() { return map_; }
-
-  BacktraceUnwindError GetError() { return error_; }
-
-  std::string GetErrorString(BacktraceUnwindError error);
-
-protected:
-  Backtrace(pid_t pid, pid_t tid, BacktraceMap* map);
-
-  // The name returned is not demangled, GetFunctionName() takes care of
-  // demangling the name.
-  virtual std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) = 0;
-
-  virtual bool VerifyReadWordArgs(uintptr_t ptr, word_t* out_value);
-
-  bool BuildMap();
-
-  pid_t pid_;
-  pid_t tid_;
-
-  BacktraceMap* map_;
-  bool map_shared_;
-
-  std::vector<backtrace_frame_data_t> frames_;
-
-  BacktraceUnwindError error_;
-};
-
-#endif // _BACKTRACE_BACKTRACE_H
diff --git a/include/backtrace/BacktraceMap.h b/include/backtrace/BacktraceMap.h
deleted file mode 100644
index b80045f..0000000
--- a/include/backtrace/BacktraceMap.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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 _BACKTRACE_BACKTRACE_MAP_H
-#define _BACKTRACE_BACKTRACE_MAP_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#ifdef USE_MINGW
-// MINGW does not define these constants.
-#define PROT_NONE 0
-#define PROT_READ 0x1
-#define PROT_WRITE 0x2
-#define PROT_EXEC 0x4
-#else
-#include <sys/mman.h>
-#endif
-
-#include <deque>
-#include <string>
-#include <vector>
-
-struct backtrace_map_t {
-  uintptr_t start = 0;
-  uintptr_t end = 0;
-  uintptr_t offset = 0;
-  uintptr_t load_base = 0;
-  int flags = 0;
-  std::string name;
-};
-
-class BacktraceMap {
-public:
-  // If uncached is true, then parse the current process map as of the call.
-  // Passing a map created with uncached set to true to Backtrace::Create()
-  // is unsupported.
-  static BacktraceMap* Create(pid_t pid, bool uncached = false);
-
-  static BacktraceMap* Create(pid_t pid, const std::vector<backtrace_map_t>& maps);
-
-  virtual ~BacktraceMap();
-
-  // Fill in the map data structure for the given address.
-  virtual void FillIn(uintptr_t addr, backtrace_map_t* map);
-
-  // The flags returned are the same flags as used by the mmap call.
-  // The values are PROT_*.
-  int GetFlags(uintptr_t pc) {
-    backtrace_map_t map;
-    FillIn(pc, &map);
-    if (IsValid(map)) {
-      return map.flags;
-    }
-    return PROT_NONE;
-  }
-
-  bool IsReadable(uintptr_t pc) { return GetFlags(pc) & PROT_READ; }
-  bool IsWritable(uintptr_t pc) { return GetFlags(pc) & PROT_WRITE; }
-  bool IsExecutable(uintptr_t pc) { return GetFlags(pc) & PROT_EXEC; }
-
-  // In order to use the iterators on this object, a caller must
-  // call the LockIterator and UnlockIterator function to guarantee
-  // that the data does not change while it's being used.
-  virtual void LockIterator() {}
-  virtual void UnlockIterator() {}
-
-  typedef std::deque<backtrace_map_t>::iterator iterator;
-  iterator begin() { return maps_.begin(); }
-  iterator end() { return maps_.end(); }
-
-  typedef std::deque<backtrace_map_t>::const_iterator const_iterator;
-  const_iterator begin() const { return maps_.begin(); }
-  const_iterator end() const { return maps_.end(); }
-
-  virtual bool Build();
-
-  static inline bool IsValid(const backtrace_map_t& map) {
-    return map.end > 0;
-  }
-
-  static uintptr_t GetRelativePc(const backtrace_map_t& map, uintptr_t pc) {
-    if (IsValid(map)) {
-      return pc - map.start + map.load_base;
-    } else {
-      return pc;
-    }
-  }
-
-protected:
-  BacktraceMap(pid_t pid);
-
-  virtual bool ParseLine(const char* line, backtrace_map_t* map);
-
-  std::deque<backtrace_map_t> maps_;
-  pid_t pid_;
-};
-
-class ScopedBacktraceMapIteratorLock {
-public:
-  explicit ScopedBacktraceMapIteratorLock(BacktraceMap* map) : map_(map) {
-    map->LockIterator();
-  }
-
-  ~ScopedBacktraceMapIteratorLock() {
-    map_->UnlockIterator();
-  }
-
-private:
-  BacktraceMap* map_;
-};
-
-#endif // _BACKTRACE_BACKTRACE_MAP_H
diff --git a/include/binderwrapper/binder_wrapper.h b/include/binderwrapper/binder_wrapper.h
deleted file mode 100644
index ccda825..0000000
--- a/include/binderwrapper/binder_wrapper.h
+++ /dev/null
@@ -1,88 +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.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
-#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
-
-#include <sys/types.h>
-
-#include <string>
-
-#include <base/callback.h>
-#include <utils/StrongPointer.h>
-
-namespace android {
-
-class BBinder;
-class IBinder;
-
-// Wraps libbinder to make it testable.
-// NOTE: Static methods of this class are not thread-safe.
-class BinderWrapper {
- public:
-  virtual ~BinderWrapper() {}
-
-  // Creates and initializes the singleton (using a wrapper that communicates
-  // with the real binder system).
-  static void Create();
-
-  // Initializes |wrapper| as the singleton, taking ownership of it. Tests that
-  // want to inject their own wrappers should call this instead of Create().
-  static void InitForTesting(BinderWrapper* wrapper);
-
-  // Destroys the singleton. Must be called before calling Create() or
-  // InitForTesting() a second time.
-  static void Destroy();
-
-  // Returns the singleton instance previously created by Create() or set by
-  // InitForTesting().
-  static BinderWrapper* Get();
-
-  // Returns the singleton instance if it was previously created by Create() or
-  // set by InitForTesting(), or creates a new one by calling Create().
-  static BinderWrapper* GetOrCreateInstance();
-
-  // Gets the binder for communicating with the service identified by
-  // |service_name|, returning null immediately if it doesn't exist.
-  virtual sp<IBinder> GetService(const std::string& service_name) = 0;
-
-  // Registers |binder| as |service_name| with the service manager.
-  virtual bool RegisterService(const std::string& service_name,
-                               const sp<IBinder>& binder) = 0;
-
-  // Creates a local binder object.
-  virtual sp<BBinder> CreateLocalBinder() = 0;
-
-  // Registers |callback| to be invoked when |binder| dies. If another callback
-  // is currently registered for |binder|, it will be replaced.
-  virtual bool RegisterForDeathNotifications(
-      const sp<IBinder>& binder,
-      const base::Closure& callback) = 0;
-
-  // Unregisters the callback, if any, for |binder|.
-  virtual bool UnregisterForDeathNotifications(const sp<IBinder>& binder) = 0;
-
-  // When called while in a transaction, returns the caller's UID or PID.
-  virtual uid_t GetCallingUid() = 0;
-  virtual pid_t GetCallingPid() = 0;
-
- private:
-  static BinderWrapper* instance_;
-};
-
-}  // namespace android
-
-#endif  // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
diff --git a/include/binderwrapper/stub_binder_wrapper.h b/include/binderwrapper/stub_binder_wrapper.h
deleted file mode 100644
index 01c9648..0000000
--- a/include/binderwrapper/stub_binder_wrapper.h
+++ /dev/null
@@ -1,133 +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.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
-#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
-
-#include <map>
-#include <string>
-#include <vector>
-
-#include <base/macros.h>
-#include <binder/Binder.h>
-#include <binder/IBinder.h>
-#include <binderwrapper/binder_wrapper.h>
-
-namespace android {
-
-// Stub implementation of BinderWrapper for testing.
-//
-// Example usage:
-//
-// First, assuming a base IFoo binder interface, create a stub class that
-// derives from BnFoo to implement the receiver side of the communication:
-//
-//   class StubFoo : public BnFoo {
-//    public:
-//     ...
-//     status_t doSomething(int arg) override {
-//       // e.g. save passed-in value for later inspection by tests.
-//       return OK;
-//     }
-//   };
-//
-// Next, from your test code, inject a StubBinderManager either directly or by
-// inheriting from the BinderTestBase class:
-//
-//   StubBinderWrapper* wrapper = new StubBinderWrapper();
-//   BinderWrapper::InitForTesting(wrapper);  // Takes ownership.
-//
-// Also from your test, create a StubFoo and register it with the wrapper:
-//
-//   StubFoo* foo = new StubFoo();
-//   sp<IBinder> binder(foo);
-//   wrapper->SetBinderForService("foo", binder);
-//
-// The code being tested can now use the wrapper to get the stub and call it:
-//
-//   sp<IBinder> binder = BinderWrapper::Get()->GetService("foo");
-//   CHECK(binder.get());
-//   sp<IFoo> foo = interface_cast<IFoo>(binder);
-//   CHECK_EQ(foo->doSomething(3), OK);
-//
-// To create a local BBinder object, production code can call
-// CreateLocalBinder(). Then, a test can get the BBinder's address via
-// local_binders() to check that they're passed as expected in binder calls.
-//
-class StubBinderWrapper : public BinderWrapper {
- public:
-  StubBinderWrapper();
-  ~StubBinderWrapper() override;
-
-  const std::vector<sp<BBinder>>& local_binders() const {
-    return local_binders_;
-  }
-  void clear_local_binders() { local_binders_.clear(); }
-
-  void set_calling_uid(uid_t uid) { calling_uid_ = uid; }
-  void set_calling_pid(pid_t pid) { calling_pid_ = pid; }
-
-  // Sets the binder to return when |service_name| is passed to GetService() or
-  // WaitForService().
-  void SetBinderForService(const std::string& service_name,
-                           const sp<IBinder>& binder);
-
-  // Returns the binder previously registered for |service_name| via
-  // RegisterService(), or null if the service hasn't been registered.
-  sp<IBinder> GetRegisteredService(const std::string& service_name) const;
-
-  // Run the calback in |death_callbacks_| corresponding to |binder|.
-  void NotifyAboutBinderDeath(const sp<IBinder>& binder);
-
-  // BinderWrapper:
-  sp<IBinder> GetService(const std::string& service_name) override;
-  bool RegisterService(const std::string& service_name,
-                       const sp<IBinder>& binder) override;
-  sp<BBinder> CreateLocalBinder() override;
-  bool RegisterForDeathNotifications(const sp<IBinder>& binder,
-                                     const base::Closure& callback) override;
-  bool UnregisterForDeathNotifications(const sp<IBinder>& binder) override;
-  uid_t GetCallingUid() override;
-  pid_t GetCallingPid() override;
-
- private:
-  using ServiceMap = std::map<std::string, sp<IBinder>>;
-
-  // Map from service name to associated binder handle. Used by GetService() and
-  // WaitForService().
-  ServiceMap services_to_return_;
-
-  // Map from service name to associated binder handle. Updated by
-  // RegisterService().
-  ServiceMap registered_services_;
-
-  // Local binders returned by CreateLocalBinder().
-  std::vector<sp<BBinder>> local_binders_;
-
-  // Map from binder handle to the callback that should be invoked on binder
-  // death.
-  std::map<sp<IBinder>, base::Closure> death_callbacks_;
-
-  // Values to return from GetCallingUid() and GetCallingPid();
-  uid_t calling_uid_;
-  pid_t calling_pid_;
-
-  DISALLOW_COPY_AND_ASSIGN(StubBinderWrapper);
-};
-
-}  // namespace android
-
-#endif  // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
diff --git a/include/cutils b/include/cutils
new file mode 120000
index 0000000..ac2ed40
--- /dev/null
+++ b/include/cutils
@@ -0,0 +1 @@
+../libcutils/include/cutils/
\ No newline at end of file
diff --git a/include/cutils/android_reboot.h b/include/cutils/android_reboot.h
deleted file mode 100644
index a3861a0..0000000
--- a/include/cutils/android_reboot.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 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 __CUTILS_ANDROID_REBOOT_H__
-#define __CUTILS_ANDROID_REBOOT_H__
-
-#include <mntent.h>
-
-__BEGIN_DECLS
-
-/* Commands */
-#define ANDROID_RB_RESTART  0xDEAD0001
-#define ANDROID_RB_POWEROFF 0xDEAD0002
-#define ANDROID_RB_RESTART2 0xDEAD0003
-
-/* Properties */
-#define ANDROID_RB_PROPERTY "sys.powerctl"
-
-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
-
-#endif /* __CUTILS_ANDROID_REBOOT_H__ */
diff --git a/include/cutils/ashmem.h b/include/cutils/ashmem.h
deleted file mode 100644
index 25b233e..0000000
--- a/include/cutils/ashmem.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* cutils/ashmem.h
- **
- ** Copyright 2008 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 _CUTILS_ASHMEM_H
-#define _CUTILS_ASHMEM_H
-
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int ashmem_create_region(const char *name, size_t size);
-int ashmem_set_prot_region(int fd, int prot);
-int ashmem_pin_region(int fd, size_t offset, size_t len);
-int ashmem_unpin_region(int fd, size_t offset, size_t len);
-int ashmem_get_size_region(int fd);
-
-#ifdef __cplusplus
-}
-#endif
-
-#ifndef __ASHMEMIOC	/* in case someone included <linux/ashmem.h> too */
-
-#define ASHMEM_NAME_LEN		256
-
-#define ASHMEM_NAME_DEF		"dev/ashmem"
-
-/* Return values from ASHMEM_PIN: Was the mapping purged while unpinned? */
-#define ASHMEM_NOT_PURGED	0
-#define ASHMEM_WAS_PURGED	1
-
-/* Return values from ASHMEM_UNPIN: Is the mapping now pinned or unpinned? */
-#define ASHMEM_IS_UNPINNED	0
-#define ASHMEM_IS_PINNED	1
-
-#endif	/* ! __ASHMEMIOC */
-
-#endif	/* _CUTILS_ASHMEM_H */
diff --git a/include/cutils/atomic.h b/include/cutils/atomic.h
deleted file mode 100644
index ded972a..0000000
--- a/include/cutils/atomic.h
+++ /dev/null
@@ -1,237 +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.
- */
-
-#ifndef ANDROID_CUTILS_ATOMIC_H
-#define ANDROID_CUTILS_ATOMIC_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <stdatomic.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE static inline
-#endif
-
-/*
- * A handful of basic atomic operations.
- * THESE ARE HERE FOR LEGACY REASONS ONLY.  AVOID.
- *
- * PREFERRED ALTERNATIVES:
- * - Use C++/C/pthread locks/mutexes whenever there is not a
- *   convincing reason to do otherwise.  Note that very clever and
- *   complicated, but correct, lock-free code is often slower than
- *   using locks, especially where nontrivial data structures
- *   are involved.
- * - C11 stdatomic.h.
- * - Where supported, C++11 std::atomic<T> .
- *
- * PLEASE STOP READING HERE UNLESS YOU ARE TRYING TO UNDERSTAND
- * OR UPDATE OLD CODE.
- *
- * The "acquire" and "release" terms can be defined intuitively in terms
- * of the placement of memory barriers in a simple lock implementation:
- *   - wait until compare-and-swap(lock-is-free --> lock-is-held) succeeds
- *   - barrier
- *   - [do work]
- *   - barrier
- *   - store(lock-is-free)
- * In very crude terms, the initial (acquire) barrier prevents any of the
- * "work" from happening before the lock is held, and the later (release)
- * barrier ensures that all of the work happens before the lock is released.
- * (Think of cached writes, cache read-ahead, and instruction reordering
- * around the CAS and store instructions.)
- *
- * The barriers must apply to both the compiler and the CPU.  Note it is
- * legal for instructions that occur before an "acquire" barrier to be
- * moved down below it, and for instructions that occur after a "release"
- * barrier to be moved up above it.
- *
- * The ARM-driven implementation we use here is short on subtlety,
- * and actually requests a full barrier from the compiler and the CPU.
- * The only difference between acquire and release is in whether they
- * are issued before or after the atomic operation with which they
- * are associated.  To ease the transition to C/C++ atomic intrinsics,
- * you should not rely on this, and instead assume that only the minimal
- * acquire/release protection is provided.
- *
- * NOTE: all int32_t* values are expected to be aligned on 32-bit boundaries.
- * If they are not, atomicity is not guaranteed.
- */
-
-/*
- * Basic arithmetic and bitwise operations.  These all provide a
- * barrier with "release" ordering, and return the previous value.
- *
- * These have the same characteristics (e.g. what happens on overflow)
- * as the equivalent non-atomic C operations.
- */
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_inc(volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-        /* Int32_t, if it exists, is the same as int_least32_t. */
-    return atomic_fetch_add_explicit(a, 1, memory_order_release);
-}
-
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_dec(volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return atomic_fetch_sub_explicit(a, 1, memory_order_release);
-}
-
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_add(int32_t value, volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return atomic_fetch_add_explicit(a, value, memory_order_release);
-}
-
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_and(int32_t value, volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return atomic_fetch_and_explicit(a, value, memory_order_release);
-}
-
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_or(int32_t value, volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return atomic_fetch_or_explicit(a, value, memory_order_release);
-}
-
-/*
- * Perform an atomic load with "acquire" or "release" ordering.
- *
- * Note that the notion of a "release" ordering for a load does not
- * really fit into the C11 or C++11 memory model.  The extra ordering
- * is normally observable only by code using memory_order_relaxed
- * atomics, or data races.  In the rare cases in which such ordering
- * is called for, use memory_order_relaxed atomics and a leading
- * atomic_thread_fence (typically with memory_order_acquire,
- * not memory_order_release!) instead.  If you do not understand
- * this comment, you are in the vast majority, and should not be
- * using release loads or replacing them with anything other than
- * locks or default sequentially consistent atomics.
- */
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_acquire_load(volatile const int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return atomic_load_explicit(a, memory_order_acquire);
-}
-
-ANDROID_ATOMIC_INLINE
-int32_t android_atomic_release_load(volatile const int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    atomic_thread_fence(memory_order_seq_cst);
-    /* Any reasonable clients of this interface would probably prefer   */
-    /* something weaker.  But some remaining clients seem to be         */
-    /* abusing this API in strange ways, e.g. by using it as a fence.   */
-    /* Thus we are conservative until we can get rid of remaining       */
-    /* clients (and this function).                                     */
-    return atomic_load_explicit(a, memory_order_relaxed);
-}
-
-/*
- * Perform an atomic store with "acquire" or "release" ordering.
- *
- * Note that the notion of an "acquire" ordering for a store does not
- * really fit into the C11 or C++11 memory model.  The extra ordering
- * is normally observable only by code using memory_order_relaxed
- * atomics, or data races.  In the rare cases in which such ordering
- * is called for, use memory_order_relaxed atomics and a trailing
- * atomic_thread_fence (typically with memory_order_release,
- * not memory_order_acquire!) instead.
- */
-ANDROID_ATOMIC_INLINE
-void android_atomic_acquire_store(int32_t value, volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    atomic_store_explicit(a, value, memory_order_relaxed);
-    atomic_thread_fence(memory_order_seq_cst);
-    /* Again overly conservative to accomodate weird clients.   */
-}
-
-ANDROID_ATOMIC_INLINE
-void android_atomic_release_store(int32_t value, volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    atomic_store_explicit(a, value, memory_order_release);
-}
-
-/*
- * Compare-and-set operation with "acquire" or "release" ordering.
- *
- * This returns zero if the new value was successfully stored, which will
- * only happen when *addr == oldvalue.
- *
- * (The return value is inverted from implementations on other platforms,
- * but matches the ARM ldrex/strex result.)
- *
- * Implementations that use the release CAS in a loop may be less efficient
- * than possible, because we re-issue the memory barrier on each iteration.
- */
-ANDROID_ATOMIC_INLINE
-int android_atomic_acquire_cas(int32_t oldvalue, int32_t newvalue,
-                           volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return (int)(!atomic_compare_exchange_strong_explicit(
-                                          a, &oldvalue, newvalue,
-                                          memory_order_acquire,
-                                          memory_order_acquire));
-}
-
-ANDROID_ATOMIC_INLINE
-int android_atomic_release_cas(int32_t oldvalue, int32_t newvalue,
-                               volatile int32_t* addr)
-{
-    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
-    return (int)(!atomic_compare_exchange_strong_explicit(
-                                          a, &oldvalue, newvalue,
-                                          memory_order_release,
-                                          memory_order_relaxed));
-}
-
-/*
- * Fence primitives.
- */
-ANDROID_ATOMIC_INLINE
-void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-    /* Could probably also be:                          */
-    /* atomic_signal_fence(memory_order_seq_cst);       */
-}
-
-ANDROID_ATOMIC_INLINE
-void android_memory_barrier(void)
-{
-    atomic_thread_fence(memory_order_seq_cst);
-}
-
-/*
- * Aliases for code using an older version of this header.  These are now
- * deprecated and should not be used.  The definitions will be removed
- * in a future release.
- */
-#define android_atomic_write android_atomic_release_store
-#define android_atomic_cmpxchg android_atomic_release_cas
-
-#endif // ANDROID_CUTILS_ATOMIC_H
diff --git a/include/cutils/debugger.h b/include/cutils/debugger.h
deleted file mode 100644
index 285e1af..0000000
--- a/include/cutils/debugger.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __CUTILS_DEBUGGER_H
-#define __CUTILS_DEBUGGER_H
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-__BEGIN_DECLS
-
-#define DEBUGGER_SOCKET_NAME "android:debuggerd"
-#define DEBUGGER32_SOCKET_NAME "android:debuggerd32"
-#define DEBUGGER64_SOCKET_NAME DEBUGGER_SOCKET_NAME
-
-typedef enum {
-    // dump a crash
-    DEBUGGER_ACTION_CRASH,
-    // dump a tombstone file
-    DEBUGGER_ACTION_DUMP_TOMBSTONE,
-    // dump a backtrace only back to the socket
-    DEBUGGER_ACTION_DUMP_BACKTRACE,
-} debugger_action_t;
-
-// Make sure that all values have a fixed size so that this structure
-// is the same for 32 bit and 64 bit processes.
-// NOTE: Any changes to this structure must also be reflected in
-//       bionic/linker/debugger.cpp.
-typedef struct __attribute__((packed)) {
-    int32_t action;
-    pid_t tid;
-    uint64_t abort_msg_address;
-    int32_t original_si_code;
-} debugger_msg_t;
-
-/* Dumps a process backtrace, registers, and stack to a tombstone file (requires root).
- * Stores the tombstone path in the provided buffer.
- * Returns 0 on success, -1 on error.
- */
-int dump_tombstone(pid_t tid, char* pathbuf, size_t pathlen);
-
-/* Dumps a process backtrace, registers, and stack to a tombstone file (requires root).
- * Stores the tombstone path in the provided buffer.
- * If reading debugger data from debuggerd ever takes longer than timeout_secs
- * seconds, then stop and return an error.
- * Returns 0 on success, -1 on error.
- */
-int dump_tombstone_timeout(pid_t tid, char* pathbuf, size_t pathlen, int timeout_secs);
-
-/* Dumps a process backtrace only to the specified file (requires root).
- * Returns 0 on success, -1 on error.
- */
-int dump_backtrace_to_file(pid_t tid, int fd);
-
-/* Dumps a process backtrace only to the specified file (requires root).
- * If reading debugger data from debuggerd ever takes longer than timeout_secs
- * seconds, then stop and return an error.
- * Returns 0 on success, -1 on error.
- */
-int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs);
-
-__END_DECLS
-
-#endif /* __CUTILS_DEBUGGER_H */
diff --git a/include/cutils/klog.h b/include/cutils/klog.h
deleted file mode 100644
index 295d62b..0000000
--- a/include/cutils/klog.h
+++ /dev/null
@@ -1,51 +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 _CUTILS_KLOG_H_
-#define _CUTILS_KLOG_H_
-
-#include <sys/cdefs.h>
-#include <sys/uio.h>
-#include <stdarg.h>
-
-__BEGIN_DECLS
-
-void klog_init(void);
-int  klog_get_level(void);
-void klog_set_level(int level);
-/* TODO: void klog_close(void); - and make klog_fd users thread safe. */
-
-void klog_write(int level, const char *fmt, ...)
-    __attribute__ ((format(printf, 2, 3)));
-void klog_writev(int level, const struct iovec* iov, int iov_count);
-
-__END_DECLS
-
-#define KLOG_ERROR_LEVEL   3
-#define KLOG_WARNING_LEVEL 4
-#define KLOG_NOTICE_LEVEL  5
-#define KLOG_INFO_LEVEL    6
-#define KLOG_DEBUG_LEVEL   7
-
-#define KLOG_ERROR(tag,x...)   klog_write(KLOG_ERROR_LEVEL, "<3>" tag ": " x)
-#define KLOG_WARNING(tag,x...) klog_write(KLOG_WARNING_LEVEL, "<4>" tag ": " x)
-#define KLOG_NOTICE(tag,x...)  klog_write(KLOG_NOTICE_LEVEL, "<5>" tag ": " x)
-#define KLOG_INFO(tag,x...)    klog_write(KLOG_INFO_LEVEL, "<6>" tag ": " x)
-#define KLOG_DEBUG(tag,x...)   klog_write(KLOG_DEBUG_LEVEL, "<7>" tag ": " x)
-
-#define KLOG_DEFAULT_LEVEL  3  /* messages <= this level are logged */
-
-#endif
diff --git a/include/cutils/multiuser.h b/include/cutils/multiuser.h
deleted file mode 100644
index 7e7f815..0000000
--- a/include/cutils/multiuser.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __CUTILS_MULTIUSER_H
-#define __CUTILS_MULTIUSER_H
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// NOTE: keep in sync with android.os.UserId
-
-#define MULTIUSER_APP_PER_USER_RANGE 100000
-#define MULTIUSER_FIRST_SHARED_APPLICATION_GID 50000
-#define MULTIUSER_FIRST_APPLICATION_UID 10000
-
-typedef uid_t userid_t;
-typedef uid_t appid_t;
-
-extern userid_t multiuser_get_user_id(uid_t uid);
-extern appid_t multiuser_get_app_id(uid_t uid);
-extern uid_t multiuser_get_uid(userid_t userId, appid_t appId);
-extern appid_t multiuser_get_shared_app_gid(uid_t uid);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CUTILS_MULTIUSER_H */
diff --git a/include/cutils/native_handle.h b/include/cutils/native_handle.h
deleted file mode 100644
index 268c5d3..0000000
--- a/include/cutils/native_handle.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2009 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 NATIVE_HANDLE_H_
-#define NATIVE_HANDLE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct native_handle
-{
-    int version;        /* sizeof(native_handle_t) */
-    int numFds;         /* number of file-descriptors at &data[0] */
-    int numInts;        /* number of ints at &data[numFds] */
-    int data[0];        /* numFds + numInts ints */
-} native_handle_t;
-
-/*
- * native_handle_close
- * 
- * closes the file descriptors contained in this native_handle_t
- * 
- * return 0 on success, or a negative error code on failure
- * 
- */
-int native_handle_close(const native_handle_t* h);
-
-
-/*
- * native_handle_create
- * 
- * creates a native_handle_t and initializes it. must be destroyed with
- * native_handle_delete().
- * 
- */
-native_handle_t* native_handle_create(int numFds, int numInts);
-
-/*
- * native_handle_delete
- * 
- * frees a native_handle_t allocated with native_handle_create().
- * This ONLY frees the memory allocated for the native_handle_t, but doesn't
- * close the file descriptors; which can be achieved with native_handle_close().
- * 
- * return 0 on success, or a negative error code on failure
- * 
- */
-int native_handle_delete(native_handle_t* h);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* NATIVE_HANDLE_H_ */
diff --git a/include/cutils/process_name.h b/include/cutils/process_name.h
deleted file mode 100644
index 1e72e5c..0000000
--- a/include/cutils/process_name.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-/**
- * Gives the current process a name.
- */
-
-#ifndef __PROCESS_NAME_H
-#define __PROCESS_NAME_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Sets the current process name.
- *
- * Warning: This leaks a string every time you call it. Use judiciously!
- */
-void set_process_name(const char* process_name);
-
-/** Gets the current process name. */
-const char* get_process_name(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __PROCESS_NAME_H */ 
diff --git a/include/cutils/properties.h b/include/cutils/properties.h
deleted file mode 100644
index 24aa224..0000000
--- a/include/cutils/properties.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef __CUTILS_PROPERTIES_H
-#define __CUTILS_PROPERTIES_H
-
-#include <sys/cdefs.h>
-#include <stddef.h>
-#include <sys/system_properties.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* System properties are *small* name value pairs managed by the
-** property service.  If your data doesn't fit in the provided
-** space it is not appropriate for a system property.
-**
-** WARNING: system/bionic/include/sys/system_properties.h also defines
-**          these, but with different names.  (TODO: fix that)
-*/
-#define PROPERTY_KEY_MAX   PROP_NAME_MAX
-#define PROPERTY_VALUE_MAX  PROP_VALUE_MAX
-
-/* property_get: returns the length of the value which will never be
-** greater than PROPERTY_VALUE_MAX - 1 and will always be zero terminated.
-** (the length does not include the terminating zero).
-**
-** If the property read fails or returns an empty value, the default
-** value is used (if nonnull).
-*/
-int property_get(const char *key, char *value, const char *default_value);
-
-/* property_get_bool: returns the value of key coerced into a
-** boolean. If the property is not set, then the default value is returned.
-**
-* The following is considered to be true (1):
-**   "1", "true", "y", "yes", "on"
-**
-** The following is considered to be false (0):
-**   "0", "false", "n", "no", "off"
-**
-** The conversion is whitespace-sensitive (e.g. " off" will not be false).
-**
-** If no property with this key is set (or the key is NULL) or the boolean
-** conversion fails, the default value is returned.
-**/
-int8_t property_get_bool(const char *key, int8_t default_value);
-
-/* property_get_int64: returns the value of key truncated and coerced into a
-** int64_t. If the property is not set, then the default value is used.
-**
-** The numeric conversion is identical to strtoimax with the base inferred:
-** - All digits up to the first non-digit characters are read
-** - The longest consecutive prefix of digits is converted to a long
-**
-** Valid strings of digits are:
-** - An optional sign character + or -
-** - An optional prefix indicating the base (otherwise base 10 is assumed)
-**   -- 0 prefix is octal
-**   -- 0x / 0X prefix is hex
-**
-** Leading/trailing whitespace is ignored. Overflow/underflow will cause
-** numeric conversion to fail.
-**
-** If no property with this key is set (or the key is NULL) or the numeric
-** conversion fails, the default value is returned.
-**/
-int64_t property_get_int64(const char *key, int64_t default_value);
-
-/* property_get_int32: returns the value of key truncated and coerced into an
-** int32_t. If the property is not set, then the default value is used.
-**
-** The numeric conversion is identical to strtoimax with the base inferred:
-** - All digits up to the first non-digit characters are read
-** - The longest consecutive prefix of digits is converted to a long
-**
-** Valid strings of digits are:
-** - An optional sign character + or -
-** - An optional prefix indicating the base (otherwise base 10 is assumed)
-**   -- 0 prefix is octal
-**   -- 0x / 0X prefix is hex
-**
-** Leading/trailing whitespace is ignored. Overflow/underflow will cause
-** numeric conversion to fail.
-**
-** If no property with this key is set (or the key is NULL) or the numeric
-** conversion fails, the default value is returned.
-**/
-int32_t property_get_int32(const char *key, int32_t default_value);
-
-/* property_set: returns 0 on success, < 0 on failure
-*/
-int property_set(const char *key, const char *value);
-    
-int property_list(void (*propfn)(const char *key, const char *value, void *cookie), void *cookie);    
-
-#if defined(__BIONIC_FORTIFY)
-
-extern int __property_get_real(const char *, char *, const char *)
-    __asm__(__USER_LABEL_PREFIX__ "property_get");
-__errordecl(__property_get_too_small_error, "property_get() called with too small of a buffer");
-
-__BIONIC_FORTIFY_INLINE
-int property_get(const char *key, char *value, const char *default_value) {
-    size_t bos = __bos(value);
-    if (bos < PROPERTY_VALUE_MAX) {
-        __property_get_too_small_error();
-    }
-    return __property_get_real(key, value, default_value);
-}
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/include/cutils/qtaguid.h b/include/cutils/qtaguid.h
deleted file mode 100644
index f8550fd..0000000
--- a/include/cutils/qtaguid.h
+++ /dev/null
@@ -1,66 +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 __CUTILS_QTAGUID_H
-#define __CUTILS_QTAGUID_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Set tags (and owning UIDs) for network sockets.
-*/
-extern int qtaguid_tagSocket(int sockfd, int tag, uid_t uid);
-
-/*
- * Untag a network socket before closing.
-*/
-extern int qtaguid_untagSocket(int sockfd);
-
-/*
- * For the given uid, switch counter sets.
- * The kernel only keeps a limited number of sets.
- * 2 for now.
- */
-extern int qtaguid_setCounterSet(int counterSetNum, uid_t uid);
-
-/*
- * Delete all tag info that relates to the given tag an uid.
- * If the tag is 0, then ALL info about the uid is freeded.
- * The delete data also affects active tagged socketd, which are
- * then untagged.
- * The calling process can only operate on its own tags.
- * Unless it is part of the happy AID_NET_BW_ACCT group.
- * In which case it can clobber everything.
- */
-extern int qtaguid_deleteTagData(int tag, uid_t uid);
-
-/*
- * Enable/disable qtaguid functionnality at a lower level.
- * When pacified, the kernel will accept commands but do nothing.
- */
-extern int qtaguid_setPacifier(int on);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CUTILS_QTAG_UID_H */
diff --git a/include/cutils/sched_policy.h b/include/cutils/sched_policy.h
deleted file mode 100644
index 591bd44..0000000
--- a/include/cutils/sched_policy.h
+++ /dev/null
@@ -1,64 +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.
- */
-
-#ifndef __CUTILS_SCHED_POLICY_H
-#define __CUTILS_SCHED_POLICY_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */
-typedef enum {
-    SP_DEFAULT    = -1,
-    SP_BACKGROUND = 0,
-    SP_FOREGROUND = 1,
-    SP_SYSTEM     = 2,  // can't be used with set_sched_policy()
-    SP_AUDIO_APP  = 3,
-    SP_AUDIO_SYS  = 4,
-    SP_TOP_APP    = 5,
-    SP_CNT,
-    SP_MAX        = SP_CNT - 1,
-    SP_SYSTEM_DEFAULT = SP_FOREGROUND,
-} SchedPolicy;
-
-extern int set_cpuset_policy(int tid, SchedPolicy policy);
-
-/* Assign thread tid to the cgroup associated with the specified policy.
- * If the thread is a thread group leader, that is it's gettid() == getpid(),
- * then the other threads in the same thread group are _not_ affected.
- * On platforms which support gettid(), zero tid means current thread.
- * Return value: 0 for success, or -errno for error.
- */
-extern int set_sched_policy(int tid, SchedPolicy policy);
-
-/* Return the policy associated with the cgroup of thread tid via policy pointer.
- * On platforms which support gettid(), zero tid means current thread.
- * Return value: 0 for success, or -1 for error and set errno.
- */
-extern int get_sched_policy(int tid, SchedPolicy *policy);
-
-/* Return a displayable string corresponding to policy.
- * Return value: non-NULL NUL-terminated name of unspecified length;
- * the caller is responsible for displaying the useful part of the string.
- */
-extern const char *get_sched_policy_name(SchedPolicy policy);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CUTILS_SCHED_POLICY_H */ 
diff --git a/include/cutils/sockets.h b/include/cutils/sockets.h
deleted file mode 100644
index 783bd0b..0000000
--- a/include/cutils/sockets.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef __CUTILS_SOCKETS_H
-#define __CUTILS_SOCKETS_H
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdbool.h>
-
-#if defined(_WIN32)
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-
-typedef int  socklen_t;
-typedef SOCKET cutils_socket_t;
-
-#else
-
-#include <sys/socket.h>
-
-typedef int cutils_socket_t;
-#define INVALID_SOCKET (-1)
-
-#endif
-
-#define ANDROID_SOCKET_ENV_PREFIX	"ANDROID_SOCKET_"
-#define ANDROID_SOCKET_DIR		"/dev/socket"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * android_get_control_socket - simple helper function to get the file
- * descriptor of our init-managed Unix domain socket. `name' is the name of the
- * socket, as given in init.rc. Returns -1 on error.
- *
- * This is inline and not in libcutils proper because we want to use this in
- * third-party daemons with minimal modification.
- */
-static inline int android_get_control_socket(const char* name)
-{
-	char key[64];
-	snprintf(key, sizeof(key), ANDROID_SOCKET_ENV_PREFIX "%s", name);
-
-	const char* val = getenv(key);
-	if (!val) {
-		return -1;
-	}
-
-	errno = 0;
-	int fd = strtol(val, NULL, 10);
-	if (errno) {
-		return -1;
-	}
-
-	return fd;
-}
-
-/*
- * See also android.os.LocalSocketAddress.Namespace
- */
-// Linux "abstract" (non-filesystem) namespace
-#define ANDROID_SOCKET_NAMESPACE_ABSTRACT 0
-// Android "reserved" (/dev/socket) namespace
-#define ANDROID_SOCKET_NAMESPACE_RESERVED 1
-// Normal filesystem namespace
-#define ANDROID_SOCKET_NAMESPACE_FILESYSTEM 2
-
-/*
- * Functions to create sockets for some common usages.
- *
- * All these functions are implemented for Unix, but only a few are implemented
- * for Windows. Those which are can be identified by the cutils_socket_t
- * return type. The idea is to be able to use this return value with the
- * standard Unix socket functions on any platform.
- *
- * On Unix the returned cutils_socket_t is a standard int file descriptor and
- * can always be used as normal with all file descriptor functions.
- *
- * On Windows utils_socket_t is an unsigned int pointer, and is only valid
- * with functions that specifically take a socket, e.g. send(), sendto(),
- * recv(), and recvfrom(). General file descriptor functions such as read(),
- * write(), and close() will not work with utils_socket_t and will require
- * special handling.
- *
- * These functions return INVALID_SOCKET (-1) on failure for all platforms.
- */
-int socket_loopback_client(int port, int type);
-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_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,
-                                int type);
-int socket_local_client(const char* name, int namespaceId, int type);
-cutils_socket_t socket_inaddr_any_server(int port, int type);
-
-/*
- * Closes a cutils_socket_t. Windows doesn't allow calling close() on a socket
- * so this is a cross-platform way to close a cutils_socket_t.
- *
- * Returns 0 on success.
- */
-int socket_close(cutils_socket_t sock);
-
-/*
- * Sets socket receive timeout using SO_RCVTIMEO. Setting |timeout_ms| to 0
- * disables receive timeouts.
- *
- * Return 0 on success.
- */
-int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms);
-
-/*
- * Returns the local port the socket is bound to or -1 on error.
- */
-int socket_get_local_port(cutils_socket_t sock);
-
-/*
- * Sends to a socket from multiple buffers; wraps writev() on Unix or WSASend()
- * on Windows. This can give significant speedup compared to calling send()
- * multiple times.
- *
- * Example usage:
- *   cutils_socket_buffer_t buffers[2] = { {data0, len0}, {data1, len1} };
- *   socket_send_buffers(sock, buffers, 2);
- *
- * If you try to pass more than SOCKET_SEND_BUFFERS_MAX_BUFFERS buffers into
- * this function it will return -1 without sending anything.
- *
- * Returns the number of bytes written or -1 on error.
- */
-typedef struct {
-  const void* data;
-  size_t length;
-} cutils_socket_buffer_t;
-
-#define SOCKET_SEND_BUFFERS_MAX_BUFFERS 16
-
-ssize_t socket_send_buffers(cutils_socket_t sock,
-                            const cutils_socket_buffer_t* buffers,
-                            size_t num_buffers);
-
-/*
- * socket_peer_is_trusted - Takes a socket which is presumed to be a
- * connected local socket (e.g. AF_LOCAL) and returns whether the peer
- * (the userid that owns the process on the other end of that socket)
- * is one of the two trusted userids, root or shell.
- *
- * Note: This only works as advertised on the Android OS and always
- * just returns true when called on other operating systems.
- */
-extern bool socket_peer_is_trusted(int fd);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CUTILS_SOCKETS_H */
diff --git a/include/cutils/trace.h b/include/cutils/trace.h
deleted file mode 100644
index 19313af..0000000
--- a/include/cutils/trace.h
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LIBS_CUTILS_TRACE_H
-#define _LIBS_CUTILS_TRACE_H
-
-#include <inttypes.h>
-#include <stdatomic.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/compiler.h>
-
-__BEGIN_DECLS
-
-/**
- * The ATRACE_TAG macro can be defined before including this header to trace
- * using one of the tags defined below.  It must be defined to one of the
- * following ATRACE_TAG_* macros.  The trace tag is used to filter tracing in
- * userland to avoid some of the runtime cost of tracing when it is not desired.
- *
- * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always
- * being enabled - this should ONLY be done for debug code, as userland tracing
- * has a performance cost even when the trace is not being recorded.  Defining
- * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result
- * in the tracing always being disabled.
- *
- * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing
- * within a hardware module.  For example a camera hardware module would set:
- * #define ATRACE_TAG  (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
- *
- * Keep these in sync with frameworks/base/core/java/android/os/Trace.java.
- */
-#define ATRACE_TAG_NEVER            0       // This tag is never enabled.
-#define ATRACE_TAG_ALWAYS           (1<<0)  // This tag is always enabled.
-#define ATRACE_TAG_GRAPHICS         (1<<1)
-#define ATRACE_TAG_INPUT            (1<<2)
-#define ATRACE_TAG_VIEW             (1<<3)
-#define ATRACE_TAG_WEBVIEW          (1<<4)
-#define ATRACE_TAG_WINDOW_MANAGER   (1<<5)
-#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6)
-#define ATRACE_TAG_SYNC_MANAGER     (1<<7)
-#define ATRACE_TAG_AUDIO            (1<<8)
-#define ATRACE_TAG_VIDEO            (1<<9)
-#define ATRACE_TAG_CAMERA           (1<<10)
-#define ATRACE_TAG_HAL              (1<<11)
-#define ATRACE_TAG_APP              (1<<12)
-#define ATRACE_TAG_RESOURCES        (1<<13)
-#define ATRACE_TAG_DALVIK           (1<<14)
-#define ATRACE_TAG_RS               (1<<15)
-#define ATRACE_TAG_BIONIC           (1<<16)
-#define ATRACE_TAG_POWER            (1<<17)
-#define ATRACE_TAG_PACKAGE_MANAGER  (1<<18)
-#define ATRACE_TAG_SYSTEM_SERVER    (1<<19)
-#define ATRACE_TAG_DATABASE         (1<<20)
-#define ATRACE_TAG_NETWORK          (1<<21)
-#define ATRACE_TAG_LAST             ATRACE_TAG_NETWORK
-
-// Reserved for initialization.
-#define ATRACE_TAG_NOT_READY        (1ULL<<63)
-
-#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST)
-
-#ifndef ATRACE_TAG
-#define ATRACE_TAG ATRACE_TAG_NEVER
-#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK
-#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h
-#endif
-
-/**
- * Opens the trace file for writing and reads the property for initial tags.
- * The atrace.tags.enableflags property sets the tags to trace.
- * This function should not be explicitly called, the first call to any normal
- * trace function will cause it to be run safely.
- */
-void atrace_setup();
-
-/**
- * If tracing is ready, set atrace_enabled_tags to the system property
- * debug.atrace.tags.enableflags. Can be used as a sysprop change callback.
- */
-void atrace_update_tags();
-
-/**
- * Set whether the process is debuggable.  By default the process is not
- * considered debuggable.  If the process is not debuggable then application-
- * level tracing is not allowed unless the ro.debuggable system property is
- * set to '1'.
- */
-void atrace_set_debuggable(bool debuggable);
-
-/**
- * Set whether tracing is enabled for the current process.  This is used to
- * prevent tracing within the Zygote process.
- */
-void atrace_set_tracing_enabled(bool enabled);
-
-/**
- * Flag indicating whether setup has been completed, initialized to 0.
- * Nonzero indicates setup has completed.
- * Note: This does NOT indicate whether or not setup was successful.
- */
-extern atomic_bool atrace_is_ready;
-
-/**
- * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY.
- * A value of zero indicates setup has failed.
- * Any other nonzero value indicates setup has succeeded, and tracing is on.
- */
-extern uint64_t atrace_enabled_tags;
-
-/**
- * Handle to the kernel's trace buffer, initialized to -1.
- * Any other value indicates setup has succeeded, and is a valid fd for tracing.
- */
-extern int atrace_marker_fd;
-
-/**
- * atrace_init readies the process for tracing by opening the trace_marker file.
- * Calling any trace function causes this to be run, so calling it is optional.
- * This can be explicitly run to avoid setup delay on first trace function.
- */
-#define ATRACE_INIT() atrace_init()
-static inline void atrace_init()
-{
-    if (CC_UNLIKELY(!atomic_load_explicit(&atrace_is_ready, memory_order_acquire))) {
-        atrace_setup();
-    }
-}
-
-/**
- * Get the mask of all tags currently enabled.
- * It can be used as a guard condition around more expensive trace calculations.
- * Every trace function calls this, which ensures atrace_init is run.
- */
-#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags()
-static inline uint64_t atrace_get_enabled_tags()
-{
-    atrace_init();
-    return atrace_enabled_tags;
-}
-
-/**
- * Test if a given tag is currently enabled.
- * Returns nonzero if the tag is enabled, otherwise zero.
- * It can be used as a guard condition around more expensive trace calculations.
- */
-#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG)
-static inline uint64_t atrace_is_tag_enabled(uint64_t tag)
-{
-    return atrace_get_enabled_tags() & tag;
-}
-
-/**
- * Trace the beginning of a context.  name is used to identify the context.
- * This is often used to time function execution.
- */
-#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name)
-static inline void atrace_begin(uint64_t tag, const char* name)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        void atrace_begin_body(const char*);
-        atrace_begin_body(name);
-    }
-}
-
-/**
- * Trace the end of a context.
- * This should match up (and occur after) a corresponding ATRACE_BEGIN.
- */
-#define ATRACE_END() atrace_end(ATRACE_TAG)
-static inline void atrace_end(uint64_t tag)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char c = 'E';
-        write(atrace_marker_fd, &c, 1);
-    }
-}
-
-/**
- * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END
- * contexts, asynchronous events do not need to be nested. The name describes
- * the event, and the cookie provides a unique identifier for distinguishing
- * simultaneous events. The name and cookie used to begin an event must be
- * used to end it.
- */
-#define ATRACE_ASYNC_BEGIN(name, cookie) \
-    atrace_async_begin(ATRACE_TAG, name, cookie)
-static inline void atrace_async_begin(uint64_t tag, const char* name,
-        int32_t cookie)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        void atrace_async_begin_body(const char*, int32_t);
-        atrace_async_begin_body(name, cookie);
-    }
-}
-
-/**
- * Trace the end of an asynchronous event.
- * This should have a corresponding ATRACE_ASYNC_BEGIN.
- */
-#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie)
-static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        void atrace_async_end_body(const char*, int32_t);
-        atrace_async_end_body(name, cookie);
-    }
-}
-
-/**
- * Traces an integer counter value.  name is used to identify the counter.
- * This can be used to track how a value changes over time.
- */
-#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value)
-static inline void atrace_int(uint64_t tag, const char* name, int32_t value)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        void atrace_int_body(const char*, int32_t);
-        atrace_int_body(name, value);
-    }
-}
-
-/**
- * Traces a 64-bit integer counter value.  name is used to identify the
- * counter. This can be used to track how a value changes over time.
- */
-#define ATRACE_INT64(name, value) atrace_int64(ATRACE_TAG, name, value)
-static inline void atrace_int64(uint64_t tag, const char* name, int64_t value)
-{
-    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        void atrace_int64_body(const char*, int64_t);
-        atrace_int64_body(name, value);
-    }
-}
-
-__END_DECLS
-
-#endif // _LIBS_CUTILS_TRACE_H
diff --git a/include/log b/include/log
new file mode 120000
index 0000000..714065f
--- /dev/null
+++ b/include/log
@@ -0,0 +1 @@
+../liblog/include/log
\ No newline at end of file
diff --git a/include/log/event_tag_map.h b/include/log/event_tag_map.h
deleted file mode 100644
index 1653c61..0000000
--- a/include/log/event_tag_map.h
+++ /dev/null
@@ -1,50 +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.
- */
-
-#ifndef _LIBS_CUTILS_EVENTTAGMAP_H
-#define _LIBS_CUTILS_EVENTTAGMAP_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define EVENT_TAG_MAP_FILE  "/system/etc/event-log-tags"
-
-struct EventTagMap;
-typedef struct EventTagMap EventTagMap;
-
-/*
- * Open the specified file as an event log tag map.
- *
- * Returns NULL on failure.
- */
-EventTagMap* android_openEventTagMap(const char* fileName);
-
-/*
- * Close the map.
- */
-void android_closeEventTagMap(EventTagMap* map);
-
-/*
- * Look up a tag by index.  Returns the tag string, or NULL if not found.
- */
-const char* android_lookupEventTag(const EventTagMap* map, int tag);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /*_LIBS_CUTILS_EVENTTAGMAP_H*/
diff --git a/include/log/log.h b/include/log/log.h
deleted file mode 100644
index e606a84..0000000
--- a/include/log/log.h
+++ /dev/null
@@ -1,699 +0,0 @@
-/*
- * Copyright (C) 2005-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.
- */
-
-//
-// C/C++ logging functions.  See the logging documentation for API details.
-//
-// We'd like these to be available from C code (in case we import some from
-// somewhere), so this has a C interface.
-//
-// The output will be correct when the log file is shared between multiple
-// threads and/or multiple processes so long as the operating system
-// supports O_APPEND.  These calls have mutex-protected data structures
-// and so are NOT reentrant.  Do not use LOG in a signal handler.
-//
-#ifndef _LIBS_LOG_LOG_H
-#define _LIBS_LOG_LOG_H
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <log/logd.h>
-#include <log/uio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Normally we strip ALOGV (VERBOSE messages) from release builds.
- * You can modify this (for example with "#define LOG_NDEBUG 0"
- * at the top of your source file) to change that behavior.
- */
-#ifndef LOG_NDEBUG
-#ifdef NDEBUG
-#define LOG_NDEBUG 1
-#else
-#define LOG_NDEBUG 0
-#endif
-#endif
-
-/*
- * This is the local tag used for the following simplified
- * logging macros.  You can change this preprocessor definition
- * before using the other macros to change the tag.
- */
-#ifndef LOG_TAG
-#define LOG_TAG NULL
-#endif
-
-// ---------------------------------------------------------------------
-
-#ifndef __predict_false
-#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
-#endif
-
-/*
- *      -DLINT_RLOG in sources that you want to enforce that all logging
- * goes to the radio log buffer. If any logging goes to any of the other
- * log buffers, there will be a compile or link error to highlight the
- * problem. This is not a replacement for a full audit of the code since
- * this only catches compiled code, not ifdef'd debug code. Options to
- * defining this, either temporarily to do a spot check, or permanently
- * to enforce, in all the communications trees; We have hopes to ensure
- * that by supplying just the radio log buffer that the communications
- * teams will have their one-stop shop for triaging issues.
- */
-#ifndef LINT_RLOG
-
-/*
- * Simplified macro to send a verbose log message using the current LOG_TAG.
- */
-#ifndef ALOGV
-#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#if LOG_NDEBUG
-#define ALOGV(...) do { if (0) { __ALOGV(__VA_ARGS__); } } while (0)
-#else
-#define ALOGV(...) __ALOGV(__VA_ARGS__)
-#endif
-#endif
-
-#ifndef ALOGV_IF
-#if LOG_NDEBUG
-#define ALOGV_IF(cond, ...)   ((void)0)
-#else
-#define ALOGV_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug log message using the current LOG_TAG.
- */
-#ifndef ALOGD
-#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGD_IF
-#define ALOGD_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info log message using the current LOG_TAG.
- */
-#ifndef ALOGI
-#define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGI_IF
-#define ALOGI_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning log message using the current LOG_TAG.
- */
-#ifndef ALOGW
-#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGW_IF
-#define ALOGW_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error log message using the current LOG_TAG.
- */
-#ifndef ALOGE
-#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGE_IF
-#define ALOGE_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * verbose priority.
- */
-#ifndef IF_ALOGV
-#if LOG_NDEBUG
-#define IF_ALOGV() if (false)
-#else
-#define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG)
-#endif
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * debug priority.
- */
-#ifndef IF_ALOGD
-#define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * info priority.
- */
-#ifndef IF_ALOGI
-#define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * warn priority.
- */
-#ifndef IF_ALOGW
-#define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * error priority.
- */
-#ifndef IF_ALOGE
-#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
-#endif
-
-
-// ---------------------------------------------------------------------
-
-/*
- * Simplified macro to send a verbose system log message using the current LOG_TAG.
- */
-#ifndef SLOGV
-#define __SLOGV(...) \
-    ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#if LOG_NDEBUG
-#define SLOGV(...) do { if (0) { __SLOGV(__VA_ARGS__); } } while (0)
-#else
-#define SLOGV(...) __SLOGV(__VA_ARGS__)
-#endif
-#endif
-
-#ifndef SLOGV_IF
-#if LOG_NDEBUG
-#define SLOGV_IF(cond, ...)   ((void)0)
-#else
-#define SLOGV_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug system log message using the current LOG_TAG.
- */
-#ifndef SLOGD
-#define SLOGD(...) \
-    ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGD_IF
-#define SLOGD_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info system log message using the current LOG_TAG.
- */
-#ifndef SLOGI
-#define SLOGI(...) \
-    ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGI_IF
-#define SLOGI_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning system log message using the current LOG_TAG.
- */
-#ifndef SLOGW
-#define SLOGW(...) \
-    ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGW_IF
-#define SLOGW_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error system log message using the current LOG_TAG.
- */
-#ifndef SLOGE
-#define SLOGE(...) \
-    ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGE_IF
-#define SLOGE_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-#endif /* !LINT_RLOG */
-
-// ---------------------------------------------------------------------
-
-/*
- * Simplified macro to send a verbose radio log message using the current LOG_TAG.
- */
-#ifndef RLOGV
-#define __RLOGV(...) \
-    ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#if LOG_NDEBUG
-#define RLOGV(...) do { if (0) { __RLOGV(__VA_ARGS__); } } while (0)
-#else
-#define RLOGV(...) __RLOGV(__VA_ARGS__)
-#endif
-#endif
-
-#ifndef RLOGV_IF
-#if LOG_NDEBUG
-#define RLOGV_IF(cond, ...)   ((void)0)
-#else
-#define RLOGV_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug radio log message using the current LOG_TAG.
- */
-#ifndef RLOGD
-#define RLOGD(...) \
-    ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGD_IF
-#define RLOGD_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info radio log message using the current LOG_TAG.
- */
-#ifndef RLOGI
-#define RLOGI(...) \
-    ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGI_IF
-#define RLOGI_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning radio log message using the current LOG_TAG.
- */
-#ifndef RLOGW
-#define RLOGW(...) \
-    ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGW_IF
-#define RLOGW_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error radio log message using the current LOG_TAG.
- */
-#ifndef RLOGE
-#define RLOGE(...) \
-    ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGE_IF
-#define RLOGE_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-
-// ---------------------------------------------------------------------
-
-/*
- * Log a fatal error.  If the given condition fails, this stops program
- * execution like a normal assertion, but also generating the given message.
- * It is NOT stripped from release builds.  Note that the condition test
- * is -inverted- from the normal assert() semantics.
- */
-#ifndef LOG_ALWAYS_FATAL_IF
-#define LOG_ALWAYS_FATAL_IF(cond, ...) \
-    ( (__predict_false(cond)) \
-    ? ((void)android_printAssert(#cond, LOG_TAG, ## __VA_ARGS__)) \
-    : (void)0 )
-#endif
-
-#ifndef LOG_ALWAYS_FATAL
-#define LOG_ALWAYS_FATAL(...) \
-    ( ((void)android_printAssert(NULL, LOG_TAG, ## __VA_ARGS__)) )
-#endif
-
-/*
- * Versions of LOG_ALWAYS_FATAL_IF and LOG_ALWAYS_FATAL that
- * are stripped out of release builds.
- */
-#if LOG_NDEBUG
-
-#ifndef LOG_FATAL_IF
-#define LOG_FATAL_IF(cond, ...) ((void)0)
-#endif
-#ifndef LOG_FATAL
-#define LOG_FATAL(...) ((void)0)
-#endif
-
-#else
-
-#ifndef LOG_FATAL_IF
-#define LOG_FATAL_IF(cond, ...) LOG_ALWAYS_FATAL_IF(cond, ## __VA_ARGS__)
-#endif
-#ifndef LOG_FATAL
-#define LOG_FATAL(...) LOG_ALWAYS_FATAL(__VA_ARGS__)
-#endif
-
-#endif
-
-/*
- * Assertion that generates a log message when the assertion fails.
- * Stripped out of release builds.  Uses the current LOG_TAG.
- */
-#ifndef ALOG_ASSERT
-#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__)
-//#define ALOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond)
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Basic log message macro.
- *
- * Example:
- *  ALOG(LOG_WARN, NULL, "Failed with error %d", errno);
- *
- * The second argument may be NULL or "" to indicate the "global" tag.
- */
-#ifndef ALOG
-#define ALOG(priority, tag, ...) \
-    LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
-#endif
-
-/*
- * Log macro that allows you to specify a number for the priority.
- */
-#ifndef LOG_PRI
-#define LOG_PRI(priority, tag, ...) \
-    android_printLog(priority, tag, __VA_ARGS__)
-#endif
-
-/*
- * Log macro that allows you to pass in a varargs ("args" is a va_list).
- */
-#ifndef LOG_PRI_VA
-#define LOG_PRI_VA(priority, tag, fmt, args) \
-    android_vprintLog(priority, NULL, tag, fmt, args)
-#endif
-
-/*
- * Conditional given a desired logging priority and tag.
- */
-#ifndef IF_ALOG
-#define IF_ALOG(priority, tag) \
-    if (android_testLog(ANDROID_##priority, tag))
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Event logging.
- */
-
-/*
- * Event log entry types.
- */
-typedef enum {
-    /* Special markers for android_log_list_element type */
-    EVENT_TYPE_LIST_STOP = '\n', /* declare end of list  */
-    EVENT_TYPE_UNKNOWN   = '?',  /* protocol error       */
-
-    /* must match with declaration in java/android/android/util/EventLog.java */
-    EVENT_TYPE_INT       = 0,    /* uint32_t */
-    EVENT_TYPE_LONG      = 1,    /* uint64_t */
-    EVENT_TYPE_STRING    = 2,
-    EVENT_TYPE_LIST      = 3,
-    EVENT_TYPE_FLOAT     = 4,
-} AndroidEventLogType;
-#define sizeof_AndroidEventLogType sizeof(typeof_AndroidEventLogType)
-#define typeof_AndroidEventLogType unsigned char
-
-#ifndef LOG_EVENT_INT
-#define LOG_EVENT_INT(_tag, _value) {                                       \
-        int intBuf = _value;                                                \
-        (void) android_btWriteLog(_tag, EVENT_TYPE_INT, &intBuf,            \
-            sizeof(intBuf));                                                \
-    }
-#endif
-#ifndef LOG_EVENT_LONG
-#define LOG_EVENT_LONG(_tag, _value) {                                      \
-        long long longBuf = _value;                                         \
-        (void) android_btWriteLog(_tag, EVENT_TYPE_LONG, &longBuf,          \
-            sizeof(longBuf));                                               \
-    }
-#endif
-#ifndef LOG_EVENT_FLOAT
-#define LOG_EVENT_FLOAT(_tag, _value) {                                     \
-        float floatBuf = _value;                                            \
-        (void) android_btWriteLog(_tag, EVENT_TYPE_FLOAT, &floatBuf,        \
-            sizeof(floatBuf));                                              \
-    }
-#endif
-#ifndef LOG_EVENT_STRING
-#define LOG_EVENT_STRING(_tag, _value)                                      \
-        (void) __android_log_bswrite(_tag, _value);
-#endif
-
-typedef enum log_id {
-    LOG_ID_MIN = 0,
-
-#ifndef LINT_RLOG
-    LOG_ID_MAIN = 0,
-#endif
-    LOG_ID_RADIO = 1,
-#ifndef LINT_RLOG
-    LOG_ID_EVENTS = 2,
-    LOG_ID_SYSTEM = 3,
-    LOG_ID_CRASH = 4,
-    LOG_ID_SECURITY = 5,
-    LOG_ID_KERNEL = 6, /* place last, third-parties can not use it */
-#endif
-
-    LOG_ID_MAX
-} log_id_t;
-#define sizeof_log_id_t sizeof(typeof_log_id_t)
-#define typeof_log_id_t unsigned char
-
-/* For manipulating lists of events. */
-
-#define ANDROID_MAX_LIST_NEST_DEPTH 8
-
-/*
- * The opaque context used to manipulate lists of events.
- */
-typedef struct android_log_context_internal *android_log_context;
-
-/*
- * Elements returned when reading a list of events.
- */
-typedef struct {
-    AndroidEventLogType type;
-    uint16_t complete;
-    uint16_t len;
-    union {
-        int32_t int32;
-        int64_t int64;
-        char *string;
-        float float32;
-    } data;
-} android_log_list_element;
-
-/*
- * Creates a context associated with an event tag to write elements to
- * the list of events.
- */
-android_log_context create_android_logger(uint32_t tag);
-
-/* All lists must be braced by a begin and end call */
-/*
- * NB: If the first level braces are missing when specifying multiple
- *     elements, we will manufacturer a list to embrace it for your API
- *     convenience. For a single element, it will remain solitary.
- */
-int android_log_write_list_begin(android_log_context ctx);
-int android_log_write_list_end(android_log_context ctx);
-
-int android_log_write_int32(android_log_context ctx, int32_t value);
-int android_log_write_int64(android_log_context ctx, int64_t value);
-int android_log_write_string8(android_log_context ctx, const char *value);
-int android_log_write_string8_len(android_log_context ctx,
-                                  const char *value, size_t maxlen);
-int android_log_write_float32(android_log_context ctx, float value);
-
-/* Submit the composed list context to the specified logger id */
-/* NB: LOG_ID_EVENTS and LOG_ID_SECURITY only valid binary buffers */
-int android_log_write_list(android_log_context ctx, log_id_t id);
-
-/*
- * Creates a context from a raw buffer representing a list of events to be read.
- */
-android_log_context create_android_log_parser(const char *msg, size_t len);
-
-android_log_list_element android_log_read_next(android_log_context ctx);
-android_log_list_element android_log_peek_next(android_log_context ctx);
-
-/* Finished with reader or writer context */
-int android_log_destroy(android_log_context *ctx);
-
-/*
- * ===========================================================================
- *
- * The stuff in the rest of this file should not be used directly.
- */
-
-#define android_printLog(prio, tag, fmt...) \
-    __android_log_print(prio, tag, fmt)
-
-#define android_vprintLog(prio, cond, tag, fmt...) \
-    __android_log_vprint(prio, tag, fmt)
-
-/* XXX Macros to work around syntax errors in places where format string
- * arg is not passed to ALOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF
- * (happens only in debug builds).
- */
-
-/* Returns 2nd arg.  Used to substitute default value if caller's vararg list
- * is empty.
- */
-#define __android_second(dummy, second, ...)     second
-
-/* If passed multiple args, returns ',' followed by all but 1st arg, otherwise
- * returns nothing.
- */
-#define __android_rest(first, ...)               , ## __VA_ARGS__
-
-#define android_printAssert(cond, tag, fmt...) \
-    __android_log_assert(cond, tag, \
-        __android_second(0, ## fmt, NULL) __android_rest(fmt))
-
-#define android_writeLog(prio, tag, text) \
-    __android_log_write(prio, tag, text)
-
-#define android_bWriteLog(tag, payload, len) \
-    __android_log_bwrite(tag, payload, len)
-#define android_btWriteLog(tag, type, payload, len) \
-    __android_log_btwrite(tag, type, payload, len)
-
-#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)
-
-/*
- *    IF_ALOG uses android_testLog, but IF_ALOG can be overridden.
- *    android_testLog will remain constant in its purpose as a wrapper
- *        for Android logging filter policy, and can be subject to
- *        change. It can be reused by the developers that override
- *        IF_ALOG as a convenient means to reimplement their policy
- *        over Android.
- */
-#if LOG_NDEBUG /* Production */
-#define android_testLog(prio, tag) \
-    (__android_log_is_loggable(prio, tag, ANDROID_LOG_DEBUG) != 0)
-#else
-#define android_testLog(prio, tag) \
-    (__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE) != 0)
-#endif
-
-/*
- * Use the per-tag properties "log.tag.<tagname>" to generate a runtime
- * result of non-zero to expose a log. prio is ANDROID_LOG_VERBOSE to
- * ANDROID_LOG_FATAL. default_prio if no property. Undefined behavior if
- * any other value.
- */
-int __android_log_is_loggable(int prio, const char *tag, int default_prio);
-
-int __android_log_security(); /* Device Owner is present */
-
-int __android_log_error_write(int tag, const char *subTag, int32_t uid, const char *data,
-                              uint32_t dataLen);
-
-/*
- * Send a simple string to the log.
- */
-int __android_log_buf_write(int bufID, int prio, const char *tag, const char *text);
-int __android_log_buf_print(int bufID, int prio, const char *tag, const char *fmt, ...)
-#if defined(__GNUC__)
-    __attribute__((__format__(printf, 4, 5)))
-#endif
-    ;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _LIBS_LOG_LOG_H */
diff --git a/include/log/log_read.h b/include/log/log_read.h
deleted file mode 100644
index 1b70aff..0000000
--- a/include/log/log_read.h
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2013-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 _LIBS_LOG_LOG_READ_H
-#define _LIBS_LOG_LOG_READ_H
-
-#include <stdint.h>
-#include <time.h>
-
-/* struct log_time is a wire-format variant of struct timespec */
-#define NS_PER_SEC 1000000000ULL
-
-#ifdef __cplusplus
-
-// NB: do NOT define a copy constructor. This will result in structure
-// no longer being compatible with pass-by-value which is desired
-// efficient behavior. Also, pass-by-reference breaks C/C++ ABI.
-struct log_time {
-public:
-    uint32_t tv_sec; // good to Feb 5 2106
-    uint32_t tv_nsec;
-
-    static const uint32_t tv_sec_max = 0xFFFFFFFFUL;
-    static const uint32_t tv_nsec_max = 999999999UL;
-
-    log_time(const timespec &T)
-    {
-        tv_sec = T.tv_sec;
-        tv_nsec = T.tv_nsec;
-    }
-    log_time(uint32_t sec, uint32_t nsec)
-    {
-        tv_sec = sec;
-        tv_nsec = nsec;
-    }
-    static const timespec EPOCH;
-    log_time()
-    {
-    }
-    log_time(clockid_t id)
-    {
-        timespec T;
-        clock_gettime(id, &T);
-        tv_sec = T.tv_sec;
-        tv_nsec = T.tv_nsec;
-    }
-    log_time(const char *T)
-    {
-        const uint8_t *c = (const uint8_t *) T;
-        tv_sec = c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24);
-        tv_nsec = c[4] | (c[5] << 8) | (c[6] << 16) | (c[7] << 24);
-    }
-
-    // timespec
-    bool operator== (const timespec &T) const
-    {
-        return (tv_sec == static_cast<uint32_t>(T.tv_sec))
-            && (tv_nsec == static_cast<uint32_t>(T.tv_nsec));
-    }
-    bool operator!= (const timespec &T) const
-    {
-        return !(*this == T);
-    }
-    bool operator< (const timespec &T) const
-    {
-        return (tv_sec < static_cast<uint32_t>(T.tv_sec))
-            || ((tv_sec == static_cast<uint32_t>(T.tv_sec))
-                && (tv_nsec < static_cast<uint32_t>(T.tv_nsec)));
-    }
-    bool operator>= (const timespec &T) const
-    {
-        return !(*this < T);
-    }
-    bool operator> (const timespec &T) const
-    {
-        return (tv_sec > static_cast<uint32_t>(T.tv_sec))
-            || ((tv_sec == static_cast<uint32_t>(T.tv_sec))
-                && (tv_nsec > static_cast<uint32_t>(T.tv_nsec)));
-    }
-    bool operator<= (const timespec &T) const
-    {
-        return !(*this > T);
-    }
-    log_time operator-= (const timespec &T);
-    log_time operator- (const timespec &T) const
-    {
-        log_time local(*this);
-        return local -= T;
-    }
-    log_time operator+= (const timespec &T);
-    log_time operator+ (const timespec &T) const
-    {
-        log_time local(*this);
-        return local += T;
-    }
-
-    // log_time
-    bool operator== (const log_time &T) const
-    {
-        return (tv_sec == T.tv_sec) && (tv_nsec == T.tv_nsec);
-    }
-    bool operator!= (const log_time &T) const
-    {
-        return !(*this == T);
-    }
-    bool operator< (const log_time &T) const
-    {
-        return (tv_sec < T.tv_sec)
-            || ((tv_sec == T.tv_sec) && (tv_nsec < T.tv_nsec));
-    }
-    bool operator>= (const log_time &T) const
-    {
-        return !(*this < T);
-    }
-    bool operator> (const log_time &T) const
-    {
-        return (tv_sec > T.tv_sec)
-            || ((tv_sec == T.tv_sec) && (tv_nsec > T.tv_nsec));
-    }
-    bool operator<= (const log_time &T) const
-    {
-        return !(*this > T);
-    }
-    log_time operator-= (const log_time &T);
-    log_time operator- (const log_time &T) const
-    {
-        log_time local(*this);
-        return local -= T;
-    }
-    log_time operator+= (const log_time &T);
-    log_time operator+ (const log_time &T) const
-    {
-        log_time local(*this);
-        return local += T;
-    }
-
-    uint64_t nsec() const
-    {
-        return static_cast<uint64_t>(tv_sec) * NS_PER_SEC + tv_nsec;
-    }
-
-    static const char default_format[];
-
-    // Add %#q for the fraction of a second to the standard library functions
-    char *strptime(const char *s, const char *format = default_format);
-} __attribute__((__packed__));
-
-#else
-
-typedef struct log_time {
-    uint32_t tv_sec;
-    uint32_t tv_nsec;
-} __attribute__((__packed__)) log_time;
-
-#endif
-
-#endif /* define _LIBS_LOG_LOG_READ_H */
diff --git a/include/log/logd.h b/include/log/logd.h
deleted file mode 100644
index b271602..0000000
--- a/include/log/logd.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2009 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_CUTILS_LOGD_H
-#define _ANDROID_CUTILS_LOGD_H
-
-/* the stable/frozen log-related definitions have been
- * moved to this header, which is exposed by the NDK
- */
-#include <android/log.h>
-
-/* the rest is only used internally by the system */
-#if !defined(_WIN32)
-#include <pthread.h>
-#endif
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <log/uio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int __android_log_bwrite(int32_t tag, const void *payload, size_t len);
-int __android_log_btwrite(int32_t tag, char type, const void *payload,
-    size_t len);
-int __android_log_bswrite(int32_t tag, const char *payload);
-
-int __android_log_security_bwrite(int32_t tag, const void *payload, size_t len);
-int __android_log_security_bswrite(int32_t tag, const char *payload);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _LOGD_H */
diff --git a/include/log/logger.h b/include/log/logger.h
deleted file mode 100644
index 60d47a2..0000000
--- a/include/log/logger.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
-**
-** Copyright 2007-2014, 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_LOGGER_H
-#define _LIBS_LOG_LOGGER_H
-
-#include <stdint.h>
-#ifdef __linux__
-#include <time.h> /* clockid_t definition */
-#endif
-
-#include <log/log.h>
-#include <log/log_read.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * The userspace structure for version 1 of the logger_entry ABI.
- * This structure is returned to userspace by the kernel logger
- * driver unless an upgrade to a newer ABI version is requested.
- */
-struct logger_entry {
-    uint16_t    len;    /* length of the payload */
-    uint16_t    __pad;  /* no matter what, we get 2 bytes of padding */
-    int32_t     pid;    /* generating process's pid */
-    int32_t     tid;    /* generating process's tid */
-    int32_t     sec;    /* seconds since Epoch */
-    int32_t     nsec;   /* nanoseconds */
-    char        msg[0]; /* the entry's payload */
-} __attribute__((__packed__));
-
-/*
- * The userspace structure for version 2 of the logger_entry ABI.
- * This structure is returned to userspace if ioctl(LOGGER_SET_VERSION)
- * is called with version==2; or used with the user space log daemon.
- */
-struct logger_entry_v2 {
-    uint16_t    len;       /* length of the payload */
-    uint16_t    hdr_size;  /* sizeof(struct logger_entry_v2) */
-    int32_t     pid;       /* generating process's pid */
-    int32_t     tid;       /* generating process's tid */
-    int32_t     sec;       /* seconds since Epoch */
-    int32_t     nsec;      /* nanoseconds */
-    uint32_t    euid;      /* effective UID of logger */
-    char        msg[0];    /* the entry's payload */
-} __attribute__((__packed__));
-
-struct logger_entry_v3 {
-    uint16_t    len;       /* length of the payload */
-    uint16_t    hdr_size;  /* sizeof(struct logger_entry_v3) */
-    int32_t     pid;       /* generating process's pid */
-    int32_t     tid;       /* generating process's tid */
-    int32_t     sec;       /* seconds since Epoch */
-    int32_t     nsec;      /* nanoseconds */
-    uint32_t    lid;       /* log id of the payload */
-    char        msg[0];    /* the entry's payload */
-} __attribute__((__packed__));
-
-struct logger_entry_v4 {
-    uint16_t    len;       /* length of the payload */
-    uint16_t    hdr_size;  /* sizeof(struct logger_entry_v4) */
-    int32_t     pid;       /* generating process's pid */
-    uint32_t    tid;       /* generating process's tid */
-    uint32_t    sec;       /* seconds since Epoch */
-    uint32_t    nsec;      /* nanoseconds */
-    uint32_t    lid;       /* log id of the payload, bottom 4 bits currently */
-    uint32_t    uid;       /* generating process's uid */
-    char        msg[0];    /* the entry's payload */
-} __attribute__((__packed__));
-
-/*
- * The maximum size of the log entry payload that can be
- * written to the logger. An attempt to write more than
- * this amount will result in a truncated log entry.
- */
-#define LOGGER_ENTRY_MAX_PAYLOAD	4068
-
-/*
- * The maximum size of a log entry which can be read from the
- * kernel logger driver. An attempt to read less than this amount
- * may result in read() returning EINVAL.
- */
-#define LOGGER_ENTRY_MAX_LEN		(5*1024)
-
-#define NS_PER_SEC 1000000000ULL
-
-struct log_msg {
-    union {
-        unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1];
-        struct logger_entry_v4 entry;
-        struct logger_entry_v4 entry_v4;
-        struct logger_entry_v3 entry_v3;
-        struct logger_entry_v2 entry_v2;
-        struct logger_entry    entry_v1;
-    } __attribute__((aligned(4)));
-#ifdef __cplusplus
-    /* Matching log_time operators */
-    bool operator== (const log_msg &T) const
-    {
-        return (entry.sec == T.entry.sec) && (entry.nsec == T.entry.nsec);
-    }
-    bool operator!= (const log_msg &T) const
-    {
-        return !(*this == T);
-    }
-    bool operator< (const log_msg &T) const
-    {
-        return (entry.sec < T.entry.sec)
-            || ((entry.sec == T.entry.sec)
-             && (entry.nsec < T.entry.nsec));
-    }
-    bool operator>= (const log_msg &T) const
-    {
-        return !(*this < T);
-    }
-    bool operator> (const log_msg &T) const
-    {
-        return (entry.sec > T.entry.sec)
-            || ((entry.sec == T.entry.sec)
-             && (entry.nsec > T.entry.nsec));
-    }
-    bool operator<= (const log_msg &T) const
-    {
-        return !(*this > T);
-    }
-    uint64_t nsec() const
-    {
-        return static_cast<uint64_t>(entry.sec) * NS_PER_SEC + entry.nsec;
-    }
-
-    /* packet methods */
-    log_id_t id()
-    {
-        return (log_id_t) entry.lid;
-    }
-    char *msg()
-    {
-        return entry.hdr_size ? (char *) buf + entry.hdr_size : entry_v1.msg;
-    }
-    unsigned int len()
-    {
-        return (entry.hdr_size ? entry.hdr_size : sizeof(entry_v1)) + entry.len;
-    }
-#endif
-};
-
-struct logger;
-
-log_id_t android_logger_get_id(struct logger *logger);
-
-int android_logger_clear(struct logger *logger);
-long android_logger_get_log_size(struct logger *logger);
-int android_logger_set_log_size(struct logger *logger, unsigned long size);
-long android_logger_get_log_readable_size(struct logger *logger);
-int android_logger_get_log_version(struct logger *logger);
-
-struct logger_list;
-
-ssize_t android_logger_get_statistics(struct logger_list *logger_list,
-                                      char *buf, size_t len);
-ssize_t android_logger_get_prune_list(struct logger_list *logger_list,
-                                      char *buf, size_t len);
-int android_logger_set_prune_list(struct logger_list *logger_list,
-                                  char *buf, size_t len);
-
-#define ANDROID_LOG_RDONLY   O_RDONLY
-#define ANDROID_LOG_WRONLY   O_WRONLY
-#define ANDROID_LOG_RDWR     O_RDWR
-#define ANDROID_LOG_ACCMODE  O_ACCMODE
-#define ANDROID_LOG_NONBLOCK O_NONBLOCK
-#define ANDROID_LOG_WRAP     0x40000000 /* Block until buffer about to wrap */
-#define ANDROID_LOG_WRAP_DEFAULT_TIMEOUT 7200 /* 2 hour default */
-#define ANDROID_LOG_PSTORE   0x80000000
-
-struct logger_list *android_logger_list_alloc(int mode,
-                                              unsigned int tail,
-                                              pid_t pid);
-struct logger_list *android_logger_list_alloc_time(int mode,
-                                                   log_time start,
-                                                   pid_t pid);
-void android_logger_list_free(struct logger_list *logger_list);
-/* In the purest sense, the following two are orthogonal interfaces */
-int android_logger_list_read(struct logger_list *logger_list,
-                             struct log_msg *log_msg);
-
-/* Multiple log_id_t opens */
-struct logger *android_logger_open(struct logger_list *logger_list,
-                                   log_id_t id);
-#define android_logger_close android_logger_free
-/* Single log_id_t open */
-struct logger_list *android_logger_list_open(log_id_t id,
-                                             int mode,
-                                             unsigned int tail,
-                                             pid_t pid);
-#define android_logger_list_close android_logger_list_free
-
-#ifdef __linux__
-clockid_t android_log_clockid();
-#endif
-
-/*
- * log_id_t helpers
- */
-log_id_t android_name_to_log_id(const char *logName);
-const char *android_log_id_to_name(log_id_t log_id);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _LIBS_LOG_LOGGER_H */
diff --git a/include/log/logprint.h b/include/log/logprint.h
deleted file mode 100644
index 539d1dc..0000000
--- a/include/log/logprint.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef _LOGPRINT_H
-#define _LOGPRINT_H
-
-#include <log/log.h>
-#include <log/logger.h>
-#include <log/event_tag_map.h>
-#include <pthread.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef enum {
-    FORMAT_OFF = 0,
-    FORMAT_BRIEF,
-    FORMAT_PROCESS,
-    FORMAT_TAG,
-    FORMAT_THREAD,
-    FORMAT_RAW,
-    FORMAT_TIME,
-    FORMAT_THREADTIME,
-    FORMAT_LONG,
-    /* The following are modifiers to above formats */
-    FORMAT_MODIFIER_COLOR,     /* converts priority to color */
-    FORMAT_MODIFIER_TIME_USEC, /* switches from msec to usec time precision */
-    FORMAT_MODIFIER_PRINTABLE, /* converts non-printable to printable escapes */
-    FORMAT_MODIFIER_YEAR,      /* Adds year to date */
-    FORMAT_MODIFIER_ZONE,      /* Adds zone to date */
-    FORMAT_MODIFIER_EPOCH,     /* Print time as seconds since Jan 1 1970 */
-    FORMAT_MODIFIER_MONOTONIC, /* Print cpu time as seconds since start */
-    FORMAT_MODIFIER_UID,       /* Adds uid */
-} AndroidLogPrintFormat;
-
-typedef struct AndroidLogFormat_t AndroidLogFormat;
-
-typedef struct AndroidLogEntry_t {
-    time_t tv_sec;
-    long tv_nsec;
-    android_LogPriority priority;
-    int32_t uid;
-    int32_t pid;
-    int32_t tid;
-    const char * tag;
-    size_t messageLen;
-    const char * message;
-} AndroidLogEntry;
-
-AndroidLogFormat *android_log_format_new();
-
-void android_log_format_free(AndroidLogFormat *p_format);
-
-/* currently returns 0 if format is a modifier, 1 if not */
-int android_log_setPrintFormat(AndroidLogFormat *p_format,
-        AndroidLogPrintFormat format);
-
-/**
- * Returns FORMAT_OFF on invalid string
- */
-AndroidLogPrintFormat android_log_formatFromString(const char *s);
-
-/**
- * filterExpression: a single filter expression
- * eg "AT:d"
- *
- * returns 0 on success and -1 on invalid expression
- *
- * Assumes single threaded execution
- *
- */
-
-int android_log_addFilterRule(AndroidLogFormat *p_format,
-        const char *filterExpression);
-
-
-/**
- * filterString: a whitespace-separated set of filter expressions
- * eg "AT:d *:i"
- *
- * returns 0 on success and -1 on invalid expression
- *
- * Assumes single threaded execution
- *
- */
-
-int android_log_addFilterString(AndroidLogFormat *p_format,
-        const char *filterString);
-
-
-/**
- * returns 1 if this log line should be printed based on its priority
- * and tag, and 0 if it should not
- */
-int android_log_shouldPrintLine (
-        AndroidLogFormat *p_format, const char *tag, android_LogPriority pri);
-
-
-/**
- * Splits a wire-format buffer into an AndroidLogEntry
- * entry allocated by caller. Pointers will point directly into buf
- *
- * Returns 0 on success and -1 on invalid wire format (entry will be
- * in unspecified state)
- */
-int android_log_processLogBuffer(struct logger_entry *buf,
-                                 AndroidLogEntry *entry);
-
-/**
- * Like android_log_processLogBuffer, but for binary logs.
- *
- * If "map" is non-NULL, it will be used to convert the log tag number
- * into a string.
- */
-int android_log_processBinaryLogBuffer(struct logger_entry *buf,
-    AndroidLogEntry *entry, const EventTagMap* map, char* messageBuf,
-    int messageBufLen);
-
-
-/**
- * Formats a log message into a buffer
- *
- * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
- * If return value != defaultBuffer, caller must call free()
- * Returns NULL on malloc error
- */
-
-char *android_log_formatLogLine (
-    AndroidLogFormat *p_format,
-    char *defaultBuffer,
-    size_t defaultBufferSize,
-    const AndroidLogEntry *p_line,
-    size_t *p_outLength);
-
-
-/**
- * Either print or do not print log line, based on filter
- *
- * Assumes single threaded execution
- *
- */
-int android_log_printLogLine(
-    AndroidLogFormat *p_format,
-    int fd,
-    const AndroidLogEntry *entry);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /*_LOGPRINT_H*/
diff --git a/include/log/uio.h b/include/log/uio.h
deleted file mode 100644
index 7059da5..0000000
--- a/include/log/uio.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2007-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 _LIBS_CUTILS_UIO_H
-#define _LIBS_CUTILS_UIO_H
-
-#if !defined(_WIN32)
-
-#include <sys/uio.h>
-
-#else
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//
-// Implementation of sys/uio.h for Win32.
-//
-
-#include <stddef.h>
-
-struct iovec {
-    void*  iov_base;
-    size_t iov_len;
-};
-
-extern int  readv( int  fd, struct iovec*  vecs, int  count );
-extern int  writev( int  fd, const struct iovec*  vecs, int  count );
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-#endif /* _LIBS_UTILS_UIO_H */
-
diff --git a/include/memtrack/memtrack.h b/include/memtrack/memtrack.h
deleted file mode 100644
index 3917300..0000000
--- a/include/memtrack/memtrack.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LIBMEMTRACK_MEMTRACK_H_
-#define _LIBMEMTRACK_MEMTRACK_H_
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <cutils/compiler.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * struct memtrack_proc
- *
- * an opaque handle to the memory stats on a process.
- * Created with memtrack_proc_new, destroyed by
- * memtrack_proc_destroy.  Can be reused multiple times with
- * memtrack_proc_get.
- */
-struct memtrack_proc;
-
-/**
- * memtrack_init
- *
- * Must be called once before calling any other functions.  After this function
- * is called, everything else is thread-safe.
- *
- * Returns 0 on success, -errno on error.
- */
-int memtrack_init(void);
-
-/**
- * memtrack_proc_new
- *
- * Return a new handle to hold process memory stats.
- *
- * Returns NULL on error.
- */
-struct memtrack_proc *memtrack_proc_new(void);
-
-/**
- * memtrack_proc_destroy
- *
- * Free all memory associated with a process memory stats handle.
- */
-void memtrack_proc_destroy(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_get
- *
- * Fill a process memory stats handle with data about the given pid.  Can be
- * called on a handle that was just allocated with memtrack_proc_new,
- * or on a handle that has been previously passed to memtrack_proc_get
- * to replace the data with new data on the same or another process.  It is
- * expected that the second call on the same handle should not require
- * allocating any new memory.
- *
- * Returns 0 on success, -errno on error.
- */
-int memtrack_proc_get(struct memtrack_proc *p, pid_t pid);
-
-/**
- * memtrack_proc_graphics_total
- *
- * Return total amount of memory that has been allocated for use as window
- * buffers.  Does not differentiate between memory that has already been
- * accounted for by reading /proc/pid/smaps and memory that has not been
- * accounted for.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_graphics_total(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_graphics_pss
- *
- * Return total amount of memory that has been allocated for use as window
- * buffers, but has not already been accounted for by reading /proc/pid/smaps.
- * Memory that is shared across processes may already be divided by the
- * number of processes that share it (preferred), or may be charged in full to
- * every process that shares it, depending on the capabilities of the driver.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_graphics_pss(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_gl_total
- *
- * Same as memtrack_proc_graphics_total, but counts GL memory (which
- * should not overlap with graphics memory) instead of graphics memory.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_gl_total(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_gl_pss
- *
- * Same as memtrack_proc_graphics_total, but counts GL memory (which
- * should not overlap with graphics memory) instead of graphics memory.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_gl_pss(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_other_total
- *
- * Same as memtrack_proc_graphics_total, but counts miscellaneous memory
- * not tracked by gl or graphics calls above.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_other_total(struct memtrack_proc *p);
-
-/**
- * memtrack_proc_other_pss
- *
- * Same as memtrack_proc_graphics_total, but counts miscellaneous memory
- * not tracked by gl or graphics calls above.
- *
- * Returns non-negative size in bytes on success, -errno on error.
- */
-ssize_t memtrack_proc_other_pss(struct memtrack_proc *p);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/include/mincrypt/dsa_sig.h b/include/mincrypt/dsa_sig.h
deleted file mode 100644
index b0d91cd..0000000
--- a/include/mincrypt/dsa_sig.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_
-
-#include "mincrypt/p256.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Returns 0 if input sig is not a valid ASN.1 sequence
-int dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_ */
diff --git a/include/mincrypt/hash-internal.h b/include/mincrypt/hash-internal.h
deleted file mode 100644
index c813b44..0000000
--- a/include/mincrypt/hash-internal.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2007 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif  // __cplusplus
-
-struct HASH_CTX;  // forward decl
-
-typedef struct HASH_VTAB {
-  void (* const init)(struct HASH_CTX*);
-  void (* const update)(struct HASH_CTX*, const void*, int);
-  const uint8_t* (* const final)(struct HASH_CTX*);
-  const uint8_t* (* const hash)(const void*, int, uint8_t*);
-  int size;
-} HASH_VTAB;
-
-typedef struct HASH_CTX {
-  const HASH_VTAB * f;
-  uint64_t count;
-  uint8_t buf[64];
-  uint32_t state[8];  // upto SHA2
-} HASH_CTX;
-
-#define HASH_init(ctx) (ctx)->f->init(ctx)
-#define HASH_update(ctx, data, len) (ctx)->f->update(ctx, data, len)
-#define HASH_final(ctx) (ctx)->f->final(ctx)
-#define HASH_hash(data, len, digest) (ctx)->f->hash(data, len, digest)
-#define HASH_size(ctx) (ctx)->f->size
-
-#ifdef __cplusplus
-}
-#endif  // __cplusplus
-
-#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_
diff --git a/include/mincrypt/p256.h b/include/mincrypt/p256.h
deleted file mode 100644
index 465a1b9..0000000
--- a/include/mincrypt/p256.h
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
-
-// Collection of routines manipulating 256 bit unsigned integers.
-// Just enough to implement ecdsa-p256 and related algorithms.
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define P256_BITSPERDIGIT 32
-#define P256_NDIGITS 8
-#define P256_NBYTES 32
-
-typedef int p256_err;
-typedef uint32_t p256_digit;
-typedef int32_t p256_sdigit;
-typedef uint64_t p256_ddigit;
-typedef int64_t p256_sddigit;
-
-// Defining p256_int as struct to leverage struct assigment.
-typedef struct {
-  p256_digit a[P256_NDIGITS];
-} p256_int;
-
-extern const p256_int SECP256r1_n;  // Curve order
-extern const p256_int SECP256r1_p;  // Curve prime
-extern const p256_int SECP256r1_b;  // Curve param
-
-// Initialize a p256_int to zero.
-void p256_init(p256_int* a);
-
-// Clear a p256_int to zero.
-void p256_clear(p256_int* a);
-
-// Return bit. Index 0 is least significant.
-int p256_get_bit(const p256_int* a, int index);
-
-// b := a % MOD
-void p256_mod(
-    const p256_int* MOD,
-    const p256_int* a,
-    p256_int* b);
-
-// c := a * (top_b | b) % MOD
-void p256_modmul(
-    const p256_int* MOD,
-    const p256_int* a,
-    const p256_digit top_b,
-    const p256_int* b,
-    p256_int* c);
-
-// b := 1 / a % MOD
-// MOD best be SECP256r1_n
-void p256_modinv(
-    const p256_int* MOD,
-    const p256_int* a,
-    p256_int* b);
-
-// b := 1 / a % MOD
-// MOD best be SECP256r1_n
-// Faster than p256_modinv()
-void p256_modinv_vartime(
-    const p256_int* MOD,
-    const p256_int* a,
-    p256_int* b);
-
-// b := a << (n % P256_BITSPERDIGIT)
-// Returns the bits shifted out of most significant digit.
-p256_digit p256_shl(const p256_int* a, int n, p256_int* b);
-
-// b := a >> (n % P256_BITSPERDIGIT)
-void p256_shr(const p256_int* a, int n, p256_int* b);
-
-int p256_is_zero(const p256_int* a);
-int p256_is_odd(const p256_int* a);
-int p256_is_even(const p256_int* a);
-
-// Returns -1, 0 or 1.
-int p256_cmp(const p256_int* a, const p256_int *b);
-
-// c: = a - b
-// Returns -1 on borrow.
-int p256_sub(const p256_int* a, const p256_int* b, p256_int* c);
-
-// c := a + b
-// Returns 1 on carry.
-int p256_add(const p256_int* a, const p256_int* b, p256_int* c);
-
-// c := a + (single digit)b
-// Returns carry 1 on carry.
-int p256_add_d(const p256_int* a, p256_digit b, p256_int* c);
-
-// ec routines.
-
-// {out_x,out_y} := nG
-void p256_base_point_mul(const p256_int *n,
-                         p256_int *out_x,
-                         p256_int *out_y);
-
-// {out_x,out_y} := n{in_x,in_y}
-void p256_point_mul(const p256_int *n,
-                    const p256_int *in_x,
-                    const p256_int *in_y,
-                    p256_int *out_x,
-                    p256_int *out_y);
-
-// {out_x,out_y} := n1G + n2{in_x,in_y}
-void p256_points_mul_vartime(
-    const p256_int *n1, const p256_int *n2,
-    const p256_int *in_x, const p256_int *in_y,
-    p256_int *out_x, p256_int *out_y);
-
-// Return whether point {x,y} is on curve.
-int p256_is_valid_point(const p256_int* x, const p256_int* y);
-
-// Outputs big-endian binary form. No leading zero skips.
-void p256_to_bin(const p256_int* src, uint8_t dst[P256_NBYTES]);
-
-// Reads from big-endian binary form,
-// thus pre-pad with leading zeros if short.
-void p256_from_bin(const uint8_t src[P256_NBYTES], p256_int* dst);
-
-#define P256_DIGITS(x) ((x)->a)
-#define P256_DIGIT(x,y) ((x)->a[y])
-
-#define P256_ZERO {{0}}
-#define P256_ONE {{1}}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
diff --git a/include/mincrypt/p256_ecdsa.h b/include/mincrypt/p256_ecdsa.h
deleted file mode 100644
index da339fa..0000000
--- a/include/mincrypt/p256_ecdsa.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_
-
-// Using current directory as relative include path here since
-// this code typically gets lifted into a variety of build systems
-// and directory structures.
-#include "p256.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Returns 0 if {r,s} is not a signature on message for
-// public key {key_x,key_y}.
-//
-// Note: message is a p256_int.
-// Convert from a binary string using p256_from_bin().
-int p256_ecdsa_verify(const p256_int* key_x,
-                      const p256_int* key_y,
-                      const p256_int* message,
-                      const p256_int* r, const p256_int* s);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_
diff --git a/include/mincrypt/rsa.h b/include/mincrypt/rsa.h
deleted file mode 100644
index 3d0556b..0000000
--- a/include/mincrypt/rsa.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/* rsa.h
-**
-** Copyright 2008, The Android Open Source Project
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**     * Redistributions of source code must retain the above copyright
-**       notice, this list of conditions and the following disclaimer.
-**     * Redistributions in binary form must reproduce the above copyright
-**       notice, this list of conditions and the following disclaimer in the
-**       documentation and/or other materials provided with the distribution.
-**     * Neither the name of Google Inc. nor the names of its contributors may
-**       be used to endorse or promote products derived from this software
-**       without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
-** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_
-
-#include <inttypes.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define RSANUMBYTES 256           /* 2048 bit key length */
-#define RSANUMWORDS (RSANUMBYTES / sizeof(uint32_t))
-
-typedef struct RSAPublicKey {
-    int len;                  /* Length of n[] in number of uint32_t */
-    uint32_t n0inv;           /* -1 / n[0] mod 2^32 */
-    uint32_t n[RSANUMWORDS];  /* modulus as little endian array */
-    uint32_t rr[RSANUMWORDS]; /* R^2 as little endian array */
-    int exponent;             /* 3 or 65537 */
-} RSAPublicKey;
-
-int RSA_verify(const RSAPublicKey *key,
-               const uint8_t* signature,
-               const int len,
-               const uint8_t* hash,
-               const int hash_len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_
diff --git a/include/mincrypt/sha.h b/include/mincrypt/sha.h
deleted file mode 100644
index ef60aab..0000000
--- a/include/mincrypt/sha.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2005 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_
-
-#include <stdint.h>
-#include "hash-internal.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-typedef HASH_CTX SHA_CTX;
-
-void SHA_init(SHA_CTX* ctx);
-void SHA_update(SHA_CTX* ctx, const void* data, int len);
-const uint8_t* SHA_final(SHA_CTX* ctx);
-
-// Convenience method. Returns digest address.
-// NOTE: *digest needs to hold SHA_DIGEST_SIZE bytes.
-const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest);
-
-#define SHA_DIGEST_SIZE 20
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_
diff --git a/include/mincrypt/sha256.h b/include/mincrypt/sha256.h
deleted file mode 100644
index 3a87c31..0000000
--- a/include/mincrypt/sha256.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2011 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_
-#define SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_
-
-#include <stdint.h>
-#include "hash-internal.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-typedef HASH_CTX SHA256_CTX;
-
-void SHA256_init(SHA256_CTX* ctx);
-void SHA256_update(SHA256_CTX* ctx, const void* data, int len);
-const uint8_t* SHA256_final(SHA256_CTX* ctx);
-
-// Convenience method. Returns digest address.
-const uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest);
-
-#define SHA256_DIGEST_SIZE 32
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_
diff --git a/include/nativebridge/native_bridge.h b/include/nativebridge/native_bridge.h
index 18300bc..9bfc935 100644
--- a/include/nativebridge/native_bridge.h
+++ b/include/nativebridge/native_bridge.h
@@ -62,12 +62,19 @@
 bool NativeBridgeInitialized();
 
 // Load a shared library that is supported by the native bridge.
+//
+// Starting with v3, NativeBridge has two scenarios: with/without namespace.
+// Use NativeBridgeLoadLibraryExt() instead in namespace scenario.
 void* NativeBridgeLoadLibrary(const char* libpath, int flag);
 
 // Get a native bridge trampoline for specified native method.
 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len);
 
-// True if native library is valid and is for an ABI that is supported by native bridge.
+// True if native library paths are valid and is for an ABI that is supported by native bridge.
+// The *libpath* must point to a library.
+//
+// Starting with v3, NativeBridge has two scenarios: with/without namespace.
+// Use NativeBridgeIsPathSupported() instead in namespace scenario.
 bool NativeBridgeIsSupported(const char* libpath);
 
 // Returns the version number of the native bridge. This information is available after a
@@ -91,6 +98,72 @@
 // This functionality is exposed mainly for testing.
 bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename);
 
+// Decrements the reference count on the dynamic library handler. If the reference count drops
+// to zero then the dynamic library is unloaded.
+int NativeBridgeUnloadLibrary(void* handle);
+
+// Get last error message of native bridge when fail to load library or search symbol.
+// This is reflection of dlerror() for native bridge.
+const char* NativeBridgeGetError();
+
+struct native_bridge_namespace_t;
+
+// True if native library paths are valid and is for an ABI that is supported by native bridge.
+// Different from NativeBridgeIsSupported(), the *path* here must be a directory containing
+// libraries of an ABI.
+//
+// Starting with v3, NativeBridge has two scenarios: with/without namespace.
+// Use NativeBridgeIsSupported() instead in non-namespace scenario.
+bool NativeBridgeIsPathSupported(const char* path);
+
+// 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 NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path);
+
+// 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.
+native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
+                                                       const char* ld_library_path,
+                                                       const char* default_library_path,
+                                                       uint64_t type,
+                                                       const char* permitted_when_isolated_path,
+                                                       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.
+void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns);
+
+// Returns vendor namespace if it is enabled for the device and null otherwise
+native_bridge_namespace_t* NativeBridgeGetVendorNamespace();
+
 // Native bridge interfaces to runtime.
 struct NativeBridgeCallbacks {
   // Version number of the interface.
@@ -103,7 +176,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);
 
@@ -114,6 +187,9 @@
   //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
   // Returns:
   //   The opaque handle of the shared library if sucessful, otherwise NULL
+  //
+  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
+  // Use loadLibraryExt instead in namespace scenario.
   void* (*loadLibrary)(const char* libpath, int flag);
 
   // Get a native bridge trampoline for specified native method. The trampoline has same
@@ -133,16 +209,19 @@
   //   libpath [IN] path to the shared library
   // Returns:
   //   TRUE if library is supported by native bridge, FALSE otherwise
+  //
+  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
+  // Use isPathSupported instead in namespace scenario.
   bool (*isSupported)(const char* libpath);
 
   // Provide environment values required by the app running with native bridge according to the
   // 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.
@@ -151,9 +230,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
@@ -162,13 +241,125 @@
   // 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.
+
+  // Decrements the reference count on the dynamic library handler. If the reference count drops
+  // to zero then the dynamic library is unloaded.
+  //
+  // Parameters:
+  //   handle [IN] the handler of a dynamic library.
+  //
+  // Returns:
+  //   0 on success, and nonzero on error.
+  int (*unloadLibrary)(void* handle);
+
+  // Dump the last failure message of native bridge when fail to load library or search symbol.
+  //
+  // Parameters:
+  //
+  // Returns:
+  //   A string describing the most recent error that occurred when load library
+  //   or lookup symbol via native bridge.
+  const char* (*getError)();
+
+  // Check whether library paths are supported by native bridge.
+  //
+  // Parameters:
+  //   library_path [IN] search paths for native libraries (directories separated by ':')
+  // Returns:
+  //   TRUE if libraries within search paths are supported by native bridge, FALSE otherwise
+  //
+  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
+  // Use isSupported instead in non-namespace scenario.
+  bool (*isPathSupported)(const char* library_path);
+
+  // 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.
+  // Returns:
+  //   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 (*initAnonymousNamespace)(const char* public_ns_sonames, const char* anon_ns_library_path);
+
+  // 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.
+  // Returns:
+  //   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.
+  native_bridge_namespace_t* (*createNamespace)(const char* name,
+                                                const char* ld_library_path,
+                                                const char* default_library_path,
+                                                uint64_t type,
+                                                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
+  //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
+  //   ns [IN] the pointer of the namespace in which the library should be loaded.
+  // Returns:
+  //   The opaque handle of the shared library if sucessful, otherwise NULL
+  //
+  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
+  // Use loadLibrary instead in non-namespace scenario.
+  void* (*loadLibraryExt)(const char* libpath, int flag, native_bridge_namespace_t* ns);
+
+  // Get native bridge version of vendor namespace.
+  // The vendor namespace is the namespace used to load vendor public libraries.
+  // With O release this namespace can be different from the default namespace.
+  // For the devices without enable vendor namespaces this function should return null
+  //
+  // Returns:
+  //   vendor namespace or null if it was not set up for the device
+  native_bridge_namespace_t* (*getVendorNamespace)();
 };
 
 // Runtime interfaces to native bridge.
diff --git a/include/private/android_filesystem_capability.h b/include/private/android_filesystem_capability.h
deleted file mode 100644
index b92d3db..0000000
--- a/include/private/android_filesystem_capability.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Taken from linux/capability.h, with minor modifications
- */
-
-#ifndef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_FILESYSTEM_CAPABILITY_H
-#define _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_FILESYSTEM_CAPABILITY_H
-
-#include <stdint.h>
-
-#define __user
-#define __u32 uint32_t
-#define __le32 uint32_t
-
-#define _LINUX_CAPABILITY_VERSION_1 0x19980330
-#define _LINUX_CAPABILITY_U32S_1 1
-#define _LINUX_CAPABILITY_VERSION_2 0x20071026
-#define _LINUX_CAPABILITY_U32S_2 2
-#define _LINUX_CAPABILITY_VERSION_3 0x20080522
-#define _LINUX_CAPABILITY_U32S_3 2
-
-typedef struct __user_cap_header_struct {
- __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;
-
-#define VFS_CAP_REVISION_MASK 0xFF000000
-#define VFS_CAP_REVISION_SHIFT 24
-#define VFS_CAP_FLAGS_MASK ~VFS_CAP_REVISION_MASK
-#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 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 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];
-};
-
-#define _LINUX_CAPABILITY_VERSION _LINUX_CAPABILITY_VERSION_1
-#define _LINUX_CAPABILITY_U32S _LINUX_CAPABILITY_U32S_1
-#define CAP_CHOWN 0
-#define CAP_DAC_OVERRIDE 1
-#define CAP_DAC_READ_SEARCH 2
-#define CAP_FOWNER 3
-#define CAP_FSETID 4
-#define CAP_KILL 5
-#define CAP_SETGID 6
-#define CAP_SETUID 7
-#define CAP_SETPCAP 8
-#define CAP_LINUX_IMMUTABLE 9
-#define CAP_NET_BIND_SERVICE 10
-#define CAP_NET_BROADCAST 11
-#define CAP_NET_ADMIN 12
-#define CAP_NET_RAW 13
-#define CAP_IPC_LOCK 14
-#define CAP_IPC_OWNER 15
-#define CAP_SYS_MODULE 16
-#define CAP_SYS_RAWIO 17
-#define CAP_SYS_CHROOT 18
-#define CAP_SYS_PTRACE 19
-#define CAP_SYS_PACCT 20
-#define CAP_SYS_ADMIN 21
-#define CAP_SYS_BOOT 22
-#define CAP_SYS_NICE 23
-#define CAP_SYS_RESOURCE 24
-#define CAP_SYS_TIME 25
-#define CAP_SYS_TTY_CONFIG 26
-#define CAP_MKNOD 27
-#define CAP_LEASE 28
-#define CAP_AUDIT_WRITE 29
-#define CAP_AUDIT_CONTROL 30
-#define CAP_SETFCAP 31
-#define CAP_MAC_OVERRIDE 32
-#define CAP_MAC_ADMIN 33
-#define CAP_SYSLOG 34
-#define CAP_WAKE_ALARM 35
-#define CAP_BLOCK_SUSPEND 36
-#define CAP_AUDIT_READ 37
-#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))
-
-#undef __user
-#undef __u32
-#undef __le32
-
-#endif
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 5ccd80e..0000000
--- a/include/private/android_filesystem_config.h
+++ /dev/null
@@ -1,264 +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.
-*/
-
-#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) */
-/* 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_NET_BT_STACK  3008  /* bluetooth: access config files */
-#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  /* first app user */
-
-#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  /* offset for uid ranges for each user */
-
-#define AID_SHARED_GID_START 50000 /* start of gids for apps in each user to share */
-#define AID_SHARED_GID_END   59999 /* start of gids for apps in each user to share */
-
-#if !defined(EXCLUDE_FS_CONFIG_STRUCTURES)
-/*
- * Used in:
- *  bionic/libc/bionic/stubs.cpp
- *  external/libselinux/src/android.c
- *  system/core/logd/LogStatistics.cpp
- *  system/core/init/ueventd.cpp
- *  system/core/init/util.cpp
- */
-struct android_id_info {
-    const char *name;
-    unsigned aid;
-};
-
-static const struct android_id_info android_ids[] = {
-    { "root",          AID_ROOT, },
-
-    { "system",        AID_SYSTEM, },
-
-    { "radio",         AID_RADIO, },
-    { "bluetooth",     AID_BLUETOOTH, },
-    { "graphics",      AID_GRAPHICS, },
-    { "input",         AID_INPUT, },
-    { "audio",         AID_AUDIO, },
-    { "camera",        AID_CAMERA, },
-    { "log",           AID_LOG, },
-    { "compass",       AID_COMPASS, },
-    { "mount",         AID_MOUNT, },
-    { "wifi",          AID_WIFI, },
-    { "adb",           AID_ADB, },
-    { "install",       AID_INSTALL, },
-    { "media",         AID_MEDIA, },
-    { "dhcp",          AID_DHCP, },
-    { "sdcard_rw",     AID_SDCARD_RW, },
-    { "vpn",           AID_VPN, },
-    { "keystore",      AID_KEYSTORE, },
-    { "usb",           AID_USB, },
-    { "drm",           AID_DRM, },
-    { "mdnsr",         AID_MDNSR, },
-    { "gps",           AID_GPS, },
-    // AID_UNUSED1
-    { "media_rw",      AID_MEDIA_RW, },
-    { "mtp",           AID_MTP, },
-    // AID_UNUSED2
-    { "drmrpc",        AID_DRMRPC, },
-    { "nfc",           AID_NFC, },
-    { "sdcard_r",      AID_SDCARD_R, },
-    { "clat",          AID_CLAT, },
-    { "loop_radio",    AID_LOOP_RADIO, },
-    { "mediadrm",      AID_MEDIA_DRM, },
-    { "package_info",  AID_PACKAGE_INFO, },
-    { "sdcard_pics",   AID_SDCARD_PICS, },
-    { "sdcard_av",     AID_SDCARD_AV, },
-    { "sdcard_all",    AID_SDCARD_ALL, },
-    { "logd",          AID_LOGD, },
-    { "shared_relro",  AID_SHARED_RELRO, },
-    { "dbus",          AID_DBUS, },
-    { "tlsdate",       AID_TLSDATE, },
-    { "mediaex",       AID_MEDIA_EX, },
-    { "audioserver",   AID_AUDIOSERVER, },
-    { "metrics_coll",  AID_METRICS_COLL },
-    { "metricsd",      AID_METRICSD },
-    { "webserv",       AID_WEBSERV },
-    { "debuggerd",     AID_DEBUGGERD, },
-    { "mediacodec",    AID_MEDIA_CODEC, },
-    { "cameraserver",  AID_CAMERASERVER, },
-    { "firewall",      AID_FIREWALL, },
-    { "trunks",        AID_TRUNKS, },
-    { "nvram",         AID_NVRAM, },
-    { "dns",           AID_DNS, },
-    { "dns_tether",    AID_DNS_TETHER, },
-
-    { "shell",         AID_SHELL, },
-    { "cache",         AID_CACHE, },
-    { "diag",          AID_DIAG, },
-
-    { "net_bt_admin",  AID_NET_BT_ADMIN, },
-    { "net_bt",        AID_NET_BT, },
-    { "inet",          AID_INET, },
-    { "net_raw",       AID_NET_RAW, },
-    { "net_admin",     AID_NET_ADMIN, },
-    { "net_bw_stats",  AID_NET_BW_STATS, },
-    { "net_bw_acct",   AID_NET_BW_ACCT, },
-    { "net_bt_stack",  AID_NET_BT_STACK, },
-    { "readproc",      AID_READPROC, },
-    { "wakelock",      AID_WAKELOCK, },
-
-    { "everybody",     AID_EVERYBODY, },
-    { "misc",          AID_MISC, },
-    { "nobody",        AID_NOBODY, },
-};
-
-#define android_id_count \
-    (sizeof(android_ids) / sizeof(android_ids[0]))
-
-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/android_logger.h b/include/private/android_logger.h
deleted file mode 100644
index c3ea1ed..0000000
--- a/include/private/android_logger.h
+++ /dev/null
@@ -1,132 +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.
- */
-
-/* This file is used to define the internal protocol for the Android Logger */
-
-#ifndef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
-#define _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
-
-/* Android private interfaces */
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <log/log.h>
-#include <log/log_read.h>
-
-#define LOGGER_MAGIC 'l'
-
-/* Header Structure to pstore */
-typedef struct __attribute__((__packed__)) {
-    uint8_t magic;
-    uint16_t len;
-    uint16_t uid;
-    uint16_t pid;
-} android_pmsg_log_header_t;
-
-/* Header Structure to logd, and second header for pstore */
-typedef struct __attribute__((__packed__)) {
-    typeof_log_id_t id;
-    uint16_t tid;
-    log_time realtime;
-} android_log_header_t;
-
-/* Event Header Structure to logd */
-typedef struct __attribute__((__packed__)) {
-    int32_t tag;  // Little Endian Order
-} android_event_header_t;
-
-/* Event payload EVENT_TYPE_INT */
-typedef struct __attribute__((__packed__)) {
-    int8_t type;  // EVENT_TYPE_INT
-    int32_t data; // Little Endian Order
-} android_event_int_t;
-
-/* Event with single EVENT_TYPE_INT */
-typedef struct __attribute__((__packed__)) {
-    android_event_header_t header;
-    android_event_int_t payload;
-} android_log_event_int_t;
-
-/* Event payload EVENT_TYPE_LONG */
-typedef struct __attribute__((__packed__)) {
-    int8_t type;  // EVENT_TYPE_LONG
-    int64_t data; // Little Endian Order
-} android_event_long_t;
-
-/* Event with single EVENT_TYPE_LONG */
-typedef struct __attribute__((__packed__)) {
-    android_event_header_t header;
-    android_event_long_t payload;
-} android_log_event_long_t;
-
-/*
- * Event payload EVENT_TYPE_STRING
- *
- * Danger: do not embed this structure into another structure.
- * This structure uses a flexible array member, and when
- * compiled using g++, __builtin_object_size(data, 1) returns
- * a bad value. This is possibly a g++ bug, or a bug due to
- * the fact that flexible array members are not supported
- * in C++.
- * http://stackoverflow.com/questions/4412749/are-flexible-array-members-valid-in-c
- */
-typedef struct __attribute__((__packed__)) {
-    int8_t type;    // EVENT_TYPE_STRING;
-    int32_t length; // Little Endian Order
-    char data[];
-} android_event_string_t;
-
-/* Event with single EVENT_TYPE_STRING */
-typedef struct __attribute__((__packed__)) {
-    android_event_header_t header;
-    int8_t type;    // EVENT_TYPE_STRING;
-    int32_t length; // Little Endian Order
-    char data[];
-} android_log_event_string_t;
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-#define ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE 256 /* 1MB file */
-#define ANDROID_LOG_PMSG_FILE_SEQUENCE     1000
-
-ssize_t __android_log_pmsg_file_write(
-        log_id_t logId,
-        char prio,
-        const char *filename,
-        const char *buf, size_t len);
-
-#define LOG_ID_ANY      ((log_id_t)-1)
-#define ANDROID_LOG_ANY ANDROID_LOG_UNKNOWN
-
-/* first 5 arguments match __android_log_msg_file_write, a cast is safe */
-typedef ssize_t (*__android_log_pmsg_file_read_fn)(
-        log_id_t logId,
-        char prio,
-        const char *filename,
-        const char *buf, size_t len, void *arg);
-
-ssize_t __android_log_pmsg_file_read(
-        log_id_t logId, char prio, const char *prefix,
-        __android_log_pmsg_file_read_fn fn, void *arg);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_ */
diff --git a/include/private/android_logger.h b/include/private/android_logger.h
new file mode 120000
index 0000000..f187a6d
--- /dev/null
+++ b/include/private/android_logger.h
@@ -0,0 +1 @@
+../../liblog/include/private/android_logger.h
\ No newline at end of file
diff --git a/include/private/canned_fs_config.h b/include/private/canned_fs_config.h
deleted file mode 100644
index d9f51ca..0000000
--- a/include/private/canned_fs_config.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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 _CANNED_FS_CONFIG_H
-#define _CANNED_FS_CONFIG_H
-
-#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);
-
-#endif
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..b443c36
--- /dev/null
+++ b/include/system
@@ -0,0 +1 @@
+../libsystem/include/system
\ No newline at end of file
diff --git a/include/system/graphics.h b/include/system/graphics.h
deleted file mode 100644
index 529a562..0000000
--- a/include/system/graphics.h
+++ /dev/null
@@ -1,1413 +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 SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
-#define SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
-
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * If the HAL needs to create service threads to handle graphics related
- * tasks, these threads need to run at HAL_PRIORITY_URGENT_DISPLAY priority
- * if they can block the main rendering thread in any way.
- *
- * the priority of the current thread can be set with:
- *
- *      #include <sys/resource.h>
- *      setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
- *
- */
-
-#define HAL_PRIORITY_URGENT_DISPLAY     (-8)
-
-/**
- * pixel format definitions
- */
-
-typedef enum android_pixel_format {
-    /*
-     * "linear" color pixel formats:
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer.
-     *
-     * The color space determines, for example, if the formats are linear or
-     * gamma-corrected; or whether any special operations are performed when
-     * reading or writing into a buffer in one of these formats.
-     */
-    HAL_PIXEL_FORMAT_RGBA_8888          = 1,
-    HAL_PIXEL_FORMAT_RGBX_8888          = 2,
-    HAL_PIXEL_FORMAT_RGB_888            = 3,
-    HAL_PIXEL_FORMAT_RGB_565            = 4,
-    HAL_PIXEL_FORMAT_BGRA_8888          = 5,
-
-    /*
-     * 0x100 - 0x1FF
-     *
-     * This range is reserved for pixel formats that are specific to the HAL
-     * implementation.  Implementations can use any value in this range to
-     * communicate video pixel formats between their HAL modules.  These formats
-     * must not have an alpha channel.  Additionally, an EGLimage created from a
-     * gralloc buffer of one of these formats must be supported for use with the
-     * GL_OES_EGL_image_external OpenGL ES extension.
-     */
-
-    /*
-     * Android YUV format:
-     *
-     * This format is exposed outside of the HAL to software decoders and
-     * applications.  EGLImageKHR must support it in conjunction with the
-     * OES_EGL_image_external extension.
-     *
-     * YV12 is a 4:2:0 YCrCb planar format comprised of a WxH Y plane followed
-     * by (W/2) x (H/2) Cr and Cb planes.
-     *
-     * This format assumes
-     * - an even width
-     * - an even height
-     * - a horizontal stride multiple of 16 pixels
-     * - a vertical stride equal to the height
-     *
-     *   y_size = stride * height
-     *   c_stride = ALIGN(stride/2, 16)
-     *   c_size = c_stride * height/2
-     *   size = y_size + c_size * 2
-     *   cr_offset = y_size
-     *   cb_offset = y_size + c_size
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer.
-     */
-    HAL_PIXEL_FORMAT_YV12   = 0x32315659, // YCrCb 4:2:0 Planar
-
-
-    /*
-     * Android Y8 format:
-     *
-     * This format is exposed outside of the HAL to the framework.
-     * The expected gralloc usage flags are SW_* and HW_CAMERA_*,
-     * and no other HW_ flags will be used.
-     *
-     * Y8 is a YUV planar format comprised of a WxH Y plane,
-     * with each pixel being represented by 8 bits.
-     *
-     * It is equivalent to just the Y plane from YV12.
-     *
-     * This format assumes
-     * - an even width
-     * - an even height
-     * - a horizontal stride multiple of 16 pixels
-     * - a vertical stride equal to the height
-     *
-     *   size = stride * height
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer.
-     */
-    HAL_PIXEL_FORMAT_Y8     = 0x20203859,
-
-    /*
-     * Android Y16 format:
-     *
-     * This format is exposed outside of the HAL to the framework.
-     * The expected gralloc usage flags are SW_* and HW_CAMERA_*,
-     * and no other HW_ flags will be used.
-     *
-     * Y16 is a YUV planar format comprised of a WxH Y plane,
-     * with each pixel being represented by 16 bits.
-     *
-     * It is just like Y8, but has double the bits per pixel (little endian).
-     *
-     * This format assumes
-     * - an even width
-     * - an even height
-     * - a horizontal stride multiple of 16 pixels
-     * - a vertical stride equal to the height
-     * - strides are specified in pixels, not in bytes
-     *
-     *   size = stride * height * 2
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer, except that dataSpace field
-     * HAL_DATASPACE_DEPTH indicates that this buffer contains a depth
-     * image where each sample is a distance value measured by a depth camera,
-     * plus an associated confidence value.
-     */
-    HAL_PIXEL_FORMAT_Y16    = 0x20363159,
-
-    /*
-     * Android RAW sensor format:
-     *
-     * This format is exposed outside of the camera HAL to applications.
-     *
-     * RAW16 is a single-channel, 16-bit, little endian format, typically
-     * representing raw Bayer-pattern images from an image sensor, with minimal
-     * processing.
-     *
-     * The exact pixel layout of the data in the buffer is sensor-dependent, and
-     * needs to be queried from the camera device.
-     *
-     * Generally, not all 16 bits are used; more common values are 10 or 12
-     * bits. If not all bits are used, the lower-order bits are filled first.
-     * All parameters to interpret the raw data (black and white points,
-     * color space, etc) must be queried from the camera device.
-     *
-     * This format assumes
-     * - an even width
-     * - an even height
-     * - a horizontal stride multiple of 16 pixels
-     * - a vertical stride equal to the height
-     * - strides are specified in pixels, not in bytes
-     *
-     *   size = stride * height * 2
-     *
-     * This format must be accepted by the gralloc module when used with the
-     * following usage flags:
-     *    - GRALLOC_USAGE_HW_CAMERA_*
-     *    - GRALLOC_USAGE_SW_*
-     *    - GRALLOC_USAGE_RENDERSCRIPT
-     *
-     * When used with ANativeWindow, the dataSpace should be
-     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
-     * extra metadata to define.
-     */
-    HAL_PIXEL_FORMAT_RAW16 = 0x20,
-
-    /*
-     * Android RAW10 format:
-     *
-     * This format is exposed outside of the camera HAL to applications.
-     *
-     * RAW10 is a single-channel, 10-bit per pixel, densely packed in each row,
-     * unprocessed format, usually representing raw Bayer-pattern images coming from
-     * an image sensor.
-     *
-     * In an image buffer with this format, starting from the first pixel of each
-     * row, each 4 consecutive pixels are packed into 5 bytes (40 bits). Each one
-     * of the first 4 bytes contains the top 8 bits of each pixel, The fifth byte
-     * contains the 2 least significant bits of the 4 pixels, the exact layout data
-     * for each 4 consecutive pixels is illustrated below (Pi[j] stands for the jth
-     * bit of the ith pixel):
-     *
-     *          bit 7                                     bit 0
-     *          =====|=====|=====|=====|=====|=====|=====|=====|
-     * Byte 0: |P0[9]|P0[8]|P0[7]|P0[6]|P0[5]|P0[4]|P0[3]|P0[2]|
-     *         |-----|-----|-----|-----|-----|-----|-----|-----|
-     * Byte 1: |P1[9]|P1[8]|P1[7]|P1[6]|P1[5]|P1[4]|P1[3]|P1[2]|
-     *         |-----|-----|-----|-----|-----|-----|-----|-----|
-     * Byte 2: |P2[9]|P2[8]|P2[7]|P2[6]|P2[5]|P2[4]|P2[3]|P2[2]|
-     *         |-----|-----|-----|-----|-----|-----|-----|-----|
-     * Byte 3: |P3[9]|P3[8]|P3[7]|P3[6]|P3[5]|P3[4]|P3[3]|P3[2]|
-     *         |-----|-----|-----|-----|-----|-----|-----|-----|
-     * Byte 4: |P3[1]|P3[0]|P2[1]|P2[0]|P1[1]|P1[0]|P0[1]|P0[0]|
-     *          ===============================================
-     *
-     * This format assumes
-     * - a width multiple of 4 pixels
-     * - an even height
-     * - a vertical stride equal to the height
-     * - strides are specified in bytes, not in pixels
-     *
-     *   size = stride * height
-     *
-     * When stride is equal to width * (10 / 8), there will be no padding bytes at
-     * the end of each row, the entire image data is densely packed. When stride is
-     * larger than width * (10 / 8), padding bytes will be present at the end of each
-     * row (including the last row).
-     *
-     * This format must be accepted by the gralloc module when used with the
-     * following usage flags:
-     *    - GRALLOC_USAGE_HW_CAMERA_*
-     *    - GRALLOC_USAGE_SW_*
-     *    - GRALLOC_USAGE_RENDERSCRIPT
-     *
-     * When used with ANativeWindow, the dataSpace field should be
-     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
-     * extra metadata to define.
-     */
-    HAL_PIXEL_FORMAT_RAW10 = 0x25,
-
-    /*
-     * Android RAW12 format:
-     *
-     * This format is exposed outside of camera HAL to applications.
-     *
-     * RAW12 is a single-channel, 12-bit per pixel, densely packed in each row,
-     * unprocessed format, usually representing raw Bayer-pattern images coming from
-     * an image sensor.
-     *
-     * In an image buffer with this format, starting from the first pixel of each
-     * row, each two consecutive pixels are packed into 3 bytes (24 bits). The first
-     * and second byte contains the top 8 bits of first and second pixel. The third
-     * byte contains the 4 least significant bits of the two pixels, the exact layout
-     * data for each two consecutive pixels is illustrated below (Pi[j] stands for
-     * the jth bit of the ith pixel):
-     *
-     *           bit 7                                            bit 0
-     *          ======|======|======|======|======|======|======|======|
-     * Byte 0: |P0[11]|P0[10]|P0[ 9]|P0[ 8]|P0[ 7]|P0[ 6]|P0[ 5]|P0[ 4]|
-     *         |------|------|------|------|------|------|------|------|
-     * Byte 1: |P1[11]|P1[10]|P1[ 9]|P1[ 8]|P1[ 7]|P1[ 6]|P1[ 5]|P1[ 4]|
-     *         |------|------|------|------|------|------|------|------|
-     * Byte 2: |P1[ 3]|P1[ 2]|P1[ 1]|P1[ 0]|P0[ 3]|P0[ 2]|P0[ 1]|P0[ 0]|
-     *          =======================================================
-     *
-     * This format assumes:
-     * - a width multiple of 4 pixels
-     * - an even height
-     * - a vertical stride equal to the height
-     * - strides are specified in bytes, not in pixels
-     *
-     *   size = stride * height
-     *
-     * When stride is equal to width * (12 / 8), there will be no padding bytes at
-     * the end of each row, the entire image data is densely packed. When stride is
-     * larger than width * (12 / 8), padding bytes will be present at the end of
-     * each row (including the last row).
-     *
-     * This format must be accepted by the gralloc module when used with the
-     * following usage flags:
-     *    - GRALLOC_USAGE_HW_CAMERA_*
-     *    - GRALLOC_USAGE_SW_*
-     *    - GRALLOC_USAGE_RENDERSCRIPT
-     *
-     * When used with ANativeWindow, the dataSpace field should be
-     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
-     * extra metadata to define.
-     */
-    HAL_PIXEL_FORMAT_RAW12 = 0x26,
-
-    /*
-     * Android opaque RAW format:
-     *
-     * This format is exposed outside of the camera HAL to applications.
-     *
-     * RAW_OPAQUE is a format for unprocessed raw image buffers coming from an
-     * image sensor. The actual structure of buffers of this format is
-     * implementation-dependent.
-     *
-     * This format must be accepted by the gralloc module when used with the
-     * following usage flags:
-     *    - GRALLOC_USAGE_HW_CAMERA_*
-     *    - GRALLOC_USAGE_SW_*
-     *    - GRALLOC_USAGE_RENDERSCRIPT
-     *
-     * When used with ANativeWindow, the dataSpace field should be
-     * HAL_DATASPACE_ARBITRARY, as raw image sensor buffers require substantial
-     * extra metadata to define.
-     */
-    HAL_PIXEL_FORMAT_RAW_OPAQUE = 0x24,
-
-    /*
-     * Android binary blob graphics buffer format:
-     *
-     * This format is used to carry task-specific data which does not have a
-     * standard image structure. The details of the format are left to the two
-     * endpoints.
-     *
-     * A typical use case is for transporting JPEG-compressed images from the
-     * Camera HAL to the framework or to applications.
-     *
-     * Buffers of this format must have a height of 1, and width equal to their
-     * size in bytes.
-     *
-     * When used with ANativeWindow, the mapping of the dataSpace field to
-     * buffer contents for BLOB is as follows:
-     *
-     *  dataSpace value               | Buffer contents
-     * -------------------------------+-----------------------------------------
-     *  HAL_DATASPACE_JFIF            | An encoded JPEG image
-     *  HAL_DATASPACE_DEPTH           | An android_depth_points buffer
-     *  Other                         | Unsupported
-     *
-     */
-    HAL_PIXEL_FORMAT_BLOB = 0x21,
-
-    /*
-     * Android format indicating that the choice of format is entirely up to the
-     * device-specific Gralloc implementation.
-     *
-     * The Gralloc implementation should examine the usage bits passed in when
-     * allocating a buffer with this format, and it should derive the pixel
-     * format from those usage flags.  This format will never be used with any
-     * of the GRALLOC_USAGE_SW_* usage flags.
-     *
-     * If a buffer of this format is to be used as an OpenGL ES texture, the
-     * framework will assume that sampling the texture will always return an
-     * alpha value of 1.0 (i.e. the buffer contains only opaque pixel values).
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer.
-     */
-    HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 0x22,
-
-    /*
-     * Android flexible YCbCr 4:2:0 formats
-     *
-     * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:0
-     * buffer layout, while still describing the general format in a
-     * layout-independent manner.  While called YCbCr, it can be
-     * used to describe formats with either chromatic ordering, as well as
-     * whole planar or semiplanar layouts.
-     *
-     * struct android_ycbcr (below) is the the struct used to describe it.
-     *
-     * This format must be accepted by the gralloc module when
-     * USAGE_SW_WRITE_* or USAGE_SW_READ_* are set.
-     *
-     * This format is locked for use by gralloc's (*lock_ycbcr) method, and
-     * locking with the (*lock) method will return an error.
-     *
-     * When used with ANativeWindow, the dataSpace field describes the color
-     * space of the buffer.
-     */
-    HAL_PIXEL_FORMAT_YCbCr_420_888 = 0x23,
-
-    /*
-     * Android flexible YCbCr 4:2:2 formats
-     *
-     * This format allows platforms to use an efficient YCbCr/YCrCb 4:2:2
-     * buffer layout, while still describing the general format in a
-     * layout-independent manner.  While called YCbCr, it can be
-     * used to describe formats with either chromatic ordering, as well as
-     * whole planar or semiplanar layouts.
-     *
-     * This format is currently only used by SW readable buffers
-     * produced by MediaCodecs, so the gralloc module can ignore this format.
-     */
-    HAL_PIXEL_FORMAT_YCbCr_422_888 = 0x27,
-
-    /*
-     * Android flexible YCbCr 4:4:4 formats
-     *
-     * This format allows platforms to use an efficient YCbCr/YCrCb 4:4:4
-     * buffer layout, while still describing the general format in a
-     * layout-independent manner.  While called YCbCr, it can be
-     * used to describe formats with either chromatic ordering, as well as
-     * whole planar or semiplanar layouts.
-     *
-     * This format is currently only used by SW readable buffers
-     * produced by MediaCodecs, so the gralloc module can ignore this format.
-     */
-    HAL_PIXEL_FORMAT_YCbCr_444_888 = 0x28,
-
-    /*
-     * Android flexible RGB 888 formats
-     *
-     * This format allows platforms to use an efficient RGB/BGR/RGBX/BGRX
-     * buffer layout, while still describing the general format in a
-     * layout-independent manner.  While called RGB, it can be
-     * used to describe formats with either color ordering and optional
-     * padding, as well as whole planar layout.
-     *
-     * This format is currently only used by SW readable buffers
-     * produced by MediaCodecs, so the gralloc module can ignore this format.
-     */
-    HAL_PIXEL_FORMAT_FLEX_RGB_888 = 0x29,
-
-    /*
-     * Android flexible RGBA 8888 formats
-     *
-     * This format allows platforms to use an efficient RGBA/BGRA/ARGB/ABGR
-     * buffer layout, while still describing the general format in a
-     * layout-independent manner.  While called RGBA, it can be
-     * used to describe formats with any of the component orderings, as
-     * well as whole planar layout.
-     *
-     * This format is currently only used by SW readable buffers
-     * produced by MediaCodecs, so the gralloc module can ignore this format.
-     */
-    HAL_PIXEL_FORMAT_FLEX_RGBA_8888 = 0x2A,
-
-    /* Legacy formats (deprecated), used by ImageFormat.java */
-    HAL_PIXEL_FORMAT_YCbCr_422_SP       = 0x10, // NV16
-    HAL_PIXEL_FORMAT_YCrCb_420_SP       = 0x11, // NV21
-    HAL_PIXEL_FORMAT_YCbCr_422_I        = 0x14, // YUY2
-} android_pixel_format_t;
-
-/*
- * Structure for describing YCbCr formats for consumption by applications.
- * This is used with HAL_PIXEL_FORMAT_YCbCr_*_888.
- *
- * Buffer chroma subsampling is defined in the format.
- * e.g. HAL_PIXEL_FORMAT_YCbCr_420_888 has subsampling 4:2:0.
- *
- * Buffers must have a 8 bit depth.
- *
- * @y, @cb, and @cr point to the first byte of their respective planes.
- *
- * Stride describes the distance in bytes from the first value of one row of
- * the image to the first value of the next row.  It includes the width of the
- * image plus padding.
- * @ystride is the stride of the luma plane.
- * @cstride is the stride of the chroma planes.
- *
- * @chroma_step is the distance in bytes from one chroma pixel value to the
- * next.  This is 2 bytes for semiplanar (because chroma values are interleaved
- * and each chroma value is one byte) and 1 for planar.
- */
-
-struct android_ycbcr {
-    void *y;
-    void *cb;
-    void *cr;
-    size_t ystride;
-    size_t cstride;
-    size_t chroma_step;
-
-    /** reserved for future use, set to 0 by gralloc's (*lock_ycbcr)() */
-    uint32_t reserved[8];
-};
-
-/*
- * Structures for describing flexible YUVA/RGBA formats for consumption by
- * applications. Such flexible formats contain a plane for each component (e.g.
- * red, green, blue), where each plane is laid out in a grid-like pattern
- * occupying unique byte addresses and with consistent byte offsets between
- * neighboring pixels.
- *
- * The android_flex_layout structure is used with any pixel format that can be
- * represented by it, such as:
- *  - HAL_PIXEL_FORMAT_YCbCr_*_888
- *  - HAL_PIXEL_FORMAT_FLEX_RGB*_888
- *  - HAL_PIXEL_FORMAT_RGB[AX]_888[8],BGRA_8888,RGB_888
- *  - HAL_PIXEL_FORMAT_YV12,Y8,Y16,YCbCr_422_SP/I,YCrCb_420_SP
- *  - even implementation defined formats that can be represented by
- *    the structures
- *
- * Vertical increment (aka. row increment or stride) describes the distance in
- * bytes from the first pixel of one row to the first pixel of the next row
- * (below) for the component plane. This can be negative.
- *
- * Horizontal increment (aka. column or pixel increment) describes the distance
- * in bytes from one pixel to the next pixel (to the right) on the same row for
- * the component plane. This can be negative.
- *
- * Each plane can be subsampled either vertically or horizontally by
- * a power-of-two factor.
- *
- * The bit-depth of each component can be arbitrary, as long as the pixels are
- * laid out on whole bytes, in native byte-order, using the most significant
- * bits of each unit.
- */
-
-typedef enum android_flex_component {
-    /* luma */
-    FLEX_COMPONENT_Y = 1 << 0,
-    /* chroma blue */
-    FLEX_COMPONENT_Cb = 1 << 1,
-    /* chroma red */
-    FLEX_COMPONENT_Cr = 1 << 2,
-
-    /* red */
-    FLEX_COMPONENT_R = 1 << 10,
-    /* green */
-    FLEX_COMPONENT_G = 1 << 11,
-    /* blue */
-    FLEX_COMPONENT_B = 1 << 12,
-
-    /* alpha */
-    FLEX_COMPONENT_A = 1 << 30,
-} android_flex_component_t;
-
-typedef struct android_flex_plane {
-    /* pointer to the first byte of the top-left pixel of the plane. */
-    uint8_t *top_left;
-
-    android_flex_component_t component;
-
-    /* bits allocated for the component in each pixel. Must be a positive
-       multiple of 8. */
-    int32_t bits_per_component;
-    /* number of the most significant bits used in the format for this
-       component. Must be between 1 and bits_per_component, inclusive. */
-    int32_t bits_used;
-
-    /* horizontal increment */
-    int32_t h_increment;
-    /* vertical increment */
-    int32_t v_increment;
-    /* horizontal subsampling. Must be a positive power of 2. */
-    int32_t h_subsampling;
-    /* vertical subsampling. Must be a positive power of 2. */
-    int32_t v_subsampling;
-} android_flex_plane_t;
-
-typedef enum android_flex_format {
-    /* not a flexible format */
-    FLEX_FORMAT_INVALID = 0x0,
-    FLEX_FORMAT_Y = FLEX_COMPONENT_Y,
-    FLEX_FORMAT_YCbCr = FLEX_COMPONENT_Y | FLEX_COMPONENT_Cb | FLEX_COMPONENT_Cr,
-    FLEX_FORMAT_YCbCrA = FLEX_FORMAT_YCbCr | FLEX_COMPONENT_A,
-    FLEX_FORMAT_RGB = FLEX_COMPONENT_R | FLEX_COMPONENT_G | FLEX_COMPONENT_B,
-    FLEX_FORMAT_RGBA = FLEX_FORMAT_RGB | FLEX_COMPONENT_A,
-} android_flex_format_t;
-
-typedef struct android_flex_layout {
-    /* the kind of flexible format */
-    android_flex_format_t format;
-
-    /* number of planes; 0 for FLEX_FORMAT_INVALID */
-    uint32_t num_planes;
-    /* a plane for each component; ordered in increasing component value order.
-       E.g. FLEX_FORMAT_RGBA maps 0 -> R, 1 -> G, etc.
-       Can be NULL for FLEX_FORMAT_INVALID */
-    android_flex_plane_t *planes;
-} android_flex_layout_t;
-
-/**
- * Structure used to define depth point clouds for format HAL_PIXEL_FORMAT_BLOB
- * with dataSpace value of HAL_DATASPACE_DEPTH.
- * When locking a native buffer of the above format and dataSpace value,
- * the vaddr pointer can be cast to this structure.
- *
- * A variable-length list of (x,y,z, confidence) 3D points, as floats.  (x, y,
- * z) represents a measured point's position, with the coordinate system defined
- * by the data source.  Confidence represents the estimated likelihood that this
- * measurement is correct. It is between 0.f and 1.f, inclusive, with 1.f ==
- * 100% confidence.
- *
- * @num_points is the number of points in the list
- *
- * @xyz_points is the flexible array of floating-point values.
- *   It contains (num_points) * 4 floats.
- *
- *   For example:
- *     android_depth_points d = get_depth_buffer();
- *     struct {
- *       float x; float y; float z; float confidence;
- *     } firstPoint, lastPoint;
- *
- *     firstPoint.x = d.xyzc_points[0];
- *     firstPoint.y = d.xyzc_points[1];
- *     firstPoint.z = d.xyzc_points[2];
- *     firstPoint.confidence = d.xyzc_points[3];
- *     lastPoint.x = d.xyzc_points[(d.num_points - 1) * 4 + 0];
- *     lastPoint.y = d.xyzc_points[(d.num_points - 1) * 4 + 1];
- *     lastPoint.z = d.xyzc_points[(d.num_points - 1) * 4 + 2];
- *     lastPoint.confidence = d.xyzc_points[(d.num_points - 1) * 4 + 3];
- */
-
-struct android_depth_points {
-    uint32_t num_points;
-
-    /** reserved for future use, set to 0 by gralloc's (*lock)() */
-    uint32_t reserved[8];
-
-    float xyzc_points[];
-};
-
-/**
- * Transformation definitions
- *
- * IMPORTANT NOTE:
- * HAL_TRANSFORM_ROT_90 is applied CLOCKWISE and AFTER HAL_TRANSFORM_FLIP_{H|V}.
- *
- */
-
-typedef enum android_transform {
-    /* flip source image horizontally (around the vertical axis) */
-    HAL_TRANSFORM_FLIP_H    = 0x01,
-    /* flip source image vertically (around the horizontal axis)*/
-    HAL_TRANSFORM_FLIP_V    = 0x02,
-    /* rotate source image 90 degrees clockwise */
-    HAL_TRANSFORM_ROT_90    = 0x04,
-    /* rotate source image 180 degrees */
-    HAL_TRANSFORM_ROT_180   = 0x03,
-    /* rotate source image 270 degrees clockwise */
-    HAL_TRANSFORM_ROT_270   = 0x07,
-    /* don't use. see system/window.h */
-    HAL_TRANSFORM_RESERVED  = 0x08,
-} android_transform_t;
-
-/**
- * Dataspace Definitions
- * ======================
- *
- * Dataspace is the definition of how pixel values should be interpreted.
- *
- * For many formats, this is the colorspace of the image data, which includes
- * primaries (including white point) and the transfer characteristic function,
- * which describes both gamma curve and numeric range (within the bit depth).
- *
- * Other dataspaces include depth measurement data from a depth camera.
- *
- * A dataspace is comprised of a number of fields.
- *
- * Version
- * --------
- * The top 2 bits represent the revision of the field specification. This is
- * currently always 0.
- *
- *
- * bits    31-30 29                      -                          0
- *        +-----+----------------------------------------------------+
- * fields | Rev |            Revision specific fields                |
- *        +-----+----------------------------------------------------+
- *
- * Field layout for version = 0:
- * ----------------------------
- *
- * A dataspace is comprised of the following fields:
- *      Standard
- *      Transfer function
- *      Range
- *
- * bits    31-30 29-27 26 -  22 21 -  16 15             -           0
- *        +-----+-----+--------+--------+----------------------------+
- * fields |  0  |Range|Transfer|Standard|    Legacy and custom       |
- *        +-----+-----+--------+--------+----------------------------+
- *          VV    RRR   TTTTT    SSSSSS    LLLLLLLL       LLLLLLLL
- *
- * If range, transfer and standard fields are all 0 (e.g. top 16 bits are
- * all zeroes), the bottom 16 bits contain either a legacy dataspace value,
- * or a custom value.
- */
-
-typedef enum android_dataspace {
-    /*
-     * Default-assumption data space, when not explicitly specified.
-     *
-     * It is safest to assume the buffer is an image with sRGB primaries and
-     * encoding ranges, but the consumer and/or the producer of the data may
-     * simply be using defaults. No automatic gamma transform should be
-     * expected, except for a possible display gamma transform when drawn to a
-     * screen.
-     */
-    HAL_DATASPACE_UNKNOWN = 0x0,
-
-    /*
-     * Arbitrary dataspace with manually defined characteristics.  Definition
-     * for colorspaces or other meaning must be communicated separately.
-     *
-     * This is used when specifying primaries, transfer characteristics,
-     * etc. separately.
-     *
-     * A typical use case is in video encoding parameters (e.g. for H.264),
-     * where a colorspace can have separately defined primaries, transfer
-     * characteristics, etc.
-     */
-    HAL_DATASPACE_ARBITRARY = 0x1,
-
-    /*
-     * Color-description aspects
-     *
-     * The following aspects define various characteristics of the color
-     * specification. These represent bitfields, so that a data space value
-     * can specify each of them independently.
-     */
-
-    HAL_DATASPACE_STANDARD_SHIFT = 16,
-
-    /*
-     * Standard aspect
-     *
-     * Defines the chromaticity coordinates of the source primaries in terms of
-     * the CIE 1931 definition of x and y specified in ISO 11664-1.
-     */
-    HAL_DATASPACE_STANDARD_MASK = 63 << HAL_DATASPACE_STANDARD_SHIFT,  // 0x3F
-
-    /*
-     * Chromacity coordinates are unknown or are determined by the application.
-     * Implementations shall use the following suggested standards:
-     *
-     * All YCbCr formats: BT709 if size is 720p or larger (since most video
-     *                    content is letterboxed this corresponds to width is
-     *                    1280 or greater, or height is 720 or greater).
-     *                    BT601_625 if size is smaller than 720p or is JPEG.
-     * All RGB formats:   BT709.
-     *
-     * For all other formats standard is undefined, and implementations should use
-     * an appropriate standard for the data represented.
-     */
-    HAL_DATASPACE_STANDARD_UNSPECIFIED = 0 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.300   0.600
-     *  blue            0.150   0.060
-     *  red             0.640   0.330
-     *  white (D65)     0.3127  0.3290
-     *
-     * Use the unadjusted KR = 0.2126, KB = 0.0722 luminance interpretation
-     * for RGB conversion.
-     */
-    HAL_DATASPACE_STANDARD_BT709 = 1 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.290   0.600
-     *  blue            0.150   0.060
-     *  red             0.640   0.330
-     *  white (D65)     0.3127  0.3290
-     *
-     *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
-     *  for RGB conversion from the one purely determined by the primaries
-     *  to minimize the color shift into RGB space that uses BT.709
-     *  primaries.
-     */
-    HAL_DATASPACE_STANDARD_BT601_625 = 2 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.290   0.600
-     *  blue            0.150   0.060
-     *  red             0.640   0.330
-     *  white (D65)     0.3127  0.3290
-     *
-     * Use the unadjusted KR = 0.222, KB = 0.071 luminance interpretation
-     * for RGB conversion.
-     */
-    HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED = 3 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.310   0.595
-     *  blue            0.155   0.070
-     *  red             0.630   0.340
-     *  white (D65)     0.3127  0.3290
-     *
-     *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
-     *  for RGB conversion from the one purely determined by the primaries
-     *  to minimize the color shift into RGB space that uses BT.709
-     *  primaries.
-     */
-    HAL_DATASPACE_STANDARD_BT601_525 = 4 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.310   0.595
-     *  blue            0.155   0.070
-     *  red             0.630   0.340
-     *  white (D65)     0.3127  0.3290
-     *
-     * Use the unadjusted KR = 0.212, KB = 0.087 luminance interpretation
-     * for RGB conversion (as in SMPTE 240M).
-     */
-    HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED = 5 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.170   0.797
-     *  blue            0.131   0.046
-     *  red             0.708   0.292
-     *  white (D65)     0.3127  0.3290
-     *
-     * Use the unadjusted KR = 0.2627, KB = 0.0593 luminance interpretation
-     * for RGB conversion.
-     */
-    HAL_DATASPACE_STANDARD_BT2020 = 6 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.170   0.797
-     *  blue            0.131   0.046
-     *  red             0.708   0.292
-     *  white (D65)     0.3127  0.3290
-     *
-     * Use the unadjusted KR = 0.2627, KB = 0.0593 luminance interpretation
-     * for RGB conversion using the linear domain.
-     */
-    HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE = 7 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x      y
-     *  green           0.21   0.71
-     *  blue            0.14   0.08
-     *  red             0.67   0.33
-     *  white (C)       0.310  0.316
-     *
-     * Use the unadjusted KR = 0.30, KB = 0.11 luminance interpretation
-     * for RGB conversion.
-     */
-    HAL_DATASPACE_STANDARD_BT470M = 8 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    /*
-     * Primaries:       x       y
-     *  green           0.243   0.692
-     *  blue            0.145   0.049
-     *  red             0.681   0.319
-     *  white (C)       0.310   0.316
-     *
-     * Use the unadjusted KR = 0.254, KB = 0.068 luminance interpretation
-     * for RGB conversion.
-     */
-    HAL_DATASPACE_STANDARD_FILM = 9 << HAL_DATASPACE_STANDARD_SHIFT,
-
-    HAL_DATASPACE_TRANSFER_SHIFT = 22,
-
-    /*
-     * Transfer aspect
-     *
-     * Transfer characteristics are the opto-electronic transfer characteristic
-     * at the source as a function of linear optical intensity (luminance).
-     *
-     * For digital signals, E corresponds to the recorded value. Normally, the
-     * transfer function is applied in RGB space to each of the R, G and B
-     * components independently. This may result in color shift that can be
-     * minized by applying the transfer function in Lab space only for the L
-     * component. Implementation may apply the transfer function in RGB space
-     * for all pixel formats if desired.
-     */
-
-    HAL_DATASPACE_TRANSFER_MASK = 31 << HAL_DATASPACE_TRANSFER_SHIFT,  // 0x1F
-
-    /*
-     * Transfer characteristics are unknown or are determined by the
-     * application.
-     *
-     * Implementations should use the following transfer functions:
-     *
-     * For YCbCr formats: use HAL_DATASPACE_TRANSFER_SMPTE_170M
-     * For RGB formats: use HAL_DATASPACE_TRANSFER_SRGB
-     *
-     * For all other formats transfer function is undefined, and implementations
-     * should use an appropriate standard for the data represented.
-     */
-    HAL_DATASPACE_TRANSFER_UNSPECIFIED = 0 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * Transfer characteristic curve:
-     *  E = L
-     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_LINEAR = 1 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * Transfer characteristic curve:
-     *
-     * E = 1.055 * L^(1/2.4) - 0.055  for 0.0031308 <= L <= 1
-     *   = 12.92 * L                  for 0 <= L < 0.0031308
-     *     L - luminance of image 0 <= L <= 1 for conventional colorimetry
-     *     E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_SRGB = 2 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * BT.601 525, BT.601 625, BT.709, BT.2020
-     *
-     * Transfer characteristic curve:
-     *  E = 1.099 * L ^ 0.45 - 0.099  for 0.018 <= L <= 1
-     *    = 4.500 * L                 for 0 <= L < 0.018
-     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_SMPTE_170M = 3 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * Assumed display gamma 2.2.
-     *
-     * Transfer characteristic curve:
-     *  E = L ^ (1/2.2)
-     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_GAMMA2_2 = 4 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     *  display gamma 2.8.
-     *
-     * Transfer characteristic curve:
-     *  E = L ^ (1/2.8)
-     *      L - luminance of image 0 <= L <= 1 for conventional colorimetry
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_GAMMA2_8 = 5 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * SMPTE ST 2084
-     *
-     * Transfer characteristic curve:
-     *  E = ((c1 + c2 * L^n) / (1 + c3 * L^n)) ^ m
-     *  c1 = c3 - c2 + 1 = 3424 / 4096 = 0.8359375
-     *  c2 = 32 * 2413 / 4096 = 18.8515625
-     *  c3 = 32 * 2392 / 4096 = 18.6875
-     *  m = 128 * 2523 / 4096 = 78.84375
-     *  n = 0.25 * 2610 / 4096 = 0.1593017578125
-     *      L - luminance of image 0 <= L <= 1 for HDR colorimetry.
-     *          L = 1 corresponds to 10000 cd/m2
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_ST2084 = 6 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    /*
-     * ARIB STD-B67 Hybrid Log Gamma
-     *
-     * Transfer characteristic curve:
-     *  E = r * L^0.5                 for 0 <= L <= 1
-     *    = a * ln(L - b) + c         for 1 < L
-     *  a = 0.17883277
-     *  b = 0.28466892
-     *  c = 0.55991073
-     *  r = 0.5
-     *      L - luminance of image 0 <= L for HDR colorimetry. L = 1 corresponds
-     *          to reference white level of 100 cd/m2
-     *      E - corresponding electrical signal
-     */
-    HAL_DATASPACE_TRANSFER_HLG = 7 << HAL_DATASPACE_TRANSFER_SHIFT,
-
-    HAL_DATASPACE_RANGE_SHIFT = 27,
-
-    /*
-     * Range aspect
-     *
-     * Defines the range of values corresponding to the unit range of 0-1.
-     * This is defined for YCbCr only, but can be expanded to RGB space.
-     */
-    HAL_DATASPACE_RANGE_MASK = 7 << HAL_DATASPACE_RANGE_SHIFT,  // 0x7
-
-    /*
-     * Range is unknown or are determined by the application.  Implementations
-     * shall use the following suggested ranges:
-     *
-     * All YCbCr formats: limited range.
-     * All RGB or RGBA formats (including RAW and Bayer): full range.
-     * All Y formats: full range
-     *
-     * For all other formats range is undefined, and implementations should use
-     * an appropriate range for the data represented.
-     */
-    HAL_DATASPACE_RANGE_UNSPECIFIED = 0 << HAL_DATASPACE_RANGE_SHIFT,
-
-    /*
-     * Full range uses all values for Y, Cb and Cr from
-     * 0 to 2^b-1, where b is the bit depth of the color format.
-     */
-    HAL_DATASPACE_RANGE_FULL = 1 << HAL_DATASPACE_RANGE_SHIFT,
-
-    /*
-     * Limited range uses values 16/256*2^b to 235/256*2^b for Y, and
-     * 1/16*2^b to 15/16*2^b for Cb, Cr, R, G and B, where b is the bit depth of
-     * the color format.
-     *
-     * E.g. For 8-bit-depth formats:
-     * Luma (Y) samples should range from 16 to 235, inclusive
-     * Chroma (Cb, Cr) samples should range from 16 to 240, inclusive
-     *
-     * For 10-bit-depth formats:
-     * Luma (Y) samples should range from 64 to 940, inclusive
-     * Chroma (Cb, Cr) samples should range from 64 to 960, inclusive
-     */
-    HAL_DATASPACE_RANGE_LIMITED = 2 << HAL_DATASPACE_RANGE_SHIFT,
-
-    /*
-     * Legacy dataspaces
-     */
-
-    /*
-     * sRGB linear encoding:
-     *
-     * The red, green, and blue components are stored in sRGB space, but
-     * are linear, not gamma-encoded.
-     * The RGB primaries and the white point are the same as BT.709.
-     *
-     * The values are encoded using the full range ([0,255] for 8-bit) for all
-     * components.
-     */
-    HAL_DATASPACE_SRGB_LINEAR = 0x200, // deprecated, use HAL_DATASPACE_V0_SRGB_LINEAR
-
-    HAL_DATASPACE_V0_SRGB_LINEAR = HAL_DATASPACE_STANDARD_BT709 |
-            HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL,
-
-
-    /*
-     * sRGB gamma encoding:
-     *
-     * The red, green and blue components are stored in sRGB space, and
-     * converted to linear space when read, using the SRGB transfer function
-     * for each of the R, G and B components. When written, the inverse
-     * transformation is performed.
-     *
-     * The alpha component, if present, is always stored in linear space and
-     * is left unmodified when read or written.
-     *
-     * Use full range and BT.709 standard.
-     */
-    HAL_DATASPACE_SRGB = 0x201, // deprecated, use HAL_DATASPACE_V0_SRGB
-
-    HAL_DATASPACE_V0_SRGB = HAL_DATASPACE_STANDARD_BT709 |
-            HAL_DATASPACE_TRANSFER_SRGB | HAL_DATASPACE_RANGE_FULL,
-
-
-    /*
-     * YCbCr Colorspaces
-     * -----------------
-     *
-     * Primaries are given using (x,y) coordinates in the CIE 1931 definition
-     * of x and y specified by ISO 11664-1.
-     *
-     * Transfer characteristics are the opto-electronic transfer characteristic
-     * at the source as a function of linear optical intensity (luminance).
-     */
-
-    /*
-     * JPEG File Interchange Format (JFIF)
-     *
-     * Same model as BT.601-625, but all values (Y, Cb, Cr) range from 0 to 255
-     *
-     * Use full range, BT.601 transfer and BT.601_625 standard.
-     */
-    HAL_DATASPACE_JFIF = 0x101, // deprecated, use HAL_DATASPACE_V0_JFIF
-
-    HAL_DATASPACE_V0_JFIF = HAL_DATASPACE_STANDARD_BT601_625 |
-            HAL_DATASPACE_TRANSFER_SMPTE_170M | HAL_DATASPACE_RANGE_FULL,
-
-    /*
-     * ITU-R Recommendation 601 (BT.601) - 625-line
-     *
-     * Standard-definition television, 625 Lines (PAL)
-     *
-     * Use limited range, BT.601 transfer and BT.601_625 standard.
-     */
-    HAL_DATASPACE_BT601_625 = 0x102, // deprecated, use HAL_DATASPACE_V0_BT601_625
-
-    HAL_DATASPACE_V0_BT601_625 = HAL_DATASPACE_STANDARD_BT601_625 |
-            HAL_DATASPACE_TRANSFER_SMPTE_170M | HAL_DATASPACE_RANGE_LIMITED,
-
-
-    /*
-     * ITU-R Recommendation 601 (BT.601) - 525-line
-     *
-     * Standard-definition television, 525 Lines (NTSC)
-     *
-     * Use limited range, BT.601 transfer and BT.601_525 standard.
-     */
-    HAL_DATASPACE_BT601_525 = 0x103, // deprecated, use HAL_DATASPACE_V0_BT601_525
-
-    HAL_DATASPACE_V0_BT601_525 = HAL_DATASPACE_STANDARD_BT601_525 |
-            HAL_DATASPACE_TRANSFER_SMPTE_170M | HAL_DATASPACE_RANGE_LIMITED,
-
-    /*
-     * ITU-R Recommendation 709 (BT.709)
-     *
-     * High-definition television
-     *
-     * Use limited range, BT.709 transfer and BT.709 standard.
-     */
-    HAL_DATASPACE_BT709 = 0x104, // deprecated, use HAL_DATASPACE_V0_BT709
-
-    HAL_DATASPACE_V0_BT709 = HAL_DATASPACE_STANDARD_BT709 |
-            HAL_DATASPACE_TRANSFER_SMPTE_170M | HAL_DATASPACE_RANGE_LIMITED,
-
-    /*
-     * Data spaces for non-color formats
-     */
-
-    /*
-     * The buffer contains depth ranging measurements from a depth camera.
-     * This value is valid with formats:
-     *    HAL_PIXEL_FORMAT_Y16: 16-bit samples, consisting of a depth measurement
-     *       and an associated confidence value. The 3 MSBs of the sample make
-     *       up the confidence value, and the low 13 LSBs of the sample make up
-     *       the depth measurement.
-     *       For the confidence section, 0 means 100% confidence, 1 means 0%
-     *       confidence. The mapping to a linear float confidence value between
-     *       0.f and 1.f can be obtained with
-     *         float confidence = (((depthSample >> 13) - 1) & 0x7) / 7.0f;
-     *       The depth measurement can be extracted simply with
-     *         uint16_t range = (depthSample & 0x1FFF);
-     *    HAL_PIXEL_FORMAT_BLOB: A depth point cloud, as
-     *       a variable-length float (x,y,z, confidence) coordinate point list.
-     *       The point cloud will be represented with the android_depth_points
-     *       structure.
-     */
-    HAL_DATASPACE_DEPTH = 0x1000
-
-} android_dataspace_t;
-
-/*
- * Color modes that may be supported by a display.
- *
- * Definitions:
- * Rendering intent generally defines the goal in mapping a source (input)
- * color to a destination device color for a given color mode.
- *
- *  It is important to keep in mind three cases where mapping may be applied:
- *  1. The source gamut is much smaller than the destination (display) gamut
- *  2. The source gamut is much larger than the destination gamut (this will
- *  ordinarily be handled using colorimetric rendering, below)
- *  3. The source and destination gamuts are roughly equal, although not
- *  completely overlapping
- *  Also, a common requirement for mappings is that skin tones should be
- *  preserved, or at least remain natural in appearance.
- *
- *  Colorimetric Rendering Intent (All cases):
- *  Colorimetric indicates that colors should be preserved. In the case
- *  that the source gamut lies wholly within the destination gamut or is
- *  about the same (#1, #3), this will simply mean that no manipulations
- *  (no saturation boost, for example) are applied. In the case where some
- *  source colors lie outside the destination gamut (#2, #3), those will
- *  need to be mapped to colors that are within the destination gamut,
- *  while the already in-gamut colors remain unchanged.
- *
- *  Non-colorimetric transforms can take many forms. There are no hard
- *  rules and it's left to the implementation to define.
- *  Two common intents are described below.
- *
- *  Stretched-Gamut Enhancement Intent (Source < Destination):
- *  When the destination gamut is much larger than the source gamut (#1), the
- *  source primaries may be redefined to reflect the full extent of the
- *  destination space, or to reflect an intermediate gamut.
- *  Skin-tone preservation would likely be applied. An example might be sRGB
- *  input displayed on a DCI-P3 capable device, with skin-tone preservation.
- *
- *  Within-Gamut Enhancement Intent (Source >= Destination):
- *  When the device (destination) gamut is not larger than the source gamut
- *  (#2 or #3), but the appearance of a larger gamut is desired, techniques
- *  such as saturation boost may be applied to the source colors. Skin-tone
- *  preservation may be applied. There is no unique method for within-gamut
- *  enhancement; it would be defined within a flexible color mode.
- *
- */
-typedef enum android_color_mode {
-
-  /*
-   * HAL_COLOR_MODE_DEFAULT is the "native" gamut of the display.
-   * White Point: Vendor/OEM defined
-   * Panel Gamma: Vendor/OEM defined (typically 2.2)
-   * Rendering Intent: Vendor/OEM defined (typically 'enhanced')
-   */
-  HAL_COLOR_MODE_NATIVE = 0,
-
-  /*
-   * HAL_COLOR_MODE_STANDARD_BT601_625 corresponds with display
-   * settings that implement the ITU-R Recommendation BT.601
-   * or Rec 601. Using 625 line version
-   * Rendering Intent: Colorimetric
-   * Primaries:
-   *                  x       y
-   *  green           0.290   0.600
-   *  blue            0.150   0.060
-   *  red             0.640   0.330
-   *  white (D65)     0.3127  0.3290
-   *
-   *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
-   *  for RGB conversion from the one purely determined by the primaries
-   *  to minimize the color shift into RGB space that uses BT.709
-   *  primaries.
-   *
-   * Gamma Correction (GC):
-   *
-   *  if Vlinear < 0.018
-   *    Vnonlinear = 4.500 * Vlinear
-   *  else
-   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
-   */
-  HAL_COLOR_MODE_STANDARD_BT601_625 = 1,
-
-  /*
-   * Primaries:
-   *                  x       y
-   *  green           0.290   0.600
-   *  blue            0.150   0.060
-   *  red             0.640   0.330
-   *  white (D65)     0.3127  0.3290
-   *
-   *  Use the unadjusted KR = 0.222, KB = 0.071 luminance interpretation
-   *  for RGB conversion.
-   *
-   * Gamma Correction (GC):
-   *
-   *  if Vlinear < 0.018
-   *    Vnonlinear = 4.500 * Vlinear
-   *  else
-   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
-   */
-  HAL_COLOR_MODE_STANDARD_BT601_625_UNADJUSTED = 2,
-
-  /*
-   * Primaries:
-   *                  x       y
-   *  green           0.310   0.595
-   *  blue            0.155   0.070
-   *  red             0.630   0.340
-   *  white (D65)     0.3127  0.3290
-   *
-   *  KR = 0.299, KB = 0.114. This adjusts the luminance interpretation
-   *  for RGB conversion from the one purely determined by the primaries
-   *  to minimize the color shift into RGB space that uses BT.709
-   *  primaries.
-   *
-   * Gamma Correction (GC):
-   *
-   *  if Vlinear < 0.018
-   *    Vnonlinear = 4.500 * Vlinear
-   *  else
-   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
-   */
-  HAL_COLOR_MODE_STANDARD_BT601_525 = 3,
-
-  /*
-   * Primaries:
-   *                  x       y
-   *  green           0.310   0.595
-   *  blue            0.155   0.070
-   *  red             0.630   0.340
-   *  white (D65)     0.3127  0.3290
-   *
-   *  Use the unadjusted KR = 0.212, KB = 0.087 luminance interpretation
-   *  for RGB conversion (as in SMPTE 240M).
-   *
-   * Gamma Correction (GC):
-   *
-   *  if Vlinear < 0.018
-   *    Vnonlinear = 4.500 * Vlinear
-   *  else
-   *    Vnonlinear = 1.099 * (Vlinear)^(0.45) – 0.099
-   */
-  HAL_COLOR_MODE_STANDARD_BT601_525_UNADJUSTED = 4,
-
-  /*
-   * HAL_COLOR_MODE_REC709 corresponds with display settings that implement
-   * the ITU-R Recommendation BT.709 / Rec. 709 for high-definition television.
-   * Rendering Intent: Colorimetric
-   * Primaries:
-   *                  x       y
-   *  green           0.300   0.600
-   *  blue            0.150   0.060
-   *  red             0.640   0.330
-   *  white (D65)     0.3127  0.3290
-   *
-   * HDTV REC709 Inverse Gamma Correction (IGC): V represents normalized
-   * (with [0 to 1] range) value of R, G, or B.
-   *
-   *  if Vnonlinear < 0.081
-   *    Vlinear = Vnonlinear / 4.5
-   *  else
-   *    Vlinear = ((Vnonlinear + 0.099) / 1.099) ^ (1/0.45)
-   *
-   * HDTV REC709 Gamma Correction (GC):
-   *
-   *  if Vlinear < 0.018
-   *    Vnonlinear = 4.5 * Vlinear
-   *  else
-   *    Vnonlinear = 1.099 * (Vlinear) ^ 0.45 – 0.099
-   */
-  HAL_COLOR_MODE_STANDARD_BT709 = 5,
-
-  /*
-   * HAL_COLOR_MODE_DCI_P3 corresponds with display settings that implement
-   * SMPTE EG 432-1 and SMPTE RP 431-2
-   * Rendering Intent: Colorimetric
-   * Primaries:
-   *                  x       y
-   *  green           0.265   0.690
-   *  blue            0.150   0.060
-   *  red             0.680   0.320
-   *  white (D65)     0.3127  0.3290
-   *
-   * Gamma: 2.2
-   */
-  HAL_COLOR_MODE_DCI_P3 = 6,
-
-  /*
-   * HAL_COLOR_MODE_SRGB corresponds with display settings that implement
-   * the sRGB color space. Uses the same primaries as ITU-R Recommendation
-   * BT.709
-   * Rendering Intent: Colorimetric
-   * Primaries:
-   *                  x       y
-   *  green           0.300   0.600
-   *  blue            0.150   0.060
-   *  red             0.640   0.330
-   *  white (D65)     0.3127  0.3290
-   *
-   * PC/Internet (sRGB) Inverse Gamma Correction (IGC):
-   *
-   *  if Vnonlinear ≤ 0.03928
-   *    Vlinear = Vnonlinear / 12.92
-   *  else
-   *    Vlinear = ((Vnonlinear + 0.055)/1.055) ^ 2.4
-   *
-   * PC/Internet (sRGB) Gamma Correction (GC):
-   *
-   *  if Vlinear ≤ 0.0031308
-   *    Vnonlinear = 12.92 * Vlinear
-   *  else
-   *    Vnonlinear = 1.055 * (Vlinear)^(1/2.4) – 0.055
-   */
-  HAL_COLOR_MODE_SRGB = 7,
-
-  /*
-   * HAL_COLOR_MODE_ADOBE_RGB corresponds with the RGB color space developed
-   * by Adobe Systems, Inc. in 1998.
-   * Rendering Intent: Colorimetric
-   * Primaries:
-   *                  x       y
-   *  green           0.210   0.710
-   *  blue            0.150   0.060
-   *  red             0.640   0.330
-   *  white (D65)     0.3127  0.3290
-   *
-   * Gamma: 2.2
-   */
-  HAL_COLOR_MODE_ADOBE_RGB = 8
-
-} android_color_mode_t;
-
-/*
- * Color transforms that may be applied by hardware composer to the whole
- * display.
- */
-typedef enum android_color_transform {
-    /* Applies no transform to the output color */
-    HAL_COLOR_TRANSFORM_IDENTITY = 0,
-
-    /* Applies an arbitrary transform defined by a 4x4 affine matrix */
-    HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX = 1,
-
-    /* Applies a transform that inverts the value or luminance of the color, but
-     * does not modify hue or saturation */
-    HAL_COLOR_TRANSFORM_VALUE_INVERSE = 2,
-
-    /* Applies a transform that maps all colors to shades of gray */
-    HAL_COLOR_TRANSFORM_GRAYSCALE = 3,
-
-    /* Applies a transform which corrects for protanopic color blindness */
-    HAL_COLOR_TRANSFORM_CORRECT_PROTANOPIA = 4,
-
-    /* Applies a transform which corrects for deuteranopic color blindness */
-    HAL_COLOR_TRANSFORM_CORRECT_DEUTERANOPIA = 5,
-
-    /* Applies a transform which corrects for tritanopic color blindness */
-    HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA = 6
-} android_color_transform_t;
-
-/*
- * Supported HDR formats. Must be kept in sync with equivalents in Display.java.
- */
-typedef enum android_hdr {
-    /* Device supports Dolby Vision HDR */
-    HAL_HDR_DOLBY_VISION = 1,
-
-    /* Device supports HDR10 */
-    HAL_HDR_HDR10 = 2,
-
-    /* Device supports hybrid log-gamma HDR */
-    HAL_HDR_HLG = 3
-} android_hdr_t;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H */
diff --git a/include/system/radio.h b/include/system/radio.h
deleted file mode 100644
index 9e291c8..0000000
--- a/include/system/radio.h
+++ /dev/null
@@ -1,250 +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.
- */
-
-#ifndef ANDROID_RADIO_H
-#define ANDROID_RADIO_H
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-
-#define RADIO_NUM_BANDS_MAX     16
-#define RADIO_NUM_SPACINGS_MAX  16
-#define RADIO_STRING_LEN_MAX    128
-
-/*
- * Radio hardware module class. A given radio hardware module HAL is of one class
- * only. The platform can not have more than one hardware module of each class.
- * Current version of the framework only supports RADIO_CLASS_AM_FM.
- */
-typedef enum {
-    RADIO_CLASS_AM_FM = 0,  /* FM (including HD radio) and AM */
-    RADIO_CLASS_SAT   = 1,  /* Satellite Radio */
-    RADIO_CLASS_DT    = 2,  /* Digital Radio (DAB) */
-} radio_class_t;
-
-/* value for field "type" of radio band described in struct radio_hal_band_config */
-typedef enum {
-    RADIO_BAND_AM     = 0,  /* Amplitude Modulation band: LW, MW, SW */
-    RADIO_BAND_FM     = 1,  /* Frequency Modulation band: FM */
-    RADIO_BAND_FM_HD  = 2,  /* FM HD Radio / DRM (IBOC) */
-    RADIO_BAND_AM_HD  = 3,  /* AM HD Radio / DRM (IBOC) */
-} radio_band_t;
-
-/* RDS variant implemented. A struct radio_hal_fm_band_config can list none or several. */
-enum {
-    RADIO_RDS_NONE   = 0x0,
-    RADIO_RDS_WORLD  = 0x01,
-    RADIO_RDS_US     = 0x02,
-};
-typedef unsigned int radio_rds_t;
-
-/* FM deemphasis variant implemented. A struct radio_hal_fm_band_config can list one or more. */
-enum {
-    RADIO_DEEMPHASIS_50   = 0x1,
-    RADIO_DEEMPHASIS_75   = 0x2,
-};
-typedef unsigned int radio_deemphasis_t;
-
-/* Region a particular radio band configuration corresponds to. Not used at the HAL.
- * Derived by the framework when converting the band descriptors retrieved from the HAL to
- * individual band descriptors for each supported region. */
-typedef enum {
-    RADIO_REGION_NONE  = -1,
-    RADIO_REGION_ITU_1 = 0,
-    RADIO_REGION_ITU_2 = 1,
-    RADIO_REGION_OIRT  = 2,
-    RADIO_REGION_JAPAN = 3,
-    RADIO_REGION_KOREA = 4,
-} radio_region_t;
-
-/* scanning direction for scan() and step() tuner APIs */
-typedef enum {
-    RADIO_DIRECTION_UP,
-    RADIO_DIRECTION_DOWN
-} radio_direction_t;
-
-/* unique handle allocated to a radio module */
-typedef unsigned int radio_handle_t;
-
-/* Opaque meta data structure used by radio meta data API (see system/radio_metadata.h) */
-typedef struct radio_medtadata radio_metadata_t;
-
-
-/* Additional attributes for an FM band configuration */
-typedef struct radio_hal_fm_band_config {
-    radio_deemphasis_t  deemphasis; /* deemphasis variant */
-    bool                stereo;     /* stereo supported */
-    radio_rds_t         rds;        /* RDS variants supported */
-    bool                ta;         /* Traffic Announcement supported */
-    bool                af;         /* Alternate Frequency supported */
-    bool                ea;         /* Emergency announcements supported */
-} radio_hal_fm_band_config_t;
-
-/* Additional attributes for an AM band configuration */
-typedef struct radio_hal_am_band_config {
-    bool                stereo;     /* stereo supported */
-} radio_hal_am_band_config_t;
-
-/* Radio band configuration. Describes a given band supported by the radio module.
- * The HAL can expose only one band per type with the the maximum range supported and all options.
- * THe framework will derive the actual regions were this module can operate and expose separate
- * band configurations for applications to chose from. */
-typedef struct radio_hal_band_config {
-    radio_band_t type;
-    bool         antenna_connected;
-    unsigned int lower_limit;
-    unsigned int upper_limit;
-    unsigned int num_spacings;
-    unsigned int spacings[RADIO_NUM_SPACINGS_MAX];
-    union {
-        radio_hal_fm_band_config_t fm;
-        radio_hal_am_band_config_t am;
-    };
-} radio_hal_band_config_t;
-
-/* Used internally by the framework to represent a band for s specific region */
-typedef struct radio_band_config {
-    radio_region_t  region;
-    radio_hal_band_config_t band;
-} radio_band_config_t;
-
-
-/* Exposes properties of a given hardware radio module.
- * NOTE: current framework implementation supports only one audio source (num_audio_sources = 1).
- * The source corresponds to AUDIO_DEVICE_IN_FM_TUNER.
- * If more than one tuner is supported (num_tuners > 1), only one can be connected to the audio
- * source. */
-typedef struct radio_hal_properties {
-    radio_class_t   class_id;   /* Class of this module. E.g RADIO_CLASS_AM_FM */
-    char            implementor[RADIO_STRING_LEN_MAX];  /* implementor name */
-    char            product[RADIO_STRING_LEN_MAX];  /* product name */
-    char            version[RADIO_STRING_LEN_MAX];  /* product version */
-    char            serial[RADIO_STRING_LEN_MAX];  /* serial number (for subscription services) */
-    unsigned int    num_tuners;     /* number of tuners controllable independently */
-    unsigned int    num_audio_sources; /* number of audio sources driven simultaneously */
-    bool            supports_capture; /* the hardware supports capture of audio source audio HAL */
-    unsigned int    num_bands;      /* number of band descriptors */
-    radio_hal_band_config_t bands[RADIO_NUM_BANDS_MAX]; /* band descriptors */
-} radio_hal_properties_t;
-
-/* Used internally by the framework. Same information as in struct radio_hal_properties plus a
- * unique handle and one band configuration per region. */
-typedef struct radio_properties {
-    radio_handle_t      handle;
-    radio_class_t       class_id;
-    char                implementor[RADIO_STRING_LEN_MAX];
-    char                product[RADIO_STRING_LEN_MAX];
-    char                version[RADIO_STRING_LEN_MAX];
-    char                serial[RADIO_STRING_LEN_MAX];
-    unsigned int        num_tuners;
-    unsigned int        num_audio_sources;
-    bool                supports_capture;
-    unsigned int        num_bands;
-    radio_band_config_t bands[RADIO_NUM_BANDS_MAX];
-} radio_properties_t;
-
-/* Radio program information. Returned by the HAL with event RADIO_EVENT_TUNED.
- * Contains information on currently tuned channel.
- */
-typedef struct radio_program_info {
-    unsigned int     channel;   /* current channel. (e.g kHz for band type RADIO_BAND_FM) */
-    unsigned int     sub_channel; /* current sub channel. (used for RADIO_BAND_FM_HD) */
-    bool             tuned;     /* tuned to a program or not */
-    bool             stereo;    /* program is stereo or not */
-    bool             digital;   /* digital program or not (e.g HD Radio program) */
-    unsigned int     signal_strength; /* signal strength from 0 to 100 */
-    radio_metadata_t *metadata; /* non null if meta data are present (e.g PTY, song title ...) */
-} radio_program_info_t;
-
-
-/* Events sent to the framework via the HAL callback. An event can notify the completion of an
- * asynchronous command (configuration, tune, scan ...) or a spontaneous change (antenna connection,
- * failure, AF switching, meta data reception... */
-enum {
-    RADIO_EVENT_HW_FAILURE  = 0,  /* hardware module failure. Requires reopening the tuner */
-    RADIO_EVENT_CONFIG      = 1,  /* configuration change completed */
-    RADIO_EVENT_ANTENNA     = 2,  /* Antenna connected, disconnected */
-    RADIO_EVENT_TUNED       = 3,  /* tune, step, scan completed */
-    RADIO_EVENT_METADATA    = 4,  /* New meta data received */
-    RADIO_EVENT_TA          = 5,  /* Traffic announcement start or stop */
-    RADIO_EVENT_AF_SWITCH   = 6,  /* Switch to Alternate Frequency */
-    RADIO_EVENT_EA          = 7,  /* Emergency announcement start or stop */
-    // begin framework only events
-    RADIO_EVENT_CONTROL     = 100, /* loss/gain of tuner control */
-    RADIO_EVENT_SERVER_DIED = 101, /* radio service died */
-};
-typedef unsigned int radio_event_type_t;
-
-/* Event passed to the framework by the HAL callback */
-typedef struct radio_hal_event {
-    radio_event_type_t  type;       /* event type */
-    int                 status;     /* used by RADIO_EVENT_CONFIG, RADIO_EVENT_TUNED */
-    union {
-        /* RADIO_EVENT_ANTENNA, RADIO_EVENT_TA, RADIO_EVENT_EA */
-        bool                    on;
-        radio_hal_band_config_t config; /* RADIO_EVENT_CONFIG */
-        radio_program_info_t    info;   /* RADIO_EVENT_TUNED, RADIO_EVENT_AF_SWITCH */
-        radio_metadata_t        *metadata; /* RADIO_EVENT_METADATA */
-    };
-} radio_hal_event_t;
-
-/* Used internally by the framework. Same information as in struct radio_hal_event */
-typedef struct radio_event {
-    radio_event_type_t  type;
-    int                 status;
-    union {
-        bool                    on;
-        radio_band_config_t     config;
-        radio_program_info_t    info;
-        radio_metadata_t        *metadata; /* offset from start of struct when in shared memory */
-    };
-} radio_event_t;
-
-
-static radio_rds_t radio_rds_for_region(bool rds, radio_region_t region) {
-    if (!rds)
-        return RADIO_RDS_NONE;
-    switch(region) {
-        case RADIO_REGION_ITU_1:
-        case RADIO_REGION_OIRT:
-        case RADIO_REGION_JAPAN:
-        case RADIO_REGION_KOREA:
-            return RADIO_RDS_WORLD;
-        case RADIO_REGION_ITU_2:
-            return RADIO_RDS_US;
-        default:
-            return RADIO_REGION_NONE;
-    }
-}
-
-static radio_deemphasis_t radio_demephasis_for_region(radio_region_t region) {
-    switch(region) {
-        case RADIO_REGION_KOREA:
-        case RADIO_REGION_ITU_2:
-            return RADIO_DEEMPHASIS_75;
-        case RADIO_REGION_ITU_1:
-        case RADIO_REGION_OIRT:
-        case RADIO_REGION_JAPAN:
-        default:
-            return RADIO_DEEMPHASIS_50;
-    }
-}
-
-#endif  // ANDROID_RADIO_H
diff --git a/include/system/window.h b/include/system/window.h
deleted file mode 100644
index 33b7c3d..0000000
--- a/include/system/window.h
+++ /dev/null
@@ -1,1004 +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 SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
-#define SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
-
-#include <cutils/native_handle.h>
-#include <errno.h>
-#include <limits.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/cdefs.h>
-#include <system/graphics.h>
-#include <unistd.h>
-#include <stdbool.h>
-
-#ifndef __UNUSED
-#define __UNUSED __attribute__((__unused__))
-#endif
-#ifndef __deprecated
-#define __deprecated __attribute__((__deprecated__))
-#endif
-
-__BEGIN_DECLS
-
-/*****************************************************************************/
-
-#define ANDROID_NATIVE_MAKE_CONSTANT(a,b,c,d) \
-    (((unsigned)(a)<<24)|((unsigned)(b)<<16)|((unsigned)(c)<<8)|(unsigned)(d))
-
-#define ANDROID_NATIVE_WINDOW_MAGIC \
-    ANDROID_NATIVE_MAKE_CONSTANT('_','w','n','d')
-
-#define ANDROID_NATIVE_BUFFER_MAGIC \
-    ANDROID_NATIVE_MAKE_CONSTANT('_','b','f','r')
-
-// ---------------------------------------------------------------------------
-
-// This #define may be used to conditionally compile device-specific code to
-// support either the prior ANativeWindow interface, which did not pass libsync
-// fences around, or the new interface that does.  This #define is only present
-// when the ANativeWindow interface does include libsync support.
-#define ANDROID_NATIVE_WINDOW_HAS_SYNC 1
-
-// ---------------------------------------------------------------------------
-
-typedef const native_handle_t* buffer_handle_t;
-
-// ---------------------------------------------------------------------------
-
-typedef struct android_native_rect_t
-{
-    int32_t left;
-    int32_t top;
-    int32_t right;
-    int32_t bottom;
-} android_native_rect_t;
-
-// ---------------------------------------------------------------------------
-
-typedef struct android_native_base_t
-{
-    /* a magic value defined by the actual EGL native type */
-    int magic;
-
-    /* the sizeof() of the actual EGL native type */
-    int version;
-
-    void* reserved[4];
-
-    /* reference-counting interface */
-    void (*incRef)(struct android_native_base_t* base);
-    void (*decRef)(struct android_native_base_t* base);
-} android_native_base_t;
-
-typedef struct ANativeWindowBuffer
-{
-#ifdef __cplusplus
-    ANativeWindowBuffer() {
-        common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
-        common.version = sizeof(ANativeWindowBuffer);
-        memset(common.reserved, 0, sizeof(common.reserved));
-    }
-
-    // Implement the methods that sp<ANativeWindowBuffer> expects so that it
-    // can be used to automatically refcount ANativeWindowBuffer's.
-    void incStrong(const void* /*id*/) const {
-        common.incRef(const_cast<android_native_base_t*>(&common));
-    }
-    void decStrong(const void* /*id*/) const {
-        common.decRef(const_cast<android_native_base_t*>(&common));
-    }
-#endif
-
-    struct android_native_base_t common;
-
-    int width;
-    int height;
-    int stride;
-    int format;
-    int usage;
-
-    void* reserved[2];
-
-    buffer_handle_t handle;
-
-    void* reserved_proc[8];
-} ANativeWindowBuffer_t;
-
-// Old typedef for backwards compatibility.
-typedef ANativeWindowBuffer_t android_native_buffer_t;
-
-// ---------------------------------------------------------------------------
-
-/* attributes queriable with query() */
-enum {
-    NATIVE_WINDOW_WIDTH     = 0,
-    NATIVE_WINDOW_HEIGHT    = 1,
-    NATIVE_WINDOW_FORMAT    = 2,
-
-    /* The minimum number of buffers that must remain un-dequeued after a buffer
-     * has been queued.  This value applies only if set_buffer_count was used to
-     * override the number of buffers and if a buffer has since been queued.
-     * Users of the set_buffer_count ANativeWindow method should query this
-     * value before calling set_buffer_count.  If it is necessary to have N
-     * buffers simultaneously dequeued as part of the steady-state operation,
-     * and this query returns M then N+M buffers should be requested via
-     * native_window_set_buffer_count.
-     *
-     * Note that this value does NOT apply until a single buffer has been
-     * queued.  In particular this means that it is possible to:
-     *
-     * 1. Query M = min undequeued buffers
-     * 2. Set the buffer count to N + M
-     * 3. Dequeue all N + M buffers
-     * 4. Cancel M buffers
-     * 5. Queue, dequeue, queue, dequeue, ad infinitum
-     */
-    NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS = 3,
-
-    /* Check whether queueBuffer operations on the ANativeWindow send the buffer
-     * to the window compositor.  The query sets the returned 'value' argument
-     * to 1 if the ANativeWindow DOES send queued buffers directly to the window
-     * compositor and 0 if the buffers do not go directly to the window
-     * compositor.
-     *
-     * This can be used to determine whether protected buffer content should be
-     * sent to the ANativeWindow.  Note, however, that a result of 1 does NOT
-     * indicate that queued buffers will be protected from applications or users
-     * capturing their contents.  If that behavior is desired then some other
-     * mechanism (e.g. the GRALLOC_USAGE_PROTECTED flag) should be used in
-     * conjunction with this query.
-     */
-    NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER = 4,
-
-    /* Get the concrete type of a ANativeWindow.  See below for the list of
-     * possible return values.
-     *
-     * This query should not be used outside the Android framework and will
-     * likely be removed in the near future.
-     */
-    NATIVE_WINDOW_CONCRETE_TYPE = 5,
-
-
-    /*
-     * Default width and height of ANativeWindow buffers, these are the
-     * dimensions of the window buffers irrespective of the
-     * NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS call and match the native window
-     * size unless overridden by NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS.
-     */
-    NATIVE_WINDOW_DEFAULT_WIDTH = 6,
-    NATIVE_WINDOW_DEFAULT_HEIGHT = 7,
-
-    /*
-     * transformation that will most-likely be applied to buffers. This is only
-     * a hint, the actual transformation applied might be different.
-     *
-     * INTENDED USE:
-     *
-     * The transform hint can be used by a producer, for instance the GLES
-     * driver, to pre-rotate the rendering such that the final transformation
-     * in the composer is identity. This can be very useful when used in
-     * conjunction with the h/w composer HAL, in situations where it
-     * cannot handle arbitrary rotations.
-     *
-     * 1. Before dequeuing a buffer, the GL driver (or any other ANW client)
-     *    queries the ANW for NATIVE_WINDOW_TRANSFORM_HINT.
-     *
-     * 2. The GL driver overrides the width and height of the ANW to
-     *    account for NATIVE_WINDOW_TRANSFORM_HINT. This is done by querying
-     *    NATIVE_WINDOW_DEFAULT_{WIDTH | HEIGHT}, swapping the dimensions
-     *    according to NATIVE_WINDOW_TRANSFORM_HINT and calling
-     *    native_window_set_buffers_dimensions().
-     *
-     * 3. The GL driver dequeues a buffer of the new pre-rotated size.
-     *
-     * 4. The GL driver renders to the buffer such that the image is
-     *    already transformed, that is applying NATIVE_WINDOW_TRANSFORM_HINT
-     *    to the rendering.
-     *
-     * 5. The GL driver calls native_window_set_transform to apply
-     *    inverse transformation to the buffer it just rendered.
-     *    In order to do this, the GL driver needs
-     *    to calculate the inverse of NATIVE_WINDOW_TRANSFORM_HINT, this is
-     *    done easily:
-     *
-     *        int hintTransform, inverseTransform;
-     *        query(..., NATIVE_WINDOW_TRANSFORM_HINT, &hintTransform);
-     *        inverseTransform = hintTransform;
-     *        if (hintTransform & HAL_TRANSFORM_ROT_90)
-     *            inverseTransform ^= HAL_TRANSFORM_ROT_180;
-     *
-     *
-     * 6. The GL driver queues the pre-transformed buffer.
-     *
-     * 7. The composer combines the buffer transform with the display
-     *    transform.  If the buffer transform happens to cancel out the
-     *    display transform then no rotation is needed.
-     *
-     */
-    NATIVE_WINDOW_TRANSFORM_HINT = 8,
-
-    /*
-     * Boolean that indicates whether the consumer is running more than
-     * one buffer behind the producer.
-     */
-    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND = 9,
-
-    /*
-     * The consumer gralloc usage bits currently set by the consumer.
-     * The values are defined in hardware/libhardware/include/gralloc.h.
-     */
-    NATIVE_WINDOW_CONSUMER_USAGE_BITS = 10,
-
-    /**
-     * Transformation that will by applied to buffers by the hwcomposer.
-     * This must not be set or checked by producer endpoints, and will
-     * disable the transform hint set in SurfaceFlinger (see
-     * NATIVE_WINDOW_TRANSFORM_HINT).
-     *
-     * INTENDED USE:
-     * Temporary - Please do not use this.  This is intended only to be used
-     * by the camera's LEGACY mode.
-     *
-     * In situations where a SurfaceFlinger client wishes to set a transform
-     * that is not visible to the producer, and will always be applied in the
-     * hardware composer, the client can set this flag with
-     * native_window_set_buffers_sticky_transform.  This can be used to rotate
-     * and flip buffers consumed by hardware composer without actually changing
-     * the aspect ratio of the buffers produced.
-     */
-    NATIVE_WINDOW_STICKY_TRANSFORM = 11,
-
-    /**
-     * The default data space for the buffers as set by the consumer.
-     * The values are defined in graphics.h.
-     */
-    NATIVE_WINDOW_DEFAULT_DATASPACE = 12,
-
-    /*
-     * Returns the age of the contents of the most recently dequeued buffer as
-     * the number of frames that have elapsed since it was last queued. For
-     * example, if the window is double-buffered, the age of any given buffer in
-     * steady state will be 2. If the dequeued buffer has never been queued, its
-     * age will be 0.
-     */
-    NATIVE_WINDOW_BUFFER_AGE = 13,
-
-    /*
-     * Returns the duration of the last dequeueBuffer call in microseconds
-     */
-    NATIVE_WINDOW_LAST_DEQUEUE_DURATION = 14,
-
-    /*
-     * Returns the duration of the last queueBuffer call in microseconds
-     */
-    NATIVE_WINDOW_LAST_QUEUE_DURATION = 15,
-};
-
-/* Valid operations for the (*perform)() hook.
- *
- * Values marked as 'deprecated' are supported, but have been superceded by
- * other functionality.
- *
- * Values marked as 'private' should be considered private to the framework.
- * HAL implementation code with access to an ANativeWindow should not use these,
- * as it may not interact properly with the framework's use of the
- * ANativeWindow.
- */
-enum {
-    NATIVE_WINDOW_SET_USAGE                 =  0,
-    NATIVE_WINDOW_CONNECT                   =  1,   /* deprecated */
-    NATIVE_WINDOW_DISCONNECT                =  2,   /* deprecated */
-    NATIVE_WINDOW_SET_CROP                  =  3,   /* private */
-    NATIVE_WINDOW_SET_BUFFER_COUNT          =  4,
-    NATIVE_WINDOW_SET_BUFFERS_GEOMETRY      =  5,   /* deprecated */
-    NATIVE_WINDOW_SET_BUFFERS_TRANSFORM     =  6,
-    NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP     =  7,
-    NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS    =  8,
-    NATIVE_WINDOW_SET_BUFFERS_FORMAT        =  9,
-    NATIVE_WINDOW_SET_SCALING_MODE          = 10,   /* private */
-    NATIVE_WINDOW_LOCK                      = 11,   /* private */
-    NATIVE_WINDOW_UNLOCK_AND_POST           = 12,   /* private */
-    NATIVE_WINDOW_API_CONNECT               = 13,   /* private */
-    NATIVE_WINDOW_API_DISCONNECT            = 14,   /* private */
-    NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS = 15, /* private */
-    NATIVE_WINDOW_SET_POST_TRANSFORM_CROP   = 16,   /* private */
-    NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM = 17,/* private */
-    NATIVE_WINDOW_SET_SIDEBAND_STREAM       = 18,
-    NATIVE_WINDOW_SET_BUFFERS_DATASPACE     = 19,
-    NATIVE_WINDOW_SET_SURFACE_DAMAGE        = 20,   /* private */
-    NATIVE_WINDOW_SET_SHARED_BUFFER_MODE    = 21,
-    NATIVE_WINDOW_SET_AUTO_REFRESH          = 22,
-    NATIVE_WINDOW_GET_FRAME_TIMESTAMPS      = 23,
-};
-
-/* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
-enum {
-    /* Buffers will be queued by EGL via eglSwapBuffers after being filled using
-     * OpenGL ES.
-     */
-    NATIVE_WINDOW_API_EGL = 1,
-
-    /* Buffers will be queued after being filled using the CPU
-     */
-    NATIVE_WINDOW_API_CPU = 2,
-
-    /* Buffers will be queued by Stagefright after being filled by a video
-     * decoder.  The video decoder can either be a software or hardware decoder.
-     */
-    NATIVE_WINDOW_API_MEDIA = 3,
-
-    /* Buffers will be queued by the the camera HAL.
-     */
-    NATIVE_WINDOW_API_CAMERA = 4,
-};
-
-/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */
-enum {
-    /* flip source image horizontally */
-    NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H ,
-    /* flip source image vertically */
-    NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
-    /* rotate source image 90 degrees clock-wise, and is applied after TRANSFORM_FLIP_{H|V} */
-    NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
-    /* rotate source image 180 degrees */
-    NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
-    /* rotate source image 270 degrees clock-wise */
-    NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
-    /* transforms source by the inverse transform of the screen it is displayed onto. This
-     * transform is applied last */
-    NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY = 0x08
-};
-
-/* parameter for NATIVE_WINDOW_SET_SCALING_MODE
- * keep in sync with Surface.java in frameworks/base */
-enum {
-    /* the window content is not updated (frozen) until a buffer of
-     * the window size is received (enqueued)
-     */
-    NATIVE_WINDOW_SCALING_MODE_FREEZE           = 0,
-    /* the buffer is scaled in both dimensions to match the window size */
-    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW  = 1,
-    /* the buffer is scaled uniformly such that the smaller dimension
-     * of the buffer matches the window size (cropping in the process)
-     */
-    NATIVE_WINDOW_SCALING_MODE_SCALE_CROP       = 2,
-    /* the window is clipped to the size of the buffer's crop rectangle; pixels
-     * outside the crop rectangle are treated as if they are completely
-     * transparent.
-     */
-    NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP    = 3,
-};
-
-/* values returned by the NATIVE_WINDOW_CONCRETE_TYPE query */
-enum {
-    NATIVE_WINDOW_FRAMEBUFFER               = 0, /* FramebufferNativeWindow */
-    NATIVE_WINDOW_SURFACE                   = 1, /* Surface */
-};
-
-/* parameter for NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP
- *
- * Special timestamp value to indicate that timestamps should be auto-generated
- * by the native window when queueBuffer is called.  This is equal to INT64_MIN,
- * defined directly to avoid problems with C99/C++ inclusion of stdint.h.
- */
-static const int64_t NATIVE_WINDOW_TIMESTAMP_AUTO = (-9223372036854775807LL-1);
-
-struct ANativeWindow
-{
-#ifdef __cplusplus
-    ANativeWindow()
-        : flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0)
-    {
-        common.magic = ANDROID_NATIVE_WINDOW_MAGIC;
-        common.version = sizeof(ANativeWindow);
-        memset(common.reserved, 0, sizeof(common.reserved));
-    }
-
-    /* Implement the methods that sp<ANativeWindow> expects so that it
-       can be used to automatically refcount ANativeWindow's. */
-    void incStrong(const void* /*id*/) const {
-        common.incRef(const_cast<android_native_base_t*>(&common));
-    }
-    void decStrong(const void* /*id*/) const {
-        common.decRef(const_cast<android_native_base_t*>(&common));
-    }
-#endif
-
-    struct android_native_base_t common;
-
-    /* flags describing some attributes of this surface or its updater */
-    const uint32_t flags;
-
-    /* min swap interval supported by this updated */
-    const int   minSwapInterval;
-
-    /* max swap interval supported by this updated */
-    const int   maxSwapInterval;
-
-    /* horizontal and vertical resolution in DPI */
-    const float xdpi;
-    const float ydpi;
-
-    /* Some storage reserved for the OEM's driver. */
-    intptr_t    oem[4];
-
-    /*
-     * Set the swap interval for this surface.
-     *
-     * Returns 0 on success or -errno on error.
-     */
-    int     (*setSwapInterval)(struct ANativeWindow* window,
-                int interval);
-
-    /*
-     * Hook called by EGL to acquire a buffer. After this call, the buffer
-     * is not locked, so its content cannot be modified. This call may block if
-     * no buffers are available.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * Returns 0 on success or -errno on error.
-     *
-     * XXX: This function is deprecated.  It will continue to work for some
-     * time for binary compatibility, but the new dequeueBuffer function that
-     * outputs a fence file descriptor should be used in its place.
-     */
-    int     (*dequeueBuffer_DEPRECATED)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer** buffer);
-
-    /*
-     * hook called by EGL to lock a buffer. This MUST be called before modifying
-     * the content of a buffer. The buffer must have been acquired with
-     * dequeueBuffer first.
-     *
-     * Returns 0 on success or -errno on error.
-     *
-     * XXX: This function is deprecated.  It will continue to work for some
-     * time for binary compatibility, but it is essentially a no-op, and calls
-     * to it should be removed.
-     */
-    int     (*lockBuffer_DEPRECATED)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer* buffer);
-
-    /*
-     * Hook called by EGL when modifications to the render buffer are done.
-     * This unlocks and post the buffer.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * Buffers MUST be queued in the same order than they were dequeued.
-     *
-     * Returns 0 on success or -errno on error.
-     *
-     * XXX: This function is deprecated.  It will continue to work for some
-     * time for binary compatibility, but the new queueBuffer function that
-     * takes a fence file descriptor should be used in its place (pass a value
-     * of -1 for the fence file descriptor if there is no valid one to pass).
-     */
-    int     (*queueBuffer_DEPRECATED)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer* buffer);
-
-    /*
-     * hook used to retrieve information about the native window.
-     *
-     * Returns 0 on success or -errno on error.
-     */
-    int     (*query)(const struct ANativeWindow* window,
-                int what, int* value);
-
-    /*
-     * hook used to perform various operations on the surface.
-     * (*perform)() is a generic mechanism to add functionality to
-     * ANativeWindow while keeping backward binary compatibility.
-     *
-     * DO NOT CALL THIS HOOK DIRECTLY.  Instead, use the helper functions
-     * defined below.
-     *
-     * (*perform)() returns -ENOENT if the 'what' parameter is not supported
-     * by the surface's implementation.
-     *
-     * See above for a list of valid operations, such as
-     * NATIVE_WINDOW_SET_USAGE or NATIVE_WINDOW_CONNECT
-     */
-    int     (*perform)(struct ANativeWindow* window,
-                int operation, ... );
-
-    /*
-     * Hook used to cancel a buffer that has been dequeued.
-     * No synchronization is performed between dequeue() and cancel(), so
-     * either external synchronization is needed, or these functions must be
-     * called from the same thread.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * XXX: This function is deprecated.  It will continue to work for some
-     * time for binary compatibility, but the new cancelBuffer function that
-     * takes a fence file descriptor should be used in its place (pass a value
-     * of -1 for the fence file descriptor if there is no valid one to pass).
-     */
-    int     (*cancelBuffer_DEPRECATED)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer* buffer);
-
-    /*
-     * Hook called by EGL to acquire a buffer. This call may block if no
-     * buffers are available.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * The libsync fence file descriptor returned in the int pointed to by the
-     * fenceFd argument will refer to the fence that must signal before the
-     * dequeued buffer may be written to.  A value of -1 indicates that the
-     * caller may access the buffer immediately without waiting on a fence.  If
-     * a valid file descriptor is returned (i.e. any value except -1) then the
-     * caller is responsible for closing the file descriptor.
-     *
-     * Returns 0 on success or -errno on error.
-     */
-    int     (*dequeueBuffer)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer** buffer, int* fenceFd);
-
-    /*
-     * Hook called by EGL when modifications to the render buffer are done.
-     * This unlocks and post the buffer.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * The fenceFd argument specifies a libsync fence file descriptor for a
-     * fence that must signal before the buffer can be accessed.  If the buffer
-     * can be accessed immediately then a value of -1 should be used.  The
-     * caller must not use the file descriptor after it is passed to
-     * queueBuffer, and the ANativeWindow implementation is responsible for
-     * closing it.
-     *
-     * Returns 0 on success or -errno on error.
-     */
-    int     (*queueBuffer)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer* buffer, int fenceFd);
-
-    /*
-     * Hook used to cancel a buffer that has been dequeued.
-     * No synchronization is performed between dequeue() and cancel(), so
-     * either external synchronization is needed, or these functions must be
-     * called from the same thread.
-     *
-     * The window holds a reference to the buffer between dequeueBuffer and
-     * either queueBuffer or cancelBuffer, so clients only need their own
-     * reference if they might use the buffer after queueing or canceling it.
-     * Holding a reference to a buffer after queueing or canceling it is only
-     * allowed if a specific buffer count has been set.
-     *
-     * The fenceFd argument specifies a libsync fence file decsriptor for a
-     * fence that must signal before the buffer can be accessed.  If the buffer
-     * can be accessed immediately then a value of -1 should be used.
-     *
-     * Note that if the client has not waited on the fence that was returned
-     * from dequeueBuffer, that same fence should be passed to cancelBuffer to
-     * ensure that future uses of the buffer are preceded by a wait on that
-     * fence.  The caller must not use the file descriptor after it is passed
-     * to cancelBuffer, and the ANativeWindow implementation is responsible for
-     * closing it.
-     *
-     * Returns 0 on success or -errno on error.
-     */
-    int     (*cancelBuffer)(struct ANativeWindow* window,
-                struct ANativeWindowBuffer* buffer, int fenceFd);
-};
-
- /* Backwards compatibility: use ANativeWindow (struct ANativeWindow in C).
-  * android_native_window_t is deprecated.
-  */
-typedef struct ANativeWindow ANativeWindow;
-typedef struct ANativeWindow android_native_window_t __deprecated;
-
-/*
- *  native_window_set_usage(..., usage)
- *  Sets the intended usage flags for the next buffers
- *  acquired with (*lockBuffer)() and on.
- *  By default (if this function is never called), a usage of
- *      GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE
- *  is assumed.
- *  Calling this function will usually cause following buffers to be
- *  reallocated.
- */
-
-static inline int native_window_set_usage(
-        struct ANativeWindow* window, int usage)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_USAGE, usage);
-}
-
-/* deprecated. Always returns 0. Don't call. */
-static inline int native_window_connect(
-        struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated;
-
-static inline int native_window_connect(
-        struct ANativeWindow* window __UNUSED, int api __UNUSED) {
-    return 0;
-}
-
-/* deprecated. Always returns 0. Don't call. */
-static inline int native_window_disconnect(
-        struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated;
-
-static inline int native_window_disconnect(
-        struct ANativeWindow* window __UNUSED, int api __UNUSED) {
-    return 0;
-}
-
-/*
- * native_window_set_crop(..., crop)
- * Sets which region of the next queued buffers needs to be considered.
- * Depending on the scaling mode, a buffer's crop region is scaled and/or
- * cropped to match the surface's size.  This function sets the crop in
- * pre-transformed buffer pixel coordinates.
- *
- * The specified crop region applies to all buffers queued after it is called.
- *
- * If 'crop' is NULL, subsequently queued buffers won't be cropped.
- *
- * An error is returned if for instance the crop region is invalid, out of the
- * buffer's bound or if the window is invalid.
- */
-static inline int native_window_set_crop(
-        struct ANativeWindow* window,
-        android_native_rect_t const * crop)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_CROP, crop);
-}
-
-/*
- * native_window_set_post_transform_crop(..., crop)
- * Sets which region of the next queued buffers needs to be considered.
- * Depending on the scaling mode, a buffer's crop region is scaled and/or
- * cropped to match the surface's size.  This function sets the crop in
- * post-transformed pixel coordinates.
- *
- * The specified crop region applies to all buffers queued after it is called.
- *
- * If 'crop' is NULL, subsequently queued buffers won't be cropped.
- *
- * An error is returned if for instance the crop region is invalid, out of the
- * buffer's bound or if the window is invalid.
- */
-static inline int native_window_set_post_transform_crop(
-        struct ANativeWindow* window,
-        android_native_rect_t const * crop)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_POST_TRANSFORM_CROP, crop);
-}
-
-/*
- * native_window_set_active_rect(..., active_rect)
- *
- * This function is deprecated and will be removed soon.  For now it simply
- * sets the post-transform crop for compatibility while multi-project commits
- * get checked.
- */
-static inline int native_window_set_active_rect(
-        struct ANativeWindow* window,
-        android_native_rect_t const * active_rect) __deprecated;
-
-static inline int native_window_set_active_rect(
-        struct ANativeWindow* window,
-        android_native_rect_t const * active_rect)
-{
-    return native_window_set_post_transform_crop(window, active_rect);
-}
-
-/*
- * native_window_set_buffer_count(..., count)
- * Sets the number of buffers associated with this native window.
- */
-static inline int native_window_set_buffer_count(
-        struct ANativeWindow* window,
-        size_t bufferCount)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFER_COUNT, bufferCount);
-}
-
-/*
- * native_window_set_buffers_geometry(..., int w, int h, int format)
- * All buffers dequeued after this call will have the dimensions and format
- * specified.  A successful call to this function has the same effect as calling
- * native_window_set_buffers_size and native_window_set_buffers_format.
- *
- * XXX: This function is deprecated.  The native_window_set_buffers_dimensions
- * and native_window_set_buffers_format functions should be used instead.
- */
-static inline int native_window_set_buffers_geometry(
-        struct ANativeWindow* window,
-        int w, int h, int format) __deprecated;
-
-static inline int native_window_set_buffers_geometry(
-        struct ANativeWindow* window,
-        int w, int h, int format)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_GEOMETRY,
-            w, h, format);
-}
-
-/*
- * native_window_set_buffers_dimensions(..., int w, int h)
- * All buffers dequeued after this call will have the dimensions specified.
- * In particular, all buffers will have a fixed-size, independent from the
- * native-window size. They will be scaled according to the scaling mode
- * (see native_window_set_scaling_mode) upon window composition.
- *
- * If w and h are 0, the normal behavior is restored. That is, dequeued buffers
- * following this call will be sized to match the window's size.
- *
- * Calling this function will reset the window crop to a NULL value, which
- * disables cropping of the buffers.
- */
-static inline int native_window_set_buffers_dimensions(
-        struct ANativeWindow* window,
-        int w, int h)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS,
-            w, h);
-}
-
-/*
- * native_window_set_buffers_user_dimensions(..., int w, int h)
- *
- * Sets the user buffer size for the window, which overrides the
- * window's size.  All buffers dequeued after this call will have the
- * dimensions specified unless overridden by
- * native_window_set_buffers_dimensions.  All buffers will have a
- * fixed-size, independent from the native-window size. They will be
- * scaled according to the scaling mode (see
- * native_window_set_scaling_mode) upon window composition.
- *
- * If w and h are 0, the normal behavior is restored. That is, the
- * default buffer size will match the windows's size.
- *
- * Calling this function will reset the window crop to a NULL value, which
- * disables cropping of the buffers.
- */
-static inline int native_window_set_buffers_user_dimensions(
-        struct ANativeWindow* window,
-        int w, int h)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS,
-            w, h);
-}
-
-/*
- * native_window_set_buffers_format(..., int format)
- * All buffers dequeued after this call will have the format specified.
- *
- * If the specified format is 0, the default buffer format will be used.
- */
-static inline int native_window_set_buffers_format(
-        struct ANativeWindow* window,
-        int format)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_FORMAT, format);
-}
-
-/*
- * native_window_set_buffers_data_space(..., int dataSpace)
- * All buffers queued after this call will be associated with the dataSpace
- * parameter specified.
- *
- * dataSpace specifies additional information about the buffer that's dependent
- * on the buffer format and the endpoints. For example, it can be used to convey
- * the color space of the image data in the buffer, or it can be used to
- * indicate that the buffers contain depth measurement data instead of color
- * images.  The default dataSpace is 0, HAL_DATASPACE_UNKNOWN, unless it has been
- * overridden by the consumer.
- */
-static inline int native_window_set_buffers_data_space(
-        struct ANativeWindow* window,
-        android_dataspace_t dataSpace)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DATASPACE,
-            dataSpace);
-}
-
-/*
- * native_window_set_buffers_transform(..., int transform)
- * All buffers queued after this call will be displayed transformed according
- * to the transform parameter specified.
- */
-static inline int native_window_set_buffers_transform(
-        struct ANativeWindow* window,
-        int transform)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TRANSFORM,
-            transform);
-}
-
-/*
- * native_window_set_buffers_sticky_transform(..., int transform)
- * All buffers queued after this call will be displayed transformed according
- * to the transform parameter specified applied on top of the regular buffer
- * transform.  Setting this transform will disable the transform hint.
- *
- * Temporary - This is only intended to be used by the LEGACY camera mode, do
- *   not use this for anything else.
- */
-static inline int native_window_set_buffers_sticky_transform(
-        struct ANativeWindow* window,
-        int transform)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM,
-            transform);
-}
-
-/*
- * native_window_set_buffers_timestamp(..., int64_t timestamp)
- * All buffers queued after this call will be associated with the timestamp
- * parameter specified. If the timestamp is set to NATIVE_WINDOW_TIMESTAMP_AUTO
- * (the default), timestamps will be generated automatically when queueBuffer is
- * called. The timestamp is measured in nanoseconds, and is normally monotonically
- * increasing. The timestamp should be unaffected by time-of-day adjustments,
- * and for a camera should be strictly monotonic but for a media player may be
- * reset when the position is set.
- */
-static inline int native_window_set_buffers_timestamp(
-        struct ANativeWindow* window,
-        int64_t timestamp)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP,
-            timestamp);
-}
-
-/*
- * native_window_set_scaling_mode(..., int mode)
- * All buffers queued after this call will be associated with the scaling mode
- * specified.
- */
-static inline int native_window_set_scaling_mode(
-        struct ANativeWindow* window,
-        int mode)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_SCALING_MODE,
-            mode);
-}
-
-/*
- * native_window_api_connect(..., int api)
- * connects an API to this window. only one API can be connected at a time.
- * Returns -EINVAL if for some reason the window cannot be connected, which
- * can happen if it's connected to some other API.
- */
-static inline int native_window_api_connect(
-        struct ANativeWindow* window, int api)
-{
-    return window->perform(window, NATIVE_WINDOW_API_CONNECT, api);
-}
-
-/*
- * native_window_api_disconnect(..., int api)
- * disconnect the API from this window.
- * An error is returned if for instance the window wasn't connected in the
- * first place.
- */
-static inline int native_window_api_disconnect(
-        struct ANativeWindow* window, int api)
-{
-    return window->perform(window, NATIVE_WINDOW_API_DISCONNECT, api);
-}
-
-/*
- * native_window_dequeue_buffer_and_wait(...)
- * Dequeue a buffer and wait on the fence associated with that buffer.  The
- * buffer may safely be accessed immediately upon this function returning.  An
- * error is returned if either of the dequeue or the wait operations fail.
- */
-static inline int native_window_dequeue_buffer_and_wait(ANativeWindow *anw,
-        struct ANativeWindowBuffer** anb) {
-    return anw->dequeueBuffer_DEPRECATED(anw, anb);
-}
-
-/*
- * native_window_set_sideband_stream(..., native_handle_t*)
- * Attach a sideband buffer stream to a native window.
- */
-static inline int native_window_set_sideband_stream(
-        struct ANativeWindow* window,
-        native_handle_t* sidebandHandle)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_SIDEBAND_STREAM,
-            sidebandHandle);
-}
-
-/*
- * native_window_set_surface_damage(..., android_native_rect_t* rects, int numRects)
- * Set the surface damage (i.e., the region of the surface that has changed
- * since the previous frame). The damage set by this call will be reset (to the
- * default of full-surface damage) after calling queue, so this must be called
- * prior to every frame with damage that does not cover the whole surface if the
- * caller desires downstream consumers to use this optimization.
- *
- * The damage region is specified as an array of rectangles, with the important
- * caveat that the origin of the surface is considered to be the bottom-left
- * corner, as in OpenGL ES.
- *
- * If numRects is set to 0, rects may be NULL, and the surface damage will be
- * set to the full surface (the same as if this function had not been called for
- * this frame).
- */
-static inline int native_window_set_surface_damage(
-        struct ANativeWindow* window,
-        const android_native_rect_t* rects, size_t numRects)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_SURFACE_DAMAGE,
-            rects, numRects);
-}
-
-/*
- * native_window_set_shared_buffer_mode(..., bool sharedBufferMode)
- * Enable/disable shared buffer mode
- */
-static inline int native_window_set_shared_buffer_mode(
-        struct ANativeWindow* window,
-        bool sharedBufferMode)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_SHARED_BUFFER_MODE,
-            sharedBufferMode);
-}
-
-/*
- * native_window_set_auto_refresh(..., autoRefresh)
- * Enable/disable auto refresh when in shared buffer mode
- */
-static inline int native_window_set_auto_refresh(
-        struct ANativeWindow* window,
-        bool autoRefresh)
-{
-    return window->perform(window, NATIVE_WINDOW_SET_AUTO_REFRESH, autoRefresh);
-}
-
-static inline int native_window_get_frame_timestamps(
-        struct ANativeWindow* window, uint32_t framesAgo,
-        int64_t* outPostedTime, int64_t* outAcquireTime,
-        int64_t* outRefreshStartTime, int64_t* outGlCompositionDoneTime,
-        int64_t* outDisplayRetireTime, int64_t* outReleaseTime)
-{
-    return window->perform(window, NATIVE_WINDOW_GET_FRAME_TIMESTAMPS,
-            framesAgo, outPostedTime, outAcquireTime, outRefreshStartTime,
-            outGlCompositionDoneTime, outDisplayRetireTime, outReleaseTime);
-}
-
-
-__END_DECLS
-
-#endif /* SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H */
diff --git a/include/sysutils b/include/sysutils
new file mode 120000
index 0000000..1c8e85b
--- /dev/null
+++ b/include/sysutils
@@ -0,0 +1 @@
+../libsysutils/include/sysutils/
\ No newline at end of file
diff --git a/include/usbhost/usbhost.h b/include/usbhost/usbhost.h
deleted file mode 100644
index 88b5b44..0000000
--- a/include/usbhost/usbhost.h
+++ /dev/null
@@ -1,246 +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 __USB_HOST_H
-#define __USB_HOST_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdint.h>
-
-#include <linux/version.h>
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
-#include <linux/usb/ch9.h>
-#else
-#include <linux/usb_ch9.h>
-#endif
-
-struct usb_host_context;
-struct usb_endpoint_descriptor;
-
-struct usb_descriptor_iter {
-    unsigned char*  config;
-    unsigned char*  config_end;
-    unsigned char*  curr_desc;
-};
-
-struct usb_request
-{
-    struct usb_device *dev;
-    void* buffer;
-    int buffer_length;
-    int actual_length;
-    int max_packet_size;
-    void *private_data; /* struct usbdevfs_urb* */
-    int endpoint;
-    void *client_data;  /* free for use by client */
-};
-
-/* Callback for notification when new USB devices are attached.
- * Return true to exit from usb_host_run.
- */
-typedef int (* usb_device_added_cb)(const char *dev_name, void *client_data);
-
-/* Callback for notification when USB devices are removed.
- * Return true to exit from usb_host_run.
- */
-typedef int (* usb_device_removed_cb)(const char *dev_name, void *client_data);
-
-/* Callback indicating that initial device discovery is done.
- * Return true to exit from usb_host_run.
- */
-typedef int (* usb_discovery_done_cb)(void *client_data);
-
-/* Call this to initialize the USB host library. */
-struct usb_host_context *usb_host_init(void);
-
-/* Call this to cleanup the USB host library. */
-void usb_host_cleanup(struct usb_host_context *context);
-
-/* Call this to get the inotify file descriptor. */
-int usb_host_get_fd(struct usb_host_context *context);
-
-/* Call this to initialize the usb host context. */
-int usb_host_load(struct usb_host_context *context,
-                  usb_device_added_cb added_cb,
-                  usb_device_removed_cb removed_cb,
-                  usb_discovery_done_cb discovery_done_cb,
-                  void *client_data);
-
-/* Call this to read and handle occuring usb event. */
-int usb_host_read_event(struct usb_host_context *context);
-
-/* Call this to monitor the USB bus for new and removed devices.
- * This is intended to be called from a dedicated thread,
- * as it will not return until one of the callbacks returns true.
- * added_cb will be called immediately for each existing USB device,
- * and subsequently each time a new device is added.
- * removed_cb is called when USB devices are removed from the bus.
- * discovery_done_cb is called after the initial discovery of already
- * connected devices is complete.
- */
-void usb_host_run(struct usb_host_context *context,
-                  usb_device_added_cb added_cb,
-                  usb_device_removed_cb removed_cb,
-                  usb_discovery_done_cb discovery_done_cb,
-                  void *client_data);
-
-/* Creates a usb_device object for a USB device */
-struct usb_device *usb_device_open(const char *dev_name);
-
-/* Releases all resources associated with the USB device */
-void usb_device_close(struct usb_device *device);
-
-/* Creates a usb_device object for already open USB device */
-struct usb_device *usb_device_new(const char *dev_name, int fd);
-
-/* Returns the file descriptor for the usb_device */
-int usb_device_get_fd(struct usb_device *device);
-
-/* Returns the name for the USB device, which is the same as
- * the dev_name passed to usb_device_open()
- */
-const char* usb_device_get_name(struct usb_device *device);
-
-/* Returns a unique ID for the device.
- *Currently this is generated from the dev_name path.
- */
-int usb_device_get_unique_id(struct usb_device *device);
-
-/* Returns a unique ID for the device name.
- * Currently this is generated from the device path.
- */
-int usb_device_get_unique_id_from_name(const char* name);
-
-/* Returns the device name for the unique ID.
- * Call free() to deallocate the returned string */
-char* usb_device_get_name_from_unique_id(int id);
-
-/* Returns the USB vendor ID from the device descriptor for the USB device */
-uint16_t usb_device_get_vendor_id(struct usb_device *device);
-
-/* Returns the USB product ID from the device descriptor for the USB device */
-uint16_t usb_device_get_product_id(struct usb_device *device);
-
-const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device);
-
-/* Returns a USB descriptor string for the given string ID.
- * Used to implement usb_device_get_manufacturer_name,
- * usb_device_get_product_name and usb_device_get_serial.
- * Call free() to free the result when you are done with it.
- */
-char* usb_device_get_string(struct usb_device *device, int id);
-
-/* Returns the manufacturer name for the USB device.
- * Call free() to free the result when you are done with it.
- */
-char* usb_device_get_manufacturer_name(struct usb_device *device);
-
-/* Returns the product name for the USB device.
- * Call free() to free the result when you are done with it.
- */
-char* usb_device_get_product_name(struct usb_device *device);
-
-/* Returns the version number for the USB device.
- */
-int usb_device_get_version(struct usb_device *device);
-
-/* Returns the USB serial number for the USB device.
- * Call free() to free the result when you are done with it.
- */
-char* usb_device_get_serial(struct usb_device *device);
-
-/* Returns true if we have write access to the USB device,
- * and false if we only have access to the USB device configuration.
- */
-int usb_device_is_writeable(struct usb_device *device);
-
-/* Initializes a usb_descriptor_iter, which can be used to iterate through all
- * the USB descriptors for a USB device.
- */
-void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter);
-
-/* Returns the next USB descriptor for a device, or NULL if we have reached the
- * end of the list.
- */
-struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter);
-
-/* Claims the specified interface of a USB device */
-int usb_device_claim_interface(struct usb_device *device, unsigned int interface);
-
-/* Releases the specified interface of a USB device */
-int usb_device_release_interface(struct usb_device *device, unsigned int interface);
-
-/* Requests the kernel to connect or disconnect its driver for the specified interface.
- * This can be used to ask the kernel to disconnect its driver for a device
- * so usb_device_claim_interface can claim it instead.
- */
-int usb_device_connect_kernel_driver(struct usb_device *device,
-        unsigned int interface, int connect);
-
-/* Sets the current configuration for the device to the specified configuration */
-int usb_device_set_configuration(struct usb_device *device, int configuration);
-
-/* Sets the specified interface of a USB device */
-int usb_device_set_interface(struct usb_device *device, unsigned int interface,
-                            unsigned int alt_setting);
-
-/* Sends a control message to the specified device on endpoint zero */
-int usb_device_control_transfer(struct usb_device *device,
-                            int requestType,
-                            int request,
-                            int value,
-                            int index,
-                            void* buffer,
-                            int length,
-                            unsigned int timeout);
-
-/* Reads or writes on a bulk endpoint.
- * Returns number of bytes transferred, or negative value for error.
- */
-int usb_device_bulk_transfer(struct usb_device *device,
-                            int endpoint,
-                            void* buffer,
-                            int length,
-                            unsigned int timeout);
-
-/** Reset USB bus for the device */
-int usb_device_reset(struct usb_device *device);
-
-/* Creates a new usb_request. */
-struct usb_request *usb_request_new(struct usb_device *dev,
-        const struct usb_endpoint_descriptor *ep_desc);
-
-/* Releases all resources associated with the request */
-void usb_request_free(struct usb_request *req);
-
-/* Submits a read or write request on the specified device */
-int usb_request_queue(struct usb_request *req);
-
- /* Waits for the results of a previous usb_request_queue operation.
-  * Returns a usb_request, or NULL for error.
-  */
-struct usb_request *usb_request_wait(struct usb_device *dev);
-
-/* Cancels a pending usb_request_queue() operation. */
-int usb_request_cancel(struct usb_request *req);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* __USB_HOST_H */
diff --git a/include/utils b/include/utils
new file mode 120000
index 0000000..e8476fd
--- /dev/null
+++ b/include/utils
@@ -0,0 +1 @@
+../libutils/include/utils/
\ No newline at end of file
diff --git a/include/utils/BlobCache.h b/include/utils/BlobCache.h
deleted file mode 100644
index 65dca9f..0000000
--- a/include/utils/BlobCache.h
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- ** Copyright 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_BLOB_CACHE_H
-#define ANDROID_BLOB_CACHE_H
-
-#include <stddef.h>
-
-#include <utils/Flattenable.h>
-#include <utils/RefBase.h>
-#include <utils/SortedVector.h>
-#include <utils/threads.h>
-
-namespace android {
-
-// A BlobCache is an in-memory cache for binary key/value pairs.  A BlobCache
-// does NOT provide any thread-safety guarantees.
-//
-// The cache contents can be serialized to an in-memory buffer or mmap'd file
-// and then reloaded in a subsequent execution of the program.  This
-// serialization is non-portable and the data should only be used by the device
-// that generated it.
-class BlobCache : public RefBase {
-
-public:
-
-    // Create an empty blob cache. The blob cache will cache key/value pairs
-    // with key and value sizes less than or equal to maxKeySize and
-    // maxValueSize, respectively. The total combined size of ALL cache entries
-    // (key sizes plus value sizes) will not exceed maxTotalSize.
-    BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize);
-
-    // set inserts a new binary value into the cache and associates it with the
-    // given binary key.  If the key or value are too large for the cache then
-    // the cache remains unchanged.  This includes the case where a different
-    // value was previously associated with the given key - the old value will
-    // remain in the cache.  If the given key and value are small enough to be
-    // put in the cache (based on the maxKeySize, maxValueSize, and maxTotalSize
-    // values specified to the BlobCache constructor), then the key/value pair
-    // will be in the cache after set returns.  Note, however, that a subsequent
-    // call to set may evict old key/value pairs from the cache.
-    //
-    // Preconditions:
-    //   key != NULL
-    //   0 < keySize
-    //   value != NULL
-    //   0 < valueSize
-    void set(const void* key, size_t keySize, const void* value,
-            size_t valueSize);
-
-    // get retrieves from the cache the binary value associated with a given
-    // binary key.  If the key is present in the cache then the length of the
-    // binary value associated with that key is returned.  If the value argument
-    // is non-NULL and the size of the cached value is less than valueSize bytes
-    // then the cached value is copied into the buffer pointed to by the value
-    // argument.  If the key is not present in the cache then 0 is returned and
-    // the buffer pointed to by the value argument is not modified.
-    //
-    // Note that when calling get multiple times with the same key, the later
-    // calls may fail, returning 0, even if earlier calls succeeded.  The return
-    // value must be checked for each call.
-    //
-    // Preconditions:
-    //   key != NULL
-    //   0 < keySize
-    //   0 <= valueSize
-    size_t get(const void* key, size_t keySize, void* value, size_t valueSize);
-
-
-    // getFlattenedSize returns the number of bytes needed to store the entire
-    // serialized cache.
-    size_t getFlattenedSize() const;
-
-    // flatten serializes the current contents of the cache into the memory
-    // pointed to by 'buffer'.  The serialized cache contents can later be
-    // loaded into a BlobCache object using the unflatten method.  The contents
-    // of the BlobCache object will not be modified.
-    //
-    // Preconditions:
-    //   size >= this.getFlattenedSize()
-    status_t flatten(void* buffer, size_t size) const;
-
-    // unflatten replaces the contents of the cache with the serialized cache
-    // contents in the memory pointed to by 'buffer'.  The previous contents of
-    // the BlobCache will be evicted from the cache.  If an error occurs while
-    // unflattening the serialized cache contents then the BlobCache will be
-    // left in an empty state.
-    //
-    status_t unflatten(void const* buffer, size_t size);
-
-private:
-    // Copying is disallowed.
-    BlobCache(const BlobCache&);
-    void operator=(const BlobCache&);
-
-    // A random function helper to get around MinGW not having nrand48()
-    long int blob_random();
-
-    // clean evicts a randomly chosen set of entries from the cache such that
-    // the total size of all remaining entries is less than mMaxTotalSize/2.
-    void clean();
-
-    // isCleanable returns true if the cache is full enough for the clean method
-    // to have some effect, and false otherwise.
-    bool isCleanable() const;
-
-    // A Blob is an immutable sized unstructured data blob.
-    class Blob : public RefBase {
-    public:
-        Blob(const void* data, size_t size, bool copyData);
-        ~Blob();
-
-        bool operator<(const Blob& rhs) const;
-
-        const void* getData() const;
-        size_t getSize() const;
-
-    private:
-        // Copying is not allowed.
-        Blob(const Blob&);
-        void operator=(const Blob&);
-
-        // mData points to the buffer containing the blob data.
-        const void* mData;
-
-        // mSize is the size of the blob data in bytes.
-        size_t mSize;
-
-        // mOwnsData indicates whether or not this Blob object should free the
-        // memory pointed to by mData when the Blob gets destructed.
-        bool mOwnsData;
-    };
-
-    // A CacheEntry is a single key/value pair in the cache.
-    class CacheEntry {
-    public:
-        CacheEntry();
-        CacheEntry(const sp<Blob>& key, const sp<Blob>& value);
-        CacheEntry(const CacheEntry& ce);
-
-        bool operator<(const CacheEntry& rhs) const;
-        const CacheEntry& operator=(const CacheEntry&);
-
-        sp<Blob> getKey() const;
-        sp<Blob> getValue() const;
-
-        void setValue(const sp<Blob>& value);
-
-    private:
-
-        // mKey is the key that identifies the cache entry.
-        sp<Blob> mKey;
-
-        // mValue is the cached data associated with the key.
-        sp<Blob> mValue;
-    };
-
-    // A Header is the header for the entire BlobCache serialization format. No
-    // need to make this portable, so we simply write the struct out.
-    struct Header {
-        // mMagicNumber is the magic number that identifies the data as
-        // serialized BlobCache contents.  It must always contain 'Blb$'.
-        uint32_t mMagicNumber;
-
-        // mBlobCacheVersion is the serialization format version.
-        uint32_t mBlobCacheVersion;
-
-        // mDeviceVersion is the device-specific version of the cache.  This can
-        // be used to invalidate the cache.
-        uint32_t mDeviceVersion;
-
-        // mNumEntries is number of cache entries following the header in the
-        // data.
-        size_t mNumEntries;
-
-        // mBuildId is the build id of the device when the cache was created.
-        // When an update to the build happens (via an OTA or other update) this
-        // is used to invalidate the cache.
-        int mBuildIdLength;
-        char mBuildId[];
-    };
-
-    // An EntryHeader is the header for a serialized cache entry.  No need to
-    // make this portable, so we simply write the struct out.  Each EntryHeader
-    // is followed imediately by the key data and then the value data.
-    //
-    // The beginning of each serialized EntryHeader is 4-byte aligned, so the
-    // number of bytes that a serialized cache entry will occupy is:
-    //
-    //   ((sizeof(EntryHeader) + keySize + valueSize) + 3) & ~3
-    //
-    struct EntryHeader {
-        // mKeySize is the size of the entry key in bytes.
-        size_t mKeySize;
-
-        // mValueSize is the size of the entry value in bytes.
-        size_t mValueSize;
-
-        // mData contains both the key and value data for the cache entry.  The
-        // key comes first followed immediately by the value.
-        uint8_t mData[];
-    };
-
-    // mMaxKeySize is the maximum key size that will be cached. Calls to
-    // BlobCache::set with a keySize parameter larger than mMaxKeySize will
-    // simply not add the key/value pair to the cache.
-    const size_t mMaxKeySize;
-
-    // mMaxValueSize is the maximum value size that will be cached. Calls to
-    // BlobCache::set with a valueSize parameter larger than mMaxValueSize will
-    // simply not add the key/value pair to the cache.
-    const size_t mMaxValueSize;
-
-    // mMaxTotalSize is the maximum size that all cache entries can occupy. This
-    // includes space for both keys and values. When a call to BlobCache::set
-    // would otherwise cause this limit to be exceeded, either the key/value
-    // pair passed to BlobCache::set will not be cached or other cache entries
-    // will be evicted from the cache to make room for the new entry.
-    const size_t mMaxTotalSize;
-
-    // mTotalSize is the total combined size of all keys and values currently in
-    // the cache.
-    size_t mTotalSize;
-
-    // mRandState is the pseudo-random number generator state. It is passed to
-    // nrand48 to generate random numbers when needed.
-    unsigned short mRandState[3];
-
-    // mCacheEntries stores all the cache entries that are resident in memory.
-    // Cache entries are added to it by the 'set' method.
-    SortedVector<CacheEntry> mCacheEntries;
-};
-
-}
-
-#endif // ANDROID_BLOB_CACHE_H
diff --git a/include/utils/Compat.h b/include/utils/Compat.h
deleted file mode 100644
index b2ba55e..0000000
--- a/include/utils/Compat.h
+++ /dev/null
@@ -1,88 +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 __LIB_UTILS_COMPAT_H
-#define __LIB_UTILS_COMPAT_H
-
-#include <unistd.h>
-
-#if defined(__APPLE__)
-
-/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */
-
-typedef off_t off64_t;
-
-static inline off64_t lseek64(int fd, off64_t offset, int whence) {
-    return lseek(fd, offset, whence);
-}
-
-static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) {
-    return pread(fd, buf, nbytes, offset);
-}
-
-static inline ssize_t pwrite64(int fd, const void* buf, size_t nbytes, off64_t offset) {
-    return pwrite(fd, buf, nbytes, offset);
-}
-
-#endif /* __APPLE__ */
-
-#if defined(_WIN32)
-#define O_CLOEXEC O_NOINHERIT
-#define O_NOFOLLOW 0
-#define DEFFILEMODE 0666
-#endif /* _WIN32 */
-
-#if defined(_WIN32)
-#define ZD "%ld"
-#define ZD_TYPE long
-#else
-#define ZD "%zd"
-#define ZD_TYPE ssize_t
-#endif
-
-/*
- * Needed for cases where something should be constexpr if possible, but not
- * being constexpr is fine if in pre-C++11 code (such as a const static float
- * member variable).
- */
-#if __cplusplus >= 201103L
-#define CONSTEXPR constexpr
-#else
-#define CONSTEXPR
-#endif
-
-/*
- * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
- * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
- * not already defined, then define it here.
- */
-#ifndef TEMP_FAILURE_RETRY
-/* Used to retry syscalls that can return EINTR. */
-#define TEMP_FAILURE_RETRY(exp) ({         \
-    typeof (exp) _rc;                      \
-    do {                                   \
-        _rc = (exp);                       \
-    } while (_rc == -1 && errno == EINTR); \
-    _rc; })
-#endif
-
-#if defined(_WIN32)
-#define OS_PATH_SEPARATOR '\\'
-#else
-#define OS_PATH_SEPARATOR '/'
-#endif
-
-#endif /* __LIB_UTILS_COMPAT_H */
diff --git a/include/utils/Condition.h b/include/utils/Condition.h
deleted file mode 100644
index 5a72519..0000000
--- a/include/utils/Condition.h
+++ /dev/null
@@ -1,158 +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.
- */
-
-#ifndef _LIBS_UTILS_CONDITION_H
-#define _LIBS_UTILS_CONDITION_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if !defined(_WIN32)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-#include <utils/Timers.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-/*
- * Condition variable class.  The implementation is system-dependent.
- *
- * Condition variables are paired up with mutexes.  Lock the mutex,
- * call wait(), then either re-wait() if things aren't quite what you want,
- * or unlock the mutex and continue.  All threads calling wait() must
- * use the same mutex for a given Condition.
- */
-class Condition {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-
-    enum WakeUpType {
-        WAKE_UP_ONE = 0,
-        WAKE_UP_ALL = 1
-    };
-
-    Condition();
-    Condition(int type);
-    ~Condition();
-    // Wait on the condition variable.  Lock the mutex before calling.
-    status_t wait(Mutex& mutex);
-    // same with relative timeout
-    status_t waitRelative(Mutex& mutex, nsecs_t reltime);
-    // Signal the condition variable, allowing exactly one thread to continue.
-    void signal();
-    // Signal the condition variable, allowing one or all threads to continue.
-    void signal(WakeUpType type) {
-        if (type == WAKE_UP_ONE) {
-            signal();
-        } else {
-            broadcast();
-        }
-    }
-    // Signal the condition variable, allowing all threads to continue.
-    void broadcast();
-
-private:
-#if !defined(_WIN32)
-    pthread_cond_t mCond;
-#else
-    void*   mState;
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-#if !defined(_WIN32)
-
-inline Condition::Condition() {
-    pthread_cond_init(&mCond, NULL);
-}
-inline Condition::Condition(int type) {
-    if (type == SHARED) {
-        pthread_condattr_t attr;
-        pthread_condattr_init(&attr);
-        pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_cond_init(&mCond, &attr);
-        pthread_condattr_destroy(&attr);
-    } else {
-        pthread_cond_init(&mCond, NULL);
-    }
-}
-inline Condition::~Condition() {
-    pthread_cond_destroy(&mCond);
-}
-inline status_t Condition::wait(Mutex& mutex) {
-    return -pthread_cond_wait(&mCond, &mutex.mMutex);
-}
-inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
-#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
-    struct timespec ts;
-    ts.tv_sec  = reltime/1000000000;
-    ts.tv_nsec = reltime%1000000000;
-    return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
-#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
-    struct timespec ts;
-#if defined(__linux__)
-    clock_gettime(CLOCK_REALTIME, &ts);
-#else // __APPLE__
-    // we don't support the clocks here.
-    struct timeval t;
-    gettimeofday(&t, NULL);
-    ts.tv_sec = t.tv_sec;
-    ts.tv_nsec= t.tv_usec*1000;
-#endif
-    ts.tv_sec += reltime/1000000000;
-    ts.tv_nsec+= reltime%1000000000;
-    if (ts.tv_nsec >= 1000000000) {
-        ts.tv_nsec -= 1000000000;
-        ts.tv_sec  += 1;
-    }
-    return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
-#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
-}
-inline void Condition::signal() {
-    /*
-     * POSIX says pthread_cond_signal wakes up "one or more" waiting threads.
-     * However bionic follows the glibc guarantee which wakes up "exactly one"
-     * waiting thread.
-     *
-     * man 3 pthread_cond_signal
-     *   pthread_cond_signal restarts one of the threads that are waiting on
-     *   the condition variable cond. If no threads are waiting on cond,
-     *   nothing happens. If several threads are waiting on cond, exactly one
-     *   is restarted, but it is not specified which.
-     */
-    pthread_cond_signal(&mCond);
-}
-inline void Condition::broadcast() {
-    pthread_cond_broadcast(&mCond);
-}
-
-#endif // !defined(_WIN32)
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_CONDITON_H
diff --git a/include/utils/Flattenable.h b/include/utils/Flattenable.h
deleted file mode 100644
index 882a8b2..0000000
--- a/include/utils/Flattenable.h
+++ /dev/null
@@ -1,198 +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 ANDROID_UTILS_FLATTENABLE_H
-#define ANDROID_UTILS_FLATTENABLE_H
-
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/Errors.h>
-#include <utils/Debug.h>
-
-namespace android {
-
-
-class FlattenableUtils {
-public:
-    template<int N>
-    static size_t align(size_t size) {
-        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
-        return (size + (N-1)) & ~(N-1);
-    }
-
-    template<int N>
-    static size_t align(void const*& buffer) {
-        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
-        intptr_t b = intptr_t(buffer);
-        buffer = (void*)((intptr_t(buffer) + (N-1)) & ~(N-1));
-        return size_t(intptr_t(buffer) - b);
-    }
-
-    template<int N>
-    static size_t align(void*& buffer) {
-        return align<N>( const_cast<void const*&>(buffer) );
-    }
-
-    static void advance(void*& buffer, size_t& size, size_t offset) {
-        buffer = reinterpret_cast<void*>( intptr_t(buffer) + offset );
-        size -= offset;
-    }
-
-    static void advance(void const*& buffer, size_t& size, size_t offset) {
-        buffer = reinterpret_cast<void const*>( intptr_t(buffer) + offset );
-        size -= offset;
-    }
-
-    // write a POD structure
-    template<typename T>
-    static void write(void*& buffer, size_t& size, const T& value) {
-        *static_cast<T*>(buffer) = value;
-        advance(buffer, size, sizeof(T));
-    }
-
-    // read a POD structure
-    template<typename T>
-    static void read(void const*& buffer, size_t& size, T& value) {
-        value = *static_cast<T const*>(buffer);
-        advance(buffer, size, sizeof(T));
-    }
-};
-
-
-/*
- * The Flattenable protocol allows an object to serialize itself out
- * to a byte-buffer and an array of file descriptors.
- * Flattenable objects must implement this protocol.
- */
-
-template <typename T>
-class Flattenable {
-public:
-    // size in bytes of the flattened object
-    inline size_t getFlattenedSize() const;
-
-    // number of file descriptors to flatten
-    inline size_t getFdCount() const;
-
-    // flattens the object into buffer.
-    // size should be at least of getFlattenedSize()
-    // file descriptors are written in the fds[] array but ownership is
-    // not transfered (ie: they must be dupped by the caller of
-    // flatten() if needed).
-    inline status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
-
-    // unflattens the object from buffer.
-    // size should be equal to the value of getFlattenedSize() when the
-    // object was flattened.
-    // unflattened file descriptors are found in the fds[] array and
-    // don't need to be dupped(). ie: the caller of unflatten doesn't
-    // keep ownership. If a fd is not retained by unflatten() it must be
-    // explicitly closed.
-    inline status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
-};
-
-template<typename T>
-inline size_t Flattenable<T>::getFlattenedSize() const {
-    return static_cast<T const*>(this)->T::getFlattenedSize();
-}
-template<typename T>
-inline size_t Flattenable<T>::getFdCount() const {
-    return static_cast<T const*>(this)->T::getFdCount();
-}
-template<typename T>
-inline status_t Flattenable<T>::flatten(
-        void*& buffer, size_t& size, int*& fds, size_t& count) const {
-    return static_cast<T const*>(this)->T::flatten(buffer, size, fds, count);
-}
-template<typename T>
-inline status_t Flattenable<T>::unflatten(
-        void const*& buffer, size_t& size, int const*& fds, size_t& count) {
-    return static_cast<T*>(this)->T::unflatten(buffer, size, fds, count);
-}
-
-/*
- * LightFlattenable is a protocol allowing object to serialize themselves out
- * to a byte-buffer. Because it doesn't handle file-descriptors,
- * LightFlattenable is usually more size efficient than Flattenable.
- * LightFlattenable objects must implement this protocol.
- */
-template <typename T>
-class LightFlattenable {
-public:
-    // returns whether this object always flatten into the same size.
-    // for efficiency, this should always be inline.
-    inline bool isFixedSize() const;
-
-    // returns size in bytes of the flattened object. must be a constant.
-    inline size_t getFlattenedSize() const;
-
-    // flattens the object into buffer.
-    inline status_t flatten(void* buffer, size_t size) const;
-
-    // unflattens the object from buffer of given size.
-    inline status_t unflatten(void const* buffer, size_t size);
-};
-
-template <typename T>
-inline bool LightFlattenable<T>::isFixedSize() const {
-    return static_cast<T const*>(this)->T::isFixedSize();
-}
-template <typename T>
-inline size_t LightFlattenable<T>::getFlattenedSize() const {
-    return static_cast<T const*>(this)->T::getFlattenedSize();
-}
-template <typename T>
-inline status_t LightFlattenable<T>::flatten(void* buffer, size_t size) const {
-    return static_cast<T const*>(this)->T::flatten(buffer, size);
-}
-template <typename T>
-inline status_t LightFlattenable<T>::unflatten(void const* buffer, size_t size) {
-    return static_cast<T*>(this)->T::unflatten(buffer, size);
-}
-
-/*
- * LightFlattenablePod is an implementation of the LightFlattenable protocol
- * for POD (plain-old-data) objects.
- * Simply derive from LightFlattenablePod<Foo> to make Foo flattenable; no
- * need to implement any methods; obviously Foo must be a POD structure.
- */
-template <typename T>
-class LightFlattenablePod : public LightFlattenable<T> {
-public:
-    inline bool isFixedSize() const {
-        return true;
-    }
-
-    inline size_t getFlattenedSize() const {
-        return sizeof(T);
-    }
-    inline status_t flatten(void* buffer, size_t size) const {
-        if (size < sizeof(T)) return NO_MEMORY;
-        *reinterpret_cast<T*>(buffer) = *static_cast<T const*>(this);
-        return NO_ERROR;
-    }
-    inline status_t unflatten(void const* buffer, size_t) {
-        *static_cast<T*>(this) = *reinterpret_cast<T const*>(buffer);
-        return NO_ERROR;
-    }
-};
-
-
-}; // namespace android
-
-
-#endif /* ANDROID_UTILS_FLATTENABLE_H */
diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h
deleted file mode 100644
index c4faae0..0000000
--- a/include/utils/KeyedVector.h
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2005 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_KEYED_VECTOR_H
-#define ANDROID_KEYED_VECTOR_H
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/log.h>
-
-#include <utils/SortedVector.h>
-#include <utils/TypeHelpers.h>
-#include <utils/Errors.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-template <typename KEY, typename VALUE>
-class KeyedVector
-{
-public:
-    typedef KEY    key_type;
-    typedef VALUE  value_type;
-
-    inline                  KeyedVector();
-
-    /*
-     * empty the vector
-     */
-
-    inline  void            clear()                     { mVector.clear(); }
-
-    /*! 
-     * vector stats
-     */
-
-    //! returns number of items in the vector
-    inline  size_t          size() const                { return mVector.size(); }
-    //! returns whether or not the vector is empty
-    inline  bool            isEmpty() const             { return mVector.isEmpty(); }
-    //! returns how many items can be stored without reallocating the backing store
-    inline  size_t          capacity() const            { return mVector.capacity(); }
-    //! sets the capacity. capacity can never be reduced less than size()
-    inline ssize_t          setCapacity(size_t size)    { return mVector.setCapacity(size); }
-
-    // returns true if the arguments is known to be identical to this vector
-    inline bool isIdenticalTo(const KeyedVector& rhs) const;
-
-    /*! 
-     * accessors
-     */
-            const VALUE&    valueFor(const KEY& key) const;
-            const VALUE&    valueAt(size_t index) const;
-            const KEY&      keyAt(size_t index) const;
-            ssize_t         indexOfKey(const KEY& key) const;
-            const VALUE&    operator[] (size_t index) const;
-
-    /*!
-     * modifying the array
-     */
-
-            VALUE&          editValueFor(const KEY& key);
-            VALUE&          editValueAt(size_t index);
-
-            /*! 
-             * add/insert/replace items
-             */
-             
-            ssize_t         add(const KEY& key, const VALUE& item);
-            ssize_t         replaceValueFor(const KEY& key, const VALUE& item);
-            ssize_t         replaceValueAt(size_t index, const VALUE& item);
-
-    /*!
-     * remove items
-     */
-
-            ssize_t         removeItem(const KEY& key);
-            ssize_t         removeItemsAt(size_t index, size_t count = 1);
-            
-private:
-            SortedVector< key_value_pair_t<KEY, VALUE> >    mVector;
-};
-
-// KeyedVector<KEY, VALUE> can be trivially moved using memcpy() because its
-// underlying SortedVector can be trivially moved.
-template<typename KEY, typename VALUE> struct trait_trivial_move<KeyedVector<KEY, VALUE> > {
-    enum { value = trait_trivial_move<SortedVector< key_value_pair_t<KEY, VALUE> > >::value };
-};
-
-
-// ---------------------------------------------------------------------------
-
-/**
- * Variation of KeyedVector that holds a default value to return when
- * valueFor() is called with a key that doesn't exist.
- */
-template <typename KEY, typename VALUE>
-class DefaultKeyedVector : public KeyedVector<KEY, VALUE>
-{
-public:
-    inline                  DefaultKeyedVector(const VALUE& defValue = VALUE());
-            const VALUE&    valueFor(const KEY& key) const;
-
-private:
-            VALUE                                           mDefault;
-};
-
-// ---------------------------------------------------------------------------
-
-template<typename KEY, typename VALUE> inline
-KeyedVector<KEY,VALUE>::KeyedVector()
-{
-}
-
-template<typename KEY, typename VALUE> inline
-bool KeyedVector<KEY,VALUE>::isIdenticalTo(const KeyedVector<KEY,VALUE>& rhs) const {
-    return mVector.array() == rhs.mVector.array();
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::indexOfKey(const KEY& key) const {
-    return mVector.indexOf( key_value_pair_t<KEY,VALUE>(key) );
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
-    ssize_t i = this->indexOfKey(key);
-    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
-    return mVector.itemAt(i).value;
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::valueAt(size_t index) const {
-    return mVector.itemAt(index).value;
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::operator[] (size_t index) const {
-    return valueAt(index);
-}
-
-template<typename KEY, typename VALUE> inline
-const KEY& KeyedVector<KEY,VALUE>::keyAt(size_t index) const {
-    return mVector.itemAt(index).key;
-}
-
-template<typename KEY, typename VALUE> inline
-VALUE& KeyedVector<KEY,VALUE>::editValueFor(const KEY& key) {
-    ssize_t i = this->indexOfKey(key);
-    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
-    return mVector.editItemAt(i).value;
-}
-
-template<typename KEY, typename VALUE> inline
-VALUE& KeyedVector<KEY,VALUE>::editValueAt(size_t index) {
-    return mVector.editItemAt(index).value;
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::add(const KEY& key, const VALUE& value) {
-    return mVector.add( key_value_pair_t<KEY,VALUE>(key, value) );
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::replaceValueFor(const KEY& key, const VALUE& value) {
-    key_value_pair_t<KEY,VALUE> pair(key, value);
-    mVector.remove(pair);
-    return mVector.add(pair);
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) {
-    if (index<size()) {
-        mVector.editItemAt(index).value = item;
-        return index;
-    }
-    return BAD_INDEX;
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::removeItem(const KEY& key) {
-    return mVector.remove(key_value_pair_t<KEY,VALUE>(key));
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY, VALUE>::removeItemsAt(size_t index, size_t count) {
-    return mVector.removeItemsAt(index, count);
-}
-
-// ---------------------------------------------------------------------------
-
-template<typename KEY, typename VALUE> inline
-DefaultKeyedVector<KEY,VALUE>::DefaultKeyedVector(const VALUE& defValue)
-    : mDefault(defValue)
-{
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& DefaultKeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
-    ssize_t i = this->indexOfKey(key);
-    return i >= 0 ? KeyedVector<KEY,VALUE>::valueAt(i) : mDefault;
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_KEYED_VECTOR_H
diff --git a/include/utils/LinearTransform.h b/include/utils/LinearTransform.h
deleted file mode 100644
index 04cb355..0000000
--- a/include/utils/LinearTransform.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 _LIBS_UTILS_LINEAR_TRANSFORM_H
-#define _LIBS_UTILS_LINEAR_TRANSFORM_H
-
-#include <stdint.h>
-
-namespace android {
-
-// LinearTransform defines a structure which hold the definition of a
-// transformation from single dimensional coordinate system A into coordinate
-// system B (and back again).  Values in A and in B are 64 bit, the linear
-// scale factor is expressed as a rational number using two 32 bit values.
-//
-// Specifically, let
-// f(a) = b
-// F(b) = f^-1(b) = a
-// then
-//
-// f(a) = (((a - a_zero) * a_to_b_numer) / a_to_b_denom) + b_zero;
-//
-// and
-//
-// F(b) = (((b - b_zero) * a_to_b_denom) / a_to_b_numer) + a_zero;
-//
-struct LinearTransform {
-  int64_t  a_zero;
-  int64_t  b_zero;
-  int32_t  a_to_b_numer;
-  uint32_t a_to_b_denom;
-
-  // Transform from A->B
-  // Returns true on success, or false in the case of a singularity or an
-  // overflow.
-  bool doForwardTransform(int64_t a_in, int64_t* b_out) const;
-
-  // Transform from B->A
-  // Returns true on success, or false in the case of a singularity or an
-  // overflow.
-  bool doReverseTransform(int64_t b_in, int64_t* a_out) const;
-
-  // Helpers which will reduce the fraction N/D using Euclid's method.
-  template <class T> static void reduce(T* N, T* D);
-  static void reduce(int32_t* N, uint32_t* D);
-};
-
-
-}
-
-#endif  // _LIBS_UTILS_LINEAR_TRANSFORM_H
diff --git a/include/utils/Log.h b/include/utils/Log.h
deleted file mode 100644
index 4259c86..0000000
--- a/include/utils/Log.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// C/C++ logging functions.  See the logging documentation for API details.
-//
-// We'd like these to be available from C code (in case we import some from
-// somewhere), so this has a C interface.
-//
-// The output will be correct when the log file is shared between multiple
-// threads and/or multiple processes so long as the operating system
-// supports O_APPEND.  These calls have mutex-protected data structures
-// and so are NOT reentrant.  Do not use LOG in a signal handler.
-//
-#ifndef _LIBS_UTILS_LOG_H
-#define _LIBS_UTILS_LOG_H
-
-#include <cutils/log.h>
-#include <sys/types.h>
-
-#ifdef __cplusplus
-
-namespace android {
-
-/*
- * A very simple utility that yells in the log when an operation takes too long.
- */
-class LogIfSlow {
-public:
-    LogIfSlow(const char* tag, android_LogPriority priority,
-            int timeoutMillis, const char* message);
-    ~LogIfSlow();
-
-private:
-    const char* const mTag;
-    const android_LogPriority mPriority;
-    const int mTimeoutMillis;
-    const char* const mMessage;
-    const int64_t mStart;
-};
-
-/*
- * Writes the specified debug log message if this block takes longer than the
- * specified number of milliseconds to run.  Includes the time actually taken.
- *
- * {
- *     ALOGD_IF_SLOW(50, "Excessive delay doing something.");
- *     doSomething();
- * }
- */
-#define ALOGD_IF_SLOW(timeoutMillis, message) \
-    android::LogIfSlow _logIfSlow(LOG_TAG, ANDROID_LOG_DEBUG, timeoutMillis, message);
-
-} // namespace android
-
-#endif // __cplusplus
-
-#endif // _LIBS_UTILS_LOG_H
diff --git a/include/utils/Looper.h b/include/utils/Looper.h
deleted file mode 100644
index da2d5f2..0000000
--- a/include/utils/Looper.h
+++ /dev/null
@@ -1,487 +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 UTILS_LOOPER_H
-#define UTILS_LOOPER_H
-
-#include <utils/threads.h>
-#include <utils/RefBase.h>
-#include <utils/KeyedVector.h>
-#include <utils/Timers.h>
-
-#include <sys/epoll.h>
-
-namespace android {
-
-/*
- * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
- * enums and the signature of Looper_callbackFunc need to align with
- * that implementation.
- */
-
-/**
- * For callback-based event loops, this is the prototype of the function
- * that is called when a file descriptor event occurs.
- * It is given the file descriptor it is associated with,
- * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
- * and the data pointer that was originally supplied.
- *
- * Implementations should return 1 to continue receiving callbacks, or 0
- * to have this file descriptor and callback unregistered from the looper.
- */
-typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
-
-/**
- * A message that can be posted to a Looper.
- */
-struct Message {
-    Message() : what(0) { }
-    Message(int what) : what(what) { }
-
-    /* The message type. (interpretation is left up to the handler) */
-    int what;
-};
-
-
-/**
- * Interface for a Looper message handler.
- *
- * The Looper holds a strong reference to the message handler whenever it has
- * a message to deliver to it.  Make sure to call Looper::removeMessages
- * to remove any pending messages destined for the handler so that the handler
- * can be destroyed.
- */
-class MessageHandler : public virtual RefBase {
-protected:
-    virtual ~MessageHandler() { }
-
-public:
-    /**
-     * Handles a message.
-     */
-    virtual void handleMessage(const Message& message) = 0;
-};
-
-
-/**
- * A simple proxy that holds a weak reference to a message handler.
- */
-class WeakMessageHandler : public MessageHandler {
-protected:
-    virtual ~WeakMessageHandler();
-
-public:
-    WeakMessageHandler(const wp<MessageHandler>& handler);
-    virtual void handleMessage(const Message& message);
-
-private:
-    wp<MessageHandler> mHandler;
-};
-
-
-/**
- * A looper callback.
- */
-class LooperCallback : public virtual RefBase {
-protected:
-    virtual ~LooperCallback() { }
-
-public:
-    /**
-     * Handles a poll event for the given file descriptor.
-     * It is given the file descriptor it is associated with,
-     * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
-     * and the data pointer that was originally supplied.
-     *
-     * Implementations should return 1 to continue receiving callbacks, or 0
-     * to have this file descriptor and callback unregistered from the looper.
-     */
-    virtual int handleEvent(int fd, int events, void* data) = 0;
-};
-
-/**
- * Wraps a Looper_callbackFunc function pointer.
- */
-class SimpleLooperCallback : public LooperCallback {
-protected:
-    virtual ~SimpleLooperCallback();
-
-public:
-    SimpleLooperCallback(Looper_callbackFunc callback);
-    virtual int handleEvent(int fd, int events, void* data);
-
-private:
-    Looper_callbackFunc mCallback;
-};
-
-/**
- * A polling loop that supports monitoring file descriptor events, optionally
- * using callbacks.  The implementation uses epoll() internally.
- *
- * A looper can be associated with a thread although there is no requirement that it must be.
- */
-class Looper : public RefBase {
-protected:
-    virtual ~Looper();
-
-public:
-    enum {
-        /**
-         * Result from Looper_pollOnce() and Looper_pollAll():
-         * The poll was awoken using wake() before the timeout expired
-         * and no callbacks were executed and no other file descriptors were ready.
-         */
-        POLL_WAKE = -1,
-
-        /**
-         * Result from Looper_pollOnce() and Looper_pollAll():
-         * One or more callbacks were executed.
-         */
-        POLL_CALLBACK = -2,
-
-        /**
-         * Result from Looper_pollOnce() and Looper_pollAll():
-         * The timeout expired.
-         */
-        POLL_TIMEOUT = -3,
-
-        /**
-         * Result from Looper_pollOnce() and Looper_pollAll():
-         * An error occurred.
-         */
-        POLL_ERROR = -4,
-    };
-
-    /**
-     * Flags for file descriptor events that a looper can monitor.
-     *
-     * These flag bits can be combined to monitor multiple events at once.
-     */
-    enum {
-        /**
-         * The file descriptor is available for read operations.
-         */
-        EVENT_INPUT = 1 << 0,
-
-        /**
-         * The file descriptor is available for write operations.
-         */
-        EVENT_OUTPUT = 1 << 1,
-
-        /**
-         * The file descriptor has encountered an error condition.
-         *
-         * The looper always sends notifications about errors; it is not necessary
-         * to specify this event flag in the requested event set.
-         */
-        EVENT_ERROR = 1 << 2,
-
-        /**
-         * The file descriptor was hung up.
-         * For example, indicates that the remote end of a pipe or socket was closed.
-         *
-         * The looper always sends notifications about hangups; it is not necessary
-         * to specify this event flag in the requested event set.
-         */
-        EVENT_HANGUP = 1 << 3,
-
-        /**
-         * The file descriptor is invalid.
-         * For example, the file descriptor was closed prematurely.
-         *
-         * The looper always sends notifications about invalid file descriptors; it is not necessary
-         * to specify this event flag in the requested event set.
-         */
-        EVENT_INVALID = 1 << 4,
-    };
-
-    enum {
-        /**
-         * Option for Looper_prepare: this looper will accept calls to
-         * Looper_addFd() that do not have a callback (that is provide NULL
-         * for the callback).  In this case the caller of Looper_pollOnce()
-         * or Looper_pollAll() MUST check the return from these functions to
-         * discover when data is available on such fds and process it.
-         */
-        PREPARE_ALLOW_NON_CALLBACKS = 1<<0
-    };
-
-    /**
-     * Creates a looper.
-     *
-     * If allowNonCallbaks is true, the looper will allow file descriptors to be
-     * registered without associated callbacks.  This assumes that the caller of
-     * pollOnce() is prepared to handle callback-less events itself.
-     */
-    Looper(bool allowNonCallbacks);
-
-    /**
-     * Returns whether this looper instance allows the registration of file descriptors
-     * using identifiers instead of callbacks.
-     */
-    bool getAllowNonCallbacks() const;
-
-    /**
-     * Waits for events to be available, with optional timeout in milliseconds.
-     * Invokes callbacks for all file descriptors on which an event occurred.
-     *
-     * If the timeout is zero, returns immediately without blocking.
-     * If the timeout is negative, waits indefinitely until an event appears.
-     *
-     * Returns POLL_WAKE if the poll was awoken using wake() before
-     * the timeout expired and no callbacks were invoked and no other file
-     * descriptors were ready.
-     *
-     * Returns POLL_CALLBACK if one or more callbacks were invoked.
-     *
-     * Returns POLL_TIMEOUT if there was no data before the given
-     * timeout expired.
-     *
-     * Returns POLL_ERROR if an error occurred.
-     *
-     * Returns a value >= 0 containing an identifier if its file descriptor has data
-     * and it has no callback function (requiring the caller here to handle it).
-     * In this (and only this) case outFd, outEvents and outData will contain the poll
-     * events and data associated with the fd, otherwise they will be set to NULL.
-     *
-     * This method does not return until it has finished invoking the appropriate callbacks
-     * for all file descriptors that were signalled.
-     */
-    int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
-    inline int pollOnce(int timeoutMillis) {
-        return pollOnce(timeoutMillis, NULL, NULL, NULL);
-    }
-
-    /**
-     * Like pollOnce(), but performs all pending callbacks until all
-     * data has been consumed or a file descriptor is available with no callback.
-     * This function will never return POLL_CALLBACK.
-     */
-    int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
-    inline int pollAll(int timeoutMillis) {
-        return pollAll(timeoutMillis, NULL, NULL, NULL);
-    }
-
-    /**
-     * Wakes the poll asynchronously.
-     *
-     * This method can be called on any thread.
-     * This method returns immediately.
-     */
-    void wake();
-
-    /**
-     * Adds a new file descriptor to be polled by the looper.
-     * If the same file descriptor was previously added, it is replaced.
-     *
-     * "fd" is the file descriptor to be added.
-     * "ident" is an identifier for this event, which is returned from pollOnce().
-     * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
-     * "events" are the poll events to wake up on.  Typically this is EVENT_INPUT.
-     * "callback" is the function to call when there is an event on the file descriptor.
-     * "data" is a private data pointer to supply to the callback.
-     *
-     * There are two main uses of this function:
-     *
-     * (1) If "callback" is non-NULL, then this function will be called when there is
-     * data on the file descriptor.  It should execute any events it has pending,
-     * appropriately reading from the file descriptor.  The 'ident' is ignored in this case.
-     *
-     * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
-     * when its file descriptor has data available, requiring the caller to take
-     * care of processing it.
-     *
-     * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
-     *
-     * This method can be called on any thread.
-     * This method may block briefly if it needs to wake the poll.
-     *
-     * The callback may either be specified as a bare function pointer or as a smart
-     * pointer callback object.  The smart pointer should be preferred because it is
-     * easier to avoid races when the callback is removed from a different thread.
-     * See removeFd() for details.
-     */
-    int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
-    int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
-
-    /**
-     * Removes a previously added file descriptor from the looper.
-     *
-     * When this method returns, it is safe to close the file descriptor since the looper
-     * will no longer have a reference to it.  However, it is possible for the callback to
-     * already be running or for it to run one last time if the file descriptor was already
-     * signalled.  Calling code is responsible for ensuring that this case is safely handled.
-     * For example, if the callback takes care of removing itself during its own execution either
-     * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
-     * again at any later time unless registered anew.
-     *
-     * A simple way to avoid this problem is to use the version of addFd() that takes
-     * a sp<LooperCallback> instead of a bare function pointer.  The LooperCallback will
-     * be released at the appropriate time by the Looper.
-     *
-     * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
-     *
-     * This method can be called on any thread.
-     * This method may block briefly if it needs to wake the poll.
-     */
-    int removeFd(int fd);
-
-    /**
-     * Enqueues a message to be processed by the specified handler.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessage(const sp<MessageHandler>& handler, const Message& message);
-
-    /**
-     * Enqueues a message to be processed by the specified handler after all pending messages
-     * after the specified delay.
-     *
-     * The time delay is specified in uptime nanoseconds.
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
-            const Message& message);
-
-    /**
-     * Enqueues a message to be processed by the specified handler after all pending messages
-     * at the specified time.
-     *
-     * The time is specified in uptime nanoseconds.
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
-            const Message& message);
-
-    /**
-     * Removes all messages for the specified handler from the queue.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void removeMessages(const sp<MessageHandler>& handler);
-
-    /**
-     * Removes all messages of a particular type for the specified handler from the queue.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void removeMessages(const sp<MessageHandler>& handler, int what);
-
-    /**
-     * Returns whether this looper's thread is currently polling for more work to do.
-     * This is a good signal that the loop is still alive rather than being stuck
-     * handling a callback.  Note that this method is intrinsically racy, since the
-     * state of the loop can change before you get the result back.
-     */
-    bool isPolling() const;
-
-    /**
-     * Prepares a looper associated with the calling thread, and returns it.
-     * If the thread already has a looper, it is returned.  Otherwise, a new
-     * one is created, associated with the thread, and returned.
-     *
-     * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
-     */
-    static sp<Looper> prepare(int opts);
-
-    /**
-     * Sets the given looper to be associated with the calling thread.
-     * If another looper is already associated with the thread, it is replaced.
-     *
-     * If "looper" is NULL, removes the currently associated looper.
-     */
-    static void setForThread(const sp<Looper>& looper);
-
-    /**
-     * Returns the looper associated with the calling thread, or NULL if
-     * there is not one.
-     */
-    static sp<Looper> getForThread();
-
-private:
-    struct Request {
-        int fd;
-        int ident;
-        int events;
-        int seq;
-        sp<LooperCallback> callback;
-        void* data;
-
-        void initEventItem(struct epoll_event* eventItem) const;
-    };
-
-    struct Response {
-        int events;
-        Request request;
-    };
-
-    struct MessageEnvelope {
-        MessageEnvelope() : uptime(0) { }
-
-        MessageEnvelope(nsecs_t uptime, const sp<MessageHandler> handler,
-                const Message& message) : uptime(uptime), handler(handler), message(message) {
-        }
-
-        nsecs_t uptime;
-        sp<MessageHandler> handler;
-        Message message;
-    };
-
-    const bool mAllowNonCallbacks; // immutable
-
-    int mWakeEventFd;  // immutable
-    Mutex mLock;
-
-    Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
-    bool mSendingMessage; // guarded by mLock
-
-    // Whether we are currently waiting for work.  Not protected by a lock,
-    // any use of it is racy anyway.
-    volatile bool mPolling;
-
-    int mEpollFd; // guarded by mLock but only modified on the looper thread
-    bool mEpollRebuildRequired; // guarded by mLock
-
-    // Locked list of file descriptor monitoring requests.
-    KeyedVector<int, Request> mRequests;  // guarded by mLock
-    int mNextRequestSeq;
-
-    // This state is only used privately by pollOnce and does not require a lock since
-    // it runs on a single thread.
-    Vector<Response> mResponses;
-    size_t mResponseIndex;
-    nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
-
-    int pollInner(int timeoutMillis);
-    int removeFd(int fd, int seq);
-    void awoken();
-    void pushResponse(int events, const Request& request);
-    void rebuildEpollLocked();
-    void scheduleEpollRebuildLocked();
-
-    static void initTLSKey();
-    static void threadDestructor(void *st);
-    static void initEpollEvent(struct epoll_event* eventItem);
-};
-
-} // namespace android
-
-#endif // UTILS_LOOPER_H
diff --git a/include/utils/LruCache.h b/include/utils/LruCache.h
deleted file mode 100644
index ed96fe4..0000000
--- a/include/utils/LruCache.h
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_UTILS_LRU_CACHE_H
-#define ANDROID_UTILS_LRU_CACHE_H
-
-#include <memory>
-#include <unordered_set>
-
-#include "utils/TypeHelpers.h"  // hash_t
-
-namespace android {
-
-/**
- * GenerationCache callback used when an item is removed
- */
-template<typename EntryKey, typename EntryValue>
-class OnEntryRemoved {
-public:
-    virtual ~OnEntryRemoved() { };
-    virtual void operator()(EntryKey& key, EntryValue& value) = 0;
-}; // class OnEntryRemoved
-
-template <typename TKey, typename TValue>
-class LruCache {
-public:
-    explicit LruCache(uint32_t maxCapacity);
-    virtual ~LruCache();
-
-    enum Capacity {
-        kUnlimitedCapacity,
-    };
-
-    void setOnEntryRemovedListener(OnEntryRemoved<TKey, TValue>* listener);
-    size_t size() const;
-    const TValue& get(const TKey& key);
-    bool put(const TKey& key, const TValue& value);
-    bool remove(const TKey& key);
-    bool removeOldest();
-    void clear();
-    const TValue& peekOldestValue();
-
-private:
-    LruCache(const LruCache& that);  // disallow copy constructor
-
-    struct Entry {
-        TKey key;
-        TValue value;
-        Entry* parent;
-        Entry* child;
-
-        Entry(TKey key_, TValue value_) : key(key_), value(value_), parent(NULL), child(NULL) {
-        }
-        const TKey& getKey() const { return key; }
-    };
-
-    struct HashForEntry : public std::unary_function<Entry*, hash_t> {
-        size_t operator() (const Entry* entry) const {
-            return hash_type(entry->key);
-        };
-    };
-
-    struct EqualityForHashedEntries : public std::unary_function<Entry*, hash_t> {
-        bool operator() (const Entry* lhs, const Entry* rhs) const {
-            return lhs->key == rhs->key;
-        };
-    };
-
-    typedef std::unordered_set<Entry*, HashForEntry, EqualityForHashedEntries> LruCacheSet;
-
-    void attachToCache(Entry& entry);
-    void detachFromCache(Entry& entry);
-
-    typename LruCacheSet::iterator findByKey(const TKey& key) {
-        Entry entryForSearch(key, mNullValue);
-        typename LruCacheSet::iterator result = mSet->find(&entryForSearch);
-        return result;
-    }
-
-    std::unique_ptr<LruCacheSet> mSet;
-    OnEntryRemoved<TKey, TValue>* mListener;
-    Entry* mOldest;
-    Entry* mYoungest;
-    uint32_t mMaxCapacity;
-    TValue mNullValue;
-
-public:
-    // To be used like:
-    // while (it.next()) {
-    //   it.value(); it.key();
-    // }
-    class Iterator {
-    public:
-        Iterator(const LruCache<TKey, TValue>& cache):
-                mCache(cache), mIterator(mCache.mSet->begin()), mBeginReturned(false) {
-        }
-
-        bool next() {
-            if (mIterator == mCache.mSet->end()) {
-                return false;
-            }
-            if (!mBeginReturned) {
-                // mIterator has been initialized to the beginning and
-                // hasn't been returned. Do not advance:
-                mBeginReturned = true;
-            } else {
-                std::advance(mIterator, 1);
-            }
-            bool ret = (mIterator != mCache.mSet->end());
-            return ret;
-        }
-
-        const TValue& value() const {
-            return (*mIterator)->value;
-        }
-
-        const TKey& key() const {
-            return (*mIterator)->key;
-        }
-    private:
-        const LruCache<TKey, TValue>& mCache;
-        typename LruCacheSet::iterator mIterator;
-        bool mBeginReturned;
-    };
-};
-
-// Implementation is here, because it's fully templated
-template <typename TKey, typename TValue>
-LruCache<TKey, TValue>::LruCache(uint32_t maxCapacity)
-    : mSet(new LruCacheSet())
-    , mListener(NULL)
-    , mOldest(NULL)
-    , mYoungest(NULL)
-    , mMaxCapacity(maxCapacity)
-    , mNullValue(NULL) {
-    mSet->max_load_factor(1.0);
-};
-
-template <typename TKey, typename TValue>
-LruCache<TKey, TValue>::~LruCache() {
-    // Need to delete created entries.
-    clear();
-};
-
-template<typename K, typename V>
-void LruCache<K, V>::setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener) {
-    mListener = listener;
-}
-
-template <typename TKey, typename TValue>
-size_t LruCache<TKey, TValue>::size() const {
-    return mSet->size();
-}
-
-template <typename TKey, typename TValue>
-const TValue& LruCache<TKey, TValue>::get(const TKey& key) {
-    typename LruCacheSet::const_iterator find_result = findByKey(key);
-    if (find_result == mSet->end()) {
-        return mNullValue;
-    }
-    Entry *entry = *find_result;
-    detachFromCache(*entry);
-    attachToCache(*entry);
-    return entry->value;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::put(const TKey& key, const TValue& value) {
-    if (mMaxCapacity != kUnlimitedCapacity && size() >= mMaxCapacity) {
-        removeOldest();
-    }
-
-    if (findByKey(key) != mSet->end()) {
-        return false;
-    }
-
-    Entry* newEntry = new Entry(key, value);
-    mSet->insert(newEntry);
-    attachToCache(*newEntry);
-    return true;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::remove(const TKey& key) {
-    typename LruCacheSet::const_iterator find_result = findByKey(key);
-    if (find_result == mSet->end()) {
-        return false;
-    }
-    Entry* entry = *find_result;
-    mSet->erase(entry);
-    if (mListener) {
-        (*mListener)(entry->key, entry->value);
-    }
-    detachFromCache(*entry);
-    delete entry;
-    return true;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::removeOldest() {
-    if (mOldest != NULL) {
-        return remove(mOldest->key);
-        // TODO: should probably abort if false
-    }
-    return false;
-}
-
-template <typename TKey, typename TValue>
-const TValue& LruCache<TKey, TValue>::peekOldestValue() {
-    if (mOldest) {
-        return mOldest->value;
-    }
-    return mNullValue;
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::clear() {
-    if (mListener) {
-        for (Entry* p = mOldest; p != NULL; p = p->child) {
-            (*mListener)(p->key, p->value);
-        }
-    }
-    mYoungest = NULL;
-    mOldest = NULL;
-    for (auto entry : *mSet.get()) {
-        delete entry;
-    }
-    mSet->clear();
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::attachToCache(Entry& entry) {
-    if (mYoungest == NULL) {
-        mYoungest = mOldest = &entry;
-    } else {
-        entry.parent = mYoungest;
-        mYoungest->child = &entry;
-        mYoungest = &entry;
-    }
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::detachFromCache(Entry& entry) {
-    if (entry.parent != NULL) {
-        entry.parent->child = entry.child;
-    } else {
-        mOldest = entry.child;
-    }
-    if (entry.child != NULL) {
-        entry.child->parent = entry.parent;
-    } else {
-        mYoungest = entry.parent;
-    }
-
-    entry.parent = NULL;
-    entry.child = NULL;
-}
-
-}
-#endif // ANDROID_UTILS_LRU_CACHE_H
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
deleted file mode 100644
index 848a600..0000000
--- a/include/utils/Mutex.h
+++ /dev/null
@@ -1,167 +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.
- */
-
-#ifndef _LIBS_UTILS_MUTEX_H
-#define _LIBS_UTILS_MUTEX_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if !defined(_WIN32)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-#include <utils/Timers.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Condition;
-
-/*
- * NOTE: This class is for code that builds on Win32.  Its usage is
- * deprecated for code which doesn't build for Win32.  New code which
- * doesn't build for Win32 should use std::mutex and std::lock_guard instead.
- *
- * Simple mutex class.  The implementation is system-dependent.
- *
- * The mutex must be unlocked by the thread that locked it.  They are not
- * recursive, i.e. the same thread can't lock it multiple times.
- */
-class Mutex {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-
-                Mutex();
-                Mutex(const char* name);
-                Mutex(int type, const char* name = NULL);
-                ~Mutex();
-
-    // lock or unlock the mutex
-    status_t    lock();
-    void        unlock();
-
-    // lock if possible; returns 0 on success, error otherwise
-    status_t    tryLock();
-
-#if defined(__ANDROID__)
-    // Lock the mutex, but don't wait longer than timeoutNs (relative time).
-    // Returns 0 on success, TIMED_OUT for failure due to timeout expiration.
-    //
-    // OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep
-    // capabilities consistent across host OSes, this method is only available
-    // when building Android binaries.
-    //
-    // FIXME?: pthread_mutex_timedlock is based on CLOCK_REALTIME,
-    // which is subject to NTP adjustments, and includes time during suspend,
-    // so a timeout may occur even though no processes could run.
-    // Not holding a partial wakelock may lead to a system suspend.
-    status_t    timedLock(nsecs_t timeoutNs);
-#endif
-
-    // Manages the mutex automatically. It'll be locked when Autolock is
-    // constructed and released when Autolock goes out of scope.
-    class Autolock {
-    public:
-        inline Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }
-        inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }
-        inline ~Autolock() { mLock.unlock(); }
-    private:
-        Mutex& mLock;
-    };
-
-private:
-    friend class Condition;
-
-    // A mutex cannot be copied
-                Mutex(const Mutex&);
-    Mutex&      operator = (const Mutex&);
-
-#if !defined(_WIN32)
-    pthread_mutex_t mMutex;
-#else
-    void    _init();
-    void*   mState;
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-#if !defined(_WIN32)
-
-inline Mutex::Mutex() {
-    pthread_mutex_init(&mMutex, NULL);
-}
-inline Mutex::Mutex(__attribute__((unused)) const char* name) {
-    pthread_mutex_init(&mMutex, NULL);
-}
-inline Mutex::Mutex(int type, __attribute__((unused)) const char* name) {
-    if (type == SHARED) {
-        pthread_mutexattr_t attr;
-        pthread_mutexattr_init(&attr);
-        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_mutex_init(&mMutex, &attr);
-        pthread_mutexattr_destroy(&attr);
-    } else {
-        pthread_mutex_init(&mMutex, NULL);
-    }
-}
-inline Mutex::~Mutex() {
-    pthread_mutex_destroy(&mMutex);
-}
-inline status_t Mutex::lock() {
-    return -pthread_mutex_lock(&mMutex);
-}
-inline void Mutex::unlock() {
-    pthread_mutex_unlock(&mMutex);
-}
-inline status_t Mutex::tryLock() {
-    return -pthread_mutex_trylock(&mMutex);
-}
-#if defined(__ANDROID__)
-inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
-    timeoutNs += systemTime(SYSTEM_TIME_REALTIME);
-    const struct timespec ts = {
-        /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
-        /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
-    };
-    return -pthread_mutex_timedlock(&mMutex, &ts);
-}
-#endif
-
-#endif // !defined(_WIN32)
-
-// ---------------------------------------------------------------------------
-
-/*
- * Automatic mutex.  Declare one of these at the top of a function.
- * When the function returns, it will go out of scope, and release the
- * mutex.
- */
-
-typedef Mutex::Autolock AutoMutex;
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_MUTEX_H
diff --git a/include/utils/NativeHandle.h b/include/utils/NativeHandle.h
deleted file mode 100644
index b825168..0000000
--- a/include/utils/NativeHandle.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_NATIVE_HANDLE_H
-#define ANDROID_NATIVE_HANDLE_H
-
-#include <utils/RefBase.h>
-#include <utils/StrongPointer.h>
-
-typedef struct native_handle native_handle_t;
-
-namespace android {
-
-class NativeHandle: public LightRefBase<NativeHandle> {
-public:
-    // Create a refcounted wrapper around a native_handle_t, and declare
-    // whether the wrapper owns the handle (so that it should clean up the
-    // handle upon destruction) or not.
-    // If handle is NULL, no NativeHandle will be created.
-    static sp<NativeHandle> create(native_handle_t* handle, bool ownsHandle);
-
-    const native_handle_t* handle() const {
-        return mHandle;
-    }
-
-private:
-    // for access to the destructor
-    friend class LightRefBase<NativeHandle>;
-
-    NativeHandle(native_handle_t* handle, bool ownsHandle);
-    virtual ~NativeHandle();
-
-    native_handle_t* mHandle;
-    bool mOwnsHandle;
-
-    // non-copyable
-    NativeHandle(const NativeHandle&);
-    NativeHandle& operator=(const NativeHandle&);
-};
-
-} // namespace android
-
-#endif // ANDROID_NATIVE_HANDLE_H
diff --git a/include/utils/RWLock.h b/include/utils/RWLock.h
deleted file mode 100644
index e743b1c..0000000
--- a/include/utils/RWLock.h
+++ /dev/null
@@ -1,126 +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.
- */
-
-#ifndef _LIBS_UTILS_RWLOCK_H
-#define _LIBS_UTILS_RWLOCK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#if !defined(_WIN32)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-#include <utils/ThreadDefs.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-#if !defined(_WIN32)
-
-/*
- * Simple mutex class.  The implementation is system-dependent.
- *
- * The mutex must be unlocked by the thread that locked it.  They are not
- * recursive, i.e. the same thread can't lock it multiple times.
- */
-class RWLock {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-
-                RWLock();
-                RWLock(const char* name);
-                RWLock(int type, const char* name = NULL);
-                ~RWLock();
-
-    status_t    readLock();
-    status_t    tryReadLock();
-    status_t    writeLock();
-    status_t    tryWriteLock();
-    void        unlock();
-
-    class AutoRLock {
-    public:
-        inline AutoRLock(RWLock& rwlock) : mLock(rwlock)  { mLock.readLock(); }
-        inline ~AutoRLock() { mLock.unlock(); }
-    private:
-        RWLock& mLock;
-    };
-
-    class AutoWLock {
-    public:
-        inline AutoWLock(RWLock& rwlock) : mLock(rwlock)  { mLock.writeLock(); }
-        inline ~AutoWLock() { mLock.unlock(); }
-    private:
-        RWLock& mLock;
-    };
-
-private:
-    // A RWLock cannot be copied
-                RWLock(const RWLock&);
-   RWLock&      operator = (const RWLock&);
-
-   pthread_rwlock_t mRWLock;
-};
-
-inline RWLock::RWLock() {
-    pthread_rwlock_init(&mRWLock, NULL);
-}
-inline RWLock::RWLock(__attribute__((unused)) const char* name) {
-    pthread_rwlock_init(&mRWLock, NULL);
-}
-inline RWLock::RWLock(int type, __attribute__((unused)) const char* name) {
-    if (type == SHARED) {
-        pthread_rwlockattr_t attr;
-        pthread_rwlockattr_init(&attr);
-        pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_rwlock_init(&mRWLock, &attr);
-        pthread_rwlockattr_destroy(&attr);
-    } else {
-        pthread_rwlock_init(&mRWLock, NULL);
-    }
-}
-inline RWLock::~RWLock() {
-    pthread_rwlock_destroy(&mRWLock);
-}
-inline status_t RWLock::readLock() {
-    return -pthread_rwlock_rdlock(&mRWLock);
-}
-inline status_t RWLock::tryReadLock() {
-    return -pthread_rwlock_tryrdlock(&mRWLock);
-}
-inline status_t RWLock::writeLock() {
-    return -pthread_rwlock_wrlock(&mRWLock);
-}
-inline status_t RWLock::tryWriteLock() {
-    return -pthread_rwlock_trywrlock(&mRWLock);
-}
-inline void RWLock::unlock() {
-    pthread_rwlock_unlock(&mRWLock);
-}
-
-#endif // !defined(_WIN32)
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_RWLOCK_H
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
deleted file mode 100644
index 14d9cb1..0000000
--- a/include/utils/RefBase.h
+++ /dev/null
@@ -1,556 +0,0 @@
-/*
- * Copyright (C) 2005 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_REF_BASE_H
-#define ANDROID_REF_BASE_H
-
-#include <atomic>
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <utils/StrongPointer.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-
-class TextOutput;
-TextOutput& printWeakPointer(TextOutput& to, const void* val);
-
-// ---------------------------------------------------------------------------
-
-#define COMPARE_WEAK(_op_)                                      \
-inline bool operator _op_ (const sp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-inline bool operator _op_ (const T* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const sp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const U* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}
-
-// ---------------------------------------------------------------------------
-
-class ReferenceRenamer {
-protected:
-    // destructor is purposedly not virtual so we avoid code overhead from
-    // subclasses; we have to make it protected to guarantee that it
-    // cannot be called from this base class (and to make strict compilers
-    // happy).
-    ~ReferenceRenamer() { }
-public:
-    virtual void operator()(size_t i) const = 0;
-};
-
-// ---------------------------------------------------------------------------
-
-class RefBase
-{
-public:
-            void            incStrong(const void* id) const;
-            void            decStrong(const void* id) const;
-    
-            void            forceIncStrong(const void* id) const;
-
-            //! DEBUGGING ONLY: Get current strong ref count.
-            int32_t         getStrongCount() const;
-
-    class weakref_type
-    {
-    public:
-        RefBase*            refBase() const;
-        
-        void                incWeak(const void* id);
-        void                decWeak(const void* id);
-        
-        // acquires a strong reference if there is already one.
-        bool                attemptIncStrong(const void* id);
-        
-        // acquires a weak reference if there is already one.
-        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
-        // for proper use.
-        bool                attemptIncWeak(const void* id);
-
-        //! DEBUGGING ONLY: Get current weak ref count.
-        int32_t             getWeakCount() const;
-
-        //! DEBUGGING ONLY: Print references held on object.
-        void                printRefs() const;
-
-        //! DEBUGGING ONLY: Enable tracking for this object.
-        // enable -- enable/disable tracking
-        // retain -- when tracking is enable, if true, then we save a stack trace
-        //           for each reference and dereference; when retain == false, we
-        //           match up references and dereferences and keep only the 
-        //           outstanding ones.
-        
-        void                trackMe(bool enable, bool retain);
-    };
-    
-            weakref_type*   createWeak(const void* id) const;
-            
-            weakref_type*   getWeakRefs() const;
-
-            //! DEBUGGING ONLY: Print references held on object.
-    inline  void            printRefs() const { getWeakRefs()->printRefs(); }
-
-            //! DEBUGGING ONLY: Enable tracking of object.
-    inline  void            trackMe(bool enable, bool retain)
-    { 
-        getWeakRefs()->trackMe(enable, retain); 
-    }
-
-    typedef RefBase basetype;
-
-protected:
-                            RefBase();
-    virtual                 ~RefBase();
-    
-    //! Flags for extendObjectLifetime()
-    enum {
-        OBJECT_LIFETIME_STRONG  = 0x0000,
-        OBJECT_LIFETIME_WEAK    = 0x0001,
-        OBJECT_LIFETIME_MASK    = 0x0001
-    };
-    
-            void            extendObjectLifetime(int32_t mode);
-            
-    //! Flags for onIncStrongAttempted()
-    enum {
-        FIRST_INC_STRONG = 0x0001
-    };
-    
-    virtual void            onFirstRef();
-    virtual void            onLastStrongRef(const void* id);
-    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
-    virtual void            onLastWeakRef(const void* id);
-
-private:
-    friend class weakref_type;
-    class weakref_impl;
-    
-                            RefBase(const RefBase& o);
-            RefBase&        operator=(const RefBase& o);
-
-private:
-    friend class ReferenceMover;
-
-    static void renameRefs(size_t n, const ReferenceRenamer& renamer);
-
-    static void renameRefId(weakref_type* ref,
-            const void* old_id, const void* new_id);
-
-    static void renameRefId(RefBase* ref,
-            const void* old_id, const void* new_id);
-
-        weakref_impl* const mRefs;
-};
-
-// ---------------------------------------------------------------------------
-
-template <class T>
-class LightRefBase
-{
-public:
-    inline LightRefBase() : mCount(0) { }
-    inline void incStrong(__attribute__((unused)) const void* id) const {
-        mCount.fetch_add(1, std::memory_order_relaxed);
-    }
-    inline void decStrong(__attribute__((unused)) const void* id) const {
-        if (mCount.fetch_sub(1, std::memory_order_release) == 1) {
-            std::atomic_thread_fence(std::memory_order_acquire);
-            delete static_cast<const T*>(this);
-        }
-    }
-    //! DEBUGGING ONLY: Get current strong ref count.
-    inline int32_t getStrongCount() const {
-        return mCount.load(std::memory_order_relaxed);
-    }
-
-    typedef LightRefBase<T> basetype;
-
-protected:
-    inline ~LightRefBase() { }
-
-private:
-    friend class ReferenceMover;
-    inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { }
-    inline static void renameRefId(T* ref,
-            const void* old_id, const void* new_id) { }
-
-private:
-    mutable std::atomic<int32_t> mCount;
-};
-
-// This is a wrapper around LightRefBase that simply enforces a virtual
-// destructor to eliminate the template requirement of LightRefBase
-class VirtualLightRefBase : public LightRefBase<VirtualLightRefBase> {
-public:
-    virtual ~VirtualLightRefBase() {}
-};
-
-// ---------------------------------------------------------------------------
-
-template <typename T>
-class wp
-{
-public:
-    typedef typename RefBase::weakref_type weakref_type;
-    
-    inline wp() : m_ptr(0) { }
-
-    wp(T* other);
-    wp(const wp<T>& other);
-    wp(const sp<T>& other);
-    template<typename U> wp(U* other);
-    template<typename U> wp(const sp<U>& other);
-    template<typename U> wp(const wp<U>& other);
-
-    ~wp();
-    
-    // Assignment
-
-    wp& operator = (T* other);
-    wp& operator = (const wp<T>& other);
-    wp& operator = (const sp<T>& other);
-    
-    template<typename U> wp& operator = (U* other);
-    template<typename U> wp& operator = (const wp<U>& other);
-    template<typename U> wp& operator = (const sp<U>& other);
-    
-    void set_object_and_refs(T* other, weakref_type* refs);
-
-    // promotion to sp
-    
-    sp<T> promote() const;
-
-    // Reset
-    
-    void clear();
-
-    // Accessors
-    
-    inline  weakref_type* get_refs() const { return m_refs; }
-    
-    inline  T* unsafe_get() const { return m_ptr; }
-
-    // Operators
-
-    COMPARE_WEAK(==)
-    COMPARE_WEAK(!=)
-    COMPARE_WEAK(>)
-    COMPARE_WEAK(<)
-    COMPARE_WEAK(<=)
-    COMPARE_WEAK(>=)
-
-    inline bool operator == (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
-    }
-    template<typename U>
-    inline bool operator == (const wp<U>& o) const {
-        return m_ptr == o.m_ptr;
-    }
-
-    inline bool operator > (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
-    }
-    template<typename U>
-    inline bool operator > (const wp<U>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
-    }
-
-    inline bool operator < (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
-    }
-    template<typename U>
-    inline bool operator < (const wp<U>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
-    }
-                         inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
-    template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
-                         inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
-    template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
-                         inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
-    template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
-
-private:
-    template<typename Y> friend class sp;
-    template<typename Y> friend class wp;
-
-    T*              m_ptr;
-    weakref_type*   m_refs;
-};
-
-template <typename T>
-TextOutput& operator<<(TextOutput& to, const wp<T>& val);
-
-#undef COMPARE_WEAK
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts below here.
-
-template<typename T>
-wp<T>::wp(T* other)
-    : m_ptr(other)
-{
-    if (other) m_refs = other->createWeak(this);
-}
-
-template<typename T>
-wp<T>::wp(const wp<T>& other)
-    : m_ptr(other.m_ptr), m_refs(other.m_refs)
-{
-    if (m_ptr) m_refs->incWeak(this);
-}
-
-template<typename T>
-wp<T>::wp(const sp<T>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = m_ptr->createWeak(this);
-    }
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(U* other)
-    : m_ptr(other)
-{
-    if (other) m_refs = other->createWeak(this);
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(const wp<U>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = other.m_refs;
-        m_refs->incWeak(this);
-    }
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(const sp<U>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = m_ptr->createWeak(this);
-    }
-}
-
-template<typename T>
-wp<T>::~wp()
-{
-    if (m_ptr) m_refs->decWeak(this);
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (T* other)
-{
-    weakref_type* newRefs =
-        other ? other->createWeak(this) : 0;
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (const wp<T>& other)
-{
-    weakref_type* otherRefs(other.m_refs);
-    T* otherPtr(other.m_ptr);
-    if (otherPtr) otherRefs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = otherRefs;
-    return *this;
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (const sp<T>& other)
-{
-    weakref_type* newRefs =
-        other != NULL ? other->createWeak(this) : 0;
-    T* otherPtr(other.m_ptr);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (U* other)
-{
-    weakref_type* newRefs =
-        other ? other->createWeak(this) : 0;
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (const wp<U>& other)
-{
-    weakref_type* otherRefs(other.m_refs);
-    U* otherPtr(other.m_ptr);
-    if (otherPtr) otherRefs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = otherRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (const sp<U>& other)
-{
-    weakref_type* newRefs =
-        other != NULL ? other->createWeak(this) : 0;
-    U* otherPtr(other.m_ptr);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T>
-void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
-{
-    if (other) refs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = refs;
-}
-
-template<typename T>
-sp<T> wp<T>::promote() const
-{
-    sp<T> result;
-    if (m_ptr && m_refs->attemptIncStrong(&result)) {
-        result.set_pointer(m_ptr);
-    }
-    return result;
-}
-
-template<typename T>
-void wp<T>::clear()
-{
-    if (m_ptr) {
-        m_refs->decWeak(this);
-        m_ptr = 0;
-    }
-}
-
-template <typename T>
-inline TextOutput& operator<<(TextOutput& to, const wp<T>& val)
-{
-    return printWeakPointer(to, val.unsafe_get());
-}
-
-// ---------------------------------------------------------------------------
-
-// this class just serves as a namespace so TYPE::moveReferences can stay
-// private.
-class ReferenceMover {
-public:
-    // it would be nice if we could make sure no extra code is generated
-    // for sp<TYPE> or wp<TYPE> when TYPE is a descendant of RefBase:
-    // Using a sp<RefBase> override doesn't work; it's a bit like we wanted
-    // a template<typename TYPE inherits RefBase> template...
-
-    template<typename TYPE> static inline
-    void move_references(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-
-        class Renamer : public ReferenceRenamer {
-            sp<TYPE>* d;
-            sp<TYPE> const* s;
-            virtual void operator()(size_t i) const {
-                // The id are known to be the sp<>'s this pointer
-                TYPE::renameRefId(d[i].get(), &s[i], &d[i]);
-            }
-        public:
-            Renamer(sp<TYPE>* d, sp<TYPE> const* s) : d(d), s(s) { }
-            virtual ~Renamer() { }
-        };
-
-        memmove(d, s, n*sizeof(sp<TYPE>));
-        TYPE::renameRefs(n, Renamer(d, s));
-    }
-
-
-    template<typename TYPE> static inline
-    void move_references(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-
-        class Renamer : public ReferenceRenamer {
-            wp<TYPE>* d;
-            wp<TYPE> const* s;
-            virtual void operator()(size_t i) const {
-                // The id are known to be the wp<>'s this pointer
-                TYPE::renameRefId(d[i].get_refs(), &s[i], &d[i]);
-            }
-        public:
-            Renamer(wp<TYPE>* d, wp<TYPE> const* s) : d(d), s(s) { }
-            virtual ~Renamer() { }
-        };
-
-        memmove(d, s, n*sizeof(wp<TYPE>));
-        TYPE::renameRefs(n, Renamer(d, s));
-    }
-};
-
-// specialization for moving sp<> and wp<> types.
-// these are used by the [Sorted|Keyed]Vector<> implementations
-// sp<> and wp<> need to be handled specially, because they do not
-// have trivial copy operation in the general case (see RefBase.cpp
-// when DEBUG ops are enabled), but can be implemented very
-// efficiently in most cases.
-
-template<typename TYPE> inline
-void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_REF_BASE_H
diff --git a/include/utils/Singleton.h b/include/utils/Singleton.h
deleted file mode 100644
index ffc03cb..0000000
--- a/include/utils/Singleton.h
+++ /dev/null
@@ -1,78 +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.
- */
-
-#ifndef ANDROID_UTILS_SINGLETON_H
-#define ANDROID_UTILS_SINGLETON_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/threads.h>
-#include <cutils/compiler.h>
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-template <typename TYPE>
-class ANDROID_API Singleton
-{
-public:
-    static TYPE& getInstance() {
-        Mutex::Autolock _l(sLock);
-        TYPE* instance = sInstance;
-        if (instance == 0) {
-            instance = new TYPE();
-            sInstance = instance;
-        }
-        return *instance;
-    }
-
-    static bool hasInstance() {
-        Mutex::Autolock _l(sLock);
-        return sInstance != 0;
-    }
-    
-protected:
-    ~Singleton() { };
-    Singleton() { };
-
-private:
-    Singleton(const Singleton&);
-    Singleton& operator = (const Singleton&);
-    static Mutex sLock;
-    static TYPE* sInstance;
-};
-
-/*
- * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file
- * (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes,
- * and avoid to have a copy of them in each compilation units Singleton<TYPE>
- * is used.
- * NOTE: we use a version of Mutex ctor that takes a parameter, because
- * for some unknown reason using the default ctor doesn't emit the variable!
- */
-
-#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE)                 \
-    template<> ::android::Mutex  \
-        (::android::Singleton< TYPE >::sLock)(::android::Mutex::PRIVATE);  \
-    template<> TYPE* ::android::Singleton< TYPE >::sInstance(0);  \
-    template class ::android::Singleton< TYPE >;
-
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_UTILS_SINGLETON_H
-
diff --git a/include/utils/SortedVector.h b/include/utils/SortedVector.h
deleted file mode 100644
index 2d3e82a..0000000
--- a/include/utils/SortedVector.h
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2005 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_SORTED_VECTOR_H
-#define ANDROID_SORTED_VECTOR_H
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/log.h>
-
-#include <utils/Vector.h>
-#include <utils/VectorImpl.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-template <class TYPE>
-class SortedVector : private SortedVectorImpl
-{
-    friend class Vector<TYPE>;
-
-public:
-            typedef TYPE    value_type;
-    
-    /*! 
-     * Constructors and destructors
-     */
-    
-                            SortedVector();
-                            SortedVector(const SortedVector<TYPE>& rhs);
-    virtual                 ~SortedVector();
-
-    /*! copy operator */
-    const SortedVector<TYPE>&   operator = (const SortedVector<TYPE>& rhs) const;    
-    SortedVector<TYPE>&         operator = (const SortedVector<TYPE>& rhs);    
-
-    /*
-     * empty the vector
-     */
-
-    inline  void            clear()             { VectorImpl::clear(); }
-
-    /*! 
-     * vector stats
-     */
-
-    //! returns number of items in the vector
-    inline  size_t          size() const                { return VectorImpl::size(); }
-    //! returns whether or not the vector is empty
-    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
-    //! returns how many items can be stored without reallocating the backing store
-    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
-    //! sets the capacity. capacity can never be reduced less than size()
-    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
-
-    /*! 
-     * C-style array access
-     */
-     
-    //! read-only C-style access 
-    inline  const TYPE*     array() const;
-
-    //! read-write C-style access. BE VERY CAREFUL when modifying the array
-    //! you must keep it sorted! You usually don't use this function.
-            TYPE*           editArray();
-
-            //! finds the index of an item
-            ssize_t         indexOf(const TYPE& item) const;
-            
-            //! finds where this item should be inserted
-            size_t          orderOf(const TYPE& item) const;
-            
-    
-    /*! 
-     * accessors
-     */
-
-    //! read-only access to an item at a given index
-    inline  const TYPE&     operator [] (size_t index) const;
-    //! alternate name for operator []
-    inline  const TYPE&     itemAt(size_t index) const;
-    //! stack-usage of the vector. returns the top of the stack (last element)
-            const TYPE&     top() const;
-
-    /*!
-     * modifying the array
-     */
-
-            //! add an item in the right place (and replace the one that is there)
-            ssize_t         add(const TYPE& item);
-            
-            //! editItemAt() MUST NOT change the order of this item
-            TYPE&           editItemAt(size_t index) {
-                return *( static_cast<TYPE *>(VectorImpl::editItemLocation(index)) );
-            }
-
-            //! merges a vector into this one
-            ssize_t         merge(const Vector<TYPE>& vector);
-            ssize_t         merge(const SortedVector<TYPE>& vector);
-            
-            //! removes an item
-            ssize_t         remove(const TYPE&);
-
-    //! remove several items
-    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
-    //! remove one item
-    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
-            
-protected:
-    virtual void    do_construct(void* storage, size_t num) const;
-    virtual void    do_destroy(void* storage, size_t num) const;
-    virtual void    do_copy(void* dest, const void* from, size_t num) const;
-    virtual void    do_splat(void* dest, const void* item, size_t num) const;
-    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
-    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
-    virtual int     do_compare(const void* lhs, const void* rhs) const;
-};
-
-// SortedVector<T> can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-template<typename T> struct trait_trivial_move<SortedVector<T> > { enum { value = true }; };
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts from here...
-// ---------------------------------------------------------------------------
-
-template<class TYPE> inline
-SortedVector<TYPE>::SortedVector()
-    : SortedVectorImpl(sizeof(TYPE),
-                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
-                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
-                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
-                )
-{
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>::SortedVector(const SortedVector<TYPE>& rhs)
-    : SortedVectorImpl(rhs) {
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>::~SortedVector() {
-    finish_vector();
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
-    SortedVectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
-    SortedVectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const TYPE* SortedVector<TYPE>::array() const {
-    return static_cast<const TYPE *>(arrayImpl());
-}
-
-template<class TYPE> inline
-TYPE* SortedVector<TYPE>::editArray() {
-    return static_cast<TYPE *>(editArrayImpl());
-}
-
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::operator[](size_t index) const {
-    LOG_FATAL_IF(index>=size(),
-            "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__,
-            int(index), int(size()));
-    return *(array() + index);
-}
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::itemAt(size_t index) const {
-    return operator[](index);
-}
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::top() const {
-    return *(array() + size() - 1);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::add(const TYPE& item) {
-    return SortedVectorImpl::add(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::indexOf(const TYPE& item) const {
-    return SortedVectorImpl::indexOf(&item);
-}
-
-template<class TYPE> inline
-size_t SortedVector<TYPE>::orderOf(const TYPE& item) const {
-    return SortedVectorImpl::orderOf(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::merge(const Vector<TYPE>& vector) {
-    return SortedVectorImpl::merge(reinterpret_cast<const VectorImpl&>(vector));
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::merge(const SortedVector<TYPE>& vector) {
-    return SortedVectorImpl::merge(reinterpret_cast<const SortedVectorImpl&>(vector));
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::remove(const TYPE& item) {
-    return SortedVectorImpl::remove(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::removeItemsAt(size_t index, size_t count) {
-    return VectorImpl::removeItemsAt(index, count);
-}
-
-// ---------------------------------------------------------------------------
-
-template<class TYPE>
-void SortedVector<TYPE>::do_construct(void* storage, size_t num) const {
-    construct_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_destroy(void* storage, size_t num) const {
-    destroy_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
-    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
-    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
-    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
-    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-int SortedVector<TYPE>::do_compare(const void* lhs, const void* rhs) const {
-    return compare_type( *reinterpret_cast<const TYPE*>(lhs), *reinterpret_cast<const TYPE*>(rhs) );
-}
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_SORTED_VECTOR_H
diff --git a/include/utils/String16.h b/include/utils/String16.h
deleted file mode 100644
index 9bb6f0d..0000000
--- a/include/utils/String16.h
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRING16_H
-#define ANDROID_STRING16_H
-
-#include <utils/Errors.h>
-#include <utils/Unicode.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-
-extern "C" {
-
-}
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-class SharedBuffer;
-class String8;
-class TextOutput;
-
-//! This is a string holding UTF-16 characters.
-class String16
-{
-public:
-    /* use String16(StaticLinkage) if you're statically linking against
-     * libutils and declaring an empty static String16, e.g.:
-     *
-     *   static String16 sAStaticEmptyString(String16::kEmptyString);
-     *   static String16 sAnotherStaticEmptyString(sAStaticEmptyString);
-     */
-    enum StaticLinkage { kEmptyString };
-
-                                String16();
-    explicit                    String16(StaticLinkage);
-                                String16(const String16& o);
-                                String16(const String16& o,
-                                         size_t len,
-                                         size_t begin=0);
-    explicit                    String16(const char16_t* o);
-    explicit                    String16(const char16_t* o, size_t len);
-    explicit                    String16(const String8& o);
-    explicit                    String16(const char* o);
-    explicit                    String16(const char* o, size_t len);
-
-                                ~String16();
-    
-    inline  const char16_t*     string() const;
-    
-            size_t              size() const;
-            void                setTo(const String16& other);
-            status_t            setTo(const char16_t* other);
-            status_t            setTo(const char16_t* other, size_t len);
-            status_t            setTo(const String16& other,
-                                      size_t len,
-                                      size_t begin=0);
-    
-            status_t            append(const String16& other);
-            status_t            append(const char16_t* other, size_t len);
-            
-    inline  String16&           operator=(const String16& other);
-    
-    inline  String16&           operator+=(const String16& other);
-    inline  String16            operator+(const String16& other) const;
-
-            status_t            insert(size_t pos, const char16_t* chrs);
-            status_t            insert(size_t pos,
-                                       const char16_t* chrs, size_t len);
-
-            ssize_t             findFirst(char16_t c) const;
-            ssize_t             findLast(char16_t c) const;
-
-            bool                startsWith(const String16& prefix) const;
-            bool                startsWith(const char16_t* prefix) const;
-
-            bool                contains(const char16_t* chrs) const;
-
-            status_t            makeLower();
-
-            status_t            replaceAll(char16_t replaceThis,
-                                           char16_t withThis);
-
-            status_t            remove(size_t len, size_t begin=0);
-
-    inline  int                 compare(const String16& other) const;
-
-    inline  bool                operator<(const String16& other) const;
-    inline  bool                operator<=(const String16& other) const;
-    inline  bool                operator==(const String16& other) const;
-    inline  bool                operator!=(const String16& other) const;
-    inline  bool                operator>=(const String16& other) const;
-    inline  bool                operator>(const String16& other) const;
-    
-    inline  bool                operator<(const char16_t* other) const;
-    inline  bool                operator<=(const char16_t* other) const;
-    inline  bool                operator==(const char16_t* other) const;
-    inline  bool                operator!=(const char16_t* other) const;
-    inline  bool                operator>=(const char16_t* other) const;
-    inline  bool                operator>(const char16_t* other) const;
-    
-    inline                      operator const char16_t*() const;
-    
-private:
-            const char16_t*     mString;
-};
-
-// String16 can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-ANDROID_TRIVIAL_MOVE_TRAIT(String16)
-
-// ---------------------------------------------------------------------------
-// No user servicable parts below.
-
-inline int compare_type(const String16& lhs, const String16& rhs)
-{
-    return lhs.compare(rhs);
-}
-
-inline int strictly_order_type(const String16& lhs, const String16& rhs)
-{
-    return compare_type(lhs, rhs) < 0;
-}
-
-inline const char16_t* String16::string() const
-{
-    return mString;
-}
-
-inline String16& String16::operator=(const String16& other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String16& String16::operator+=(const String16& other)
-{
-    append(other);
-    return *this;
-}
-
-inline String16 String16::operator+(const String16& other) const
-{
-    String16 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline int String16::compare(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size());
-}
-
-inline bool String16::operator<(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) < 0;
-}
-
-inline bool String16::operator<=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) <= 0;
-}
-
-inline bool String16::operator==(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) == 0;
-}
-
-inline bool String16::operator!=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) != 0;
-}
-
-inline bool String16::operator>=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) >= 0;
-}
-
-inline bool String16::operator>(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) > 0;
-}
-
-inline bool String16::operator<(const char16_t* other) const
-{
-    return strcmp16(mString, other) < 0;
-}
-
-inline bool String16::operator<=(const char16_t* other) const
-{
-    return strcmp16(mString, other) <= 0;
-}
-
-inline bool String16::operator==(const char16_t* other) const
-{
-    return strcmp16(mString, other) == 0;
-}
-
-inline bool String16::operator!=(const char16_t* other) const
-{
-    return strcmp16(mString, other) != 0;
-}
-
-inline bool String16::operator>=(const char16_t* other) const
-{
-    return strcmp16(mString, other) >= 0;
-}
-
-inline bool String16::operator>(const char16_t* other) const
-{
-    return strcmp16(mString, other) > 0;
-}
-
-inline String16::operator const char16_t*() const
-{
-    return mString;
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRING16_H
diff --git a/include/utils/String8.h b/include/utils/String8.h
deleted file mode 100644
index 2a75b98..0000000
--- a/include/utils/String8.h
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRING8_H
-#define ANDROID_STRING8_H
-
-#include <utils/Errors.h>
-#include <utils/Unicode.h>
-#include <utils/TypeHelpers.h>
-
-#include <string.h> // for strcmp
-#include <stdarg.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-class String16;
-class TextOutput;
-
-//! This is a string holding UTF-8 characters. Does not allow the value more
-// than 0x10FFFF, which is not valid unicode codepoint.
-class String8
-{
-public:
-    /* use String8(StaticLinkage) if you're statically linking against
-     * libutils and declaring an empty static String8, e.g.:
-     *
-     *   static String8 sAStaticEmptyString(String8::kEmptyString);
-     *   static String8 sAnotherStaticEmptyString(sAStaticEmptyString);
-     */
-    enum StaticLinkage { kEmptyString };
-
-                                String8();
-    explicit                    String8(StaticLinkage);
-                                String8(const String8& o);
-    explicit                    String8(const char* o);
-    explicit                    String8(const char* o, size_t numChars);
-    
-    explicit                    String8(const String16& o);
-    explicit                    String8(const char16_t* o);
-    explicit                    String8(const char16_t* o, size_t numChars);
-    explicit                    String8(const char32_t* o);
-    explicit                    String8(const char32_t* o, size_t numChars);
-                                ~String8();
-
-    static inline const String8 empty();
-
-    static String8              format(const char* fmt, ...) __attribute__((format (printf, 1, 2)));
-    static String8              formatV(const char* fmt, va_list args);
-
-    inline  const char*         string() const;
-    inline  size_t              size() const;
-    inline  size_t              bytes() const;
-    inline  bool                isEmpty() const;
-    
-            size_t              length() const;
-    
-            void                clear();
-
-            void                setTo(const String8& other);
-            status_t            setTo(const char* other);
-            status_t            setTo(const char* other, size_t numChars);
-            status_t            setTo(const char16_t* other, size_t numChars);
-            status_t            setTo(const char32_t* other,
-                                      size_t length);
-
-            status_t            append(const String8& other);
-            status_t            append(const char* other);
-            status_t            append(const char* other, size_t numChars);
-
-            status_t            appendFormat(const char* fmt, ...)
-                    __attribute__((format (printf, 2, 3)));
-            status_t            appendFormatV(const char* fmt, va_list args);
-
-            // Note that this function takes O(N) time to calculate the value.
-            // No cache value is stored.
-            size_t              getUtf32Length() const;
-            int32_t             getUtf32At(size_t index,
-                                           size_t *next_index) const;
-            void                getUtf32(char32_t* dst) const;
-
-    inline  String8&            operator=(const String8& other);
-    inline  String8&            operator=(const char* other);
-    
-    inline  String8&            operator+=(const String8& other);
-    inline  String8             operator+(const String8& other) const;
-    
-    inline  String8&            operator+=(const char* other);
-    inline  String8             operator+(const char* other) const;
-
-    inline  int                 compare(const String8& other) const;
-
-    inline  bool                operator<(const String8& other) const;
-    inline  bool                operator<=(const String8& other) const;
-    inline  bool                operator==(const String8& other) const;
-    inline  bool                operator!=(const String8& other) const;
-    inline  bool                operator>=(const String8& other) const;
-    inline  bool                operator>(const String8& other) const;
-    
-    inline  bool                operator<(const char* other) const;
-    inline  bool                operator<=(const char* other) const;
-    inline  bool                operator==(const char* other) const;
-    inline  bool                operator!=(const char* other) const;
-    inline  bool                operator>=(const char* other) const;
-    inline  bool                operator>(const char* other) const;
-    
-    inline                      operator const char*() const;
-    
-            char*               lockBuffer(size_t size);
-            void                unlockBuffer();
-            status_t            unlockBuffer(size_t size);
-            
-            // return the index of the first byte of other in this at or after
-            // start, or -1 if not found
-            ssize_t             find(const char* other, size_t start = 0) const;
-
-            // return true if this string contains the specified substring
-    inline  bool                contains(const char* other) const;
-
-            // removes all occurrence of the specified substring
-            // returns true if any were found and removed
-            bool                removeAll(const char* other);
-
-            void                toLower();
-            void                toLower(size_t start, size_t numChars);
-            void                toUpper();
-            void                toUpper(size_t start, size_t numChars);
-
-
-    /*
-     * These methods operate on the string as if it were a path name.
-     */
-
-    /*
-     * Set the filename field to a specific value.
-     *
-     * Normalizes the filename, removing a trailing '/' if present.
-     */
-    void setPathName(const char* name);
-    void setPathName(const char* name, size_t numChars);
-
-    /*
-     * Get just the filename component.
-     *
-     * "/tmp/foo/bar.c" --> "bar.c"
-     */
-    String8 getPathLeaf(void) const;
-
-    /*
-     * Remove the last (file name) component, leaving just the directory
-     * name.
-     *
-     * "/tmp/foo/bar.c" --> "/tmp/foo"
-     * "/tmp" --> "" // ????? shouldn't this be "/" ???? XXX
-     * "bar.c" --> ""
-     */
-    String8 getPathDir(void) const;
-
-    /*
-     * Retrieve the front (root dir) component.  Optionally also return the
-     * remaining components.
-     *
-     * "/tmp/foo/bar.c" --> "tmp" (remain = "foo/bar.c")
-     * "/tmp" --> "tmp" (remain = "")
-     * "bar.c" --> "bar.c" (remain = "")
-     */
-    String8 walkPath(String8* outRemains = NULL) const;
-
-    /*
-     * Return the filename extension.  This is the last '.' and any number
-     * of characters that follow it.  The '.' is included in case we
-     * decide to expand our definition of what constitutes an extension.
-     *
-     * "/tmp/foo/bar.c" --> ".c"
-     * "/tmp" --> ""
-     * "/tmp/foo.bar/baz" --> ""
-     * "foo.jpeg" --> ".jpeg"
-     * "foo." --> ""
-     */
-    String8 getPathExtension(void) const;
-
-    /*
-     * Return the path without the extension.  Rules for what constitutes
-     * an extension are described in the comment for getPathExtension().
-     *
-     * "/tmp/foo/bar.c" --> "/tmp/foo/bar"
-     */
-    String8 getBasePath(void) const;
-
-    /*
-     * Add a component to the pathname.  We guarantee that there is
-     * exactly one path separator between the old path and the new.
-     * If there is no existing name, we just copy the new name in.
-     *
-     * If leaf is a fully qualified path (i.e. starts with '/', it
-     * replaces whatever was there before.
-     */
-    String8& appendPath(const char* leaf);
-    String8& appendPath(const String8& leaf)  { return appendPath(leaf.string()); }
-
-    /*
-     * Like appendPath(), but does not affect this string.  Returns a new one instead.
-     */
-    String8 appendPathCopy(const char* leaf) const
-                                             { String8 p(*this); p.appendPath(leaf); return p; }
-    String8 appendPathCopy(const String8& leaf) const { return appendPathCopy(leaf.string()); }
-
-    /*
-     * Converts all separators in this string to /, the default path separator.
-     *
-     * If the default OS separator is backslash, this converts all
-     * backslashes to slashes, in-place. Otherwise it does nothing.
-     * Returns self.
-     */
-    String8& convertToResPath();
-
-private:
-            status_t            real_append(const char* other, size_t numChars);
-            char*               find_extension(void) const;
-
-            const char* mString;
-};
-
-// String8 can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-ANDROID_TRIVIAL_MOVE_TRAIT(String8)
-
-// ---------------------------------------------------------------------------
-// No user servicable parts below.
-
-inline int compare_type(const String8& lhs, const String8& rhs)
-{
-    return lhs.compare(rhs);
-}
-
-inline int strictly_order_type(const String8& lhs, const String8& rhs)
-{
-    return compare_type(lhs, rhs) < 0;
-}
-
-inline const String8 String8::empty() {
-    return String8();
-}
-
-inline const char* String8::string() const
-{
-    return mString;
-}
-
-inline size_t String8::size() const
-{
-    return length();
-}
-
-inline bool String8::isEmpty() const
-{
-    return length() == 0;
-}
-
-inline size_t String8::bytes() const
-{
-    return length();
-}
-
-inline bool String8::contains(const char* other) const
-{
-    return find(other) >= 0;
-}
-
-inline String8& String8::operator=(const String8& other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String8& String8::operator=(const char* other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String8& String8::operator+=(const String8& other)
-{
-    append(other);
-    return *this;
-}
-
-inline String8 String8::operator+(const String8& other) const
-{
-    String8 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline String8& String8::operator+=(const char* other)
-{
-    append(other);
-    return *this;
-}
-
-inline String8 String8::operator+(const char* other) const
-{
-    String8 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline int String8::compare(const String8& other) const
-{
-    return strcmp(mString, other.mString);
-}
-
-inline bool String8::operator<(const String8& other) const
-{
-    return strcmp(mString, other.mString) < 0;
-}
-
-inline bool String8::operator<=(const String8& other) const
-{
-    return strcmp(mString, other.mString) <= 0;
-}
-
-inline bool String8::operator==(const String8& other) const
-{
-    return strcmp(mString, other.mString) == 0;
-}
-
-inline bool String8::operator!=(const String8& other) const
-{
-    return strcmp(mString, other.mString) != 0;
-}
-
-inline bool String8::operator>=(const String8& other) const
-{
-    return strcmp(mString, other.mString) >= 0;
-}
-
-inline bool String8::operator>(const String8& other) const
-{
-    return strcmp(mString, other.mString) > 0;
-}
-
-inline bool String8::operator<(const char* other) const
-{
-    return strcmp(mString, other) < 0;
-}
-
-inline bool String8::operator<=(const char* other) const
-{
-    return strcmp(mString, other) <= 0;
-}
-
-inline bool String8::operator==(const char* other) const
-{
-    return strcmp(mString, other) == 0;
-}
-
-inline bool String8::operator!=(const char* other) const
-{
-    return strcmp(mString, other) != 0;
-}
-
-inline bool String8::operator>=(const char* other) const
-{
-    return strcmp(mString, other) >= 0;
-}
-
-inline bool String8::operator>(const char* other) const
-{
-    return strcmp(mString, other) > 0;
-}
-
-inline String8::operator const char*() const
-{
-    return mString;
-}
-
-}  // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRING8_H
diff --git a/include/utils/StrongPointer.h b/include/utils/StrongPointer.h
deleted file mode 100644
index 50fde35..0000000
--- a/include/utils/StrongPointer.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRONG_POINTER_H
-#define ANDROID_STRONG_POINTER_H
-
-#include <cutils/atomic.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <stdlib.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-
-template<typename T> class wp;
-
-// ---------------------------------------------------------------------------
-
-#define COMPARE(_op_)                                           \
-inline bool operator _op_ (const sp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-inline bool operator _op_ (const T* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const sp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const U* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-inline bool operator _op_ (const wp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const wp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}
-
-// ---------------------------------------------------------------------------
-
-template<typename T>
-class sp {
-public:
-    inline sp() : m_ptr(0) { }
-
-    sp(T* other);
-    sp(const sp<T>& other);
-    sp(sp<T>&& other);
-    template<typename U> sp(U* other);
-    template<typename U> sp(const sp<U>& other);
-    template<typename U> sp(sp<U>&& other);
-
-    ~sp();
-
-    // Assignment
-
-    sp& operator = (T* other);
-    sp& operator = (const sp<T>& other);
-    sp& operator = (sp<T>&& other);
-
-    template<typename U> sp& operator = (const sp<U>& other);
-    template<typename U> sp& operator = (sp<U>&& other);
-    template<typename U> sp& operator = (U* other);
-
-    //! Special optimization for use by ProcessState (and nobody else).
-    void force_set(T* other);
-
-    // Reset
-
-    void clear();
-
-    // Accessors
-
-    inline  T&      operator* () const  { return *m_ptr; }
-    inline  T*      operator-> () const { return m_ptr;  }
-    inline  T*      get() const         { return m_ptr; }
-
-    // Operators
-
-    COMPARE(==)
-    COMPARE(!=)
-    COMPARE(>)
-    COMPARE(<)
-    COMPARE(<=)
-    COMPARE(>=)
-
-private:    
-    template<typename Y> friend class sp;
-    template<typename Y> friend class wp;
-    void set_pointer(T* ptr);
-    T* m_ptr;
-};
-
-#undef COMPARE
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts below here.
-
-template<typename T>
-sp<T>::sp(T* other)
-        : m_ptr(other) {
-    if (other)
-        other->incStrong(this);
-}
-
-template<typename T>
-sp<T>::sp(const sp<T>& other)
-        : m_ptr(other.m_ptr) {
-    if (m_ptr)
-        m_ptr->incStrong(this);
-}
-
-template<typename T>
-sp<T>::sp(sp<T>&& other)
-        : m_ptr(other.m_ptr) {
-    other.m_ptr = nullptr;
-}
-
-template<typename T> template<typename U>
-sp<T>::sp(U* other)
-        : m_ptr(other) {
-    if (other)
-        ((T*) other)->incStrong(this);
-}
-
-template<typename T> template<typename U>
-sp<T>::sp(const sp<U>& other)
-        : m_ptr(other.m_ptr) {
-    if (m_ptr)
-        m_ptr->incStrong(this);
-}
-
-template<typename T> template<typename U>
-sp<T>::sp(sp<U>&& other)
-        : m_ptr(other.m_ptr) {
-    other.m_ptr = nullptr;
-}
-
-template<typename T>
-sp<T>::~sp() {
-    if (m_ptr)
-        m_ptr->decStrong(this);
-}
-
-template<typename T>
-sp<T>& sp<T>::operator =(const sp<T>& other) {
-    T* otherPtr(other.m_ptr);
-    if (otherPtr)
-        otherPtr->incStrong(this);
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = otherPtr;
-    return *this;
-}
-
-template<typename T>
-sp<T>& sp<T>::operator =(sp<T>&& other) {
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = other.m_ptr;
-    other.m_ptr = nullptr;
-    return *this;
-}
-
-template<typename T>
-sp<T>& sp<T>::operator =(T* other) {
-    if (other)
-        other->incStrong(this);
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = other;
-    return *this;
-}
-
-template<typename T> template<typename U>
-sp<T>& sp<T>::operator =(const sp<U>& other) {
-    T* otherPtr(other.m_ptr);
-    if (otherPtr)
-        otherPtr->incStrong(this);
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = otherPtr;
-    return *this;
-}
-
-template<typename T> template<typename U>
-sp<T>& sp<T>::operator =(sp<U>&& other) {
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = other.m_ptr;
-    other.m_ptr = nullptr;
-    return *this;
-}
-
-template<typename T> template<typename U>
-sp<T>& sp<T>::operator =(U* other) {
-    if (other)
-        ((T*) other)->incStrong(this);
-    if (m_ptr)
-        m_ptr->decStrong(this);
-    m_ptr = other;
-    return *this;
-}
-
-template<typename T>
-void sp<T>::force_set(T* other) {
-    other->forceIncStrong(this);
-    m_ptr = other;
-}
-
-template<typename T>
-void sp<T>::clear() {
-    if (m_ptr) {
-        m_ptr->decStrong(this);
-        m_ptr = 0;
-    }
-}
-
-template<typename T>
-void sp<T>::set_pointer(T* ptr) {
-    m_ptr = ptr;
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRONG_POINTER_H
diff --git a/include/utils/Thread.h b/include/utils/Thread.h
deleted file mode 100644
index 3792db7..0000000
--- a/include/utils/Thread.h
+++ /dev/null
@@ -1,116 +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.
- */
-
-#ifndef _LIBS_UTILS_THREAD_H
-#define _LIBS_UTILS_THREAD_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if !defined(_WIN32)
-# include <pthread.h>
-#endif
-
-#include <utils/Condition.h>
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-#include <utils/ThreadDefs.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Thread : virtual public RefBase
-{
-public:
-    // Create a Thread object, but doesn't create or start the associated
-    // thread. See the run() method.
-                        Thread(bool canCallJava = true);
-    virtual             ~Thread();
-
-    // Start the thread in threadLoop() which needs to be implemented.
-    virtual status_t    run(    const char* name,
-                                int32_t priority = PRIORITY_DEFAULT,
-                                size_t stack = 0);
-    
-    // Ask this object's thread to exit. This function is asynchronous, when the
-    // function returns the thread might still be running. Of course, this
-    // function can be called from a different thread.
-    virtual void        requestExit();
-
-    // Good place to do one-time initializations
-    virtual status_t    readyToRun();
-    
-    // Call requestExit() and wait until this object's thread exits.
-    // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call
-    // this function from this object's thread. Will return WOULD_BLOCK in
-    // that case.
-            status_t    requestExitAndWait();
-
-    // Wait until this object's thread exits. Returns immediately if not yet running.
-    // Do not call from this object's thread; will return WOULD_BLOCK in that case.
-            status_t    join();
-
-    // Indicates whether this thread is running or not.
-            bool        isRunning() const;
-
-#if defined(__ANDROID__)
-    // Return the thread's kernel ID, same as the thread itself calling gettid(),
-    // or -1 if the thread is not running.
-            pid_t       getTid() const;
-#endif
-
-protected:
-    // exitPending() returns true if requestExit() has been called.
-            bool        exitPending() const;
-    
-private:
-    // Derived class must implement threadLoop(). The thread starts its life
-    // here. There are two ways of using the Thread object:
-    // 1) loop: if threadLoop() returns true, it will be called again if
-    //          requestExit() wasn't called.
-    // 2) once: if threadLoop() returns false, the thread will exit upon return.
-    virtual bool        threadLoop() = 0;
-
-private:
-    Thread& operator=(const Thread&);
-    static  int             _threadLoop(void* user);
-    const   bool            mCanCallJava;
-    // always hold mLock when reading or writing
-            thread_id_t     mThread;
-    mutable Mutex           mLock;
-            Condition       mThreadExitedCondition;
-            status_t        mStatus;
-    // note that all accesses of mExitPending and mRunning need to hold mLock
-    volatile bool           mExitPending;
-    volatile bool           mRunning;
-            sp<Thread>      mHoldSelf;
-#if defined(__ANDROID__)
-    // legacy for debugging, not used by getTid() as it is set by the child thread
-    // and so is not initialized until the child reaches that point
-            pid_t           mTid;
-#endif
-};
-
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-#endif // _LIBS_UTILS_THREAD_H
-// ---------------------------------------------------------------------------
diff --git a/include/utils/Trace.h b/include/utils/Trace.h
deleted file mode 100644
index 6ba68f6..0000000
--- a/include/utils/Trace.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_TRACE_H
-#define ANDROID_TRACE_H
-
-#if defined(__ANDROID__)
-
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/compiler.h>
-#include <utils/threads.h>
-#include <cutils/trace.h>
-
-// See <cutils/trace.h> for more ATRACE_* macros.
-
-// ATRACE_NAME traces the beginning and end of the current scope.  To trace
-// the correct start and end times this macro should be declared first in the
-// scope body.
-#define ATRACE_NAME(name) android::ScopedTrace ___tracer(ATRACE_TAG, name)
-// ATRACE_CALL is an ATRACE_NAME that uses the current function name.
-#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
-
-namespace android {
-
-class ScopedTrace {
-public:
-inline ScopedTrace(uint64_t tag, const char* name)
-    : mTag(tag) {
-    atrace_begin(mTag,name);
-}
-
-inline ~ScopedTrace() {
-    atrace_end(mTag);
-}
-
-private:
-    uint64_t mTag;
-};
-
-}; // namespace android
-
-#else // !__ANDROID__
-
-#define ATRACE_NAME(...)
-#define ATRACE_CALL()
-
-#endif // __ANDROID__
-
-#endif // ANDROID_TRACE_H
diff --git a/include/utils/TypeHelpers.h b/include/utils/TypeHelpers.h
deleted file mode 100644
index 61d618e..0000000
--- a/include/utils/TypeHelpers.h
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (C) 2005 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_TYPE_HELPERS_H
-#define ANDROID_TYPE_HELPERS_H
-
-#include <new>
-#include <stdint.h>
-#include <string.h>
-#include <sys/types.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-/*
- * Types traits
- */
-
-template <typename T> struct trait_trivial_ctor { enum { value = false }; };
-template <typename T> struct trait_trivial_dtor { enum { value = false }; };
-template <typename T> struct trait_trivial_copy { enum { value = false }; };
-template <typename T> struct trait_trivial_move { enum { value = false }; };
-template <typename T> struct trait_pointer      { enum { value = false }; };    
-template <typename T> struct trait_pointer<T*>  { enum { value = true }; };
-
-template <typename TYPE>
-struct traits {
-    enum {
-        // whether this type is a pointer
-        is_pointer          = trait_pointer<TYPE>::value,
-        // whether this type's constructor is a no-op
-        has_trivial_ctor    = is_pointer || trait_trivial_ctor<TYPE>::value,
-        // whether this type's destructor is a no-op
-        has_trivial_dtor    = is_pointer || trait_trivial_dtor<TYPE>::value,
-        // whether this type type can be copy-constructed with memcpy
-        has_trivial_copy    = is_pointer || trait_trivial_copy<TYPE>::value,
-        // whether this type can be moved with memmove
-        has_trivial_move    = is_pointer || trait_trivial_move<TYPE>::value
-    };
-};
-
-template <typename T, typename U>
-struct aggregate_traits {
-    enum {
-        is_pointer          = false,
-        has_trivial_ctor    = 
-            traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor,
-        has_trivial_dtor    = 
-            traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor,
-        has_trivial_copy    = 
-            traits<T>::has_trivial_copy && traits<U>::has_trivial_copy,
-        has_trivial_move    = 
-            traits<T>::has_trivial_move && traits<U>::has_trivial_move
-    };
-};
-
-#define ANDROID_TRIVIAL_CTOR_TRAIT( T ) \
-    template<> struct trait_trivial_ctor< T >   { enum { value = true }; };
-
-#define ANDROID_TRIVIAL_DTOR_TRAIT( T ) \
-    template<> struct trait_trivial_dtor< T >   { enum { value = true }; };
-
-#define ANDROID_TRIVIAL_COPY_TRAIT( T ) \
-    template<> struct trait_trivial_copy< T >   { enum { value = true }; };
-
-#define ANDROID_TRIVIAL_MOVE_TRAIT( T ) \
-    template<> struct trait_trivial_move< T >   { enum { value = true }; };
-
-#define ANDROID_BASIC_TYPES_TRAITS( T ) \
-    ANDROID_TRIVIAL_CTOR_TRAIT( T ) \
-    ANDROID_TRIVIAL_DTOR_TRAIT( T ) \
-    ANDROID_TRIVIAL_COPY_TRAIT( T ) \
-    ANDROID_TRIVIAL_MOVE_TRAIT( T )
-
-// ---------------------------------------------------------------------------
-
-/*
- * basic types traits
- */
-
-ANDROID_BASIC_TYPES_TRAITS( void )
-ANDROID_BASIC_TYPES_TRAITS( bool )
-ANDROID_BASIC_TYPES_TRAITS( char )
-ANDROID_BASIC_TYPES_TRAITS( unsigned char )
-ANDROID_BASIC_TYPES_TRAITS( short )
-ANDROID_BASIC_TYPES_TRAITS( unsigned short )
-ANDROID_BASIC_TYPES_TRAITS( int )
-ANDROID_BASIC_TYPES_TRAITS( unsigned int )
-ANDROID_BASIC_TYPES_TRAITS( long )
-ANDROID_BASIC_TYPES_TRAITS( unsigned long )
-ANDROID_BASIC_TYPES_TRAITS( long long )
-ANDROID_BASIC_TYPES_TRAITS( unsigned long long )
-ANDROID_BASIC_TYPES_TRAITS( float )
-ANDROID_BASIC_TYPES_TRAITS( double )
-
-// ---------------------------------------------------------------------------
-
-
-/*
- * compare and order types
- */
-
-template<typename TYPE> inline
-int strictly_order_type(const TYPE& lhs, const TYPE& rhs) {
-    return (lhs < rhs) ? 1 : 0;
-}
-
-template<typename TYPE> inline
-int compare_type(const TYPE& lhs, const TYPE& rhs) {
-    return strictly_order_type(rhs, lhs) - strictly_order_type(lhs, rhs);
-}
-
-/*
- * create, destroy, copy and move types...
- */
-
-template<typename TYPE> inline
-void construct_type(TYPE* p, size_t n) {
-    if (!traits<TYPE>::has_trivial_ctor) {
-        while (n > 0) {
-            n--;
-            new(p++) TYPE;
-        }
-    }
-}
-
-template<typename TYPE> inline
-void destroy_type(TYPE* p, size_t n) {
-    if (!traits<TYPE>::has_trivial_dtor) {
-        while (n > 0) {
-            n--;
-            p->~TYPE();
-            p++;
-        }
-    }
-}
-
-template<typename TYPE> inline
-void copy_type(TYPE* d, const TYPE* s, size_t n) {
-    if (!traits<TYPE>::has_trivial_copy) {
-        while (n > 0) {
-            n--;
-            new(d) TYPE(*s);
-            d++, s++;
-        }
-    } else {
-        memcpy(d,s,n*sizeof(TYPE));
-    }
-}
-
-template<typename TYPE> inline
-void splat_type(TYPE* where, const TYPE* what, size_t n) {
-    if (!traits<TYPE>::has_trivial_copy) {
-        while (n > 0) {
-            n--;
-            new(where) TYPE(*what);
-            where++;
-        }
-    } else {
-        while (n > 0) {
-            n--;
-            *where++ = *what;
-        }
-    }
-}
-
-template<typename TYPE> inline
-void move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) {
-    if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) 
-            || traits<TYPE>::has_trivial_move) 
-    {
-        memmove(d,s,n*sizeof(TYPE));
-    } else {
-        d += n;
-        s += n;
-        while (n > 0) {
-            n--;
-            --d, --s;
-            if (!traits<TYPE>::has_trivial_copy) {
-                new(d) TYPE(*s);
-            } else {
-                *d = *s;   
-            }
-            if (!traits<TYPE>::has_trivial_dtor) {
-                s->~TYPE();
-            }
-        }
-    }
-}
-
-template<typename TYPE> inline
-void move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) {
-    if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) 
-            || traits<TYPE>::has_trivial_move) 
-    {
-        memmove(d,s,n*sizeof(TYPE));
-    } else {
-        while (n > 0) {
-            n--;
-            if (!traits<TYPE>::has_trivial_copy) {
-                new(d) TYPE(*s);
-            } else {
-                *d = *s;   
-            }
-            if (!traits<TYPE>::has_trivial_dtor) {
-                s->~TYPE();
-            }
-            d++, s++;
-        }
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-/*
- * a key/value pair
- */
-
-template <typename KEY, typename VALUE>
-struct key_value_pair_t {
-    typedef KEY key_t;
-    typedef VALUE value_t;
-
-    KEY     key;
-    VALUE   value;
-    key_value_pair_t() { }
-    key_value_pair_t(const key_value_pair_t& o) : key(o.key), value(o.value) { }
-    key_value_pair_t(const KEY& k, const VALUE& v) : key(k), value(v)  { }
-    key_value_pair_t(const KEY& k) : key(k) { }
-    inline bool operator < (const key_value_pair_t& o) const {
-        return strictly_order_type(key, o.key);
-    }
-    inline const KEY& getKey() const {
-        return key;
-    }
-    inline const VALUE& getValue() const {
-        return value;
-    }
-};
-
-template <typename K, typename V>
-struct trait_trivial_ctor< key_value_pair_t<K, V> >
-{ enum { value = aggregate_traits<K,V>::has_trivial_ctor }; };
-template <typename K, typename V>
-struct trait_trivial_dtor< key_value_pair_t<K, V> >
-{ enum { value = aggregate_traits<K,V>::has_trivial_dtor }; };
-template <typename K, typename V>
-struct trait_trivial_copy< key_value_pair_t<K, V> >
-{ enum { value = aggregate_traits<K,V>::has_trivial_copy }; };
-template <typename K, typename V>
-struct trait_trivial_move< key_value_pair_t<K, V> >
-{ enum { value = aggregate_traits<K,V>::has_trivial_move }; };
-
-// ---------------------------------------------------------------------------
-
-/*
- * Hash codes.
- */
-typedef uint32_t hash_t;
-
-template <typename TKey>
-hash_t hash_type(const TKey& key);
-
-/* Built-in hash code specializations.
- * Assumes pointers are 32bit. */
-#define ANDROID_INT32_HASH(T) \
-        template <> inline hash_t hash_type(const T& value) { return hash_t(value); }
-#define ANDROID_INT64_HASH(T) \
-        template <> inline hash_t hash_type(const T& value) { \
-                return hash_t((value >> 32) ^ value); }
-#define ANDROID_REINTERPRET_HASH(T, R) \
-        template <> inline hash_t hash_type(const T& value) { \
-                return hash_type(*reinterpret_cast<const R*>(&value)); }
-
-ANDROID_INT32_HASH(bool)
-ANDROID_INT32_HASH(int8_t)
-ANDROID_INT32_HASH(uint8_t)
-ANDROID_INT32_HASH(int16_t)
-ANDROID_INT32_HASH(uint16_t)
-ANDROID_INT32_HASH(int32_t)
-ANDROID_INT32_HASH(uint32_t)
-ANDROID_INT64_HASH(int64_t)
-ANDROID_INT64_HASH(uint64_t)
-ANDROID_REINTERPRET_HASH(float, uint32_t)
-ANDROID_REINTERPRET_HASH(double, uint64_t)
-
-template <typename T> inline hash_t hash_type(T* const & value) {
-    return hash_type(uintptr_t(value));
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_TYPE_HELPERS_H
diff --git a/include/utils/Unicode.h b/include/utils/Unicode.h
deleted file mode 100644
index cddbab4..0000000
--- a/include/utils/Unicode.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2005 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_UNICODE_H
-#define ANDROID_UNICODE_H
-
-#include <sys/types.h>
-#include <stdint.h>
-
-extern "C" {
-
-// Standard string functions on char16_t strings.
-int strcmp16(const char16_t *, const char16_t *);
-int strncmp16(const char16_t *s1, const char16_t *s2, size_t n);
-size_t strlen16(const char16_t *);
-size_t strnlen16(const char16_t *, size_t);
-char16_t *strcpy16(char16_t *, const char16_t *);
-char16_t *strncpy16(char16_t *, const char16_t *, size_t);
-char16_t *strstr16(const char16_t*, const char16_t*);
-
-// Version of comparison that supports embedded nulls.
-// This is different than strncmp() because we don't stop
-// at a nul character and consider the strings to be different
-// if the lengths are different (thus we need to supply the
-// lengths of both strings).  This can also be used when
-// your string is not nul-terminated as it will have the
-// equivalent result as strcmp16 (unlike strncmp16).
-int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2);
-
-// Version of strzcmp16 for comparing strings in different endianness.
-int strzcmp16_h_n(const char16_t *s1H, size_t n1, const char16_t *s2N, size_t n2);
-
-// Standard string functions on char32_t strings.
-size_t strlen32(const char32_t *);
-size_t strnlen32(const char32_t *, size_t);
-
-/**
- * Measure the length of a UTF-32 string in UTF-8. If the string is invalid
- * such as containing a surrogate character, -1 will be returned.
- */
-ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len);
-
-/**
- * Stores a UTF-8 string converted from "src" in "dst", if "dst_length" is not
- * large enough to store the string, the part of the "src" string is stored
- * into "dst" as much as possible. See the examples for more detail.
- * Returns the size actually used for storing the string.
- * dst" is not null-terminated when dst_len is fully used (like strncpy).
- *
- * Example 1
- * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
- * "src_len" == 2
- * "dst_len" >= 7
- * ->
- * Returned value == 6
- * "dst" becomes \xE3\x81\x82\xE3\x81\x84\0
- * (note that "dst" is null-terminated)
- *
- * Example 2
- * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
- * "src_len" == 2
- * "dst_len" == 5
- * ->
- * Returned value == 3
- * "dst" becomes \xE3\x81\x82\0
- * (note that "dst" is null-terminated, but \u3044 is not stored in "dst"
- * since "dst" does not have enough size to store the character)
- *
- * Example 3
- * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
- * "src_len" == 2
- * "dst_len" == 6
- * ->
- * Returned value == 6
- * "dst" becomes \xE3\x81\x82\xE3\x81\x84
- * (note that "dst" is NOT null-terminated, like strncpy)
- */
-void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len);
-
-/**
- * Returns the unicode value at "index".
- * Returns -1 when the index is invalid (equals to or more than "src_len").
- * If returned value is positive, it is able to be converted to char32_t, which
- * is unsigned. Then, if "next_index" is not NULL, the next index to be used is
- * stored in "next_index". "next_index" can be NULL.
- */
-int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index);
-
-
-/**
- * Returns the UTF-8 length of UTF-16 string "src".
- */
-ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len);
-
-/**
- * Converts a UTF-16 string to UTF-8. The destination buffer must be large
- * enough to fit the UTF-16 as measured by utf16_to_utf8_length with an added
- * NULL terminator.
- */
-void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len);
-
-/**
- * Returns the length of "src" when "src" is valid UTF-8 string.
- * Returns 0 if src is NULL or 0-length string. Returns -1 when the source
- * is an invalid string.
- *
- * This function should be used to determine whether "src" is valid UTF-8
- * characters with valid unicode codepoints. "src" must be null-terminated.
- *
- * If you are going to use other utf8_to_... functions defined in this header
- * with string which may not be valid UTF-8 with valid codepoint (form 0 to
- * 0x10FFFF), you should use this function before calling others, since the
- * other functions do not check whether the string is valid UTF-8 or not.
- *
- * If you do not care whether "src" is valid UTF-8 or not, you should use
- * strlen() as usual, which should be much faster.
- */
-ssize_t utf8_length(const char *src);
-
-/**
- * Measure the length of a UTF-32 string.
- */
-size_t utf8_to_utf32_length(const char *src, size_t src_len);
-
-/**
- * Stores a UTF-32 string converted from "src" in "dst". "dst" must be large
- * enough to store the entire converted string as measured by
- * utf8_to_utf32_length plus space for a NULL terminator.
- */
-void utf8_to_utf32(const char* src, size_t src_len, char32_t* dst);
-
-/**
- * Returns the UTF-16 length of UTF-8 string "src".
- */
-ssize_t utf8_to_utf16_length(const uint8_t* src, size_t srcLen);
-
-/**
- * Convert UTF-8 to UTF-16 including surrogate pairs.
- * Returns a pointer to the end of the string (where a null terminator might go
- * if you wanted to add one).
- */
-char16_t* utf8_to_utf16_no_null_terminator(const uint8_t* src, size_t srcLen, char16_t* dst);
-
-/**
- * Convert UTF-8 to UTF-16 including surrogate pairs. The destination buffer
- * must be large enough to hold the result as measured by utf8_to_utf16_length
- * plus an added NULL terminator.
- */
-void utf8_to_utf16(const uint8_t* src, size_t srcLen, char16_t* dst);
-
-/**
- * Like utf8_to_utf16_no_null_terminator, but you can supply a maximum length of the
- * decoded string.  The decoded string will fill up to that length; if it is longer
- * the returned pointer will be to the character after dstLen.
- */
-char16_t* utf8_to_utf16_n(const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen);
-
-}
-
-#endif
diff --git a/include/utils/Vector.h b/include/utils/Vector.h
deleted file mode 100644
index ed7b725..0000000
--- a/include/utils/Vector.h
+++ /dev/null
@@ -1,423 +0,0 @@
-/*
- * Copyright (C) 2005 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_VECTOR_H
-#define ANDROID_VECTOR_H
-
-#include <new>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/log.h>
-
-#include <utils/VectorImpl.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-template <typename TYPE>
-class SortedVector;
-
-/*!
- * The main templated vector class ensuring type safety
- * while making use of VectorImpl.
- * This is the class users want to use.
- */
-
-template <class TYPE>
-class Vector : private VectorImpl
-{
-public:
-            typedef TYPE    value_type;
-    
-    /*! 
-     * Constructors and destructors
-     */
-    
-                            Vector();
-                            Vector(const Vector<TYPE>& rhs);
-    explicit                Vector(const SortedVector<TYPE>& rhs);
-    virtual                 ~Vector();
-
-    /*! copy operator */
-            const Vector<TYPE>&     operator = (const Vector<TYPE>& rhs) const;
-            Vector<TYPE>&           operator = (const Vector<TYPE>& rhs);    
-
-            const Vector<TYPE>&     operator = (const SortedVector<TYPE>& rhs) const;
-            Vector<TYPE>&           operator = (const SortedVector<TYPE>& rhs);
-
-            /*
-     * empty the vector
-     */
-
-    inline  void            clear()             { VectorImpl::clear(); }
-
-    /*! 
-     * vector stats
-     */
-
-    //! returns number of items in the vector
-    inline  size_t          size() const                { return VectorImpl::size(); }
-    //! returns whether or not the vector is empty
-    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
-    //! returns how many items can be stored without reallocating the backing store
-    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
-    //! sets the capacity. capacity can never be reduced less than size()
-    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
-
-    /*!
-     * set the size of the vector. items are appended with the default
-     * constructor, or removed from the end as needed.
-     */
-    inline  ssize_t         resize(size_t size)         { return VectorImpl::resize(size); }
-
-    /*!
-     * C-style array access
-     */
-     
-    //! read-only C-style access 
-    inline  const TYPE*     array() const;
-    //! read-write C-style access
-            TYPE*           editArray();
-    
-    /*! 
-     * accessors
-     */
-
-    //! read-only access to an item at a given index
-    inline  const TYPE&     operator [] (size_t index) const;
-    //! alternate name for operator []
-    inline  const TYPE&     itemAt(size_t index) const;
-    //! stack-usage of the vector. returns the top of the stack (last element)
-            const TYPE&     top() const;
-
-    /*!
-     * modifying the array
-     */
-
-    //! copy-on write support, grants write access to an item
-            TYPE&           editItemAt(size_t index);
-    //! grants right access to the top of the stack (last element)
-            TYPE&           editTop();
-
-            /*! 
-             * append/insert another vector
-             */
-            
-    //! insert another vector at a given index
-            ssize_t         insertVectorAt(const Vector<TYPE>& vector, size_t index);
-
-    //! append another vector at the end of this one
-            ssize_t         appendVector(const Vector<TYPE>& vector);
-
-
-    //! insert an array at a given index
-            ssize_t         insertArrayAt(const TYPE* array, size_t index, size_t length);
-
-    //! append an array at the end of this vector
-            ssize_t         appendArray(const TYPE* array, size_t length);
-
-            /*! 
-             * add/insert/replace items
-             */
-             
-    //! insert one or several items initialized with their default constructor
-    inline  ssize_t         insertAt(size_t index, size_t numItems = 1);
-    //! insert one or several items initialized from a prototype item
-            ssize_t         insertAt(const TYPE& prototype_item, size_t index, size_t numItems = 1);
-    //! pop the top of the stack (removes the last element). No-op if the stack's empty
-    inline  void            pop();
-    //! pushes an item initialized with its default constructor
-    inline  void            push();
-    //! pushes an item on the top of the stack
-            void            push(const TYPE& item);
-    //! same as push() but returns the index the item was added at (or an error)
-    inline  ssize_t         add();
-    //! same as push() but returns the index the item was added at (or an error)
-            ssize_t         add(const TYPE& item);            
-    //! replace an item with a new one initialized with its default constructor
-    inline  ssize_t         replaceAt(size_t index);
-    //! replace an item with a new one
-            ssize_t         replaceAt(const TYPE& item, size_t index);
-
-    /*!
-     * remove items
-     */
-
-    //! remove several items
-    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
-    //! remove one item
-    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
-
-    /*!
-     * sort (stable) the array
-     */
-     
-     typedef int (*compar_t)(const TYPE* lhs, const TYPE* rhs);
-     typedef int (*compar_r_t)(const TYPE* lhs, const TYPE* rhs, void* state);
-     
-     inline status_t        sort(compar_t cmp);
-     inline status_t        sort(compar_r_t cmp, void* state);
-
-     // for debugging only
-     inline size_t getItemSize() const { return itemSize(); }
-
-
-     /*
-      * these inlines add some level of compatibility with STL. eventually
-      * we should probably turn things around.
-      */
-     typedef TYPE* iterator;
-     typedef TYPE const* const_iterator;
-
-     inline iterator begin() { return editArray(); }
-     inline iterator end()   { return editArray() + size(); }
-     inline const_iterator begin() const { return array(); }
-     inline const_iterator end() const   { return array() + size(); }
-     inline void reserve(size_t n) { setCapacity(n); }
-     inline bool empty() const{ return isEmpty(); }
-     inline void push_back(const TYPE& item)  { insertAt(item, size(), 1); }
-     inline void push_front(const TYPE& item) { insertAt(item, 0, 1); }
-     inline iterator erase(iterator pos) {
-         ssize_t index = removeItemsAt(pos-array());
-         return begin() + index;
-     }
-
-protected:
-    virtual void    do_construct(void* storage, size_t num) const;
-    virtual void    do_destroy(void* storage, size_t num) const;
-    virtual void    do_copy(void* dest, const void* from, size_t num) const;
-    virtual void    do_splat(void* dest, const void* item, size_t num) const;
-    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
-    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
-};
-
-// Vector<T> can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-template<typename T> struct trait_trivial_move<Vector<T> > { enum { value = true }; };
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts from here...
-// ---------------------------------------------------------------------------
-
-template<class TYPE> inline
-Vector<TYPE>::Vector()
-    : VectorImpl(sizeof(TYPE),
-                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
-                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
-                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
-                )
-{
-}
-
-template<class TYPE> inline
-Vector<TYPE>::Vector(const Vector<TYPE>& rhs)
-    : VectorImpl(rhs) {
-}
-
-template<class TYPE> inline
-Vector<TYPE>::Vector(const SortedVector<TYPE>& rhs)
-    : VectorImpl(static_cast<const VectorImpl&>(rhs)) {
-}
-
-template<class TYPE> inline
-Vector<TYPE>::~Vector() {
-    finish_vector();
-}
-
-template<class TYPE> inline
-Vector<TYPE>& Vector<TYPE>::operator = (const Vector<TYPE>& rhs) {
-    VectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const Vector<TYPE>& Vector<TYPE>::operator = (const Vector<TYPE>& rhs) const {
-    VectorImpl::operator = (static_cast<const VectorImpl&>(rhs));
-    return *this;
-}
-
-template<class TYPE> inline
-Vector<TYPE>& Vector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
-    VectorImpl::operator = (static_cast<const VectorImpl&>(rhs));
-    return *this;
-}
-
-template<class TYPE> inline
-const Vector<TYPE>& Vector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
-    VectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const TYPE* Vector<TYPE>::array() const {
-    return static_cast<const TYPE *>(arrayImpl());
-}
-
-template<class TYPE> inline
-TYPE* Vector<TYPE>::editArray() {
-    return static_cast<TYPE *>(editArrayImpl());
-}
-
-
-template<class TYPE> inline
-const TYPE& Vector<TYPE>::operator[](size_t index) const {
-    LOG_FATAL_IF(index>=size(),
-            "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__,
-            int(index), int(size()));
-    return *(array() + index);
-}
-
-template<class TYPE> inline
-const TYPE& Vector<TYPE>::itemAt(size_t index) const {
-    return operator[](index);
-}
-
-template<class TYPE> inline
-const TYPE& Vector<TYPE>::top() const {
-    return *(array() + size() - 1);
-}
-
-template<class TYPE> inline
-TYPE& Vector<TYPE>::editItemAt(size_t index) {
-    return *( static_cast<TYPE *>(editItemLocation(index)) );
-}
-
-template<class TYPE> inline
-TYPE& Vector<TYPE>::editTop() {
-    return *( static_cast<TYPE *>(editItemLocation(size()-1)) );
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::insertVectorAt(const Vector<TYPE>& vector, size_t index) {
-    return VectorImpl::insertVectorAt(reinterpret_cast<const VectorImpl&>(vector), index);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::appendVector(const Vector<TYPE>& vector) {
-    return VectorImpl::appendVector(reinterpret_cast<const VectorImpl&>(vector));
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::insertArrayAt(const TYPE* array, size_t index, size_t length) {
-    return VectorImpl::insertArrayAt(array, index, length);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::appendArray(const TYPE* array, size_t length) {
-    return VectorImpl::appendArray(array, length);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::insertAt(const TYPE& item, size_t index, size_t numItems) {
-    return VectorImpl::insertAt(&item, index, numItems);
-}
-
-template<class TYPE> inline
-void Vector<TYPE>::push(const TYPE& item) {
-    return VectorImpl::push(&item);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::add(const TYPE& item) {
-    return VectorImpl::add(&item);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::replaceAt(const TYPE& item, size_t index) {
-    return VectorImpl::replaceAt(&item, index);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::insertAt(size_t index, size_t numItems) {
-    return VectorImpl::insertAt(index, numItems);
-}
-
-template<class TYPE> inline
-void Vector<TYPE>::pop() {
-    VectorImpl::pop();
-}
-
-template<class TYPE> inline
-void Vector<TYPE>::push() {
-    VectorImpl::push();
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::add() {
-    return VectorImpl::add();
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::replaceAt(size_t index) {
-    return VectorImpl::replaceAt(index);
-}
-
-template<class TYPE> inline
-ssize_t Vector<TYPE>::removeItemsAt(size_t index, size_t count) {
-    return VectorImpl::removeItemsAt(index, count);
-}
-
-template<class TYPE> inline
-status_t Vector<TYPE>::sort(Vector<TYPE>::compar_t cmp) {
-    return VectorImpl::sort((VectorImpl::compar_t)cmp);
-}
-
-template<class TYPE> inline
-status_t Vector<TYPE>::sort(Vector<TYPE>::compar_r_t cmp, void* state) {
-    return VectorImpl::sort((VectorImpl::compar_r_t)cmp, state);
-}
-
-// ---------------------------------------------------------------------------
-
-template<class TYPE>
-void Vector<TYPE>::do_construct(void* storage, size_t num) const {
-    construct_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void Vector<TYPE>::do_destroy(void* storage, size_t num) const {
-    destroy_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void Vector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
-    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void Vector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
-    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
-}
-
-template<class TYPE>
-void Vector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
-    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void Vector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
-    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_VECTOR_H
diff --git a/include/utils/VectorImpl.h b/include/utils/VectorImpl.h
deleted file mode 100644
index 21ad71c..0000000
--- a/include/utils/VectorImpl.h
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2005 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_VECTOR_IMPL_H
-#define ANDROID_VECTOR_IMPL_H
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/Errors.h>
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts in here...
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-/*!
- * Implementation of the guts of the vector<> class
- * this ensures backward binary compatibility and
- * reduces code size.
- * For performance reasons, we expose mStorage and mCount
- * so these fields are set in stone.
- *
- */
-
-class VectorImpl
-{
-public:
-    enum { // flags passed to the ctor
-        HAS_TRIVIAL_CTOR    = 0x00000001,
-        HAS_TRIVIAL_DTOR    = 0x00000002,
-        HAS_TRIVIAL_COPY    = 0x00000004,
-    };
-
-                            VectorImpl(size_t itemSize, uint32_t flags);
-                            VectorImpl(const VectorImpl& rhs);
-    virtual                 ~VectorImpl();
-
-    /*! must be called from subclasses destructor */
-            void            finish_vector();
-
-            VectorImpl&     operator = (const VectorImpl& rhs);    
-            
-    /*! C-style array access */
-    inline  const void*     arrayImpl() const       { return mStorage; }
-            void*           editArrayImpl();
-            
-    /*! vector stats */
-    inline  size_t          size() const        { return mCount; }
-    inline  bool            isEmpty() const     { return mCount == 0; }
-            size_t          capacity() const;
-            ssize_t         setCapacity(size_t size);
-            ssize_t         resize(size_t size);
-
-            /*! append/insert another vector or array */
-            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
-            ssize_t         appendVector(const VectorImpl& vector);
-            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
-            ssize_t         appendArray(const void* array, size_t length);
-            
-            /*! add/insert/replace items */
-            ssize_t         insertAt(size_t where, size_t numItems = 1);
-            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
-            void            pop();
-            void            push();
-            void            push(const void* item);
-            ssize_t         add();
-            ssize_t         add(const void* item);
-            ssize_t         replaceAt(size_t index);
-            ssize_t         replaceAt(const void* item, size_t index);
-
-            /*! remove items */
-            ssize_t         removeItemsAt(size_t index, size_t count = 1);
-            void            clear();
-
-            const void*     itemLocation(size_t index) const;
-            void*           editItemLocation(size_t index);
-
-            typedef int (*compar_t)(const void* lhs, const void* rhs);
-            typedef int (*compar_r_t)(const void* lhs, const void* rhs, void* state);
-            status_t        sort(compar_t cmp);
-            status_t        sort(compar_r_t cmp, void* state);
-
-protected:
-            size_t          itemSize() const;
-            void            release_storage();
-
-    virtual void            do_construct(void* storage, size_t num) const = 0;
-    virtual void            do_destroy(void* storage, size_t num) const = 0;
-    virtual void            do_copy(void* dest, const void* from, size_t num) const = 0;
-    virtual void            do_splat(void* dest, const void* item, size_t num) const = 0;
-    virtual void            do_move_forward(void* dest, const void* from, size_t num) const = 0;
-    virtual void            do_move_backward(void* dest, const void* from, size_t num) const = 0;
-    
-private:
-        void* _grow(size_t where, size_t amount);
-        void  _shrink(size_t where, size_t amount);
-
-        inline void _do_construct(void* storage, size_t num) const;
-        inline void _do_destroy(void* storage, size_t num) const;
-        inline void _do_copy(void* dest, const void* from, size_t num) const;
-        inline void _do_splat(void* dest, const void* item, size_t num) const;
-        inline void _do_move_forward(void* dest, const void* from, size_t num) const;
-        inline void _do_move_backward(void* dest, const void* from, size_t num) const;
-
-            // These 2 fields are exposed in the inlines below,
-            // so they're set in stone.
-            void *      mStorage;   // base address of the vector
-            size_t      mCount;     // number of items
-
-    const   uint32_t    mFlags;
-    const   size_t      mItemSize;
-};
-
-
-
-class SortedVectorImpl : public VectorImpl
-{
-public:
-                            SortedVectorImpl(size_t itemSize, uint32_t flags);
-                            SortedVectorImpl(const VectorImpl& rhs);
-    virtual                 ~SortedVectorImpl();
-    
-    SortedVectorImpl&     operator = (const SortedVectorImpl& rhs);    
-
-    //! finds the index of an item
-            ssize_t         indexOf(const void* item) const;
-
-    //! finds where this item should be inserted
-            size_t          orderOf(const void* item) const;
-
-    //! add an item in the right place (or replaces it if there is one)
-            ssize_t         add(const void* item);
-
-    //! merges a vector into this one
-            ssize_t         merge(const VectorImpl& vector);
-            ssize_t         merge(const SortedVectorImpl& vector);
-             
-    //! removes an item
-            ssize_t         remove(const void* item);
-        
-protected:
-    virtual int             do_compare(const void* lhs, const void* rhs) const = 0;
-
-private:
-            ssize_t         _indexOrderOf(const void* item, size_t* order = 0) const;
-
-            // these are made private, because they can't be used on a SortedVector
-            // (they don't have an implementation either)
-            ssize_t         add();
-            void            pop();
-            void            push();
-            void            push(const void* item);
-            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
-            ssize_t         appendVector(const VectorImpl& vector);
-            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
-            ssize_t         appendArray(const void* array, size_t length);
-            ssize_t         insertAt(size_t where, size_t numItems = 1);
-            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
-            ssize_t         replaceAt(size_t index);
-            ssize_t         replaceAt(const void* item, size_t index);
-};
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_VECTOR_IMPL_H
diff --git a/include/utils/ashmem.h b/include/utils/ashmem.h
deleted file mode 100644
index 0854775..0000000
--- a/include/utils/ashmem.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* utils/ashmem.h
- **
- ** Copyright 2008 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 _UTILS_ASHMEM_H
-#define _UTILS_ASHMEM_H
-
-#include <linux/limits.h>
-#include <linux/ioctl.h>
-
-#define ASHMEM_NAME_LEN		256
-
-#define ASHMEM_NAME_DEF		"dev/ashmem"
-
-/* Return values from ASHMEM_PIN: Was the mapping purged while unpinned? */
-#define ASHMEM_NOT_REAPED	0
-#define ASHMEM_WAS_REAPED	1
-
-/* Return values from ASHMEM_UNPIN: Is the mapping now pinned or unpinned? */
-#define ASHMEM_NOW_UNPINNED	0
-#define ASHMEM_NOW_PINNED	1
-
-#define __ASHMEMIOC		0x77
-
-#define ASHMEM_SET_NAME		_IOW(__ASHMEMIOC, 1, char[ASHMEM_NAME_LEN])
-#define ASHMEM_GET_NAME		_IOR(__ASHMEMIOC, 2, char[ASHMEM_NAME_LEN])
-#define ASHMEM_SET_SIZE		_IOW(__ASHMEMIOC, 3, size_t)
-#define ASHMEM_GET_SIZE		_IO(__ASHMEMIOC, 4)
-#define ASHMEM_SET_PROT_MASK	_IOW(__ASHMEMIOC, 5, unsigned long)
-#define ASHMEM_GET_PROT_MASK	_IO(__ASHMEMIOC, 6)
-#define ASHMEM_PIN		_IO(__ASHMEMIOC, 7)
-#define ASHMEM_UNPIN		_IO(__ASHMEMIOC, 8)
-#define ASHMEM_ISPINNED		_IO(__ASHMEMIOC, 9)
-#define ASHMEM_PURGE_ALL_CACHES	_IO(__ASHMEMIOC, 10)
-
-#endif	/* _UTILS_ASHMEM_H */
diff --git a/include/ziparchive/zip_archive.h b/include/ziparchive/zip_archive.h
index 7dc60ae..31fc2df 100644
--- a/include/ziparchive/zip_archive.h
+++ b/include/ziparchive/zip_archive.h
@@ -26,8 +26,6 @@
 #include <sys/types.h>
 #include <utils/Compat.h>
 
-__BEGIN_DECLS
-
 /* Zip compression methods we support */
 enum {
   kCompressStored     = 0,        // no compression
@@ -43,8 +41,7 @@
   /*
    * entry_name has to be an c-style string with only ASCII characters.
    */
-  explicit ZipString(const char* entry_name)
-      : name(reinterpret_cast<const uint8_t*>(entry_name)), name_length(strlen(entry_name)) {}
+  explicit ZipString(const char* entry_name);
 
   bool operator==(const ZipString& rhs) const {
     return name && (name_length == rhs.name_length) &&
@@ -131,6 +128,8 @@
 int32_t OpenArchiveFd(const int fd, const char* debugFileName,
                       ZipArchiveHandle *handle, bool assume_ownership = true);
 
+int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debugFileName,
+                              ZipArchiveHandle *handle);
 /*
  * Close archive, releasing resources associated with it. This will
  * unmap the central directory of the zipfile and free all internal
@@ -194,7 +193,8 @@
  * Uncompress and write an entry to an open file identified by |fd|.
  * |entry->uncompressed_length| bytes will be written to the file at
  * its current offset, and the file will be truncated at the end of
- * the uncompressed data.
+ * the uncompressed data (no truncation if |fd| references a block
+ * device).
  *
  * Returns 0 on success and negative values on failure.
  */
@@ -215,6 +215,15 @@
 
 const char* ErrorCodeString(int32_t error_code);
 
-__END_DECLS
+#if !defined(_WIN32)
+typedef bool (*ProcessZipEntryFunction)(const uint8_t* buf, size_t buf_size, void* cookie);
+
+/*
+ * Stream the uncompressed data through the supplied function,
+ * passing cookie to it each time it gets called.
+*/
+int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
+        ProcessZipEntryFunction func, void* cookie);
+#endif
 
 #endif  // LIBZIPARCHIVE_ZIPARCHIVE_H_
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/.clang-format b/init/.clang-format
new file mode 120000
index 0000000..1af4f51
--- /dev/null
+++ b/init/.clang-format
@@ -0,0 +1 @@
+../.clang-format-4
\ No newline at end of file
diff --git a/init/Android.mk b/init/Android.mk
index 67541b8..42e42ec 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -5,9 +5,25 @@
 # --
 
 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 \
+    -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 \
+    -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
@@ -17,6 +33,7 @@
     -Wall -Wextra \
     -Wno-unused-parameter \
     -Werror \
+    -std=gnu++1z \
 
 # --
 
@@ -45,6 +62,8 @@
 LOCAL_CPPFLAGS := $(init_cflags)
 LOCAL_SRC_FILES:= \
     action.cpp \
+    capabilities.cpp \
+    descriptors.cpp \
     import_parser.cpp \
     init_parser.cpp \
     log.cpp \
@@ -52,7 +71,8 @@
     service.cpp \
     util.cpp \
 
-LOCAL_STATIC_LIBRARIES := libbase libselinux
+LOCAL_STATIC_LIBRARIES := libbase libselinux liblog libprocessgroup
+LOCAL_WHOLE_STATIC_LIBRARIES := libcap
 LOCAL_MODULE := libinit
 LOCAL_SANITIZE := integer
 LOCAL_CLANG := true
@@ -65,8 +85,10 @@
     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 \
@@ -74,7 +96,6 @@
 
 LOCAL_MODULE:= init
 LOCAL_C_INCLUDES += \
-    system/extras/ext4_utils \
     system/core/mkbootimg
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
@@ -89,21 +110,22 @@
     libfec_rs \
     libsquashfs_utils \
     liblogwrap \
+    libext4_utils \
     libcutils \
-    libext4_utils_static \
     libbase \
-    libutils \
     libc \
     libselinux \
     liblog \
-    libmincrypt \
-    libcrypto_static \
+    libcrypto_utils \
+    libcrypto \
     libc++_static \
     libdl \
-    libsparse_static \
-    libz
+    libsparse \
+    libz \
+    libprocessgroup \
+    libavb
 
-# Create symlinks
+# Create symlinks.
 LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
     ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
     ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd
@@ -113,12 +135,14 @@
 include $(BUILD_EXECUTABLE)
 
 
-
-
+# Unit tests.
+# =========================================================
 include $(CLEAR_VARS)
 LOCAL_MODULE := init_tests
 LOCAL_SRC_FILES := \
     init_parser_test.cpp \
+    property_service_test.cpp \
+    service_test.cpp \
     util_test.cpp \
 
 LOCAL_SHARED_LIBRARIES += \
@@ -128,4 +152,10 @@
 LOCAL_STATIC_LIBRARIES := libinit
 LOCAL_SANITIZE := integer
 LOCAL_CLANG := true
+LOCAL_CPPFLAGS := -Wall -Wextra -Werror
 include $(BUILD_NATIVE_TEST)
+
+
+# Include targets in subdirs.
+# =========================================================
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/init/README.md b/init/README.md
new file mode 100644
index 0000000..8cb1e52
--- /dev/null
+++ b/init/README.md
@@ -0,0 +1,587 @@
+Android Init Language
+---------------------
+
+The Android Init Language consists of five broad classes of statements:
+Actions, Commands, Services, Options, and Imports.
+
+All of these are line-oriented, consisting of tokens separated by
+whitespace.  The c-style backslash escapes may be used to insert
+whitespace into a token.  Double quotes may also be used to prevent
+whitespace from breaking text into multiple tokens.  The backslash,
+when it is the last character on a line, may be used for line-folding.
+
+Lines which start with a # (leading whitespace allowed) are comments.
+
+Actions and Services implicitly declare a new section.  All commands
+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
+with the same name as an existing one, it is ignored and an error
+message is logged.
+
+
+Init .rc Files
+--------------
+The init language is used in plain text files that take the .rc file
+extension.  There are typically multiple of these in multiple
+locations on the system, described below.
+
+/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.
+
+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.
+This is primarily for supporting factory mode and other non-standard boot
+modes.  The three default paths should be used for the normal boot process.
+
+The intention of these directories is:
+
+   1. /system/etc/init/ is for core system items such as
+      SurfaceFlinger, MediaService, and logcatd.
+   2. /vendor/etc/init/ is for SoC vendor items such as actions or
+      daemons needed for core SoC functionality.
+   3. /odm/etc/init/ is for device manufacturer items such as
+      actions or daemons needed for motion sensor or other peripheral
+      functionality.
+
+All services whose binaries reside on the system, vendor, or odm
+partitions should have their service entries placed into a
+corresponding init .rc file, located in the /etc/init/
+directory of the partition where they reside.  There is a build
+system macro, LOCAL\_INIT\_RC, that handles this for developers.  Each
+init .rc file should additionally contain any actions associated with
+its service.
+
+An example is the logcatd.rc and Android.mk files located in the
+system/core/logcat directory.  The LOCAL\_INIT\_RC macro in the
+Android.mk file places logcatd.rc in /system/etc/init/ during the
+build process.  Init loads logcatd.rc during the mount\_all command and
+allows the service to be run and the action to be queued when
+appropriate.
+
+This break up of init .rc files according to their daemon is preferred
+to the previously used monolithic init .rc files.  This approach
+ensures that the only service entries that init reads and the only
+actions that init performs correspond to services whose binaries are in
+fact present on the file system, which was not the case with the
+monolithic init .rc files.  This additionally will aid in merge
+conflict resolution when multiple services are added to the system, as
+each one will go into a separate file.
+
+There are two options "early" and "late" in mount\_all command
+which can be set after optional paths. With "--early" set, the
+init executable will skip mounting entries with "latemount" flag
+and triggering fs encryption state event. With "--late" set,
+init executable will only mount entries with "latemount" flag but skip
+importing rc files. By default, no option is set, and mount\_all will
+process all entries in the given fstab.
+
+Actions
+-------
+Actions are named sequences of commands.  Actions have a trigger which
+is used to determine when the action should occur.  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).
+
+Each action in the queue is dequeued in sequence and each command in
+that action is executed in sequence.  Init handles other activities
+(device creation/destruction, property setting, process restarting)
+"between" the execution of the commands in activities.
+
+Actions take the form of:
+
+    on <trigger> [&& <trigger>]*
+       <command>
+       <command>
+       <command>
+
+
+Services
+--------
+Services are programs which init launches and (optionally) restarts
+when they exit.  Services take the form of:
+
+    service <name> <pathname> [ <argument> ]*
+       <option>
+       <option>
+       ...
+
+
+Options
+-------
+Options are modifiers to services.  They affect how and when init
+runs the service.
+
+`console [<console>]`
+> This service needs a console. The optional second parameter chooses a
+  specific console instead of the default. The default "/dev/console" can
+  be changed by setting the "androidboot.console" kernel parameter. In
+  all cases the leading "/dev/" should be omitted, so "/dev/tty0" would be
+  specified as just "console tty0".
+
+`critical`
+> This is a device-critical service. If it exits more than four times in
+  four minutes, the device will reboot into recovery mode.
+
+`disabled`
+> This service will not automatically start with its class.
+  It must be explicitly started by name.
+
+`setenv <name> <value>`
+> Set the environment variable _name_ to _value_ in the launched process.
+
+`socket <name> <type> <perm> [ <user> [ <group> [ <seclabel> ] ] ]`
+> Create a unix domain socket named /dev/socket/_name_ and pass its fd to the
+  launched process.  _type_ must be "dgram", "stream" or "seqpacket".  User and
+  group default to 0.  'seclabel' is the SELinux security context for the
+  socket.  It defaults to the service security context, as specified by
+  seclabel or computed based on the service executable file security context.
+  For native executables see libcutils android\_get\_control\_socket().
+
+`file <path> <type>`
+> Open a file path and pass its fd to the launched process. _type_ must be
+  "r", "w" or "rw".  For native executables see libcutils
+  android\_get\_control\_file().
+
+`user <username>`
+> Change to 'username' before exec'ing this service.
+  Currently defaults to root.  (??? probably should default to nobody)
+  As of Android M, processes should use this option even if they
+  require Linux capabilities.  Previously, to acquire Linux
+  capabilities, a process would need to run as root, request the
+  capabilities, then drop to its desired uid.  There is a new
+  mechanism through fs\_config that allows device manufacturers to add
+  Linux capabilities to specific binaries on a file system that should
+  be used instead. This mechanism is described on
+  <http://source.android.com/devices/tech/config/filesystem.html>.  When
+  using this new mechanism, processes can use the user option to
+  select their desired uid without ever running as root.
+  As of Android O, processes can also request capabilities directly in their .rc
+  files. See the "capabilities" option below.
+
+`group <groupname> [ <groupname>\* ]`
+> Change to 'groupname' before exec'ing this service.  Additional
+  groupnames beyond the (required) first one are used to set the
+  supplemental groups of the process (via setgroups()).
+  Currently defaults to root.  (??? probably should default to nobody)
+
+`capabilities <capability> [ <capability>\* ]`
+> Set capabilities when exec'ing this service. 'capability' should be a Linux
+  capability without the "CAP\_" prefix, like "NET\_ADMIN" or "SETPCAP". See
+  http://man7.org/linux/man-pages/man7/capabilities.7.html for a list of Linux
+  capabilities.
+
+`seclabel <seclabel>`
+> Change to 'seclabel' before exec'ing this service.
+  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
+  Services on the system partition can instead use policy-defined transitions
+  based on their file security context.
+  If not specified and no transition is defined in policy, defaults to the init context.
+
+`oneshot`
+> Do not restart the service when it exits.
+
+`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. 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> [ <file>\* ]`
+> Write the child's pid to the given files when it forks. Meant for
+  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
+  -20 to 19. Default priority is 0. Priority is set via setpriority().
+
+`namespace <pid|mnt>`
+> Enter a new PID or mount namespace when forking the service.
+
+`oom_score_adjust <value>`
+> Sets the child's /proc/self/oom\_score\_adj to the specified value,
+  which must range from -1000 to 1000.
+
+
+Triggers
+--------
+Triggers are strings which can be used to match certain kinds of
+events and used to cause an action to occur.
+
+Triggers are subdivided into event triggers and property triggers.
+
+Event triggers are strings triggered by the 'trigger' command or by
+the QueueEventTrigger() function within the init executable.  These
+take the form of a simple string such as 'boot' or 'late-init'.
+
+Property triggers are strings triggered when a named property changes
+value to a given new value or when a named property changes value to
+any new value.  These take the form of 'property:<name>=<value>' and
+'property:<name>=\*' respectively.  Property triggers are additionally
+evaluated and triggered accordingly during the initial boot phase of
+init.
+
+An Action can have multiple property triggers but may only have one
+event trigger.
+
+For example:
+`on boot && property:a=b` defines an action that is only executed when
+the 'boot' event trigger happens and the property a equals b.
+
+`on property:a=b && property:c=d` defines an action that is executed
+at three times:
+
+   1. During initial boot if property a=b and property c=d.
+   2. Any time that property a transitions to value b, while property c already equals d.
+   3. Any time that property c transitions to value d, while property a already equals b.
+
+
+Commands
+--------
+
+`bootchart [start|stop]`
+> Start/stop bootcharting. These are present in the default init.rc files,
+  but bootcharting is only active if the file /data/bootchart/enabled exists;
+  otherwise bootchart start/stop are no-ops.
+
+`chmod <octal-mode> <path>`
+> Change file access permissions.
+
+`chown <owner> <group> <path>`
+> Change file owner and group.
+
+`class_start <serviceclass>`
+> Start all services of the specified class if they are
+  not already running.
+
+`class_stop <serviceclass>`
+> Stop and disable all services of the specified class if they are
+  currently running.
+
+`class_reset <serviceclass>`
+> Stop all services of the specified class if they are
+  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.
+
+`enable <servicename>`
+> Turns a disabled service into an enabled one as if the service did not
+  specify disabled.
+  If the service is supposed to be running, it will be started now.
+  Typically used when the bootloader sets a variable that indicates a specific
+  service should be started when needed. E.g.
+
+    on property:ro.boot.myfancyhardware=1
+        enable my_fancy_service_for_my_fancy_hardware
+
+`exec [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]`
+> Fork and execute command with the given arguments. The command starts
+  after "--" so that an optional security context, user, and supplementary
+  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
+  global environment (which will be inherited by all processes
+  started after this command is executed)
+
+`hostname <name>`
+> Set the host name.
+
+`ifup <interface>`
+> Bring the network interface _interface_ online.
+
+`insmod [-f] <path> [<options>]`
+> Install the module at _path_ with the specified options.
+  -f: force installation of the module even if the version of the running kernel
+  and the version of the kernel for which the module was compiled do not match.
+
+`load_all_props`
+> Loads properties from /system, /vendor, et cetera.
+  This is included in the default init.rc.
+
+`load_persist_props`
+> Loads persistent properties when /data has been decrypted.
+  This is included in the default init.rc.
+
+`loglevel <level>`
+> Sets the kernel log level to level. Properties are expanded within _level_.
+
+`mkdir <path> [mode] [owner] [group]`
+> Create a directory at _path_, optionally with the given mode, owner, and
+  group. If not provided, the directory is created with permissions 755 and
+  owned by the root user and root group. If provided, the mode, owner and group
+  will be updated if the directory exists already.
+
+`mount_all <fstab> [ <path> ]\* [--<option>]`
+> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab and imports .rc files
+  at the specified paths (e.g., on the partitions just mounted) with optional
+  options "early" and "late".
+  Refer to the section of "Init .rc Files" for detail.
+
+`mount <type> <device> <dir> [ <flag>\* ] [<options>]`
+> Attempt to mount the named device at the directory _dir_
+  _flag_s include "ro", "rw", "remount", "noatime", ...
+  _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
+  a comma separated string, eg: barrier=1,noauto\_da\_alloc
+
+`restart <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
+  in the file\_contexts configuration.
+  Not required for directories created by the init.rc as these are
+  automatically labeled correctly by init.
+
+`restorecon_recursive <path> [ <path>\* ]`
+> Recursively restore the directory tree named by _path_ to the
+  security contexts specified in the file\_contexts configuration.
+
+`rm <path>`
+> Calls unlink(2) on the given path. You might want to
+  use "exec -- rm ..." instead (provided the system partition is
+  already mounted).
+
+`rmdir <path>`
+> Calls rmdir(2) on the given path.
+
+`setprop <name> <value>`
+> Set system property _name_ to _value_. Properties are expanded
+  within _value_.
+
+`setrlimit <resource> <cur> <max>`
+> Set the rlimit for a resource.
+
+`start <service>`
+> Start a service running if it is not already running.
+
+`stop <service>`
+> Stop a service from running if it is currently running.
+
+`swapon_all <fstab>`
+> Calls fs\_mgr\_swapon\_all on the given fstab file.
+
+`symlink <target> <path>`
+> Create a symbolic link at _path_ with the value _target_
+
+`sysclktz <mins_west_of_gmt>`
+> Set the system clock base (0 if system clock ticks in GMT)
+
+`trigger <event>`
+> Trigger an event.  Used to queue an action from another
+  action.
+
+`umount <path>`
+> Unmount the filesystem mounted at that path.
+
+`verity_load_state`
+> Internal implementation detail used to load dm-verity state.
+
+`verity_update_state <mount-point>`
+> Internal implementation detail used to update dm-verity state and
+  set the partition._mount-point_.verified properties used by adb remount
+  because fs\_mgr can't set them directly itself.
+
+`wait <path> [ <timeout> ]`
+> Poll for the existence of the given file and return when found,
+  or the timeout has been reached. If timeout is not specified it
+  currently defaults to five seconds.
+
+`wait_for_prop <name> <value>`
+> Wait for system property _name_ to be _value_. Properties are expanded
+  within _value_. If property _name_ is already set to _value_, continue
+  immediately.
+
+`write <path> <content>`
+> Open the file at _path_ and write a string to it with write(2).
+  If the file does not exist, it will be created. If it does exist,
+  it will be truncated. Properties are expanded within _content_.
+
+
+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:
+
+   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
+
+
+Properties
+----------
+Init provides information about the services that it is responsible
+for via the below properties.
+
+`init.svc.<name>`
+> State of a named service ("stopped", "stopping", "running", "restarting")
+
+
+Boot timing
+-----------
+Init records some boot timing information in system properties.
+
+`ro.boottime.init`
+> Time after boot in ns (via the CLOCK\_BOOTTIME clock) at which the first
+  stage of init started.
+
+`ro.boottime.init.selinux`
+> How long it took the first stage to initialize SELinux.
+
+`ro.boottime.init.cold_boot_wait`
+> How long init waited for ueventd's coldboot phase to end.
+
+`ro.boottime.<service-name>`
+> Time after boot in ns (via the CLOCK\_BOOTTIME clock) that the service was
+  first started.
+
+
+Bootcharting
+------------
+This version of init contains code to perform "bootcharting": generating log
+files that can be later processed by the tools provided by <http://www.bootchart.org/>.
+
+On the emulator, use the -bootchart _timeout_ option to boot with bootcharting
+activated for _timeout_ seconds.
+
+On a device:
+
+    adb shell 'touch /data/bootchart/enabled'
+
+Don't forget to delete this file when you're done collecting data!
+
+The log files are written to /data/bootchart/. A script is provided to
+retrieve them and create a bootchart.tgz file that can be used with the
+bootchart command-line utility:
+
+    sudo apt-get install pybootchartgui
+    # grab-bootchart.sh uses $ANDROID_SERIAL.
+    $ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh
+
+One thing to watch for is that the bootchart will show init as if it started
+running at 0s. You'll have to look at dmesg to work out when the kernel
+actually started init.
+
+
+Comparing two bootcharts
+------------------------
+A handy script named compare-bootcharts.py can be used to compare the
+start/end time of selected processes. The aforementioned grab-bootchart.sh
+will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
+If two such barballs are preserved on the host machine under different
+directories, the script can list the timestamps differences. For example:
+
+Usage: system/core/init/compare-bootcharts.py _base-bootchart-dir_ _exp-bootchart-dir_
+
+    process: baseline experiment (delta) - Unit is ms (a jiffy is 10 ms on the system)
+    ------------------------------------
+    /init: 50 40 (-10)
+    /system/bin/surfaceflinger: 4320 4470 (+150)
+    /system/bin/bootanimation: 6980 6990 (+10)
+    zygote64: 10410 10640 (+230)
+    zygote: 10410 10640 (+230)
+    system_server: 15350 15150 (-200)
+    bootanimation ends at: 33790 31230 (-2560)
+
+
+Systrace
+--------
+Systrace (<http://developer.android.com/tools/help/systrace.html>) can be
+used for obtaining performance analysis reports during boot
+time on userdebug or eng builds.
+
+Here is an example of trace events of "wm" and "am" categories:
+
+    $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py \
+          wm am --boot
+
+This command will cause the device to reboot. After the device is rebooted and
+the boot sequence has finished, the trace report is obtained from the device
+and written as trace.html on the host by hitting Ctrl+C.
+
+Limitation: recording trace events is started after persistent properties are loaded, so
+the trace events that are emitted before that are not recorded. Several
+services such as vold, surfaceflinger, and servicemanager are affected by this
+limitation since they are started before persistent properties are loaded.
+Zygote initialization and the processes that are forked from the zygote are not
+affected.
+
+
+Debugging init
+--------------
+By default, programs executed by init will drop stdout and stderr into
+/dev/null. To help with debugging, you can execute your program via the
+Android program logwrapper. This will redirect stdout/stderr into the
+Android logging system (accessed via logcat).
+
+For example
+service akmd /system/bin/logwrapper /sbin/akmd
+
+For quicker turnaround when working on init itself, use:
+
+    mm -j &&
+    m ramdisk-nodeps &&
+    m bootimage-nodeps &&
+    adb reboot bootloader &&
+    fastboot boot $ANDROID_PRODUCT_OUT/boot.img
+
+Alternatively, use the emulator:
+
+    emulator -partition-size 1024 \
+        -verbose -show-kernel -no-window
diff --git a/init/action.cpp b/init/action.cpp
index 510ea89..2ccf0bc 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -18,14 +18,14 @@
 
 #include <errno.h>
 
-#include <android-base/strings.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;
@@ -42,7 +42,7 @@
     expanded_args[0] = args_[0];
     for (std::size_t i = 1; i < args_.size(); ++i) {
         if (!expand_props(args_[i], &expanded_args[i])) {
-            ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
+            LOG(ERROR) << args_[0] << ": cannot expand '" << args_[i] << "'";
             return -EINVAL;
         }
     }
@@ -105,7 +105,10 @@
 }
 
 void Action::ExecuteOneCommand(std::size_t command) const {
-    ExecuteCommand(commands_[command]);
+    // We need a copy here since some Command execution may result in
+    // changing commands_ vector by importing .rc files through parser
+    Command cmd = commands_[command];
+    ExecuteCommand(cmd);
 }
 
 void Action::ExecuteAllCommands() const {
@@ -118,14 +121,16 @@
     Timer t;
     int result = command.InvokeFunc();
 
-    if (klog_get_level() >= KLOG_INFO_LEVEL) {
+    double duration_ms = t.duration_s() * 1000;
+    // Any action longer than 50ms will be warned to user as slow operation
+    if (duration_ms > 50.0 ||
+        android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
         std::string trigger_name = BuildTriggersString();
         std::string cmd_str = command.BuildCommandString();
         std::string source = command.BuildSourceString();
 
-        INFO("Command '%s' action=%s%s returned %d took %.2fs\n",
-             cmd_str.c_str(), trigger_name.c_str(), source.c_str(),
-             result, t.duration());
+        LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << source
+                  << " returned " << result << " took " << duration_ms << "ms.";
     }
 }
 
@@ -141,8 +146,7 @@
     std::string prop_value(prop_name.substr(equal_pos + 1));
     prop_name.erase(equal_pos);
 
-    auto res = property_triggers_.emplace(prop_name, prop_value);
-    if (res.second == false) {
+    if (auto [it, inserted] = property_triggers_.emplace(prop_name, prop_value); !inserted) {
         *err = "multiple property triggers found for same property";
         return false;
     }
@@ -152,6 +156,11 @@
 bool Action::InitTriggers(const std::vector<std::string>& args, std::string* err) {
     const static std::string prop_str("property:");
     for (std::size_t i = 0; i < args.size(); ++i) {
+        if (args[i].empty()) {
+            *err = "empty trigger is not valid";
+            return false;
+        }
+
         if (i % 2) {
             if (args[i] != "&&") {
                 *err = "&& is the only symbol allowed to concatenate actions";
@@ -181,7 +190,11 @@
 bool Action::InitSingleTrigger(const std::string& trigger) {
     std::vector<std::string> name_vector{trigger};
     std::string err;
-    return InitTriggers(name_vector, &err);
+    bool ret = InitTriggers(name_vector, &err);
+    if (!ret) {
+        LOG(ERROR) << "InitSingleTrigger failed due to: " << err;
+    }
+    return ret;
 }
 
 // This function checks that all property triggers are satisfied, that is
@@ -198,9 +211,7 @@
     }
 
     bool found = name.empty();
-    for (const auto& t : property_triggers_) {
-        const auto& trigger_name = t.first;
-        const auto& trigger_value = t.second;
+    for (const auto& [trigger_name, trigger_value] : property_triggers_) {
         if (trigger_name == name) {
             if (trigger_value != "*" && trigger_value != value) {
                 return false;
@@ -208,9 +219,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;
             }
         }
@@ -235,36 +245,31 @@
 }
 
 std::string Action::BuildTriggersString() const {
-    std::string result;
+    std::vector<std::string> triggers;
 
-    for (const auto& t : property_triggers_) {
-        result += t.first;
-        result += '=';
-        result += t.second;
-        result += ' ';
+    for (const auto& [trigger_name, trigger_value] : property_triggers_) {
+        triggers.emplace_back(trigger_name + '=' + trigger_value);
     }
     if (!event_trigger_.empty()) {
-        result += event_trigger_;
-        result += ' ';
+        triggers.emplace_back(event_trigger_);
     }
-    result.pop_back();
-    return result;
+
+    return Join(triggers, " && ");
 }
 
 void Action::DumpState() const {
     std::string trigger_name = BuildTriggersString();
-    INFO("on %s\n", trigger_name.c_str());
+    LOG(INFO) << "on " << trigger_name;
 
     for (const auto& c : commands_) {
         std::string cmd_str = c.BuildCommandString();
-        INFO(" %s\n", cmd_str.c_str());
+        LOG(INFO) << "  " << cmd_str;
     }
-    INFO("\n");
 }
 
 class EventTrigger : public Trigger {
 public:
-    EventTrigger(const std::string& trigger) : trigger_(trigger) {
+    explicit EventTrigger(const std::string& trigger) : trigger_(trigger) {
     }
     bool CheckTriggers(const Action& action) const override {
         return action.CheckEventTrigger(trigger_);
@@ -288,7 +293,7 @@
 
 class BuiltinTrigger : public Trigger {
 public:
-    BuiltinTrigger(Action* action) : action_(action) {
+    explicit BuiltinTrigger(Action* action) : action_(action) {
     }
     bool CheckTriggers(const Action& action) const override {
         return action_ == &action;
@@ -366,7 +371,7 @@
 
     if (current_command_ == 0) {
         std::string trigger_name = action->BuildTriggersString();
-        INFO("processing action (%s)\n", trigger_name.c_str());
+        LOG(INFO) << "processing action (" << trigger_name << ")";
     }
 
     action->ExecuteOneCommand(current_command_);
@@ -395,7 +400,6 @@
     for (const auto& a : actions_) {
         a->DumpState();
     }
-    INFO("\n");
 }
 
 bool ActionParser::ParseSection(const std::vector<std::string>& args,
diff --git a/init/action.h b/init/action.h
index 6dee2d0..0bae9f0 100644
--- a/init/action.h
+++ b/init/action.h
@@ -44,7 +44,7 @@
 
 class Action {
 public:
-    Action(bool oneshot = false);
+    explicit Action(bool oneshot = false);
 
     bool AddCommand(const std::vector<std::string>& args,
                     const std::string& filename, int line, std::string* err);
diff --git a/init/bootchart.cpp b/init/bootchart.cpp
index 5704d28..beabea1 100644
--- a/init/bootchart.cpp
+++ b/init/bootchart.cpp
@@ -15,8 +15,6 @@
  */
 
 #include "bootchart.h"
-#include "log.h"
-#include "property_service.h"
 
 #include <dirent.h>
 #include <errno.h>
@@ -29,246 +27,171 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <chrono>
+#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>
 
-#define LOG_ROOT        "/data/bootchart"
-#define LOG_STAT        LOG_ROOT"/proc_stat.log"
-#define LOG_PROCS       LOG_ROOT"/proc_ps.log"
-#define LOG_DISK        LOG_ROOT"/proc_diskstats.log"
-#define LOG_HEADER      LOG_ROOT"/header"
-#define LOG_ACCT        LOG_ROOT"/kernel_pacct"
+using android::base::StringPrintf;
+using namespace std::chrono_literals;
 
-#define LOG_STARTFILE   LOG_ROOT"/start"
-#define LOG_STOPFILE    LOG_ROOT"/stop"
+static std::thread* g_bootcharting_thread;
 
-// Polling period in ms.
-static const int BOOTCHART_POLLING_MS = 200;
-
-// Max polling time in seconds.
-static const int BOOTCHART_MAX_TIME_SEC = 10*60;
-
-static long long g_last_bootchart_time;
-static int g_remaining_samples;
-
-static FILE* log_stat;
-static FILE* log_procs;
-static FILE* log_disks;
+static std::mutex g_bootcharting_finished_mutex;
+static std::condition_variable g_bootcharting_finished_cv;
+static bool g_bootcharting_finished;
 
 static long long get_uptime_jiffies() {
-    std::string uptime;
-    if (!android::base::ReadFileToString("/proc/uptime", &uptime)) {
-        return 0;
-    }
-    return 100LL * strtod(uptime.c_str(), NULL);
+  std::string uptime;
+  if (!android::base::ReadFileToString("/proc/uptime", &uptime)) return 0;
+  return 100LL * strtod(uptime.c_str(), NULL);
+}
+
+static std::unique_ptr<FILE, decltype(&fclose)> fopen_unique(const char* filename,
+                                                             const char* mode) {
+  std::unique_ptr<FILE, decltype(&fclose)> result(fopen(filename, mode), fclose);
+  if (!result) PLOG(ERROR) << "bootchart: failed to open " << filename;
+  return result;
 }
 
 static void log_header() {
-    char date[32];
-    time_t now_t = time(NULL);
-    struct tm now = *localtime(&now_t);
-    strftime(date, sizeof(date), "%F %T", &now);
+  char date[32];
+  time_t now_t = time(NULL);
+  struct tm now = *localtime(&now_t);
+  strftime(date, sizeof(date), "%F %T", &now);
 
-    utsname uts;
-    if (uname(&uts) == -1) {
-        return;
-    }
+  utsname uts;
+  if (uname(&uts) == -1) return;
 
-    std::string fingerprint = property_get("ro.build.fingerprint");
-    if (fingerprint.empty()) {
-        return;
-    }
+  std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "");
+  if (fingerprint.empty()) return;
 
-    std::string kernel_cmdline;
-    android::base::ReadFileToString("/proc/cmdline", &kernel_cmdline);
+  std::string kernel_cmdline;
+  android::base::ReadFileToString("/proc/cmdline", &kernel_cmdline);
 
-    FILE* out = fopen(LOG_HEADER, "we");
-    if (out == NULL) {
-        return;
-    }
-    fprintf(out, "version = Android init 0.8\n");
-    fprintf(out, "title = Boot chart for Android (%s)\n", date);
-    fprintf(out, "system.uname = %s %s %s %s\n", uts.sysname, uts.release, uts.version, uts.machine);
-    fprintf(out, "system.release = %s\n", fingerprint.c_str());
-    // TODO: use /proc/cpuinfo "model name" line for x86, "Processor" line for arm.
-    fprintf(out, "system.cpu = %s\n", uts.machine);
-    fprintf(out, "system.kernel.options = %s\n", kernel_cmdline.c_str());
-    fclose(out);
+  auto fp = fopen_unique("/data/bootchart/header", "we");
+  if (!fp) return;
+  fprintf(&*fp, "version = Android init 0.8\n");
+  fprintf(&*fp, "title = Boot chart for Android (%s)\n", date);
+  fprintf(&*fp, "system.uname = %s %s %s %s\n", uts.sysname, uts.release, uts.version, uts.machine);
+  fprintf(&*fp, "system.release = %s\n", fingerprint.c_str());
+  // TODO: use /proc/cpuinfo "model name" line for x86, "Processor" line for arm.
+  fprintf(&*fp, "system.cpu = %s\n", uts.machine);
+  fprintf(&*fp, "system.kernel.options = %s\n", kernel_cmdline.c_str());
 }
 
-static void do_log_uptime(FILE* log) {
-    fprintf(log, "%lld\n", get_uptime_jiffies());
+static void log_uptime(FILE* log) {
+  fprintf(log, "%lld\n", get_uptime_jiffies());
 }
 
-static void do_log_file(FILE* log, const char* procfile) {
-    do_log_uptime(log);
+static void log_file(FILE* log, const char* procfile) {
+  log_uptime(log);
 
-    std::string content;
-    if (android::base::ReadFileToString(procfile, &content)) {
-        fprintf(log, "%s\n", content.c_str());
-    }
+  std::string content;
+  if (android::base::ReadFileToString(procfile, &content)) {
+    fprintf(log, "%s\n", content.c_str());
+  }
 }
 
-static void do_log_procs(FILE* log) {
-    do_log_uptime(log);
+static void log_processes(FILE* log) {
+  log_uptime(log);
 
-    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir("/proc"), closedir);
-    struct dirent* entry;
-    while ((entry = readdir(dir.get())) != NULL) {
-        // Only match numeric values.
-        char* end;
-        int pid = strtol(entry->d_name, &end, 10);
-        if (end != NULL && end > entry->d_name && *end == 0) {
-            char filename[32];
+  std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir("/proc"), closedir);
+  struct dirent* entry;
+  while ((entry = readdir(dir.get())) != NULL) {
+    // Only match numeric values.
+    int pid = atoi(entry->d_name);
+    if (pid == 0) continue;
 
-            // /proc/<pid>/stat only has truncated task names, so get the full
-            // name from /proc/<pid>/cmdline.
-            snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
-            std::string cmdline;
-            android::base::ReadFileToString(filename, &cmdline);
-            const char* full_name = cmdline.c_str(); // So we stop at the first NUL.
+    // /proc/<pid>/stat only has truncated task names, so get the full
+    // name from /proc/<pid>/cmdline.
+    std::string cmdline;
+    android::base::ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline);
+    const char* full_name = cmdline.c_str(); // So we stop at the first NUL.
 
-            // Read process stat line.
-            snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
-            std::string stat;
-            if (android::base::ReadFileToString(filename, &stat)) {
-                if (!cmdline.empty()) {
-                    // Substitute the process name with its real name.
-                    size_t open = stat.find('(');
-                    size_t close = stat.find_last_of(')');
-                    if (open != std::string::npos && close != std::string::npos) {
-                        stat.replace(open + 1, close - open - 1, full_name);
-                    }
-                }
-                fputs(stat.c_str(), log);
-            }
+    // Read process stat line.
+    std::string stat;
+    if (android::base::ReadFileToString(StringPrintf("/proc/%d/stat", pid), &stat)) {
+      if (!cmdline.empty()) {
+        // Substitute the process name with its real name.
+        size_t open = stat.find('(');
+        size_t close = stat.find_last_of(')');
+        if (open != std::string::npos && close != std::string::npos) {
+          stat.replace(open + 1, close - open - 1, full_name);
         }
+      }
+      fputs(stat.c_str(), log);
     }
+  }
 
-    fputc('\n', log);
+  fputc('\n', log);
 }
 
-static int bootchart_init() {
-    int timeout = 0;
+static void bootchart_thread_main() {
+  LOG(INFO) << "Bootcharting started";
 
-    std::string start;
-    android::base::ReadFileToString(LOG_STARTFILE, &start);
-    if (!start.empty()) {
-        timeout = atoi(start.c_str());
-    } else {
-        // When running with emulator, androidboot.bootchart=<timeout>
-        // might be passed by as kernel parameters to specify the bootchart
-        // timeout. this is useful when using -wipe-data since the /data
-        // partition is fresh.
-        std::string cmdline;
-        const char* s;
-        android::base::ReadFileToString("/proc/cmdline", &cmdline);
-#define KERNEL_OPTION  "androidboot.bootchart="
-        if ((s = strstr(cmdline.c_str(), KERNEL_OPTION)) != NULL) {
-            timeout = atoi(s + sizeof(KERNEL_OPTION) - 1);
-        }
-    }
-    if (timeout == 0)
-        return 0;
+  // Open log files.
+  auto stat_log = fopen_unique("/data/bootchart/proc_stat.log", "we");
+  if (!stat_log) return;
+  auto proc_log = fopen_unique("/data/bootchart/proc_ps.log", "we");
+  if (!proc_log) return;
+  auto disk_log = fopen_unique("/data/bootchart/proc_diskstats.log", "we");
+  if (!disk_log) return;
 
-    if (timeout > BOOTCHART_MAX_TIME_SEC)
-        timeout = BOOTCHART_MAX_TIME_SEC;
+  log_header();
 
-    int count = (timeout*1000 + BOOTCHART_POLLING_MS-1)/BOOTCHART_POLLING_MS;
-
-    log_stat = fopen(LOG_STAT, "we");
-    if (log_stat == NULL) {
-        return -1;
-    }
-    log_procs = fopen(LOG_PROCS, "we");
-    if (log_procs == NULL) {
-        fclose(log_stat);
-        return -1;
-    }
-    log_disks = fopen(LOG_DISK, "we");
-    if (log_disks == NULL) {
-        fclose(log_stat);
-        fclose(log_procs);
-        return -1;
+  while (true) {
+    {
+      std::unique_lock<std::mutex> lock(g_bootcharting_finished_mutex);
+      g_bootcharting_finished_cv.wait_for(lock, 200ms);
+      if (g_bootcharting_finished) break;
     }
 
-    // Create kernel process accounting file.
-    close(open(LOG_ACCT, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644));
-    acct(LOG_ACCT);
+    log_file(&*stat_log, "/proc/stat");
+    log_file(&*disk_log, "/proc/diskstats");
+    log_processes(&*proc_log);
+  }
 
-    log_header();
-    return count;
+  LOG(INFO) << "Bootcharting finished";
 }
 
-int do_bootchart_init(const std::vector<std::string>& args) {
-    g_remaining_samples = bootchart_init();
-    if (g_remaining_samples < 0) {
-        ERROR("Bootcharting init failure: %s\n", strerror(errno));
-    } else if (g_remaining_samples > 0) {
-        NOTICE("Bootcharting started (will run for %d s).\n",
-               (g_remaining_samples * BOOTCHART_POLLING_MS) / 1000);
-    } else {
-        NOTICE("Not bootcharting.\n");
-    }
+static int do_bootchart_start() {
+  // We don't care about the content, but we do care that /data/bootchart/enabled actually exists.
+  std::string start;
+  if (!android::base::ReadFileToString("/data/bootchart/enabled", &start)) {
+    LOG(VERBOSE) << "Not bootcharting";
     return 0;
+  }
+
+  g_bootcharting_thread = new std::thread(bootchart_thread_main);
+  return 0;
 }
 
-static int bootchart_step() {
-    do_log_file(log_stat,   "/proc/stat");
-    do_log_file(log_disks,  "/proc/diskstats");
-    do_log_procs(log_procs);
+static int do_bootchart_stop() {
+  if (!g_bootcharting_thread) return 0;
 
-    // Stop if /data/bootchart/stop contains 1.
-    std::string stop;
-    if (android::base::ReadFileToString(LOG_STOPFILE, &stop) && stop == "1") {
-        return -1;
-    }
+  // Tell the worker thread it's time to quit.
+  {
+    std::lock_guard<std::mutex> lock(g_bootcharting_finished_mutex);
+    g_bootcharting_finished = true;
+    g_bootcharting_finished_cv.notify_one();
+  }
 
-    return 0;
+  g_bootcharting_thread->join();
+  delete g_bootcharting_thread;
+  g_bootcharting_thread = nullptr;
+  return 0;
 }
 
-/* called to get time (in ms) used by bootchart */
-static long long bootchart_gettime() {
-    return 10LL*get_uptime_jiffies();
-}
-
-static void bootchart_finish() {
-    unlink(LOG_STOPFILE);
-    fclose(log_stat);
-    fclose(log_disks);
-    fclose(log_procs);
-    acct(NULL);
-}
-
-void bootchart_sample(int* timeout) {
-    // Do we have any more bootcharting to do?
-    if (g_remaining_samples <= 0) {
-        return;
-    }
-
-    long long current_time = bootchart_gettime();
-    int elapsed_time = current_time - g_last_bootchart_time;
-
-    if (elapsed_time >= BOOTCHART_POLLING_MS) {
-        /* count missed samples */
-        while (elapsed_time >= BOOTCHART_POLLING_MS) {
-            elapsed_time -= BOOTCHART_POLLING_MS;
-            g_remaining_samples--;
-        }
-        /* count may be negative, take a sample anyway */
-        g_last_bootchart_time = current_time;
-        if (bootchart_step() < 0 || g_remaining_samples <= 0) {
-            bootchart_finish();
-            g_remaining_samples = 0;
-        }
-    }
-    if (g_remaining_samples > 0) {
-        int remaining_time = BOOTCHART_POLLING_MS - elapsed_time;
-        if (*timeout < 0 || *timeout > remaining_time) {
-            *timeout = remaining_time;
-        }
-    }
+int do_bootchart(const std::vector<std::string>& args) {
+  if (args[1] == "start") return do_bootchart_start();
+  return do_bootchart_stop();
 }
diff --git a/init/bootchart.h b/init/bootchart.h
index 47eda7a..0e3593d 100644
--- a/init/bootchart.h
+++ b/init/bootchart.h
@@ -20,7 +20,6 @@
 #include <string>
 #include <vector>
 
-int do_bootchart_init(const std::vector<std::string>& args);
-void bootchart_sample(int* timeout);
+int do_bootchart(const std::vector<std::string>& args);
 
 #endif /* _BOOTCHART_H */
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 44217f0..7ee02d0 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -36,21 +36,26 @@
 #include <sys/wait.h>
 #include <unistd.h>
 #include <linux/loop.h>
-#include <ext4_crypt.h>
-#include <ext4_crypt_init_extensions.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/parseint.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 <fs_mgr.h>
 #include <logwrap/logwrap.h>
-#include <private/android_filesystem_config.h>
 
 #include "action.h"
 #include "bootchart.h"
@@ -59,25 +64,26 @@
 #include "init_parser.h"
 #include "log.h"
 #include "property_service.h"
+#include "reboot.h"
 #include "service.h"
 #include "signal_handler.h"
 #include "util.h"
 
+using namespace std::literals::string_literals;
+
 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
-#define UNMOUNT_CHECK_MS 5000
-#define UNMOUNT_CHECK_TIMES 10
 
-static const int kTerminateServiceDelayMicroSeconds = 50000;
+static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
 
-static int insmod(const char *filename, const char *options) {
+static int insmod(const char *filename, const char *options, int flags) {
     int fd = open(filename, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
     if (fd == -1) {
-        ERROR("insmod: open(\"%s\") failed: %s", filename, strerror(errno));
+        PLOG(ERROR) << "insmod: open(\"" << filename << "\") failed";
         return -1;
     }
-    int rc = syscall(__NR_finit_module, fd, options, 0);
+    int rc = syscall(__NR_finit_module, fd, options, flags);
     if (rc == -1) {
-        ERROR("finit_module for \"%s\" failed: %s", filename, strerror(errno));
+        PLOG(ERROR) << "finit_module for \"" << filename << "\" failed";
     }
     close(fd);
     return rc;
@@ -110,118 +116,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 wipe_data_via_recovery(const std::string& reason) {
-    const std::vector<std::string> options = {"--wipe_data", std::string() + "--reason=" + reason};
+static int reboot_into_recovery(const std::vector<std::string>& options) {
     std::string err;
     if (!write_bootloader_message(options, &err)) {
-        ERROR("failed to set bootloader message: %s", err.c_str());
+        LOG(ERROR) << "failed to set bootloader message: " << err;
         return -1;
     }
-    android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-    while (1) { pause(); }  // never reached
-}
-
-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.
-             */
-            TEMP_FAILURE_RETRY(
-                usleep(UNMOUNT_CHECK_MS * 1000 / 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(ARRAY_SIZE(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(ARRAY_SIZE(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) {
@@ -246,8 +148,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());
+    return write_file("/proc/sys/kernel/domainname", args[1]) ? 0 : 1;
 }
 
 static int do_enable(const std::vector<std::string>& args) {
@@ -259,15 +167,11 @@
 }
 
 static int do_exec(const std::vector<std::string>& args) {
-    Service* svc = ServiceManager::GetInstance().MakeExecOneshotService(args);
-    if (!svc) {
-        return -1;
-    }
-    if (!svc->Start()) {
-        return -1;
-    }
-    waiting_for_exec = true;
-    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) {
@@ -275,7 +179,7 @@
 }
 
 static int do_hostname(const std::vector<std::string>& args) {
-    return write_file("/proc/sys/kernel/hostname", args[1].c_str());
+    return write_file("/proc/sys/kernel/hostname", args[1]) ? 0 : 1;
 }
 
 static int do_ifup(const std::vector<std::string>& args) {
@@ -283,17 +187,17 @@
 }
 
 static int do_insmod(const std::vector<std::string>& args) {
-    std::string options;
+    int flags = 0;
+    auto it = args.begin() + 1;
 
-    if (args.size() > 2) {
-        options += args[2];
-        for (std::size_t i = 3; i < args.size(); ++i) {
-            options += ' ';
-            options += args[i];
-        }
+    if (!(*it).compare("-f")) {
+        flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
+        it++;
     }
 
-    return insmod(args[1].c_str(), options.c_str());
+    std::string filename = *it++;
+    std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
+    return insmod(filename.c_str(), options.c_str(), flags);
 }
 
 static int do_mkdir(const std::vector<std::string>& args) {
@@ -303,7 +207,7 @@
     /* mkdir <path> [mode] [owner] [group] */
 
     if (args.size() >= 3) {
-        mode = std::stoul(args[2], 0, 8);
+        mode = std::strtoul(args[2].c_str(), 0, 8);
     }
 
     ret = make_dir(args[1].c_str(), mode);
@@ -338,7 +242,10 @@
 
     if (e4crypt_is_native()) {
         if (e4crypt_set_directory_policy(args[1].c_str())) {
-            wipe_data_via_recovery(std::string() + "set_policy_failed:" + args[1]);
+            const std::vector<std::string> options = {
+                "--prompt_and_wipe_data",
+                "--reason=set_policy_failed:"s + args[1]};
+            reboot_into_recovery(options);
             return -1;
         }
     }
@@ -405,22 +312,7 @@
     source = args[2].c_str();
     target = args[3].c_str();
 
-    if (!strncmp(source, "mtd@", 4)) {
-        n = mtd_name_to_number(source + 4);
-        if (n < 0) {
-            return -1;
-        }
-
-        snprintf(tmp, sizeof(tmp), "/dev/block/mtdblock%d", n);
-
-        if (wait)
-            wait_for_file(tmp, COMMAND_RETRY_TIMEOUT);
-        if (mount(tmp, target, system, flags, options) < 0) {
-            return -1;
-        }
-
-        goto exit_success;
-    } else if (!strncmp(source, "loop@", 5)) {
+    if (!strncmp(source, "loop@", 5)) {
         int mode, loop, fd;
         struct loop_info info;
 
@@ -459,11 +351,11 @@
         }
 
         close(fd);
-        ERROR("out of loopback devices");
+        LOG(ERROR) << "out of loopback devices";
         return -1;
     } else {
         if (wait)
-            wait_for_file(source, COMMAND_RETRY_TIMEOUT);
+            wait_for_file(source, kCommandRetryTimeout);
         if (mount(source, target, system, flags, options) < 0) {
             return -1;
         }
@@ -482,21 +374,28 @@
 static void import_late(const std::vector<std::string>& args, size_t start_index, size_t end_index) {
     Parser& parser = Parser::GetInstance();
     if (end_index <= start_index) {
-        // Use the default set if no path is given
-        static const std::vector<std::string> init_directories = {
-            "/system/etc/init",
-            "/vendor/etc/init",
-            "/odm/etc/init"
-        };
-
-        for (const auto& dir : init_directories) {
-            parser.ParseConfig(dir);
+        // Fallbacks for partitions on which early mount isn't enabled.
+        if (!parser.is_system_etc_init_loaded()) {
+            parser.ParseConfig("/system/etc/init");
+            parser.set_is_system_etc_init_loaded(true);
+        }
+        if (!parser.is_vendor_etc_init_loaded()) {
+            parser.ParseConfig("/vendor/etc/init");
+            parser.set_is_vendor_etc_init_loaded(true);
+        }
+        if (!parser.is_odm_etc_init_loaded()) {
+            parser.ParseConfig("/odm/etc/init");
+            parser.set_is_odm_etc_init_loaded(true);
         }
     } else {
         for (size_t i = start_index; i < end_index; ++i) {
             parser.ParseConfig(args[i]);
         }
     }
+
+    // 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();
 }
 
 /* mount_fstab
@@ -504,11 +403,7 @@
  *  Call fs_mgr_mount_all() to mount the given fstab
  */
 static int mount_fstab(const char* fstabfile, int mount_mode) {
-    pid_t pid;
     int ret = -1;
-    int child_ret = -1;
-    int status;
-    struct fstab *fstab;
 
     /*
      * Call fs_mgr_mount_all() to mount all filesystems.  We fork(2) and
@@ -516,13 +411,14 @@
      * process if anything goes wrong (crash or memory leak), and wait for
      * the child to finish in the parent.
      */
-    pid = fork();
+    pid_t pid = fork();
     if (pid > 0) {
         /* Parent.  Wait for the child to return */
+        int status;
         int wp_ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
-        if (wp_ret < 0) {
-            /* Unexpected error code. We will continue anyway. */
-            NOTICE("waitpid failed rc=%d: %s\n", wp_ret, strerror(errno));
+        if (wp_ret == -1) {
+            // Unexpected error code. We will continue anyway.
+            PLOG(WARNING) << "waitpid failed";
         }
 
         if (WIFEXITED(status)) {
@@ -532,12 +428,16 @@
         }
     } else if (pid == 0) {
         /* child, call fs_mgr_mount_all() */
-        klog_set_level(6);  /* So we can see what fs_mgr_mount_all() does */
-        fstab = fs_mgr_read_fstab(fstabfile);
-        child_ret = fs_mgr_mount_all(fstab, mount_mode);
+
+        // So we can always see what fs_mgr_mount_all() does.
+        // Only needed if someone explicitly changes the default log level in their init.rc.
+        android::base::ScopedLogSeverity info(android::base::INFO);
+
+        struct fstab* fstab = fs_mgr_read_fstab(fstabfile);
+        int child_ret = fs_mgr_mount_all(fstab, mount_mode);
         fs_mgr_free_fstab(fstab);
         if (child_ret == -1) {
-            ERROR("fs_mgr_mount_all returned an error\n");
+            PLOG(ERROR) << "fs_mgr_mount_all returned an error";
         }
         _exit(child_ret);
     } else {
@@ -572,8 +472,9 @@
         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
     } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
         /* Setup a wipe via recovery, and reboot into recovery */
-        ERROR("fs_mgr_mount_all suggested recovery, so wiping data via recovery.\n");
-        ret = wipe_data_via_recovery("wipe_data_via_recovery");
+        PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
+        const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
+        ret = reboot_into_recovery(options);
         /* If reboot worked, there is no return. */
     } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) {
         if (e4crypt_install_keyring()) {
@@ -586,7 +487,7 @@
         // do anything different from the nonencrypted case.
         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
     } else if (code > 0) {
-        ERROR("fs_mgr_mount_all returned unexpected error %d\n", code);
+        PLOG(ERROR) << "fs_mgr_mount_all returned unexpected error " << code;
     }
     /* else ... < 0: error */
 
@@ -605,20 +506,27 @@
     int mount_mode = MOUNT_MODE_DEFAULT;
     const char* fstabfile = args[1].c_str();
     std::size_t path_arg_end = args.size();
+    const char* prop_post_fix = "default";
 
     for (na = args.size() - 1; na > 1; --na) {
         if (args[na] == "--early") {
-             path_arg_end = na;
-             queue_event = false;
-             mount_mode = MOUNT_MODE_EARLY;
+            path_arg_end = na;
+            queue_event = false;
+            mount_mode = MOUNT_MODE_EARLY;
+            prop_post_fix = "early";
         } else if (args[na] == "--late") {
             path_arg_end = na;
             import_rc = false;
             mount_mode = MOUNT_MODE_LATE;
+            prop_post_fix = "late";
         }
     }
 
+    std::string prop_name = android::base::StringPrintf("ro.boottime.init.mount_all.%s",
+                                                        prop_post_fix);
+    Timer t;
     int ret =  mount_fstab(fstabfile, mount_mode);
+    property_set(prop_name.c_str(), std::to_string(t.duration_ms()).c_str());
 
     if (import_rc) {
         /* Paths of .rc files are specified at the 2nd argument and beyond */
@@ -655,16 +563,19 @@
 static int do_setrlimit(const std::vector<std::string>& args) {
     struct rlimit limit;
     int resource;
-    resource = std::stoi(args[1]);
-    limit.rlim_cur = std::stoi(args[2]);
-    limit.rlim_max = std::stoi(args[3]);
-    return setrlimit(resource, &limit);
+    if (android::base::ParseInt(args[1], &resource) &&
+        android::base::ParseUint(args[2], &limit.rlim_cur) &&
+        android::base::ParseUint(args[3], &limit.rlim_max)) {
+        return setrlimit(resource, &limit);
+    }
+    LOG(WARNING) << "ignoring setrlimit " << args[1] << " " << args[2] << " " << args[3];
+    return -1;
 }
 
 static int do_start(const std::vector<std::string>& args) {
     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
     if (!svc) {
-        ERROR("do_start: Service %s not found\n", args[1].c_str());
+        LOG(ERROR) << "do_start: Service " << args[1] << " not found";
         return -1;
     }
     if (!svc->Start())
@@ -675,7 +586,7 @@
 static int do_stop(const std::vector<std::string>& args) {
     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
     if (!svc) {
-        ERROR("do_stop: Service %s not found\n", args[1].c_str());
+        LOG(ERROR) << "do_stop: Service " << args[1] << " not found";
         return -1;
     }
     svc->Stop();
@@ -685,85 +596,13 @@
 static int do_restart(const std::vector<std::string>& args) {
     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
     if (!svc) {
-        ERROR("do_restart: Service %s not found\n", args[1].c_str());
+        LOG(ERROR) << "do_restart: Service " << args[1] << " not found";
         return -1;
     }
     svc->Restart();
     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 {
-        ERROR("powerctl: unrecognized command '%s'\n", 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];
-        }
-    } else if (command[len] != '\0') {
-        ERROR("powerctl: unrecognized reboot target '%s'\n", &command[len]);
-        return -EINVAL;
-    }
-
-    std::string timeout = property_get("ro.build.shutdown_timeout");
-    unsigned int delay = 0;
-
-    if (android::base::ParseUint(timeout.c_str(), &delay) && delay > 0) {
-        Timer t;
-        // Ask all services to terminate.
-        ServiceManager::GetInstance().ForEachService(
-            [] (Service* s) { s->Terminate(); });
-
-        while (t.duration() < 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.
-            usleep(kTerminateServiceDelayMicroSeconds);
-        }
-        NOTICE("Terminating running services took %.02f seconds", t.duration());
-    }
-
-    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;
@@ -782,22 +621,20 @@
 }
 
 static int do_sysclktz(const std::vector<std::string>& args) {
-    struct timezone tz;
-
-    memset(&tz, 0, sizeof(tz));
-    tz.tz_minuteswest = std::stoi(args[1]);
-    if (settimeofday(NULL, &tz))
-        return -1;
-    return 0;
+    struct timezone tz = {};
+    if (android::base::ParseInt(args[1], &tz.tz_minuteswest) && settimeofday(NULL, &tz) != -1) {
+        return 0;
+    }
+    return -1;
 }
 
 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,
@@ -807,71 +644,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);
+    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) {
@@ -913,34 +698,70 @@
 static int do_restorecon(const std::vector<std::string>& args) {
     int ret = 0;
 
-    for (auto it = std::next(args.begin()); it != args.end(); ++it) {
-        if (restorecon(it->c_str()) < 0)
-            ret = -errno;
-    }
-    return ret;
-}
+    struct flag_type {const char* name; int value;};
+    static const flag_type flags[] = {
+        {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE},
+        {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE},
+        {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS},
+        {0, 0}
+    };
 
-static int do_restorecon_recursive(const std::vector<std::string>& args) {
-    int ret = 0;
+    int flag = 0;
 
-    for (auto it = std::next(args.begin()); it != args.end(); ++it) {
-        /* The contents of CE paths are encrypted on FBE devices until user
-         * credentials are presented (filenames inside are mangled), so we need
-         * to delay restorecon of those until vold explicitly requests it. */
-        if (restorecon_recursive_skipce(it->c_str()) < 0) {
-            ret = -errno;
+    bool in_flags = true;
+    for (size_t i = 1; i < args.size(); ++i) {
+        if (android::base::StartsWith(args[i], "--")) {
+            if (!in_flags) {
+                LOG(ERROR) << "restorecon - flags must precede paths";
+                return -1;
+            }
+            bool found = false;
+            for (size_t j = 0; flags[j].name; ++j) {
+                if (args[i] == flags[j].name) {
+                    flag |= flags[j].value;
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) {
+                LOG(ERROR) << "restorecon - bad flag " << args[i];
+                return -1;
+            }
+        } else {
+            in_flags = false;
+            if (restorecon(args[i].c_str(), flag) < 0) {
+                ret = -errno;
+            }
         }
     }
     return ret;
 }
 
+static int do_restorecon_recursive(const std::vector<std::string>& args) {
+    std::vector<std::string> non_const_args(args);
+    non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
+    return do_restorecon(non_const_args);
+}
+
 static int do_loglevel(const std::vector<std::string>& args) {
-    int log_level = std::stoi(args[1]);
-    if (log_level < KLOG_ERROR_LEVEL || log_level > KLOG_DEBUG_LEVEL) {
-        ERROR("loglevel: invalid log level'%d'\n", log_level);
-        return -EINVAL;
+    // TODO: support names instead/as well?
+    int log_level = -1;
+    android::base::ParseInt(args[1], &log_level);
+    android::base::LogSeverity severity;
+    switch (log_level) {
+        case 7: severity = android::base::DEBUG; break;
+        case 6: severity = android::base::INFO; break;
+        case 5:
+        case 4: severity = android::base::WARNING; break;
+        case 3: severity = android::base::ERROR; break;
+        case 2:
+        case 1:
+        case 0: severity = android::base::FATAL; break;
+        default:
+            LOG(ERROR) << "loglevel: invalid log level " << log_level;
+            return -EINVAL;
     }
-    klog_set_level(log_level);
+    android::base::SetMinimumLogSeverity(severity);
     return 0;
 }
 
@@ -956,11 +777,37 @@
 
 static int do_wait(const std::vector<std::string>& args) {
     if (args.size() == 2) {
-        return wait_for_file(args[1].c_str(), COMMAND_RETRY_TIMEOUT);
+        return wait_for_file(args[1].c_str(), kCommandRetryTimeout);
     } else if (args.size() == 3) {
-        return wait_for_file(args[1].c_str(), std::stoi(args[2]));
-    } else
+        int timeout;
+        if (android::base::ParseInt(args[2], &timeout)) {
+            return wait_for_file(args[1].c_str(), std::chrono::seconds(timeout));
+        }
+    }
+    return -1;
+}
+
+static int do_wait_for_prop(const std::vector<std::string>& args) {
+    const char* name = args[1].c_str();
+    const char* value = args[2].c_str();
+    size_t value_len = strlen(value);
+
+    if (!is_legal_property_name(name)) {
+        LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
+                   << "\") failed: bad name";
         return -1;
+    }
+    if (value_len >= PROP_VALUE_MAX) {
+        LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
+                   << "\") failed: value too long";
+        return -1;
+    }
+    if (!start_waiting_for_property(name, value)) {
+        LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
+                   << "\") failed: init already in waiting";
+        return -1;
+    }
+    return 0;
 }
 
 /*
@@ -975,16 +822,21 @@
 }
 
 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) {
@@ -993,17 +845,20 @@
 
 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_init",          {0,     0,    do_bootchart_init}},
+        {"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}},
@@ -1017,7 +872,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}},
@@ -1034,7 +888,9 @@
         {"verity_load_state",       {0,     0,    do_verity_load_state}},
         {"verity_update_state",     {0,     0,    do_verity_update_state}},
         {"wait",                    {1,     2,    do_wait}},
+        {"wait_for_prop",           {2,     2,    do_wait_for_prop}},
         {"write",                   {2,     2,    do_write}},
     };
+    // clang-format on
     return builtin_functions;
 }
diff --git a/init/capabilities.cpp b/init/capabilities.cpp
new file mode 100644
index 0000000..b8a9ec0
--- /dev/null
+++ b/init/capabilities.cpp
@@ -0,0 +1,194 @@
+// 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 "capabilities.h"
+
+#include <sys/capability.h>
+#include <sys/prctl.h>
+
+#include <map>
+#include <memory>
+
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+
+#define CAP_MAP_ENTRY(cap) { #cap, CAP_##cap }
+
+static const std::map<std::string, int> cap_map = {
+    CAP_MAP_ENTRY(CHOWN),
+    CAP_MAP_ENTRY(DAC_OVERRIDE),
+    CAP_MAP_ENTRY(DAC_READ_SEARCH),
+    CAP_MAP_ENTRY(FOWNER),
+    CAP_MAP_ENTRY(FSETID),
+    CAP_MAP_ENTRY(KILL),
+    CAP_MAP_ENTRY(SETGID),
+    CAP_MAP_ENTRY(SETUID),
+    CAP_MAP_ENTRY(SETPCAP),
+    CAP_MAP_ENTRY(LINUX_IMMUTABLE),
+    CAP_MAP_ENTRY(NET_BIND_SERVICE),
+    CAP_MAP_ENTRY(NET_BROADCAST),
+    CAP_MAP_ENTRY(NET_ADMIN),
+    CAP_MAP_ENTRY(NET_RAW),
+    CAP_MAP_ENTRY(IPC_LOCK),
+    CAP_MAP_ENTRY(IPC_OWNER),
+    CAP_MAP_ENTRY(SYS_MODULE),
+    CAP_MAP_ENTRY(SYS_RAWIO),
+    CAP_MAP_ENTRY(SYS_CHROOT),
+    CAP_MAP_ENTRY(SYS_PTRACE),
+    CAP_MAP_ENTRY(SYS_PACCT),
+    CAP_MAP_ENTRY(SYS_ADMIN),
+    CAP_MAP_ENTRY(SYS_BOOT),
+    CAP_MAP_ENTRY(SYS_NICE),
+    CAP_MAP_ENTRY(SYS_RESOURCE),
+    CAP_MAP_ENTRY(SYS_TIME),
+    CAP_MAP_ENTRY(SYS_TTY_CONFIG),
+    CAP_MAP_ENTRY(MKNOD),
+    CAP_MAP_ENTRY(LEASE),
+    CAP_MAP_ENTRY(AUDIT_WRITE),
+    CAP_MAP_ENTRY(AUDIT_CONTROL),
+    CAP_MAP_ENTRY(SETFCAP),
+    CAP_MAP_ENTRY(MAC_OVERRIDE),
+    CAP_MAP_ENTRY(MAC_ADMIN),
+    CAP_MAP_ENTRY(SYSLOG),
+    CAP_MAP_ENTRY(WAKE_ALARM),
+    CAP_MAP_ENTRY(BLOCK_SUSPEND),
+    CAP_MAP_ENTRY(AUDIT_READ),
+};
+
+static_assert(CAP_LAST_CAP == CAP_AUDIT_READ, "CAP_LAST_CAP is not CAP_AUDIT_READ");
+
+static bool ComputeCapAmbientSupported() {
+    return prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_CHOWN, 0, 0) >= 0;
+}
+
+static unsigned int ComputeLastValidCap() {
+    // Android does not support kernels < 3.8. 'CAP_WAKE_ALARM' has been present since 3.0, see
+    // http://lxr.free-electrons.com/source/include/linux/capability.h?v=3.0#L360.
+    unsigned int last_valid_cap = CAP_WAKE_ALARM;
+    for (; prctl(PR_CAPBSET_READ, last_valid_cap, 0, 0, 0) >= 0; ++last_valid_cap);
+
+    // |last_valid_cap| will be the first failing value.
+    return last_valid_cap - 1;
+}
+
+static bool DropBoundingSet(const CapSet& to_keep) {
+    unsigned int last_valid_cap = GetLastValidCap();
+    // When dropping the bounding set, attempt to drop capabilities reported at
+    // run-time, not at compile-time.
+    // If the run-time kernel is older than the compile-time headers, this
+    // avoids dropping an invalid capability. If the run-time kernel is newer
+    // than the headers, this guarantees all capabilities (even those unknown at
+    // compile time) will be dropped.
+    for (size_t cap = 0; cap <= last_valid_cap; ++cap) {
+        if (cap < to_keep.size() && to_keep.test(cap)) {
+            // No need to drop this capability.
+            continue;
+        }
+        if (cap_drop_bound(cap) == -1) {
+            PLOG(ERROR) << "cap_drop_bound(" << cap << ") failed";
+            return false;
+        }
+    }
+    return true;
+}
+
+static bool SetProcCaps(const CapSet& to_keep, bool add_setpcap) {
+    cap_t caps = cap_init();
+    auto deleter = [](cap_t* p) { cap_free(*p); };
+    std::unique_ptr<cap_t, decltype(deleter)> ptr_caps(&caps, deleter);
+
+    cap_clear(caps);
+    cap_value_t value[1];
+    for (size_t cap = 0; cap < to_keep.size(); ++cap) {
+        if (to_keep.test(cap)) {
+            value[0] = cap;
+            if (cap_set_flag(caps, CAP_INHERITABLE, arraysize(value), value, CAP_SET) != 0 ||
+                cap_set_flag(caps, CAP_PERMITTED, arraysize(value), value, CAP_SET) != 0) {
+                PLOG(ERROR) << "cap_set_flag(INHERITABLE|PERMITTED, " << cap << ") failed";
+                return false;
+            }
+        }
+    }
+
+    if (add_setpcap) {
+        value[0] = CAP_SETPCAP;
+        if (cap_set_flag(caps, CAP_PERMITTED, arraysize(value), value, CAP_SET) != 0 ||
+            cap_set_flag(caps, CAP_EFFECTIVE, arraysize(value), value, CAP_SET) != 0) {
+            PLOG(ERROR) << "cap_set_flag(PERMITTED|EFFECTIVE, " << CAP_SETPCAP << ") failed";
+            return false;
+        }
+    }
+
+    if (cap_set_proc(caps) != 0) {
+        PLOG(ERROR) << "cap_set_proc(" << to_keep.to_ulong() << ") failed";
+        return false;
+    }
+    return true;
+}
+
+static bool SetAmbientCaps(const CapSet& to_raise) {
+    for (size_t cap = 0; cap < to_raise.size(); ++cap) {
+        if (to_raise.test(cap)) {
+            if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0) != 0) {
+                PLOG(ERROR) << "prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, " << cap << ") failed";
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+int LookupCap(const std::string& cap_name) {
+    auto e = cap_map.find(cap_name);
+    if (e != cap_map.end()) {
+        return e->second;
+    } else {
+        return -1;
+    }
+}
+
+bool CapAmbientSupported() {
+    static bool cap_ambient_supported = ComputeCapAmbientSupported();
+    return cap_ambient_supported;
+}
+
+unsigned int GetLastValidCap() {
+    static unsigned int last_valid_cap = ComputeLastValidCap();
+    return last_valid_cap;
+}
+
+bool SetCapsForExec(const CapSet& to_keep) {
+    // Need to keep SETPCAP to drop bounding set below.
+    bool add_setpcap = true;
+    if (!SetProcCaps(to_keep, add_setpcap)) {
+        LOG(ERROR) << "failed to apply initial capset";
+        return false;
+    }
+
+    if (!DropBoundingSet(to_keep)) {
+        return false;
+    }
+
+    // If SETPCAP wasn't specifically requested, drop it now.
+    add_setpcap = false;
+    if (!SetProcCaps(to_keep, add_setpcap)) {
+        LOG(ERROR) << "failed to apply final capset";
+        return false;
+    }
+
+    // Add the capabilities to the ambient set so that they are preserved across
+    // execve(2).
+    // See http://man7.org/linux/man-pages/man7/capabilities.7.html.
+    return SetAmbientCaps(to_keep);
+}
diff --git a/init/capabilities.h b/init/capabilities.h
new file mode 100644
index 0000000..abd7fb2
--- /dev/null
+++ b/init/capabilities.h
@@ -0,0 +1,30 @@
+// 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 _INIT_CAPABILITIES_H
+#define _INIT_CAPABILITIES_H
+
+#include <linux/capability.h>
+
+#include <bitset>
+#include <string>
+
+using CapSet = std::bitset<CAP_LAST_CAP + 1>;
+
+int LookupCap(const std::string& cap_name);
+bool CapAmbientSupported();
+unsigned int GetLastValidCap();
+bool SetCapsForExec(const CapSet& to_keep);
+
+#endif  // _INIT_CAPABILITIES_H
diff --git a/init/descriptors.cpp b/init/descriptors.cpp
new file mode 100644
index 0000000..6e457cd
--- /dev/null
+++ b/init/descriptors.cpp
@@ -0,0 +1,125 @@
+/*
+ * 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 "descriptors.h"
+
+#include <ctype.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.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,
+                               gid_t gid, int perm, const std::string& context)
+        : name_(name), type_(type), uid_(uid), gid_(gid), perm_(perm), context_(context) {
+}
+
+DescriptorInfo::~DescriptorInfo() {
+}
+
+std::ostream& operator<<(std::ostream& os, const DescriptorInfo& info) {
+  return os << "  descriptors " << info.name_ << " " << info.type_ << " " << std::oct << info.perm_;
+}
+
+bool DescriptorInfo::operator==(const DescriptorInfo& other) const {
+  return name_ == other.name_ && type_ == other.type_ && key() == other.key();
+}
+
+void DescriptorInfo::CreateAndPublish(const std::string& globalContext) const {
+  // Create
+  const std::string& contextStr = context_.empty() ? globalContext : context_;
+  int fd = Create(contextStr);
+  if (fd < 0) return;
+
+  // Publish
+  std::string publishedName = key() + name_;
+  std::for_each(publishedName.begin(), publishedName.end(),
+                [] (char& c) { c = isalnum(c) ? c : '_'; });
+
+  std::string val = android::base::StringPrintf("%d", fd);
+  add_environment(publishedName.c_str(), val.c_str());
+
+  // make sure we don't close on exec
+  fcntl(fd, F_SETFD, 0);
+}
+
+void DescriptorInfo::Clean() const {
+}
+
+SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
+                       gid_t gid, int perm, const std::string& context)
+        : DescriptorInfo(name, type, uid, gid, perm, context) {
+}
+
+void SocketInfo::Clean() const {
+  unlink(android::base::StringPrintf(ANDROID_SOCKET_DIR "/%s", name().c_str()).c_str());
+}
+
+int SocketInfo::Create(const std::string& context) const {
+  int flags = ((type() == "stream" ? SOCK_STREAM :
+                (type() == "dgram" ? SOCK_DGRAM :
+                 SOCK_SEQPACKET)));
+  return create_socket(name().c_str(), flags, perm(), uid(), gid(), context.c_str());
+}
+
+const std::string SocketInfo::key() const {
+  return ANDROID_SOCKET_ENV_PREFIX;
+}
+
+FileInfo::FileInfo(const std::string& name, const std::string& type, uid_t uid,
+                   gid_t gid, int perm, const std::string& context)
+        // defaults OK for uid,..., they are ignored for this class.
+        : DescriptorInfo(name, type, uid, gid, perm, context) {
+}
+
+int FileInfo::Create(const std::string&) const {
+  int flags = (type() == "r") ? O_RDONLY :
+              (type() == "w") ? O_WRONLY :
+                                O_RDWR;
+
+  // Make sure we do not block on open (eg: devices can chose to block on
+  // carrier detect).  Our intention is never to delay launch of a service
+  // for such a condition.  The service can perform its own blocking on
+  // carrier detect.
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(name().c_str(),
+                                                      flags | O_NONBLOCK)));
+
+  if (fd < 0) {
+    PLOG(ERROR) << "Failed to open file '" << name().c_str() << "'";
+    return -1;
+  }
+
+  // Fixup as we set O_NONBLOCK for open, the intent for fd is to block reads.
+  fcntl(fd, F_SETFL, flags);
+
+  LOG(INFO) << "Opened file '" << name().c_str() << "'"
+            << ", flags " << std::oct << flags << std::dec;
+
+  return fd.release();
+}
+
+const std::string FileInfo::key() const {
+  return ANDROID_FILE_ENV_PREFIX;
+}
diff --git a/init/descriptors.h b/init/descriptors.h
new file mode 100644
index 0000000..ff276fb
--- /dev/null
+++ b/init/descriptors.h
@@ -0,0 +1,78 @@
+/*
+ * 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 _INIT_DESCRIPTORS_H
+#define _INIT_DESCRIPTORS_H
+
+#include <sys/types.h>
+
+#include <string>
+
+class DescriptorInfo {
+ public:
+  DescriptorInfo(const std::string& name, const std::string& type, uid_t uid,
+                 gid_t gid, int perm, const std::string& context);
+  virtual ~DescriptorInfo();
+
+  friend std::ostream& operator<<(std::ostream& os, const class DescriptorInfo& info);
+  bool operator==(const DescriptorInfo& other) const;
+
+  void CreateAndPublish(const std::string& globalContext) const;
+  virtual void Clean() const;
+
+ protected:
+  const std::string& name() const { return name_; }
+  const std::string& type() const { return type_; }
+  uid_t uid() const { return uid_; }
+  gid_t gid() const { return gid_; }
+  int perm() const { return perm_; }
+  const std::string& context() const { return context_; }
+
+ private:
+  std::string name_;
+  std::string type_;
+  uid_t uid_;
+  gid_t gid_;
+  int perm_;
+  std::string context_;
+
+  virtual int Create(const std::string& globalContext) const = 0;
+  virtual const std::string key() const = 0;
+};
+
+std::ostream& operator<<(std::ostream& os, const DescriptorInfo& info);
+
+class SocketInfo : public DescriptorInfo {
+ public:
+  SocketInfo(const std::string& name, const std::string& type, uid_t uid,
+             gid_t gid, int perm, const std::string& context);
+  void Clean() const override;
+ private:
+  virtual int Create(const std::string& context) const override;
+  virtual const std::string key() const override;
+};
+
+class FileInfo : public DescriptorInfo {
+ public:
+  FileInfo(const std::string& name, const std::string& type, uid_t uid,
+           gid_t gid, int perm, const std::string& context);
+ private:
+  virtual int Create(const std::string& context) const override;
+  virtual const std::string key() const override;
+};
+
+#endif
diff --git a/init/devices.cpp b/init/devices.cpp
index cffc561..39571ac 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -14,33 +14,39 @@
  * limitations under the License.
  */
 
+#include <dirent.h>
 #include <errno.h>
+#include <fcntl.h>
 #include <fnmatch.h>
+#include <libgen.h>
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <fcntl.h>
-#include <dirent.h>
-#include <unistd.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 <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 <sys/time.h>
-#include <sys/wait.h>
 
 #include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
 #include <cutils/list.h>
 #include <cutils/uevent.h>
 
@@ -56,19 +62,7 @@
 
 extern struct selabel_handle *sehandle;
 
-static int device_fd = -1;
-
-struct uevent {
-    const char *action;
-    const char *path;
-    const char *subsystem;
-    const char *firmware;
-    const char *partition_name;
-    const char *device_name;
-    int partition_num;
-    int major;
-    int minor;
-};
+static android::base::unique_fd device_fd;
 
 struct perms_ {
     char *name;
@@ -105,13 +99,18 @@
         return -ENOMEM;
 
     node->dp.name = strdup(name);
-    if (!node->dp.name)
+    if (!node->dp.name) {
+        free(node);
         return -ENOMEM;
+    }
 
     if (attr) {
         node->dp.attr = strdup(attr);
-        if (!node->dp.attr)
+        if (!node->dp.attr) {
+            free(node->dp.name);
+            free(node);
             return -ENOMEM;
+        }
     }
 
     node->dp.perm = perm;
@@ -128,49 +127,6 @@
     return 0;
 }
 
-void fixup_sys_perms(const char *upath)
-{
-    char buf[512];
-    struct listnode *node;
-    struct perms_ *dp;
-
-    /* upaths omit the "/sys" that paths in this list
-     * contain, so we add 4 when comparing...
-     */
-    list_for_each(node, &sys_perms) {
-        dp = &(node_to_item(node, struct perm_node, plist))->dp;
-        if (dp->prefix) {
-            if (strncmp(upath, dp->name + 4, strlen(dp->name + 4)))
-                continue;
-        } else if (dp->wildcard) {
-            if (fnmatch(dp->name + 4, upath, FNM_PATHNAME) != 0)
-                continue;
-        } else {
-            if (strcmp(upath, dp->name + 4))
-                continue;
-        }
-
-        if ((strlen(upath) + strlen(dp->attr) + 6) > sizeof(buf))
-            break;
-
-        snprintf(buf, sizeof(buf), "/sys%s/%s", upath, dp->attr);
-        INFO("fixup %s %d %d 0%o\n", buf, dp->uid, dp->gid, dp->perm);
-        chown(buf, dp->uid, dp->gid);
-        chmod(buf, dp->perm);
-    }
-
-    // Now fixup SELinux file labels
-    int len = snprintf(buf, sizeof(buf), "/sys%s", upath);
-    if ((len < 0) || ((size_t) len >= sizeof(buf))) {
-        // Overflow
-        return;
-    }
-    if (access(buf, F_OK) == 0) {
-        INFO("restorecon_recursive: %s\n", buf);
-        restorecon_recursive(buf);
-    }
-}
-
 static bool perm_path_matches(const char *path, struct perms_ *dp)
 {
     if (dp->prefix) {
@@ -187,6 +143,45 @@
     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) {
+        return false;
+    }
+
+    std::string subsys_path = android::base::StringPrintf(pattern, subsystem, basename(path));
+    return perm_path_matches(subsys_path.c_str(), dp);
+}
+
+static void fixup_sys_perms(const char* upath, const char* subsystem) {
+    // upaths omit the "/sys" that paths in this list
+    // contain, so we prepend it...
+    std::string path = std::string(SYSFS_PREFIX) + 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);
+    }
+
+    if (access(path.c_str(), F_OK) == 0) {
+        LOG(VERBOSE) << "restorecon_recursive: " << path;
+        restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE);
+    }
+}
+
 static mode_t get_device_perm(const char *path, const char **links,
                 unsigned *uid, unsigned *gid)
 {
@@ -242,12 +237,13 @@
 
     mode = get_device_perm(path, links, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
 
-    if (selabel_lookup_best_match(sehandle, &secontext, path, links, mode)) {
-        ERROR("Device '%s' not created; cannot find SELinux label (%s)\n",
-                path, strerror(errno));
-        return;
+    if (sehandle) {
+        if (selabel_lookup_best_match(sehandle, &secontext, path, links, mode)) {
+            PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
+            return;
+        }
+        setfscreatecon(secontext);
     }
-    setfscreatecon(secontext);
 
     dev = makedev(major, minor);
     /* Temporarily change egid to avoid race condition setting the gid of the
@@ -255,20 +251,39 @@
      * some device nodes, so the uid has to be set with chown() and is still
      * racy. Fixing the gid race at least fixed the issue with system_server
      * opening dynamic input devices under the AID_INPUT gid. */
-    setegid(gid);
+    if (setegid(gid)) {
+        PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed";
+        goto out;
+    }
     /* 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)) {
-        if (lsetfilecon(path, secontext)) {
-            ERROR("Cannot set '%s' SELinux label on '%s' device (%s)\n",
-                    secontext, path, strerror(errno));
+    if (mknod(path, mode, dev) && (errno == EEXIST) && secontext) {
+
+        char* fcon = nullptr;
+        int rc = lgetfilecon(path, &fcon);
+        if (rc < 0) {
+            PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
+            goto out;
+        }
+
+        bool different = strcmp(fcon, secontext) != 0;
+        freecon(fcon);
+
+        if (different && lsetfilecon(path, secontext)) {
+            PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path << "' device";
         }
     }
-    chown(path, uid, -1);
-    setegid(AID_ROOT);
 
-    freecon(secontext);
-    setfscreatecon(NULL);
+out:
+    chown(path, uid, -1);
+    if (setegid(AID_ROOT)) {
+        PLOG(FATAL) << "setegid(AID_ROOT) failed";
+    }
+
+    if (secontext) {
+        freecon(secontext);
+        setfscreatecon(NULL);
+    }
 }
 
 static void add_platform_device(const char *path)
@@ -283,7 +298,7 @@
             name += 9;
     }
 
-    INFO("adding platform device %s (%s)\n", name, path);
+    LOG(VERBOSE) << "adding platform device " << name << " (" << path << ")";
 
     bus = (platform_node*) calloc(1, sizeof(struct platform_node));
     bus->path = strdup(path);
@@ -322,7 +337,7 @@
     list_for_each_reverse(node, &platform_names) {
         bus = node_to_item(node, struct platform_node, list);
         if (!strcmp(path, bus->path)) {
-            INFO("removing platform device %s\n", bus->name);
+            LOG(INFO) << "removing platform device " << bus->name;
             free(bus->path);
             list_remove(node);
             free(bus);
@@ -331,6 +346,19 @@
     }
 }
 
+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);
+    }
+}
+
 /* 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 */
@@ -362,6 +390,34 @@
     return 0;
 }
 
+/* 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;
+
+    /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
+    if (strncmp(path, "/devices/vbd-", 13))
+        return -1;
+
+    /* 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;
+
+    /* Make sure we have enough room for the string plus null terminator */
+    if (end - start + 1 > buf_sz)
+        return -1;
+
+    strncpy(buf, start, end - start);
+    buf[end - start] = '\0';
+    return 0;
+}
+
 static void parse_event(const char *msg, struct uevent *uevent)
 {
     uevent->action = "";
@@ -411,16 +467,16 @@
     }
 
     if (LOG_UEVENTS) {
-        INFO("event { '%s', '%s', '%s', '%s', %d, %d }\n",
-             uevent->action, uevent->path, uevent->subsystem,
-             uevent->firmware, uevent->major, uevent->minor);
+        LOG(INFO) << android::base::StringPrintf("event { '%s', '%s', '%s', '%s', %d, %d }",
+                                                 uevent->action, uevent->path, uevent->subsystem,
+                                                 uevent->firmware, uevent->major, uevent->minor);
     }
 }
 
 static char **get_character_device_symlinks(struct uevent *uevent)
 {
     const char *parent;
-    char *slash;
+    const char *slash;
     char **links;
     int link_num = 0;
     int width;
@@ -470,11 +526,10 @@
     return NULL;
 }
 
-static char **get_block_device_symlinks(struct uevent *uevent)
-{
+char** get_block_device_symlinks(struct uevent* uevent) {
     const char *device;
     struct platform_node *pdev;
-    char *slash;
+    const char *slash;
     const char *type;
     char buf[256];
     char link_path[256];
@@ -488,6 +543,9 @@
     } else if (!find_pci_device_prefix(uevent->path, buf, sizeof(buf))) {
         device = buf;
         type = "pci";
+    } else if (!find_vbd_device_prefix(uevent->path, buf, sizeof(buf))) {
+        device = buf;
+        type = "vbd";
     } else {
         return NULL;
     }
@@ -497,15 +555,16 @@
         return NULL;
     memset(links, 0, sizeof(char *) * 4);
 
-    INFO("found %s device %s\n", type, device);
+    LOG(VERBOSE) << "found " << type << " device " << device;
 
     snprintf(link_path, sizeof(link_path), "/dev/block/%s/%s", type, device);
 
     if (uevent->partition_name) {
         p = strdup(uevent->partition_name);
         sanitize(p);
-        if (strcmp(uevent->partition_name, p))
-            NOTICE("Linking partition '%s' as '%s'\n", uevent->partition_name, p);
+        if (strcmp(uevent->partition_name, p)) {
+            LOG(VERBOSE) << "Linking partition '" << uevent->partition_name << "' as '" << p << "'";
+        }
         if (asprintf(&links[link_num], "%s/by-name/%s", link_path, p) > 0)
             link_num++;
         else
@@ -529,30 +588,49 @@
     return links;
 }
 
+static void make_link_init(const char* oldpath, const char* newpath) {
+  const char* slash = strrchr(newpath, '/');
+  if (!slash) return;
+
+  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;
+  }
+}
+
+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 handle_device(const char *action, const char *devpath,
         const char *path, int block, int major, int minor, char **links)
 {
-    int i;
-
     if(!strcmp(action, "add")) {
         make_device(devpath, path, block, major, minor, (const char **)links);
         if (links) {
-            for (i = 0; links[i]; i++)
+            for (int i = 0; links[i]; i++) {
                 make_link_init(devpath, links[i]);
+            }
         }
     }
 
     if(!strcmp(action, "remove")) {
         if (links) {
-            for (i = 0; links[i]; i++)
+            for (int i = 0; links[i]; i++) {
                 remove_link(devpath, links[i]);
+            }
         }
         unlink(devpath);
     }
 
     if (links) {
-        for (i = 0; links[i]; i++)
+        for (int i = 0; links[i]; i++) {
             free(links[i]);
+        }
         free(links);
     }
 }
@@ -583,22 +661,24 @@
 
     /* too-long names would overrun our buffer */
     if(strlen(name) > len) {
-        ERROR("DEVPATH=%s exceeds %u-character limit on filename; ignoring event\n",
-                name, len);
+        LOG(ERROR) << "DEVPATH=" << name << " exceeds " << len << "-character limit on filename; ignoring event";
         return NULL;
     }
 
     return name;
 }
 
+#define DEVPATH_LEN 96
+#define MAX_DEV_NAME 64
+
 static void handle_block_device_event(struct uevent *uevent)
 {
     const char *base = "/dev/block/";
     const char *name;
-    char devpath[96];
+    char devpath[DEVPATH_LEN];
     char **links = NULL;
 
-    name = parse_device_name(uevent, 64);
+    name = parse_device_name(uevent, MAX_DEV_NAME);
     if (!name)
         return;
 
@@ -612,19 +692,16 @@
             uevent->major, uevent->minor, links);
 }
 
-#define DEVPATH_LEN 96
-
 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) {
-        ERROR("failed to assemble device path (%s); ignoring event\n",
-                strerror(errno));
+        PLOG(ERROR) << "failed to assemble device path; ignoring event";
         return false;
     } else if (s >= DEVPATH_LEN) {
-        ERROR("%s/%s exceeds %u-character limit on path; ignoring event\n",
-                dirname, devname, DEVPATH_LEN);
+        LOG(ERROR) << dirname << "/" << devname
+                   << " exceeds " << DEVPATH_LEN << "-character limit on path; ignoring event";
         return false;
     }
     return true;
@@ -648,7 +725,7 @@
     char devpath[DEVPATH_LEN] = {0};
     char **links = NULL;
 
-    name = parse_device_name(uevent, 64);
+    name = parse_device_name(uevent, MAX_DEV_NAME);
     if (!name)
         return;
 
@@ -668,8 +745,7 @@
             break;
 
         default:
-            ERROR("%s subsystem's devpath option is not set; ignoring event\n",
-                    uevent->subsystem);
+            LOG(ERROR) << uevent->subsystem << " subsystem's devpath option is not set; ignoring event";
             return;
         }
 
@@ -725,9 +801,8 @@
      } 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)) {
-         INFO("kernel logger is deprecated\n");
+     } 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;
@@ -745,7 +820,7 @@
 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);
+        fixup_sys_perms(uevent->path, uevent->subsystem);
 
     if (!strncmp(uevent->subsystem, "block", 5)) {
         handle_block_device_event(uevent);
@@ -756,144 +831,99 @@
     }
 }
 
-static int load_firmware(int fw_fd, int loading_fd, int data_fd)
-{
-    struct stat st;
-    long len_to_copy;
-    int ret = 0;
+static void load_firmware(uevent* uevent, const std::string& root,
+                          int fw_fd, size_t fw_size,
+                          int loading_fd, int data_fd) {
+    // Start transfer.
+    android::base::WriteFully(loading_fd, "1", 1);
 
-    if(fstat(fw_fd, &st) < 0)
-        return -1;
-    len_to_copy = st.st_size;
-
-    write(loading_fd, "1", 1);  /* start transfer */
-
-    while (len_to_copy > 0) {
-        char buf[PAGE_SIZE];
-        ssize_t nr;
-
-        nr = read(fw_fd, buf, sizeof(buf));
-        if(!nr)
-            break;
-        if(nr < 0) {
-            ret = -1;
-            break;
-        }
-        if (!android::base::WriteFully(data_fd, buf, nr)) {
-            ret = -1;
-            break;
-        }
-        len_to_copy -= nr;
+    // Copy the firmware.
+    int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
+    if (rc == -1) {
+        PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << uevent->firmware << "' }";
     }
 
-    if(!ret)
-        write(loading_fd, "0", 1);  /* successful end of transfer */
-    else
-        write(loading_fd, "-1", 2); /* abort transfer */
-
-    return ret;
+    // Tell the firmware whether to abort or commit.
+    const char* response = (rc != -1) ? "0" : "-1";
+    android::base::WriteFully(loading_fd, response, strlen(response));
 }
 
-static int is_booting(void)
-{
+static int is_booting() {
     return access("/dev/.booting", F_OK) == 0;
 }
 
-static void process_firmware_event(struct uevent *uevent)
-{
-    char *root, *loading, *data;
-    int l, loading_fd, data_fd, fw_fd;
-    size_t i;
+static void process_firmware_event(uevent* uevent) {
     int booting = is_booting();
 
-    INFO("firmware: loading '%s' for '%s'\n",
-         uevent->firmware, uevent->path);
+    LOG(INFO) << "firmware: loading '" << uevent->firmware << "' for '" << uevent->path << "'";
 
-    l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
-    if (l == -1)
+    std::string root = android::base::StringPrintf("/sys%s", uevent->path);
+    std::string loading = root + "/loading";
+    std::string data = root + "/data";
+
+    android::base::unique_fd loading_fd(open(loading.c_str(), O_WRONLY|O_CLOEXEC));
+    if (loading_fd == -1) {
+        PLOG(ERROR) << "couldn't open firmware loading fd for " << uevent->firmware;
         return;
+    }
 
-    l = asprintf(&loading, "%sloading", root);
-    if (l == -1)
-        goto root_free_out;
-
-    l = asprintf(&data, "%sdata", root);
-    if (l == -1)
-        goto loading_free_out;
-
-    loading_fd = open(loading, O_WRONLY|O_CLOEXEC);
-    if(loading_fd < 0)
-        goto data_free_out;
-
-    data_fd = open(data, O_WRONLY|O_CLOEXEC);
-    if(data_fd < 0)
-        goto loading_close_out;
+    android::base::unique_fd data_fd(open(data.c_str(), O_WRONLY|O_CLOEXEC));
+    if (data_fd == -1) {
+        PLOG(ERROR) << "couldn't open firmware data fd for " << uevent->firmware;
+        return;
+    }
 
 try_loading_again:
-    for (i = 0; i < ARRAY_SIZE(firmware_dirs); i++) {
-        char *file = NULL;
-        l = asprintf(&file, "%s/%s", firmware_dirs[i], uevent->firmware);
-        if (l == -1)
-            goto data_free_out;
-        fw_fd = open(file, O_RDONLY|O_CLOEXEC);
-        free(file);
-        if (fw_fd >= 0) {
-            if(!load_firmware(fw_fd, loading_fd, data_fd))
-                INFO("firmware: copy success { '%s', '%s' }\n", root, uevent->firmware);
-            else
-                INFO("firmware: copy failure { '%s', '%s' }\n", root, uevent->firmware);
-            break;
+    for (size_t i = 0; i < arraysize(firmware_dirs); i++) {
+        std::string file = android::base::StringPrintf("%s/%s", 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) {
+            load_firmware(uevent, root, fw_fd, sb.st_size, loading_fd, data_fd);
+            return;
         }
     }
-    if (fw_fd < 0) {
-        if (booting) {
-            /* If we're not fully booted, we may be missing
-             * filesystems needed for firmware, wait and retry.
-             */
-            usleep(100000);
-            booting = is_booting();
-            goto try_loading_again;
-        }
-        INFO("firmware: could not open '%s': %s\n", uevent->firmware, strerror(errno));
-        write(loading_fd, "-1", 2);
-        goto data_close_out;
-    }
 
-    close(fw_fd);
-data_close_out:
-    close(data_fd);
-loading_close_out:
-    close(loading_fd);
-data_free_out:
-    free(data);
-loading_free_out:
-    free(loading);
-root_free_out:
-    free(root);
+    if (booting) {
+        // If we're not fully booted, we may be missing
+        // filesystems needed for firmware, wait and retry.
+        std::this_thread::sleep_for(100ms);
+        booting = is_booting();
+        goto try_loading_again;
+    }
+
+    LOG(ERROR) << "firmware: could not find firmware for " << uevent->firmware;
+
+    // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
+    write(loading_fd, "-1", 2);
 }
 
-static void handle_firmware_event(struct uevent *uevent)
-{
-    pid_t pid;
+static void handle_firmware_event(uevent* uevent) {
+    if (strcmp(uevent->subsystem, "firmware")) return;
+    if (strcmp(uevent->action, "add")) return;
 
-    if(strcmp(uevent->subsystem, "firmware"))
-        return;
-
-    if(strcmp(uevent->action, "add"))
-        return;
-
-    /* we fork, to avoid making large memory allocations in init proper */
-    pid = fork();
-    if (!pid) {
+    // Loading the firmware in a child means we can do that in parallel...
+    // (We ignore SIGCHLD rather than wait for our children.)
+    pid_t pid = fork();
+    if (pid == 0) {
+        Timer t;
         process_firmware_event(uevent);
+        LOG(INFO) << "loading " << uevent->path << " took " << t;
         _exit(EXIT_SUCCESS);
-    } else if (pid < 0) {
-        ERROR("could not fork to process firmware event: %s\n", strerror(errno));
+    } else if (pid == -1) {
+        PLOG(ERROR) << "could not fork to process firmware event for " << uevent->firmware;
     }
 }
 
+static bool inline should_stop_coldboot(coldboot_action_t act)
+{
+    return (act == COLDBOOT_STOP || act == COLDBOOT_FINISH);
+}
+
 #define UEVENT_MSG_LEN  2048
-void handle_device_fd()
+
+static inline coldboot_action_t handle_device_fd_with(
+        std::function<coldboot_action_t(uevent* uevent)> handle_uevent)
 {
     char msg[UEVENT_MSG_LEN+2];
     int n;
@@ -906,19 +936,42 @@
 
         struct uevent uevent;
         parse_event(msg, &uevent);
-
-        if (selinux_status_updated() > 0) {
-            struct selabel_handle *sehandle2;
-            sehandle2 = selinux_android_file_context_handle();
-            if (sehandle2) {
-                selabel_close(sehandle);
-                sehandle = sehandle2;
-            }
-        }
-
-        handle_device_event(&uevent);
-        handle_firmware_event(&uevent);
+        coldboot_action_t act = handle_uevent(&uevent);
+        if (should_stop_coldboot(act))
+            return act;
     }
+
+    return COLDBOOT_CONTINUE;
+}
+
+coldboot_action_t handle_device_fd(coldboot_callback fn)
+{
+    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) {
+                act = fn(uevent);
+            }
+
+            if (act == COLDBOOT_CREATE || act == COLDBOOT_STOP) {
+                handle_device_event(uevent);
+                handle_firmware_event(uevent);
+            }
+
+            return act;
+        });
+
+    return ret;
 }
 
 /* Coldboot walks parts of the /sys tree and pokes the uevent files
@@ -930,21 +983,24 @@
 ** socket's buffer.
 */
 
-static void do_coldboot(DIR *d)
+static coldboot_action_t do_coldboot(DIR *d, coldboot_callback fn)
 {
     struct dirent *de;
     int dfd, fd;
+    coldboot_action_t act = COLDBOOT_CONTINUE;
 
     dfd = dirfd(d);
 
     fd = openat(dfd, "uevent", O_WRONLY);
-    if(fd >= 0) {
+    if (fd >= 0) {
         write(fd, "add\n", 4);
         close(fd);
-        handle_device_fd();
+        act = handle_device_fd(fn);
+        if (should_stop_coldboot(act))
+            return act;
     }
 
-    while((de = readdir(d))) {
+    while (!should_stop_coldboot(act) && (de = readdir(d))) {
         DIR *d2;
 
         if(de->d_type != DT_DIR || de->d_name[0] == '.')
@@ -958,46 +1014,75 @@
         if(d2 == 0)
             close(fd);
         else {
-            do_coldboot(d2);
+            act = do_coldboot(d2, fn);
             closedir(d2);
         }
     }
+
+    // default is always to continue looking for uevents
+    return act;
 }
 
-static void coldboot(const char *path)
+static coldboot_action_t coldboot(const char *path, coldboot_callback fn)
 {
-    DIR *d = opendir(path);
-    if(d) {
-        do_coldboot(d);
-        closedir(d);
+    std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path), closedir);
+    if (d) {
+        return do_coldboot(d.get(), fn);
     }
+
+    return COLDBOOT_CONTINUE;
 }
 
-void device_init() {
-    sehandle = selinux_android_file_context_handle();
-    selinux_status_open(true);
-
-    /* is 256K enough? udev uses 16MB! */
-    device_fd = uevent_open_socket(256*1024, true);
-    if (device_fd == -1) {
-        return;
+void device_init(const char* path, coldboot_callback fn) {
+    if (!sehandle) {
+        sehandle = selinux_android_file_context_handle();
     }
-    fcntl(device_fd, F_SETFL, O_NONBLOCK);
+    // open uevent socket and selinux status only if it hasn't been
+    // done before
+    if (device_fd == -1) {
+        /* is 256K enough? udev uses 16MB! */
+        device_fd.reset(uevent_open_socket(256 * 1024, true));
+        if (device_fd == -1) {
+            return;
+        }
+        fcntl(device_fd, F_SETFL, O_NONBLOCK);
+        selinux_status_open(true);
+    }
 
     if (access(COLDBOOT_DONE, F_OK) == 0) {
-        NOTICE("Skipping coldboot, already done!\n");
+        LOG(VERBOSE) << "Skipping coldboot, already done!";
         return;
     }
 
     Timer t;
-    coldboot("/sys/class");
-    coldboot("/sys/block");
-    coldboot("/sys/devices");
-    close(open(COLDBOOT_DONE, O_WRONLY|O_CREAT|O_CLOEXEC, 0000));
-    NOTICE("Coldboot took %.2fs.\n", t.duration());
+    coldboot_action_t act;
+    if (!path) {
+        act = coldboot("/sys/class", fn);
+        if (!should_stop_coldboot(act)) {
+            act = coldboot("/sys/block", fn);
+            if (!should_stop_coldboot(act)) {
+                act = coldboot("/sys/devices", fn);
+            }
+        }
+    } else {
+        act = coldboot(path, fn);
+    }
+
+    // If we have a callback, then do as it says. If no, then the default is
+    // to always create COLDBOOT_DONE file.
+    if (!fn || (act == COLDBOOT_FINISH)) {
+        close(open(COLDBOOT_DONE, O_WRONLY|O_CREAT|O_CLOEXEC, 0000));
+    }
+
+    LOG(INFO) << "Coldboot took " << t;
 }
 
-int get_device_fd()
-{
+void device_close() {
+    destroy_platform_devices();
+    device_fd.reset();
+    selinux_status_close();
+}
+
+int get_device_fd() {
     return device_fd;
 }
diff --git a/init/devices.h b/init/devices.h
index 6cb0a77..3f2cde4 100644
--- a/init/devices.h
+++ b/init/devices.h
@@ -17,14 +17,44 @@
 #ifndef _INIT_DEVICES_H
 #define _INIT_DEVICES_H
 
+#include <functional>
 #include <sys/stat.h>
 
-extern void handle_device_fd();
-extern void device_init(void);
+enum coldboot_action_t {
+    // coldboot continues without creating the device for the uevent
+    COLDBOOT_CONTINUE = 0,
+    // coldboot continues after creating the device for the uevent
+    COLDBOOT_CREATE,
+    // coldboot stops after creating the device for uevent but doesn't
+    // create the COLDBOOT_DONE file
+    COLDBOOT_STOP,
+    // same as COLDBOOT_STOP, but creates the COLDBOOT_DONE file
+    COLDBOOT_FINISH
+};
+
+struct uevent {
+    const char* action;
+    const char* path;
+    const char* subsystem;
+    const char* firmware;
+    const char* partition_name;
+    const char* device_name;
+    int partition_num;
+    int major;
+    int minor;
+};
+
+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();
 
+char** get_block_device_symlinks(struct uevent* uevent);
+
 #endif	/* _INIT_DEVICES_H */
diff --git a/init/grab-bootchart.sh b/init/grab-bootchart.sh
index d6082aa..c4ff6df 100755
--- a/init/grab-bootchart.sh
+++ b/init/grab-bootchart.sh
@@ -11,7 +11,7 @@
 LOGROOT=/data/bootchart
 TARBALL=bootchart.tgz
 
-FILES="header proc_stat.log proc_ps.log proc_diskstats.log kernel_pacct"
+FILES="header proc_stat.log proc_ps.log proc_diskstats.log"
 
 for f in $FILES; do
     adb "${@}" pull $LOGROOT/$f $TMPDIR/$f 2>&1 > /dev/null
diff --git a/init/import_parser.cpp b/init/import_parser.cpp
index e2a0f83..d52247b 100644
--- a/init/import_parser.cpp
+++ b/init/import_parser.cpp
@@ -38,7 +38,7 @@
         return false;
     }
 
-    INFO("Added '%s' to import list\n", conf_file.c_str());
+    LOG(INFO) << "Added '" << conf_file << "' to import list";
     imports_.emplace_back(std::move(conf_file));
     return true;
 }
@@ -48,8 +48,7 @@
     imports_.clear();
     for (const auto& s : current_imports) {
         if (!Parser::GetInstance().ParseConfig(s)) {
-            ERROR("could not import file '%s' from '%s': %s\n",
-                  s.c_str(), filename.c_str(), strerror(errno));
+            PLOG(ERROR) << "could not import file '" << s << "' from '" << filename << "'";
         }
     }
 }
diff --git a/init/init.cpp b/init/init.cpp
index cd2d2e6..bb6355a 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -18,7 +18,8 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <fstream>
+#include <inttypes.h>
+#include <keyutils.h>
 #include <libgen.h>
 #include <paths.h>
 #include <signal.h>
@@ -30,44 +31,48 @@
 #include <sys/mount.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
+#include <sys/sysmacros.h>
 #include <sys/types.h>
 #include <sys/un.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <mtd/mtd-user.h>
-
 #include <selinux/selinux.h>
 #include <selinux/label.h>
 #include <selinux/android.h>
 
 #include <android-base/file.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <cutils/android_reboot.h>
-#include <cutils/fs.h>
-#include <cutils/iosched_policy.h>
-#include <cutils/list.h>
-#include <cutils/sockets.h>
+#include <android-base/unique_fd.h>
+#include <libavb/libavb.h>
 #include <private/android_filesystem_config.h>
 
+#include <fstream>
 #include <memory>
+#include <vector>
 
 #include "action.h"
 #include "bootchart.h"
 #include "devices.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::GetProperty;
+using android::base::StringPrintf;
+
 struct selabel_handle *sehandle;
 struct selabel_handle *sehandle_prop;
 
@@ -75,22 +80,23 @@
 
 static char qemu[32];
 
-int have_console;
-std::string console_name = "/dev/console";
-static time_t process_needs_restart;
+std::string default_console = "/dev/console";
+static time_t process_needs_restart_at;
 
 const char *ENV[32];
 
-bool waiting_for_exec = false;
-
 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 register_epoll_handler(int fd, void (*fn)()) {
     epoll_event ev;
     ev.events = EPOLLIN;
     ev.data.ptr = reinterpret_cast<void*>(fn);
     if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
-        ERROR("epoll_ctl failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "epoll_ctl failed";
     }
 }
 
@@ -101,7 +107,7 @@
     size_t key_len = strlen(key);
 
     /* The last environment entry is reserved to terminate the list */
-    for (n = 0; n < (ARRAY_SIZE(ENV) - 1); n++) {
+    for (n = 0; n < (arraysize(ENV) - 1); n++) {
 
         /* Delete any existing entry for this key */
         if (ENV[n] != NULL) {
@@ -121,30 +127,59 @@
         }
     }
 
-    ERROR("No env. room to store: '%s':'%s'\n", key, val);
+    LOG(ERROR) << "No env. room to store: '" << key << "':'" << val << "'";
 
     return -1;
 }
 
-void property_changed(const char *name, const char *value)
+bool start_waiting_for_property(const char *name, const char *value)
 {
+    if (waiting_for_prop) {
+        return false;
+    }
+    if (GetProperty(name, "") != value) {
+        // Current property value is not equal to expected value
+        wait_prop_name = name;
+        wait_prop_value = value;
+        waiting_for_prop.reset(new Timer());
+    } else {
+        LOG(INFO) << "start_waiting_for_property(\""
+                  << name << "\", \"" << value << "\"): already set";
+    }
+    return true;
+}
+
+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().QueuePropertyTrigger(name, value);
+    if (waiting_for_prop) {
+        if (wait_prop_name == name && wait_prop_value == value) {
+            wait_prop_name.clear();
+            wait_prop_value.clear();
+            LOG(INFO) << "Wait for property took " << *waiting_for_prop;
+            waiting_for_prop.reset();
+        }
+    }
 }
 
 static void restart_processes()
 {
-    process_needs_restart = 0;
-    ServiceManager::GetInstance().
-        ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
-                s->RestartIfNeeded(process_needs_restart);
-            });
+    process_needs_restart_at = 0;
+    ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
+        s->RestartIfNeeded(&process_needs_restart_at);
+    });
 }
 
 void handle_control_message(const std::string& msg, const std::string& name) {
     Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
     if (svc == nullptr) {
-        ERROR("no such service '%s'\n", name.c_str());
+        LOG(ERROR) << "no such service '" << name << "'";
         return;
     }
 
@@ -155,22 +190,29 @@
     } else if (msg == "restart") {
         svc->Restart();
     } else {
-        ERROR("unknown control msg '%s'\n", msg.c_str());
+        LOG(ERROR) << "unknown control msg '" << msg << "'";
     }
 }
 
 static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
     Timer t;
 
-    NOTICE("Waiting for %s...\n", COLDBOOT_DONE);
-    // Any longer than 1s is an unreasonable length of time to delay booting.
-    // If you're hitting this timeout, check that you didn't make your
-    // sepolicy regular expressions too expensive (http://b/19899875).
-    if (wait_for_file(COLDBOOT_DONE, 1)) {
-        ERROR("Timed out waiting for %s\n", COLDBOOT_DONE);
+    LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
+
+    // Historically we had a 1s timeout here because we weren't otherwise
+    // tracking boot time, and many OEMs made their sepolicy regular
+    // expressions too expensive (http://b/19899875).
+
+    // Now we're tracking boot time, just log the time taken to a system
+    // property. We still panic if it takes more than a minute though,
+    // because any build that slow isn't likely to boot at all, and we'd
+    // rather any test lab devices fail back to the bootloader.
+    if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
+        LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
+        panic();
     }
 
-    NOTICE("Waiting for %s took %.2fs.\n", COLDBOOT_DONE, t.duration());
+    property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ms()).c_str());
     return 0;
 }
 
@@ -202,11 +244,11 @@
             open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
     if (hwrandom_fd == -1) {
         if (errno == ENOENT) {
-          ERROR("/dev/hw_random not found\n");
-          /* It's not an error to not have a Hardware RNG. */
-          result = 0;
+            LOG(ERROR) << "/dev/hw_random not found";
+            // It's not an error to not have a Hardware RNG.
+            result = 0;
         } else {
-          ERROR("Failed to open /dev/hw_random: %s\n", strerror(errno));
+            PLOG(ERROR) << "Failed to open /dev/hw_random";
         }
         goto ret;
     }
@@ -214,7 +256,7 @@
     urandom_fd = TEMP_FAILURE_RETRY(
             open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
     if (urandom_fd == -1) {
-        ERROR("Failed to open /dev/urandom: %s\n", strerror(errno));
+        PLOG(ERROR) << "Failed to open /dev/urandom";
         goto ret;
     }
 
@@ -222,23 +264,22 @@
         chunk_size = TEMP_FAILURE_RETRY(
                 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
         if (chunk_size == -1) {
-            ERROR("Failed to read from /dev/hw_random: %s\n", strerror(errno));
+            PLOG(ERROR) << "Failed to read from /dev/hw_random";
             goto ret;
         } else if (chunk_size == 0) {
-            ERROR("Failed to read from /dev/hw_random: EOF\n");
+            LOG(ERROR) << "Failed to read from /dev/hw_random: EOF";
             goto ret;
         }
 
         chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
         if (chunk_size == -1) {
-            ERROR("Failed to write to /dev/urandom: %s\n", strerror(errno));
+            PLOG(ERROR) << "Failed to write to /dev/urandom";
             goto ret;
         }
         total_bytes_written += chunk_size;
     }
 
-    INFO("Mixed %zu bytes from /dev/hw_random into /dev/urandom",
-                total_bytes_written);
+    LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
     result = 0;
 
 ret:
@@ -252,9 +293,46 @@
 }
 
 static void security_failure() {
-    ERROR("Security failure; rebooting into recovery mode...\n");
-    android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-    while (true) { pause(); }  // never reached
+    LOG(ERROR) << "Security failure...";
+    panic();
+}
+
+static bool set_highest_available_option_value(std::string path, int min, int max)
+{
+    std::ifstream inf(path, std::fstream::in);
+    if (!inf) {
+        LOG(ERROR) << "Cannot open for reading: " << path;
+        return false;
+    }
+
+    int current = max;
+    while (current >= min) {
+        // try to write out new value
+        std::string str_val = std::to_string(current);
+        std::ofstream of(path, std::fstream::out);
+        if (!of) {
+            LOG(ERROR) << "Cannot open for writing: " << path;
+            return false;
+        }
+        of << str_val << std::endl;
+        of.close();
+
+        // check to make sure it was recorded
+        inf.seekg(0);
+        std::string str_rec;
+        inf >> str_rec;
+        if (str_val.compare(str_rec) == 0) {
+            break;
+        }
+        current--;
+    }
+    inf.close();
+
+    if (current < min) {
+        LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
+        return false;
+    }
+    return true;
 }
 
 #define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
@@ -269,39 +347,23 @@
     } else {
         path = MMAP_RND_PATH;
     }
-    std::ifstream inf(path, std::fstream::in);
-    if (!inf) {
-        return false;
-    }
-    while (start >= min) {
-        // try to write out new value
-        std::string str_val = std::to_string(start);
-        std::ofstream of(path, std::fstream::out);
-        if (!of) {
-            return false;
-        }
-        of << str_val << std::endl;
-        of.close();
 
-        // check to make sure it was recorded
-        inf.seekg(0);
-        std::string str_rec;
-        inf >> str_rec;
-        if (str_val.compare(str_rec) == 0) {
-            break;
-        }
-        start--;
-    }
-    inf.close();
-    return (start >= min);
+    return set_highest_available_option_value(path, min, start);
 }
 
 /*
  * Set /proc/sys/vm/mmap_rnd_bits and potentially
  * /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
- * Returns -1 if unable to set these to an acceptable value.  Apply
- * upstream patch-sets https://lkml.org/lkml/2015/12/21/337 and
- * https://lkml.org/lkml/2016/2/4/831 to enable this.
+ * Returns -1 if unable to set these to an acceptable value.
+ *
+ * To support this sysctl, the following upstream commits are needed:
+ *
+ * d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
+ * e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
+ * 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
+ * 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
+ * ec9ee4acd97c drivers: char: random: add get_random_long()
+ * 5ef11c35ce86 mm: ASLR: use get_random_long()
  */
 static int set_mmap_rnd_bits_action(const std::vector<std::string>& args)
 {
@@ -331,20 +393,35 @@
     // TODO: add mips support b/27788820
     ret = 0;
 #else
-    ERROR("Unknown architecture\n");
+    LOG(ERROR) << "Unknown architecture";
 #endif
 
-#ifdef __BRILLO__
-    // TODO: b/27794137
-    ret = 0;
-#endif
     if (ret == -1) {
-        ERROR("Unable to set adequate mmap entropy value!\n");
+        LOG(ERROR) << "Unable to set adequate mmap entropy value!";
         security_failure();
     }
     return ret;
 }
 
+#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
+#define KPTR_RESTRICT_MINVALUE 2
+#define KPTR_RESTRICT_MAXVALUE 4
+
+/* Set kptr_restrict to the highest available level.
+ *
+ * Aborts if unable to set this to an acceptable value.
+ */
+static int set_kptr_restrict_action(const std::vector<std::string>& args)
+{
+    std::string path = KPTR_RESTRICT_PATH;
+
+    if (!set_highest_available_option_value(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
+        LOG(ERROR) << "Unable to set adequate kptr_restrict value!";
+        security_failure();
+    }
+    return 0;
+}
+
 static int keychord_init_action(const std::vector<std::string>& args)
 {
     keychord_init();
@@ -353,38 +430,10 @@
 
 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()) {
-        console_name = "/dev/" + console;
+        default_console = "/dev/" + console;
     }
-
-    int fd = open(console_name.c_str(), O_RDWR | O_CLOEXEC);
-    if (fd >= 0)
-        have_console = 1;
-    close(fd);
-
-    fd = open("/dev/tty0", O_WRONLY | O_CLOEXEC);
-    if (fd >= 0) {
-        const char *msg;
-            msg = "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"  // console is 40 cols x 30 lines
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "\n"
-        "             A N D R O I D ";
-        write(fd, msg, strlen(msg));
-        close(fd);
-    }
-
     return 0;
 }
 
@@ -393,24 +442,23 @@
 
     if (for_emulator) {
         // In the emulator, export any kernel option with the "ro.kernel." prefix.
-        property_set(android::base::StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
+        property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
         return;
     }
 
     if (key == "qemu") {
         strlcpy(qemu, value.c_str(), sizeof(qemu));
     } else if (android::base::StartsWith(key, "androidboot.")) {
-        property_set(android::base::StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(),
-                     value.c_str());
+        property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str());
     }
 }
 
 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");
@@ -430,47 +478,38 @@
         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
         { "ro.boot.revision",   "ro.revision",   "0", },
     };
-    for (size_t i = 0; i < ARRAY_SIZE(prop_map); i++) {
-        std::string value = property_get(prop_map[i].src_prop);
+    for (size_t i = 0; i < arraysize(prop_map); i++) {
+        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 void process_kernel_dt() {
-    static const char android_dir[] = "/proc/device-tree/firmware/android";
-
-    std::string file_name = android::base::StringPrintf("%s/compatible", android_dir);
-
-    std::string dt_file;
-    android::base::ReadFileToString(file_name, &dt_file);
-    if (!dt_file.compare("android,firmware")) {
-        ERROR("firmware/android is not compatible with 'android,firmware'\n");
+    if (!is_android_dt_value_expected("compatible", "android,firmware")) {
         return;
     }
 
-    std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(android_dir), closedir);
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kAndroidDtDir.c_str()), closedir);
     if (!dir) return;
 
+    std::string dt_file;
     struct dirent *dp;
     while ((dp = readdir(dir.get())) != NULL) {
         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
             continue;
         }
 
-        file_name = android::base::StringPrintf("%s/%s", android_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(), ',', '.');
 
-        std::string property_name = android::base::StringPrintf("ro.boot.%s", dp->d_name);
+        std::string property_name = StringPrintf("ro.boot.%s", dp->d_name);
         property_set(property_name.c_str(), dt_file.c_str());
     }
 }
 
 static void process_kernel_cmdline() {
-    // Don't expose the raw commandline to unprivileged processes.
-    chmod("/proc/cmdline", 0440);
-
     // The first pass does the common stuff, and finds if we are in qemu.
     // The second pass is only necessary for qemu to export all kernel params
     // as properties.
@@ -521,30 +560,12 @@
     return true;
 }
 
-int selinux_reload_policy(void)
-{
-    INFO("SELinux: Attempting to reload policy files\n");
-
-    if (selinux_android_reload_policy() == -1) {
-        return -1;
-    }
-
-    if (sehandle)
-        selabel_close(sehandle);
-
-    if (sehandle_prop)
-        selabel_close(sehandle_prop);
-
-    selinux_init_all_handles();
-    return 0;
-}
-
 static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
 
     property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
 
     if (!d || !d->name || !d->cr) {
-        ERROR("audit_callback invoked with null data arguments!");
+        LOG(ERROR) << "audit_callback invoked with null data arguments!";
         return 0;
     }
 
@@ -553,6 +574,270 @@
     return 0;
 }
 
+/*
+ * Forks, executes the provided program in the child, and waits for the completion in the parent.
+ * Child's stderr is captured and logged using LOG(ERROR).
+ *
+ * Returns true if the child exited with status code 0, returns false otherwise.
+ */
+static bool fork_execve_and_wait_for_completion(const char* filename, char* const argv[],
+                                                char* const envp[]) {
+    // Create a pipe used for redirecting child process's output.
+    // * pipe_fds[0] is the FD the parent will use for reading.
+    // * pipe_fds[1] is the FD the child will use for writing.
+    int pipe_fds[2];
+    if (pipe(pipe_fds) == -1) {
+        PLOG(ERROR) << "Failed to create pipe";
+        return false;
+    }
+
+    pid_t child_pid = fork();
+    if (child_pid == -1) {
+        PLOG(ERROR) << "Failed to fork for " << filename;
+        return false;
+    }
+
+    if (child_pid == 0) {
+        // fork succeeded -- this is executing in the child process
+
+        // Close the pipe FD not used by this process
+        TEMP_FAILURE_RETRY(close(pipe_fds[0]));
+
+        // Redirect stderr to the pipe FD provided by the parent
+        if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
+            PLOG(ERROR) << "Failed to redirect stderr of " << filename;
+            _exit(127);
+            return false;
+        }
+        TEMP_FAILURE_RETRY(close(pipe_fds[1]));
+
+        if (execve(filename, argv, envp) == -1) {
+            PLOG(ERROR) << "Failed to execve " << filename;
+            return false;
+        }
+        // Unreachable because execve will have succeeded and replaced this code
+        // with child process's code.
+        _exit(127);
+        return false;
+    } else {
+        // fork succeeded -- this is executing in the original/parent process
+
+        // Close the pipe FD not used by this process
+        TEMP_FAILURE_RETRY(close(pipe_fds[1]));
+
+        // Log the redirected output of the child process.
+        // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
+        // As a result, we're buffering all output and logging it in one go at the end of the
+        // invocation, instead of logging it as it comes in.
+        const int child_out_fd = pipe_fds[0];
+        std::string child_output;
+        if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
+            PLOG(ERROR) << "Failed to capture full output of " << filename;
+        }
+        TEMP_FAILURE_RETRY(close(child_out_fd));
+        if (!child_output.empty()) {
+            // Log captured output, line by line, because LOG expects to be invoked for each line
+            std::istringstream in(child_output);
+            std::string line;
+            while (std::getline(in, line)) {
+                LOG(ERROR) << filename << ": " << line;
+            }
+        }
+
+        // Wait for child to terminate
+        int status;
+        if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
+            PLOG(ERROR) << "Failed to wait for " << filename;
+            return false;
+        }
+
+        if (WIFEXITED(status)) {
+            int status_code = WEXITSTATUS(status);
+            if (status_code == 0) {
+                return true;
+            } else {
+                LOG(ERROR) << filename << " exited with status " << status_code;
+            }
+        } else if (WIFSIGNALED(status)) {
+            LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
+        } else if (WIFSTOPPED(status)) {
+            LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
+        } else {
+            LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
+        }
+
+        return false;
+    }
+}
+
+static bool read_first_line(const char* file, std::string* line) {
+    line->clear();
+
+    std::string contents;
+    if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) {
+        return false;
+    }
+    std::istringstream in(contents);
+    std::getline(in, *line);
+    return true;
+}
+
+static bool selinux_find_precompiled_split_policy(std::string* file) {
+    file->clear();
+
+    static constexpr const char precompiled_sepolicy[] = "/vendor/etc/selinux/precompiled_sepolicy";
+    if (access(precompiled_sepolicy, R_OK) == -1) {
+        return false;
+    }
+    std::string actual_plat_id;
+    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_and_mapping.sha256",
+                         &precompiled_plat_id)) {
+        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)) {
+        return false;
+    }
+
+    *file = precompiled_sepolicy;
+    return true;
+}
+
+static bool selinux_get_vendor_mapping_version(std::string* plat_vers) {
+    if (!read_first_line("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) {
+        PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt";
+        return false;
+    }
+    if (plat_vers->empty()) {
+        LOG(ERROR) << "No version present in plat_sepolicy_vers.txt";
+        return false;
+    }
+    return true;
+}
+
+static constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil";
+
+static bool selinux_is_split_policy_device() { return access(plat_policy_cil_file, R_OK) != -1; }
+
+/*
+ * Loads SELinux policy split across platform/system and non-platform/vendor files.
+ *
+ * Returns true upon success, false otherwise (failure cause is logged).
+ */
+static bool selinux_load_split_policy() {
+    // IMPLEMENTATION NOTE: Split policy consists of three CIL files:
+    // * platform -- policy needed due to logic contained in the system image,
+    // * non-platform -- policy needed due to logic contained in the vendor image,
+    // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy
+    //   with newer versions of platform policy.
+    //
+    // secilc is invoked to compile the above three policy files into a single monolithic policy
+    // file. This file is then loaded into the kernel.
+
+    // Load precompiled policy from vendor image, if a matching policy is found there. The policy
+    // must match the platform policy on the system image.
+    std::string precompiled_sepolicy_file;
+    if (selinux_find_precompiled_split_policy(&precompiled_sepolicy_file)) {
+        android::base::unique_fd fd(
+            open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY));
+        if (fd != -1) {
+            if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) {
+                LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file;
+                return false;
+            }
+            return true;
+        }
+    }
+    // No suitable precompiled policy could be loaded
+
+    LOG(INFO) << "Compiling SELinux policy";
+
+    // Determine the highest policy language version supported by the kernel
+    set_selinuxmnt("/sys/fs/selinux");
+    int max_policy_version = security_policyvers();
+    if (max_policy_version == -1) {
+        PLOG(ERROR) << "Failed to determine highest policy version supported by kernel";
+        return false;
+    }
+
+    // We store the output of the compilation on /dev because this is the most convenient tmpfs
+    // storage mount available this early in the boot sequence.
+    char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX";
+    android::base::unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC));
+    if (compiled_sepolicy_fd < 0) {
+        PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy;
+        return false;
+    }
+
+    // Determine which mapping file to include
+    std::string vend_plat_vers;
+    if (!selinux_get_vendor_mapping_version(&vend_plat_vers)) {
+        return false;
+    }
+    std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil");
+    // clang-format off
+    const char* compile_args[] = {
+        "/system/bin/secilc",
+        plat_policy_cil_file,
+        "-M", "true", "-G", "-N",
+        // Target the highest policy language version supported by the kernel
+        "-c", std::to_string(max_policy_version).c_str(),
+        mapping_file.c_str(),
+        "/vendor/etc/selinux/nonplat_sepolicy.cil",
+        "-o", compiled_sepolicy,
+        // We don't care about file_contexts output by the compiler
+        "-f", "/sys/fs/selinux/null",  // /dev/null is not yet available
+        nullptr};
+    // clang-format on
+
+    if (!fork_execve_and_wait_for_completion(compile_args[0], (char**)compile_args, (char**)ENV)) {
+        unlink(compiled_sepolicy);
+        return false;
+    }
+    unlink(compiled_sepolicy);
+
+    LOG(INFO) << "Loading compiled SELinux policy";
+    if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) {
+        LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy;
+        return false;
+    }
+
+    return true;
+}
+
+/*
+ * Loads SELinux policy from a monolithic file.
+ *
+ * Returns true upon success, false otherwise (failure cause is logged).
+ */
+static bool selinux_load_monolithic_policy() {
+    LOG(VERBOSE) << "Loading SELinux policy from monolithic file";
+    if (selinux_android_load_policy() < 0) {
+        PLOG(ERROR) << "Failed to load monolithic SELinux policy";
+        return false;
+    }
+    return true;
+}
+
+/*
+ * Loads SELinux policy into the kernel.
+ *
+ * Returns true upon success, false otherwise (failure cause is logged).
+ */
+static bool selinux_load_policy() {
+    return selinux_is_split_policy_device() ? selinux_load_split_policy()
+                                            : selinux_load_monolithic_policy();
+}
+
 static void selinux_initialize(bool in_kernel_domain) {
     Timer t;
 
@@ -563,33 +848,103 @@
     selinux_set_callback(SELINUX_CB_AUDIT, cb);
 
     if (in_kernel_domain) {
-        INFO("Loading SELinux policy...\n");
-        if (selinux_android_load_policy() < 0) {
-            ERROR("failed to load policy: %s\n", strerror(errno));
-            security_failure();
+        LOG(INFO) << "Loading SELinux policy";
+        if (!selinux_load_policy()) {
+            panic();
         }
 
         bool kernel_enforcing = (security_getenforce() == 1);
         bool is_enforcing = selinux_is_enforcing();
         if (kernel_enforcing != is_enforcing) {
             if (security_setenforce(is_enforcing)) {
-                ERROR("security_setenforce(%s) failed: %s\n",
-                      is_enforcing ? "true" : "false", strerror(errno));
+                PLOG(ERROR) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false");
                 security_failure();
             }
         }
 
-        if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) {
+        if (!write_file("/sys/fs/selinux/checkreqprot", "0")) {
             security_failure();
         }
 
-        NOTICE("(Initializing SELinux %s took %.2fs.)\n",
-               is_enforcing ? "enforcing" : "non-enforcing", t.duration());
+        // init's first stage can't set properties, so pass the time to the second stage.
+        setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ms()).c_str(), 1);
     } else {
         selinux_init_all_handles();
     }
 }
 
+// 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");
+    restorecon("/dev/socket");
+    restorecon("/dev/random");
+    restorecon("/dev/urandom");
+    restorecon("/dev/__properties__");
+
+    restorecon("/file_contexts.bin");
+    restorecon("/plat_file_contexts");
+    restorecon("/nonplat_file_contexts");
+    restorecon("/plat_property_contexts");
+    restorecon("/nonplat_property_contexts");
+    restorecon("/plat_seapp_contexts");
+    restorecon("/nonplat_seapp_contexts");
+    restorecon("/plat_service_contexts");
+    restorecon("/nonplat_service_contexts");
+    restorecon("/plat_hwservice_contexts");
+    restorecon("/nonplat_hwservice_contexts");
+    restorecon("/sepolicy");
+    restorecon("/vndservice_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.
+static void set_usb_controller() {
+    std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
+    if (!dir) return;
+
+    dirent* dp;
+    while ((dp = readdir(dir.get())) != nullptr) {
+        if (dp->d_name[0] == '.') continue;
+
+        property_set("sys.usb.controller", dp->d_name);
+        break;
+    }
+}
+
+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) {
     if (!strcmp(basename(argv[0]), "ueventd")) {
         return ueventd_main(argc, argv);
@@ -599,82 +954,121 @@
         return watchdogd_main(argc, argv);
     }
 
-    // Clear the umask.
-    umask(0);
+    if (REBOOT_BOOTLOADER_ON_PANIC) {
+        install_reboot_signal_handlers();
+    }
 
     add_environment("PATH", _PATH_DEFPATH);
 
-    bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
+    bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
 
-    // Get the basic filesystem setup we need put together in the initramdisk
-    // on / and then we'll let the rc file figure out the rest.
     if (is_first_stage) {
+        boot_clock::time_point start_time = boot_clock::now();
+
+        // Clear the umask.
+        umask(0);
+
+        // Get the basic filesystem setup we need put together in the initramdisk
+        // on / and then we'll let the rc file figure out the rest.
         mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
         mkdir("/dev/pts", 0755);
         mkdir("/dev/socket", 0755);
         mount("devpts", "/dev/pts", "devpts", 0, NULL);
         #define MAKE_STR(x) __STRING(x)
         mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
+        // Don't expose the raw commandline to unprivileged processes.
+        chmod("/proc/cmdline", 0440);
+        gid_t groups[] = { AID_READPROC };
+        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));
+        mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
+        mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
 
-    // We must have some place other than / to create the device nodes for
-    // kmsg and null, otherwise we won't be able to remount / read-only
-    // later on. Now that tmpfs is mounted on /dev, we can actually talk
-    // to the outside world.
-    open_devnull_stdio();
-    klog_init();
-    klog_set_level(KLOG_NOTICE_LEVEL);
+        // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
+        // talk to the outside world...
+        InitKernelLogging(argv);
 
-    NOTICE("init %s started!\n", is_first_stage ? "first stage" : "second stage");
+        LOG(INFO) << "init first stage started!";
 
-    if (!is_first_stage) {
-        // Indicate that booting is in progress to background fw loaders, etc.
-        close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
+        if (!DoFirstStageMount()) {
+            LOG(ERROR) << "Failed to mount required partitions early ...";
+            panic();
+        }
 
-        property_init();
+        SetInitAvbVersionInRecovery();
 
-        // If arguments are passed both on the command line and in DT,
-        // properties set in DT always have priority over the command-line ones.
-        process_kernel_dt();
-        process_kernel_cmdline();
+        // Set up SELinux, loading the SELinux policy.
+        selinux_initialize(true);
 
-        // Propagate the kernel variables to internal variables
-        // used by init as well as the current required properties.
-        export_kernel_boot_props();
-    }
-
-    // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
-    selinux_initialize(is_first_stage);
-
-    // If we're in the kernel domain, re-exec init to transition to the init domain now
-    // that the SELinux policy has been loaded.
-    if (is_first_stage) {
+        // We're in the kernel domain, so re-exec init to transition to the init domain now
+        // that the SELinux policy has been loaded.
         if (restorecon("/init") == -1) {
-            ERROR("restorecon failed: %s\n", strerror(errno));
+            PLOG(ERROR) << "restorecon failed";
             security_failure();
         }
+
+        setenv("INIT_SECOND_STAGE", "true", 1);
+
+        static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
+        uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
+        setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ms).c_str(), 1);
+
         char* path = argv[0];
-        char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
-        if (execv(path, args) == -1) {
-            ERROR("execv(\"%s\") failed: %s\n", path, strerror(errno));
-            security_failure();
-        }
+        char* args[] = { path, nullptr };
+        execv(path, args);
+
+        // execv() only returns if an error happened, in which case we
+        // panic and never fall through this conditional.
+        PLOG(ERROR) << "execv(\"" << path << "\") failed";
+        security_failure();
     }
 
-    // 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.
-    NOTICE("Running restorecon...\n");
-    restorecon("/dev");
-    restorecon("/dev/socket");
-    restorecon("/dev/__properties__");
-    restorecon("/property_contexts");
-    restorecon_recursive("/sys");
+    // At this point we're in the second stage of init.
+    InitKernelLogging(argv);
+    LOG(INFO) << "init second stage started!";
+
+    // Set up a session keyring that all processes will have access to. It
+    // will hold things like FBE encryption keys. No process should override
+    // its session keyring.
+    keyctl(KEYCTL_GET_KEYRING_ID, KEY_SPEC_SESSION_KEYRING, 1);
+
+    // Indicate that booting is in progress to background fw loaders, etc.
+    close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
+
+    property_init();
+
+    // If arguments are passed both on the command line and in DT,
+    // properties set in DT always have priority over the command-line ones.
+    process_kernel_dt();
+    process_kernel_cmdline();
+
+    // Propagate the kernel variables to internal variables
+    // used by init as well as the current required properties.
+    export_kernel_boot_props();
+
+    // Make the time that init started available for bootstat to log.
+    property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
+    property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
+
+    // Set libavb version for Framework-only OTA match in Treble build.
+    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);
+    selinux_restore_context();
 
     epoll_fd = epoll_create1(EPOLL_CLOEXEC);
     if (epoll_fd == -1) {
-        ERROR("epoll_create1 failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "epoll_create1 failed";
         exit(1);
     }
 
@@ -683,6 +1077,7 @@
     property_load_boot_defaults();
     export_oem_lock_status();
     start_property_service();
+    set_usb_controller();
 
     const BuiltinFunctionMap function_map;
     Action::set_function_map(&function_map);
@@ -691,7 +1086,24 @@
     parser.AddSectionParser("service",std::make_unique<ServiceParser>());
     parser.AddSectionParser("on", std::make_unique<ActionParser>());
     parser.AddSectionParser("import", std::make_unique<ImportParser>());
-    parser.ParseConfig("/init.rc");
+    std::string bootscript = GetProperty("ro.boot.init_rc", "");
+    if (bootscript.empty()) {
+        parser.ParseConfig("/init.rc");
+        parser.set_is_system_etc_init_loaded(
+                parser.ParseConfig("/system/etc/init"));
+        parser.set_is_vendor_etc_init_loaded(
+                parser.ParseConfig("/vendor/etc/init"));
+        parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init"));
+    } else {
+        parser.ParseConfig(bootscript);
+        parser.set_is_system_etc_init_loaded(true);
+        parser.set_is_vendor_etc_init_loaded(true);
+        parser.set_is_odm_etc_init_loaded(true);
+    }
+
+    // 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();
 
@@ -702,6 +1114,7 @@
     // ... so that we can start queuing up actions that require stuff from /dev.
     am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
     am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
+    am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict");
     am.QueueBuiltinAction(keychord_init_action, "keychord_init");
     am.QueueBuiltinAction(console_init_action, "console_init");
 
@@ -713,7 +1126,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 {
@@ -724,28 +1137,29 @@
     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
 
     while (true) {
-        if (!waiting_for_exec) {
+        // By default, sleep until something happens.
+        int epoll_timeout_ms = -1;
+
+        if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
             am.ExecuteOneCommand();
+        }
+        if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
             restart_processes();
-        }
 
-        int timeout = -1;
-        if (process_needs_restart) {
-            timeout = (process_needs_restart - gettime()) * 1000;
-            if (timeout < 0)
-                timeout = 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 (am.HasMoreCommands()) {
-            timeout = 0;
+            // If there's more work to do, wake up again immediately.
+            if (am.HasMoreCommands()) epoll_timeout_ms = 0;
         }
 
-        bootchart_sample(&timeout);
-
         epoll_event ev;
-        int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
+        int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
         if (nr == -1) {
-            ERROR("epoll_wait failed: %s\n", strerror(errno));
+            PLOG(ERROR) << "epoll_wait failed";
         } else if (nr == 1) {
             ((void (*)()) ev.data.ptr)();
         }
diff --git a/init/init.h b/init/init.h
index 345d442..1da3350 100644
--- a/init/init.h
+++ b/init/init.h
@@ -19,26 +19,19 @@
 
 #include <string>
 
-class Action;
-class Service;
-
-#define COMMAND_RETRY_TIMEOUT 5
-
 extern const char *ENV[32];
-extern bool waiting_for_exec;
-extern int have_console;
-extern std::string console_name;
+extern std::string default_console;
 extern struct selabel_handle *sehandle;
 extern struct selabel_handle *sehandle_prop;
 
 void handle_control_message(const std::string& msg, const std::string& arg);
 
-void property_changed(const char *name, const char *value);
-
-int selinux_reload_policy(void);
+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_property(const char *name, const char *value);
+
 #endif  /* _INIT_INIT_H */
diff --git a/init/init_first_stage.cpp b/init/init_first_stage.cpp
new file mode 100644
index 0000000..bcc8d1b
--- /dev/null
+++ b/init/init_first_stage.cpp
@@ -0,0 +1,466 @@
+/*
+ * 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();
+    void InitVerityDevice(const std::string& verity_device);
+    bool MountPartitions();
+
+    virtual coldboot_action_t ColdbootCallback(uevent* uevent);
+
+    // Pure virtual functions.
+    virtual bool GetRequiredDevices() = 0;
+    virtual bool SetUpDmVerity(fstab_rec* fstab_rec) = 0;
+
+    bool need_dm_verity_;
+    // 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_;
+    std::set<std::string> required_devices_partition_names_;
+};
+
+class FirstStageMountVBootV1 : public FirstStageMount {
+  public:
+    FirstStageMountVBootV1() = default;
+    ~FirstStageMountVBootV1() override = default;
+
+  protected:
+    bool GetRequiredDevices() override;
+    bool SetUpDmVerity(fstab_rec* fstab_rec) override;
+};
+
+class FirstStageMountVBootV2 : public FirstStageMount {
+  public:
+    friend void SetInitAvbVersionInRecovery();
+
+    FirstStageMountVBootV2();
+    ~FirstStageMountVBootV2() override = default;
+
+  protected:
+    coldboot_action_t ColdbootCallback(uevent* uevent) override;
+    bool GetRequiredDevices() override;
+    bool SetUpDmVerity(fstab_rec* fstab_rec) override;
+    bool InitAvbHandle();
+
+    std::string device_tree_vbmeta_parts_;
+    FsManagerAvbUniquePtr avb_handle_;
+    ByNameSymlinkMap by_name_symlink_map_;
+};
+
+// 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()
+    : need_dm_verity_(false), 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() {
+    if (!GetRequiredDevices()) return false;
+
+    InitRequiredDevices();
+
+    // InitRequiredDevices() will remove found partitions from required_devices_partition_names_.
+    // So if it isn't empty here, it means some partitions are not found.
+    if (!required_devices_partition_names_.empty()) {
+        LOG(ERROR) << __FUNCTION__ << "(): partition(s) not found: "
+                   << android::base::Join(required_devices_partition_names_, ", ");
+        return false;
+    } else {
+        return true;
+    }
+}
+
+// Creates devices with uevent->partition_name matching one in the member variable
+// required_devices_partition_names_. Found partitions will then be removed from it
+// for the subsequent member function to check which devices are NOT created.
+void FirstStageMount::InitRequiredDevices() {
+    if (required_devices_partition_names_.empty()) {
+        return;
+    }
+
+    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 && uevent->path == dm_path) return COLDBOOT_STOP;
+            return COLDBOOT_CONTINUE;  // dm_path not found, continue to find it.
+        });
+    }
+
+    device_init(nullptr,
+                [this](uevent* uevent) -> coldboot_action_t { return ColdbootCallback(uevent); });
+
+    device_close();
+}
+
+coldboot_action_t FirstStageMount::ColdbootCallback(uevent* uevent) {
+    // We need platform devices to create symlinks.
+    if (!strncmp(uevent->subsystem, "platform", 8)) {
+        return COLDBOOT_CREATE;
+    }
+
+    // Ignores everything that is not a block device.
+    if (strncmp(uevent->subsystem, "block", 5)) {
+        return COLDBOOT_CONTINUE;
+    }
+
+    if (uevent->partition_name) {
+        // Matches partition name to create device nodes.
+        // Both required_devices_partition_names_ and uevent->partition_name have A/B
+        // suffix when A/B is used.
+        auto iter = required_devices_partition_names_.find(uevent->partition_name);
+        if (iter != required_devices_partition_names_.end()) {
+            LOG(VERBOSE) << __FUNCTION__ << "(): found partition: " << *iter;
+            required_devices_partition_names_.erase(iter);
+            if (required_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 && 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::string verity_loc_device;
+    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)) {
+            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_) {
+        required_devices_partition_names_.emplace(basename(fstab_rec->blk_device));
+    }
+
+    if (!verity_loc_device.empty()) {
+        required_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 partitions from device tree.
+// /{
+//     firmware {
+//         android {
+//             vbmeta {
+//                 compatible = "android,vbmeta";
+//                 parts = "vbmeta,boot,system,vendor"
+//             };
+//         };
+//     };
+//  }
+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;
+    }
+}
+
+bool FirstStageMountVBootV2::GetRequiredDevices() {
+    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)) {
+            need_dm_verity_ = true;
+        }
+        required_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 (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) {
+            // required_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
+            required_devices_partition_names_.emplace(partition + ab_suffix);
+        }
+    }
+    return true;
+}
+
+coldboot_action_t FirstStageMountVBootV2::ColdbootCallback(uevent* uevent) {
+    // Invokes the parent function to see if any desired partition has been found.
+    // If yes, record the by-name symlink for creating FsManagerAvbHandle later.
+    coldboot_action_t parent_callback_ret = FirstStageMount::ColdbootCallback(uevent);
+
+    // Skips the uevent if the parent function returns COLDBOOT_CONTINUE (meaning
+    // that the uevent was skipped) or there is no uevent->partition_name to
+    // create the by-name symlink.
+    if (parent_callback_ret != COLDBOOT_CONTINUE && uevent->partition_name) {
+        // get_block_device_symlinks() will return three symlinks at most, depending on
+        // the content of uevent. by-name symlink will be at [0] if uevent->partition_name
+        // is not empty. e.g.,
+        //   - /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
+        char** links = get_block_device_symlinks(uevent);
+        if (links && links[0]) {
+            auto[it, inserted] = by_name_symlink_map_.emplace(uevent->partition_name, links[0]);
+            if (!inserted) {
+                LOG(ERROR) << "Partition '" << uevent->partition_name
+                           << "' already existed in the by-name symlink map with a value of '"
+                           << it->second << "', new value '" << links[0] << "' will be ignored.";
+            }
+        }
+    }
+
+    return parent_callback_ret;
+}
+
+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.
+
+    if (by_name_symlink_map_.empty()) {
+        LOG(ERROR) << "by_name_symlink_map_ is empty";
+        return false;
+    }
+
+    avb_handle_ = FsManagerAvbHandle::Open(std::move(by_name_symlink_map_));
+    by_name_symlink_map_.clear();  // Removes all elements after the above std::move().
+
+    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(std::move(avb_first_mount.by_name_symlink_map_));
+    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/init/init_first_stage.h b/init/init_first_stage.h
new file mode 100644
index 0000000..170a24c
--- /dev/null
+++ b/init/init_first_stage.h
@@ -0,0 +1,23 @@
+/*
+ * 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_FIRST_STAGE_H
+#define _INIT_FIRST_STAGE_H
+
+bool DoFirstStageMount();
+void SetInitAvbVersionInRecovery();
+
+#endif
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index f2e5d6d..a192862 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -93,10 +93,10 @@
 }
 
 bool Parser::ParseConfigFile(const std::string& path) {
-    INFO("Parsing file %s...\n", path.c_str());
+    LOG(INFO) << "Parsing file " << path << "...";
     Timer t;
     std::string data;
-    if (!read_file(path.c_str(), &data)) {
+    if (!read_file(path, &data)) {
         return false;
     }
 
@@ -106,19 +106,15 @@
         sp.second->EndFile(path);
     }
 
-    // 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) DumpState();
-
-    NOTICE("(Parsing %s took %.2fs.)\n", path.c_str(), t.duration());
+    LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
     return true;
 }
 
 bool Parser::ParseConfigDir(const std::string& path) {
-    INFO("Parsing directory %s...\n", path.c_str());
+    LOG(INFO) << "Parsing directory " << path << "...";
     std::unique_ptr<DIR, int(*)(DIR*)> config_dir(opendir(path.c_str()), closedir);
     if (!config_dir) {
-        ERROR("Could not import directory '%s'\n", path.c_str());
+        PLOG(ERROR) << "Could not import directory '" << path << "'";
         return false;
     }
     dirent* current_file;
@@ -135,7 +131,7 @@
     std::sort(files.begin(), files.end());
     for (const auto& file : files) {
         if (!ParseConfigFile(file)) {
-            ERROR("Could not import file '%s'\n", file.c_str());
+            LOG(ERROR) << "could not import file '" << file << "'";
         }
     }
     return true;
diff --git a/init/init_parser.h b/init/init_parser.h
index 5ed30ad..f66ba52 100644
--- a/init/init_parser.h
+++ b/init/init_parser.h
@@ -41,6 +41,18 @@
     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;
+    }
+    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();
@@ -50,6 +62,9 @@
     bool ParseConfigDir(const std::string& path);
 
     std::map<std::string, std::unique_ptr<SectionParser>> section_parsers_;
+    bool is_system_etc_init_loaded_ = false;
+    bool is_vendor_etc_init_loaded_ = false;
+    bool is_odm_etc_init_loaded_ = false;
 };
 
 #endif
diff --git a/init/keychords.cpp b/init/keychords.cpp
index 1468c57..5801ea8 100644
--- a/init/keychords.cpp
+++ b/init/keychords.cpp
@@ -23,9 +23,10 @@
 #include <linux/keychord.h>
 #include <unistd.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;
@@ -43,7 +44,7 @@
         size = sizeof(*keychord) + svc->keycodes().size() * sizeof(keychord->keycodes[0]);
         keychords = (input_keychord*) realloc(keychords, keychords_length + size);
         if (!keychords) {
-            ERROR("could not allocate keychords\n");
+            PLOG(ERROR) << "could not allocate keychords";
             keychords_length = 0;
             keychords_count = 0;
             return;
@@ -69,22 +70,22 @@
 
     ret = read(keychord_fd, &id, sizeof(id));
     if (ret != sizeof(id)) {
-        ERROR("could not read keychord id\n");
+        PLOG(ERROR) << "could not read keychord id";
         return;
     }
 
     // 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) {
-            NOTICE("Starting service '%s' from keychord %d\n", svc->name().c_str(), id);
+            LOG(INFO) << "Starting service " << svc->name() << " from keychord " << id;
             svc->Start();
         } else {
-            ERROR("Service for keychord %d not found\n", id);
+            LOG(ERROR) << "Service for keychord " << id << " not found";
         }
     } else {
-        WARNING("Not starting service for keychord %d because ADB is disabled\n", id);
+        LOG(WARNING) << "Not starting service for keychord " << id << " because ADB is disabled";
     }
 }
 
@@ -98,13 +99,13 @@
 
     keychord_fd = TEMP_FAILURE_RETRY(open("/dev/keychord", O_RDWR | O_CLOEXEC));
     if (keychord_fd == -1) {
-        ERROR("could not open /dev/keychord: %s\n", strerror(errno));
+        PLOG(ERROR) << "could not open /dev/keychord";
         return;
     }
 
     int ret = write(keychord_fd, keychords, keychords_length);
     if (ret != keychords_length) {
-        ERROR("could not configure /dev/keychord %d: %s\n", ret, strerror(errno));
+        PLOG(ERROR) << "could not configure /dev/keychord " << ret;
         close(keychord_fd);
     }
 
diff --git a/init/keyutils.h b/init/keyutils.h
new file mode 100644
index 0000000..de01beb
--- /dev/null
+++ b/init/keyutils.h
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+/* Miniature version of a header-only keyutils.h (no library required) */
+
+#ifndef _INIT_KEYUTILS_H_
+#define _INIT_KEYUTILS_H_
+
+#ifndef KEYUTILS_H /* walk away if the _real_ one exists */
+
+#include <linux/keyctl.h>
+#include <stdarg.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+static inline long keyctl(int cmd, ...) {
+    va_list va;
+    unsigned long arg2, arg3, arg4, arg5;
+
+    va_start(va, cmd);
+    arg2 = va_arg(va, unsigned long);
+    arg3 = va_arg(va, unsigned long);
+    arg4 = va_arg(va, unsigned long);
+    arg5 = va_arg(va, unsigned long);
+    va_end(va);
+    return syscall(__NR_keyctl, cmd, arg2, arg3, arg4, arg5);
+}
+
+#endif
+
+#endif
diff --git a/init/log.cpp b/init/log.cpp
index ace9fd7..0615730 100644
--- a/init/log.cpp
+++ b/init/log.cpp
@@ -16,54 +16,42 @@
 
 #include "log.h"
 
-#include <stdlib.h>
+#include <fcntl.h>
+#include <linux/audit.h>
 #include <string.h>
-#include <sys/uio.h>
 
+#include <android-base/logging.h>
 #include <selinux/selinux.h>
 
-#include <android-base/stringprintf.h>
-
-static void init_klog_vwrite(int level, const char* fmt, va_list ap) {
-    static const char* tag = basename(getprogname());
-
-    if (level > klog_get_level()) return;
-
-    // The kernel's printk buffer is only 1024 bytes.
-    // TODO: should we automatically break up long lines into multiple lines?
-    // Or we could log but with something like "..." at the end?
-    char buf[1024];
-    size_t prefix_size = snprintf(buf, sizeof(buf), "<%d>%s: ", level, tag);
-    size_t msg_size = vsnprintf(buf + prefix_size, sizeof(buf) - prefix_size, fmt, ap);
-    if (msg_size >= sizeof(buf) - prefix_size) {
-        msg_size = snprintf(buf + prefix_size, sizeof(buf) - prefix_size,
-                            "(%zu-byte message too long for printk)\n", msg_size);
+void InitKernelLogging(char* argv[]) {
+    // Make stdin/stdout/stderr all point to /dev/null.
+    int fd = open("/sys/fs/selinux/null", O_RDWR);
+    if (fd == -1) {
+        int saved_errno = errno;
+        android::base::InitLogging(argv, &android::base::KernelLogger);
+        errno = saved_errno;
+        PLOG(FATAL) << "Couldn't open /sys/fs/selinux/null";
     }
+    dup2(fd, 0);
+    dup2(fd, 1);
+    dup2(fd, 2);
+    if (fd > 2) close(fd);
 
-    iovec iov[1];
-    iov[0].iov_base = buf;
-    iov[0].iov_len = prefix_size + msg_size;
-
-    klog_writev(level, iov, 1);
-}
-
-void init_klog_write(int level, const char* fmt, ...) {
-    va_list ap;
-    va_start(ap, fmt);
-    init_klog_vwrite(level, fmt, ap);
-    va_end(ap);
+    android::base::InitLogging(argv, &android::base::KernelLogger);
 }
 
 int selinux_klog_callback(int type, const char *fmt, ...) {
-    int level = KLOG_ERROR_LEVEL;
+    android::base::LogSeverity severity = android::base::ERROR;
     if (type == SELINUX_WARNING) {
-        level = KLOG_WARNING_LEVEL;
+        severity = android::base::WARNING;
     } else if (type == SELINUX_INFO) {
-        level = KLOG_INFO_LEVEL;
+        severity = android::base::INFO;
     }
+    char buf[1024];
     va_list ap;
     va_start(ap, fmt);
-    init_klog_vwrite(level, fmt, ap);
+    vsnprintf(buf, sizeof(buf), fmt, ap);
     va_end(ap);
+    android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
     return 0;
 }
diff --git a/init/log.h b/init/log.h
index c5c30af..8fa6d74 100644
--- a/init/log.h
+++ b/init/log.h
@@ -17,16 +17,10 @@
 #ifndef _INIT_LOG_H_
 #define _INIT_LOG_H_
 
-#include <cutils/klog.h>
+#include <android-base/logging.h>
 
-#define ERROR(x...)   init_klog_write(KLOG_ERROR_LEVEL, x)
-#define WARNING(x...) init_klog_write(KLOG_WARNING_LEVEL, x)
-#define NOTICE(x...)  init_klog_write(KLOG_NOTICE_LEVEL, x)
-#define INFO(x...)    init_klog_write(KLOG_INFO_LEVEL, x)
-#define DEBUG(x...)   init_klog_write(KLOG_DEBUG_LEVEL, x)
-#define VERBOSE(x...) init_klog_write(KLOG_DEBUG_LEVEL, x)
+void InitKernelLogging(char* argv[]);
 
-void init_klog_write(int level, const char* fmt, ...) __printflike(2, 3);
 int selinux_klog_callback(int level, const char* fmt, ...) __printflike(2, 3);
 
 #endif
diff --git a/init/parser.cpp b/init/parser.cpp
index 8193729..45862b7 100644
--- a/init/parser.cpp
+++ b/init/parser.cpp
@@ -12,7 +12,7 @@
     char buf[128];
     int off;
 
-    snprintf(buf, 128, "%s: %d: ", state->filename, state->line);
+    snprintf(buf, sizeof(buf), "%s: %d: ", state->filename, state->line);
     buf[127] = 0;
     off = strlen(buf);
 
@@ -20,7 +20,7 @@
     vsnprintf(buf + off, 128 - off, fmt, ap);
     va_end(ap);
     buf[127] = 0;
-    ERROR("%s", buf);
+    LOG(ERROR) << buf;
 }
 
 int next_token(struct parse_state *state)
diff --git a/init/parser/tokenizer.h b/init/parser/tokenizer.h
index 8312a08..ade8f73 100644
--- a/init/parser/tokenizer.h
+++ b/init/parser/tokenizer.h
@@ -36,7 +36,7 @@
 // a TOK_NEWLINE will not be generated for that line.
 class Tokenizer {
  public:
-  Tokenizer(const std::string& data);
+  explicit Tokenizer(const std::string& data);
   ~Tokenizer();
 
   enum TokenType { TOK_START, TOK_END, TOK_NEWLINE, TOK_TEXT };
diff --git a/init/perfboot.py b/init/perfboot.py
index 91e6c2b..713290b 100755
--- a/init/perfboot.py
+++ b/init/perfboot.py
@@ -191,9 +191,9 @@
 
 def init_perf(device, output, record_list, tags):
     device.wait()
-    build_type = device.get_prop('ro.build.type')
+    debuggable = device.get_prop('ro.debuggable')
     original_dropbox_max_files = None
-    if build_type != 'user':
+    if debuggable == '1':
         # Workaround for Dropbox issue (http://b/20890386).
         original_dropbox_max_files = disable_dropbox(device)
 
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 5c1ae79..73954fe 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <inttypes.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
@@ -27,10 +28,7 @@
 #include <sys/poll.h>
 
 #include <memory>
-
-#include <cutils/misc.h>
-#include <cutils/sockets.h>
-#include <cutils/multiuser.h>
+#include <vector>
 
 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
 #include <sys/_system_properties.h>
@@ -41,13 +39,16 @@
 #include <sys/types.h>
 #include <netinet/in.h>
 #include <sys/mman.h>
-#include <private/android_filesystem_config.h>
 
+#include <selinux/android.h>
 #include <selinux/selinux.h>
 #include <selinux/label.h>
 
-#include <fs_mgr.h>
 #include <android-base/file.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <fs_mgr.h>
 #include "bootimg.h"
 
 #include "property_service.h"
@@ -55,8 +56,9 @@
 #include "util.h"
 #include "log.h"
 
+using android::base::StringPrintf;
+
 #define PERSISTENT_PROPERTY_DIR  "/data/property"
-#define FSTAB_PREFIX "/fstab."
 #define RECOVERY_MOUNT_POINT "/recovery"
 
 static int persistent_properties_loaded = 0;
@@ -65,35 +67,35 @@
 
 void property_init() {
     if (__system_property_area_init()) {
-        ERROR("Failed to initialize property area\n");
+        LOG(ERROR) << "Failed to initialize property area";
         exit(1);
     }
 }
 
-static int check_mac_perms(const char *name, char *sctx, struct ucred *cr)
-{
-    char *tctx = NULL;
-    int result = 0;
+static bool check_mac_perms(const std::string& name, char* sctx, struct ucred* cr) {
+
+    if (!sctx) {
+      return false;
+    }
+
+    if (!sehandle_prop) {
+      return false;
+    }
+
+    char* tctx = nullptr;
+    if (selabel_lookup(sehandle_prop, &tctx, name.c_str(), 1) != 0) {
+      return false;
+    }
+
     property_audit_data audit_data;
 
-    if (!sctx)
-        goto err;
-
-    if (!sehandle_prop)
-        goto err;
-
-    if (selabel_lookup(sehandle_prop, &tctx, name, 1) != 0)
-        goto err;
-
-    audit_data.name = name;
+    audit_data.name = name.c_str();
     audit_data.cr = cr;
 
-    if (selinux_check_access(sctx, tctx, "property_service", "set", reinterpret_cast<void*>(&audit_data)) == 0)
-        result = 1;
+    bool has_access = (selinux_check_access(sctx, tctx, "property_service", "set", &audit_data) == 0);
 
     freecon(tctx);
- err:
-    return result;
+    return has_access;
 }
 
 static int check_control_mac_perms(const char *name, char *sctx, struct ucred *cr)
@@ -113,12 +115,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];
@@ -128,7 +124,7 @@
     snprintf(tempPath, sizeof(tempPath), "%s/.temp.XXXXXX", PERSISTENT_PROPERTY_DIR);
     fd = mkstemp(tempPath);
     if (fd < 0) {
-        ERROR("Unable to write persistent property to temp file %s: %s\n", tempPath, strerror(errno));
+        PLOG(ERROR) << "Unable to write persistent property to temp file " << tempPath;
         return;
     }
     write(fd, value, strlen(value));
@@ -137,28 +133,27 @@
 
     snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);
     if (rename(tempPath, path)) {
+        PLOG(ERROR) << "Unable to rename persistent property file " << tempPath << " to " << path;
         unlink(tempPath);
-        ERROR("Unable to rename persistent property file %s to %s\n", tempPath, path);
     }
 }
 
-static bool is_legal_property_name(const char* name, size_t namelen)
-{
-    size_t i;
-    if (namelen >= PROP_NAME_MAX) return false;
+bool is_legal_property_name(const std::string& name) {
+    size_t namelen = name.size();
+
     if (namelen < 1) return false;
     if (name[0] == '.') return false;
     if (name[namelen - 1] == '.') return false;
 
-    /* Only allow alphanumeric, plus '.', '-', or '_' */
+    /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */
     /* Don't allow ".." to appear in a property name */
-    for (i = 0; i < namelen; i++) {
+    for (size_t i = 0; i < namelen; i++) {
         if (name[i] == '.') {
             // i=0 is guaranteed to never have a dot. See above.
             if (name[i-1] == '.') return false;
             continue;
         }
-        if (name[i] == '_' || name[i] == '-') continue;
+        if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue;
         if (name[i] >= 'a' && name[i] <= 'z') continue;
         if (name[i] >= 'A' && name[i] <= 'Z') continue;
         if (name[i] >= '0' && name[i] <= '9') continue;
@@ -168,160 +163,288 @@
     return true;
 }
 
-static int property_set_impl(const char* name, const char* value) {
-    size_t namelen = strlen(name);
-    size_t valuelen = strlen(value);
+uint32_t property_set(const std::string& name, const std::string& value) {
+    size_t valuelen = value.size();
 
-    if (!is_legal_property_name(name, namelen)) return -1;
-    if (valuelen >= PROP_VALUE_MAX) return -1;
+    if (!is_legal_property_name(name)) {
+        LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: bad name";
+        return PROP_ERROR_INVALID_NAME;
+    }
 
-    if (strcmp("selinux.reload_policy", name) == 0 && strcmp("1", value) == 0) {
-        if (selinux_reload_policy() != 0) {
-            ERROR("Failed to reload policy\n");
-        }
-    } else if (strcmp("selinux.restorecon_recursive", name) == 0 && valuelen > 0) {
-        if (restorecon_recursive(value) != 0) {
-            ERROR("Failed to restorecon_recursive %s\n", value);
+    if (valuelen >= PROP_VALUE_MAX) {
+        LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                   << "value too long";
+        return PROP_ERROR_INVALID_VALUE;
+    }
+
+    if (name == "selinux.restorecon_recursive" && valuelen > 0) {
+        if (restorecon(value.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
+            LOG(ERROR) << "Failed to restorecon_recursive " << value;
         }
     }
 
-    prop_info* pi = (prop_info*) __system_property_find(name);
+    prop_info* pi = (prop_info*) __system_property_find(name.c_str());
+    if (pi != nullptr) {
+        // ro.* properties are actually "write-once".
+        if (android::base::StartsWith(name, "ro.")) {
+            LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                       << "property already set";
+            return PROP_ERROR_READ_ONLY_PROPERTY;
+        }
 
-    if(pi != 0) {
-        /* ro.* properties may NEVER be modified once set */
-        if(!strncmp(name, "ro.", 3)) return -1;
-
-        __system_property_update(pi, value, valuelen);
+        __system_property_update(pi, value.c_str(), valuelen);
     } else {
-        int rc = __system_property_add(name, namelen, value, valuelen);
+        int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
         if (rc < 0) {
-            return rc;
+            LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                       << "__system_property_add failed";
+            return PROP_ERROR_SET_FAILED;
         }
     }
-    /* If name starts with "net." treat as a DNS property. */
-    if (strncmp("net.", name, strlen("net.")) == 0)  {
-        if (strcmp("net.change", name) == 0) {
-            return 0;
-        }
-       /*
-        * The 'net.change' property is a special property used track when any
-        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
-        * contains the last updated 'net.*' property.
-        */
-        property_set("net.change", name);
-    } else if (persistent_properties_loaded &&
-            strncmp("persist.", name, strlen("persist.")) == 0) {
-        /*
-         * Don't write properties to disk until after we have read all default properties
-         * to prevent them from being overwritten by default values.
-         */
-        write_persistent_property(name, value);
+
+    // Don't write properties to disk until after we have read all default
+    // properties to prevent them from being overwritten by default values.
+    if (persistent_properties_loaded && android::base::StartsWith(name, "persist.")) {
+        write_persistent_property(name.c_str(), value.c_str());
     }
     property_changed(name, value);
-    return 0;
+    return PROP_SUCCESS;
 }
 
-int property_set(const char* name, const char* value) {
-    int rc = property_set_impl(name, value);
-    if (rc == -1) {
-        ERROR("property_set(\"%s\", \"%s\") failed\n", name, value);
+class SocketConnection {
+ public:
+  SocketConnection(int socket, const struct ucred& cred)
+      : socket_(socket), cred_(cred) {}
+
+  ~SocketConnection() {
+    close(socket_);
+  }
+
+  bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
+    return RecvFully(value, sizeof(*value), timeout_ms);
+  }
+
+  bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
+    return RecvFully(chars, size, timeout_ms);
+  }
+
+  bool RecvString(std::string* value, uint32_t* timeout_ms) {
+    uint32_t len = 0;
+    if (!RecvUint32(&len, timeout_ms)) {
+      return false;
     }
-    return rc;
-}
 
-static void handle_property_set_fd()
-{
-    prop_msg msg;
-    int s;
-    int r;
-    struct ucred cr;
-    struct sockaddr_un addr;
-    socklen_t addr_size = sizeof(addr);
-    socklen_t cr_size = sizeof(cr);
-    char * source_ctx = NULL;
+    if (len == 0) {
+      *value = "";
+      return true;
+    }
+
+    // http://b/35166374: don't allow init to make arbitrarily large allocations.
+    if (len > 0xffff) {
+      LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
+      errno = ENOMEM;
+      return false;
+    }
+
+    std::vector<char> chars(len);
+    if (!RecvChars(&chars[0], len, timeout_ms)) {
+      return false;
+    }
+
+    *value = std::string(&chars[0], len);
+    return true;
+  }
+
+  bool SendUint32(uint32_t value) {
+    int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0));
+    return result == sizeof(value);
+  }
+
+  int socket() {
+    return socket_;
+  }
+
+  const struct ucred& cred() {
+    return cred_;
+  }
+
+ private:
+  bool PollIn(uint32_t* timeout_ms) {
     struct pollfd ufds[1];
-    const int timeout_ms = 2 * 1000;  /* Default 2 sec timeout for caller to send property. */
-    int nr;
-
-    if ((s = accept(property_set_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
-        return;
-    }
-
-    /* Check socket options here */
-    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
-        close(s);
-        ERROR("Unable to receive socket options\n");
-        return;
-    }
-
-    ufds[0].fd = s;
+    ufds[0].fd = socket_;
     ufds[0].events = POLLIN;
     ufds[0].revents = 0;
-    nr = TEMP_FAILURE_RETRY(poll(ufds, 1, timeout_ms));
-    if (nr == 0) {
-        ERROR("sys_prop: timeout waiting for uid=%d to send property message.\n", cr.uid);
-        close(s);
-        return;
-    } else if (nr < 0) {
-        ERROR("sys_prop: error waiting for uid=%d to send property message: %s\n", cr.uid, strerror(errno));
-        close(s);
-        return;
-    }
+    while (*timeout_ms > 0) {
+      Timer timer;
+      int nr = poll(ufds, 1, *timeout_ms);
+      uint64_t millis = timer.duration_ms();
+      *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
 
-    r = TEMP_FAILURE_RETRY(recv(s, &msg, sizeof(msg), MSG_DONTWAIT));
-    if(r != sizeof(prop_msg)) {
-        ERROR("sys_prop: mis-match msg size received: %d expected: %zu: %s\n",
-              r, sizeof(prop_msg), strerror(errno));
-        close(s);
-        return;
-    }
+      if (nr > 0) {
+        return true;
+      }
 
-    switch(msg.cmd) {
-    case PROP_MSG_SETPROP:
-        msg.name[PROP_NAME_MAX-1] = 0;
-        msg.value[PROP_VALUE_MAX-1] = 0;
-
-        if (!is_legal_property_name(msg.name, strlen(msg.name))) {
-            ERROR("sys_prop: illegal property name. Got: \"%s\"\n", msg.name);
-            close(s);
-            return;
-        }
-
-        getpeercon(s, &source_ctx);
-
-        if(memcmp(msg.name,"ctl.",4) == 0) {
-            // Keep the old close-socket-early behavior when handling
-            // ctl.* properties.
-            close(s);
-            if (check_control_mac_perms(msg.value, source_ctx, &cr)) {
-                handle_control_message((char*) msg.name + 4, (char*) msg.value);
-            } else {
-                ERROR("sys_prop: Unable to %s service ctl [%s] uid:%d gid:%d pid:%d\n",
-                        msg.name + 4, msg.value, cr.uid, cr.gid, cr.pid);
-            }
-        } else {
-            if (check_mac_perms(msg.name, source_ctx, &cr)) {
-                property_set((char*) msg.name, (char*) msg.value);
-            } else {
-                ERROR("sys_prop: permission denied uid:%d  name:%s\n",
-                      cr.uid, msg.name);
-            }
-
-            // Note: bionic's property client code assumes that the
-            // property server will not close the socket until *AFTER*
-            // the property is written to memory.
-            close(s);
-        }
-        freecon(source_ctx);
+      if (nr == 0) {
+        // Timeout
         break;
+      }
+
+      if (nr < 0 && errno != EINTR) {
+        PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid << " to send property message";
+        return false;
+      } else { // errno == EINTR
+        // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
+        // to avoid slowing init down by causing EINTR with under millisecond timeout.
+        if (*timeout_ms > 0) {
+          --(*timeout_ms);
+        }
+      }
+    }
+
+    LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid << " to send property message.";
+    return false;
+  }
+
+  bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
+    size_t bytes_left = size;
+    char* data = static_cast<char*>(data_ptr);
+    while (*timeout_ms > 0 && bytes_left > 0) {
+      if (!PollIn(timeout_ms)) {
+        return false;
+      }
+
+      int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT));
+      if (result <= 0) {
+        return false;
+      }
+
+      bytes_left -= result;
+      data += result;
+    }
+
+    return bytes_left == 0;
+  }
+
+  int socket_;
+  struct ucred cred_;
+
+  DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection);
+};
+
+static void handle_property_set(SocketConnection& socket,
+                                const std::string& name,
+                                const std::string& value,
+                                bool legacy_protocol) {
+  const char* cmd_name = legacy_protocol ? "PROP_MSG_SETPROP" : "PROP_MSG_SETPROP2";
+  if (!is_legal_property_name(name)) {
+    LOG(ERROR) << "sys_prop(" << cmd_name << "): illegal property name \"" << name << "\"";
+    socket.SendUint32(PROP_ERROR_INVALID_NAME);
+    return;
+  }
+
+  struct ucred cr = socket.cred();
+  char* source_ctx = nullptr;
+  getpeercon(socket.socket(), &source_ctx);
+
+  if (android::base::StartsWith(name, "ctl.")) {
+    if (check_control_mac_perms(value.c_str(), source_ctx, &cr)) {
+      handle_control_message(name.c_str() + 4, value.c_str());
+      if (!legacy_protocol) {
+        socket.SendUint32(PROP_SUCCESS);
+      }
+    } else {
+      LOG(ERROR) << "sys_prop(" << cmd_name << "): Unable to " << (name.c_str() + 4)
+                 << " service ctl [" << value << "]"
+                 << " uid:" << cr.uid
+                 << " gid:" << cr.gid
+                 << " pid:" << cr.pid;
+      if (!legacy_protocol) {
+        socket.SendUint32(PROP_ERROR_HANDLE_CONTROL_MESSAGE);
+      }
+    }
+  } else {
+    if (check_mac_perms(name, source_ctx, &cr)) {
+      uint32_t result = property_set(name, value);
+      if (!legacy_protocol) {
+        socket.SendUint32(result);
+      }
+    } else {
+      LOG(ERROR) << "sys_prop(" << cmd_name << "): permission denied uid:" << cr.uid << " name:" << name;
+      if (!legacy_protocol) {
+        socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
+      }
+    }
+  }
+
+  freecon(source_ctx);
+}
+
+static void handle_property_set_fd() {
+    static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
+
+    int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
+    if (s == -1) {
+        return;
+    }
+
+    struct ucred cr;
+    socklen_t cr_size = sizeof(cr);
+    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
+        close(s);
+        PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
+        return;
+    }
+
+    SocketConnection socket(s, cr);
+    uint32_t timeout_ms = kDefaultSocketTimeout;
+
+    uint32_t cmd = 0;
+    if (!socket.RecvUint32(&cmd, &timeout_ms)) {
+        PLOG(ERROR) << "sys_prop: error while reading command from the socket";
+        socket.SendUint32(PROP_ERROR_READ_CMD);
+        return;
+    }
+
+    switch (cmd) {
+    case PROP_MSG_SETPROP: {
+        char prop_name[PROP_NAME_MAX];
+        char prop_value[PROP_VALUE_MAX];
+
+        if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
+            !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
+          PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
+          return;
+        }
+
+        prop_name[PROP_NAME_MAX-1] = 0;
+        prop_value[PROP_VALUE_MAX-1] = 0;
+
+        handle_property_set(socket, prop_value, prop_value, true);
+        break;
+      }
+
+    case PROP_MSG_SETPROP2: {
+        std::string name;
+        std::string value;
+        if (!socket.RecvString(&name, &timeout_ms) ||
+            !socket.RecvString(&value, &timeout_ms)) {
+          PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
+          socket.SendUint32(PROP_ERROR_READ_DATA);
+          return;
+        }
+
+        handle_property_set(socket, name, value, false);
+        break;
+      }
 
     default:
-        close(s);
+        LOG(ERROR) << "sys_prop: invalid command " << cmd;
+        socket.SendUint32(PROP_ERROR_INVALID_CMD);
         break;
     }
 }
 
-static void load_properties_from_file(const char *, const char *);
+static bool load_properties_from_file(const char *, const char *);
 
 /*
  * Filter is used to decide which properties to load: NULL loads all keys,
@@ -383,18 +506,19 @@
     }
 }
 
-/*
- * Filter is used to decide which properties to load: NULL loads all keys,
- * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
- */
-static void load_properties_from_file(const char* filename, const char* filter) {
+// Filter is used to decide which properties to load: NULL loads all keys,
+// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
+static bool load_properties_from_file(const char* filename, const char* filter) {
     Timer t;
     std::string data;
-    if (read_file(filename, &data)) {
-        data.push_back('\n');
-        load_properties(&data[0], filter);
+    if (!read_file(filename, &data)) {
+        PLOG(WARNING) << "Couldn't load properties from " << filename;
+        return false;
     }
-    NOTICE("(Loading properties from %s took %.2fs.)\n", filename, t.duration());
+    data.push_back('\n');
+    load_properties(&data[0], filter);
+    LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
+    return true;
 }
 
 static void load_persistent_properties() {
@@ -402,8 +526,8 @@
 
     std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(PERSISTENT_PROPERTY_DIR), closedir);
     if (!dir) {
-        ERROR("Unable to open persistent property directory \"%s\": %s\n",
-              PERSISTENT_PROPERTY_DIR, strerror(errno));
+        PLOG(ERROR) << "Unable to open persistent property directory \""
+                    << PERSISTENT_PROPERTY_DIR << "\"";
         return;
     }
 
@@ -419,25 +543,23 @@
         // Open the file and read the property value.
         int fd = openat(dirfd(dir.get()), entry->d_name, O_RDONLY | O_NOFOLLOW);
         if (fd == -1) {
-            ERROR("Unable to open persistent property file \"%s\": %s\n",
-                  entry->d_name, strerror(errno));
+            PLOG(ERROR) << "Unable to open persistent property file \"" << entry->d_name << "\"";
             continue;
         }
 
         struct stat sb;
         if (fstat(fd, &sb) == -1) {
-            ERROR("fstat on property file \"%s\" failed: %s\n", entry->d_name, strerror(errno));
+            PLOG(ERROR) << "fstat on property file \"" << entry->d_name << "\" failed";
             close(fd);
             continue;
         }
 
         // File must not be accessible to others, be owned by root/root, and
         // not be a hard link to any other file.
-        if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || (sb.st_uid != 0) || (sb.st_gid != 0) ||
-                (sb.st_nlink != 1)) {
-            ERROR("skipping insecure property file %s (uid=%u gid=%u nlink=%u mode=%o)\n",
-                  entry->d_name, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid,
-                  (unsigned int)sb.st_nlink, sb.st_mode);
+        if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || sb.st_uid != 0 || sb.st_gid != 0 || sb.st_nlink != 1) {
+            PLOG(ERROR) << "skipping insecure property file " << entry->d_name
+                        << " (uid=" << sb.st_uid << " gid=" << sb.st_gid
+                        << " nlink=" << sb.st_nlink << " mode=" << std::oct << sb.st_mode << ")";
             close(fd);
             continue;
         }
@@ -448,23 +570,45 @@
             value[length] = 0;
             property_set(entry->d_name, value);
         } else {
-            ERROR("Unable to read persistent property file %s: %s\n",
-                  entry->d_name, strerror(errno));
+            PLOG(ERROR) << "Unable to read persistent property file " << entry->d_name;
         }
         close(fd);
     }
 }
 
+// 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(PROP_PATH_RAMDISK_DEFAULT, NULL);
+    if (!load_properties_from_file("/system/etc/prop.default", NULL)) {
+        // Try recovery path
+        if (!load_properties_from_file("/prop.default", NULL)) {
+            // Try legacy path
+            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(PROP_PATH_LOCAL_OVERRIDE, NULL);
-        }
+        load_properties_from_file("/data/local.prop", NULL);
     }
 }
 
@@ -477,32 +621,26 @@
     load_override_properties();
     /* Read persistent properties after all default values have been loaded. */
     load_persistent_properties();
+    property_set("ro.persistent_properties.ready", "true");
 }
 
 void load_recovery_id_prop() {
-    std::string ro_hardware = property_get("ro.hardware");
-    if (ro_hardware.empty()) {
-        ERROR("ro.hardware not set - unable to load recovery id\n");
-        return;
-    }
-    std::string fstab_filename = FSTAB_PREFIX + ro_hardware;
-
-    std::unique_ptr<fstab, void(*)(fstab*)> tab(fs_mgr_read_fstab(fstab_filename.c_str()),
-            fs_mgr_free_fstab);
-    if (!tab) {
-        ERROR("unable to read fstab %s: %s\n", fstab_filename.c_str(), strerror(errno));
+    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
+                                                               fs_mgr_free_fstab);
+    if (!fstab) {
+        PLOG(ERROR) << "unable to read default fstab";
         return;
     }
 
-    fstab_rec* rec = fs_mgr_get_entry_for_mount_point(tab.get(), RECOVERY_MOUNT_POINT);
+    fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab.get(), RECOVERY_MOUNT_POINT);
     if (rec == NULL) {
-        ERROR("/recovery not specified in fstab\n");
+        LOG(ERROR) << "/recovery not specified in fstab";
         return;
     }
 
     int fd = open(rec->blk_device, O_RDONLY);
     if (fd == -1) {
-        ERROR("error opening block device %s: %s\n", rec->blk_device, strerror(errno));
+        PLOG(ERROR) << "error opening block device " << rec->blk_device;
         return;
     }
 
@@ -511,24 +649,27 @@
         std::string hex = bytes_to_hex(reinterpret_cast<uint8_t*>(hdr.id), sizeof(hdr.id));
         property_set("ro.recovery_id", hex.c_str());
     } else {
-        ERROR("error reading /recovery: %s\n", strerror(errno));
+        PLOG(ERROR) << "error reading /recovery";
     }
 
     close(fd);
 }
 
 void load_system_props() {
-    load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
-    load_properties_from_file(PROP_PATH_VENDOR_BUILD, NULL);
-    load_properties_from_file(PROP_PATH_FACTORY, "ro.*");
+    load_properties_from_file("/system/build.prop", NULL);
+    load_properties_from_file("/odm/build.prop", NULL);
+    load_properties_from_file("/vendor/build.prop", NULL);
+    load_properties_from_file("/factory/factory.prop", "ro.*");
     load_recovery_id_prop();
 }
 
 void start_property_service() {
+    property_set("ro.property_service.version", "2");
+
     property_set_fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
                                     0666, 0, 0, NULL);
     if (property_set_fd == -1) {
-        ERROR("start_property_service socket creation failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "start_property_service socket creation failed";
         exit(1);
     }
 
diff --git a/init/property_service.h b/init/property_service.h
index dbaed34..994da63 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -27,13 +27,13 @@
     const char* name;
 };
 
-extern void property_init(void);
-extern void property_load_boot_defaults(void);
-extern void load_persist_props(void);
-extern void load_system_props(void);
-extern void start_property_service(void);
-std::string property_get(const char* name);
-extern int property_set(const char *name, const char *value);
+void property_init(void);
+void property_load_boot_defaults(void);
+void load_persist_props(void);
+void load_system_props(void);
+void start_property_service(void);
+uint32_t property_set(const std::string& name, const std::string& value);
+bool is_legal_property_name(const std::string& name);
 
 
 #endif  /* _INIT_PROPERTY_H */
diff --git a/init/property_service_test.cpp b/init/property_service_test.cpp
new file mode 100644
index 0000000..4d784aa
--- /dev/null
+++ b/init/property_service_test.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+
+#include <gtest/gtest.h>
+
+TEST(property_service, very_long_name_35166374) {
+  // Connect to the property service directly...
+  int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
+  ASSERT_NE(fd, -1);
+
+  static const char* property_service_socket = "/dev/socket/" PROP_SERVICE_NAME;
+  sockaddr_un addr = {};
+  addr.sun_family = AF_LOCAL;
+  strlcpy(addr.sun_path, property_service_socket, sizeof(addr.sun_path));
+
+  socklen_t addr_len = strlen(property_service_socket) + offsetof(sockaddr_un, sun_path) + 1;
+  ASSERT_NE(connect(fd, reinterpret_cast<sockaddr*>(&addr), addr_len), -1);
+
+  // ...so we can send it a malformed request.
+  uint32_t msg = PROP_MSG_SETPROP2;
+  uint32_t size = 0xffffffff;
+  uint32_t data = 0xdeadbeef;
+
+  ASSERT_EQ(static_cast<ssize_t>(sizeof(msg)), send(fd, &msg, sizeof(msg), 0));
+  ASSERT_EQ(static_cast<ssize_t>(sizeof(size)), send(fd, &size, sizeof(size), 0));
+  ASSERT_EQ(static_cast<ssize_t>(sizeof(data)), send(fd, &data, sizeof(data), 0));
+  ASSERT_EQ(0, close(fd));
+}
diff --git a/init/readme.txt b/init/readme.txt
deleted file mode 100644
index dad7e06..0000000
--- a/init/readme.txt
+++ /dev/null
@@ -1,519 +0,0 @@
-Android Init Language
----------------------
-
-The Android Init Language consists of five broad classes of statements,
-which are Actions, Commands, Services, Options, and Imports.
-
-All of these are line-oriented, consisting of tokens separated by
-whitespace.  The c-style backslash escapes may be used to insert
-whitespace into a token.  Double quotes may also be used to prevent
-whitespace from breaking text into multiple tokens.  The backslash,
-when it is the last character on a line, may be used for line-folding.
-
-Lines which start with a # (leading whitespace allowed) are comments.
-
-Actions and Services implicitly declare a new section.  All commands
-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
-with the same name as an existing one, it is ignored and an error
-message is logged.
-
-
-Init .rc Files
---------------
-The init language is used in plaintext files that take the .rc file
-extension.  These are typically multiple of these in multiple
-locations on the system, described below.
-
-/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.
-
-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.
-This is primarily for supporting factory mode and other non-standard boot
-modes.  The three default paths should be used for the normal boot process.
-
-The intention of these directories is as follows
-   1) /system/etc/init/ is for core system items such as
-      SurfaceFlinger, MediaService, and logcatd.
-   2) /vendor/etc/init/ is for SoC vendor items such as actions or
-      daemons needed for core SoC functionality.
-   3) /odm/etc/init/ is for device manufacturer items such as
-      actions or daemons needed for motion sensor or other peripheral
-      functionality.
-
-All services whose binaries reside on the system, vendor, or odm
-partitions should have their service entries placed into a
-corresponding init .rc file, located in the /etc/init/
-directory of the partition where they reside.  There is a build
-system macro, LOCAL_INIT_RC, that handles this for developers.  Each
-init .rc file should additionally contain any actions associated with
-its service.
-
-An example is the logcatd.rc and Android.mk files located in the
-system/core/logcat directory.  The LOCAL_INIT_RC macro in the
-Android.mk file places logcatd.rc in /system/etc/init/ during the
-build process.  Init loads logcatd.rc during the mount_all command and
-allows the service to be run and the action to be queued when
-appropriate.
-
-This break up of init .rc files according to their daemon is preferred
-to the previously used monolithic init .rc files.  This approach
-ensures that the only service entries that init reads and the only
-actions that init performs correspond to services whose binaries are in
-fact present on the file system, which was not the case with the
-monolithic init .rc files.  This additionally will aid in merge
-conflict resolution when multiple services are added to the system, as
-each one will go into a separate file.
-
-There are two options "early" and "late" in mount_all command
-which can be set after optional paths. With "--early" set, the
-init executable will skip mounting entries with "latemount" flag
-and triggering fs encryption state event. With "--late" set,
-init executable will only mount entries with "latemount" flag but skip
-importing rc files. By default, no option is set, and mount_all will
-mount_all will process all entries in the given fstab.
-
-Actions
--------
-Actions are named sequences of commands.  Actions have a trigger which
-is used to determine when the action should occur.  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).
-
-Each action in the queue is dequeued in sequence and each command in
-that action is executed in sequence.  Init handles other activities
-(device creation/destruction, property setting, process restarting)
-"between" the execution of the commands in activities.
-
-Actions take the form of:
-
-on <trigger> [&& <trigger>]*
-   <command>
-   <command>
-   <command>
-
-
-Services
---------
-Services are programs which init launches and (optionally) restarts
-when they exit.  Services take the form of:
-
-service <name> <pathname> [ <argument> ]*
-   <option>
-   <option>
-   ...
-
-
-Options
--------
-Options are modifiers to services.  They affect how and when init
-runs the service.
-
-critical
-  This is a device-critical service. If it exits more than four times in
-  four minutes, the device will reboot into recovery mode.
-
-disabled
-  This service will not automatically start with its class.
-  It must be explicitly started by name.
-
-setenv <name> <value>
-  Set the environment variable <name> to <value> in the launched process.
-
-socket <name> <type> <perm> [ <user> [ <group> [ <seclabel> ] ] ]
-  Create a unix domain socket named /dev/socket/<name> and pass
-  its fd to the launched process.  <type> must be "dgram", "stream" or "seqpacket".
-  User and group default to 0.
-  'seclabel' is the SELinux security context for the socket.
-  It defaults to the service security context, as specified by seclabel or
-  computed based on the service executable file security context.
-
-user <username>
-  Change to username before exec'ing this service.
-  Currently defaults to root.  (??? probably should default to nobody)
-  As of Android M, processes should use this option even if they
-  require linux capabilities.  Previously, to acquire linux
-  capabilities, a process would need to run as root, request the
-  capabilities, then drop to its desired uid.  There is a new
-  mechanism through fs_config that allows device manufacturers to add
-  linux capabilities to specific binaries on a file system that should
-  be used instead. This mechanism is described on
-  http://source.android.com/devices/tech/config/filesystem.html.  When
-  using this new mechanism, processes can use the user option to
-  select their desired uid without ever running as root.
-
-group <groupname> [ <groupname> ]*
-  Change to groupname before exec'ing this service.  Additional
-  groupnames beyond the (required) first one are used to set the
-  supplemental groups of the process (via setgroups()).
-  Currently defaults to root.  (??? probably should default to nobody)
-
-seclabel <seclabel>
-  Change to 'seclabel' before exec'ing this service.
-  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
-  Services on the system partition can instead use policy-defined transitions
-  based on their file security context.
-  If not specified and no transition is defined in policy, defaults to the init context.
-
-oneshot
-  Do not restart the service when it exits.
-
-class <name>
-  Specify a class name 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.
-
-onrestart
-  Execute a Command (see below) when service restarts.
-
-writepid <file...>
-  Write the child's pid to the given files when it forks. Meant for
-  cgroup/cpuset usage.
-
-
-Triggers
---------
-Triggers are strings which can be used to match certain kinds of
-events and used to cause an action to occur.
-
-Triggers are subdivided into event triggers and property triggers.
-
-Event triggers are strings triggered by the 'trigger' command or by
-the QueueEventTrigger() function within the init executable.  These
-take the form of a simple string such as 'boot' or 'late-init'.
-
-Property triggers are strings triggered when a named property changes
-value to a given new value or when a named property changes value to
-any new value.  These take the form of 'property:<name>=<value>' and
-'property:<name>=*' respectively.  Property triggers are additionally
-evaluated and triggered accordingly during the initial boot phase of
-init.
-
-An Action can have multiple property triggers but may only have one
-event trigger.
-
-For example:
-'on boot && property:a=b' defines an action that is only executed when
-the 'boot' event trigger happens and the property a equals b.
-
-'on property:a=b && property:c=d' defines an action that is executed
-at three times,
-   1) During initial boot if property a=b and property c=d
-   2) Any time that property a transitions to value b, while property
-      c already equals d.
-   3) Any time that property c transitions to value d, while property
-      a already equals b.
-
-
-Commands
---------
-
-bootchart_init
-   Start bootcharting if configured (see below).
-   This is included in the default init.rc.
-
-chmod <octal-mode> <path>
-   Change file access permissions.
-
-chown <owner> <group> <path>
-   Change file owner and group.
-
-class_start <serviceclass>
-   Start all services of the specified class if they are
-   not already running.
-
-class_stop <serviceclass>
-   Stop and disable all services of the specified class if they are
-   currently running.
-
-class_reset <serviceclass>
-   Stop all services of the specified class if they are
-   currently running, without disabling them. They can be restarted
-   later using class_start.
-
-copy <src> <dst>
-   Copies a file. Similar to write, but useful for binary/large
-   amounts of data.
-
-domainname <name>
-   Set the domain name.
-
-enable <servicename>
-   Turns a disabled service into an enabled one as if the service did not
-   specify disabled.
-   If the service is supposed to be running, it will be started now.
-   Typically used when the bootloader sets a variable that indicates a specific
-   service should be started when needed. E.g.
-     on property:ro.boot.myfancyhardware=1
-        enable my_fancy_service_for_my_fancy_hardware
-
-exec [ <seclabel> [ <user> [ <group> ]* ] ] -- <command> [ <argument> ]*
-   Fork and execute command with the given arguments. The command starts
-   after "--" so that an optional security context, user, and supplementary
-   groups can be provided. No other commands will be run until this one
-   finishes. <seclabel> can be a - to denote default.
-
-export <name> <value>
-   Set the environment variable <name> equal to <value> in the
-   global environment (which will be inherited by all processes
-   started after this command is executed)
-
-hostname <name>
-   Set the host name.
-
-ifup <interface>
-   Bring the network interface <interface> online.
-
-insmod <path>
-   Install the module at <path>
-
-load_all_props
-   Loads properties from /system, /vendor, et cetera.
-   This is included in the default init.rc.
-
-load_persist_props
-   Loads persistent properties when /data has been decrypted.
-   This is included in the default init.rc.
-
-loglevel <level>
-   Sets the kernel log level to level. Properties are expanded within <level>.
-
-mkdir <path> [mode] [owner] [group]
-   Create a directory at <path>, optionally with the given mode, owner, and
-   group. If not provided, the directory is created with permissions 755 and
-   owned by the root user and root group. If provided, the mode, owner and group
-   will be updated if the directory exists already.
-
-mount_all <fstab> [ <path> ]* [--<option>]
-   Calls fs_mgr_mount_all on the given fs_mgr-format fstab and imports .rc files
-   at the specified paths (e.g., on the partitions just mounted) with optional
-   options "early" and "late".
-   Refer to the section of "Init .rc Files" for detail.
-
-mount <type> <device> <dir> [ <flag> ]* [<options>]
-   Attempt to mount the named device at the directory <dir>
-   <device> may be of the form mtd@name to specify a mtd block
-   device by name.
-   <flag>s include "ro", "rw", "remount", "noatime", ...
-   <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.
-
-restorecon <path> [ <path> ]*
-   Restore the file named by <path> to the security context specified
-   in the file_contexts configuration.
-   Not required for directories created by the init.rc as these are
-   automatically labeled correctly by init.
-
-restorecon_recursive <path> [ <path> ]*
-   Recursively restore the directory tree named by <path> to the
-   security contexts specified in the file_contexts configuration.
-
-rm <path>
-   Calls unlink(2) on the given path. You might want to
-   use "exec -- rm ..." instead (provided the system partition is
-   already mounted).
-
-rmdir <path>
-   Calls rmdir(2) on the given path.
-
-setprop <name> <value>
-   Set system property <name> to <value>. Properties are expanded
-   within <value>.
-
-setrlimit <resource> <cur> <max>
-   Set the rlimit for a resource.
-
-start <service>
-   Start a service running if it is not already running.
-
-stop <service>
-   Stop a service from running if it is currently running.
-
-swapon_all <fstab>
-   Calls fs_mgr_swapon_all on the given fstab file.
-
-symlink <target> <path>
-   Create a symbolic link at <path> with the value <target>
-
-sysclktz <mins_west_of_gmt>
-   Set the system clock base (0 if system clock ticks in GMT)
-
-trigger <event>
-   Trigger an event.  Used to queue an action from another
-   action.
-
-umount <path>
-   Unmount the filesystem mounted at that path.
-
-verity_load_state
-   Internal implementation detail used to load dm-verity state.
-
-verity_update_state <mount_point>
-   Internal implementation detail used to update dm-verity state and
-   set the partition.<mount_point>.verified properties used by adb remount
-   because fs_mgr can't set them directly itself.
-
-wait <path> [ <timeout> ]
-   Poll for the existence of the given file and return when found,
-   or the timeout has been reached. If timeout is not specified it
-   currently defaults to five seconds.
-
-write <path> <content>
-   Open the file at <path> and write a string to it with write(2).
-   If the file does not exist, it will be created. If it does exist,
-   it will be truncated. Properties are expanded within <content>.
-
-
-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,
-   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
-
-
-Properties
-----------
-Init provides information about the services that it is responsible
-for via the below properties.
-
-init.svc.<name>
-   State of a named service ("stopped", "stopping", "running", "restarting")
-
-
-Bootcharting
-------------
-This version of init contains code to perform "bootcharting": generating log
-files that can be later processed by the tools provided by www.bootchart.org.
-
-On the emulator, use the -bootchart <timeout> option to boot with bootcharting
-activated for <timeout> seconds.
-
-On a device, create /data/bootchart/start with a command like the following:
-
-  adb shell 'echo $TIMEOUT > /data/bootchart/start'
-
-Where the value of $TIMEOUT corresponds to the desired bootcharted period in
-seconds. Bootcharting will stop after that many seconds have elapsed.
-You can also stop the bootcharting at any moment by doing the following:
-
-  adb shell 'echo 1 > /data/bootchart/stop'
-
-Note that /data/bootchart/stop is deleted automatically by init at the end of
-the bootcharting. This is not the case with /data/bootchart/start, so don't
-forget to delete it when you're done collecting data.
-
-The log files are written to /data/bootchart/. A script is provided to
-retrieve them and create a bootchart.tgz file that can be used with the
-bootchart command-line utility:
-
-  sudo apt-get install pybootchartgui
-  # grab-bootchart.sh uses $ANDROID_SERIAL.
-  $ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh
-
-One thing to watch for is that the bootchart will show init as if it started
-running at 0s. You'll have to look at dmesg to work out when the kernel
-actually started init.
-
-
-Comparing two bootcharts
-------------------------
-A handy script named compare-bootcharts.py can be used to compare the
-start/end time of selected processes. The aforementioned grab-bootchart.sh
-will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
-If two such barballs are preserved on the host machine under different
-directories, the script can list the timestamps differences. For example:
-
-Usage: system/core/init/compare-bootcharts.py base_bootchart_dir
-       exp_bootchart_dir
-
-process: baseline experiment (delta)
- - Unit is ms (a jiffy is 10 ms on the system)
-------------------------------------
-/init: 50 40 (-10)
-/system/bin/surfaceflinger: 4320 4470 (+150)
-/system/bin/bootanimation: 6980 6990 (+10)
-zygote64: 10410 10640 (+230)
-zygote: 10410 10640 (+230)
-system_server: 15350 15150 (-200)
-bootanimation ends at: 33790 31230 (-2560)
-
-
-Systrace
---------
-Systrace [1] can be used for obtaining performance analysis reports during boot
-time on userdebug or eng builds.
-Here is an example of trace events of "wm" and "am" categories:
-
-  $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py wm am --boot
-
-This command will cause the device to reboot. After the device is rebooted and
-the boot sequence has finished, the trace report is obtained from the device
-and written as trace.html on the host by hitting Ctrl+C.
-
-LIMITATION
-Recording trace events is started after persistent properties are loaded, so
-the trace events that are emitted before that are not recorded. Several
-services such as vold, surfaceflinger, and servicemanager are affected by this
-limitation since they are started before persistent properties are loaded.
-Zygote initialization and the processes that are forked from the zygote are not
-affected.
-
-[1] http://developer.android.com/tools/help/systrace.html
-
-
-Debugging init
---------------
-By default, programs executed by init will drop stdout and stderr into
-/dev/null. To help with debugging, you can execute your program via the
-Android program logwrapper. This will redirect stdout/stderr into the
-Android logging system (accessed via logcat).
-
-For example
-service akmd /system/bin/logwrapper /sbin/akmd
-
-For quicker turnaround when working on init itself, use:
-
-  mm -j
-  m ramdisk-nodeps
-  m bootimage-nodeps
-  adb reboot bootloader
-  fastboot boot $ANDROID_PRODUCT_OUT/boot.img
-
-Alternatively, use the emulator:
-
-  emulator -partition-size 1024 -verbose -show-kernel -no-window
-
-You might want to call klog_set_level(6) after the klog_init() call
-so you see the kernel logging in dmesg (or the emulator output).
diff --git a/init/reboot.cpp b/init/reboot.cpp
new file mode 100644
index 0000000..aac1b5c
--- /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 <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 <string>
+#include <thread>
+#include <vector>
+
+#include <android-base/file.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 "log.h"
+#include "property_service.h"
+#include "reboot.h"
+#include "service.h"
+#include "util.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", "ueventd"};
+    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..cd6be39
--- /dev/null
+++ b/init/reboot.h
@@ -0,0 +1,33 @@
+/*
+ * 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
+
+/* 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 3149f8e..9ba0272 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -17,7 +17,14 @@
 #include "service.h"
 
 #include <fcntl.h>
+#include <inttypes.h>
+#include <linux/securebits.h>
+#include <sched.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+#include <sys/resource.h>
 #include <sys/stat.h>
+#include <sys/time.h>
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <termios.h>
@@ -26,9 +33,13 @@
 #include <selinux/selinux.h>
 
 #include <android-base/file.h>
+#include <android-base/parseint.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
-#include <cutils/android_reboot.h>
-#include <cutils/sockets.h>
+#include <android-base/strings.h>
+#include <system/thread_defs.h>
+
+#include <processgroup/processgroup.h>
 
 #include "action.h"
 #include "init.h"
@@ -37,18 +48,98 @@
 #include "property_service.h"
 #include "util.h"
 
+using android::base::ParseInt;
 using android::base::StringPrintf;
 using android::base::WriteStringToFile;
 
-#define CRITICAL_CRASH_THRESHOLD    4       // if we crash >4 times ...
-#define CRITICAL_CRASH_WINDOW       (4*60)  // ... in 4 minutes, goto recovery
+static std::string ComputeContextFromExecutable(std::string& service_name,
+                                                const std::string& service_path) {
+    std::string computed_context;
 
-SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
+    char* raw_con = nullptr;
+    char* raw_filecon = nullptr;
+
+    if (getcon(&raw_con) == -1) {
+        LOG(ERROR) << "could not get context while starting '" << service_name << "'";
+        return "";
+    }
+    std::unique_ptr<char> mycon(raw_con);
+
+    if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
+        LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
+        return "";
+    }
+    std::unique_ptr<char> filecon(raw_filecon);
+
+    char* new_con = nullptr;
+    int rc = security_compute_create(mycon.get(), filecon.get(),
+                                     string_to_security_class("process"), &new_con);
+    if (rc == 0) {
+        computed_context = new_con;
+        free(new_con);
+    }
+    if (rc == 0 && computed_context == mycon.get()) {
+        LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
+        return "";
+    }
+    if (rc < 0) {
+        LOG(ERROR) << "could not get context while starting '" << service_name << "'";
+        return "";
+    }
+    return computed_context;
 }
 
-SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
-                       gid_t gid, int perm, const std::string& socketcon)
-    : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
+static void SetUpPidNamespace(const std::string& service_name) {
+    constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
+
+    // It's OK to LOG(FATAL) in this function since it's running in the first
+    // child process.
+    if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
+        PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
+    }
+
+    if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
+        PLOG(FATAL) << "couldn't set name for " << service_name;
+    }
+
+    pid_t child_pid = fork();
+    if (child_pid == -1) {
+        PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
+    }
+
+    if (child_pid > 0) {
+        // So that we exit with the right status.
+        static int init_exitstatus = 0;
+        signal(SIGTERM, [](int) { _exit(init_exitstatus); });
+
+        pid_t waited_pid;
+        int status;
+        while ((waited_pid = wait(&status)) > 0) {
+             // This loop will end when there are no processes left inside the
+             // PID namespace or when the init process inside the PID namespace
+             // gets a signal.
+            if (waited_pid == child_pid) {
+                init_exitstatus = status;
+            }
+        }
+        if (!WIFEXITED(init_exitstatus)) {
+            _exit(EXIT_FAILURE);
+        }
+        _exit(WEXITSTATUS(init_exitstatus));
+    }
+}
+
+static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
+    std::vector<std::string> expanded_args;
+    expanded_args.resize(args.size());
+    strs->push_back(const_cast<char*>(args[0].c_str()));
+    for (std::size_t i = 1; i < args.size(); ++i) {
+        if (!expand_props(args[i], &expanded_args[i])) {
+            LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
+        }
+        strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
+    }
+    strs->push_back(nullptr);
 }
 
 ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
@@ -59,56 +150,135 @@
     : 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), time_started_(0),
-      time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
-      ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), 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_(""),
+      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 std::string& seclabel,  const std::vector<std::string>& args)
-    : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
-      time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
-      seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
+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),
+      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),
+      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;
     }
 
     std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
-    if (prop_name.length() >= PROP_NAME_MAX) {
-        // If the property name would be too long, we can't set it.
-        ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
-              name_.c_str(), new_state.c_str());
-        return;
-    }
-
     property_set(prop_name.c_str(), new_state.c_str());
+
+    if (new_state == "running") {
+        uint64_t start_ns = time_started_.time_since_epoch().count();
+        property_set(StringPrintf("ro.boottime.%s", name_.c_str()).c_str(),
+                     StringPrintf("%" PRIu64, start_ns).c_str());
+    }
 }
 
-bool Service::Reap() {
+void Service::KillProcessGroup(int signal) {
+    LOG(INFO) << "Sending signal " << signal
+              << " to service '" << name_
+              << "' (pid " << pid_ << ") process group...";
+    int r;
+    if (signal == SIGTERM) {
+        r = killProcessGroupOnce(uid_, pid_, signal);
+    } else {
+        r = killProcessGroup(uid_, pid_, signal);
+    }
+    if (r == -1) {
+        PLOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
+    }
+    if (kill(-pid_, signal) == -1) {
+        PLOG(ERROR) << "kill(" << pid_ << ", " << signal << ") failed";
+    }
+}
+
+void Service::SetProcessAttributes() {
+    // Keep capabilites on uid change.
+    if (capabilities_.any() && uid_) {
+        if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED) != 0) {
+            PLOG(FATAL) << "prtcl(PR_SET_KEEPCAPS) failed for " << name_;
+        }
+    }
+
+    // TODO: work out why this fails for `console` then upgrade to FATAL.
+    if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
+
+    if (gid_) {
+        if (setgid(gid_) != 0) {
+            PLOG(FATAL) << "setgid failed for " << name_;
+        }
+    }
+    if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
+        PLOG(FATAL) << "setgroups failed for " << name_;
+    }
+    if (uid_) {
+        if (setuid(uid_) != 0) {
+            PLOG(FATAL) << "setuid failed for " << name_;
+        }
+    }
+    if (!seclabel_.empty()) {
+        if (setexeccon(seclabel_.c_str()) < 0) {
+            PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
+        }
+    }
+    if (priority_ != 0) {
+        if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
+            PLOG(FATAL) << "setpriority failed for " << name_;
+        }
+    }
+    if (capabilities_.any()) {
+        if (!SetCapsForExec(capabilities_)) {
+            LOG(FATAL) << "cannot set capabilities for " << name_;
+        }
+    }
+}
+
+void Service::Reap() {
     if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
-        NOTICE("Service '%s' (pid %d) killing any children in process group\n",
-               name_.c_str(), pid_);
-        kill(-pid_, SIGKILL);
+        KillProcessGroup(SIGKILL);
     }
 
-    // Remove any sockets we may have created.
-    for (const auto& si : sockets_) {
-        std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
-        unlink(tmp.c_str());
-    }
+    // Remove any descriptor resources we may have created.
+    std::for_each(descriptors_.begin(), descriptors_.end(),
+                  std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
 
-    if (flags_ & SVC_EXEC) {
-        INFO("SVC_EXEC pid %d finished...\n", pid_);
-        return true;
+    if (flags_ & SVC_TEMPORARY) {
+        return;
     }
 
     pid_ = 0;
@@ -123,22 +293,20 @@
     // Disabled and reset processes do not get restarted automatically.
     if (flags_ & (SVC_DISABLED | SVC_RESET))  {
         NotifyStateChange("stopped");
-        return false;
+        return;
     }
 
-    time_t now = gettime();
+    // If we crash > 4 times in 4 minutes, reboot into recovery.
+    boot_clock::time_point now = boot_clock::now();
     if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
-        if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
-            if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
-                ERROR("critical process '%s' exited %d times in %d minutes; "
-                      "rebooting into recovery mode\n", name_.c_str(),
-                      CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
-                android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-                return false;
+        if (now < time_crashed_ + 4min) {
+            if (++crash_count_ > 4) {
+                LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
+                panic();
             }
         } else {
             time_crashed_ = now;
-            nr_crashed_ = 1;
+            crash_count_ = 1;
         }
     }
 
@@ -149,44 +317,70 @@
     onrestart_.ExecuteAllCommands();
 
     NotifyStateChange("restarting");
-    return false;
+    return;
 }
 
 void Service::DumpState() const {
-    INFO("service %s\n", name_.c_str());
-    INFO("  class '%s'\n", classname_.c_str());
-    INFO("  exec");
-    for (const auto& s : args_) {
-        INFO(" '%s'", s.c_str());
-    }
-    INFO("\n");
-    for (const auto& si : sockets_) {
-        INFO("  socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
-    }
+    LOG(INFO) << "service " << name_;
+    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; });
 }
 
-bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
-    classname_ = args[1];
+bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
+    capabilities_ = 0;
+
+    if (!CapAmbientSupported()) {
+        *err = "capabilities requested but the kernel does not support ambient capabilities";
+        return false;
+    }
+
+    unsigned int last_valid_cap = GetLastValidCap();
+    if (last_valid_cap >= capabilities_.size()) {
+        LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
+    }
+
+    for (size_t i = 1; i < args.size(); i++) {
+        const std::string& arg = args[i];
+        int res = LookupCap(arg);
+        if (res < 0) {
+            *err = StringPrintf("invalid capability '%s'", arg.c_str());
+            return false;
+        }
+        unsigned int cap = static_cast<unsigned int>(res);  // |res| is >= 0.
+        if (cap > last_valid_cap) {
+            *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
+            return false;
+        }
+        capabilities_[cap] = true;
+    }
     return true;
 }
 
-bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
+    classnames_ = std::set<std::string>(args.begin() + 1, args.end());
+    return true;
+}
+
+bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
     flags_ |= SVC_CONSOLE;
+    console_ = args.size() > 1 ? "/dev/" + args[1] : "";
     return true;
 }
 
-bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
     flags_ |= SVC_CRITICAL;
     return true;
 }
 
-bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
     flags_ |= SVC_DISABLED;
     flags_ |= SVC_RC_DISABLED;
     return true;
 }
 
-bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
     gid_ = decode_uid(args[1].c_str());
     for (std::size_t n = 2; n < args.size(); n++) {
         supp_gids_.emplace_back(decode_uid(args[n].c_str()));
@@ -194,10 +388,20 @@
     return true;
 }
 
-bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
-    ioprio_pri_ = std::stoul(args[2], 0, 8);
+bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
+    priority_ = 0;
+    if (!ParseInt(args[1], &priority_,
+                  static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
+                  static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
+        *err = StringPrintf("process priority value must be range %d - %d",
+                ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
+        return false;
+    }
+    return true;
+}
 
-    if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
+bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
+    if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
         *err = "priority value must be range 0 - 7";
         return false;
     }
@@ -216,110 +420,187 @@
     return true;
 }
 
-bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
     for (std::size_t i = 1; i < args.size(); i++) {
-        keycodes_.emplace_back(std::stoi(args[i]));
+        int code;
+        if (ParseInt(args[i], &code)) {
+            keycodes_.emplace_back(code);
+        } else {
+            LOG(WARNING) << "ignoring invalid keycode: " << args[i];
+        }
     }
     return true;
 }
 
-bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
     flags_ |= SVC_ONESHOT;
     return true;
 }
 
-bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
+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);
     return true;
 }
 
-bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
+    for (size_t i = 1; i < args.size(); i++) {
+        if (args[i] == "pid") {
+            namespace_flags_ |= CLONE_NEWPID;
+            // PID namespaces require mount namespaces.
+            namespace_flags_ |= CLONE_NEWNS;
+        } else if (args[i] == "mnt") {
+            namespace_flags_ |= CLONE_NEWNS;
+        } else {
+            *err = "namespace must be 'pid' or 'mnt'";
+            return false;
+        }
+    }
+    return true;
+}
+
+bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
+    if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
+        *err = "oom_score_adjust value must be in range -1000 - +1000";
+        return false;
+    }
+    return true;
+}
+
+bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
     seclabel_ = args[1];
     return true;
 }
 
-bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
     envvars_.emplace_back(args[1], args[2]);
     return true;
 }
 
-/* name type perm [ uid gid context ] */
-bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
+template <typename T>
+bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
+    int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
+    uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
+    gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
+    std::string context = args.size() > 6 ? args[6] : "";
+
+    auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
+
+    auto old =
+        std::find_if(descriptors_.begin(), descriptors_.end(),
+                     [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
+
+    if (old != descriptors_.end()) {
+        *err = "duplicate descriptor " + args[1] + " " + args[2];
+        return false;
+    }
+
+    descriptors_.emplace_back(std::move(descriptor));
+    return true;
+}
+
+// name type perm [ uid gid context ]
+bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
     if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
         *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
         return false;
     }
-
-    int perm = std::stoul(args[3], 0, 8);
-    uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
-    gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
-    std::string socketcon = args.size() > 6 ? args[6] : "";
-
-    sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
-    return true;
+    return AddDescriptor<SocketInfo>(args, err);
 }
 
-bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
+// name type perm [ uid gid context ]
+bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
+    if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
+        *err = "file type must be 'r', 'w' or 'rw'";
+        return false;
+    }
+    if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
+        *err = "file name must not be relative";
+        return false;
+    }
+    return AddDescriptor<FileInfo>(args, err);
+}
+
+bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
     uid_ = decode_uid(args[1].c_str());
     return true;
 }
 
-bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
+bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
     writepid_files_.assign(args.begin() + 1, args.end());
     return true;
 }
 
-class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
+class Service::OptionParserMap : public KeywordMap<OptionParser> {
 public:
-    OptionHandlerMap() {
+    OptionParserMap() {
     }
 private:
     Map& map() const override;
 };
 
-Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
+Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
-    static const Map option_handlers = {
-        {"class",       {1,     1,    &Service::HandleClass}},
-        {"console",     {0,     0,    &Service::HandleConsole}},
-        {"critical",    {0,     0,    &Service::HandleCritical}},
-        {"disabled",    {0,     0,    &Service::HandleDisabled}},
-        {"group",       {1,     NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
-        {"ioprio",      {2,     2,    &Service::HandleIoprio}},
-        {"keycodes",    {1,     kMax, &Service::HandleKeycodes}},
-        {"oneshot",     {0,     0,    &Service::HandleOneshot}},
-        {"onrestart",   {1,     kMax, &Service::HandleOnrestart}},
-        {"seclabel",    {1,     1,    &Service::HandleSeclabel}},
-        {"setenv",      {2,     2,    &Service::HandleSetenv}},
-        {"socket",      {3,     6,    &Service::HandleSocket}},
-        {"user",        {1,     1,    &Service::HandleUser}},
-        {"writepid",    {1,     kMax, &Service::HandleWritepid}},
+    // clang-format off
+    static const Map option_parsers = {
+        {"capabilities",
+                        {1,     kMax, &Service::ParseCapabilities}},
+        {"class",       {1,     kMax, &Service::ParseClass}},
+        {"console",     {0,     1,    &Service::ParseConsole}},
+        {"critical",    {0,     0,    &Service::ParseCritical}},
+        {"disabled",    {0,     0,    &Service::ParseDisabled}},
+        {"group",       {1,     NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
+        {"ioprio",      {2,     2,    &Service::ParseIoprio}},
+        {"priority",    {1,     1,    &Service::ParsePriority}},
+        {"keycodes",    {1,     kMax, &Service::ParseKeycodes}},
+        {"oneshot",     {0,     0,    &Service::ParseOneshot}},
+        {"onrestart",   {1,     kMax, &Service::ParseOnrestart}},
+        {"oom_score_adjust",
+                        {1,     1,    &Service::ParseOomScoreAdjust}},
+        {"namespace",   {1,     2,    &Service::ParseNamespace}},
+        {"seclabel",    {1,     1,    &Service::ParseSeclabel}},
+        {"setenv",      {2,     2,    &Service::ParseSetenv}},
+        {"socket",      {3,     6,    &Service::ParseSocket}},
+        {"file",        {2,     2,    &Service::ParseFile}},
+        {"user",        {1,     1,    &Service::ParseUser}},
+        {"writepid",    {1,     kMax, &Service::ParseWritepid}},
     };
-    return option_handlers;
+    // clang-format on
+    return option_parsers;
 }
 
-bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
+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 OptionHandlerMap handler_map;
-    auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
+    static const OptionParserMap parser_map;
+    auto parser = parser_map.FindFunction(args[0], args.size() - 1, err);
 
-    if (!handler) {
+    if (!parser) {
         return false;
     }
 
-    return (this->*handler)(args, err);
+    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.
     flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
-    time_started_ = 0;
 
     // Running processes require no additional work --- if they're in the
     // process of exiting, we've ensured that they will immediately restart
@@ -329,16 +610,25 @@
     }
 
     bool needs_console = (flags_ & SVC_CONSOLE);
-    if (needs_console && !have_console) {
-        ERROR("service '%s' requires console\n", name_.c_str());
-        flags_ |= SVC_DISABLED;
-        return false;
+    if (needs_console) {
+        if (console_.empty()) {
+            console_ = default_console;
+        }
+
+        // Make sure that open call succeeds to ensure a console driver is
+        // properly registered for the device node
+        int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
+        if (console_fd < 0) {
+            PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
+            flags_ |= SVC_DISABLED;
+            return false;
+        }
+        close(console_fd);
     }
 
     struct stat sb;
     if (stat(args_[0].c_str(), &sb) == -1) {
-        ERROR("cannot find '%s' (%s), disabling '%s'\n",
-              args_[0].c_str(), strerror(errno), name_.c_str());
+        PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
         flags_ |= SVC_DISABLED;
         return false;
     }
@@ -347,80 +637,71 @@
     if (!seclabel_.empty()) {
         scon = seclabel_;
     } else {
-        char* mycon = nullptr;
-        char* fcon = nullptr;
-
-        INFO("computing context for service '%s'\n", args_[0].c_str());
-        int rc = getcon(&mycon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", name_.c_str());
-            return false;
-        }
-
-        rc = getfilecon(args_[0].c_str(), &fcon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", name_.c_str());
-            free(mycon);
-            return false;
-        }
-
-        char* ret_scon = nullptr;
-        rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
-                                     &ret_scon);
-        if (rc == 0) {
-            scon = ret_scon;
-            free(ret_scon);
-        }
-        if (rc == 0 && scon == mycon) {
-            ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
-            free(mycon);
-            free(fcon);
-            return false;
-        }
-        free(mycon);
-        free(fcon);
-        if (rc < 0) {
-            ERROR("could not get context while starting '%s'\n", name_.c_str());
+        LOG(INFO) << "computing context for service '" << name_ << "'";
+        scon = ComputeContextFromExecutable(name_, args_[0]);
+        if (scon == "") {
             return false;
         }
     }
 
-    NOTICE("Starting service '%s'...\n", name_.c_str());
+    LOG(INFO) << "starting service '" << name_ << "'...";
 
-    pid_t pid = fork();
+    pid_t pid = -1;
+    if (namespace_flags_) {
+        pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
+    } else {
+        pid = fork();
+    }
+
     if (pid == 0) {
         umask(077);
 
+        if (namespace_flags_ & CLONE_NEWPID) {
+            // This will fork again to run an init process inside the PID
+            // namespace.
+            SetUpPidNamespace(name_);
+        }
+
         for (const auto& ei : envvars_) {
             add_environment(ei.name.c_str(), ei.value.c_str());
         }
 
-        for (const auto& si : sockets_) {
-            int socket_type = ((si.type == "stream" ? SOCK_STREAM :
-                                (si.type == "dgram" ? SOCK_DGRAM :
-                                 SOCK_SEQPACKET)));
-            const char* socketcon =
-                !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
+        std::for_each(descriptors_.begin(), descriptors_.end(),
+                      std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
 
-            int s = create_socket(si.name.c_str(), socket_type, si.perm,
-                                  si.uid, si.gid, socketcon);
-            if (s >= 0) {
-                PublishSocket(si.name, s);
+        // 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)) {
-                ERROR("couldn't write %s to %s: %s\n",
-                      pid_str.c_str(), file.c_str(), strerror(errno));
+                PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
             }
         }
 
         if (ioprio_class_ != IoSchedClass_NONE) {
             if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
-                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
-                      getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
+                PLOG(ERROR) << "failed to set pid " << getpid()
+                            << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
             }
         }
 
@@ -431,69 +712,47 @@
             ZapStdio();
         }
 
-        setpgid(0, getpid());
+        // As requested, set our gid, supplemental gids, uid, context, and
+        // priority. Aborts on failure.
+        SetProcessAttributes();
 
-        // As requested, set our gid, supplemental gids, and uid.
-        if (gid_) {
-            if (setgid(gid_) != 0) {
-                ERROR("setgid failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (!supp_gids_.empty()) {
-            if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
-                ERROR("setgroups failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (uid_) {
-            if (setuid(uid_) != 0) {
-                ERROR("setuid failed: %s\n", strerror(errno));
-                _exit(127);
-            }
-        }
-        if (!seclabel_.empty()) {
-            if (setexeccon(seclabel_.c_str()) < 0) {
-                ERROR("cannot setexeccon('%s'): %s\n",
-                      seclabel_.c_str(), strerror(errno));
-                _exit(127);
-            }
-        }
-
-        std::vector<std::string> expanded_args;
         std::vector<char*> strs;
-        expanded_args.resize(args_.size());
-        strs.push_back(const_cast<char*>(args_[0].c_str()));
-        for (std::size_t i = 1; i < args_.size(); ++i) {
-            if (!expand_props(args_[i], &expanded_args[i])) {
-                ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
-                _exit(127);
-            }
-            strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
-        }
-        strs.push_back(nullptr);
-
+        ExpandArgs(args_, &strs);
         if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
-            ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
+            PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
         }
 
         _exit(127);
     }
 
     if (pid < 0) {
-        ERROR("failed to start '%s'\n", name_.c_str());
+        PLOG(ERROR) << "failed to fork for '" << name_ << "'";
         pid_ = 0;
         return false;
     }
 
-    time_started_ = gettime();
+    if (oom_score_adjust_ != -1000) {
+        std::string oom_str = StringPrintf("%d", oom_score_adjust_);
+        std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
+        if (!WriteStringToFile(oom_str, oom_file)) {
+            PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
+        }
+    }
+
+    time_started_ = boot_clock::now();
     pid_ = pid;
     flags_ |= SVC_RUNNING;
 
+    errno = -createProcessGroup(uid_, pid_);
+    if (errno != 0) {
+        PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
+                    << name_ << "'";
+    }
+
     if ((flags_ & SVC_EXEC) != 0) {
-        INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
-             pid_, uid_, gid_, supp_gids_.size(),
-             !seclabel_.empty() ? seclabel_.c_str() : "default");
+        LOG(INFO) << android::base::StringPrintf(
+            "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
+            supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
     }
 
     NotifyStateChange("running");
@@ -529,9 +788,7 @@
     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
     flags_ |= SVC_DISABLED;
     if (pid_) {
-        NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
-               pid_);
-        kill(-pid_, SIGTERM);
+        KillProcessGroup(SIGTERM);
         NotifyStateChange("stopping");
     }
 }
@@ -546,34 +803,34 @@
     } /* else: Service is restarting anyways. */
 }
 
-void Service::RestartIfNeeded(time_t& process_needs_restart) {
-    time_t next_start_time = time_started_ + 5;
-
-    if (next_start_time <= gettime()) {
+void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
+    boot_clock::time_point now = boot_clock::now();
+    boot_clock::time_point next_start = time_started_ + 5s;
+    if (now > next_start) {
         flags_ &= (~SVC_RESTARTING);
         Start();
         return;
     }
 
-    if ((next_start_time < process_needs_restart) ||
-        (process_needs_restart == 0)) {
-        process_needs_restart = next_start_time;
+    time_t next_start_time_t = time(nullptr) +
+        time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
+    if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
+        *process_needs_restart_at = next_start_time_t;
     }
 }
 
-/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
+// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
 void Service::StopOrReset(int how) {
-    /* The service is still SVC_RUNNING until its process exits, but if it has
-     * already exited it shoudn't attempt a restart yet. */
+    // The service is still SVC_RUNNING until its process exits, but if it has
+    // already exited it shoudn't attempt a restart yet.
     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
 
     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
-        /* Hrm, an illegal flag.  Default to SVC_DISABLED */
+        // An illegal flag: default to SVC_DISABLED.
         how = SVC_DISABLED;
     }
-        /* if the service has not yet started, prevent
-         * it from auto-starting with its class
-         */
+
+    // If the service has not yet started, prevent it from auto-starting with its class.
     if (how == SVC_RESET) {
         flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
     } else {
@@ -581,8 +838,7 @@
     }
 
     if (pid_) {
-        NOTICE("Service '%s' is being killed...\n", name_.c_str());
-        kill(-pid_, SIGKILL);
+        KillProcessGroup(SIGKILL);
         NotifyStateChange("stopping");
     } else {
         NotifyStateChange("stopped");
@@ -599,10 +855,8 @@
 }
 
 void Service::OpenConsole() const {
-    int fd;
-    if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
-        fd = open("/dev/null", O_RDWR);
-    }
+    int fd = open(console_.c_str(), O_RDWR);
+    if (fd == -1) fd = open("/dev/null", O_RDWR);
     ioctl(fd, TIOCSCTTY, 0);
     dup2(fd, 0);
     dup2(fd, 1);
@@ -610,15 +864,6 @@
     close(fd);
 }
 
-void Service::PublishSocket(const std::string& name, int fd) const {
-    std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
-    std::string val = StringPrintf("%d", fd);
-    add_environment(key.c_str(), val.c_str());
-
-    /* make sure we don't close-on-exec */
-    fcntl(fd, F_SETFD, 0);
-}
-
 int ServiceManager::exec_count_ = 0;
 
 ServiceManager::ServiceManager() {
@@ -632,13 +877,41 @@
 void ServiceManager::AddService(std::unique_ptr<Service> service) {
     Service* old_service = FindServiceByName(service->name());
     if (old_service) {
-        ERROR("ignored duplicate definition of service '%s'",
-              service->name().c_str());
+        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
@@ -650,19 +923,21 @@
         }
     }
     if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
-        ERROR("exec called with too many supplementary group ids\n");
+        LOG(ERROR) << "exec called with too many supplementary group ids";
         return nullptr;
     }
 
     if (command_arg >= args.size()) {
-        ERROR("exec called without command\n");
+        LOG(ERROR) << "exec called without command";
         return nullptr;
     }
     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;
+    unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
+    CapSet no_capabilities;
+    unsigned namespace_flags = 0;
 
     std::string seclabel = "";
     if (command_arg > 2 && args[1] != "-") {
@@ -682,15 +957,10 @@
         }
     }
 
-    std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
-                                               supp_gids, seclabel, str_args));
-    if (!svc_p) {
-        ERROR("Couldn't allocate service for exec of '%s'",
-              str_args[0].c_str());
-        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;
 }
@@ -729,7 +999,7 @@
     return nullptr;
 }
 
-void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
+void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
     for (const auto& s : services_) {
         callback(s.get());
     }
@@ -738,7 +1008,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());
         }
     }
@@ -769,7 +1039,6 @@
     for (const auto& s : services_) {
         s->DumpState();
     }
-    INFO("\n");
 }
 
 bool ServiceManager::ReapOneProcess() {
@@ -778,36 +1047,45 @@
     if (pid == 0) {
         return false;
     } else if (pid == -1) {
-        ERROR("waitpid failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "waitpid failed";
         return false;
     }
 
     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)) {
-        NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
+        LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
     } else if (WIFSIGNALED(status)) {
-        NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
+        LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
     } else if (WIFSTOPPED(status)) {
-        NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
+        LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status) << wait_string;
     } else {
-        NOTICE("%s state changed", name.c_str());
+        LOG(INFO) << name << " state changed" << wait_string;
     }
 
     if (!svc) {
         return true;
     }
 
-    if (svc->Reap()) {
-        waiting_for_exec = false;
+    svc->Reap();
+
+    if (svc->flags() & SVC_EXEC) {
+        exec_waiter_.reset();
+    }
+    if (svc->flags() & SVC_TEMPORARY) {
         RemoveService(*svc);
     }
 
@@ -833,14 +1111,14 @@
     }
 
     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_->HandleLine(args, err) : false;
+    return service_ ? service_->ParseLine(args, err) : false;
 }
 
 void ServiceParser::EndSection() {
@@ -850,13 +1128,9 @@
 }
 
 bool ServiceParser::IsValidName(const std::string& name) const {
-    if (name.size() > 16) {
-        return false;
-    }
-    for (const auto& c : name) {
-        if (!isalnum(c) && (c != '_') && (c != '-')) {
-            return false;
-        }
-    }
-    return true;
+    // Property names can be any length, but may only contain certain characters.
+    // Property values can contain any characters, but may only be a certain length.
+    // (The latter restriction is needed because `start` and `stop` work by writing
+    // the service name to the "ctl.start" and "ctl.stop" properties.)
+    return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
 }
diff --git a/init/service.h b/init/service.h
index d9d18ef..f93ac38 100644
--- a/init/service.h
+++ b/init/service.h
@@ -22,43 +22,41 @@
 #include <cutils/iosched_policy.h>
 
 #include <memory>
+#include <set>
 #include <string>
 #include <vector>
 
 #include "action.h"
+#include "capabilities.h"
+#include "descriptors.h"
 #include "init_parser.h"
 #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
 
 class Action;
 class ServiceManager;
 
-struct SocketInfo {
-    SocketInfo();
-    SocketInfo(const std::string& name, const std::string& type, uid_t uid,
-                       gid_t gid, int perm, const std::string& socketcon);
-    std::string name;
-    std::string type;
-    uid_t uid;
-    gid_t gid;
-    int perm;
-    std::string socketcon;
-};
-
 struct ServiceEnvironmentInfo {
     ServiceEnvironmentInfo();
     ServiceEnvironmentInfo(const std::string& name, const std::string& value);
@@ -67,15 +65,17 @@
 };
 
 class Service {
-public:
-    Service(const std::string& name, const std::string& classname,
+  public:
+    Service(const std::string& name, const std::vector<std::string>& args);
+
+    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);
 
-    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 std::string& seclabel,  const std::vector<std::string>& args);
-
-    bool HandleLine(const std::vector<std::string>& args, std::string* err);
+    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();
@@ -83,65 +83,85 @@
     void Stop();
     void Terminate();
     void Restart();
-    void RestartIfNeeded(time_t& process_needs_restart);
-    bool Reap();
+    void RestartIfNeeded(time_t* process_needs_restart_at);
+    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_; }
+    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:
-    using OptionHandler = bool (Service::*) (const std::vector<std::string>& args,
-                                             std::string* err);
-    class OptionHandlerMap;
+  private:
+    using OptionParser = bool (Service::*) (const std::vector<std::string>& args,
+                                            std::string* err);
+    class OptionParserMap;
 
     void NotifyStateChange(const std::string& new_state) const;
     void StopOrReset(int how);
     void ZapStdio() const;
     void OpenConsole() const;
-    void PublishSocket(const std::string& name, int fd) const;
+    void KillProcessGroup(int signal);
+    void SetProcessAttributes();
 
-    bool HandleClass(const std::vector<std::string>& args, std::string* err);
-    bool HandleConsole(const std::vector<std::string>& args, std::string* err);
-    bool HandleCritical(const std::vector<std::string>& args, std::string* err);
-    bool HandleDisabled(const std::vector<std::string>& args, std::string* err);
-    bool HandleGroup(const std::vector<std::string>& args, std::string* err);
-    bool HandleIoprio(const std::vector<std::string>& args, std::string* err);
-    bool HandleKeycodes(const std::vector<std::string>& args, std::string* err);
-    bool HandleOneshot(const std::vector<std::string>& args, std::string* err);
-    bool HandleOnrestart(const std::vector<std::string>& args, std::string* err);
-    bool HandleSeclabel(const std::vector<std::string>& args, std::string* err);
-    bool HandleSetenv(const std::vector<std::string>& args, std::string* err);
-    bool HandleSocket(const std::vector<std::string>& args, std::string* err);
-    bool HandleUser(const std::vector<std::string>& args, std::string* err);
-    bool HandleWritepid(const std::vector<std::string>& args, std::string* err);
+    bool ParseCapabilities(const std::vector<std::string>& args, std::string *err);
+    bool ParseClass(const std::vector<std::string>& args, std::string* err);
+    bool ParseConsole(const std::vector<std::string>& args, std::string* err);
+    bool ParseCritical(const std::vector<std::string>& args, std::string* err);
+    bool ParseDisabled(const std::vector<std::string>& args, std::string* err);
+    bool ParseGroup(const std::vector<std::string>& args, std::string* err);
+    bool ParsePriority(const std::vector<std::string>& args, std::string* err);
+    bool ParseIoprio(const std::vector<std::string>& args, std::string* err);
+    bool ParseKeycodes(const std::vector<std::string>& args, std::string* err);
+    bool ParseOneshot(const std::vector<std::string>& args, std::string* err);
+    bool ParseOnrestart(const std::vector<std::string>& args, std::string* err);
+    bool ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err);
+    bool ParseNamespace(const std::vector<std::string>& args, std::string* err);
+    bool ParseSeclabel(const std::vector<std::string>& args, std::string* err);
+    bool ParseSetenv(const std::vector<std::string>& args, std::string* err);
+    bool ParseSocket(const std::vector<std::string>& args, std::string* err);
+    bool ParseFile(const std::vector<std::string>& args, std::string* err);
+    bool ParseUser(const std::vector<std::string>& args, std::string* err);
+    bool ParseWritepid(const std::vector<std::string>& args, std::string* err);
+
+    template <typename T>
+    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_;
-    time_t time_started_;    // time of last start
-    time_t time_crashed_;    // first crash within inspection window
-    int nr_crashed_;         // number of times crashed within window
+    boot_clock::time_point time_started_; // time of last start
+    boot_clock::time_point time_crashed_; // first crash within inspection window
+    int crash_count_;                     // number of times crashed within window
 
     uid_t uid_;
     gid_t gid_;
     std::vector<gid_t> supp_gids_;
+    CapSet capabilities_;
+    unsigned namespace_flags_;
 
     std::string seclabel_;
 
-    std::vector<SocketInfo> sockets_;
+    std::vector<std::unique_ptr<DescriptorInfo>> descriptors_;
     std::vector<ServiceEnvironmentInfo> envvars_;
 
     Action onrestart_;  // Commands to execute on restart.
@@ -154,6 +174,9 @@
 
     IoSchedClass ioprio_class_;
     int ioprio_pri_;
+    int priority_;
+
+    int oom_score_adjust_;
 
     std::vector<std::string> args_;
 };
@@ -162,12 +185,18 @@
 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;
-    void ForEachService(std::function<void(Service*)> callback) const;
+    void ForEachService(const std::function<void(Service*)>& callback) const;
     void ForEachServiceInClass(const std::string& classname,
                                void (*func)(Service* svc)) const;
     void ForEachServiceWithFlags(unsigned matchflags,
@@ -177,13 +206,13 @@
     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_;
 };
 
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 ea483d4..5e3acac 100644
--- a/init/signal_handler.cpp
+++ b/init/signal_handler.cpp
@@ -24,9 +24,6 @@
 #include <unistd.h>
 
 #include <android-base/stringprintf.h>
-#include <cutils/android_reboot.h>
-#include <cutils/list.h>
-#include <cutils/sockets.h>
 
 #include "action.h"
 #include "init.h"
@@ -47,7 +44,7 @@
 
 static void SIGCHLD_handler(int) {
     if (TEMP_FAILURE_RETRY(write(signal_write_fd, "1", 1)) == -1) {
-        ERROR("write(signal_write_fd) failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "write(signal_write_fd) failed";
     }
 }
 
@@ -55,7 +52,7 @@
     // Create a signalling mechanism for SIGCHLD.
     int s[2];
     if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, s) == -1) {
-        ERROR("socketpair failed: %s\n", strerror(errno));
+        PLOG(ERROR) << "socketpair failed";
         exit(1);
     }
 
diff --git a/init/test_service/Android.mk b/init/test_service/Android.mk
new file mode 100644
index 0000000..30c9e9d
--- /dev/null
+++ b/init/test_service/Android.mk
@@ -0,0 +1,27 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+# Sample service for testing.
+# =========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := test_service
+LOCAL_SRC_FILES := test_service.cpp
+
+LOCAL_SHARED_LIBRARIES += libbase
+
+LOCAL_INIT_RC := test_service.rc
+
+include $(BUILD_EXECUTABLE)
diff --git a/init/test_service/README.md b/init/test_service/README.md
new file mode 100644
index 0000000..6773235
--- /dev/null
+++ b/init/test_service/README.md
@@ -0,0 +1,43 @@
+# Sample service for testing
+This is a sample service that can be used for testing init.
+
+## Design
+The service includes a `.rc` file that allows starting it from init.
+
+    service test_service /system/bin/test_service CapAmb 0000000000003000
+        class main
+        user system
+        group system
+        capabilities NET_ADMIN NET_RAW
+        disabled
+        oneshot
+
+The service accepts any even number of arguments on the command line
+(i.e. any number of pairs of arguments.)
+It will attempt to find the first element of each pair of arguments in
+`/proc/self/status`, and attempt to exactly match the second element of the pair
+to the relevant line of `proc/self/status`.
+
+### Example
+In the above case, the service will look for lines containing `CapAmb`:
+
+    cat /proc/self/status
+    ...
+    CapAmb:	0000000000003000
+
+And then attempt to exactly match the token after `:`, `0000000000003000`,
+with the command-line argument.
+If they match, the service exits successfully. If not, the service will exit
+with an error.
+
+## Usage
+	mmma -j <jobs> system/core/init/testservice
+	adb root
+	adb remount
+	adb sync
+	adb reboot
+	adb root
+	adb shell start test_service
+	adb logcat -b all -d | grep test_service
+
+Look for an exit status of 0.
diff --git a/init/test_service/test_service.cpp b/init/test_service/test_service.cpp
new file mode 100644
index 0000000..e7206f8
--- /dev/null
+++ b/init/test_service/test_service.cpp
@@ -0,0 +1,78 @@
+// 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 <unistd.h>
+
+#include <map>
+#include <sstream>
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+
+void Usage(char* argv[]) {
+    printf("Usage: %s <status field> <value> [<status field> <value>]*\n", argv[0]);
+    printf("E.g.: $ %s Uid \"1000 1000 1000 1000\"\n", argv[0]);
+}
+
+int main(int argc, char* argv[]) {
+    if (argc < 3) {
+        Usage(argv);
+        LOG(FATAL) << "no status field requested";
+    }
+    if (argc % 2 == 0) {
+        // Since |argc| counts argv[0], if |argc| is odd, then the number of
+        // command-line arguments is even.
+        Usage(argv);
+        LOG(FATAL) << "need even number of command-line arguments";
+    }
+
+    std::string status;
+    bool res = android::base::ReadFileToString("/proc/self/status", &status, true);
+    if (!res) {
+        PLOG(FATAL) << "could not read /proc/self/status";
+    }
+
+    std::map<std::string, std::string> fields;
+    std::vector<std::string> lines = android::base::Split(status, "\n");
+    for (const auto& line : lines) {
+        std::vector<std::string> tokens = android::base::Split(line, ":");
+        if (tokens.size() >= 2) {
+            std::string field = tokens[0];
+            std::string value = android::base::Trim(tokens[1]);
+            if (field.length() > 0) {
+                fields[field] = value;
+            }
+        }
+    }
+
+    bool test_fails = false;
+    size_t uargc = static_cast<size_t>(argc);  // |argc| >= 3.
+    for (size_t i = 1; i < static_cast<size_t>(argc); i = i + 2) {
+        std::string expected_value = argv[i + 1];
+        auto f = fields.find(argv[i]);
+        if (f != fields.end()) {
+            if (f->second != expected_value) {
+                LOG(ERROR) << "field '" << argv[i] << "' expected '" << expected_value
+                           << "', actual '" << f->second << "'";
+                test_fails = true;
+            }
+        } else {
+            LOG(WARNING) << "could not find field '" << argv[i] << "'";
+        }
+    }
+
+    return test_fails ? 1 : 0;
+}
diff --git a/init/test_service/test_service.rc b/init/test_service/test_service.rc
new file mode 100644
index 0000000..91e1a0f
--- /dev/null
+++ b/init/test_service/test_service.rc
@@ -0,0 +1,7 @@
+service test_service /system/bin/test_service CapAmb 0000000000003000
+    class main
+    user system
+    group system
+    capabilities NET_ADMIN NET_RAW
+    disabled
+    oneshot
diff --git a/init/ueventd.cpp b/init/ueventd.cpp
index 249739b..f27be64 100644
--- a/init/ueventd.cpp
+++ b/init/ueventd.cpp
@@ -16,14 +16,18 @@
 
 #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/properties.h>
 #include <android-base/stringprintf.h>
-#include <private/android_filesystem_config.h>
 #include <selinux/selinux.h>
 
 #include "ueventd.h"
@@ -31,7 +35,6 @@
 #include "util.h"
 #include "devices.h"
 #include "ueventd_parser.h"
-#include "property_service.h"
 
 int ueventd_main(int argc, char **argv)
 {
@@ -49,19 +52,26 @@
      */
     signal(SIGCHLD, SIG_IGN);
 
-    open_devnull_stdio();
-    klog_init();
-    klog_set_level(KLOG_NOTICE_LEVEL);
+    InitKernelLogging(argv);
 
-    NOTICE("ueventd started!\n");
+    LOG(INFO) << "ueventd started!";
 
     selinux_callback cb;
     cb.func_log = selinux_klog_callback;
     selinux_set_callback(SELINUX_CB_LOG, cb);
 
-    std::string hardware = property_get("ro.hardware");
-
     ueventd_parse_config_file("/ueventd.rc");
+    ueventd_parse_config_file("/vendor/ueventd.rc");
+    ueventd_parse_config_file("/odm/ueventd.rc");
+
+    /*
+     * keep the current product name base configuration so
+     * we remain backwards compatible and allow it to override
+     * everything
+     * TODO: cleanup platform ueventd.rc to remove vendor specific
+     * device node entries (b/34968103)
+     */
+    std::string hardware = android::base::GetProperty("ro.hardware", "");
     ueventd_parse_config_file(android::base::StringPrintf("/ueventd.%s.rc", hardware.c_str()).c_str());
 
     device_init();
@@ -84,15 +94,6 @@
     return 0;
 }
 
-static int get_android_id(const char *id)
-{
-    unsigned int i;
-    for (i = 0; i < ARRAY_SIZE(android_ids); i++)
-        if (!strcmp(id, android_ids[i].name))
-            return android_ids[i].aid;
-    return -1;
-}
-
 void set_device_permission(int nargs, char **args)
 {
     char *name;
@@ -103,8 +104,6 @@
     int prefix = 0;
     int wildcard = 0;
     char *endptr;
-    int ret;
-    char *tmp = 0;
 
     if (nargs == 0)
         return;
@@ -115,58 +114,53 @@
     name = args[0];
 
     if (!strncmp(name,"/sys/", 5) && (nargs == 5)) {
-        INFO("/sys/ rule %s %s\n",args[0],args[1]);
+        LOG(INFO) << "/sys/ rule " << args[0] << " " << args[1];
         attr = args[1];
         args++;
         nargs--;
     }
 
     if (nargs != 4) {
-        ERROR("invalid line ueventd.rc line for '%s'\n", args[0]);
+        LOG(ERROR) << "invalid line ueventd.rc line for '" << args[0] << "'";
         return;
     }
 
-    /* If path starts with mtd@ lookup the mount number. */
-    if (!strncmp(name, "mtd@", 4)) {
-        int n = mtd_name_to_number(name + 4);
-        if (n >= 0)
-            asprintf(&tmp, "/dev/mtd/mtd%d", n);
-        name = tmp;
-    } else {
-        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;
-        }
+    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') {
-        ERROR("invalid mode '%s'\n", args[1]);
-        free(tmp);
+        LOG(ERROR) << "invalid mode '" << args[1] << "'";
         return;
     }
 
-    ret = get_android_id(args[2]);
-    if (ret < 0) {
-        ERROR("invalid uid '%s'\n", args[2]);
-        free(tmp);
+    struct passwd* pwd = getpwnam(args[2]);
+    if (!pwd) {
+        LOG(ERROR) << "invalid uid '" << args[2] << "'";
         return;
     }
-    uid = ret;
+    uid = pwd->pw_uid;
 
-    ret = get_android_id(args[3]);
-    if (ret < 0) {
-        ERROR("invalid gid '%s'\n", args[3]);
-        free(tmp);
+    struct group* grp = getgrnam(args[3]);
+    if (!grp) {
+        LOG(ERROR) << "invalid gid '" << args[3] << "'";
         return;
     }
-    gid = ret;
+    gid = grp->gr_gid;
 
-    add_dev_perms(name, attr, perm, uid, gid, prefix, wildcard);
-    free(tmp);
+    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_parser.cpp b/init/ueventd_parser.cpp
index 09f4638..baff58c 100644
--- a/init/ueventd_parser.cpp
+++ b/init/ueventd_parser.cpp
@@ -38,7 +38,7 @@
 #include "ueventd_keywords.h"
 
 #define KEYWORD(symbol, flags, nargs) \
-    [ K_##symbol ] = { #symbol, nargs + 1, flags, },
+    [ K_##symbol ] = { #symbol, (nargs) + 1, flags, },
 
 static struct {
     const char *name;
diff --git a/init/util.cpp b/init/util.cpp
index 89d3276..4e3537b 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -14,63 +14,57 @@
  * limitations under the License.
  */
 
+#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 <string.h>
-#include <fcntl.h>
-#include <ctype.h>
-#include <errno.h>
 #include <time.h>
-#include <ftw.h>
+#include <unistd.h>
 
-#include <selinux/label.h>
 #include <selinux/android.h>
+#include <selinux/label.h>
 
+#include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/socket.h>
 #include <sys/un.h>
 
-#include <android-base/file.h>
-#include <android-base/strings.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 <android-base/stringprintf.h>
-
-#include <private/android_filesystem_config.h>
 
 #include "init.h"
 #include "log.h"
-#include "property_service.h"
+#include "reboot.h"
 #include "util.h"
 
-/*
- * android_name_to_id - returns the integer uid/gid associated with the given
- * name, or UINT_MAX on error.
- */
-static unsigned int android_name_to_id(const char *name)
-{
-    const struct android_id_info *info = android_ids;
-    unsigned int n;
-
-    for (n = 0; n < android_id_count; n++) {
-        if (!strcmp(info[n].name, name))
-            return info[n].aid;
-    }
-
-    return UINT_MAX;
-}
-
 static unsigned int do_decode_uid(const char *s)
 {
     unsigned int v;
 
     if (!s || *s == '\0')
         return UINT_MAX;
-    if (isalpha(s[0]))
-        return android_name_to_id(s);
+
+    if (isalpha(s[0])) {
+        struct passwd* pwd = getpwnam(s);
+        if (!pwd)
+            return UINT_MAX;
+        return pwd->pw_uid;
+    }
 
     errno = 0;
     v = (unsigned int) strtoul(s, 0, 0);
@@ -87,7 +81,7 @@
 unsigned int decode_uid(const char *s) {
     unsigned int v = do_decode_uid(s);
     if (v == UINT_MAX) {
-        ERROR("decode_uid: Unable to find UID for '%s'. Returning UINT_MAX\n", s);
+        LOG(ERROR) << "decode_uid: Unable to find UID for '" << s << "'; returning UINT_MAX";
     }
     return v;
 }
@@ -101,82 +95,77 @@
 int create_socket(const char *name, int type, mode_t perm, uid_t uid,
                   gid_t gid, const char *socketcon)
 {
-    struct sockaddr_un addr;
-    int fd, ret, savederrno;
-    char *filecon;
-
     if (socketcon) {
         if (setsockcreatecon(socketcon) == -1) {
-            ERROR("setsockcreatecon(\"%s\") failed: %s\n", socketcon, strerror(errno));
+            PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed";
             return -1;
         }
     }
 
-    fd = socket(PF_UNIX, type, 0);
+    android::base::unique_fd fd(socket(PF_UNIX, type, 0));
     if (fd < 0) {
-        ERROR("Failed to open socket '%s': %s\n", name, strerror(errno));
+        PLOG(ERROR) << "Failed to open socket '" << name << "'";
         return -1;
     }
 
-    if (socketcon)
-        setsockcreatecon(NULL);
+    if (socketcon) setsockcreatecon(NULL);
 
+    struct sockaddr_un addr;
     memset(&addr, 0 , sizeof(addr));
     addr.sun_family = AF_UNIX;
     snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s",
              name);
 
-    ret = unlink(addr.sun_path);
-    if (ret != 0 && errno != ENOENT) {
-        ERROR("Failed to unlink old socket '%s': %s\n", name, strerror(errno));
-        goto out_close;
+    if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
+        PLOG(ERROR) << "Failed to unlink old socket '" << name << "'";
+        return -1;
     }
 
-    filecon = NULL;
+    char *filecon = NULL;
     if (sehandle) {
-        ret = selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK);
-        if (ret == 0)
+        if (selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK) == 0) {
             setfscreatecon(filecon);
+        }
     }
 
-    ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
-    savederrno = errno;
+    int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
+    int savederrno = errno;
 
     setfscreatecon(NULL);
     freecon(filecon);
 
     if (ret) {
-        ERROR("Failed to bind socket '%s': %s\n", name, strerror(savederrno));
+        errno = savederrno;
+        PLOG(ERROR) << "Failed to bind socket '" << name << "'";
         goto out_unlink;
     }
 
-    ret = lchown(addr.sun_path, uid, gid);
-    if (ret) {
-        ERROR("Failed to lchown socket '%s': %s\n", addr.sun_path, strerror(errno));
+    if (lchown(addr.sun_path, uid, gid)) {
+        PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'";
         goto out_unlink;
     }
-    ret = fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW);
-    if (ret) {
-        ERROR("Failed to fchmodat socket '%s': %s\n", addr.sun_path, strerror(errno));
+    if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
+        PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'";
         goto out_unlink;
     }
 
-    INFO("Created socket '%s' with mode '%o', user '%d', group '%d'\n",
-         addr.sun_path, perm, uid, gid);
+    LOG(INFO) << "Created socket '" << addr.sun_path << "'"
+              << ", mode " << std::oct << perm << std::dec
+              << ", user " << uid
+              << ", group " << gid;
 
-    return fd;
+    return fd.release();
 
 out_unlink:
     unlink(addr.sun_path);
-out_close:
-    close(fd);
     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;
     }
@@ -185,115 +174,36 @@
     // or group-writable files.
     struct stat sb;
     if (fstat(fd, &sb) == -1) {
-        ERROR("fstat failed for '%s': %s\n", path, strerror(errno));
+        PLOG(ERROR) << "fstat failed for '" << path << "'";
         return false;
     }
     if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
-        ERROR("skipping insecure file '%s'\n", 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);
 }
 
-int 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) {
-        NOTICE("write_file: Unable to open '%s': %s\n", path, strerror(errno));
-        return -1;
+        PLOG(ERROR) << "write_file: Unable to open '" << path << "'";
+        return false;
     }
-    int result = android::base::WriteStringToFd(content, fd) ? 0 : -1;
-    if (result == -1) {
-        NOTICE("write_file: Unable to write to '%s': %s\n", path, strerror(errno));
+    bool success = android::base::WriteStringToFd(content, fd);
+    if (!success) {
+        PLOG(ERROR) << "write_file: Unable to write to '" << path << "'";
     }
-    close(fd);
-    return result;
+    return success;
 }
 
-#define MAX_MTD_PARTITIONS 16
-
-static struct {
-    char name[16];
-    int number;
-} mtd_part_map[MAX_MTD_PARTITIONS];
-
-static int mtd_part_count = -1;
-
-static void find_mtd_partitions(void)
-{
-    int fd;
-    char buf[1024];
-    char *pmtdbufp;
-    ssize_t pmtdsize;
-    int r;
-
-    fd = open("/proc/mtd", O_RDONLY|O_CLOEXEC);
-    if (fd < 0)
-        return;
-
-    buf[sizeof(buf) - 1] = '\0';
-    pmtdsize = read(fd, buf, sizeof(buf) - 1);
-    pmtdbufp = buf;
-    while (pmtdsize > 0) {
-        int mtdnum, mtdsize, mtderasesize;
-        char mtdname[16];
-        mtdname[0] = '\0';
-        mtdnum = -1;
-        r = sscanf(pmtdbufp, "mtd%d: %x %x %15s",
-                   &mtdnum, &mtdsize, &mtderasesize, mtdname);
-        if ((r == 4) && (mtdname[0] == '"')) {
-            char *x = strchr(mtdname + 1, '"');
-            if (x) {
-                *x = 0;
-            }
-            INFO("mtd partition %d, %s\n", mtdnum, mtdname + 1);
-            if (mtd_part_count < MAX_MTD_PARTITIONS) {
-                strcpy(mtd_part_map[mtd_part_count].name, mtdname + 1);
-                mtd_part_map[mtd_part_count].number = mtdnum;
-                mtd_part_count++;
-            } else {
-                ERROR("too many mtd partitions\n");
-            }
-        }
-        while (pmtdsize > 0 && *pmtdbufp != '\n') {
-            pmtdbufp++;
-            pmtdsize--;
-        }
-        if (pmtdsize > 0) {
-            pmtdbufp++;
-            pmtdsize--;
-        }
-    }
-    close(fd);
-}
-
-int mtd_name_to_number(const char *name)
-{
-    int n;
-    if (mtd_part_count < 0) {
-        mtd_part_count = 0;
-        find_mtd_partitions();
-    }
-    for (n = 0; n < mtd_part_count; n++) {
-        if (!strcmp(name, mtd_part_map[n].name)) {
-            return mtd_part_map[n].number;
-        }
-    }
-    return -1;
-}
-
-time_t gettime() {
-    timespec now;
-    clock_gettime(CLOCK_MONOTONIC, &now);
-    return now.tv_sec;
-}
-
-uint64_t gettime_ns() {
-    timespec now;
-    clock_gettime(CLOCK_MONOTONIC, &now);
-    return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
+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)
@@ -313,7 +223,7 @@
         if (width == 0)
             continue;
         if ((unsigned int)width > sizeof(buf) - 1) {
-            ERROR("path too long for mkdir_recursive\n");
+            LOG(ERROR) << "path too long for mkdir_recursive";
             return -1;
         }
         memcpy(buf, pathname, width);
@@ -351,82 +261,19 @@
     }
 }
 
-void make_link_init(const char *oldpath, const char *newpath)
-{
-    int ret;
-    char buf[256];
-    char *slash;
-    int width;
+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) {
+        struct stat sb;
+        if (stat(filename, &sb) != -1) return 0;
 
-    slash = strrchr(newpath, '/');
-    if (!slash)
-        return;
-    width = slash - newpath;
-    if (width <= 0 || width > (int)sizeof(buf) - 1)
-        return;
-    memcpy(buf, newpath, width);
-    buf[width] = 0;
-    ret = mkdir_recursive(buf, 0755);
-    if (ret)
-        ERROR("Failed to create directory %s: %s (%d)\n", buf, strerror(errno), errno);
-
-    ret = symlink(oldpath, newpath);
-    if (ret && errno != EEXIST)
-        ERROR("Failed to symlink %s to %s: %s (%d)\n", oldpath, newpath, strerror(errno), errno);
-}
-
-void remove_link(const char *oldpath, const char *newpath)
-{
-    char path[256];
-    ssize_t ret;
-    ret = readlink(newpath, path, sizeof(path) - 1);
-    if (ret <= 0)
-        return;
-    path[ret] = 0;
-    if (!strcmp(path, oldpath))
-        unlink(newpath);
-}
-
-int wait_for_file(const char *filename, int timeout)
-{
-    struct stat info;
-    uint64_t timeout_time_ns = gettime_ns() + timeout * UINT64_C(1000000000);
-    int ret = -1;
-
-    while (gettime_ns() < timeout_time_ns && ((ret = stat(filename, &info)) < 0))
-        usleep(10000);
-
-    return ret;
-}
-
-void open_devnull_stdio(void)
-{
-    // Try to avoid the mknod() call if we can. Since SELinux makes
-    // a /dev/null replacement available for free, let's use it.
-    int fd = open("/sys/fs/selinux/null", O_RDWR);
-    if (fd == -1) {
-        // OOPS, /sys/fs/selinux/null isn't available, likely because
-        // /sys/fs/selinux isn't mounted. Fall back to mknod.
-        static const char *name = "/dev/__null__";
-        if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) {
-            fd = open(name, O_RDWR);
-            unlink(name);
-        }
-        if (fd == -1) {
-            exit(1);
-        }
+        std::this_thread::sleep_for(10ms);
     }
-
-    dup2(fd, 0);
-    dup2(fd, 1);
-    dup2(fd, 2);
-    if (fd > 2) {
-        close(fd);
-    }
+    return -1;
 }
 
 void import_kernel_cmdline(bool in_qemu,
-                           std::function<void(const std::string&, const std::string&, bool)> fn) {
+                           const std::function<void(const std::string&, const std::string&, bool)>& fn) {
     std::string cmdline;
     android::base::ReadFileToString("/proc/cmdline", &cmdline);
 
@@ -461,20 +308,9 @@
     return rc;
 }
 
-int restorecon(const char* pathname)
+int restorecon(const char* pathname, int flags)
 {
-    return selinux_android_restorecon(pathname, 0);
-}
-
-int restorecon_recursive(const char* pathname)
-{
-    return selinux_android_restorecon(pathname, SELINUX_ANDROID_RESTORECON_RECURSE);
-}
-
-int restorecon_recursive_skipce(const char* pathname)
-{
-    return selinux_android_restorecon(pathname,
-            SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIPCE);
+    return selinux_android_restorecon(pathname, flags);
 }
 
 /*
@@ -539,7 +375,7 @@
             const char* end = strchr(c, '}');
             if (!end) {
                 // failed to find closing brace, abort.
-                ERROR("unexpected end of string in '%s', looking for }\n", src.c_str());
+                LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }";
                 return false;
             }
             prop_name = std::string(c, end);
@@ -551,21 +387,19 @@
             }
         } else {
             prop_name = c;
-            ERROR("using deprecated syntax for specifying property '%s', use ${name} instead\n",
-                  c);
+            LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead";
             c += prop_name.size();
         }
 
         if (prop_name.empty()) {
-            ERROR("invalid zero-length prop name in '%s'\n", src.c_str());
+            LOG(ERROR) << "invalid zero-length property name in '" << src << "'";
             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()) {
-                ERROR("property '%s' doesn't exist while expanding '%s'\n",
-                      prop_name.c_str(), src.c_str());
+                LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'";
                 return false;
             }
             prop_val = def_val;
@@ -577,3 +411,36 @@
 
     return true;
 }
+
+void panic() {
+    LOG(ERROR) << "panic: rebooting to 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 af4b098..bb281bd 100644
--- a/init/util.h
+++ b/init/util.h
@@ -20,51 +20,70 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#include <string>
+#include <chrono>
 #include <functional>
-
-#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
+#include <ostream>
+#include <string>
 
 #define COLDBOOT_DONE "/dev/.coldboot_done"
 
-int mtd_name_to_number(const char *name);
+const std::string kAndroidDtDir("/proc/device-tree/firmware/android/");
+
+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);
-int write_file(const char* path, const char* content);
+bool read_file(const std::string& path, std::string* content);
+bool write_file(const std::string& path, const std::string& content);
 
-time_t gettime();
-uint64_t gettime_ns();
+// 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();
+};
 
 class Timer {
  public:
-  Timer() : t0(gettime_ns()) {
+  Timer() : start_(boot_clock::now()) {
   }
 
-  double duration() {
-    return static_cast<double>(gettime_ns() - t0) / 1000000000.0;
+  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();
   }
 
  private:
-  uint64_t t0;
+  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);
-void make_link_init(const char *oldpath, const char *newpath);
-void remove_link(const char *oldpath, const char *newpath);
-int wait_for_file(const char *filename, int timeout);
-void open_devnull_stdio(void);
+int wait_for_file(const char *filename, std::chrono::nanoseconds timeout);
 void import_kernel_cmdline(bool in_qemu,
-                           std::function<void(const std::string&, const std::string&, bool)>);
+                           const std::function<void(const std::string&, const std::string&, bool)>&);
 int make_dir(const char *path, mode_t mode);
-int restorecon(const char *pathname);
-int restorecon_recursive(const char *pathname);
-int restorecon_recursive_skipce(const char *pathname);
+int restorecon(const char *pathname, int flags = 0);
 std::string bytes_to_hex(const uint8_t *bytes, size_t bytes_len);
 bool is_dir(const char* pathname);
 bool expand_props(const std::string& src, std::string* dst);
+
+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 228954b..0c0350a 100644
--- a/init/util_test.cpp
+++ b/init/util_test.cpp
@@ -17,6 +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) {
@@ -27,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));
@@ -36,6 +70,51 @@
   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"));
diff --git a/init/watchdogd.cpp b/init/watchdogd.cpp
index 0d16db9..b196147 100644
--- a/init/watchdogd.cpp
+++ b/init/watchdogd.cpp
@@ -28,9 +28,7 @@
 #define DEV_NAME "/dev/watchdog"
 
 int watchdogd_main(int argc, char **argv) {
-    open_devnull_stdio();
-    klog_init();
-    klog_set_level(KLOG_NOTICE_LEVEL);
+    InitKernelLogging(argv);
 
     int interval = 10;
     if (argc >= 2) interval = atoi(argv[1]);
@@ -38,30 +36,31 @@
     int margin = 10;
     if (argc >= 3) margin = atoi(argv[2]);
 
-    NOTICE("started (interval %d, margin %d)!\n", interval, margin);
+    LOG(INFO) << "watchdogd started (interval " << interval << ", margin " << margin << ")!";
 
     int fd = open(DEV_NAME, O_RDWR|O_CLOEXEC);
     if (fd == -1) {
-        ERROR("Failed to open %s: %s\n", DEV_NAME, strerror(errno));
+        PLOG(ERROR) << "Failed to open " << DEV_NAME;
         return 1;
     }
 
     int timeout = interval + margin;
     int ret = ioctl(fd, WDIOC_SETTIMEOUT, &timeout);
     if (ret) {
-        ERROR("Failed to set timeout to %d: %s\n", timeout, strerror(errno));
+        PLOG(ERROR) << "Failed to set timeout to " << timeout;
         ret = ioctl(fd, WDIOC_GETTIMEOUT, &timeout);
         if (ret) {
-            ERROR("Failed to get timeout: %s\n", strerror(errno));
+            PLOG(ERROR) << "Failed to get timeout";
         } else {
             if (timeout > margin) {
                 interval = timeout - margin;
             } else {
                 interval = 1;
             }
-            WARNING("Adjusted interval to timeout returned by driver:"
-                    " timeout %d, interval %d, margin %d\n",
-                    timeout, interval, margin);
+            LOG(WARNING) << "Adjusted interval to timeout returned by driver: "
+                         << "timeout " << timeout
+                         << ", interval " << interval
+                         << ", margin " << margin;
         }
     }
 
diff --git a/libappfuse/Android.bp b/libappfuse/Android.bp
new file mode 100644
index 0000000..0d57814
--- /dev/null
+++ b/libappfuse/Android.bp
@@ -0,0 +1,35 @@
+// Copyright 2016 The Android Open Source Project
+
+cc_defaults {
+    name: "libappfuse_defaults",
+    local_include_dirs: ["include"],
+    shared_libs: ["libbase"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    clang: true
+}
+
+cc_library_shared {
+    name: "libappfuse",
+    defaults: ["libappfuse_defaults"],
+    export_include_dirs: ["include"],
+    srcs: [
+        "FuseAppLoop.cc",
+        "FuseBuffer.cc",
+        "FuseBridgeLoop.cc",
+        "EpollController.cc",
+    ]
+}
+
+cc_test {
+    name: "libappfuse_test",
+    defaults: ["libappfuse_defaults"],
+    shared_libs: ["libappfuse"],
+    srcs: [
+        "tests/FuseAppLoopTest.cc",
+        "tests/FuseBridgeLoopTest.cc",
+        "tests/FuseBufferTest.cc",
+    ]
+}
diff --git a/libappfuse/EpollController.cc b/libappfuse/EpollController.cc
new file mode 100644
index 0000000..9daeab8
--- /dev/null
+++ b/libappfuse/EpollController.cc
@@ -0,0 +1,66 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/logging.h>
+
+#include "libappfuse/EpollController.h"
+
+namespace android {
+namespace fuse {
+
+EpollController::EpollController(base::unique_fd&& poll_fd) : poll_fd_(std::move(poll_fd)) {
+}
+
+bool EpollController::Wait(size_t event_count) {
+    events_.resize(event_count);
+    const int result = TEMP_FAILURE_RETRY(epoll_wait(poll_fd_, events_.data(), event_count, -1));
+    if (result == -1) {
+        PLOG(ERROR) << "Failed to wait for epoll";
+        return false;
+    }
+    events_.resize(result);
+    return true;
+}
+
+bool EpollController::AddFd(int fd, int events, void* data) {
+    return InvokeControl(EPOLL_CTL_ADD, fd, events, data);
+}
+
+bool EpollController::UpdateFd(int fd, int events, void* data) {
+    return InvokeControl(EPOLL_CTL_MOD, fd, events, data);
+}
+
+bool EpollController::RemoveFd(int fd) {
+    return InvokeControl(EPOLL_CTL_DEL, fd, /* events */ 0, nullptr);
+}
+
+const std::vector<epoll_event>& EpollController::events() const {
+    return events_;
+}
+
+bool EpollController::InvokeControl(int op, int fd, int events, void* data) const {
+    epoll_event event;
+    memset(&event, 0, sizeof(event));
+    event.events = events;
+    event.data.ptr = data;
+    if (epoll_ctl(poll_fd_, op, fd, &event) == -1) {
+        PLOG(ERROR) << "epoll_ctl() error op=" << op;
+        return false;
+    }
+    return true;
+}
+}
+}
diff --git a/libappfuse/FuseAppLoop.cc b/libappfuse/FuseAppLoop.cc
new file mode 100644
index 0000000..b6bc191
--- /dev/null
+++ b/libappfuse/FuseAppLoop.cc
@@ -0,0 +1,248 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseAppLoop.h"
+
+#include <sys/eventfd.h>
+#include <sys/stat.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+#include "libappfuse/EpollController.h"
+
+namespace android {
+namespace fuse {
+
+namespace {
+
+bool HandleLookUp(FuseAppLoop* loop, FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+    // AppFuse does not support directory structure now.
+    // It can lookup only files under the mount point.
+    if (buffer->request.header.nodeid != FUSE_ROOT_ID) {
+        LOG(ERROR) << "Nodeid is not FUSE_ROOT_ID.";
+        return loop->ReplySimple(buffer->request.header.unique, -ENOENT);
+    }
+
+    // Ensure that the filename ends with 0.
+    const size_t filename_length = buffer->request.header.len - sizeof(fuse_in_header);
+    if (buffer->request.lookup_name[filename_length - 1] != 0) {
+        LOG(ERROR) << "File name does not end with 0.";
+        return loop->ReplySimple(buffer->request.header.unique, -ENOENT);
+    }
+
+    const uint64_t inode = static_cast<uint64_t>(atol(buffer->request.lookup_name));
+    if (inode == 0 || inode == LONG_MAX) {
+        LOG(ERROR) << "Invalid filename";
+        return loop->ReplySimple(buffer->request.header.unique, -ENOENT);
+    }
+
+    callback->OnLookup(buffer->request.header.unique, inode);
+    return true;
+}
+
+bool HandleGetAttr(FuseAppLoop* loop, FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+    if (buffer->request.header.nodeid == FUSE_ROOT_ID) {
+        return loop->ReplyGetAttr(buffer->request.header.unique, buffer->request.header.nodeid, 0,
+                                  S_IFDIR | 0777);
+    } else {
+        callback->OnGetAttr(buffer->request.header.unique, buffer->request.header.nodeid);
+        return true;
+    }
+}
+
+bool HandleRead(FuseAppLoop* loop, FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+    if (buffer->request.read_in.size > kFuseMaxRead) {
+        return loop->ReplySimple(buffer->request.header.unique, -EINVAL);
+    }
+
+    callback->OnRead(buffer->request.header.unique, buffer->request.header.nodeid,
+                     buffer->request.read_in.offset, buffer->request.read_in.size);
+    return true;
+}
+
+bool HandleWrite(FuseAppLoop* loop, FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+    if (buffer->request.write_in.size > kFuseMaxWrite) {
+        return loop->ReplySimple(buffer->request.header.unique, -EINVAL);
+    }
+
+    callback->OnWrite(buffer->request.header.unique, buffer->request.header.nodeid,
+                      buffer->request.write_in.offset, buffer->request.write_in.size,
+                      buffer->request.write_data);
+    return true;
+}
+
+bool HandleMessage(FuseAppLoop* loop, FuseBuffer* buffer, int fd, FuseAppLoopCallback* callback) {
+    if (!buffer->request.Read(fd)) {
+        return false;
+    }
+
+    const uint32_t opcode = buffer->request.header.opcode;
+    LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
+    switch (opcode) {
+        case FUSE_FORGET:
+            // Do not reply to FUSE_FORGET.
+            return true;
+
+        case FUSE_LOOKUP:
+            return HandleLookUp(loop, buffer, callback);
+
+        case FUSE_GETATTR:
+            return HandleGetAttr(loop, buffer, callback);
+
+        case FUSE_OPEN:
+            callback->OnOpen(buffer->request.header.unique, buffer->request.header.nodeid);
+            return true;
+
+        case FUSE_READ:
+            return HandleRead(loop, buffer, callback);
+
+        case FUSE_WRITE:
+            return HandleWrite(loop, buffer, callback);
+
+        case FUSE_RELEASE:
+            callback->OnRelease(buffer->request.header.unique, buffer->request.header.nodeid);
+            return true;
+
+        case FUSE_FSYNC:
+            callback->OnFsync(buffer->request.header.unique, buffer->request.header.nodeid);
+            return true;
+
+        default:
+            buffer->HandleNotImpl();
+            return buffer->response.Write(fd);
+    }
+}
+
+} // namespace
+
+FuseAppLoopCallback::~FuseAppLoopCallback() = default;
+
+FuseAppLoop::FuseAppLoop(base::unique_fd&& fd) : fd_(std::move(fd)) {}
+
+void FuseAppLoop::Break() {
+    const int64_t value = 1;
+    if (write(break_fd_, &value, sizeof(value)) == -1) {
+        PLOG(ERROR) << "Failed to send a break event";
+    }
+}
+
+bool FuseAppLoop::ReplySimple(uint64_t unique, int32_t result) {
+    if (result == -ENOSYS) {
+        // We should not return -ENOSYS because the kernel stops delivering FUSE
+        // command after receiving -ENOSYS as a result for the command.
+        result = -EBADF;
+    }
+    FuseSimpleResponse response;
+    response.Reset(0, result, unique);
+    return response.Write(fd_);
+}
+
+bool FuseAppLoop::ReplyLookup(uint64_t unique, uint64_t inode, int64_t size) {
+    FuseSimpleResponse response;
+    response.Reset(sizeof(fuse_entry_out), 0, unique);
+    response.entry_out.nodeid = inode;
+    response.entry_out.attr_valid = 10;
+    response.entry_out.entry_valid = 10;
+    response.entry_out.attr.ino = inode;
+    response.entry_out.attr.mode = S_IFREG | 0777;
+    response.entry_out.attr.size = size;
+    return response.Write(fd_);
+}
+
+bool FuseAppLoop::ReplyGetAttr(uint64_t unique, uint64_t inode, int64_t size, int mode) {
+    CHECK(mode == (S_IFREG | 0777) || mode == (S_IFDIR | 0777));
+    FuseSimpleResponse response;
+    response.Reset(sizeof(fuse_attr_out), 0, unique);
+    response.attr_out.attr_valid = 10;
+    response.attr_out.attr.ino = inode;
+    response.attr_out.attr.mode = mode;
+    response.attr_out.attr.size = size;
+    return response.Write(fd_);
+}
+
+bool FuseAppLoop::ReplyOpen(uint64_t unique, uint64_t fh) {
+    FuseSimpleResponse response;
+    response.Reset(sizeof(fuse_open_out), kFuseSuccess, unique);
+    response.open_out.fh = fh;
+    return response.Write(fd_);
+}
+
+bool FuseAppLoop::ReplyWrite(uint64_t unique, uint32_t size) {
+    CHECK(size <= kFuseMaxWrite);
+    FuseSimpleResponse response;
+    response.Reset(sizeof(fuse_write_out), kFuseSuccess, unique);
+    response.write_out.size = size;
+    return response.Write(fd_);
+}
+
+bool FuseAppLoop::ReplyRead(uint64_t unique, uint32_t size, const void* data) {
+    CHECK(size <= kFuseMaxRead);
+    FuseSimpleResponse response;
+    response.ResetHeader(size, kFuseSuccess, unique);
+    return response.WriteWithBody(fd_, sizeof(FuseResponse), data);
+}
+
+void FuseAppLoop::Start(FuseAppLoopCallback* callback) {
+    break_fd_.reset(eventfd(/* initval */ 0, EFD_CLOEXEC));
+    if (break_fd_.get() == -1) {
+        PLOG(ERROR) << "Failed to open FD for break event";
+        return;
+    }
+
+    base::unique_fd epoll_fd(epoll_create1(EPOLL_CLOEXEC));
+    if (epoll_fd.get() == -1) {
+        PLOG(ERROR) << "Failed to open FD for epoll";
+        return;
+    }
+
+    int last_event;
+    int break_event;
+
+    std::unique_ptr<EpollController> epoll_controller(new EpollController(std::move(epoll_fd)));
+    if (!epoll_controller->AddFd(fd_, EPOLLIN, &last_event)) {
+        return;
+    }
+    if (!epoll_controller->AddFd(break_fd_, EPOLLIN, &break_event)) {
+        return;
+    }
+
+    last_event = 0;
+    break_event = 0;
+
+    FuseBuffer buffer;
+    while (true) {
+        if (!epoll_controller->Wait(1)) {
+            break;
+        }
+        last_event = 0;
+        *reinterpret_cast<int*>(epoll_controller->events()[0].data.ptr) =
+            epoll_controller->events()[0].events;
+
+        if (break_event != 0 || (last_event & ~EPOLLIN) != 0) {
+            break;
+        }
+
+        if (!HandleMessage(this, &buffer, fd_, callback)) {
+            break;
+        }
+    }
+
+    LOG(VERBOSE) << "FuseAppLoop exit";
+}
+
+}  // namespace fuse
+}  // namespace android
diff --git a/libappfuse/FuseBridgeLoop.cc b/libappfuse/FuseBridgeLoop.cc
new file mode 100644
index 0000000..3f47066
--- /dev/null
+++ b/libappfuse/FuseBridgeLoop.cc
@@ -0,0 +1,371 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBridgeLoop.h"
+
+#include <sys/epoll.h>
+#include <sys/socket.h>
+
+#include <unordered_map>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+#include "libappfuse/EpollController.h"
+
+namespace android {
+namespace fuse {
+namespace {
+
+enum class FuseBridgeState { kWaitToReadEither, kWaitToReadProxy, kWaitToWriteProxy, kClosing };
+
+struct FuseBridgeEntryEvent {
+    FuseBridgeEntry* entry;
+    int events;
+};
+
+void GetObservedEvents(FuseBridgeState state, int* device_events, int* proxy_events) {
+    switch (state) {
+        case FuseBridgeState::kWaitToReadEither:
+            *device_events = EPOLLIN;
+            *proxy_events = EPOLLIN;
+            return;
+        case FuseBridgeState::kWaitToReadProxy:
+            *device_events = 0;
+            *proxy_events = EPOLLIN;
+            return;
+        case FuseBridgeState::kWaitToWriteProxy:
+            *device_events = 0;
+            *proxy_events = EPOLLOUT;
+            return;
+        case FuseBridgeState::kClosing:
+            *device_events = 0;
+            *proxy_events = 0;
+            return;
+    }
+}
+}
+
+class FuseBridgeEntry {
+  public:
+    FuseBridgeEntry(int mount_id, base::unique_fd&& dev_fd, base::unique_fd&& proxy_fd)
+        : mount_id_(mount_id),
+          device_fd_(std::move(dev_fd)),
+          proxy_fd_(std::move(proxy_fd)),
+          state_(FuseBridgeState::kWaitToReadEither),
+          last_state_(FuseBridgeState::kWaitToReadEither),
+          last_device_events_({this, 0}),
+          last_proxy_events_({this, 0}),
+          open_count_(0) {}
+
+    // Transfer bytes depends on availability of FDs and the internal |state_|.
+    void Transfer(FuseBridgeLoopCallback* callback) {
+        constexpr int kUnexpectedEventMask = ~(EPOLLIN | EPOLLOUT);
+        const bool unexpected_event = (last_device_events_.events & kUnexpectedEventMask) ||
+                                      (last_proxy_events_.events & kUnexpectedEventMask);
+        const bool device_read_ready = last_device_events_.events & EPOLLIN;
+        const bool proxy_read_ready = last_proxy_events_.events & EPOLLIN;
+        const bool proxy_write_ready = last_proxy_events_.events & EPOLLOUT;
+
+        last_device_events_.events = 0;
+        last_proxy_events_.events = 0;
+
+        LOG(VERBOSE) << "Transfer device_read_ready=" << device_read_ready
+                     << " proxy_read_ready=" << proxy_read_ready
+                     << " proxy_write_ready=" << proxy_write_ready;
+
+        if (unexpected_event) {
+            LOG(ERROR) << "Invalid epoll event is observed";
+            state_ = FuseBridgeState::kClosing;
+            return;
+        }
+
+        switch (state_) {
+            case FuseBridgeState::kWaitToReadEither:
+                if (proxy_read_ready) {
+                    state_ = ReadFromProxy();
+                } else if (device_read_ready) {
+                    state_ = ReadFromDevice(callback);
+                }
+                return;
+
+            case FuseBridgeState::kWaitToReadProxy:
+                CHECK(proxy_read_ready);
+                state_ = ReadFromProxy();
+                return;
+
+            case FuseBridgeState::kWaitToWriteProxy:
+                CHECK(proxy_write_ready);
+                state_ = WriteToProxy();
+                return;
+
+            case FuseBridgeState::kClosing:
+                return;
+        }
+    }
+
+    bool IsClosing() const { return state_ == FuseBridgeState::kClosing; }
+
+    int mount_id() const { return mount_id_; }
+
+  private:
+    friend class BridgeEpollController;
+
+    FuseBridgeState ReadFromProxy() {
+        switch (buffer_.response.ReadOrAgain(proxy_fd_)) {
+            case ResultOrAgain::kSuccess:
+                break;
+            case ResultOrAgain::kFailure:
+                return FuseBridgeState::kClosing;
+            case ResultOrAgain::kAgain:
+                return FuseBridgeState::kWaitToReadProxy;
+        }
+
+        if (!buffer_.response.Write(device_fd_)) {
+            return FuseBridgeState::kClosing;
+        }
+
+        auto it = opcode_map_.find(buffer_.response.header.unique);
+        if (it != opcode_map_.end()) {
+            switch (it->second) {
+                case FUSE_OPEN:
+                    if (buffer_.response.header.error == fuse::kFuseSuccess) {
+                        open_count_++;
+                    }
+                    break;
+
+                case FUSE_RELEASE:
+                    if (open_count_ > 0) {
+                        open_count_--;
+                    } else {
+                        LOG(WARNING) << "Unexpected FUSE_RELEASE before opening a file.";
+                        break;
+                    }
+                    if (open_count_ == 0) {
+                        return FuseBridgeState::kClosing;
+                    }
+                    break;
+            }
+            opcode_map_.erase(it);
+        }
+
+        return FuseBridgeState::kWaitToReadEither;
+    }
+
+    FuseBridgeState ReadFromDevice(FuseBridgeLoopCallback* callback) {
+        LOG(VERBOSE) << "ReadFromDevice";
+        if (!buffer_.request.Read(device_fd_)) {
+            return FuseBridgeState::kClosing;
+        }
+
+        const uint32_t opcode = buffer_.request.header.opcode;
+        LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
+        switch (opcode) {
+            case FUSE_FORGET:
+                // Do not reply to FUSE_FORGET.
+                return FuseBridgeState::kWaitToReadEither;
+
+            case FUSE_LOOKUP:
+            case FUSE_GETATTR:
+            case FUSE_OPEN:
+            case FUSE_READ:
+            case FUSE_WRITE:
+            case FUSE_RELEASE:
+            case FUSE_FSYNC:
+                if (opcode == FUSE_OPEN || opcode == FUSE_RELEASE) {
+                    opcode_map_.emplace(buffer_.request.header.unique, opcode);
+                }
+                return WriteToProxy();
+
+            case FUSE_INIT:
+                buffer_.HandleInit();
+                break;
+
+            default:
+                buffer_.HandleNotImpl();
+                break;
+        }
+
+        if (!buffer_.response.Write(device_fd_)) {
+            return FuseBridgeState::kClosing;
+        }
+
+        if (opcode == FUSE_INIT) {
+            callback->OnMount(mount_id_);
+        }
+
+        return FuseBridgeState::kWaitToReadEither;
+    }
+
+    FuseBridgeState WriteToProxy() {
+        switch (buffer_.request.WriteOrAgain(proxy_fd_)) {
+            case ResultOrAgain::kSuccess:
+                return FuseBridgeState::kWaitToReadEither;
+            case ResultOrAgain::kFailure:
+                return FuseBridgeState::kClosing;
+            case ResultOrAgain::kAgain:
+                return FuseBridgeState::kWaitToWriteProxy;
+        }
+    }
+
+    const int mount_id_;
+    base::unique_fd device_fd_;
+    base::unique_fd proxy_fd_;
+    FuseBuffer buffer_;
+    FuseBridgeState state_;
+    FuseBridgeState last_state_;
+    FuseBridgeEntryEvent last_device_events_;
+    FuseBridgeEntryEvent last_proxy_events_;
+
+    // Remember map between unique and opcode in fuse_in_header so that we can
+    // refer the opcode later.
+    std::unordered_map<uint64_t, uint32_t> opcode_map_;
+
+    int open_count_;
+
+    DISALLOW_COPY_AND_ASSIGN(FuseBridgeEntry);
+};
+
+class BridgeEpollController : private EpollController {
+  public:
+    BridgeEpollController(base::unique_fd&& poll_fd) : EpollController(std::move(poll_fd)) {}
+
+    bool AddBridgePoll(FuseBridgeEntry* bridge) const {
+        return InvokeControl(EPOLL_CTL_ADD, bridge);
+    }
+
+    bool UpdateOrDeleteBridgePoll(FuseBridgeEntry* bridge) const {
+        return InvokeControl(
+            bridge->state_ != FuseBridgeState::kClosing ? EPOLL_CTL_MOD : EPOLL_CTL_DEL, bridge);
+    }
+
+    bool Wait(size_t bridge_count, std::unordered_set<FuseBridgeEntry*>* entries_out) {
+        CHECK(entries_out);
+        const size_t event_count = std::max<size_t>(bridge_count * 2, 1);
+        if (!EpollController::Wait(event_count)) {
+            return false;
+        }
+        entries_out->clear();
+        for (const auto& event : events()) {
+            FuseBridgeEntryEvent* const entry_event =
+                reinterpret_cast<FuseBridgeEntryEvent*>(event.data.ptr);
+            entry_event->events = event.events;
+            entries_out->insert(entry_event->entry);
+        }
+        return true;
+    }
+
+  private:
+    bool InvokeControl(int op, FuseBridgeEntry* bridge) const {
+        LOG(VERBOSE) << "InvokeControl op=" << op << " bridge=" << bridge->mount_id_
+                     << " state=" << static_cast<int>(bridge->state_)
+                     << " last_state=" << static_cast<int>(bridge->last_state_);
+
+        int last_device_events;
+        int last_proxy_events;
+        int device_events;
+        int proxy_events;
+        GetObservedEvents(bridge->last_state_, &last_device_events, &last_proxy_events);
+        GetObservedEvents(bridge->state_, &device_events, &proxy_events);
+        bool result = true;
+        if (op != EPOLL_CTL_MOD || last_device_events != device_events) {
+            result &= EpollController::InvokeControl(op, bridge->device_fd_, device_events,
+                                                     &bridge->last_device_events_);
+        }
+        if (op != EPOLL_CTL_MOD || last_proxy_events != proxy_events) {
+            result &= EpollController::InvokeControl(op, bridge->proxy_fd_, proxy_events,
+                                                     &bridge->last_proxy_events_);
+        }
+        return result;
+    }
+};
+
+FuseBridgeLoop::FuseBridgeLoop() : opened_(true) {
+    base::unique_fd epoll_fd(epoll_create1(/* no flag */ 0));
+    if (epoll_fd.get() == -1) {
+        PLOG(ERROR) << "Failed to open FD for epoll";
+        opened_ = false;
+        return;
+    }
+    epoll_controller_.reset(new BridgeEpollController(std::move(epoll_fd)));
+}
+
+FuseBridgeLoop::~FuseBridgeLoop() { CHECK(bridges_.empty()); }
+
+bool FuseBridgeLoop::AddBridge(int mount_id, base::unique_fd dev_fd, base::unique_fd proxy_fd) {
+    LOG(VERBOSE) << "Adding bridge " << mount_id;
+
+    std::unique_ptr<FuseBridgeEntry> bridge(
+        new FuseBridgeEntry(mount_id, std::move(dev_fd), std::move(proxy_fd)));
+    std::lock_guard<std::mutex> lock(mutex_);
+    if (!opened_) {
+        LOG(ERROR) << "Tried to add a mount to a closed bridge";
+        return false;
+    }
+    if (bridges_.count(mount_id)) {
+        LOG(ERROR) << "Tried to add a mount point that has already been added";
+        return false;
+    }
+    if (!epoll_controller_->AddBridgePoll(bridge.get())) {
+        return false;
+    }
+
+    bridges_.emplace(mount_id, std::move(bridge));
+    return true;
+}
+
+bool FuseBridgeLoop::ProcessEventLocked(const std::unordered_set<FuseBridgeEntry*>& entries,
+                                        FuseBridgeLoopCallback* callback) {
+    for (auto entry : entries) {
+        entry->Transfer(callback);
+        if (!epoll_controller_->UpdateOrDeleteBridgePoll(entry)) {
+            return false;
+        }
+        if (entry->IsClosing()) {
+            const int mount_id = entry->mount_id();
+            callback->OnClosed(mount_id);
+            bridges_.erase(mount_id);
+            if (bridges_.size() == 0) {
+                // All bridges are now closed.
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+void FuseBridgeLoop::Start(FuseBridgeLoopCallback* callback) {
+    LOG(DEBUG) << "Start fuse bridge loop";
+    std::unordered_set<FuseBridgeEntry*> entries;
+    while (true) {
+        const bool wait_result = epoll_controller_->Wait(bridges_.size(), &entries);
+        LOG(VERBOSE) << "Receive epoll events";
+        {
+            std::lock_guard<std::mutex> lock(mutex_);
+            if (!(wait_result && ProcessEventLocked(entries, callback))) {
+                for (auto it = bridges_.begin(); it != bridges_.end();) {
+                    callback->OnClosed(it->second->mount_id());
+                    it = bridges_.erase(it);
+                }
+                opened_ = false;
+                return;
+            }
+        }
+    }
+}
+
+}  // namespace fuse
+}  // namespace android
diff --git a/libappfuse/FuseBuffer.cc b/libappfuse/FuseBuffer.cc
new file mode 100644
index 0000000..653e96b
--- /dev/null
+++ b/libappfuse/FuseBuffer.cc
@@ -0,0 +1,262 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBuffer.h"
+
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <type_traits>
+
+#include <sys/socket.h>
+#include <sys/uio.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+
+namespace android {
+namespace fuse {
+namespace {
+
+constexpr useconds_t kRetrySleepForWriting = 1000;  // 1 ms
+
+template <typename T>
+bool CheckHeaderLength(const FuseMessage<T>* self, const char* name, size_t max_size) {
+    const auto& header = static_cast<const T*>(self)->header;
+    if (header.len >= sizeof(header) && header.len <= max_size) {
+        return true;
+    } else {
+        LOG(ERROR) << "Invalid header length is found in " << name << ": " << header.len;
+        return false;
+    }
+}
+
+template <typename T>
+ResultOrAgain ReadInternal(FuseMessage<T>* self, int fd, int sockflag) {
+    char* const buf = reinterpret_cast<char*>(self);
+    const ssize_t result = sockflag ? TEMP_FAILURE_RETRY(recv(fd, buf, sizeof(T), sockflag))
+                                    : TEMP_FAILURE_RETRY(read(fd, buf, sizeof(T)));
+
+    switch (result) {
+        case 0:
+            // Expected EOF.
+            return ResultOrAgain::kFailure;
+        case -1:
+            if (errno == EAGAIN) {
+                return ResultOrAgain::kAgain;
+            }
+            PLOG(ERROR) << "Failed to read a FUSE message";
+            return ResultOrAgain::kFailure;
+    }
+
+    const auto& header = static_cast<const T*>(self)->header;
+    if (result < static_cast<ssize_t>(sizeof(header))) {
+        LOG(ERROR) << "Read bytes " << result << " are shorter than header size " << sizeof(header);
+        return ResultOrAgain::kFailure;
+    }
+
+    if (!CheckHeaderLength<T>(self, "Read", sizeof(T))) {
+        return ResultOrAgain::kFailure;
+    }
+
+    if (static_cast<uint32_t>(result) != header.len) {
+        LOG(ERROR) << "Read bytes " << result << " are different from header.len " << header.len;
+        return ResultOrAgain::kFailure;
+    }
+
+    return ResultOrAgain::kSuccess;
+}
+
+template <typename T>
+ResultOrAgain WriteInternal(const FuseMessage<T>* self, int fd, int sockflag, const void* data,
+                            size_t max_size) {
+    if (!CheckHeaderLength<T>(self, "Write", max_size)) {
+        return ResultOrAgain::kFailure;
+    }
+
+    const char* const buf = reinterpret_cast<const char*>(self);
+    const auto& header = static_cast<const T*>(self)->header;
+
+    while (true) {
+        int result;
+        if (sockflag) {
+            CHECK(data == nullptr);
+            result = TEMP_FAILURE_RETRY(send(fd, buf, header.len, sockflag));
+        } else if (data) {
+            const struct iovec vec[] = {{const_cast<char*>(buf), sizeof(header)},
+                                        {const_cast<void*>(data), header.len - sizeof(header)}};
+            result = TEMP_FAILURE_RETRY(writev(fd, vec, arraysize(vec)));
+        } else {
+            result = TEMP_FAILURE_RETRY(write(fd, buf, header.len));
+        }
+        if (result == -1) {
+            switch (errno) {
+                case ENOBUFS:
+                    // When returning ENOBUFS, epoll still reports the FD is writable. Just usleep
+                    // and retry again.
+                    usleep(kRetrySleepForWriting);
+                    continue;
+                case EAGAIN:
+                    return ResultOrAgain::kAgain;
+                default:
+                    PLOG(ERROR) << "Failed to write a FUSE message";
+                    return ResultOrAgain::kFailure;
+            }
+        }
+
+        if (static_cast<unsigned int>(result) != header.len) {
+            LOG(ERROR) << "Written bytes " << result << " is different from length in header "
+                       << header.len;
+            return ResultOrAgain::kFailure;
+        }
+        return ResultOrAgain::kSuccess;
+    }
+}
+}
+
+static_assert(std::is_standard_layout<FuseBuffer>::value,
+              "FuseBuffer must be standard layout union.");
+
+bool SetupMessageSockets(base::unique_fd (*result)[2]) {
+    base::unique_fd fds[2];
+    {
+        int raw_fds[2];
+        if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_fds) == -1) {
+            PLOG(ERROR) << "Failed to create sockets for proxy";
+            return false;
+        }
+        fds[0].reset(raw_fds[0]);
+        fds[1].reset(raw_fds[1]);
+    }
+
+    constexpr int kMaxMessageSize = sizeof(FuseBuffer);
+    if (setsockopt(fds[0], SOL_SOCKET, SO_SNDBUFFORCE, &kMaxMessageSize, sizeof(int)) != 0 ||
+        setsockopt(fds[1], SOL_SOCKET, SO_SNDBUFFORCE, &kMaxMessageSize, sizeof(int)) != 0) {
+        PLOG(ERROR) << "Failed to update buffer size for socket";
+        return false;
+    }
+
+    (*result)[0] = std::move(fds[0]);
+    (*result)[1] = std::move(fds[1]);
+    return true;
+}
+
+template <typename T>
+bool FuseMessage<T>::Read(int fd) {
+    return ReadInternal(this, fd, 0) == ResultOrAgain::kSuccess;
+}
+
+template <typename T>
+ResultOrAgain FuseMessage<T>::ReadOrAgain(int fd) {
+    return ReadInternal(this, fd, MSG_DONTWAIT);
+}
+
+template <typename T>
+bool FuseMessage<T>::Write(int fd) const {
+    return WriteInternal(this, fd, 0, nullptr, sizeof(T)) == ResultOrAgain::kSuccess;
+}
+
+template <typename T>
+bool FuseMessage<T>::WriteWithBody(int fd, size_t max_size, const void* data) const {
+    CHECK(data != nullptr);
+    return WriteInternal(this, fd, 0, data, max_size) == ResultOrAgain::kSuccess;
+}
+
+template <typename T>
+ResultOrAgain FuseMessage<T>::WriteOrAgain(int fd) const {
+    return WriteInternal(this, fd, MSG_DONTWAIT, nullptr, sizeof(T));
+}
+
+void FuseRequest::Reset(
+    uint32_t data_length, uint32_t opcode, uint64_t unique) {
+  memset(this, 0, sizeof(fuse_in_header) + data_length);
+  header.len = sizeof(fuse_in_header) + data_length;
+  header.opcode = opcode;
+  header.unique = unique;
+}
+
+template <size_t N>
+void FuseResponseBase<N>::ResetHeader(uint32_t data_length, int32_t error, uint64_t unique) {
+    CHECK_LE(error, 0) << "error should be zero or negative.";
+    header.len = sizeof(fuse_out_header) + data_length;
+    header.error = error;
+    header.unique = unique;
+}
+
+template <size_t N>
+void FuseResponseBase<N>::Reset(uint32_t data_length, int32_t error, uint64_t unique) {
+    memset(this, 0, sizeof(fuse_out_header) + data_length);
+    ResetHeader(data_length, error, unique);
+}
+
+void FuseBuffer::HandleInit() {
+  const fuse_init_in* const in = &request.init_in;
+
+  // Before writing |out|, we need to copy data from |in|.
+  const uint64_t unique = request.header.unique;
+  const uint32_t minor = in->minor;
+  const uint32_t max_readahead = in->max_readahead;
+
+  // Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
+  // defined (fuse version 7.6). The structure is the same from 7.6 through
+  // 7.22. Beginning with 7.23, the structure increased in size and added
+  // new parameters.
+  if (in->major != FUSE_KERNEL_VERSION || in->minor < 6) {
+    LOG(ERROR) << "Fuse kernel version mismatch: Kernel version " << in->major
+        << "." << in->minor << " Expected at least " << FUSE_KERNEL_VERSION
+        << ".6";
+    response.Reset(0, -EPERM, unique);
+    return;
+  }
+
+  // We limit ourselves to minor=15 because we don't handle BATCH_FORGET yet.
+  // Thus we need to use FUSE_COMPAT_22_INIT_OUT_SIZE.
+#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
+  // FUSE_KERNEL_VERSION >= 23.
+  const size_t response_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
+#else
+  const size_t response_size = sizeof(fuse_init_out);
+#endif
+
+  response.Reset(response_size, kFuseSuccess, unique);
+  fuse_init_out* const out = &response.init_out;
+  out->major = FUSE_KERNEL_VERSION;
+  out->minor = std::min(minor, 15u);
+  out->max_readahead = max_readahead;
+  out->flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
+  out->max_background = 32;
+  out->congestion_threshold = 32;
+  out->max_write = kFuseMaxWrite;
+}
+
+void FuseBuffer::HandleNotImpl() {
+  LOG(VERBOSE) << "NOTIMPL op=" << request.header.opcode << " uniq="
+      << request.header.unique << " nid=" << request.header.nodeid;
+  const uint64_t unique = request.header.unique;
+  response.Reset(0, -ENOSYS, unique);
+}
+
+template class FuseMessage<FuseRequest>;
+template class FuseMessage<FuseResponse>;
+template class FuseMessage<FuseSimpleResponse>;
+template struct FuseResponseBase<0u>;
+template struct FuseResponseBase<kFuseMaxRead>;
+
+}  // namespace fuse
+}  // namespace android
diff --git a/libappfuse/include/libappfuse/EpollController.h b/libappfuse/include/libappfuse/EpollController.h
new file mode 100644
index 0000000..622bd2c
--- /dev/null
+++ b/libappfuse/include/libappfuse/EpollController.h
@@ -0,0 +1,52 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_EPOLLCONTROLLER_H_
+#define ANDROID_LIBAPPFUSE_EPOLLCONTROLLER_H_
+
+#include <sys/epoll.h>
+
+#include <vector>
+
+#include <android-base/macros.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+namespace fuse {
+
+class EpollController {
+  public:
+    explicit EpollController(base::unique_fd&& poll_fd);
+    bool Wait(size_t event_count);
+    bool AddFd(int fd, int events, void* data);
+    bool UpdateFd(int fd, int events, void* data);
+    bool RemoveFd(int fd);
+
+    const std::vector<epoll_event>& events() const;
+
+  protected:
+    bool InvokeControl(int op, int fd, int events, void* data) const;
+
+  private:
+    base::unique_fd poll_fd_;
+    std::vector<epoll_event> events_;
+
+    DISALLOW_COPY_AND_ASSIGN(EpollController);
+};
+}
+}
+
+#endif  // ANDROID_LIBAPPFUSE_EPOLLCONTROLLER_H_
diff --git a/libappfuse/include/libappfuse/FuseAppLoop.h b/libappfuse/include/libappfuse/FuseAppLoop.h
new file mode 100644
index 0000000..f2ef2b5
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseAppLoop.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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
+#define ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
+
+#include <memory>
+#include <mutex>
+
+#include <android-base/unique_fd.h>
+
+#include "libappfuse/FuseBuffer.h"
+
+namespace android {
+namespace fuse {
+
+class EpollController;
+
+class FuseAppLoopCallback {
+ public:
+   virtual void OnLookup(uint64_t unique, uint64_t inode) = 0;
+   virtual void OnGetAttr(uint64_t unique, uint64_t inode) = 0;
+   virtual void OnFsync(uint64_t unique, uint64_t inode) = 0;
+   virtual void OnWrite(uint64_t unique, uint64_t inode, uint64_t offset, uint32_t size,
+                        const void* data) = 0;
+   virtual void OnRead(uint64_t unique, uint64_t inode, uint64_t offset, uint32_t size) = 0;
+   virtual void OnOpen(uint64_t unique, uint64_t inode) = 0;
+   virtual void OnRelease(uint64_t unique, uint64_t inode) = 0;
+   virtual ~FuseAppLoopCallback();
+};
+
+class FuseAppLoop final {
+  public:
+    FuseAppLoop(base::unique_fd&& fd);
+
+    void Start(FuseAppLoopCallback* callback);
+    void Break();
+
+    bool ReplySimple(uint64_t unique, int32_t result);
+    bool ReplyLookup(uint64_t unique, uint64_t inode, int64_t size);
+    bool ReplyGetAttr(uint64_t unique, uint64_t inode, int64_t size, int mode);
+    bool ReplyOpen(uint64_t unique, uint64_t fh);
+    bool ReplyWrite(uint64_t unique, uint32_t size);
+    bool ReplyRead(uint64_t unique, uint32_t size, const void* data);
+
+  private:
+    base::unique_fd fd_;
+    base::unique_fd break_fd_;
+
+    // Lock for multi-threading.
+    std::mutex mutex_;
+};
+
+bool StartFuseAppLoop(int fd, FuseAppLoopCallback* callback);
+
+}  // namespace fuse
+}  // namespace android
+
+#endif  // ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
diff --git a/libappfuse/include/libappfuse/FuseBridgeLoop.h b/libappfuse/include/libappfuse/FuseBridgeLoop.h
new file mode 100644
index 0000000..6bfda98
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseBridgeLoop.h
@@ -0,0 +1,73 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
+#define ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
+
+#include <map>
+#include <mutex>
+#include <queue>
+#include <unordered_set>
+
+#include <android-base/macros.h>
+
+#include "libappfuse/FuseBuffer.h"
+
+namespace android {
+namespace fuse {
+
+class FuseBridgeLoopCallback {
+ public:
+   virtual void OnMount(int mount_id) = 0;
+   virtual void OnClosed(int mount_id) = 0;
+   virtual ~FuseBridgeLoopCallback() = default;
+};
+
+class FuseBridgeEntry;
+class BridgeEpollController;
+
+class FuseBridgeLoop final {
+  public:
+    FuseBridgeLoop();
+    ~FuseBridgeLoop();
+
+    void Start(FuseBridgeLoopCallback* callback);
+
+    // Add bridge to the loop. It's OK to invoke the method from a different
+    // thread from one which invokes |Start|.
+    bool AddBridge(int mount_id, base::unique_fd dev_fd, base::unique_fd proxy_fd);
+
+  private:
+    bool ProcessEventLocked(const std::unordered_set<FuseBridgeEntry*>& entries,
+                            FuseBridgeLoopCallback* callback);
+
+    std::unique_ptr<BridgeEpollController> epoll_controller_;
+
+    // Map between |mount_id| and bridge entry.
+    std::map<int, std::unique_ptr<FuseBridgeEntry>> bridges_;
+
+    // Lock for multi-threading.
+    std::mutex mutex_;
+
+    bool opened_;
+
+    DISALLOW_COPY_AND_ASSIGN(FuseBridgeLoop);
+};
+
+}  // namespace fuse
+}  // namespace android
+
+#endif  // ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
diff --git a/libappfuse/include/libappfuse/FuseBuffer.h b/libappfuse/include/libappfuse/FuseBuffer.h
new file mode 100644
index 0000000..7a70bf3
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseBuffer.h
@@ -0,0 +1,112 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
+#define ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
+
+#include <android-base/unique_fd.h>
+#include <linux/fuse.h>
+
+namespace android {
+namespace fuse {
+
+// The numbers came from sdcard.c.
+// Maximum number of bytes to write/read in one request/one reply.
+constexpr size_t kFuseMaxWrite = 256 * 1024;
+constexpr size_t kFuseMaxRead = 128 * 1024;
+constexpr int32_t kFuseSuccess = 0;
+
+// Setup sockets to transfer FuseMessage.
+bool SetupMessageSockets(base::unique_fd (*sockets)[2]);
+
+enum class ResultOrAgain {
+    kSuccess,
+    kFailure,
+    kAgain,
+};
+
+template<typename T>
+class FuseMessage {
+ public:
+  bool Read(int fd);
+  bool Write(int fd) const;
+  bool WriteWithBody(int fd, size_t max_size, const void* data) const;
+  ResultOrAgain ReadOrAgain(int fd);
+  ResultOrAgain WriteOrAgain(int fd) const;
+};
+
+// FuseRequest represents file operation requests from /dev/fuse. It starts
+// from fuse_in_header. The body layout depends on the operation code.
+struct FuseRequest : public FuseMessage<FuseRequest> {
+  fuse_in_header header;
+  union {
+    // for FUSE_WRITE
+    struct {
+      fuse_write_in write_in;
+      char write_data[kFuseMaxWrite];
+    };
+    // for FUSE_OPEN
+    fuse_open_in open_in;
+    // for FUSE_INIT
+    fuse_init_in init_in;
+    // for FUSE_READ
+    fuse_read_in read_in;
+    // for FUSE_LOOKUP
+    char lookup_name[kFuseMaxWrite];
+  };
+  void Reset(uint32_t data_length, uint32_t opcode, uint64_t unique);
+};
+
+// FuseResponse represents file operation responses to /dev/fuse. It starts
+// from fuse_out_header. The body layout depends on the operation code.
+template <size_t N>
+struct FuseResponseBase : public FuseMessage<FuseResponseBase<N>> {
+    fuse_out_header header;
+    union {
+        // for FUSE_INIT
+        fuse_init_out init_out;
+        // for FUSE_LOOKUP
+        fuse_entry_out entry_out;
+        // for FUSE_GETATTR
+        fuse_attr_out attr_out;
+        // for FUSE_OPEN
+        fuse_open_out open_out;
+        // for FUSE_READ
+        char read_data[N];
+        // for FUSE_WRITE
+        fuse_write_out write_out;
+    };
+    void Reset(uint32_t data_length, int32_t error, uint64_t unique);
+    void ResetHeader(uint32_t data_length, int32_t error, uint64_t unique);
+};
+
+using FuseResponse = FuseResponseBase<kFuseMaxRead>;
+using FuseSimpleResponse = FuseResponseBase<0u>;
+
+// To reduce memory usage, FuseBuffer shares the memory region for request and
+// response.
+union FuseBuffer final {
+  FuseRequest request;
+  FuseResponse response;
+
+  void HandleInit();
+  void HandleNotImpl();
+};
+
+}  // namespace fuse
+}  // namespace android
+
+#endif  // ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
diff --git a/libappfuse/tests/FuseAppLoopTest.cc b/libappfuse/tests/FuseAppLoopTest.cc
new file mode 100644
index 0000000..98e3665
--- /dev/null
+++ b/libappfuse/tests/FuseAppLoopTest.cc
@@ -0,0 +1,299 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseAppLoop.h"
+
+#include <sys/socket.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+#include <thread>
+
+#include "libappfuse/EpollController.h"
+#include "libappfuse/FuseBridgeLoop.h"
+
+namespace android {
+namespace fuse {
+namespace {
+
+constexpr unsigned int kTestFileSize = 1024;
+
+struct CallbackRequest {
+  uint32_t code;
+  uint64_t inode;
+};
+
+class Callback : public FuseAppLoopCallback {
+ public:
+  std::vector<CallbackRequest> requests;
+  FuseAppLoop* loop;
+
+  void OnGetAttr(uint64_t seq, uint64_t inode) override {
+      EXPECT_NE(FUSE_ROOT_ID, static_cast<int>(inode));
+      EXPECT_TRUE(loop->ReplyGetAttr(seq, inode, kTestFileSize, S_IFREG | 0777));
+  }
+
+  void OnLookup(uint64_t unique, uint64_t inode) override {
+      EXPECT_NE(FUSE_ROOT_ID, static_cast<int>(inode));
+      EXPECT_TRUE(loop->ReplyLookup(unique, inode, kTestFileSize));
+  }
+
+  void OnFsync(uint64_t seq, uint64_t inode) override {
+      requests.push_back({.code = FUSE_FSYNC, .inode = inode});
+      loop->ReplySimple(seq, 0);
+  }
+
+  void OnWrite(uint64_t seq, uint64_t inode, uint64_t offset ATTRIBUTE_UNUSED,
+               uint32_t size ATTRIBUTE_UNUSED, const void* data ATTRIBUTE_UNUSED) override {
+      requests.push_back({.code = FUSE_WRITE, .inode = inode});
+      loop->ReplyWrite(seq, 0);
+  }
+
+  void OnRead(uint64_t seq, uint64_t inode, uint64_t offset ATTRIBUTE_UNUSED,
+              uint32_t size ATTRIBUTE_UNUSED) override {
+      requests.push_back({.code = FUSE_READ, .inode = inode});
+      loop->ReplySimple(seq, 0);
+  }
+
+  void OnOpen(uint64_t seq, uint64_t inode) override {
+      requests.push_back({.code = FUSE_OPEN, .inode = inode});
+      loop->ReplyOpen(seq, inode);
+  }
+
+  void OnRelease(uint64_t seq, uint64_t inode) override {
+      requests.push_back({.code = FUSE_RELEASE, .inode = inode});
+      loop->ReplySimple(seq, 0);
+  }
+};
+
+class FuseAppLoopTest : public ::testing::Test {
+ protected:
+   std::thread thread_;
+   base::unique_fd sockets_[2];
+   Callback callback_;
+   FuseRequest request_;
+   FuseResponse response_;
+   std::unique_ptr<FuseAppLoop> loop_;
+
+   void SetUp() override {
+       base::SetMinimumLogSeverity(base::VERBOSE);
+       ASSERT_TRUE(SetupMessageSockets(&sockets_));
+       loop_.reset(new FuseAppLoop(std::move(sockets_[1])));
+       callback_.loop = loop_.get();
+       thread_ = std::thread([this] { loop_->Start(&callback_); });
+  }
+
+  void CheckCallback(
+      size_t data_size, uint32_t code, size_t expected_out_size) {
+    request_.Reset(data_size, code, 1);
+    request_.header.nodeid = 10;
+
+    ASSERT_TRUE(request_.Write(sockets_[0]));
+    ASSERT_TRUE(response_.Read(sockets_[0]));
+
+    Close();
+
+    EXPECT_EQ(kFuseSuccess, response_.header.error);
+    EXPECT_EQ(sizeof(fuse_out_header) + expected_out_size,
+              response_.header.len);
+    EXPECT_EQ(1u, response_.header.unique);
+
+    ASSERT_EQ(1u, callback_.requests.size());
+    EXPECT_EQ(code, callback_.requests[0].code);
+    EXPECT_EQ(10u, callback_.requests[0].inode);
+  }
+
+  void Close() {
+    sockets_[0].reset();
+    sockets_[1].reset();
+    if (thread_.joinable()) {
+      thread_.join();
+    }
+  }
+
+  void TearDown() override {
+    Close();
+  }
+};
+
+}  // namespace
+
+TEST_F(FuseAppLoopTest, LookUp) {
+  request_.Reset(3u, FUSE_LOOKUP, 1);
+  request_.header.nodeid = FUSE_ROOT_ID;
+  strcpy(request_.lookup_name, "10");
+
+  ASSERT_TRUE(request_.Write(sockets_[0].get()));
+  ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+  EXPECT_EQ(kFuseSuccess, response_.header.error);
+  EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_entry_out),
+            response_.header.len);
+  EXPECT_EQ(1u, response_.header.unique);
+
+  EXPECT_EQ(10u, response_.entry_out.nodeid);
+  EXPECT_EQ(0u, response_.entry_out.generation);
+  EXPECT_EQ(10u, response_.entry_out.entry_valid);
+  EXPECT_EQ(10u, response_.entry_out.attr_valid);
+  EXPECT_EQ(0u, response_.entry_out.entry_valid_nsec);
+  EXPECT_EQ(0u, response_.entry_out.attr_valid_nsec);
+
+  EXPECT_EQ(10u, response_.entry_out.attr.ino);
+  EXPECT_EQ(kTestFileSize, response_.entry_out.attr.size);
+  EXPECT_EQ(0u, response_.entry_out.attr.blocks);
+  EXPECT_EQ(0u, response_.entry_out.attr.atime);
+  EXPECT_EQ(0u, response_.entry_out.attr.mtime);
+  EXPECT_EQ(0u, response_.entry_out.attr.ctime);
+  EXPECT_EQ(0u, response_.entry_out.attr.atimensec);
+  EXPECT_EQ(0u, response_.entry_out.attr.mtimensec);
+  EXPECT_EQ(0u, response_.entry_out.attr.ctimensec);
+  EXPECT_EQ(S_IFREG | 0777u, response_.entry_out.attr.mode);
+  EXPECT_EQ(0u, response_.entry_out.attr.nlink);
+  EXPECT_EQ(0u, response_.entry_out.attr.uid);
+  EXPECT_EQ(0u, response_.entry_out.attr.gid);
+  EXPECT_EQ(0u, response_.entry_out.attr.rdev);
+  EXPECT_EQ(0u, response_.entry_out.attr.blksize);
+  EXPECT_EQ(0u, response_.entry_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, LookUp_InvalidName) {
+  request_.Reset(3u, FUSE_LOOKUP, 1);
+  request_.header.nodeid = FUSE_ROOT_ID;
+  strcpy(request_.lookup_name, "aa");
+
+  ASSERT_TRUE(request_.Write(sockets_[0].get()));
+  ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+  EXPECT_EQ(sizeof(fuse_out_header), response_.header.len);
+  EXPECT_EQ(-ENOENT, response_.header.error);
+  EXPECT_EQ(1u, response_.header.unique);
+}
+
+TEST_F(FuseAppLoopTest, LookUp_TooLargeName) {
+  request_.Reset(21u, FUSE_LOOKUP, 1);
+  request_.header.nodeid = FUSE_ROOT_ID;
+  strcpy(request_.lookup_name, "18446744073709551616");
+
+  ASSERT_TRUE(request_.Write(sockets_[0].get()));
+  ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+  EXPECT_EQ(sizeof(fuse_out_header), response_.header.len);
+  EXPECT_EQ(-ENOENT, response_.header.error);
+  EXPECT_EQ(1u, response_.header.unique);
+}
+
+TEST_F(FuseAppLoopTest, GetAttr) {
+  request_.Reset(sizeof(fuse_getattr_in), FUSE_GETATTR, 1);
+  request_.header.nodeid = 10;
+
+  ASSERT_TRUE(request_.Write(sockets_[0].get()));
+  ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+  EXPECT_EQ(kFuseSuccess, response_.header.error);
+  EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_attr_out),
+            response_.header.len);
+  EXPECT_EQ(1u, response_.header.unique);
+
+  EXPECT_EQ(10u, response_.attr_out.attr_valid);
+  EXPECT_EQ(0u, response_.attr_out.attr_valid_nsec);
+
+  EXPECT_EQ(10u, response_.attr_out.attr.ino);
+  EXPECT_EQ(kTestFileSize, response_.attr_out.attr.size);
+  EXPECT_EQ(0u, response_.attr_out.attr.blocks);
+  EXPECT_EQ(0u, response_.attr_out.attr.atime);
+  EXPECT_EQ(0u, response_.attr_out.attr.mtime);
+  EXPECT_EQ(0u, response_.attr_out.attr.ctime);
+  EXPECT_EQ(0u, response_.attr_out.attr.atimensec);
+  EXPECT_EQ(0u, response_.attr_out.attr.mtimensec);
+  EXPECT_EQ(0u, response_.attr_out.attr.ctimensec);
+  EXPECT_EQ(S_IFREG | 0777u, response_.attr_out.attr.mode);
+  EXPECT_EQ(0u, response_.attr_out.attr.nlink);
+  EXPECT_EQ(0u, response_.attr_out.attr.uid);
+  EXPECT_EQ(0u, response_.attr_out.attr.gid);
+  EXPECT_EQ(0u, response_.attr_out.attr.rdev);
+  EXPECT_EQ(0u, response_.attr_out.attr.blksize);
+  EXPECT_EQ(0u, response_.attr_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, GetAttr_Root) {
+  request_.Reset(sizeof(fuse_getattr_in), FUSE_GETATTR, 1);
+  request_.header.nodeid = FUSE_ROOT_ID;
+
+  ASSERT_TRUE(request_.Write(sockets_[0].get()));
+  ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+  EXPECT_EQ(kFuseSuccess, response_.header.error);
+  EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_attr_out),
+            response_.header.len);
+  EXPECT_EQ(1u, response_.header.unique);
+
+  EXPECT_EQ(10u, response_.attr_out.attr_valid);
+  EXPECT_EQ(0u, response_.attr_out.attr_valid_nsec);
+
+  EXPECT_EQ(static_cast<unsigned>(FUSE_ROOT_ID), response_.attr_out.attr.ino);
+  EXPECT_EQ(0u, response_.attr_out.attr.size);
+  EXPECT_EQ(0u, response_.attr_out.attr.blocks);
+  EXPECT_EQ(0u, response_.attr_out.attr.atime);
+  EXPECT_EQ(0u, response_.attr_out.attr.mtime);
+  EXPECT_EQ(0u, response_.attr_out.attr.ctime);
+  EXPECT_EQ(0u, response_.attr_out.attr.atimensec);
+  EXPECT_EQ(0u, response_.attr_out.attr.mtimensec);
+  EXPECT_EQ(0u, response_.attr_out.attr.ctimensec);
+  EXPECT_EQ(S_IFDIR | 0777u, response_.attr_out.attr.mode);
+  EXPECT_EQ(0u, response_.attr_out.attr.nlink);
+  EXPECT_EQ(0u, response_.attr_out.attr.uid);
+  EXPECT_EQ(0u, response_.attr_out.attr.gid);
+  EXPECT_EQ(0u, response_.attr_out.attr.rdev);
+  EXPECT_EQ(0u, response_.attr_out.attr.blksize);
+  EXPECT_EQ(0u, response_.attr_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, Open) {
+  CheckCallback(sizeof(fuse_open_in), FUSE_OPEN, sizeof(fuse_open_out));
+}
+
+TEST_F(FuseAppLoopTest, Fsync) {
+  CheckCallback(0u, FUSE_FSYNC, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Release) {
+  CheckCallback(0u, FUSE_RELEASE, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Read) {
+  CheckCallback(sizeof(fuse_read_in), FUSE_READ, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Write) {
+  CheckCallback(sizeof(fuse_write_in), FUSE_WRITE, sizeof(fuse_write_out));
+}
+
+TEST_F(FuseAppLoopTest, Break) {
+    // Ensure that the loop started.
+    request_.Reset(sizeof(fuse_open_in), FUSE_OPEN, 1);
+    request_.header.nodeid = 10;
+    ASSERT_TRUE(request_.Write(sockets_[0]));
+    ASSERT_TRUE(response_.Read(sockets_[0]));
+
+    loop_->Break();
+    if (thread_.joinable()) {
+        thread_.join();
+    }
+}
+
+}  // namespace fuse
+}  // namespace android
diff --git a/libappfuse/tests/FuseBridgeLoopTest.cc b/libappfuse/tests/FuseBridgeLoopTest.cc
new file mode 100644
index 0000000..51d6051
--- /dev/null
+++ b/libappfuse/tests/FuseBridgeLoopTest.cc
@@ -0,0 +1,213 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBridgeLoop.h"
+
+#include <sys/socket.h>
+
+#include <sstream>
+#include <thread>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+
+namespace android {
+namespace fuse {
+namespace {
+
+class Callback : public FuseBridgeLoopCallback {
+ public:
+  bool mounted;
+  bool closed;
+  Callback() : mounted(false), closed(false) {}
+
+  void OnMount(int /*mount_id*/) override { mounted = true; }
+
+  void OnClosed(int /* mount_id */) override { closed = true; }
+};
+
+class FuseBridgeLoopTest : public ::testing::Test {
+ protected:
+  base::unique_fd dev_sockets_[2];
+  base::unique_fd proxy_sockets_[2];
+  Callback callback_;
+  std::thread thread_;
+
+  FuseRequest request_;
+  FuseResponse response_;
+
+  void SetUp() override {
+    base::SetMinimumLogSeverity(base::VERBOSE);
+    ASSERT_TRUE(SetupMessageSockets(&dev_sockets_));
+    ASSERT_TRUE(SetupMessageSockets(&proxy_sockets_));
+    thread_ = std::thread([this] {
+        FuseBridgeLoop loop;
+        loop.AddBridge(1, std::move(dev_sockets_[1]), std::move(proxy_sockets_[0]));
+        loop.Start(&callback_);
+    });
+  }
+
+  void CheckNotImpl(uint32_t opcode) {
+    SCOPED_TRACE((std::ostringstream() << "opcode: " << opcode).str());
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = opcode;
+    request_.header.len = sizeof(fuse_in_header);
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+    EXPECT_EQ(-ENOSYS, response_.header.error);
+  }
+
+  void CheckProxy(uint32_t opcode) {
+    SCOPED_TRACE((std::ostringstream() << "opcode: " << opcode).str());
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = opcode;
+    request_.header.unique = opcode; // Use opcode as unique.
+    request_.header.len = sizeof(fuse_in_header);
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+    memset(&request_, 0, sizeof(FuseRequest));
+    ASSERT_TRUE(request_.Read(proxy_sockets_[1]));
+    EXPECT_EQ(opcode, request_.header.opcode);
+    EXPECT_EQ(opcode, request_.header.unique);
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    response_.header.len = sizeof(fuse_out_header);
+    response_.header.unique = opcode;  // Use opcode as unique.
+    response_.header.error = kFuseSuccess;
+    ASSERT_TRUE(response_.Write(proxy_sockets_[1]));
+
+    memset(&response_, 0, sizeof(FuseResponse));
+    ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+    EXPECT_EQ(opcode, response_.header.unique);
+    EXPECT_EQ(kFuseSuccess, response_.header.error);
+  }
+
+  void SendInitRequest(uint64_t unique) {
+    memset(&request_, 0, sizeof(FuseRequest));
+    request_.header.opcode = FUSE_INIT;
+    request_.header.unique = unique;
+    request_.header.len = sizeof(fuse_in_header) + sizeof(fuse_init_in);
+    request_.init_in.major = FUSE_KERNEL_VERSION;
+    request_.init_in.minor = FUSE_KERNEL_MINOR_VERSION;
+    ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+  }
+
+  void Close() {
+    dev_sockets_[0].reset();
+    dev_sockets_[1].reset();
+    proxy_sockets_[0].reset();
+    proxy_sockets_[1].reset();
+    if (thread_.joinable()) {
+      thread_.join();
+    }
+    ASSERT_TRUE(callback_.closed);
+  }
+
+  void TearDown() override {
+    Close();
+  }
+};
+
+} //  namespace
+
+TEST_F(FuseBridgeLoopTest, FuseInit) {
+  SendInitRequest(1u);
+
+  memset(&response_, 0, sizeof(FuseResponse));
+  ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+  EXPECT_EQ(kFuseSuccess, response_.header.error);
+  EXPECT_EQ(1u, response_.header.unique);
+
+  // Unmount.
+  Close();
+  EXPECT_TRUE(callback_.mounted);
+}
+
+TEST_F(FuseBridgeLoopTest, FuseForget) {
+  memset(&request_, 0, sizeof(FuseRequest));
+  request_.header.opcode = FUSE_FORGET;
+  request_.header.unique = 1u;
+  request_.header.len = sizeof(fuse_in_header) + sizeof(fuse_forget_in);
+  ASSERT_TRUE(request_.Write(dev_sockets_[0]));
+
+  SendInitRequest(2u);
+
+  memset(&response_, 0, sizeof(FuseResponse));
+  ASSERT_TRUE(response_.Read(dev_sockets_[0]));
+  EXPECT_EQ(2u, response_.header.unique) <<
+      "The loop must not respond to FUSE_FORGET";
+}
+
+TEST_F(FuseBridgeLoopTest, FuseNotImpl) {
+  CheckNotImpl(FUSE_SETATTR);
+  CheckNotImpl(FUSE_READLINK);
+  CheckNotImpl(FUSE_SYMLINK);
+  CheckNotImpl(FUSE_MKNOD);
+  CheckNotImpl(FUSE_MKDIR);
+  CheckNotImpl(FUSE_UNLINK);
+  CheckNotImpl(FUSE_RMDIR);
+  CheckNotImpl(FUSE_RENAME);
+  CheckNotImpl(FUSE_LINK);
+  CheckNotImpl(FUSE_STATFS);
+  CheckNotImpl(FUSE_SETXATTR);
+  CheckNotImpl(FUSE_GETXATTR);
+  CheckNotImpl(FUSE_LISTXATTR);
+  CheckNotImpl(FUSE_REMOVEXATTR);
+  CheckNotImpl(FUSE_FLUSH);
+  CheckNotImpl(FUSE_OPENDIR);
+  CheckNotImpl(FUSE_READDIR);
+  CheckNotImpl(FUSE_RELEASEDIR);
+  CheckNotImpl(FUSE_FSYNCDIR);
+  CheckNotImpl(FUSE_GETLK);
+  CheckNotImpl(FUSE_SETLK);
+  CheckNotImpl(FUSE_SETLKW);
+  CheckNotImpl(FUSE_ACCESS);
+  CheckNotImpl(FUSE_CREATE);
+  CheckNotImpl(FUSE_INTERRUPT);
+  CheckNotImpl(FUSE_BMAP);
+  CheckNotImpl(FUSE_DESTROY);
+  CheckNotImpl(FUSE_IOCTL);
+  CheckNotImpl(FUSE_POLL);
+  CheckNotImpl(FUSE_NOTIFY_REPLY);
+  CheckNotImpl(FUSE_BATCH_FORGET);
+  CheckNotImpl(FUSE_FALLOCATE);
+  CheckNotImpl(FUSE_READDIRPLUS);
+  CheckNotImpl(FUSE_RENAME2);
+  CheckNotImpl(FUSE_LSEEK);
+}
+
+TEST_F(FuseBridgeLoopTest, Proxy) {
+  CheckProxy(FUSE_LOOKUP);
+  CheckProxy(FUSE_GETATTR);
+  CheckProxy(FUSE_READ);
+  CheckProxy(FUSE_WRITE);
+  CheckProxy(FUSE_FSYNC);
+
+  // Invoke FUSE_OPEN and FUSE_RELEASE at last as the loop will exit when all files are closed.
+  CheckProxy(FUSE_OPEN);
+  CheckProxy(FUSE_RELEASE);
+
+  // Ensure the loop exits.
+  Close();
+}
+
+}  // namespace fuse
+}  // namespace android
diff --git a/libappfuse/tests/FuseBufferTest.cc b/libappfuse/tests/FuseBufferTest.cc
new file mode 100644
index 0000000..ade34ac
--- /dev/null
+++ b/libappfuse/tests/FuseBufferTest.cc
@@ -0,0 +1,215 @@
+/*
+ * 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 specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseBuffer.h"
+
+#include <fcntl.h>
+#include <string.h>
+#include <sys/socket.h>
+
+#include <thread>
+
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+
+namespace android {
+namespace fuse {
+
+constexpr char kTempFile[] = "/data/local/tmp/appfuse_test_dump";
+
+void OpenTempFile(android::base::unique_fd* fd) {
+  fd->reset(open(kTempFile, O_CREAT | O_RDWR, 0600));
+  ASSERT_NE(-1, *fd) << strerror(errno);
+  unlink(kTempFile);
+  ASSERT_NE(-1, *fd) << strerror(errno);
+}
+
+void TestReadInvalidLength(size_t headerSize, size_t write_size) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  char buffer[std::max(headerSize, sizeof(FuseRequest))];
+  FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer);
+  packet->header.len = headerSize;
+  ASSERT_NE(-1, write(fd, packet, write_size)) << strerror(errno);
+
+  lseek(fd, 0, SEEK_SET);
+  EXPECT_FALSE(packet->Read(fd));
+}
+
+void TestWriteInvalidLength(size_t size) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  char buffer[std::max(size, sizeof(FuseRequest))];
+  FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer);
+  packet->header.len = size;
+  EXPECT_FALSE(packet->Write(fd));
+}
+
+// Use FuseRequest as a template instance of FuseMessage.
+
+TEST(FuseMessageTest, ReadAndWrite) {
+  android::base::unique_fd fd;
+  OpenTempFile(&fd);
+
+  FuseRequest request;
+  request.header.len = sizeof(FuseRequest);
+  request.header.opcode = 1;
+  request.header.unique = 2;
+  request.header.nodeid = 3;
+  request.header.uid = 4;
+  request.header.gid = 5;
+  request.header.pid = 6;
+  strcpy(request.lookup_name, "test");
+
+  ASSERT_TRUE(request.Write(fd));
+
+  memset(&request, 0, sizeof(FuseRequest));
+  lseek(fd, 0, SEEK_SET);
+
+  ASSERT_TRUE(request.Read(fd));
+  EXPECT_EQ(sizeof(FuseRequest), request.header.len);
+  EXPECT_EQ(1u, request.header.opcode);
+  EXPECT_EQ(2u, request.header.unique);
+  EXPECT_EQ(3u, request.header.nodeid);
+  EXPECT_EQ(4u, request.header.uid);
+  EXPECT_EQ(5u, request.header.gid);
+  EXPECT_EQ(6u, request.header.pid);
+  EXPECT_STREQ("test", request.lookup_name);
+}
+
+TEST(FuseMessageTest, Read_InconsistentLength) {
+  TestReadInvalidLength(sizeof(fuse_in_header), sizeof(fuse_in_header) + 1);
+}
+
+TEST(FuseMessageTest, Read_TooLong) {
+  TestReadInvalidLength(sizeof(FuseRequest) + 1, sizeof(FuseRequest) + 1);
+}
+
+TEST(FuseMessageTest, Read_TooShort) {
+  TestReadInvalidLength(sizeof(fuse_in_header) - 1, sizeof(fuse_in_header) - 1);
+}
+
+TEST(FuseMessageTest, Write_TooLong) {
+  TestWriteInvalidLength(sizeof(FuseRequest) + 1);
+}
+
+TEST(FuseMessageTest, Write_TooShort) {
+  TestWriteInvalidLength(sizeof(fuse_in_header) - 1);
+}
+
+TEST(FuseResponseTest, Reset) {
+  FuseResponse response;
+  // Write 1 to the first ten bytes.
+  memset(response.read_data, 'a', 10);
+
+  response.Reset(0, -1, 2);
+  EXPECT_EQ(sizeof(fuse_out_header), response.header.len);
+  EXPECT_EQ(-1, response.header.error);
+  EXPECT_EQ(2u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+
+  response.Reset(5, -4, 3);
+  EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len);
+  EXPECT_EQ(-4, response.header.error);
+  EXPECT_EQ(3u, response.header.unique);
+  EXPECT_EQ(0, response.read_data[0]);
+  EXPECT_EQ(0, response.read_data[1]);
+  EXPECT_EQ(0, response.read_data[2]);
+  EXPECT_EQ(0, response.read_data[3]);
+  EXPECT_EQ(0, response.read_data[4]);
+  EXPECT_EQ('a', response.read_data[5]);
+}
+
+TEST(FuseResponseTest, ResetHeader) {
+  FuseResponse response;
+  // Write 1 to the first ten bytes.
+  memset(response.read_data, 'a', 10);
+
+  response.ResetHeader(0, -1, 2);
+  EXPECT_EQ(sizeof(fuse_out_header), response.header.len);
+  EXPECT_EQ(-1, response.header.error);
+  EXPECT_EQ(2u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+
+  response.ResetHeader(5, -4, 3);
+  EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len);
+  EXPECT_EQ(-4, response.header.error);
+  EXPECT_EQ(3u, response.header.unique);
+  EXPECT_EQ('a', response.read_data[0]);
+  EXPECT_EQ('a', response.read_data[9]);
+}
+
+TEST(FuseBufferTest, HandleInit) {
+  FuseBuffer buffer;
+  memset(&buffer, 0, sizeof(FuseBuffer));
+
+  buffer.request.header.opcode = FUSE_INIT;
+  buffer.request.init_in.major = FUSE_KERNEL_VERSION;
+  buffer.request.init_in.minor = FUSE_KERNEL_MINOR_VERSION;
+
+  buffer.HandleInit();
+
+  ASSERT_EQ(sizeof(fuse_out_header) + FUSE_COMPAT_22_INIT_OUT_SIZE,
+            buffer.response.header.len);
+  EXPECT_EQ(kFuseSuccess, buffer.response.header.error);
+  EXPECT_EQ(static_cast<unsigned int>(FUSE_KERNEL_VERSION),
+            buffer.response.init_out.major);
+  EXPECT_EQ(15u, buffer.response.init_out.minor);
+  EXPECT_EQ(static_cast<unsigned int>(FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES),
+      buffer.response.init_out.flags);
+  EXPECT_EQ(kFuseMaxWrite, buffer.response.init_out.max_write);
+}
+
+TEST(FuseBufferTest, HandleNotImpl) {
+  FuseBuffer buffer;
+  memset(&buffer, 0, sizeof(FuseBuffer));
+
+  buffer.HandleNotImpl();
+
+  ASSERT_EQ(sizeof(fuse_out_header), buffer.response.header.len);
+  EXPECT_EQ(-ENOSYS, buffer.response.header.error);
+}
+
+TEST(SetupMessageSocketsTest, Stress) {
+    constexpr int kCount = 1000;
+
+    FuseRequest request;
+    request.header.len = sizeof(FuseRequest);
+
+    base::unique_fd fds[2];
+    SetupMessageSockets(&fds);
+
+    std::thread thread([&fds] {
+        FuseRequest request;
+        for (int i = 0; i < kCount; ++i) {
+            ASSERT_TRUE(request.Read(fds[1]));
+            usleep(1000);
+        }
+    });
+
+    for (int i = 0; i < kCount; ++i) {
+        ASSERT_TRUE(request.Write(fds[0]));
+    }
+
+    thread.join();
+}
+
+} // namespace fuse
+} // namespace android
diff --git a/libbacktrace/.clang-format b/libbacktrace/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libbacktrace/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
new file mode 100644
index 0000000..285aa6e
--- /dev/null
+++ b/libbacktrace/Android.bp
@@ -0,0 +1,231 @@
+//
+// 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.
+//
+
+cc_defaults {
+    name: "libbacktrace_common",
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+
+    // The latest clang (r230699) does not allow SP/PC to be declared in inline asm lists.
+    clang_cflags: ["-Wno-inline-asm"],
+
+    include_dirs: ["external/libunwind/include/tdep"],
+
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    }
+}
+
+libbacktrace_sources = [
+    "Backtrace.cpp",
+    "BacktraceCurrent.cpp",
+    "BacktracePtrace.cpp",
+    "thread_utils.c",
+    "ThreadEntry.cpp",
+    "UnwindCurrent.cpp",
+    "UnwindMap.cpp",
+    "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,
+
+    srcs: [
+        "BacktraceMap.cpp",
+    ],
+
+    export_include_dirs: ["include"],
+
+    target: {
+        darwin: {
+            enabled: true,
+        },
+        linux: {
+            srcs: libbacktrace_sources,
+
+            shared_libs: [
+                "libbase",
+                "liblog",
+                "libunwind",
+            ],
+
+            static_libs: ["libcutils"],
+            host_ldlibs: ["-lrt"],
+        },
+        linux_bionic: {
+            enabled: true,
+            srcs: libbacktrace_sources,
+
+            shared_libs: [
+                "libbase",
+                "liblog",
+                "libunwind",
+            ],
+
+            static_libs: ["libcutils"],
+        },
+        android: {
+            srcs: libbacktrace_sources,
+
+            shared_libs: [
+                "libbase",
+                "liblog",
+                "libunwind",
+            ],
+
+            static_libs: ["libcutils"],
+        },
+    },
+}
+
+cc_library_shared {
+    name: "libbacktrace_test",
+    defaults: ["libbacktrace_common"],
+    host_supported: true,
+    strip: {
+        none: true,
+    },
+    cflags: ["-O0"],
+    srcs: ["backtrace_testlib.cpp"],
+
+    target: {
+        linux: {
+            shared_libs: [
+                "libunwind",
+            ],
+        },
+        android: {
+            shared_libs: [
+                "libunwind",
+            ],
+        },
+    }
+}
+
+//-------------------------------------------------------------------------
+// The libbacktrace_offline static library.
+//-------------------------------------------------------------------------
+cc_library_static {
+    name: "libbacktrace_offline",
+    defaults: ["libbacktrace_common"],
+    host_supported: true,
+    srcs: ["BacktraceOffline.cpp"],
+
+    cflags: [
+        "-D__STDC_CONSTANT_MACROS",
+        "-D__STDC_LIMIT_MACROS",
+        "-D__STDC_FORMAT_MACROS",
+    ],
+
+    header_libs: ["llvm-headers"],
+
+    // Use shared libraries so their headers get included during build.
+    shared_libs = [
+        "libbase",
+        "libunwind",
+    ],
+}
+
+//-------------------------------------------------------------------------
+// The backtrace_test executable.
+//-------------------------------------------------------------------------
+cc_test {
+    name: "backtrace_test",
+    defaults: ["libbacktrace_common"],
+    host_supported: true,
+    srcs: [
+        "backtrace_offline_test.cpp",
+        "backtrace_test.cpp",
+        "GetPss.cpp",
+        "thread_utils.c",
+    ],
+
+    cflags: [
+        "-fno-builtin",
+        "-O0",
+        "-g",
+    ],
+
+    shared_libs: [
+        "libbacktrace_test",
+        "libbacktrace",
+        "libbase",
+        "libcutils",
+        "liblog",
+        "libunwind",
+    ],
+
+    group_static_libs: true,
+
+    // Statically link LLVMlibraries to remove dependency on llvm shared library.
+    static_libs = [
+        "libbacktrace_offline",
+        "libLLVMObject",
+        "libLLVMBitReader",
+        "libLLVMMC",
+        "libLLVMMCParser",
+        "libLLVMCore",
+        "libLLVMSupport",
+
+        "libziparchive",
+        "libz",
+    ],
+
+    header_libs: ["llvm-headers"],
+
+    target: {
+        android: {
+            cflags: ["-DENABLE_PSS_TESTS"],
+            shared_libs: [
+                "libdl",
+                "libutils",
+            ],
+        },
+        linux: {
+            host_ldlibs: [
+                "-lpthread",
+                "-lrt",
+                "-ldl",
+                "-lncurses",
+            ],
+            static_libs: ["libutils"],
+        },
+    },
+}
diff --git a/libbacktrace/Android.build.mk b/libbacktrace/Android.build.mk
deleted file mode 100644
index 2467f3e..0000000
--- a/libbacktrace/Android.build.mk
+++ /dev/null
@@ -1,95 +0,0 @@
-#
-# 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.
-#
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := $(module)
-LOCAL_MODULE_TAGS := $(module_tag)
-LOCAL_MULTILIB := $($(module)_multilib)
-ifeq ($(LOCAL_MULTILIB),both)
-ifneq ($(build_target),$(filter $(build_target),SHARED_LIBRARY STATIC_LIBRARY))
-  LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-  LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-endif
-endif
-
-ifeq ($(build_type),target)
-  include $(LLVM_DEVICE_BUILD_MK)
-else
-  include $(LLVM_HOST_BUILD_MK)
-endif
-
-LOCAL_ADDITIONAL_DEPENDENCIES += \
-    $(LOCAL_PATH)/Android.mk \
-    $(LOCAL_PATH)/Android.build.mk \
-
-LOCAL_CFLAGS += \
-    $(libbacktrace_common_cflags) \
-    $($(module)_cflags) \
-    $($(module)_cflags_$(build_type)) \
-
-LOCAL_CLANG_CFLAGS += \
-    $(libbacktrace_common_clang_cflags) \
-
-LOCAL_CONLYFLAGS += \
-    $(libbacktrace_common_conlyflags) \
-    $($(module)_conlyflags) \
-    $($(module)_conlyflags_$(build_type)) \
-
-LOCAL_CPPFLAGS += \
-    $(libbacktrace_common_cppflags) \
-    $($(module)_cppflags) \
-    $($(module)_cppflags_$(build_type)) \
-
-LOCAL_C_INCLUDES += \
-    $(libbacktrace_common_c_includes) \
-    $($(module)_c_includes) \
-    $($(module)_c_includes_$(build_type)) \
-
-LOCAL_SRC_FILES := \
-    $($(module)_src_files) \
-    $($(module)_src_files_$(build_type)) \
-
-LOCAL_STATIC_LIBRARIES += \
-    $($(module)_static_libraries) \
-    $($(module)_static_libraries_$(build_type)) \
-
-LOCAL_SHARED_LIBRARIES += \
-    $($(module)_shared_libraries) \
-    $($(module)_shared_libraries_$(build_type)) \
-
-LOCAL_LDLIBS += \
-    $($(module)_ldlibs) \
-    $($(module)_ldlibs_$(build_type)) \
-
-LOCAL_STRIP_MODULE := $($(module)_strip_module)
-
-ifeq ($(build_type),target)
-  include $(BUILD_$(build_target))
-endif
-
-ifeq ($(build_type),host)
-  # Only build if host builds are supported.
-  ifeq ($(build_host),true)
-    # -fno-omit-frame-pointer should be set for host build. Because currently
-    # libunwind can't recognize .debug_frame using dwarf version 4, and it relies
-    # on stack frame pointer to do unwinding on x86.
-    # $(LLVM_HOST_BUILD_MK) overwrites -fno-omit-frame-pointer. so the below line
-    # must be after the include.
-    LOCAL_CFLAGS += -Wno-extern-c-compat -fno-omit-frame-pointer
-    include $(BUILD_HOST_$(build_target))
-  endif
-endif
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
deleted file mode 100644
index ee25e08..0000000
--- a/libbacktrace/Android.mk
+++ /dev/null
@@ -1,230 +0,0 @@
-#
-# 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.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-libbacktrace_common_cflags := \
-	-Wall \
-	-Werror \
-
-libbacktrace_common_conlyflags := \
-	-std=gnu99 \
-
-libbacktrace_common_cppflags := \
-	-std=gnu++11 \
-	-I external/libunwind/include/tdep \
-
-# The latest clang (r230699) does not allow SP/PC to be declared in inline asm lists.
-libbacktrace_common_clang_cflags += \
-    -Wno-inline-asm
-
-build_host := false
-ifeq ($(HOST_OS),linux)
-ifeq ($(HOST_ARCH),$(filter $(HOST_ARCH),x86 x86_64))
-build_host := true
-endif
-endif
-
-LLVM_ROOT_PATH := external/llvm
-include $(LLVM_ROOT_PATH)/llvm.mk
-
-#-------------------------------------------------------------------------
-# The libbacktrace library.
-#-------------------------------------------------------------------------
-libbacktrace_src_files := \
-	Backtrace.cpp \
-	BacktraceCurrent.cpp \
-	BacktraceMap.cpp \
-	BacktracePtrace.cpp \
-	thread_utils.c \
-	ThreadEntry.cpp \
-	UnwindCurrent.cpp \
-	UnwindMap.cpp \
-	UnwindPtrace.cpp \
-
-libbacktrace_shared_libraries := \
-	libbase \
-	liblog \
-	libunwind \
-
-libbacktrace_static_libraries := \
-	libcutils
-
-module := libbacktrace
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-libbacktrace_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-libbacktrace_static_libraries := \
-	libbase \
-	liblog \
-	libunwind \
-
-build_target := STATIC_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-libbacktrace_static_libraries :=
-
-#-------------------------------------------------------------------------
-# The libbacktrace_offline shared library.
-#-------------------------------------------------------------------------
-libbacktrace_offline_src_files := \
-	BacktraceOffline.cpp \
-
-# Use shared llvm library on device to save space.
-libbacktrace_offline_shared_libraries_target := \
-	libbacktrace \
-	libbase \
-	liblog \
-	libunwind \
-	libutils \
-	libLLVM \
-
-libbacktrace_offline_static_libraries_target := \
-	libziparchive \
-	libz \
-
-# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
-# which is not included in the prebuilt.
-libbacktrace_offline_static_libraries_host := \
-	libbacktrace \
-	libunwind \
-	libziparchive-host \
-	libz \
-	libbase \
-	liblog \
-	libutils \
-	libLLVMObject \
-	libLLVMBitReader \
-	libLLVMMC \
-	libLLVMMCParser \
-	libLLVMCore \
-	libLLVMSupport \
-
-module := libbacktrace_offline
-build_type := target
-build_target := STATIC_LIBRARY
-libbacktrace_offline_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-include $(LOCAL_PATH)/Android.build.mk
-
-#-------------------------------------------------------------------------
-# The libbacktrace_test library needed by backtrace_test.
-#-------------------------------------------------------------------------
-libbacktrace_test_cflags := \
-	-O0 \
-
-libbacktrace_test_src_files := \
-	backtrace_testlib.c \
-
-libbacktrace_test_strip_module := false
-
-module := libbacktrace_test
-module_tag := debug
-build_type := target
-build_target := SHARED_LIBRARY
-libbacktrace_test_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-include $(LOCAL_PATH)/Android.build.mk
-
-#-------------------------------------------------------------------------
-# The backtrace_test executable.
-#-------------------------------------------------------------------------
-backtrace_test_cflags := \
-	-fno-builtin \
-	-O0 \
-	-g \
-
-backtrace_test_cflags_target := \
-	-DENABLE_PSS_TESTS \
-
-backtrace_test_src_files := \
-	backtrace_offline_test.cpp \
-	backtrace_test.cpp \
-	GetPss.cpp \
-	thread_utils.c \
-
-backtrace_test_ldlibs_host := \
-	-lpthread \
-	-lrt \
-
-backtrace_test_shared_libraries := \
-	libbacktrace_test \
-	libbacktrace \
-	libbase \
-	libcutils \
-	liblog \
-	libunwind \
-
-backtrace_test_shared_libraries_target += \
-	libdl \
-	libutils \
-	libLLVM \
-
-backtrace_test_static_libraries := \
-	libbacktrace_offline \
-
-backtrace_test_static_libraries_target := \
-	libziparchive \
-	libz \
-
-backtrace_test_static_libraries_host := \
-	libziparchive-host \
-	libz \
-	libutils \
-	libLLVMObject \
-	libLLVMBitReader \
-	libLLVMMC \
-	libLLVMMCParser \
-	libLLVMCore \
-	libLLVMSupport \
-
-backtrace_test_ldlibs_host += \
-	-ldl \
-
-backtrace_test_strip_module := false
-
-module := backtrace_test
-module_tag := debug
-build_type := target
-build_target := NATIVE_TEST
-backtrace_test_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-include $(LOCAL_PATH)/Android.build.mk
-
-#----------------------------------------------------------------------------
-# Special truncated libbacktrace library for mac.
-#----------------------------------------------------------------------------
-ifeq ($(HOST_OS),darwin)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbacktrace
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-	BacktraceMap.cpp \
-
-LOCAL_MULTILIB := both
-
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-endif # HOST_OS-darwin
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.cpp b/libbacktrace/BacktraceCurrent.cpp
index 5173e2c..d7a3b01 100644
--- a/libbacktrace/BacktraceCurrent.cpp
+++ b/libbacktrace/BacktraceCurrent.cpp
@@ -95,11 +95,31 @@
 
 static pthread_mutex_t g_sigaction_mutex = PTHREAD_MUTEX_INITIALIZER;
 
+// Since errno is stored per thread, changing it in the signal handler
+// modifies the value on the thread in which the signal handler executes.
+// If a signal occurs between a call and an errno check, it's possible
+// to get the errno set here. Always save and restore it just in case
+// code would modify it.
+class ErrnoRestorer {
+ public:
+  ErrnoRestorer() : saved_errno_(errno) {}
+  ~ErrnoRestorer() {
+    errno = saved_errno_;
+  }
+
+ private:
+  int saved_errno_;
+};
+
 static void SignalLogOnly(int, siginfo_t*, void*) {
+  ErrnoRestorer restore;
+
   BACK_LOGE("pid %d, tid %d: Received a spurious signal %d\n", getpid(), gettid(), THREAD_SIGNAL);
 }
 
 static void SignalHandler(int, siginfo_t*, void* sigcontext) {
+  ErrnoRestorer restore;
+
   ThreadEntry* entry = ThreadEntry::Get(getpid(), gettid(), false);
   if (!entry) {
     BACK_LOGE("pid %d, tid %d entry not found", getpid(), gettid());
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/BacktraceMap.cpp b/libbacktrace/BacktraceMap.cpp
index 85f2436..0e31495 100644
--- a/libbacktrace/BacktraceMap.cpp
+++ b/libbacktrace/BacktraceMap.cpp
@@ -14,14 +14,18 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "backtrace-map"
+
 #include <ctype.h>
+#include <inttypes.h>
 #include <stdint.h>
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <log/log.h>
+
 #include <backtrace/backtrace_constants.h>
 #include <backtrace/BacktraceMap.h>
-#include <log/log.h>
 
 #include "thread_utils.h"
 
@@ -46,8 +50,8 @@
 }
 
 bool BacktraceMap::ParseLine(const char* line, backtrace_map_t* map) {
-  unsigned long int start;
-  unsigned long int end;
+  uint64_t start;
+  uint64_t end;
   char permissions[5];
   int name_pos;
 
@@ -56,14 +60,14 @@
 // __TEXT                 0009f000-000a1000 [    8K     8K] r-x/rwx SM=COW  /Volumes/android/dalvik-dev/out/host/darwin-x86/bin/libcorkscrew_test\n
 // 012345678901234567890123456789012345678901234567890123456789
 // 0         1         2         3         4         5
-  if (sscanf(line, "%*21c %lx-%lx [%*13c] %3c/%*3c SM=%*3c  %n",
+  if (sscanf(line, "%*21c %" SCNx64 "-%" SCNx64 " [%*13c] %3c/%*3c SM=%*3c  %n",
              &start, &end, permissions, &name_pos) != 3) {
 #else
 // Linux /proc/<pid>/maps lines:
 // 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so\n
 // 012345678901234567890123456789012345678901234567890123456789
 // 0         1         2         3         4         5
-  if (sscanf(line, "%lx-%lx %4s %*x %*x:%*x %*d %n",
+  if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %*x %*x:%*x %*d %n",
              &start, &end, permissions, &name_pos) != 3) {
 #endif
     return false;
diff --git a/libbacktrace/BacktraceOffline.cpp b/libbacktrace/BacktraceOffline.cpp
index 9a4f622..0a2f5a3 100644
--- a/libbacktrace/BacktraceOffline.cpp
+++ b/libbacktrace/BacktraceOffline.cpp
@@ -21,6 +21,7 @@
 #include <dwarf.h>
 }
 
+#include <pthread.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <string.h>
@@ -30,10 +31,12 @@
 #include <unistd.h>
 
 #include <memory>
+#include <mutex>
 #include <string>
 #include <vector>
 
 #include <android-base/file.h>
+#include <android-base/macros.h>
 #include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
 #include <ziparchive/zip_archive.h>
@@ -50,6 +53,45 @@
 
 #include "BacktraceLog.h"
 
+struct EhFrame {
+  uint64_t hdr_vaddr;
+  uint64_t vaddr;
+  uint64_t fde_table_offset;
+  uintptr_t min_func_vaddr;
+  std::vector<uint8_t> hdr_data;
+  std::vector<uint8_t> data;
+};
+
+struct ArmIdxEntry {
+  uint32_t func_offset;
+  uint32_t value;
+};
+
+struct ArmExidx {
+  uint64_t exidx_vaddr;
+  uint64_t extab_vaddr;
+  std::vector<ArmIdxEntry> exidx_data;
+  std::vector<uint8_t> extab_data;
+  // There is a one-to-one map from exidx_data.func_offset to func_vaddr_array.
+  std::vector<uint32_t> func_vaddr_array;
+};
+
+struct DebugFrameInfo {
+  bool has_arm_exidx;
+  bool has_eh_frame;
+  bool has_debug_frame;
+  bool has_gnu_debugdata;
+
+  EhFrame eh_frame;
+  ArmExidx arm_exidx;
+
+  uint64_t min_vaddr;
+  uint64_t text_end_vaddr;
+
+  DebugFrameInfo() : has_arm_exidx(false), has_eh_frame(false),
+      has_debug_frame(false), has_gnu_debugdata(false) { }
+};
+
 void Space::Clear() {
   start = 0;
   end = 0;
@@ -207,23 +249,18 @@
   if (read_size != 0) {
     return read_size;
   }
+  read_size = arm_exidx_space_.Read(addr, buffer, bytes);
+  if (read_size != 0) {
+    return read_size;
+  }
+  read_size = arm_extab_space_.Read(addr, buffer, bytes);
+  if (read_size != 0) {
+    return read_size;
+  }
   read_size = stack_space_.Read(addr, buffer, bytes);
   return read_size;
 }
 
-static bool FileOffsetToVaddr(
-    const std::vector<DebugFrameInfo::EhFrame::ProgramHeader>& program_headers,
-    uint64_t file_offset, uint64_t* vaddr) {
-  for (auto& header : program_headers) {
-    if (file_offset >= header.file_offset && file_offset < header.file_offset + header.file_size) {
-      // TODO: Consider load_bias?
-      *vaddr = file_offset - header.file_offset + header.vaddr;
-      return true;
-    }
-  }
-  return false;
-}
-
 bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
                                     unw_proc_info_t* proc_info, int need_unwind_info) {
   backtrace_map_t map;
@@ -236,45 +273,97 @@
   if (debug_frame == nullptr) {
     return false;
   }
-  if (debug_frame->is_eh_frame) {
-    uint64_t ip_offset = ip - map.start + map.offset;
-    uint64_t ip_vaddr;  // vaddr in the elf file.
-    bool result = FileOffsetToVaddr(debug_frame->eh_frame.program_headers, ip_offset, &ip_vaddr);
-    if (!result) {
-      return false;
-    }
-    // Calculate the addresses where .eh_frame_hdr and .eh_frame stay when the process was running.
-    eh_frame_hdr_space_.start = (ip - ip_vaddr) + debug_frame->eh_frame.eh_frame_hdr_vaddr;
-    eh_frame_hdr_space_.end =
-        eh_frame_hdr_space_.start + debug_frame->eh_frame.eh_frame_hdr_data.size();
-    eh_frame_hdr_space_.data = debug_frame->eh_frame.eh_frame_hdr_data.data();
-
-    eh_frame_space_.start = (ip - ip_vaddr) + debug_frame->eh_frame.eh_frame_vaddr;
-    eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.eh_frame_data.size();
-    eh_frame_space_.data = debug_frame->eh_frame.eh_frame_data.data();
-
-    unw_dyn_info di;
-    memset(&di, '\0', sizeof(di));
-    di.start_ip = map.start;
-    di.end_ip = map.end;
-    di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
-    di.u.rti.name_ptr = 0;
-    di.u.rti.segbase = eh_frame_hdr_space_.start;
-    di.u.rti.table_data =
-        eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset_in_eh_frame_hdr;
-    di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
-    int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
-    return ret == 0;
-  }
 
   eh_frame_hdr_space_.Clear();
   eh_frame_space_.Clear();
-  unw_dyn_info_t di;
-  unw_word_t segbase = map.start - map.offset;
-  int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
-  if (found == 1) {
-    int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
-    return ret == 0;
+  arm_exidx_space_.Clear();
+  arm_extab_space_.Clear();
+
+  // vaddr in the elf file.
+  uint64_t ip_vaddr = ip - map.start + debug_frame->min_vaddr;
+
+  // The unwind info can come from .ARM.exidx or .eh_frame, or .debug_frame/.gnu_debugdata.
+  // First check .eh_frame/.debug_frame, then check .ARM.exidx. Because .eh_frame/.debug_frame has
+  // function range for each entry, by matching ip address with the function range, we know exactly
+  // whether the ip address hits an entry. But .ARM.exidx doesn't have function range for each
+  // entry, it thinks that an ip address hits an entry when (entry.addr <= ip < next_entry.addr).
+  // To prevent ip addresses hit in .eh_frame/.debug_frame being regarded as addresses hit in
+  // .ARM.exidx, we need to check .eh_frame/.debug_frame first.
+  if (debug_frame->has_eh_frame) {
+    if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
+        ip_vaddr < debug_frame->text_end_vaddr) {
+      // Prepare eh_frame_hdr space and eh_frame space.
+      eh_frame_hdr_space_.start = ip - ip_vaddr + debug_frame->eh_frame.hdr_vaddr;
+      eh_frame_hdr_space_.end =
+          eh_frame_hdr_space_.start + debug_frame->eh_frame.hdr_data.size();
+      eh_frame_hdr_space_.data = debug_frame->eh_frame.hdr_data.data();
+      eh_frame_space_.start = ip - ip_vaddr + debug_frame->eh_frame.vaddr;
+      eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.data.size();
+      eh_frame_space_.data = debug_frame->eh_frame.data.data();
+
+      unw_dyn_info di;
+      memset(&di, '\0', sizeof(di));
+      di.start_ip = map.start;
+      di.end_ip = map.end;
+      di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
+      di.u.rti.name_ptr = 0;
+      di.u.rti.segbase = eh_frame_hdr_space_.start;
+      di.u.rti.table_data =
+          eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset;
+      di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
+      // TODO: Do it ourselves is more efficient than calling this function.
+      int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
+      if (ret == 0) {
+        return true;
+      }
+    }
+  }
+  if (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata) {
+    unw_dyn_info_t di;
+    unw_word_t segbase = map.start - map.offset;
+    // TODO: http://b/32916571
+    // TODO: Do it ourselves is more efficient than calling libunwind functions.
+    int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
+    if (found == 1) {
+      int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
+      if (ret == 0) {
+        return true;
+      }
+    }
+  }
+
+  if (debug_frame->has_arm_exidx) {
+    auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
+    if (ip_vaddr >= func_vaddrs[0] && ip_vaddr < debug_frame->text_end_vaddr) {
+      // Use binary search to find the correct function.
+      auto it = std::upper_bound(func_vaddrs.begin(), func_vaddrs.end(),
+                                 static_cast<uint32_t>(ip_vaddr));
+      if (it != func_vaddrs.begin()) {
+        --it;
+        // Found the exidx entry.
+        size_t index = it - func_vaddrs.begin();
+        proc_info->start_ip = *it;
+        proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
+        proc_info->unwind_info = reinterpret_cast<void*>(
+            static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
+                                   debug_frame->arm_exidx.exidx_vaddr +
+                                   debug_frame->min_vaddr));
+        eh_frame_hdr_space_.Clear();
+        eh_frame_space_.Clear();
+        // Prepare arm_exidx space and arm_extab space.
+        arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
+        arm_exidx_space_.end = arm_exidx_space_.start +
+            debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
+        arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
+            debug_frame->arm_exidx.exidx_data.data());
+
+        arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
+        arm_extab_space_.end = arm_extab_space_.start +
+            debug_frame->arm_exidx.extab_data.size();
+        arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
+        return true;
+      }
+    }
   }
   return false;
 }
@@ -452,6 +541,10 @@
     default:
       result = false;
   }
+#else
+  UNUSED(reg);
+  UNUSED(value);
+  result = false;
 #endif
   return result;
 }
@@ -462,33 +555,31 @@
   return "";
 }
 
-std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>> BacktraceOffline::debug_frames_;
-std::unordered_set<std::string> BacktraceOffline::debug_frame_missing_files_;
+static std::mutex g_lock;
+static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>* g_debug_frames = nullptr;
 
 static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
 
 DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
   if (cache_file_) {
-    auto it = debug_frames_.find(filename);
-    if (it != debug_frames_.end()) {
-      return it->second.get();
-    }
-    if (debug_frame_missing_files_.find(filename) != debug_frame_missing_files_.end()) {
-      return nullptr;
+    std::lock_guard<std::mutex> lock(g_lock);
+    if (g_debug_frames != nullptr) {
+      auto it = g_debug_frames->find(filename);
+      if (it != g_debug_frames->end()) {
+        return it->second.get();
+      }
     }
   }
   DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
   if (cache_file_) {
-    if (debug_frame != nullptr) {
-      debug_frames_.emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
-    } else {
-      debug_frame_missing_files_.insert(filename);
+    std::lock_guard<std::mutex> lock(g_lock);
+    if (g_debug_frames == nullptr) {
+      g_debug_frames = new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
     }
-  } else {
-    if (last_debug_frame_ != nullptr) {
-      delete last_debug_frame_;
+    auto pair = g_debug_frames->emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
+    if (!pair.second) {
+      debug_frame = pair.first->second.get();
     }
-    last_debug_frame_ = debug_frame;
   }
   return debug_frame;
 }
@@ -556,72 +647,106 @@
   return true;
 }
 
-using ProgramHeader = DebugFrameInfo::EhFrame::ProgramHeader;
-
 template <class ELFT>
 DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
+  DebugFrameInfo* result = new DebugFrameInfo;
+  result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
+
   bool has_eh_frame_hdr = false;
-  uint64_t eh_frame_hdr_vaddr = 0;
-  std::vector<uint8_t> eh_frame_hdr_data;
   bool has_eh_frame = false;
-  uint64_t eh_frame_vaddr = 0;
-  std::vector<uint8_t> eh_frame_data;
 
   for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
     llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
     if (name) {
-      if (name.get() == ".debug_frame") {
-        DebugFrameInfo* debug_frame = new DebugFrameInfo;
-        debug_frame->is_eh_frame = false;
-        return debug_frame;
-      }
-      if (name.get() == ".eh_frame_hdr") {
-        has_eh_frame_hdr = true;
-        eh_frame_hdr_vaddr = it->sh_addr;
+      std::string s = name.get();
+      if (s == ".debug_frame") {
+        result->has_debug_frame = true;
+      } else if (s == ".gnu_debugdata") {
+        result->has_gnu_debugdata = true;
+      } else if (s == ".eh_frame_hdr") {
+        result->eh_frame.hdr_vaddr = it->sh_addr;
         llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
         if (data) {
-          eh_frame_hdr_data.insert(eh_frame_hdr_data.begin(), data->data(),
-                                   data->data() + data->size());
-        } else {
-          return nullptr;
+          result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
+              data->data(), data->data() + data->size());
+
+          uint64_t fde_table_offset;
+          if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data,
+                                             &fde_table_offset)) {
+            result->eh_frame.fde_table_offset = fde_table_offset;
+            // Make sure we have at least one entry in fde_table.
+            if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
+              intptr_t eh_frame_hdr_vaddr = it->sh_addr;
+              int32_t sdata;
+              uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
+              memcpy(&sdata, p, sizeof(sdata));
+              result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
+              has_eh_frame_hdr = true;
+            }
+          }
         }
-      } else if (name.get() == ".eh_frame") {
-        has_eh_frame = true;
-        eh_frame_vaddr = it->sh_addr;
+      } else if (s == ".eh_frame") {
+        result->eh_frame.vaddr = it->sh_addr;
         llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
         if (data) {
-          eh_frame_data.insert(eh_frame_data.begin(), data->data(), data->data() + data->size());
-        } else {
-          return nullptr;
+          result->eh_frame.data.insert(result->eh_frame.data.end(),
+                                                data->data(), data->data() + data->size());
+          has_eh_frame = true;
         }
+      } else if (s == ".ARM.exidx") {
+        result->arm_exidx.exidx_vaddr = it->sh_addr;
+        llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
+        if (data) {
+          size_t entry_count = data->size() / sizeof(ArmIdxEntry);
+          result->arm_exidx.exidx_data.resize(entry_count);
+          memcpy(result->arm_exidx.exidx_data.data(), data->data(),
+                 entry_count * sizeof(ArmIdxEntry));
+          if (entry_count > 0u) {
+            // Change IdxEntry.func_offset into vaddr.
+            result->arm_exidx.func_vaddr_array.reserve(entry_count);
+            uint32_t vaddr = it->sh_addr;
+            for (auto& entry : result->arm_exidx.exidx_data) {
+              uint32_t func_offset = entry.func_offset + vaddr;
+              // Clear bit 31 for the prel31 offset.
+              // Arm sets bit 0 to mark it as thumb code, remove the flag.
+              result->arm_exidx.func_vaddr_array.push_back(
+                  func_offset & 0x7ffffffe);
+              vaddr += 8;
+            }
+            result->has_arm_exidx = true;
+          }
+        }
+      } else if (s == ".ARM.extab") {
+        result->arm_exidx.extab_vaddr = it->sh_addr;
+        llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
+        if (data) {
+          result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
+                                              data->data(), data->data() + data->size());
+        }
+      } else if (s == ".text") {
+        result->text_end_vaddr = it->sh_addr + it->sh_size;
       }
     }
   }
-  if (!(has_eh_frame_hdr && has_eh_frame)) {
-    return nullptr;
-  }
-  uint64_t fde_table_offset;
-  if (!GetFdeTableOffsetInEhFrameHdr(eh_frame_hdr_data, &fde_table_offset)) {
-    return nullptr;
+
+  if (has_eh_frame_hdr && has_eh_frame) {
+    result->has_eh_frame = true;
   }
 
-  std::vector<ProgramHeader> program_headers;
+  result->min_vaddr = std::numeric_limits<uint64_t>::max();
   for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
-    ProgramHeader header;
-    header.vaddr = it->p_vaddr;
-    header.file_offset = it->p_offset;
-    header.file_size = it->p_filesz;
-    program_headers.push_back(header);
+    if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
+      if (it->p_vaddr < result->min_vaddr) {
+        result->min_vaddr = it->p_vaddr;
+      }
+    }
   }
-  DebugFrameInfo* debug_frame = new DebugFrameInfo;
-  debug_frame->is_eh_frame = true;
-  debug_frame->eh_frame.eh_frame_hdr_vaddr = eh_frame_hdr_vaddr;
-  debug_frame->eh_frame.eh_frame_vaddr = eh_frame_vaddr;
-  debug_frame->eh_frame.fde_table_offset_in_eh_frame_hdr = fde_table_offset;
-  debug_frame->eh_frame.eh_frame_hdr_data = std::move(eh_frame_hdr_data);
-  debug_frame->eh_frame.eh_frame_data = std::move(eh_frame_data);
-  debug_frame->eh_frame.program_headers = program_headers;
-  return debug_frame;
+  if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
+      !result->has_gnu_debugdata) {
+    delete result;
+    return nullptr;
+  }
+  return result;
 }
 
 static bool IsValidElfPath(const std::string& filename) {
@@ -665,7 +790,7 @@
 
 class ScopedZiparchiveHandle {
  public:
-  ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
+  explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
   }
 
   ~ScopedZiparchiveHandle() {
@@ -719,7 +844,7 @@
   auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
   if (!binary_or_err) {
     BACK_LOGW("failed to create binary for %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
-              binary_or_err.getError().message().c_str());
+              llvm::toString(binary_or_err.takeError()).c_str());
     return nothing;
   }
   return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
diff --git a/libbacktrace/BacktraceOffline.h b/libbacktrace/BacktraceOffline.h
index 42f826d..c0b686e 100644
--- a/libbacktrace/BacktraceOffline.h
+++ b/libbacktrace/BacktraceOffline.h
@@ -40,22 +40,7 @@
   size_t Read(uint64_t addr, uint8_t* buffer, size_t size);
 };
 
-struct DebugFrameInfo {
-  bool is_eh_frame;
-  struct EhFrame {
-    uint64_t eh_frame_hdr_vaddr;
-    uint64_t eh_frame_vaddr;
-    uint64_t fde_table_offset_in_eh_frame_hdr;
-    std::vector<uint8_t> eh_frame_hdr_data;
-    std::vector<uint8_t> eh_frame_data;
-    struct ProgramHeader {
-      uint64_t vaddr;
-      uint64_t file_offset;
-      uint64_t file_size;
-    };
-    std::vector<ProgramHeader> program_headers;
-  } eh_frame;
-};
+struct DebugFrameInfo;
 
 class BacktraceOffline : public Backtrace {
  public:
@@ -63,18 +48,13 @@
                    bool cache_file)
       : Backtrace(pid, tid, map),
         cache_file_(cache_file),
-        context_(nullptr),
-        last_debug_frame_(nullptr) {
+        context_(nullptr) {
     stack_space_.start = stack.start;
     stack_space_.end = stack.end;
     stack_space_.data = stack.data;
   }
 
-  virtual ~BacktraceOffline() {
-    if (last_debug_frame_ != nullptr) {
-      delete last_debug_frame_;
-    }
-  }
+  virtual ~BacktraceOffline() = default;
 
   bool Unwind(size_t num_ignore_frames, ucontext_t* context) override;
 
@@ -91,15 +71,13 @@
   std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
   DebugFrameInfo* GetDebugFrameInFile(const std::string& filename);
 
-  static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>> debug_frames_;
-  static std::unordered_set<std::string> debug_frame_missing_files_;
-
   bool cache_file_;
   ucontext_t* context_;
   Space eh_frame_hdr_space_;
   Space eh_frame_space_;
+  Space arm_extab_space_;
+  Space arm_exidx_space_;
   Space stack_space_;
-  DebugFrameInfo* last_debug_frame_;
 };
 
 #endif  // _LIBBACKTRACE_BACKTRACE_OFFLINE_H
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/GetPss.cpp b/libbacktrace/GetPss.cpp
index 09a721d..6d750ea 100644
--- a/libbacktrace/GetPss.cpp
+++ b/libbacktrace/GetPss.cpp
@@ -24,7 +24,7 @@
 
 // This is an extremely simplified version of libpagemap.
 
-#define _BITS(x, offset, bits) (((x) >> offset) & ((1LL << (bits)) - 1))
+#define _BITS(x, offset, bits) (((x) >> (offset)) & ((1LL << (bits)) - 1))
 
 #define PAGEMAP_PRESENT(x)     (_BITS(x, 63, 1))
 #define PAGEMAP_SWAPPED(x)     (_BITS(x, 62, 1))
@@ -33,7 +33,7 @@
 #define PAGEMAP_SWAP_OFFSET(x) (_BITS(x, 5, 50))
 #define PAGEMAP_SWAP_TYPE(x)   (_BITS(x, 0,  5))
 
-static bool ReadData(int fd, unsigned long place, uint64_t *data) {
+static bool ReadData(int fd, off_t place, uint64_t *data) {
   if (lseek(fd, place * sizeof(uint64_t), SEEK_SET) < 0) {
     return false;
   }
@@ -71,12 +71,13 @@
       total_pss = 0;
       break;
     }
-    for (size_t page = start/pagesize; page < end/pagesize; page++) {
+    for (off_t page = static_cast<off_t>(start/pagesize);
+         page < static_cast<off_t>(end/pagesize); page++) {
       uint64_t data;
       if (ReadData(pagemap_fd, page, &data)) {
         if (PAGEMAP_PRESENT(data) && !PAGEMAP_SWAPPED(data)) {
           uint64_t count;
-          if (ReadData(pagecount_fd, PAGEMAP_PFN(data), &count)) {
+          if (ReadData(pagecount_fd, static_cast<off_t>(PAGEMAP_PFN(data)), &count)) {
             total_pss += (count >= 1) ? pagesize / count : 0;
           }
         }
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 f85b54a..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:
-  UnwindMap(pid_t pid);
+ 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:
-  UnwindMapRemote(pid_t pid);
+ 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_offline_test.cpp b/libbacktrace/backtrace_offline_test.cpp
index 88a3533..465b3f9 100644
--- a/libbacktrace/backtrace_offline_test.cpp
+++ b/libbacktrace/backtrace_offline_test.cpp
@@ -1,3 +1,20 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <inttypes.h>
 #include <libunwind.h>
 #include <pthread.h>
 #include <stdint.h>
@@ -9,6 +26,9 @@
 #include <utility>
 #include <vector>
 
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
 #include <cutils/threads.h>
@@ -22,29 +42,7 @@
 int test_level_three(int, int, int, int, void (*)(void*), void*);
 int test_level_four(int, int, int, int, void (*)(void*), void*);
 int test_recursive_call(int, void (*)(void*), void*);
-}
-
-static volatile bool g_exit_flag = false;
-
-static void GetContextAndExit(void* arg) {
-  unw_context_t* unw_context = reinterpret_cast<unw_context_t*>(arg);
-  unw_getcontext(unw_context);
-  // Don't touch the stack anymore.
-  while (!g_exit_flag) {
-  }
-}
-
-struct OfflineThreadArg {
-  unw_context_t unw_context;
-  pid_t tid;
-  std::function<int(void (*)(void*), void*)> function;
-};
-
-static void* OfflineThreadFunc(void* arg) {
-  OfflineThreadArg* fn_arg = reinterpret_cast<OfflineThreadArg*>(arg);
-  fn_arg->tid = gettid();
-  fn_arg->function(GetContextAndExit, &fn_arg->unw_context);
-  return nullptr;
+void test_get_context_and_wait(unw_context_t* unw_context, volatile int* exit_flag);
 }
 
 static ucontext_t GetUContextFromUnwContext(const unw_context_t& unw_context) {
@@ -73,11 +71,68 @@
   return ucontext;
 }
 
-static void OfflineBacktraceFunctionCall(std::function<int(void (*)(void*), void*)> function,
-                                         std::vector<uintptr_t>* pc_values) {
+struct FunctionSymbol {
+  std::string name;
+  uintptr_t start;
+  uintptr_t end;
+};
+
+static std::vector<FunctionSymbol> GetFunctionSymbols() {
+  std::vector<FunctionSymbol> symbols = {
+      {"unknown_start", 0, 0},
+      {"test_level_one", reinterpret_cast<uintptr_t>(&test_level_one), 0},
+      {"test_level_two", reinterpret_cast<uintptr_t>(&test_level_two), 0},
+      {"test_level_three", reinterpret_cast<uintptr_t>(&test_level_three), 0},
+      {"test_level_four", reinterpret_cast<uintptr_t>(&test_level_four), 0},
+      {"test_recursive_call", reinterpret_cast<uintptr_t>(&test_recursive_call), 0},
+      {"test_get_context_and_wait", reinterpret_cast<uintptr_t>(&test_get_context_and_wait), 0},
+      {"unknown_end", static_cast<uintptr_t>(-1), static_cast<uintptr_t>(-1)},
+  };
+  std::sort(
+      symbols.begin(), symbols.end(),
+      [](const FunctionSymbol& s1, const FunctionSymbol& s2) { return s1.start < s2.start; });
+  for (size_t i = 0; i + 1 < symbols.size(); ++i) {
+    symbols[i].end = symbols[i + 1].start;
+  }
+  return symbols;
+}
+
+static std::string RawDataToHexString(const void* data, size_t size) {
+  const uint8_t* p = static_cast<const uint8_t*>(data);
+  std::string s;
+  for (size_t i = 0; i < size; ++i) {
+    s += android::base::StringPrintf("%02x", p[i]);
+  }
+  return s;
+}
+
+static void HexStringToRawData(const char* s, void* data, size_t size) {
+  uint8_t* p = static_cast<uint8_t*>(data);
+  for (size_t i = 0; i < size; ++i) {
+    int value;
+    sscanf(s, "%02x", &value);
+    *p++ = static_cast<uint8_t>(value);
+    s += 2;
+  }
+}
+
+struct OfflineThreadArg {
+  unw_context_t unw_context;
+  pid_t tid;
+  volatile int exit_flag;
+};
+
+static void* OfflineThreadFunc(void* arg) {
+  OfflineThreadArg* fn_arg = reinterpret_cast<OfflineThreadArg*>(arg);
+  fn_arg->tid = gettid();
+  test_get_context_and_wait(&fn_arg->unw_context, &fn_arg->exit_flag);
+  return nullptr;
+}
+
+// This test is disable because it is for generating test data.
+TEST(libbacktrace, DISABLED_generate_offline_testdata) {
   // Create a thread to generate the needed stack and registers information.
-  g_exit_flag = false;
-  const size_t stack_size = 1024 * 1024;
+  const size_t stack_size = 16 * 1024;
   void* stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_NE(MAP_FAILED, stack);
   uintptr_t stack_addr = reinterpret_cast<uintptr_t>(stack);
@@ -86,18 +141,17 @@
   ASSERT_EQ(0, pthread_attr_setstack(&attr, reinterpret_cast<void*>(stack), stack_size));
   pthread_t thread;
   OfflineThreadArg arg;
-  arg.function = function;
+  arg.exit_flag = 0;
   ASSERT_EQ(0, pthread_create(&thread, &attr, OfflineThreadFunc, &arg));
   // Wait for the offline thread to generate the stack and unw_context information.
   sleep(1);
   // Copy the stack information.
   std::vector<uint8_t> stack_data(reinterpret_cast<uint8_t*>(stack),
                                   reinterpret_cast<uint8_t*>(stack) + stack_size);
-  g_exit_flag = true;
+  arg.exit_flag = 1;
   ASSERT_EQ(0, pthread_join(thread, nullptr));
   ASSERT_EQ(0, munmap(stack, stack_size));
 
-  // Do offline backtrace.
   std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
   ASSERT_TRUE(map != nullptr);
 
@@ -106,47 +160,44 @@
   stack_info.end = stack_addr + stack_size;
   stack_info.data = stack_data.data();
 
-  std::unique_ptr<Backtrace> backtrace(
-      Backtrace::CreateOffline(getpid(), arg.tid, map.get(), stack_info));
-  ASSERT_TRUE(backtrace != nullptr);
-
-  ucontext_t ucontext = GetUContextFromUnwContext(arg.unw_context);
-  ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
-
-  // Collect pc values of the call stack frames.
-  for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
-    pc_values->push_back(backtrace->GetFrame(i)->pc);
+  // Generate offline testdata.
+  std::string testdata;
+  // 1. Dump pid, tid
+  testdata += android::base::StringPrintf("pid: %d tid: %d\n", getpid(), arg.tid);
+  // 2. Dump maps
+  for (auto it = map->begin(); it != map->end(); ++it) {
+    testdata += android::base::StringPrintf(
+        "map: start: %" PRIxPTR " end: %" PRIxPTR " offset: %" PRIxPTR
+        " load_base: %" PRIxPTR " flags: %d name: %s\n",
+        it->start, it->end, it->offset, it->load_base, it->flags, it->name.c_str());
   }
+  // 3. Dump registers
+  testdata += android::base::StringPrintf("registers: %zu ", sizeof(arg.unw_context));
+  testdata += RawDataToHexString(&arg.unw_context, sizeof(arg.unw_context));
+  testdata.push_back('\n');
+
+  // 4. Dump stack
+  testdata += android::base::StringPrintf(
+      "stack: start: %" PRIx64 " end: %" PRIx64 " size: %zu ",
+      stack_info.start, stack_info.end, stack_data.size());
+  testdata += RawDataToHexString(stack_data.data(), stack_data.size());
+  testdata.push_back('\n');
+
+  // 5. Dump function symbols
+  std::vector<FunctionSymbol> function_symbols = GetFunctionSymbols();
+  for (const auto& symbol : function_symbols) {
+    testdata += android::base::StringPrintf(
+        "function: start: %" PRIxPTR " end: %" PRIxPTR" name: %s\n",
+        symbol.start, symbol.end, symbol.name.c_str());
+  }
+
+  ASSERT_TRUE(android::base::WriteStringToFile(testdata, "offline_testdata"));
 }
 
 // Return the name of the function which matches the address. Although we don't know the
 // exact end of each function, it is accurate enough for the tests.
-static std::string FunctionNameForAddress(uintptr_t addr) {
-  struct FunctionSymbol {
-    std::string name;
-    uintptr_t start;
-    uintptr_t end;
-  };
-
-  static std::vector<FunctionSymbol> symbols;
-  if (symbols.empty()) {
-    symbols = std::vector<FunctionSymbol>{
-        {"unknown_start", 0, 0},
-        {"test_level_one", reinterpret_cast<uintptr_t>(&test_level_one), 0},
-        {"test_level_two", reinterpret_cast<uintptr_t>(&test_level_two), 0},
-        {"test_level_three", reinterpret_cast<uintptr_t>(&test_level_three), 0},
-        {"test_level_four", reinterpret_cast<uintptr_t>(&test_level_four), 0},
-        {"test_recursive_call", reinterpret_cast<uintptr_t>(&test_recursive_call), 0},
-        {"GetContextAndExit", reinterpret_cast<uintptr_t>(&GetContextAndExit), 0},
-        {"unknown_end", static_cast<uintptr_t>(-1), static_cast<uintptr_t>(-1)},
-    };
-    std::sort(
-        symbols.begin(), symbols.end(),
-        [](const FunctionSymbol& s1, const FunctionSymbol& s2) { return s1.start < s2.start; });
-    for (size_t i = 0; i + 1 < symbols.size(); ++i) {
-      symbols[i].end = symbols[i + 1].start;
-    }
-  }
+static std::string FunctionNameForAddress(uintptr_t addr,
+                                          const std::vector<FunctionSymbol>& symbols) {
   for (auto& symbol : symbols) {
     if (addr >= symbol.start && addr < symbol.end) {
       return symbol.name;
@@ -155,35 +206,195 @@
   return "";
 }
 
-TEST(libbacktrace, offline) {
-  std::function<int(void (*)(void*), void*)> function =
-      std::bind(test_level_one, 1, 2, 3, 4, std::placeholders::_1, std::placeholders::_2);
+static std::string GetArch() {
+#if defined(__arm__)
+  return "arm";
+#elif defined(__aarch64__)
+  return "aarch64";
+#elif defined(__i386__)
+  return "x86";
+#elif defined(__x86_64__)
+  return "x86_64";
+#else
+  return "";
+#endif
+}
+
+struct OfflineTestData {
+  int pid;
+  int tid;
+  std::vector<backtrace_map_t> maps;
+  unw_context_t unw_context;
+  backtrace_stackinfo_t stack_info;
+  std::vector<uint8_t> stack;
+  std::vector<FunctionSymbol> symbols;
+};
+
+bool ReadOfflineTestData(const std::string offline_testdata_path, OfflineTestData* testdata) {
+  std::string s;
+  if (!android::base::ReadFileToString(offline_testdata_path, &s)) {
+    return false;
+  }
+  // Parse offline_testdata.
+  std::vector<std::string> lines = android::base::Split(s, "\n");
+  memset(&testdata->unw_context, 0, sizeof(testdata->unw_context));
+  for (const auto& line : lines) {
+    if (android::base::StartsWith(line, "pid:")) {
+      sscanf(line.c_str(), "pid: %d tid: %d", &testdata->pid, &testdata->tid);
+    } else if (android::base::StartsWith(line, "map:")) {
+      testdata->maps.resize(testdata->maps.size() + 1);
+      backtrace_map_t& map = testdata->maps.back();
+      int pos;
+      sscanf(line.c_str(),
+             "map: start: %" SCNxPTR " end: %" SCNxPTR " offset: %" SCNxPTR
+             " load_base: %" SCNxPTR " flags: %d name: %n",
+             &map.start, &map.end, &map.offset, &map.load_base, &map.flags, &pos);
+      map.name = android::base::Trim(line.substr(pos));
+    } else if (android::base::StartsWith(line, "registers:")) {
+      size_t size;
+      int pos;
+      sscanf(line.c_str(), "registers: %zu %n", &size, &pos);
+      if (sizeof(testdata->unw_context) != size) {
+        return false;
+      }
+      HexStringToRawData(&line[pos], &testdata->unw_context, size);
+    } else if (android::base::StartsWith(line, "stack:")) {
+      size_t size;
+      int pos;
+      sscanf(line.c_str(),
+             "stack: start: %" SCNx64 " end: %" SCNx64 " size: %zu %n",
+             &testdata->stack_info.start, &testdata->stack_info.end, &size, &pos);
+      testdata->stack.resize(size);
+      HexStringToRawData(&line[pos], &testdata->stack[0], size);
+      testdata->stack_info.data = testdata->stack.data();
+    } else if (android::base::StartsWith(line, "function:")) {
+      testdata->symbols.resize(testdata->symbols.size() + 1);
+      FunctionSymbol& symbol = testdata->symbols.back();
+      int pos;
+      sscanf(line.c_str(),
+             "function: start: %" SCNxPTR " end: %" SCNxPTR " name: %n",
+             &symbol.start, &symbol.end, &pos);
+      symbol.name = line.substr(pos);
+    }
+  }
+  return true;
+}
+
+static void BacktraceOfflineTest(const std::string& testlib_name) {
+  const std::string arch = GetArch();
+  if (arch.empty()) {
+    GTEST_LOG_(INFO) << "This test does nothing on current arch.";
+    return;
+  }
+  const std::string testlib_path = "testdata/" + arch + "/" + testlib_name;
+  struct stat st;
+  if (stat(testlib_path.c_str(), &st) == -1) {
+    GTEST_LOG_(INFO) << "This test is skipped as " << testlib_path << " doesn't exist.";
+    return;
+  }
+
+  const std::string offline_testdata_path = "testdata/" + arch + "/offline_testdata";
+  OfflineTestData testdata;
+  ASSERT_TRUE(ReadOfflineTestData(offline_testdata_path, &testdata));
+
+  // Fix path of libbacktrace_testlib.so.
+  for (auto& map : testdata.maps) {
+    if (map.name.find("libbacktrace_test.so") != std::string::npos) {
+      map.name = testlib_path;
+    }
+  }
+
+  // Do offline backtrace.
+  std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(testdata.pid, testdata.maps));
+  ASSERT_TRUE(map != nullptr);
+
+  std::unique_ptr<Backtrace> backtrace(
+      Backtrace::CreateOffline(testdata.pid, testdata.tid, map.get(), testdata.stack_info));
+  ASSERT_TRUE(backtrace != nullptr);
+
+  ucontext_t ucontext = GetUContextFromUnwContext(testdata.unw_context);
+  ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
+
+  // Collect pc values of the call stack frames.
   std::vector<uintptr_t> pc_values;
-  OfflineBacktraceFunctionCall(function, &pc_values);
-  ASSERT_FALSE(pc_values.empty());
-  ASSERT_LE(pc_values.size(), static_cast<size_t>(MAX_BACKTRACE_FRAMES));
+  for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
+    pc_values.push_back(backtrace->GetFrame(i)->pc);
+  }
 
   size_t test_one_index = 0;
   for (size_t i = 0; i < pc_values.size(); ++i) {
-    if (FunctionNameForAddress(pc_values[i]) == "test_level_one") {
+    if (FunctionNameForAddress(pc_values[i], testdata.symbols) == "test_level_one") {
       test_one_index = i;
       break;
     }
   }
 
   ASSERT_GE(test_one_index, 3u);
-  ASSERT_EQ("test_level_one", FunctionNameForAddress(pc_values[test_one_index]));
-  ASSERT_EQ("test_level_two", FunctionNameForAddress(pc_values[test_one_index - 1]));
-  ASSERT_EQ("test_level_three", FunctionNameForAddress(pc_values[test_one_index - 2]));
-  ASSERT_EQ("test_level_four", FunctionNameForAddress(pc_values[test_one_index - 3]));
+  ASSERT_EQ("test_level_one", FunctionNameForAddress(pc_values[test_one_index], testdata.symbols));
+  ASSERT_EQ("test_level_two", FunctionNameForAddress(pc_values[test_one_index - 1],
+                                                     testdata.symbols));
+  ASSERT_EQ("test_level_three", FunctionNameForAddress(pc_values[test_one_index - 2],
+                                                       testdata.symbols));
+  ASSERT_EQ("test_level_four", FunctionNameForAddress(pc_values[test_one_index - 3],
+                                                      testdata.symbols));
 }
 
-TEST(libbacktrace, offline_max_trace) {
-  std::function<int(void (*)(void*), void*)> function = std::bind(
-      test_recursive_call, MAX_BACKTRACE_FRAMES + 10, std::placeholders::_1, std::placeholders::_2);
-  std::vector<uintptr_t> pc_values;
-  OfflineBacktraceFunctionCall(function, &pc_values);
-  ASSERT_FALSE(pc_values.empty());
-  ASSERT_EQ(static_cast<size_t>(MAX_BACKTRACE_FRAMES), pc_values.size());
-  ASSERT_EQ("test_recursive_call", FunctionNameForAddress(pc_values.back()));
+TEST(libbacktrace, offline_eh_frame) {
+  BacktraceOfflineTest("libbacktrace_test_eh_frame.so");
+}
+
+TEST(libbacktrace, offline_debug_frame) {
+  BacktraceOfflineTest("libbacktrace_test_debug_frame.so");
+}
+
+TEST(libbacktrace, offline_gnu_debugdata) {
+  BacktraceOfflineTest("libbacktrace_test_gnu_debugdata.so");
+}
+
+TEST(libbacktrace, offline_arm_exidx) {
+  BacktraceOfflineTest("libbacktrace_test_arm_exidx.so");
+}
+
+// This test tests the situation that ranges of functions covered by .eh_frame and .ARM.exidx
+// overlap with each other, which appears in /system/lib/libart.so.
+TEST(libbacktrace, offline_unwind_mix_eh_frame_and_arm_exidx) {
+  const std::string arch = GetArch();
+  if (arch.empty() || arch != "arm") {
+    GTEST_LOG_(INFO) << "This test does nothing on current arch.";
+    return;
+  }
+  const std::string testlib_path = "testdata/" + arch + "/libart.so";
+  struct stat st;
+  ASSERT_EQ(0, stat(testlib_path.c_str(), &st)) << "can't find testlib " << testlib_path;
+
+  const std::string offline_testdata_path = "testdata/" + arch + "/offline_testdata_for_libart";
+  OfflineTestData testdata;
+  ASSERT_TRUE(ReadOfflineTestData(offline_testdata_path, &testdata));
+
+  // Fix path of /system/lib/libart.so.
+  for (auto& map : testdata.maps) {
+    if (map.name.find("libart.so") != std::string::npos) {
+      map.name = testlib_path;
+    }
+  }
+
+  // Do offline backtrace.
+  std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(testdata.pid, testdata.maps));
+  ASSERT_TRUE(map != nullptr);
+
+  std::unique_ptr<Backtrace> backtrace(
+      Backtrace::CreateOffline(testdata.pid, testdata.tid, map.get(), testdata.stack_info));
+  ASSERT_TRUE(backtrace != nullptr);
+
+  ucontext_t ucontext = GetUContextFromUnwContext(testdata.unw_context);
+  ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
+
+  // The last frame is outside of libart.so
+  ASSERT_EQ(testdata.symbols.size() + 1, backtrace->NumFrames());
+  for (size_t i = 0; i + 1 < backtrace->NumFrames(); ++i) {
+    uintptr_t vaddr_in_file = backtrace->GetFrame(i)->pc - testdata.maps[0].start +
+        testdata.maps[0].load_base;
+    std::string name = FunctionNameForAddress(vaddr_in_file, testdata.symbols);
+    ASSERT_EQ(name, testdata.symbols[i].name);
+  }
 }
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index 913e12d..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,27 +411,26 @@
 }
 
 // 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);
 
-  DIR* tasks_dir = opendir(task_path);
+  std::unique_ptr<DIR, decltype(&closedir)> tasks_dir(opendir(task_path), closedir);
   ASSERT_TRUE(tasks_dir != nullptr);
   struct dirent* entry;
-  while ((entry = readdir(tasks_dir)) != nullptr) {
+  while ((entry = readdir(tasks_dir.get())) != nullptr) {
     char* end;
     pid_t tid = strtoul(entry->d_name, &end, 10);
     if (*end == '\0') {
       threads->push_back(tid);
     }
   }
-  closedir(tasks_dir);
 }
 
 TEST(libbacktrace, ptrace_threads) {
@@ -462,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*) {
@@ -482,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));
@@ -495,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();
@@ -586,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();
@@ -617,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)) {
@@ -874,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);
 
@@ -909,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') {
@@ -942,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();
@@ -983,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.
@@ -1044,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;
@@ -1118,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;
@@ -1138,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
@@ -1294,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)) {
@@ -1313,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);
 
@@ -1325,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);
@@ -1419,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
+#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);
@@ -1446,9 +1768,9 @@
   }
   size_t new_pss = GetPssBytes();
   ASSERT_TRUE(new_pss != 0);
-  size_t abs_diff = (new_pss > stable_pss) ? new_pss - stable_pss : stable_pss - new_pss;
-  // As long as the new pss is within a certain amount, consider everything okay.
-  ASSERT_LE(abs_diff, MAX_LEAK_BYTES);
+  if (new_pss > stable_pss) {
+    ASSERT_LE(new_pss - stable_pss, MAX_LEAK_BYTES);
+  }
 }
 
 TEST(libbacktrace, check_for_leak_local) {
@@ -1473,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.c
deleted file mode 100644
index d4d15db..0000000
--- a/libbacktrace/backtrace_testlib.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-
-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) {
-    }
-  }
-  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_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_recursive_call(int level, void (*callback_func)(void*), void* data) {
-  if (level > 0) {
-    return test_recursive_call(level - 1, callback_func, data) + level;
-  } else if (callback_func != NULL) {
-    callback_func(data);
-  } else {
-    while (1) {
-    }
-  }
-  return 0;
-}
diff --git a/libbacktrace/backtrace_testlib.cpp b/libbacktrace/backtrace_testlib.cpp
new file mode 100644
index 0000000..3081d64
--- /dev/null
+++ b/libbacktrace/backtrace_testlib.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <libunwind.h>
+#include <signal.h>
+#include <stdio.h>
+
+#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)
+      ;
+  }
+  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_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_recursive_call(int level, void (*callback_func)(void*), void* data) {
+  if (level > 0) {
+    return test_recursive_call(level - 1, callback_func, data) + level;
+  } else if (callback_func != NULL) {
+    callback_func(data);
+  } else {
+    while (1) {
+    }
+  }
+  return 0;
+}
+
+typedef struct {
+  unw_context_t* unw_context;
+  volatile int* exit_flag;
+} GetContextArg;
+
+static void GetContextAndExit(void* data) {
+  GetContextArg* arg = (GetContextArg*)data;
+  unw_getcontext(arg->unw_context);
+  // Don't touch the stack anymore.
+  while (*arg->exit_flag == 0) {
+  }
+}
+
+void test_get_context_and_wait(unw_context_t* unw_context, volatile int* exit_flag) {
+  GetContextArg arg;
+  arg.unw_context = unw_context;
+  arg.exit_flag = exit_flag;
+  test_level_one(1, 2, 3, 4, GetContextAndExit, &arg);
+}
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/libbacktrace/include/backtrace/Backtrace.h b/libbacktrace/include/backtrace/Backtrace.h
new file mode 100644
index 0000000..4f73a65
--- /dev/null
+++ b/libbacktrace/include/backtrace/Backtrace.h
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BACKTRACE_BACKTRACE_H
+#define _BACKTRACE_BACKTRACE_H
+
+#include <inttypes.h>
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+#include <backtrace/backtrace_constants.h>
+#include <backtrace/BacktraceMap.h>
+
+#if __LP64__
+#define PRIPTR "016" PRIxPTR
+typedef uint64_t word_t;
+#else
+#define PRIPTR "08" PRIxPTR
+typedef uint32_t word_t;
+#endif
+
+enum BacktraceUnwindError : uint32_t {
+  BACKTRACE_UNWIND_NO_ERROR,
+  // Something failed while trying to perform the setup to begin the unwind.
+  BACKTRACE_UNWIND_ERROR_SETUP_FAILED,
+  // There is no map information to use with the unwind.
+  BACKTRACE_UNWIND_ERROR_MAP_MISSING,
+  // An error occurred that indicates a programming error.
+  BACKTRACE_UNWIND_ERROR_INTERNAL,
+  // The thread to unwind has disappeared before the unwind can begin.
+  BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST,
+  // The thread to unwind has not responded to a signal in a timely manner.
+  BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT,
+  // Attempt to do an unsupported operation.
+  BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION,
+  // Attempt to do an offline unwind without a context.
+  BACKTRACE_UNWIND_ERROR_NO_CONTEXT,
+};
+
+struct backtrace_frame_data_t {
+  size_t num;             // The current fame number.
+  uintptr_t pc;           // The absolute pc.
+  uintptr_t sp;           // The top of the stack.
+  size_t stack_size;      // The size of the stack, zero indicate an unknown stack size.
+  backtrace_map_t map;    // The map associated with the given pc.
+  std::string func_name;  // The function name associated with this pc, NULL if not found.
+  uintptr_t func_offset;  // pc relative to the start of the function, only valid if func_name is not NULL.
+};
+
+#if defined(__APPLE__)
+struct __darwin_ucontext;
+typedef __darwin_ucontext ucontext_t;
+#else
+struct ucontext;
+typedef ucontext ucontext_t;
+#endif
+
+struct backtrace_stackinfo_t {
+  uint64_t start;
+  uint64_t end;
+  const uint8_t* data;
+};
+
+class Backtrace {
+public:
+  // Create the correct Backtrace object based on what is to be unwound.
+  // If pid < 0 or equals the current pid, then the Backtrace object
+  // corresponds to the current process.
+  // If pid < 0 or equals the current pid and tid >= 0, then the Backtrace
+  // object corresponds to a thread in the current process.
+  // If pid >= 0 and tid < 0, then the Backtrace object corresponds to a
+  // different process.
+  // Tracing a thread in a different process is not supported.
+  // If map is NULL, then create the map and manage it internally.
+  // If map is not NULL, the map is still owned by the caller.
+  static Backtrace* Create(pid_t pid, pid_t tid, BacktraceMap* map = NULL);
+
+  // Create an offline Backtrace object that can be used to do an unwind without a process
+  // that is still running. If cache_file is set to true, then elf information will be cached
+  // for this call. The cached information survives until the calling process ends. This means
+  // that subsequent calls to create offline Backtrace objects will continue to use the same
+  // cache. It also assumes that the elf files used for each offline unwind are the same.
+  static Backtrace* CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
+                                  const backtrace_stackinfo_t& stack, bool cache_file = false);
+
+  virtual ~Backtrace();
+
+  // Get the current stack trace and store in the backtrace_ structure.
+  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,
+  // 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);
+
+  // Read the data at a specific address.
+  virtual bool ReadWord(uintptr_t ptr, word_t* out_value) = 0;
+
+  // Read arbitrary data from a specific address. If a read request would
+  // span from one map to another, this call only reads up until the end
+  // of the current map.
+  // Returns the total number of bytes actually read.
+  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) = 0;
+
+  // Create a string representing the formatted line of backtrace information
+  // for a single frame.
+  virtual std::string FormatFrameData(size_t frame_num);
+  virtual std::string FormatFrameData(const backtrace_frame_data_t* frame);
+
+  pid_t Pid() const { return pid_; }
+  pid_t Tid() const { return tid_; }
+  size_t NumFrames() const { return frames_.size(); }
+
+  const backtrace_frame_data_t* GetFrame(size_t frame_num) {
+    if (frame_num >= frames_.size()) {
+      return NULL;
+    }
+    return &frames_[frame_num];
+  }
+
+  typedef std::vector<backtrace_frame_data_t>::iterator iterator;
+  iterator begin() { return frames_.begin(); }
+  iterator end() { return frames_.end(); }
+
+  typedef std::vector<backtrace_frame_data_t>::const_iterator const_iterator;
+  const_iterator begin() const { return frames_.begin(); }
+  const_iterator end() const { return frames_.end(); }
+
+  BacktraceMap* GetMap() { return map_; }
+
+  BacktraceUnwindError GetError() { return error_; }
+
+  std::string GetErrorString(BacktraceUnwindError error);
+
+protected:
+  Backtrace(pid_t pid, pid_t tid, BacktraceMap* map);
+
+  // The name returned is not demangled, GetFunctionName() takes care of
+  // demangling the name.
+  virtual std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) = 0;
+
+  virtual bool VerifyReadWordArgs(uintptr_t ptr, word_t* out_value);
+
+  bool BuildMap();
+
+  pid_t pid_;
+  pid_t tid_;
+
+  BacktraceMap* map_;
+  bool map_shared_;
+
+  std::vector<backtrace_frame_data_t> frames_;
+
+  BacktraceUnwindError error_;
+};
+
+#endif // _BACKTRACE_BACKTRACE_H
diff --git a/libbacktrace/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
new file mode 100644
index 0000000..8ab0dfa
--- /dev/null
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -0,0 +1,129 @@
+/*
+ * 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 _BACKTRACE_BACKTRACE_MAP_H
+#define _BACKTRACE_BACKTRACE_MAP_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#ifdef _WIN32
+// MINGW does not define these constants.
+#define PROT_NONE 0
+#define PROT_READ 0x1
+#define PROT_WRITE 0x2
+#define PROT_EXEC 0x4
+#else
+#include <sys/mman.h>
+#endif
+
+#include <deque>
+#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;
+  uintptr_t offset = 0;
+  uintptr_t load_base = 0;
+  int flags = 0;
+  std::string name;
+};
+
+class BacktraceMap {
+public:
+  // If uncached is true, then parse the current process map as of the call.
+  // Passing a map created with uncached set to true to Backtrace::Create()
+  // is unsupported.
+  static BacktraceMap* Create(pid_t pid, bool uncached = false);
+
+  static BacktraceMap* Create(pid_t pid, const std::vector<backtrace_map_t>& maps);
+
+  virtual ~BacktraceMap();
+
+  // Fill in the map data structure for the given address.
+  virtual void FillIn(uintptr_t addr, backtrace_map_t* map);
+
+  // The flags returned are the same flags as used by the mmap call.
+  // The values are PROT_*.
+  int GetFlags(uintptr_t pc) {
+    backtrace_map_t map;
+    FillIn(pc, &map);
+    if (IsValid(map)) {
+      return map.flags;
+    }
+    return PROT_NONE;
+  }
+
+  bool IsReadable(uintptr_t pc) { return GetFlags(pc) & PROT_READ; }
+  bool IsWritable(uintptr_t pc) { return GetFlags(pc) & PROT_WRITE; }
+  bool IsExecutable(uintptr_t pc) { return GetFlags(pc) & PROT_EXEC; }
+
+  // In order to use the iterators on this object, a caller must
+  // call the LockIterator and UnlockIterator function to guarantee
+  // that the data does not change while it's being used.
+  virtual void LockIterator() {}
+  virtual void UnlockIterator() {}
+
+  typedef std::deque<backtrace_map_t>::iterator iterator;
+  iterator begin() { return maps_.begin(); }
+  iterator end() { return maps_.end(); }
+
+  typedef std::deque<backtrace_map_t>::const_iterator const_iterator;
+  const_iterator begin() const { return maps_.begin(); }
+  const_iterator end() const { return maps_.end(); }
+
+  virtual bool Build();
+
+  static inline bool IsValid(const backtrace_map_t& map) {
+    return map.end > 0;
+  }
+
+  static uintptr_t GetRelativePc(const backtrace_map_t& map, uintptr_t pc) {
+    if (IsValid(map)) {
+      return pc - map.start + map.load_base;
+    } else {
+      return pc;
+    }
+  }
+
+protected:
+  BacktraceMap(pid_t pid);
+
+  virtual bool ParseLine(const char* line, backtrace_map_t* map);
+
+  std::deque<backtrace_map_t> maps_;
+  pid_t pid_;
+};
+
+class ScopedBacktraceMapIteratorLock {
+public:
+  explicit ScopedBacktraceMapIteratorLock(BacktraceMap* map) : map_(map) {
+    map->LockIterator();
+  }
+
+  ~ScopedBacktraceMapIteratorLock() {
+    map_->UnlockIterator();
+  }
+
+private:
+  BacktraceMap* map_;
+};
+
+#endif // _BACKTRACE_BACKTRACE_MAP_H
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/libbacktrace/testdata/aarch64/libbacktrace_test_eh_frame.so b/libbacktrace/testdata/aarch64/libbacktrace_test_eh_frame.so
new file mode 100755
index 0000000..880f337
--- /dev/null
+++ b/libbacktrace/testdata/aarch64/libbacktrace_test_eh_frame.so
Binary files differ
diff --git a/libbacktrace/testdata/aarch64/offline_testdata b/libbacktrace/testdata/aarch64/offline_testdata
new file mode 100644
index 0000000..ba44e09
--- /dev/null
+++ b/libbacktrace/testdata/aarch64/offline_testdata
@@ -0,0 +1,107 @@
+pid: 32438 tid: 32439
+map: start: 557066e000 end: 55706ee000 offset: 0 load_base: 0 flags: 5 name: /data/backtrace_test64
+map: start: 55706ef000 end: 55706f2000 offset: 80000 load_base: 0 flags: 1 name: /data/backtrace_test64
+map: start: 55706f2000 end: 55706f3000 offset: 83000 load_base: 0 flags: 3 name: /data/backtrace_test64
+map: start: 7014200000 end: 7014600000 offset: 0 load_base: 0 flags: 3 name: [anon:libc_malloc]
+map: start: 701464c000 end: 701465c000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libcutils.so
+map: start: 701465c000 end: 701465d000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 701465d000 end: 701465e000 offset: 10000 load_base: 0 flags: 1 name: /system/lib64/libcutils.so
+map: start: 701465e000 end: 701465f000 offset: 11000 load_base: 0 flags: 3 name: /system/lib64/libcutils.so
+map: start: 7014691000 end: 70146b5000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/liblzma.so
+map: start: 70146b5000 end: 70146b6000 offset: 23000 load_base: 0 flags: 1 name: /system/lib64/liblzma.so
+map: start: 70146b6000 end: 70146b7000 offset: 24000 load_base: 0 flags: 3 name: /system/lib64/liblzma.so
+map: start: 70146b7000 end: 70146bc000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 70146c9000 end: 70158b5000 offset: 0 load_base: af000 flags: 5 name: /system/lib64/libLLVM.so
+map: start: 70158b5000 end: 701596b000 offset: 11eb000 load_base: 0 flags: 1 name: /system/lib64/libLLVM.so
+map: start: 701596b000 end: 701596c000 offset: 12a1000 load_base: 0 flags: 3 name: /system/lib64/libLLVM.so
+map: start: 701596c000 end: 701599f000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 70159c2000 end: 70159f9000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libm.so
+map: start: 70159f9000 end: 70159fa000 offset: 36000 load_base: 0 flags: 1 name: /system/lib64/libm.so
+map: start: 70159fa000 end: 70159fb000 offset: 37000 load_base: 0 flags: 3 name: /system/lib64/libm.so
+map: start: 7015a1e000 end: 7015a2e000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libbacktrace.so
+map: start: 7015a2e000 end: 7015a2f000 offset: f000 load_base: 0 flags: 1 name: /system/lib64/libbacktrace.so
+map: start: 7015a2f000 end: 7015a30000 offset: 10000 load_base: 0 flags: 3 name: /system/lib64/libbacktrace.so
+map: start: 7015a5e000 end: 7015a7d000 offset: 0 load_base: 1000 flags: 5 name: /system/lib64/libutils.so
+map: start: 7015a7d000 end: 7015a7e000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 7015a7e000 end: 7015a7f000 offset: 1f000 load_base: 0 flags: 1 name: /system/lib64/libutils.so
+map: start: 7015a7f000 end: 7015a80000 offset: 20000 load_base: 0 flags: 3 name: /system/lib64/libutils.so
+map: start: 7015a99000 end: 7015b6d000 offset: 0 load_base: 9000 flags: 5 name: /system/lib64/libc++.so
+map: start: 7015b6d000 end: 7015b6e000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 7015b6e000 end: 7015b76000 offset: d4000 load_base: 0 flags: 1 name: /system/lib64/libc++.so
+map: start: 7015b76000 end: 7015b77000 offset: dc000 load_base: 0 flags: 3 name: /system/lib64/libc++.so
+map: start: 7015b77000 end: 7015b7a000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 7015b81000 end: 7015b92000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/liblog.so
+map: start: 7015b92000 end: 7015b93000 offset: 10000 load_base: 0 flags: 1 name: /system/lib64/liblog.so
+map: start: 7015b93000 end: 7015b94000 offset: 11000 load_base: 0 flags: 3 name: /system/lib64/liblog.so
+map: start: 7015be3000 end: 7015ca3000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libc.so
+map: start: 7015ca3000 end: 7015ca9000 offset: bf000 load_base: 0 flags: 1 name: /system/lib64/libc.so
+map: start: 7015ca9000 end: 7015cab000 offset: c5000 load_base: 0 flags: 3 name: /system/lib64/libc.so
+map: start: 7015cab000 end: 7015cac000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 7015cac000 end: 7015cad000 offset: 0 load_base: 0 flags: 1 name: [anon:.bss]
+map: start: 7015cad000 end: 7015cb4000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 7015cf5000 end: 7015cf6000 offset: 0 load_base: 0 flags: 5 name: /data/libbacktrace_test.so
+map: start: 7015cf6000 end: 7015cf7000 offset: 0 load_base: 0 flags: 1 name: /data/libbacktrace_test.so
+map: start: 7015cf7000 end: 7015cf8000 offset: 1000 load_base: 0 flags: 3 name: /data/libbacktrace_test.so
+map: start: 7015d1f000 end: 7015d39000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libunwind.so
+map: start: 7015d39000 end: 7015d3a000 offset: 19000 load_base: 0 flags: 1 name: /system/lib64/libunwind.so
+map: start: 7015d3a000 end: 7015d3b000 offset: 1a000 load_base: 0 flags: 3 name: /system/lib64/libunwind.so
+map: start: 7015d3b000 end: 7015da4000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: 7015de8000 end: 7015df7000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libbase.so
+map: start: 7015df7000 end: 7015df8000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 7015df8000 end: 7015df9000 offset: f000 load_base: 0 flags: 1 name: /system/lib64/libbase.so
+map: start: 7015df9000 end: 7015dfa000 offset: 10000 load_base: 0 flags: 3 name: /system/lib64/libbase.so
+map: start: 7015e35000 end: 7015e36000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc]
+map: start: 7015e4f000 end: 7015e50000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 7015f11000 end: 7015f13000 offset: 0 load_base: 0 flags: 5 name: /system/lib64/libnetd_client.so
+map: start: 7015f13000 end: 7015f14000 offset: 1000 load_base: 0 flags: 1 name: /system/lib64/libnetd_client.so
+map: start: 7015f14000 end: 7015f15000 offset: 2000 load_base: 0 flags: 3 name: /system/lib64/libnetd_client.so
+map: start: 7015f6c000 end: 7015f79000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7015f79000 end: 7015f99000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/u:object_r:default_prop:s0
+map: start: 7015f99000 end: 7015f9a000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 7015f9a000 end: 7015f9b000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 7015fa6000 end: 7015fa7000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 7015fa8000 end: 7015fa9000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: 7015faf000 end: 7015fcf000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/properties_serial
+map: start: 7015fcf000 end: 7015fd0000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 7015fd0000 end: 7015fd1000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 7015fd1000 end: 7015fd2000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 7015fd4000 end: 7015fd7000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7015fd7000 end: 7015fdb000 offset: 0 load_base: 0 flags: 1 name: [anon:atexit handlers]
+map: start: 7015fdb000 end: 7015fdc000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc]
+map: start: 7015fdc000 end: 7015fdd000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7015fdd000 end: 7015fde000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: 7015fde000 end: 7015ffe000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/u:object_r:debug_prop:s0
+map: start: 7015ffe000 end: 701601e000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/properties_serial
+map: start: 701601e000 end: 701601f000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 701601f000 end: 7016020000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 7016020000 end: 7016021000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7016021000 end: 7016022000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: 7016022000 end: 7016023000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_lob]
+map: start: 7016023000 end: 7016025000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: 7016025000 end: 7016026000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 7016026000 end: 7016027000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: 7016027000 end: 7016028000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 7016028000 end: 7016029000 offset: 0 load_base: 0 flags: 3 name: [anon:arc4random data]
+map: start: 7016029000 end: 701602a000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: 701602a000 end: 701602b000 offset: 0 load_base: 0 flags: 1 name: [anon:atexit handlers]
+map: start: 701602b000 end: 701602c000 offset: 0 load_base: 0 flags: 0 name: [anon:thread signal stack guard page]
+map: start: 701602c000 end: 7016030000 offset: 0 load_base: 0 flags: 3 name: [anon:thread signal stack]
+map: start: 7016030000 end: 7016031000 offset: 0 load_base: 0 flags: 3 name: [anon:arc4random data]
+map: start: 7016031000 end: 7016033000 offset: 0 load_base: 0 flags: 5 name: [vdso]
+map: start: 7016033000 end: 70160dd000 offset: 0 load_base: 0 flags: 5 name: /system/bin/linker64
+map: start: 70160dd000 end: 70160e0000 offset: a9000 load_base: 0 flags: 1 name: /system/bin/linker64
+map: start: 70160e0000 end: 70160e1000 offset: ac000 load_base: 0 flags: 3 name: /system/bin/linker64
+map: start: 70160e1000 end: 70160e4000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 70160e4000 end: 70160e5000 offset: 0 load_base: 0 flags: 1 name: 
+map: start: 70160e5000 end: 70160e8000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd8baf000 end: 7fd8be6000 offset: 0 load_base: 0 flags: 3 name: [stack]
+registers: 4560 679a0b1670000000f3eb6d705500000090f56e7055000000000000000000000000206f705500000014e0677055000000d038bed87f0000004cde67705500000041000000000000001900000000000000c00f241470000000d3aec914588f4bcd0400000000000000e493af157000000090f56e7055000000060000000000000023c00b1670000000b1d1fd15700000003039bed87f000000c898041670000000304cbed87f000000b8130e1670000000303cbed87f000000f838bed87f0000000e0000000000000015000000000000001c00000000000000ec59cf1570000000b863fd15700000005064fd15700000000000000000000000ec59cf15700000000200000000000000b863fd1570000000144abed87f0000006064fd15700000005064fd157000000000010000000000005826bed87f000000d86fcf15700000006057cf157000000000000000000000005064fd15700000005064fd15700000005064fd1570000000b67e00000000000040fd677055000000d064fd15700000000030fd157000000002000000000000000100000000000000fcb58a56000000000063fd15700000009857cf1570000000c062fd15700000001c5acf157000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000003003167000000001000000030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000033000000000000000300000000000000003303167000000008330316700000000000000006000000f8320316700000005839bed87f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000c84cbed87f000000e84cbed87f000000984dbed87f00000078170e167000000002fd0000000000001400000000000000ff8100000100000000000000000000000000000000000000000000000000000078145700000000000010000000000000902b000000000000bdd04058000000000000000000000000bdd04058000000000000000000000000ccb58a560000000042487408000000000000000000000000cc57041670000000004704167000000010c0fd157000000010c0fd157000000090c0fd15700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000010000000000000002f48bed87f000000d3aec914588f4bcd2045bed87f0000002045bed87f0000002f48bed87f00000001000000000000002f000080000000005045bed87f0000000045bed87f000000c0a0c315700000006045bed87f0000006045bed87f000000010000000000000001000000000000000344bed87f00000001000000100000009c3fbed87f0000009b3fbed87f0000000344bed87f0000009a3fbed87f0000000100000000000000953fbed87f0000004344bed80100000001000000010000002c48bed87f0000000444bed87f0000004344bed80100000000000000000000000100000000000000b03fbed87f000000000000000200000000000000000000000000000000000000d3aec914588f4bcd000000000100000000000000000000000100000000000000f03fbed87f000000000000000200000000000000000000000000000000000000d3aec914588f4bcd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a03fbed87f0000000000000000000000000000000000000000000000000000000000000000000000d3aec914588f4bcd08226f70550000000000000000000000000000000000000000000000000000001048bed87f0000008047bed87f0000006047bed87f000000e0ffffff80ffffff03000000000000000000000000000000891d6e7055000000d3aec914588f4bcd5047bed87f0000005047bed87f000000861d6e705500000003000000000000002f00008000000000f0a6ca15700000004047bed87f000000c0a0c31570000000891d6e7055000000d3aec914000000000100000000000000a047bed800000000f9006e70550000000100000000000000dc41bed87f000000db41bed87f0000004346bed87f000000da41bed87f0000000100000000000000d541bed87f00000001000000010000000100000001000000861d6e70550000004446bed87f0000002c42bed80300000000000000000000000100000000000000f041bed87f0000009b1e6e700100000000000000000000000000000000000000d3aec914588f4bcd8e1e6e70550000000d000000000000002f00008000000000f0a6ca15700000003048bed87f000000c0a0c31570000000661e6e700100000000000000000000002f000000000000001000000000000000e21e6e7055000000d3aec914588f4bcdb048bed87f000000b048bed87f000000e21e6e70550000002f000000000000002f00008000000000f0a6ca1570000000a048bed87f000000c0a0c315700000008e1e6e7055000000000000000000000022000000000000000000000000000000205827147000000022000000000000003c43bed87f0000003b43bed87f000000a347bed87f0000003a43bed87f00000001000000000000003543bed87f000000f048bed8010000000100000001000000dd1e6e7055000000a447bed87f0000008c43bed82f000000000000000000000001000000000000005043bed87f000000861d6e700300000000000000000000000000000000000000d3aec914588f4bcd721e6e7055000000f447bed87f000000981123141800000000000000000000000100000000000000a043bed87f000000861d6e70030000000000000000000000d042bed87f0000000000000000000000981123147000000098112314700000009811231470000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000504abed87f000000b049bed87f0000008049bed87f00000000000000000000004043bed87f0000000000000000000000991123147000000000000000000000008e1e6e70550000000d00000000000000a04abed87f000000000000000000000000000000000000000000000000000000504abed87f000000e049bed87f000000a049bed87f000000c8ffffff80ffffff591e6e70550000000d0000000000000098112314700000000000000000000000df1e6e7055000000010000000000000020582714700000002200000000000000f049bed87f000000c8ffffff80ffffff9811231470000000980023147000000098112314700000009811231470000000741e6e7055000000060000000000000009f12914700000000c00000000000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b149bed87f000000b149bed87f000000f049be317f000000f049bed87f000000f049bed87f000000b149bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000b049bed87f000000f149bed87f000000f049bed87f000000d3aec914588f4bcdfcb58a56000000006cbb687055000000160000000000000098112314700000009911231470000000991123147000000098112314700000009911231470000000fcb58a5600000000010000000000000000000000000000000100000000000000604a050000000000e845bed87f0000006048bed87f000000a046bed87f00000017000000000000002c48bed87f0000009046bed87f000000ac73c515700000009911231470000000d3aec914588f4bcd1048bed87f0000008047bed87f0000006047bed87f000000e8ffffff80ffffffffffffffffffffff99112314700000006148bed87f000000981123141500000008020000ffffffff6048bed87f000000160000000000000058112314700000001700000000000000a849bed87f0000000000000000000000284abed87f0000001700000000000000284abed87f000000284abed87f000000d249bed87f00000001000000000000009a112314700000001600000000000000284abed87f000000ffffffffffffffff284abed87f000000284abed87f000000284abed87f000000284abed87f0000001700000000000000ffffffffffffffff284abed87f000000284abed87f000000ff49bed87f000000284abed87f00000000000000000000000000000000000000d049bed87f000000d049bed87f000000004abed87f000000d049bed87f0000000100000000000000d049bed87f000000d049bed87f000000d049bed87f00000017000000000000000100000000000000ffffffffffffffff991123147000000001000000000000003448bed87f0000009911231470000000b0ca687055000000ffffffffffffffff010000000000000099112314700000007047bed87f000000d3aec914588f4bcdfcb58a56000000000100000000000000000000000000000050226f70550000000000000000000000b44b05000000000000102a1470000000861d6e70550000000300000000000000f0a6ca1570000000a047bed87f0000006c79c31570000000f048bed87f0000008048bed87f0000004048bed87f000000c8ffffff80ffffff0000000000000000d3aec914588f4bcdf849bed87f000000f0a6ca15700000000200000000000000085b0e1670000000e048bed87f0000002c6fc515700000009048bed87f000000d3aec914588f4bcd0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a89912314700000000000000000000000e9216f70550000008991231470000000e449bed87f0000008991231470000000000000000000000000000000000000008891231470000000899123147000000089912314700000008891231470000000170000000000000088912314700000008891231470000000d3aec914588f4bcd899123147000000016000000000000000000000000000000e9216f705500000088912314700000008891231470000000889123147000000088912314700000008891231470000000f0a6ca15700000000049bed87f0000006c79c31570000000889123147000000088912314700000008891231470000000889123147000000088912314700000008891231470000000889123147000000089912314700000008991231470000000085b0e1670000000404abed87f0000002c6fc51570000000c80a6f7055000000d3aec914588f4bcd0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a3b3325736d001b5b6d002c20776865726520002573203d202573000a526570650000000000000000000000000000000000000000000000008891231470000000000000000000000088912314700000008891231470000000889123147000000088912314700000000000000000000000889123147000000088912314700000008891231470000000470000000000000000502a1470000000d3aec914588f4bcdf05727147000000000b2221470000000604abed87f0000005c716c7055000000fcb58a56000000007c706c7055000000fcb58a5600000000ea4b050000000000
+stack: start: 7015fd3000 end: 7015fd7000 size: 16384 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f838bed87f0000004038bed87f000000b863fd1570000000b863fd1570000000b863fd1570000000ec59cf15700000001c000000150000000e000000070000003063fd15700000001c58cf1570000000b863fd1570000000ec59cf1570000000100000000c00000008000000040000006063fd15700000007c58cf1570000000b863fd1570000000ec59cf1570000000080000000600000004000000020000009063fd1570000000dc58cf1570000000b863fd1570000000ec59cf157000000004000000030000000200000001000000d063fd1570000000c459cf15700000000100000000000000144abed87f0000004038bed87f0000004038bed87f000000144abed87f000000d3aec914588f4bcd1064fd157000000074fd6770550000004038bed87f0000004038bed87f000000ec84c41570000000e484c41570000000c484c4157000000000000000000000004064fd15700000004015c01570000000b67e0000000000000000000000000000705a0e1670000000185b0e167000000000000000000000000000000000000000705a0e16700000000000000000000000b77e0000b67e000000000000550000000030fd157000000050340000000000000010000000000000000000000000000000b222147000000000102a14700000000000000000000000000000000000000040fd6770550000004038bed87f000000000000000000000000a0fa1570000000010000000000000000000000000000000000000000000000e864fd15700000005064fd1570000000000000000000000000000000000000000000000000000000d3aec914588f4bcd0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+function: start: 0 end: 7015cf5760 name: unknown_start
+function: start: 7015cf5760 end: 7015cf57cc name: test_level_four
+function: start: 7015cf57cc end: 7015cf582c name: test_level_three
+function: start: 7015cf582c end: 7015cf588c name: test_level_two
+function: start: 7015cf588c end: 7015cf58ec name: test_level_one
+function: start: 7015cf58ec end: 7015cf5968 name: test_recursive_call
+function: start: 7015cf5968 end: ffffffffffffffff name: test_get_context_and_wait
+function: start: ffffffffffffffff end: ffffffffffffffff name: unknown_end
diff --git a/libbacktrace/testdata/arm/libart.so b/libbacktrace/testdata/arm/libart.so
new file mode 100644
index 0000000..bed8e35
--- /dev/null
+++ b/libbacktrace/testdata/arm/libart.so
Binary files differ
diff --git a/libbacktrace/testdata/arm/libbacktrace_test_arm_exidx.so b/libbacktrace/testdata/arm/libbacktrace_test_arm_exidx.so
new file mode 100755
index 0000000..454b032
--- /dev/null
+++ b/libbacktrace/testdata/arm/libbacktrace_test_arm_exidx.so
Binary files differ
diff --git a/libbacktrace/testdata/arm/libbacktrace_test_debug_frame.so b/libbacktrace/testdata/arm/libbacktrace_test_debug_frame.so
new file mode 100755
index 0000000..787f2cb
--- /dev/null
+++ b/libbacktrace/testdata/arm/libbacktrace_test_debug_frame.so
Binary files differ
diff --git a/libbacktrace/testdata/arm/libbacktrace_test_gnu_debugdata.so b/libbacktrace/testdata/arm/libbacktrace_test_gnu_debugdata.so
new file mode 100755
index 0000000..9340d98
--- /dev/null
+++ b/libbacktrace/testdata/arm/libbacktrace_test_gnu_debugdata.so
Binary files differ
diff --git a/libbacktrace/testdata/arm/offline_testdata b/libbacktrace/testdata/arm/offline_testdata
new file mode 100644
index 0000000..43d305a
--- /dev/null
+++ b/libbacktrace/testdata/arm/offline_testdata
@@ -0,0 +1,105 @@
+pid: 32232 tid: 32233
+map: start: aad19000 end: aad6c000 offset: 0 load_base: 0 flags: 5 name: /data/backtrace_test32
+map: start: aad6c000 end: aad6e000 offset: 52000 load_base: 0 flags: 1 name: /data/backtrace_test32
+map: start: aad6e000 end: aad6f000 offset: 54000 load_base: 0 flags: 3 name: /data/backtrace_test32
+map: start: e7380000 end: e7400000 offset: 0 load_base: 0 flags: 3 name: [anon:libc_malloc]
+map: start: e745f000 end: e7463000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libnetd_client.so
+map: start: e7463000 end: e7464000 offset: 3000 load_base: 0 flags: 1 name: /system/lib/libnetd_client.so
+map: start: e7464000 end: e7465000 offset: 4000 load_base: 0 flags: 3 name: /system/lib/libnetd_client.so
+map: start: e7480000 end: e7500000 offset: 0 load_base: 0 flags: 3 name: [anon:libc_malloc]
+map: start: e7558000 end: e756c000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libunwind.so
+map: start: e756c000 end: e756d000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e756d000 end: e756e000 offset: 14000 load_base: 0 flags: 1 name: /system/lib/libunwind.so
+map: start: e756e000 end: e756f000 offset: 15000 load_base: 0 flags: 3 name: /system/lib/libunwind.so
+map: start: e756f000 end: e75b5000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e75d4000 end: e75e1000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libbase.so
+map: start: e75e1000 end: e75e2000 offset: c000 load_base: 0 flags: 1 name: /system/lib/libbase.so
+map: start: e75e2000 end: e75e3000 offset: d000 load_base: 0 flags: 3 name: /system/lib/libbase.so
+map: start: e7600000 end: e7616000 offset: 0 load_base: 0 flags: 5 name: /system/lib/liblzma.so
+map: start: e7616000 end: e7617000 offset: 15000 load_base: 0 flags: 1 name: /system/lib/liblzma.so
+map: start: e7617000 end: e7618000 offset: 16000 load_base: 0 flags: 3 name: /system/lib/liblzma.so
+map: start: e7618000 end: e761d000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e7647000 end: e7656000 offset: 0 load_base: 0 flags: 5 name: /system/lib/liblog.so
+map: start: e7656000 end: e7657000 offset: e000 load_base: 0 flags: 1 name: /system/lib/liblog.so
+map: start: e7657000 end: e7658000 offset: f000 load_base: 0 flags: 3 name: /system/lib/liblog.so
+map: start: e7681000 end: e76a2000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libm.so
+map: start: e76a2000 end: e76a3000 offset: 20000 load_base: 0 flags: 1 name: /system/lib/libm.so
+map: start: e76a3000 end: e76a4000 offset: 21000 load_base: 0 flags: 3 name: /system/lib/libm.so
+map: start: e76eb000 end: e76ee000 offset: 0 load_base: 0 flags: 5 name: /data/libbacktrace_test.so
+map: start: e76ee000 end: e76ef000 offset: 2000 load_base: 0 flags: 1 name: /data/libbacktrace_test.so
+map: start: e76ef000 end: e76f0000 offset: 3000 load_base: 0 flags: 3 name: /data/libbacktrace_test.so
+map: start: e7712000 end: e771f000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libbacktrace.so
+map: start: e771f000 end: e7720000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e7720000 end: e7721000 offset: d000 load_base: 0 flags: 1 name: /system/lib/libbacktrace.so
+map: start: e7721000 end: e7722000 offset: e000 load_base: 0 flags: 3 name: /system/lib/libbacktrace.so
+map: start: e7761000 end: e7778000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libutils.so
+map: start: e7778000 end: e7779000 offset: 16000 load_base: 0 flags: 1 name: /system/lib/libutils.so
+map: start: e7779000 end: e777a000 offset: 17000 load_base: 0 flags: 3 name: /system/lib/libutils.so
+map: start: e77a5000 end: e782d000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libc.so
+map: start: e782d000 end: e7831000 offset: 87000 load_base: 0 flags: 1 name: /system/lib/libc.so
+map: start: e7831000 end: e7833000 offset: 8b000 load_base: 0 flags: 3 name: /system/lib/libc.so
+map: start: e7833000 end: e7834000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e7834000 end: e7835000 offset: 0 load_base: 0 flags: 1 name: [anon:.bss]
+map: start: e7835000 end: e783b000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e7845000 end: e8437000 offset: 0 load_base: 2b000 flags: 5 name: /system/lib/libLLVM.so
+map: start: e8437000 end: e8438000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e8438000 end: e848a000 offset: bf2000 load_base: 0 flags: 1 name: /system/lib/libLLVM.so
+map: start: e848a000 end: e848b000 offset: c44000 load_base: 0 flags: 3 name: /system/lib/libLLVM.so
+map: start: e848b000 end: e84a1000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e84eb000 end: e84f7000 offset: 0 load_base: 0 flags: 5 name: /system/lib/libcutils.so
+map: start: e84f7000 end: e84f8000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e84f8000 end: e84f9000 offset: c000 load_base: 0 flags: 1 name: /system/lib/libcutils.so
+map: start: e84f9000 end: e84fa000 offset: d000 load_base: 0 flags: 3 name: /system/lib/libcutils.so
+map: start: e852e000 end: e85b3000 offset: 0 load_base: 2000 flags: 5 name: /system/lib/libc++.so
+map: start: e85b3000 end: e85b4000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e85b4000 end: e85b8000 offset: 85000 load_base: 0 flags: 1 name: /system/lib/libc++.so
+map: start: e85b8000 end: e85b9000 offset: 89000 load_base: 0 flags: 3 name: /system/lib/libc++.so
+map: start: e85b9000 end: e85ba000 offset: 0 load_base: 0 flags: 3 name: [anon:.bss]
+map: start: e85ce000 end: e85cf000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc]
+map: start: e85e4000 end: e85e5000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: e8607000 end: e8608000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: e8680000 end: e8700000 offset: 0 load_base: 0 flags: 3 name: [anon:libc_malloc]
+map: start: e870d000 end: e8719000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: e8719000 end: e871b000 offset: 0 load_base: 0 flags: 1 name: [anon:atexit handlers]
+map: start: e871b000 end: e873b000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/u:object_r:default_prop:s0
+map: start: e873b000 end: e875b000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/properties_serial
+map: start: e875b000 end: e875c000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: e875c000 end: e875d000 offset: 0 load_base: 0 flags: 3 name: [anon:arc4random data]
+map: start: e875d000 end: e875e000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc]
+map: start: e875e000 end: e875f000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: e875f000 end: e877f000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/u:object_r:debug_prop:s0
+map: start: e877f000 end: e879f000 offset: 0 load_base: 0 flags: 32769 name: /dev/__properties__/properties_serial
+map: start: e879f000 end: e87a0000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: e87a0000 end: e87a1000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: e87a1000 end: e87a2000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: e87a2000 end: e87a3000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e87a3000 end: e87a4000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: e87a4000 end: e87a5000 offset: 0 load_base: 0 flags: 0 name: 
+map: start: e87a5000 end: e87a6000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_lob]
+map: start: e87a6000 end: e87a7000 offset: 0 load_base: 0 flags: 1 name: [anon:linker_alloc]
+map: start: e87a7000 end: e87a8000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: e87a8000 end: e87a9000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: e87a9000 end: e87aa000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_vector]
+map: start: e87aa000 end: e87ab000 offset: 0 load_base: 0 flags: 3 name: [anon:linker_alloc_small_objects]
+map: start: e87ab000 end: e87ac000 offset: 0 load_base: 0 flags: 1 name: [anon:atexit handlers]
+map: start: e87ac000 end: e87ad000 offset: 0 load_base: 0 flags: 0 name: [anon:thread signal stack guard page]
+map: start: e87ad000 end: e87af000 offset: 0 load_base: 0 flags: 3 name: [anon:thread signal stack]
+map: start: e87af000 end: e87b0000 offset: 0 load_base: 0 flags: 3 name: [anon:arc4random data]
+map: start: e87b0000 end: e880d000 offset: 0 load_base: 0 flags: 5 name: /system/bin/linker
+map: start: e880d000 end: e880f000 offset: 5c000 load_base: 0 flags: 1 name: /system/bin/linker
+map: start: e880f000 end: e8810000 offset: 5e000 load_base: 0 flags: 3 name: /system/bin/linker
+map: start: e8810000 end: e8812000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: e8812000 end: e8813000 offset: 0 load_base: 0 flags: 1 name: 
+map: start: e8813000 end: e8815000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: ff886000 end: ff8a9000 offset: 0 load_base: 0 flags: 3 name: [stack]
+map: start: ffff0000 end: ffff1000 offset: 0 load_base: 0 flags: 5 name: [vectors]
+registers: 64 34868affdc8871e8150000001c0000001c000000150000000e00000007000000e08771e834868aff2354d2aa24f9ffffdc8871e88c8771e875b86ee778ba6ee7
+stack: start: e8715000 end: e8719000 size: 16384 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dc8871e87dba6ee734868affdc8871e8dc8871e85dba6ee7070000000e000000150000001c000000dc8871e85dba6ee71c000000150000000e00000007000000100000000c0000000800000004000000ddb86ee75dba6ee7dc8871e804000000080000000c00000010000000dc8871e85dba6ee7100000000c000000080000000400000008000000060000000400000002000000288871e835b96ee75dba6ee7dc8871e802000000040000000600000008000000dc8871e85dba6ee70800000006000000040000000200000004000000030000000200000001000000708871e88db96ee75dba6ee7dc8871e801000000020000000300000004000000dc8871e85dba6ee70400000003000000020000000100000004000000208971e8208971e878000000e87d00003dba6ee75dba6ee7dc8871e878000000c5807ce7fc7183e734868aff78868aff78868aff34868aff34868aff78868affe0879437208971e84154d2aa0020000034868aff34868aff34868aff78000000c9b87ee7b1b87ee7a3f47be7288971e8b1b87ee7208971e800000000f83481e800000000e97d0000e87d000000000000005071e82039000000100000000000000000000000000000000000002354d2aa34868aff00000000002071e801000000000000000000000000000000708971e8208971e8000000000000000000000000e0879437000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+function: start: 0 end: e76eb835 name: unknown_start
+function: start: e76eb835 end: e76eb88d name: test_level_four
+function: start: e76eb88d end: e76eb8e5 name: test_level_three
+function: start: e76eb8e5 end: e76eb93d name: test_level_two
+function: start: e76eb93d end: e76eb995 name: test_level_one
+function: start: e76eb995 end: e76eb9f1 name: test_recursive_call
+function: start: e76eb9f1 end: ffffffff name: test_get_context_and_wait
+function: start: ffffffff end: ffffffff name: unknown_end
diff --git a/libbacktrace/testdata/arm/offline_testdata_for_libart b/libbacktrace/testdata/arm/offline_testdata_for_libart
new file mode 100644
index 0000000..63f6a07
--- /dev/null
+++ b/libbacktrace/testdata/arm/offline_testdata_for_libart
@@ -0,0 +1,10 @@
+pid: 32232 tid: 32233
+registers: 64 000000000000000000000000000000006473602451b3e2e700000000d82fd1ff5600000000908eec00000000d42dd1ff00000000c02dd1ff617171e9617171e9
+map: start: e9380000 end: e9766000 offset: 0 load_base: b000 flags: 5 name: /system/lib/libart.so
+stack: start: ffd12dc0 end: ffd16000 size: 12864 00000000000c5024070000000300000005070a0a0100000051b3e2e700000000d82fd1ff560000004c2ed1ff000000000000000081b771e9d82fd1ff000000004c2ed1ff0c2ed1ff40a8d27024bf76e900908eec000000000834d1ff0000000000000000000000000d000000050000000000000000000000080000000101d1ff44b8bfeb4b0000000000000000000000e8b8952400000000fc2ed1ff4fb3e2e7bc49ac6f00908eecb02ed1ffd82fd1ff040000008c908eec942fd1ffd5c141e9d82fd1ff4fb3e2e7542fd1ff336c68e940000000400000007030d1fff031d1ff00000000bc49ac6f5c30d1ff942fd1ff842fd1ffd82fd1ff00000000b8f1786f4fb3e2e7610d67e9d82fd1ff4fb3e2e77880adeb7980adeb7a80adeb7b80adeb7c80adeb7d80adeb7e80adeb7f80adeb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007430d1ff02000000e8b89524e8d895240200000000908eec5c30d1ffbc49ac6f4fb3e2e74030d1ffe8d8952400000000b8f1786fbc49ac6f332367e94fb3e2e701000000637171e9637171e9000000005c30d1ff8430d1ffe0c08bec882fd1ff4fb3e2e70200000004000000942fd1ffe8b8952400908eec58d8952458d895247fbd69e90500000000400fe40100000000908eec58d89524060000009c86bd6f6b876fe900908eece0c08bec00008eec0000000000000000000000000000000044b8bfeb4b000000009be86f040000000038d1ff01000000c8e7446f060000000000000000908eec30d89524e8b895249c86bd6f7893476f00908eec00000000358c6fe970400fe4116e71e9a0285a6fa4d49c6f4489bd6f30d8952458d89524e8d8952400908eeca431d1ff2c31d1ffb75861e90100000000908eec30528bec409181e958d8952431abed6fac33576fb438d1ff030000007800502400000000a0005024060000007893476f00908eec000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004489bd6f78005024d00c5024a0005024a431d1ff2c31d1ff9b99aa71a4d49c6f30d8952400000000e8d895244489bd6fa8e5bc6fc8b895240100000000000000b033d1ff56000000637171e900000000d00c5024c8b89524000000000100000000000000b033d1ff560000006431d1ffa431d1ff000000009fb671e9b033d1ff00000000a431d1ff6431d1ffc431d1ff000000000000000081b771e9b033d1ff00000000c431d1ff8431d1ff01000000020000002429000001000000dc501b002033d1ff0100000018f9736f0100000000908eec58d8952440f180e9a8ec01245b215ce8a4d49c6f00908eec0832d1ffb033d1ff040000008c908eeca832d1ffabc141e9b033d1ff5b215ce82832d1ffb033d1ff080000008c908eec000000000035d1ff0834d1ffa832d1ffa4d49c6f04000000cca312e800908eec6832d1ffb033d1ff0834d1ff6bc354e9b033d1ff5b215ce8cca312e800908eec8832d1ffb033d1ff0834d1ff6bc354e900908eeca4d49c6f44b8bfeb1833d1ff000000006832d1ffb033d1ff478054e9b033d1ff1b8054e90834d1ffa4d49c6f0000000000000000000000000000000008000000000000000834d1ff0000000000000000000000000000000000000000000000000000000058d895240000000000000000000000000000000000000000000000000000000058d89524b17e54e98c56af6f00000000a4d49c6f288944e800908eec00000000d032d1ff0000000000000000000000000000000000000000000000007e8ea6c358a58cec00f580e90834d1ffa4d49c6f58d8952400908eecb033d1ffe9100000da8844e8833c70e9e9100000b033d1ff0200000058d8952408b1796f0200000000908eecda8844e82c34d1ff00908eece9100000005d70e9070000007d1300006034d1ff98d170e9b033d1ff0834d1ff148844e800908eecb033d1ffa034d1ffa833d1ff0100000044b8bfeb41f252e9e91fdeeaa491deea000000004700000001000000d9c4ddea0000000000000000b834d1ff00b051ff0834d1ff00908eecf833d1ffa034d1ff148844e800000000020000004d4c53e900000000000000000000000000908eec44b8bfeb0834d1ff3835d1ff148844e85035d1ffbb936fe90000000044b8bfebb033d1ffda8844e8148844e8000000000d0000005a0000007d137d13d00c502400000000600480240400000070048024f80c5024170000000100000002000000000000000040000000000000d0018024d00c502400000000600480240000000070048024f80c5024000000000000000000000000000000000000000000000000d001802465906fe97b2e5ce8000000000300000000000000881388131a00000001000000000000004cdd76e9010000007b2e5ce8020000009835d1ff5835d1ffc435d1ff010000000000000000000000010000000000000000dd76e90834d1ff0d0000000100000000000000000000005035d1ff9036d1ff00000000a435d1ff7e8ea6c3080000000000000000000000000000000000000038cb7e7044b8bfeb7d2e5ce800000000c037d1ff5600000000908eec00000000cc35d1ff55af71e9e0285a6f040000000800000001000000a437d1ff010000001c73d870000000000000000043000000339768e9040000006c36d1ff0e000000b436d1ff8cc97e706c36d1ff0e00000018eb01243173d870040000007d2e5ce800000000c037d1ff5600000000000000cc35d1ff637171e90000000018eb012402000000010000007d2e5ce800000000c037d1ff560000004436d1ff000000000000000081b771e9c037d1ff000000004436d1ff0436d1ff00e68dec0800000001000000a437d1ff010000001c73d870000000000000000043000000339768e9040000006c36d1ff0e000000b436d1ff8cc97e706c36d1ff0e000000adf861e918eb01243173d870040000007b2e5ce844b8bfeb00908eeca836d1ffc037d1ff040000008c908eec7c37d1ffd5c141e9c037d1ff7b2e5ce80000000000908eecd036d1ff00000000b038d1ff183ad1ff0000000044b8bfeb1038d1ff7c37d1ff6c37d1ffc037d1ff7b2e5ce8000000007b2e5ce8610d67e9c037d1ff7b2e5ce8280477e99835456f960300009a35456f10aa5e6f9a35456f9835456f68b85e6f881e77e9b30a47e9e81382e94c95b4ec7100000000908eec9c908eec30528bec1038d1ff7b2e5ce800000000c78469e91038d1ff0aeb3b52208989ec150645e9010000001038d1ff6c37d1ff44b8bfeb6c37d1ff00000000d837d1ff1038d1ff7b2e5ce8000000006c38d1ff8f0b67e97b2e5ce818eb012400000000000000000838d1ff7b2e5ce802000000040000007c37d1ff18eb01249835456f00000000901e77e9180000000300000000908eec480000004800000043000000640477e97669747954687265070000001a00000060eb0124000000000000000000000000a500000044b8bfeb1038d1ff00908eeceeac73e943000000640477e9901e77e9e6ac73e961705ce96c38d1ff18eb012400908eeceeac73e943000000640477e9000059008bc95ce900908eec30528bec409181e900908eec430000005900000000528bec409181e900004300710000000300000030528bec89c75ce944b8bfebe2050000103dd1ff03000000a3f6a7eb89c75ce96c38d1ff7e8ea6c389c75ce997f5a7eb710000000000000030528bec7e8ea6c3e83cd1ff2079002488beba6ff0ca726f5600000000908eec000000005439d1ff8b1db8aa803a89ec7e8ea6c3000000009173d870ec55af6f00000000010000004892796f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003801802488beba6ff0ca726f56000000000000005439d1ff9d3daa71cc55af6f7039d1ff0b0000006839d1ff7d2e5ce800000000483bd1ff637171e900000000207900240b00000058a58cec40f180e9010000007d2e5ce800000000483bd1ff56000000cc39d1ff000000000000000081b771e9483bd1ff00000000cc39d1ff8c39d1ff05000000050000000c000000040000000100000012000000958c00000100000074d73500483bd1ff01000000e880746f0100000000908eec903ad1ff40f180e97e02000000908eec2079002400000000383ad1ff7b2e5ce8cc55af6f00908eec303ad1ff483bd1ff040000008c908eec043bd1ffd5c141e9483bd1ff7b2e5ce840f180e900908eec583ad1ff00000000000000000000000000000000cc55af6f983bd1ff043bd1fff43ad1ff483bd1ff7b2e5ce8000000007b2e5ce8610d67e9483bd1ff7b2e5ce8280477e94892796f860100004e92796f00a088ec4e92796f4892796f18a688ec881e77e9b30a47e978e388ec4c95b4ec2100000000908eec9c908eec30528bec983bd1ff7b2e5ce800000000c78469e9983bd1ff06b005fdf0298aec150645e901000000983bd1fff43ad1ffcc55af6ff43ad1ff00000000603bd1ff983bd1ff7b2e5ce800000000f43bd1ff8f0b67e97b2e5ce8e00864e80000000000000000903bd1ff7b2e5ce80200000004000000043bd1ff207900249c908eec04000000583bd1ff603bd1ff4892796f04000000ac3bd1ff01000000901e77e917885ee9010000004d5cb1eb485cb1eb00908eec4892796f00000000000000000000000000004300cc55af6f983bd1ff00908eeceeac73e943000000640477e9901e77e9e6ac73e961705ce9f43bd1ff55000000ac3bd1ffeeac73e943000000640477e900005900e3225ce900908eec30528bec409181e900908eec430000005900000000528bec409181e9000043005500000078e388ec2100000009215ce901000000ce3fb8aae83cd1ff40420f00a3f6a7eb09215ce9f43bd1ff7e8ea6c309215ce9ed0ea8eb2100000075270000003289ec0000000030528becef665c74db0e42e911ac58e99daf58e9103dd1ff010000007e8ea6c31b000000385cd1ff385cd1ff02000000103dd1ff0300000087e26deae43cd1ff0200000001000000a31eb8aa020000007c3cd1ff18ac89ec1dac89ec0f000000fc94b4ec7c3cd1ff18ac89ec7e8ea6c3e83cd1ff884dd1ff741ab8aaa81ab8aa000000000700000004000000e43cd1ff3b19b8aa000000000000000000000000000000000000000000000000884dd1ff0000000001000000844dd1ff7e8ea6c3f065b4ec00fd0000205db8aa308789ec010000000000000004000000b8e78aec18ac89ec005db8aa2ceab2eb101082e935000000000000000800000001100000ba5bd1ff99000000b8e78aec205db8aa508789ec030000000000000004000000e2050000108789ec00000000d991aeece583aeec10d0acec10d0acec50d0acec6170705f70726f63657373333200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080a4ec00000000001000009dfe6feb00000000975673eb000000002516b8aa844dd1ff08000000a84dd1ff0000000000000000000000007c4dd1ff3b996feb00000000000000000000000000000000000000005015b8aad45cb8aadc5cb8aae85cb8aa804dd1ff0000000015b8aeec08000000ba5bd1ffd45bd1ffe05bd1ffee5bd1ff0f5cd1ff335cd1ff355cd1ff385cd1ff00000000535cd1ff6f5cd1ff825cd1ff9d5cd1ffbf5cd1ffd45cd1ffee5cd1ff015dd1ff1c5dd1ffe35ed1fffc5ed1ff465fd1ffc55fd1ff0000000010000000d6b0270006000000001000001100000064000000030000003400b8aa040000002000000005000000090000000700000000d0adec080000000000000009000000ec14b8aa0b000000752700000c000000752700000d000000752700000e000000752700001700000000000000190000007c4ed1ff1a0000001f0000001f000000de5fd1ff0f0000008c4ed1ff00000000000000000000000086da76325883c1a6b44d586d68c7843576386c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000636f6d2e6578616d706c652e7375646f67616d65000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f3d2f73797374656d2f62696e2f6170705f70726f63657373333200414e44524f49445f444154413d2f6461746100444f574e4c4f41445f43414348453d2f646174612f636163686500414e44524f49445f534f434b45545f7a79676f74655f7365636f6e646172793d3900414e44524f49445f524f4f543d2f73797374656d00415345435f4d4f554e54504f494e543d2f6d6e742f6173656300414e44524f49445f424f4f544c4f474f3d3100414e44524f49445f4153534554533d2f73797374656d2f61707000424f4f54434c415353504154483d2f73797374656d2f6672616d65776f726b2f636f72652d6f6a2e6a61723a2f73797374656d2f6672616d65776f726b2f636f72652d6c69626172742e6a61723a2f73797374656d2f6672616d65776f726b2f636f6e7363727970742e6a61723a2f73797374656d2f6672616d65776f726b2f6f6b687474702e6a61723a2f73797374656d2f6672616d65776f726b2f6c65676163792d746573742e6a61723a2f73797374656d2f6672616d65776f726b2f626f756e6379636173746c652e6a61723a2f73797374656d2f6672616d65776f726b2f6578742e6a61723a2f73797374656d2f6672616d65776f726b2f6672616d65776f726b2e6a61723a2f73797374656d2f6672616d65776f726b2f74656c6570686f6e792d636f6d6d6f6e2e6a61723a2f73797374656d2f6672616d65776f726b2f766f69702d636f6d6d6f6e2e6a61723a2f73797374656d2f6672616d65776f726b2f696d732d636f6d6d6f6e2e6a61723a2f73797374656d2f6672616d65776f726b2f6170616368652d786d6c2e6a61723a2f73797374656d2f6672616d65776f726b2f6f72672e6170616368652e687474702e6c65676163792e626f6f742e6a617200414e44524f49445f53544f524147453d2f73746f7261676500504154483d2f7362696e3a2f73797374656d2f7362696e3a2f73797374656d2f62696e3a2f73797374656d2f7862696e3a2f76656e646f722f62696e3a2f76656e646f722f7862696e0053595354454d534552564552434c415353504154483d2f73797374656d2f6672616d65776f726b2f73657276696365732e6a61723a2f73797374656d2f6672616d65776f726b2f65746865726e65742d736572766963652e6a61723a2f73797374656d2f6672616d65776f726b2f776966692d736572766963652e6a61720045585445524e414c5f53544f524147453d2f736463617264002f73797374656d2f62696e2f6170705f70726f636573733332000000000000000000
+function: start: 3a2121 end: 3a217a name: art_quick_invoke_stub_internal
+function: start: 3a66a5 end: 3a6787 name: art_quick_invoke_static_stub
+function: start: a7129 end: a72f1 name: art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)
+function: start: 2fbd35 end: 2fc789 name: art::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::ArgArray*, art::JValue*, char const*)
+function: start: 2fcf75 end: 2fd88d name: art::InvokeMethod(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jobject*, _jobject*, unsigned int)
+function: start: 2a089d end: 2a08bb name: art::Method_invoke(_JNIEnv*, _jobject*, _jobject*, _jobject*)
\ No newline at end of file
diff --git a/libbacktrace/testdata/x86/libbacktrace_test_debug_frame.so b/libbacktrace/testdata/x86/libbacktrace_test_debug_frame.so
new file mode 100755
index 0000000..a6f3b29
--- /dev/null
+++ b/libbacktrace/testdata/x86/libbacktrace_test_debug_frame.so
Binary files differ
diff --git a/libbacktrace/testdata/x86/libbacktrace_test_gnu_debugdata.so b/libbacktrace/testdata/x86/libbacktrace_test_gnu_debugdata.so
new file mode 100755
index 0000000..ea58dfb
--- /dev/null
+++ b/libbacktrace/testdata/x86/libbacktrace_test_gnu_debugdata.so
Binary files differ
diff --git a/libbacktrace/testdata/x86/offline_testdata b/libbacktrace/testdata/x86/offline_testdata
new file mode 100644
index 0000000..3e4e06c
--- /dev/null
+++ b/libbacktrace/testdata/x86/offline_testdata
@@ -0,0 +1,82 @@
+pid: 34545 tid: 34546
+map: start: f705a000 end: f705c000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f705c000 end: f707f000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblzma.so
+map: start: f707f000 end: f7080000 offset: 22000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblzma.so
+map: start: f7080000 end: f7081000 offset: 23000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblzma.so
+map: start: f7081000 end: f7088000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7088000 end: f7230000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libc-2.19.so
+map: start: f7230000 end: f7231000 offset: 1a8000 load_base: 0 flags: 0 name: /lib/i386-linux-gnu/libc-2.19.so
+map: start: f7231000 end: f7233000 offset: 1a8000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libc-2.19.so
+map: start: f7233000 end: f7234000 offset: 1aa000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libc-2.19.so
+map: start: f7234000 end: f7237000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7237000 end: f727b000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libm-2.19.so
+map: start: f727b000 end: f727c000 offset: 43000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libm-2.19.so
+map: start: f727c000 end: f727d000 offset: 44000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libm-2.19.so
+map: start: f727d000 end: f7299000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libgcc_s.so.1
+map: start: f7299000 end: f729a000 offset: 1b000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libgcc_s.so.1
+map: start: f729a000 end: f72b8000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libtinfo.so.5.9
+map: start: f72b8000 end: f72b9000 offset: 1e000 load_base: 0 flags: 0 name: /lib/i386-linux-gnu/libtinfo.so.5.9
+map: start: f72b9000 end: f72bb000 offset: 1e000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libtinfo.so.5.9
+map: start: f72bb000 end: f72bc000 offset: 20000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libtinfo.so.5.9
+map: start: f72bc000 end: f72bd000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f72bd000 end: f72e0000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libncurses.so.5.9
+map: start: f72e0000 end: f72e1000 offset: 22000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libncurses.so.5.9
+map: start: f72e1000 end: f72e2000 offset: 23000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libncurses.so.5.9
+map: start: f72e2000 end: f72e5000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libdl-2.19.so
+map: start: f72e5000 end: f72e6000 offset: 2000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libdl-2.19.so
+map: start: f72e6000 end: f72e7000 offset: 3000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libdl-2.19.so
+map: start: f72e7000 end: f72ee000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/librt-2.19.so
+map: start: f72ee000 end: f72ef000 offset: 6000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/librt-2.19.so
+map: start: f72ef000 end: f72f0000 offset: 7000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/librt-2.19.so
+map: start: f72f0000 end: f7308000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/libpthread-2.19.so
+map: start: f7308000 end: f7309000 offset: 18000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/libpthread-2.19.so
+map: start: f7309000 end: f730a000 offset: 19000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/libpthread-2.19.so
+map: start: f730a000 end: f730c000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f732f000 end: f7331000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7331000 end: f7425000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libc++.so
+map: start: f7425000 end: f7426000 offset: f4000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libc++.so
+map: start: f7426000 end: f742a000 offset: f4000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libc++.so
+map: start: f742a000 end: f742b000 offset: f8000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libc++.so
+map: start: f742b000 end: f742d000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f742d000 end: f7446000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libunwind.so
+map: start: f7446000 end: f7447000 offset: 18000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libunwind.so
+map: start: f7447000 end: f7448000 offset: 19000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libunwind.so
+map: start: f7448000 end: f7457000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7457000 end: f745c000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblog.so
+map: start: f745c000 end: f745d000 offset: 4000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblog.so
+map: start: f745d000 end: f745e000 offset: 5000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/liblog.so
+map: start: f745e000 end: f7467000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libcutils.so
+map: start: f7467000 end: f7468000 offset: 9000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libcutils.so
+map: start: f7468000 end: f7469000 offset: 9000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libcutils.so
+map: start: f7469000 end: f746a000 offset: a000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libcutils.so
+map: start: f746a000 end: f7477000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbase.so
+map: start: f7477000 end: f7478000 offset: c000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbase.so
+map: start: f7478000 end: f7479000 offset: d000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbase.so
+map: start: f7479000 end: f7489000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace.so
+map: start: f7489000 end: f748a000 offset: f000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace.so
+map: start: f748a000 end: f748b000 offset: 10000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace.so
+map: start: f748b000 end: f748c000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f748c000 end: f748d000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace_test.so
+map: start: f748d000 end: f748e000 offset: 0 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace_test.so
+map: start: f748e000 end: f748f000 offset: 1000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib/libbacktrace_test.so
+map: start: f748f000 end: f7491000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7491000 end: f74b1000 offset: 0 load_base: 0 flags: 5 name: /lib/i386-linux-gnu/ld-2.19.so
+map: start: f74b1000 end: f74b2000 offset: 1f000 load_base: 0 flags: 1 name: /lib/i386-linux-gnu/ld-2.19.so
+map: start: f74b2000 end: f74b3000 offset: 20000 load_base: 0 flags: 3 name: /lib/i386-linux-gnu/ld-2.19.so
+map: start: f74b3000 end: f77c6000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest/backtrace_test/backtrace_test32
+map: start: f77c6000 end: f77c7000 offset: 0 load_base: ffffe000 flags: 5 name: [vdso]
+map: start: f77c7000 end: f77d4000 offset: 313000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest/backtrace_test/backtrace_test32
+map: start: f77d4000 end: f77d5000 offset: 320000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest/backtrace_test/backtrace_test32
+map: start: f77d5000 end: f77d6000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: f7ec6000 end: f7ee7000 offset: 0 load_base: 0 flags: 3 name: [heap]
+map: start: ffe4e000 end: ffe70000 offset: 0 load_base: 0 flags: 3 name: [stack]
+registers: 348 00000000abdae6fff83b7df704000000a6ec77f7abdae6ff00000000afdae6ff78dae6ff150000001c000000b8f132f7a0f132f7d0df48f7a0ca48f728d9e6ff000000008c8decf78c8decf7ceca48f7a8dae6ff8d8decf70a0000000000000014dae6ff8c8decf78c8decf78c8decf78c8decf78c8decf7a9dae6ff06000000c03a23f78c8decf78c8decf78c8decf78c8decf78c8decf78c8decf78c8decf78d8decf78d8decf7c03a23f7543b23f7000033f75f5f0ff7c03a23f7503423f77000000098000000020000000f2700006c0000000e00000080000000000000008c8decf7000000008c8decf77f03ffff0000ffffffffffff0000000000000000000000000000ffff040000000f27000008000000003023f78d8decf7f069ec000046bdaa308decf715537df7f83b7df78c8decf74c1c71f78c8decf715537df70000000000000000f069ecf7f83b7df75064ecf792e671f7f069ecf7
+stack: start: f732c000 end: f7330000 size: 16384 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009d9d49f761b009f71e382ff7000000000000000000000000000000000000000002000000f6372ff704c82bf70000000000204bf7f0a908f7ceca48f728d9e6fff4a449f70000000020f332f720f332f7d0df48f7f8f132f794c748f720f332f70c144205978142a8d4be08f7d0df48f720f332f7a0ca48f71c000000150000000e000000070000001c000000a0ca48f7d0df48f748f232f739c848f7070000000e000000150000001c000000a0ca48f720f332f70000000000000000d0df48f720f332f7a0ca48f7100000000c000000080000000400000010000000a0ca48f7d0df48f798f232f7c9c848f704000000080000000c00000010000000a0ca48f720f332f70000000000000000d0df48f720f332f7a0ca48f70800000006000000040000000200000008000000a0ca48f7d0df48f7e8f232f759c948f702000000040000000600000008000000a0ca48f720f332f70000000000000000d0df48f720f332f7a0ca48f7040000000300000002000000010000000046bdaa00000000d0df48f738f332f77cca48f701000000020000000300000004000000a0ca48f720f332f700000000f83b7df7696d4df7d0df48f788dae6ff28d9e6ff28d9e6ff88dae6ff58f332f70046bdaa40fb32f7f83b7df758f332f78d6d4df728d9e6ff88dae6fff83b7df728d9e6ff28d9e6ff009030f728f432f7726f2ff728d9e6ff40fb32f740fb32f740fb32f790f332f700000000000000000000000000000000000000000000000000000000009030f740fb32f7000f3d0028f432f703b12c75032f144e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a06e2ff700000000000f3d00000000008e3f17f740fb32f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a03823f7c4fd32f700000000e0341df7e02e1df7e03d1df70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040fb32f7188eecf740fb32f70100000030647cf70046bdaa28658876000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000060a705f7a4b130f7f2860000f1860000b0fb32f7ecffffff000000000000000090f332f7000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ccfb32f70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000c2638cfa7f3e1d0000000000000000000000000000000000406d4df728d9e6ff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c032f7004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+function: start: 0 end: f748c740 name: unknown_start
+function: start: f748c740 end: f748c7c0 name: test_level_four
+function: start: f748c7c0 end: f748c850 name: test_level_three
+function: start: f748c850 end: f748c8e0 name: test_level_two
+function: start: f748c8e0 end: f748c970 name: test_level_one
+function: start: f748c970 end: f748ca10 name: test_recursive_call
+function: start: f748ca10 end: ffffffff name: test_get_context_and_wait
+function: start: ffffffff end: ffffffff name: unknown_end
diff --git a/libbacktrace/testdata/x86_64/libbacktrace_test_eh_frame.so b/libbacktrace/testdata/x86_64/libbacktrace_test_eh_frame.so
new file mode 100755
index 0000000..f116658
--- /dev/null
+++ b/libbacktrace/testdata/x86_64/libbacktrace_test_eh_frame.so
Binary files differ
diff --git a/libbacktrace/testdata/x86_64/offline_testdata b/libbacktrace/testdata/x86_64/offline_testdata
new file mode 100644
index 0000000..baf6450
--- /dev/null
+++ b/libbacktrace/testdata/x86_64/offline_testdata
@@ -0,0 +1,93 @@
+pid: 25683 tid: 25692
+map: start: 7fd5aa784000 end: 7fd5aa93e000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libc-2.19.so
+map: start: 7fd5aa93e000 end: 7fd5aab3e000 offset: 1ba000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libc-2.19.so
+map: start: 7fd5aab3e000 end: 7fd5aab42000 offset: 1ba000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libc-2.19.so
+map: start: 7fd5aab42000 end: 7fd5aab44000 offset: 1be000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libc-2.19.so
+map: start: 7fd5aab44000 end: 7fd5aab49000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5aab49000 end: 7fd5aac4e000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libm-2.19.so
+map: start: 7fd5aac4e000 end: 7fd5aae4d000 offset: 105000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libm-2.19.so
+map: start: 7fd5aae4d000 end: 7fd5aae4e000 offset: 104000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libm-2.19.so
+map: start: 7fd5aae4e000 end: 7fd5aae4f000 offset: 105000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libm-2.19.so
+map: start: 7fd5aae4f000 end: 7fd5aae65000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libgcc_s.so.1
+map: start: 7fd5aae65000 end: 7fd5ab064000 offset: 16000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libgcc_s.so.1
+map: start: 7fd5ab064000 end: 7fd5ab065000 offset: 15000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libgcc_s.so.1
+map: start: 7fd5ab065000 end: 7fd5ab08a000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libtinfo.so.5.9
+map: start: 7fd5ab08a000 end: 7fd5ab289000 offset: 25000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libtinfo.so.5.9
+map: start: 7fd5ab289000 end: 7fd5ab28d000 offset: 24000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libtinfo.so.5.9
+map: start: 7fd5ab28d000 end: 7fd5ab28e000 offset: 28000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libtinfo.so.5.9
+map: start: 7fd5ab28e000 end: 7fd5ab2b0000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libncurses.so.5.9
+map: start: 7fd5ab2b0000 end: 7fd5ab4af000 offset: 22000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libncurses.so.5.9
+map: start: 7fd5ab4af000 end: 7fd5ab4b0000 offset: 21000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libncurses.so.5.9
+map: start: 7fd5ab4b0000 end: 7fd5ab4b1000 offset: 22000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libncurses.so.5.9
+map: start: 7fd5ab4b1000 end: 7fd5ab4b4000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libdl-2.19.so
+map: start: 7fd5ab4b4000 end: 7fd5ab6b3000 offset: 3000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libdl-2.19.so
+map: start: 7fd5ab6b3000 end: 7fd5ab6b4000 offset: 2000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libdl-2.19.so
+map: start: 7fd5ab6b4000 end: 7fd5ab6b5000 offset: 3000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libdl-2.19.so
+map: start: 7fd5ab6b5000 end: 7fd5ab6bc000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/librt-2.19.so
+map: start: 7fd5ab6bc000 end: 7fd5ab8bb000 offset: 7000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/librt-2.19.so
+map: start: 7fd5ab8bb000 end: 7fd5ab8bc000 offset: 6000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/librt-2.19.so
+map: start: 7fd5ab8bc000 end: 7fd5ab8bd000 offset: 7000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/librt-2.19.so
+map: start: 7fd5ab8bd000 end: 7fd5ab8d6000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/libpthread-2.19.so
+map: start: 7fd5ab8d6000 end: 7fd5abad5000 offset: 19000 load_base: 0 flags: 0 name: /lib/x86_64-linux-gnu/libpthread-2.19.so
+map: start: 7fd5abad5000 end: 7fd5abad6000 offset: 18000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/libpthread-2.19.so
+map: start: 7fd5abad6000 end: 7fd5abad7000 offset: 19000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/libpthread-2.19.so
+map: start: 7fd5abad7000 end: 7fd5abadb000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abadb000 end: 7fd5abafe000 offset: 0 load_base: 0 flags: 5 name: /lib/x86_64-linux-gnu/ld-2.19.so
+map: start: 7fd5abb17000 end: 7fd5abb1a000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abb1a000 end: 7fd5abb40000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblzma.so
+map: start: 7fd5abb40000 end: 7fd5abb41000 offset: 25000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblzma.so
+map: start: 7fd5abb41000 end: 7fd5abb42000 offset: 26000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblzma.so
+map: start: 7fd5abb42000 end: 7fd5abb4b000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abb6a000 end: 7fd5abb70000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abb70000 end: 7fd5abc62000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libc++.so
+map: start: 7fd5abc62000 end: 7fd5abc63000 offset: f2000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libc++.so
+map: start: 7fd5abc63000 end: 7fd5abc6b000 offset: f2000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libc++.so
+map: start: 7fd5abc6b000 end: 7fd5abc6c000 offset: fa000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libc++.so
+map: start: 7fd5abc6c000 end: 7fd5abc70000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abc70000 end: 7fd5abc8d000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libunwind.so
+map: start: 7fd5abc8d000 end: 7fd5abc8e000 offset: 1c000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libunwind.so
+map: start: 7fd5abc8e000 end: 7fd5abc8f000 offset: 1d000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libunwind.so
+map: start: 7fd5abc8f000 end: 7fd5abcb8000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abcb8000 end: 7fd5abcbe000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblog.so
+map: start: 7fd5abcbe000 end: 7fd5abcbf000 offset: 6000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblog.so
+map: start: 7fd5abcbf000 end: 7fd5abcc0000 offset: 6000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblog.so
+map: start: 7fd5abcc0000 end: 7fd5abcc1000 offset: 7000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/liblog.so
+map: start: 7fd5abcc1000 end: 7fd5abcc2000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abcc2000 end: 7fd5abccd000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libcutils.so
+map: start: 7fd5abccd000 end: 7fd5abcce000 offset: b000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libcutils.so
+map: start: 7fd5abcce000 end: 7fd5abccf000 offset: b000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libcutils.so
+map: start: 7fd5abccf000 end: 7fd5abcd0000 offset: c000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libcutils.so
+map: start: 7fd5abcd0000 end: 7fd5abcdf000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbase.so
+map: start: 7fd5abcdf000 end: 7fd5abce0000 offset: f000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbase.so
+map: start: 7fd5abce0000 end: 7fd5abce1000 offset: f000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbase.so
+map: start: 7fd5abce1000 end: 7fd5abce2000 offset: 10000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbase.so
+map: start: 7fd5abce2000 end: 7fd5abcf5000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace.so
+map: start: 7fd5abcf5000 end: 7fd5abcf6000 offset: 12000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace.so
+map: start: 7fd5abcf6000 end: 7fd5abcf7000 offset: 13000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace.so
+map: start: 7fd5abcf7000 end: 7fd5abcf8000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace_test.so
+map: start: 7fd5abcf8000 end: 7fd5abcf9000 offset: 1000 load_base: 0 flags: 0 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace_test.so
+map: start: 7fd5abcf9000 end: 7fd5abcfa000 offset: 1000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace_test.so
+map: start: 7fd5abcfa000 end: 7fd5abcfb000 offset: 2000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/lib64/libbacktrace_test.so
+map: start: 7fd5abcfb000 end: 7fd5abcfd000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abcfd000 end: 7fd5abcfe000 offset: 22000 load_base: 0 flags: 1 name: /lib/x86_64-linux-gnu/ld-2.19.so
+map: start: 7fd5abcfe000 end: 7fd5abcff000 offset: 23000 load_base: 0 flags: 3 name: /lib/x86_64-linux-gnu/ld-2.19.so
+map: start: 7fd5abcff000 end: 7fd5abd00000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5abd00000 end: 7fd5ac053000 offset: 0 load_base: 0 flags: 5 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest64/backtrace_test/backtrace_test64
+map: start: 7fd5ac053000 end: 7fd5ac054000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5ac054000 end: 7fd5ac06f000 offset: 353000 load_base: 0 flags: 1 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest64/backtrace_test/backtrace_test64
+map: start: 7fd5ac06f000 end: 7fd5ac070000 offset: 36e000 load_base: 0 flags: 3 name: /ssd/android/aosp_master/out/host/linux-x86/nativetest64/backtrace_test/backtrace_test64
+map: start: 7fd5ac070000 end: 7fd5ac071000 offset: 0 load_base: 0 flags: 3 name: 
+map: start: 7fd5ad54e000 end: 7fd5ad56f000 offset: 0 load_base: 0 flags: 3 name: [heap]
+map: start: 7ffcf47ed000 end: 7ffcf480f000 offset: 0 load_base: 0 flags: 3 name: [stack]
+map: start: 7ffcf48d5000 end: 7ffcf48d7000 offset: 0 load_base: ffffffffff700000 flags: 5 name: [vdso]
+map: start: ffffffffff600000 end: ffffffffff601000 offset: 0 load_base: 0 flags: 5 name: [vsyscall]
+registers: 936 010000000000000028b480f4fc7f000028b480f4fc7f000028b480f4fc7f0000b92455add57f0000b07bcfabd57f000098deb6abd57f0000b82455add57f0000010000000000000000000000000000000000000000000000c0e354add57f000000e7b6abd57f0000c8b080f4fc7f00000e0000000000000080ddb6abd57f000000000000000000001500000000000000b07bcfabd57f00001c0000000000000060ddb6abd57f0000d07bcfabd57f0000a0b180f4fc7f000028b480f4fc7f000028b480f4fc7f000028b480f4fc7f000078b480f4fc7f000078b480f4fc7f00007f03ffff0000ffffffffffff000000000000000000000000801f0000fc7f000078b480f4fc7f000060b280f4fc7f000000006a80f3f73cf110b480f4fc7f0000de66d6abd57f00000000000000000000000000000000000000006a80f3f73cf128b480f4fc7f0000782455add57f0000fd96d6abd57f0000092555add57f0000000000000000000057b480f4fc7f0000092555add57f000060b480f4fc7f00006994d6abd57f0000b0e0c6abd57f000071b280f4fc7f000070b280f4fc7f0000256c640000000000a8b180f4fc7f000090b480f4fc7f0000082555add57f0000092555add57f0000092555add57f0000082555add57f00001700000000000000082555add57f0000082555add57f0000f93cfcabd57f0000092555add57f000016000000000000000000000000000000090c07acd57f0000082555add57f0000082555add57f0000082555add57f0000082555add57f0000082555add57f000010b380f4fc7f000078b480f4fc7f00000000000000000000082555add57f0000082555add57f0000082555add57f0000082555add57f0000082555add57f0000082555add57f0000082555add57f0000092555add57f0000092555add57f0000b92455add57f000028b480f4fc7f0000c800000000000000014c7f0b0380ffff0d000000fc7f0000030000000000000033000000d57f000000b480f4fc7f00000000000000000000a0e154ad5b000000000000000000000000000000000000006e000000770000000000000000000000082555add57f00000000000000000000082555add57f0000082555add57f0000082555add57f0000082555add57f00000000000000000000082555add57f0000082555add57f0000082555add57f00006027b4aad57f0000c800000000000000a0e154add57f0000c0e354add57f0000092555add57f000000006a80f3f73cf1e0e054add57f0000e0e554add57f0000d14df6abd57f0000
+stack: start: 7fd5abb6b000 end: 7fd5abb6f000 size: 16384 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006c4eaeabd57f00000000000000000000978142a8000000000f0000000000000012000000000000003888b4abd57f0000e657aeabd57f00000000000000000000a0dcb6abd57f0000307d78aad57f0000b0ddb6abd57f000028d978aad57f0000060aa10200000000a0ddb6abd57f0000000000000000000000000000000000002091b1abd57f0000e094b4abd57f000017008cabd57f0000c84d79aad57f000028e28babd57f00000000000005000000d503000001000000000000000000000068deb6abd57f000040deb6abd57f00002091b1abd57f00000100000000000000e0f3c6abd57f000088f0c6abd57f00006159aeabd57f000000000000000000002091b1abd57f000005000000000000000000000000000000010000000000000088f0c6abd57f00000000000000000000d07bcfabd57f00000000000000000000000000000000000098deb6abd57f000098deb6abd57f0000b0ddb6abd57f00006179cfabd57f000098deb6abd57f0000b07bcfabd57f00001c000000150000000e00000007000000f0ddb6abd57f0000e179cfabd57f00000000000000000000150000001c00000098deb6abd57f0000b07bcfabd57f0000100000000c000000080000000400000030deb6abd57f0000417acfabd57f000000000000000000000c0000001000000098deb6abd57f0000b07bcfabd57f00000800000006000000040000000200000070deb6abd57f0000a17acfabd57f00000000000000000000060000000800000098deb6abd57f0000b07bcfabd57f000004000000030000000200000001000000b0deb6abd57f0000817bcfabd57f0000000000000000000074b480f4fc7f0000c8b080f4fc7f0000c8b080f4fc7f000074b480f4fc7f000000006a80f3f73cf1d0deb6abd57f00002a52d5abd57f0000c8b080f4fc7f0000c8b080f4fc7f0000000000000000000084518cabd57f0000000000000000000000e7b6abd57f000000e7b6abd57f00008f990b1e3bad5a6700000000000000000000000000000000c0e354add57f000000e7b6abd57f00008f99cba356faf1988f9991bc23faf1980000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e7b6abd57f00007de387aad57f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006030b4aad57f0000b8edb6abd57f00000000000000000000000000000000000080b88eaad57f0000000000000000000080b28eaad57f0000000000000000000080c18eaad57f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e7b6abd57f0000402555add57f000000e7b6abd57f00000100000000000000000000000000000000006a80f3f73cf1058f9d56adb3c7cc000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000407ab1abd57f000030a3adabd57f00005c64000053640000e0e9b6abd57f0000e0e9b6abd57f0000e0ffffffffffffff00000000000000000000000000000000f0deb6abd57f00000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010eab6abd57f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000c46ad90f52391d00000000000000000000000000000000000000000000000000f051d5abd57f0000c8b080f4fc7f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b0b6abd57f000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+function: start: 0 end: 7fd5abcf7930 name: unknown_start
+function: start: 7fd5abcf7930 end: 7fd5abcf7990 name: test_level_four
+function: start: 7fd5abcf7990 end: 7fd5abcf79f0 name: test_level_three
+function: start: 7fd5abcf79f0 end: 7fd5abcf7a50 name: test_level_two
+function: start: 7fd5abcf7a50 end: 7fd5abcf7ab0 name: test_level_one
+function: start: 7fd5abcf7ab0 end: 7fd5abcf7b30 name: test_recursive_call
+function: start: 7fd5abcf7b30 end: ffffffffffffffff name: test_get_context_and_wait
+function: start: ffffffffffffffff end: ffffffffffffffff name: unknown_end
diff --git a/libbinderwrapper/Android.mk b/libbinderwrapper/Android.mk
index 23c2246..c768373 100644
--- a/libbinderwrapper/Android.mk
+++ b/libbinderwrapper/Android.mk
@@ -18,8 +18,8 @@
 
 binderwrapperCommonCFlags := -Wall -Werror -Wno-unused-parameter
 binderwrapperCommonCFlags += -Wno-sign-promo  # for libchrome
-binderwrapperCommonExportCIncludeDirs := $(LOCAL_PATH)/../include
-binderwrapperCommonCIncludes := $(LOCAL_PATH)/../include
+binderwrapperCommonExportCIncludeDirs := $(LOCAL_PATH)/include
+binderwrapperCommonCIncludes := $(LOCAL_PATH)/include
 binderwrapperCommonSharedLibraries := \
   libbinder \
   libchrome \
@@ -41,7 +41,7 @@
 
 include $(BUILD_SHARED_LIBRARY)
 
-# libbinderwrapper_test_support shared library
+# libbinderwrapper_test_support static library
 # ========================================================
 
 include $(CLEAR_VARS)
@@ -59,4 +59,4 @@
   binder_test_base.cc \
   stub_binder_wrapper.cc \
 
-include $(BUILD_SHARED_LIBRARY)
+include $(BUILD_STATIC_LIBRARY)
diff --git a/include/binderwrapper/binder_test_base.h b/libbinderwrapper/include/binderwrapper/binder_test_base.h
similarity index 100%
rename from include/binderwrapper/binder_test_base.h
rename to libbinderwrapper/include/binderwrapper/binder_test_base.h
diff --git a/libbinderwrapper/include/binderwrapper/binder_wrapper.h b/libbinderwrapper/include/binderwrapper/binder_wrapper.h
new file mode 100644
index 0000000..a104bff
--- /dev/null
+++ b/libbinderwrapper/include/binderwrapper/binder_wrapper.h
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+#ifndef SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
+#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
+
+#include <sys/types.h>
+
+#include <string>
+
+#include <base/callback.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+class BBinder;
+class IBinder;
+
+// Wraps libbinder to make it testable.
+// NOTE: Static methods of this class are not thread-safe.
+class BinderWrapper {
+ public:
+  virtual ~BinderWrapper() {}
+
+  // Creates and initializes the singleton (using a wrapper that communicates
+  // with the real binder system).
+  static void Create();
+
+  // Initializes |wrapper| as the singleton, taking ownership of it. Tests that
+  // want to inject their own wrappers should call this instead of Create().
+  static void InitForTesting(BinderWrapper* wrapper);
+
+  // Destroys the singleton. Must be called before calling Create() or
+  // InitForTesting() a second time.
+  static void Destroy();
+
+  // Returns the singleton instance previously created by Create() or set by
+  // InitForTesting().
+  static BinderWrapper* Get();
+
+  // Returns the singleton instance if it was previously created by Create() or
+  // set by InitForTesting(), or creates a new one by calling Create().
+  static BinderWrapper* GetOrCreateInstance();
+
+  // Gets the binder for communicating with the service identified by
+  // |service_name|, returning null immediately if it doesn't exist.
+  virtual sp<IBinder> GetService(const std::string& service_name) = 0;
+
+  // Registers |binder| as |service_name| with the service manager.
+  virtual bool RegisterService(const std::string& service_name,
+                               const sp<IBinder>& binder) = 0;
+
+  // Creates a local binder object.
+  virtual sp<BBinder> CreateLocalBinder() = 0;
+
+  // Registers |callback| to be invoked when |binder| dies. If another callback
+  // is currently registered for |binder|, it will be replaced.
+  virtual bool RegisterForDeathNotifications(
+      const sp<IBinder>& binder,
+      const ::base::Closure& callback) = 0;
+
+  // Unregisters the callback, if any, for |binder|.
+  virtual bool UnregisterForDeathNotifications(const sp<IBinder>& binder) = 0;
+
+  // When called while in a transaction, returns the caller's UID or PID.
+  virtual uid_t GetCallingUid() = 0;
+  virtual pid_t GetCallingPid() = 0;
+
+ private:
+  static BinderWrapper* instance_;
+};
+
+}  // namespace android
+
+#endif  // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
diff --git a/libbinderwrapper/include/binderwrapper/stub_binder_wrapper.h b/libbinderwrapper/include/binderwrapper/stub_binder_wrapper.h
new file mode 100644
index 0000000..9d4578e
--- /dev/null
+++ b/libbinderwrapper/include/binderwrapper/stub_binder_wrapper.h
@@ -0,0 +1,133 @@
+/*
+ * 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.
+ */
+
+#ifndef SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
+#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include <base/macros.h>
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binderwrapper/binder_wrapper.h>
+
+namespace android {
+
+// Stub implementation of BinderWrapper for testing.
+//
+// Example usage:
+//
+// First, assuming a base IFoo binder interface, create a stub class that
+// derives from BnFoo to implement the receiver side of the communication:
+//
+//   class StubFoo : public BnFoo {
+//    public:
+//     ...
+//     status_t doSomething(int arg) override {
+//       // e.g. save passed-in value for later inspection by tests.
+//       return OK;
+//     }
+//   };
+//
+// Next, from your test code, inject a StubBinderManager either directly or by
+// inheriting from the BinderTestBase class:
+//
+//   StubBinderWrapper* wrapper = new StubBinderWrapper();
+//   BinderWrapper::InitForTesting(wrapper);  // Takes ownership.
+//
+// Also from your test, create a StubFoo and register it with the wrapper:
+//
+//   StubFoo* foo = new StubFoo();
+//   sp<IBinder> binder(foo);
+//   wrapper->SetBinderForService("foo", binder);
+//
+// The code being tested can now use the wrapper to get the stub and call it:
+//
+//   sp<IBinder> binder = BinderWrapper::Get()->GetService("foo");
+//   CHECK(binder.get());
+//   sp<IFoo> foo = interface_cast<IFoo>(binder);
+//   CHECK_EQ(foo->doSomething(3), OK);
+//
+// To create a local BBinder object, production code can call
+// CreateLocalBinder(). Then, a test can get the BBinder's address via
+// local_binders() to check that they're passed as expected in binder calls.
+//
+class StubBinderWrapper : public BinderWrapper {
+ public:
+  StubBinderWrapper();
+  ~StubBinderWrapper() override;
+
+  const std::vector<sp<BBinder>>& local_binders() const {
+    return local_binders_;
+  }
+  void clear_local_binders() { local_binders_.clear(); }
+
+  void set_calling_uid(uid_t uid) { calling_uid_ = uid; }
+  void set_calling_pid(pid_t pid) { calling_pid_ = pid; }
+
+  // Sets the binder to return when |service_name| is passed to GetService() or
+  // WaitForService().
+  void SetBinderForService(const std::string& service_name,
+                           const sp<IBinder>& binder);
+
+  // Returns the binder previously registered for |service_name| via
+  // RegisterService(), or null if the service hasn't been registered.
+  sp<IBinder> GetRegisteredService(const std::string& service_name) const;
+
+  // Run the calback in |death_callbacks_| corresponding to |binder|.
+  void NotifyAboutBinderDeath(const sp<IBinder>& binder);
+
+  // BinderWrapper:
+  sp<IBinder> GetService(const std::string& service_name) override;
+  bool RegisterService(const std::string& service_name,
+                       const sp<IBinder>& binder) override;
+  sp<BBinder> CreateLocalBinder() override;
+  bool RegisterForDeathNotifications(const sp<IBinder>& binder,
+                                     const ::base::Closure& callback) override;
+  bool UnregisterForDeathNotifications(const sp<IBinder>& binder) override;
+  uid_t GetCallingUid() override;
+  pid_t GetCallingPid() override;
+
+ private:
+  using ServiceMap = std::map<std::string, sp<IBinder>>;
+
+  // Map from service name to associated binder handle. Used by GetService() and
+  // WaitForService().
+  ServiceMap services_to_return_;
+
+  // Map from service name to associated binder handle. Updated by
+  // RegisterService().
+  ServiceMap registered_services_;
+
+  // Local binders returned by CreateLocalBinder().
+  std::vector<sp<BBinder>> local_binders_;
+
+  // Map from binder handle to the callback that should be invoked on binder
+  // death.
+  std::map<sp<IBinder>, ::base::Closure> death_callbacks_;
+
+  // Values to return from GetCallingUid() and GetCallingPid();
+  uid_t calling_uid_;
+  pid_t calling_pid_;
+
+  DISALLOW_COPY_AND_ASSIGN(StubBinderWrapper);
+};
+
+}  // namespace android
+
+#endif  // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
diff --git a/libbinderwrapper/real_binder_wrapper.cc b/libbinderwrapper/real_binder_wrapper.cc
index 1c51822..f93f183 100644
--- a/libbinderwrapper/real_binder_wrapper.cc
+++ b/libbinderwrapper/real_binder_wrapper.cc
@@ -29,7 +29,7 @@
 // be awkward.
 class RealBinderWrapper::DeathRecipient : public IBinder::DeathRecipient {
  public:
-  explicit DeathRecipient(const base::Closure& callback)
+  explicit DeathRecipient(const ::base::Closure& callback)
       : callback_(callback) {}
   ~DeathRecipient() = default;
 
@@ -40,7 +40,7 @@
 
  private:
   // Callback to run in response to binder death.
-  base::Closure callback_;
+  ::base::Closure callback_;
 
   DISALLOW_COPY_AND_ASSIGN(DeathRecipient);
 };
@@ -85,7 +85,7 @@
 
 bool RealBinderWrapper::RegisterForDeathNotifications(
     const sp<IBinder>& binder,
-    const base::Closure& callback) {
+    const ::base::Closure& callback) {
   sp<DeathRecipient> recipient(new DeathRecipient(callback));
   if (binder->linkToDeath(recipient) != OK) {
     LOG(ERROR) << "Failed to register for death notifications on "
diff --git a/libbinderwrapper/real_binder_wrapper.h b/libbinderwrapper/real_binder_wrapper.h
index ea08371..fa05383 100644
--- a/libbinderwrapper/real_binder_wrapper.h
+++ b/libbinderwrapper/real_binder_wrapper.h
@@ -17,6 +17,8 @@
 #ifndef SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
 #define SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
 
+#include <map>
+
 #include <base/macros.h>
 #include <binderwrapper/binder_wrapper.h>
 
@@ -36,7 +38,7 @@
                        const sp<IBinder>& binder) override;
   sp<BBinder> CreateLocalBinder() override;
   bool RegisterForDeathNotifications(const sp<IBinder>& binder,
-                                     const base::Closure& callback) override;
+                                     const ::base::Closure& callback) override;
   bool UnregisterForDeathNotifications(const sp<IBinder>& binder) override;
   uid_t GetCallingUid() override;
   pid_t GetCallingPid() override;
diff --git a/libbinderwrapper/stub_binder_wrapper.cc b/libbinderwrapper/stub_binder_wrapper.cc
index 87c6ab7..8e75f62 100644
--- a/libbinderwrapper/stub_binder_wrapper.cc
+++ b/libbinderwrapper/stub_binder_wrapper.cc
@@ -64,7 +64,7 @@
 
 bool StubBinderWrapper::RegisterForDeathNotifications(
     const sp<IBinder>& binder,
-    const base::Closure& callback) {
+    const ::base::Closure& callback) {
   death_callbacks_[binder] = callback;
   return true;
 }
diff --git a/libcrypto_utils/Android.bp b/libcrypto_utils/Android.bp
new file mode 100644
index 0000000..4a5f2a7
--- /dev/null
+++ b/libcrypto_utils/Android.bp
@@ -0,0 +1,37 @@
+//
+// 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.
+//
+
+cc_library {
+    name: "libcrypto_utils",
+    vendor_available: true,
+    host_supported: true,
+    srcs: [
+        "android_pubkey.c",
+    ],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+    shared_libs: ["libcrypto"],
+    target: {
+        windows: {
+            enabled: true,
+        },
+    },
+}
diff --git a/libcrypto_utils/android_pubkey.c b/libcrypto_utils/android_pubkey.c
new file mode 100644
index 0000000..3052e52
--- /dev/null
+++ b/libcrypto_utils/android_pubkey.c
@@ -0,0 +1,169 @@
+/*
+ * 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 <crypto_utils/android_pubkey.h>
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <openssl/bn.h>
+
+// Better safe than sorry.
+#if (ANDROID_PUBKEY_MODULUS_SIZE % 4) != 0
+#error RSA modulus size must be multiple of the word size!
+#endif
+
+// Size of the RSA modulus in words.
+#define ANDROID_PUBKEY_MODULUS_SIZE_WORDS (ANDROID_PUBKEY_MODULUS_SIZE / 4)
+
+// This file implements encoding and decoding logic for Android's custom RSA
+// public key binary format. Public keys are stored as a sequence of
+// little-endian 32 bit words. Note that Android only supports little-endian
+// processors, so we don't do any byte order conversions when parsing the binary
+// struct.
+typedef struct RSAPublicKey {
+    // Modulus length. This must be ANDROID_PUBKEY_MODULUS_SIZE.
+    uint32_t modulus_size_words;
+
+    // Precomputed montgomery parameter: -1 / n[0] mod 2^32
+    uint32_t n0inv;
+
+    // RSA modulus as a little-endian array.
+    uint8_t modulus[ANDROID_PUBKEY_MODULUS_SIZE];
+
+    // Montgomery parameter R^2 as a little-endian array of little-endian words.
+    uint8_t rr[ANDROID_PUBKEY_MODULUS_SIZE];
+
+    // RSA modulus: 3 or 65537
+    uint32_t exponent;
+} RSAPublicKey;
+
+// Reverses byte order in |buffer|.
+static void reverse_bytes(uint8_t* buffer, size_t size) {
+  for (size_t i = 0; i < (size + 1) / 2; ++i) {
+    uint8_t tmp = buffer[i];
+    buffer[i] = buffer[size - i - 1];
+    buffer[size - i - 1] = tmp;
+  }
+}
+
+bool android_pubkey_decode(const uint8_t* key_buffer, size_t size, RSA** key) {
+  const RSAPublicKey* key_struct = (RSAPublicKey*)key_buffer;
+  bool ret = false;
+  uint8_t modulus_buffer[ANDROID_PUBKEY_MODULUS_SIZE];
+  RSA* new_key = RSA_new();
+  if (!new_key) {
+    goto cleanup;
+  }
+
+  // Check |size| is large enough and the modulus size is correct.
+  if (size < sizeof(RSAPublicKey)) {
+    goto cleanup;
+  }
+  if (key_struct->modulus_size_words != ANDROID_PUBKEY_MODULUS_SIZE_WORDS) {
+    goto cleanup;
+  }
+
+  // Convert the modulus to big-endian byte order as expected by BN_bin2bn.
+  memcpy(modulus_buffer, key_struct->modulus, sizeof(modulus_buffer));
+  reverse_bytes(modulus_buffer, sizeof(modulus_buffer));
+  new_key->n = BN_bin2bn(modulus_buffer, sizeof(modulus_buffer), NULL);
+  if (!new_key->n) {
+    goto cleanup;
+  }
+
+  // Read the exponent.
+  new_key->e = BN_new();
+  if (!new_key->e || !BN_set_word(new_key->e, key_struct->exponent)) {
+    goto cleanup;
+  }
+
+  // Note that we don't extract the montgomery parameters n0inv and rr from
+  // the RSAPublicKey structure. They assume a word size of 32 bits, but
+  // BoringSSL may use a word size of 64 bits internally, so we're lacking the
+  // top 32 bits of n0inv in general. For now, we just ignore the parameters
+  // and have BoringSSL recompute them internally. More sophisticated logic can
+  // be added here if/when we want the additional speedup from using the
+  // pre-computed montgomery parameters.
+
+  *key = new_key;
+  ret = true;
+
+cleanup:
+  if (!ret && new_key) {
+    RSA_free(new_key);
+  }
+  return ret;
+}
+
+static bool android_pubkey_encode_bignum(const BIGNUM* num, uint8_t* buffer) {
+  if (!BN_bn2bin_padded(buffer, ANDROID_PUBKEY_MODULUS_SIZE, num)) {
+    return false;
+  }
+
+  reverse_bytes(buffer, ANDROID_PUBKEY_MODULUS_SIZE);
+  return true;
+}
+
+bool android_pubkey_encode(const RSA* key, uint8_t* key_buffer, size_t size) {
+  RSAPublicKey* key_struct = (RSAPublicKey*)key_buffer;
+  bool ret = false;
+  BN_CTX* ctx = BN_CTX_new();
+  BIGNUM* r32 = BN_new();
+  BIGNUM* n0inv = BN_new();
+  BIGNUM* rr = BN_new();
+
+  if (sizeof(RSAPublicKey) > size ||
+      RSA_size(key) != ANDROID_PUBKEY_MODULUS_SIZE) {
+    goto cleanup;
+  }
+
+  // Store the modulus size.
+  key_struct->modulus_size_words = ANDROID_PUBKEY_MODULUS_SIZE_WORDS;
+
+  // Compute and store n0inv = -1 / N[0] mod 2^32.
+  if (!ctx || !r32 || !n0inv || !BN_set_bit(r32, 32) ||
+      !BN_mod(n0inv, key->n, r32, ctx) ||
+      !BN_mod_inverse(n0inv, n0inv, r32, ctx) || !BN_sub(n0inv, r32, n0inv)) {
+    goto cleanup;
+  }
+  key_struct->n0inv = (uint32_t)BN_get_word(n0inv);
+
+  // Store the modulus.
+  if (!android_pubkey_encode_bignum(key->n, key_struct->modulus)) {
+    goto cleanup;
+  }
+
+  // Compute and store rr = (2^(rsa_size)) ^ 2 mod N.
+  if (!ctx || !rr || !BN_set_bit(rr, ANDROID_PUBKEY_MODULUS_SIZE * 8) ||
+      !BN_mod_sqr(rr, rr, key->n, ctx) ||
+      !android_pubkey_encode_bignum(rr, key_struct->rr)) {
+    goto cleanup;
+  }
+
+  // Store the exponent.
+  key_struct->exponent = (uint32_t)BN_get_word(key->e);
+
+  ret = true;
+
+cleanup:
+  BN_free(rr);
+  BN_free(n0inv);
+  BN_free(r32);
+  BN_CTX_free(ctx);
+  return ret;
+}
diff --git a/libcrypto_utils/include/crypto_utils/android_pubkey.h b/libcrypto_utils/include/crypto_utils/android_pubkey.h
new file mode 100644
index 0000000..1045eba
--- /dev/null
+++ b/libcrypto_utils/include/crypto_utils/android_pubkey.h
@@ -0,0 +1,61 @@
+/*
+ * 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 CRYPTO_UTILS_ANDROID_PUBKEY_H
+#define CRYPTO_UTILS_ANDROID_PUBKEY_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#include <openssl/rsa.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Size of an RSA modulus such as an encrypted block or a signature.
+#define ANDROID_PUBKEY_MODULUS_SIZE (2048 / 8)
+
+// Size of an encoded RSA key.
+#define ANDROID_PUBKEY_ENCODED_SIZE \
+  (3 * sizeof(uint32_t) + 2 * ANDROID_PUBKEY_MODULUS_SIZE)
+
+/* Allocates a new RSA |key| object, decodes a public RSA key stored in
+ * Android's custom binary format from |key_buffer| and sets the key parameters
+ * in |key|. |size| specifies the size of the key buffer and must be at least
+ * |ANDROID_PUBKEY_ENCODED_SIZE|. The resulting |*key| can be used with the
+ * standard BoringSSL API to perform public operations.
+ *
+ * Returns true if successful, in which case the caller receives ownership of
+ * the |*key| object, i.e. needs to call RSA_free() when done with it. If there
+ * is an error, |key| is left untouched and the return value will be false.
+ */
+bool android_pubkey_decode(const uint8_t* key_buffer, size_t size, RSA** key);
+
+/* Encodes |key| in the Android RSA public key binary format and stores the
+ * bytes in |key_buffer|. |key_buffer| should be of size at least
+ * |ANDROID_PUBKEY_ENCODED_SIZE|.
+ *
+ * Returns true if successful, false on error.
+ */
+bool android_pubkey_encode(const RSA* key, uint8_t* key_buffer, size_t size);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif  // CRYPTO_UTILS_ANDROID_PUBKEY_H
diff --git a/libcrypto_utils/tests/Android.mk b/libcrypto_utils/tests/Android.mk
new file mode 100644
index 0000000..ef3d0cf
--- /dev/null
+++ b/libcrypto_utils/tests/Android.mk
@@ -0,0 +1,24 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libcrypto_utils_test
+LOCAL_SRC_FILES := android_pubkey_test.cpp
+LOCAL_CFLAGS := -Wall -Werror -Wextra
+LOCAL_SHARED_LIBRARIES := libcrypto_utils libcrypto
+include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libcrypto_utils/tests/android_pubkey_test.cpp b/libcrypto_utils/tests/android_pubkey_test.cpp
new file mode 100644
index 0000000..f8c2e0c
--- /dev/null
+++ b/libcrypto_utils/tests/android_pubkey_test.cpp
@@ -0,0 +1,129 @@
+/*
+ * 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 <crypto_utils/android_pubkey.h>
+
+#include <string.h>
+
+#include <memory>
+
+#include <openssl/obj_mac.h>
+#include <openssl/rsa.h>
+
+#include <gtest/gtest.h>
+
+// Test digest to verify.
+const uint8_t kDigest[] = {
+    0x31, 0x5f, 0x5b, 0xdb, 0x76, 0xd0, 0x78, 0xc4, 0x3b, 0x8a, 0xc0,
+    0x06, 0x4e, 0x4a, 0x01, 0x64, 0x61, 0x2b, 0x1f, 0xce, 0x77, 0xc8,
+    0x69, 0x34, 0x5b, 0xfc, 0x94, 0xc7, 0x58, 0x94, 0xed, 0xd3,
+};
+
+// 2048 RSA test key.
+const uint8_t kKey2048[ANDROID_PUBKEY_ENCODED_SIZE] = {
+    0x40, 0x00, 0x00, 0x00, 0x05, 0x75, 0x61, 0xd1, 0x33, 0xf0, 0x2d, 0x12,
+    0x45, 0xfb, 0xae, 0x07, 0x02, 0x15, 0x4f, 0x3a, 0x2b, 0xa3, 0xbc, 0x49,
+    0xbd, 0x14, 0x07, 0xa0, 0xc0, 0x9f, 0x0c, 0x52, 0x60, 0x77, 0x9f, 0xa2,
+    0x31, 0xd0, 0xa7, 0xfb, 0x7e, 0xde, 0xfb, 0xc9, 0x05, 0xc0, 0x97, 0xf7,
+    0x74, 0x99, 0xe6, 0xd1, 0x08, 0xa6, 0xc2, 0x59, 0x5a, 0xd8, 0x37, 0x1d,
+    0xe0, 0x48, 0x5e, 0x63, 0x44, 0x04, 0x8b, 0x05, 0x20, 0xf6, 0x25, 0x67,
+    0x38, 0xb2, 0xb6, 0xf9, 0xbe, 0xb6, 0x1d, 0x7f, 0x1b, 0x71, 0x8a, 0xeb,
+    0xb7, 0xf8, 0x01, 0xc1, 0x5e, 0xf7, 0xfe, 0x48, 0x08, 0x27, 0x0f, 0x27,
+    0x2a, 0x64, 0x1a, 0x43, 0x8d, 0xcf, 0x5a, 0x33, 0x5c, 0x18, 0xc5, 0xf4,
+    0xe7, 0xfe, 0xee, 0xd3, 0x12, 0x62, 0xad, 0x61, 0x78, 0x9a, 0x03, 0xb0,
+    0xaf, 0xab, 0x91, 0x57, 0x46, 0xbf, 0x18, 0xc6, 0xbc, 0x0c, 0x6b, 0x55,
+    0xcd, 0xda, 0xc4, 0xcc, 0x98, 0x46, 0x91, 0x99, 0xbc, 0xa3, 0xca, 0x6c,
+    0x86, 0xa6, 0x1c, 0x8f, 0xca, 0xf8, 0xf6, 0x8a, 0x00, 0x8e, 0x05, 0xd7,
+    0x13, 0x43, 0xe2, 0xf2, 0x1a, 0x13, 0xf3, 0x50, 0x13, 0xa4, 0xf2, 0x4e,
+    0x41, 0xb1, 0x36, 0x78, 0x55, 0x4c, 0x5e, 0x27, 0xc5, 0xc0, 0x4b, 0xd8,
+    0x93, 0xaa, 0x7e, 0xf0, 0x90, 0x08, 0x10, 0x26, 0x72, 0x6d, 0xb9, 0x21,
+    0xae, 0x4d, 0x01, 0x4b, 0x55, 0x1d, 0xe7, 0x1e, 0x5e, 0x31, 0x6e, 0x62,
+    0xd1, 0x33, 0x26, 0xcb, 0xdb, 0xfe, 0x72, 0x98, 0xc8, 0x06, 0x1c, 0x12,
+    0xdf, 0xfc, 0x74, 0xe5, 0x7a, 0x6f, 0xf5, 0xa3, 0x63, 0x08, 0xe3, 0x02,
+    0x68, 0x4d, 0x7c, 0x70, 0x05, 0xec, 0x95, 0x7e, 0x24, 0xa4, 0xbc, 0x4c,
+    0xcd, 0x39, 0x14, 0xb5, 0x2a, 0x8f, 0xc1, 0xe3, 0x4e, 0xfa, 0xf8, 0x70,
+    0x50, 0x8f, 0xd5, 0x8e, 0xc7, 0xb5, 0x32, 0x89, 0x4d, 0xbb, 0x6a, 0xc1,
+    0xc1, 0xa2, 0x42, 0x57, 0x57, 0xbd, 0x2a, 0xdc, 0xa6, 0xfd, 0xc8, 0x86,
+    0x44, 0x6a, 0x03, 0x5d, 0x4d, 0x28, 0xe1, 0xde, 0xb4, 0xa9, 0xa5, 0x03,
+    0x61, 0x7a, 0x5f, 0xb1, 0x09, 0x17, 0x2b, 0x9c, 0xa2, 0x54, 0x28, 0xad,
+    0x34, 0xc9, 0x5f, 0x6c, 0x9f, 0xb8, 0xd2, 0xa9, 0x78, 0xa7, 0xaa, 0xb3,
+    0x11, 0x2f, 0x65, 0x9b, 0x4e, 0x67, 0x0c, 0xcc, 0x20, 0x36, 0xbf, 0x26,
+    0x2b, 0x4e, 0xc0, 0xd4, 0xbd, 0x22, 0x64, 0xc4, 0x1c, 0x56, 0x69, 0xdb,
+    0x5f, 0x89, 0xe1, 0x75, 0x68, 0x8d, 0x0e, 0xab, 0x1c, 0x10, 0x1a, 0xc0,
+    0x12, 0x5d, 0x6f, 0xbd, 0x09, 0xbb, 0x47, 0xcb, 0xe7, 0x34, 0xef, 0x56,
+    0xab, 0xea, 0xc3, 0xe9, 0x7f, 0x9a, 0x3d, 0xe9, 0x2d, 0x14, 0x61, 0x25,
+    0x37, 0x5c, 0x3b, 0x4b, 0xaf, 0x5a, 0x4b, 0xc8, 0x99, 0x1a, 0x32, 0x8f,
+    0x54, 0x07, 0xd3, 0x57, 0x8a, 0x3d, 0x2a, 0xf7, 0x9e, 0x7e, 0x92, 0x2a,
+    0x50, 0xe9, 0xd8, 0xdb, 0xd6, 0x03, 0xd3, 0x8e, 0x54, 0x32, 0xce, 0x87,
+    0x93, 0x92, 0xe7, 0x75, 0xe1, 0x6b, 0x78, 0x1a, 0x85, 0xc2, 0x46, 0xa1,
+    0x31, 0xbb, 0xc7, 0xb9, 0x1d, 0xd1, 0x71, 0xe0, 0xe2, 0x9b, 0x9c, 0x0d,
+    0xa3, 0xcf, 0x93, 0x4d, 0x87, 0x7b, 0x65, 0xd9, 0xda, 0x4c, 0xd9, 0x6a,
+    0xa6, 0x36, 0xc2, 0xc7, 0xe3, 0x33, 0xe2, 0xc3, 0x83, 0xd1, 0x72, 0x54,
+    0x30, 0x81, 0x5e, 0x34, 0x2c, 0x61, 0xee, 0xf4, 0x48, 0x97, 0xb6, 0xaa,
+    0x47, 0x6a, 0x05, 0x09, 0xd8, 0x4d, 0x90, 0xaf, 0xa8, 0x4e, 0x82, 0xe4,
+    0x8e, 0xb5, 0xe2, 0x65, 0x86, 0x67, 0xe9, 0x5b, 0x4b, 0x9a, 0x68, 0x08,
+    0x30, 0xf6, 0x25, 0x8b, 0x20, 0xda, 0x26, 0x6f, 0xbd, 0x0d, 0xa5, 0xd8,
+    0x6a, 0x7b, 0x01, 0x2f, 0xab, 0x7b, 0xb5, 0xfe, 0x62, 0x37, 0x2d, 0x94,
+    0x43, 0x2f, 0x4d, 0x16, 0x01, 0x00, 0x01, 0x00,
+};
+
+// 2048 bit RSA signature.
+const uint8_t kSignature2048[ANDROID_PUBKEY_MODULUS_SIZE] = {
+    0x3a, 0x11, 0x84, 0x40, 0xc1, 0x2f, 0x13, 0x8c, 0xde, 0xb0, 0xc3, 0x89,
+    0x8a, 0x63, 0xb2, 0x50, 0x93, 0x58, 0xc0, 0x0c, 0xb7, 0x08, 0xe7, 0x6c,
+    0x52, 0x87, 0x4e, 0x78, 0x89, 0xa3, 0x9a, 0x47, 0xeb, 0x11, 0x57, 0xbc,
+    0xb3, 0x97, 0xf8, 0x34, 0xf1, 0xf7, 0xbf, 0x3a, 0xfa, 0x1c, 0x6b, 0xdc,
+    0xd1, 0x02, 0xde, 0x9a, 0x0d, 0x72, 0xe7, 0x19, 0x63, 0x81, 0x46, 0x68,
+    0x1e, 0x63, 0x64, 0xc6, 0x59, 0xe7, 0x7c, 0x39, 0xed, 0x32, 0xd2, 0xd1,
+    0xd5, 0x1f, 0x13, 0x9b, 0x52, 0xdf, 0x34, 0xa3, 0xc0, 0xc4, 0x9a, 0x63,
+    0x9b, 0x9c, 0xbe, 0x22, 0xc8, 0xd8, 0x14, 0x2f, 0x4c, 0x78, 0x36, 0xdb,
+    0x16, 0x41, 0x67, 0xc1, 0x21, 0x8a, 0x73, 0xb2, 0xe5, 0xb0, 0xd3, 0x80,
+    0x91, 0x7a, 0xbf, 0xf9, 0x59, 0x4a, 0x4d, 0x78, 0x45, 0x44, 0xa1, 0x52,
+    0x86, 0x29, 0x48, 0x4d, 0xf0, 0x5d, 0xf2, 0x55, 0xa7, 0xcd, 0xc5, 0x2b,
+    0x7b, 0xe0, 0xb1, 0xf6, 0x2a, 0xd5, 0x61, 0xba, 0x1e, 0x1e, 0x3a, 0xf0,
+    0x55, 0xbc, 0x8c, 0x44, 0x41, 0xfc, 0xb8, 0x8c, 0x76, 0xbf, 0x80, 0x58,
+    0x82, 0x35, 0x4b, 0x0c, 0xfd, 0xef, 0xd5, 0x70, 0xd1, 0x64, 0xcb, 0x46,
+    0x58, 0x37, 0xbc, 0xa9, 0x7d, 0xd4, 0x70, 0xac, 0xce, 0xec, 0xca, 0x48,
+    0xcb, 0x0a, 0x40, 0x77, 0x04, 0x59, 0xca, 0x9c, 0x7d, 0x1a, 0x0b, 0xf0,
+    0xb5, 0xdd, 0xde, 0x71, 0x18, 0xb8, 0xef, 0x90, 0x2a, 0x09, 0x42, 0x39,
+    0x74, 0xff, 0x45, 0xa1, 0x39, 0x17, 0x50, 0x89, 0xa6, 0x5f, 0xbc, 0x9c,
+    0x0c, 0x9b, 0x47, 0x25, 0x79, 0x3e, 0xe3, 0xaa, 0xaf, 0xbe, 0x73, 0x6b,
+    0xcb, 0xe7, 0x35, 0xc1, 0x27, 0x09, 0xcd, 0xeb, 0xd7, 0xcf, 0x63, 0x83,
+    0x64, 0x8c, 0x45, 0x1c, 0x1d, 0x58, 0xcc, 0xd2, 0xf8, 0x2b, 0x4c, 0x4e,
+    0x14, 0x89, 0x2d, 0x70,
+};
+
+struct AndroidPubkeyTest : public ::testing::Test {
+  void SetUp() override {
+    RSA* new_key = nullptr;
+    ASSERT_TRUE(android_pubkey_decode(kKey2048, sizeof(kKey2048), &new_key));
+    key_.reset(new_key);
+  }
+
+  std::unique_ptr<RSA, void(*)(RSA*)> key_ = {nullptr, RSA_free};
+};
+
+TEST_F(AndroidPubkeyTest, Decode) {
+  // Make sure the decoded key successfully verifies a valid signature.
+  EXPECT_TRUE(RSA_verify(NID_sha256, kDigest, sizeof(kDigest), kSignature2048,
+                         sizeof(kSignature2048), key_.get()));
+}
+
+TEST_F(AndroidPubkeyTest, Encode) {
+  uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
+  ASSERT_TRUE(android_pubkey_encode(key_.get(), key_data, sizeof(key_data)));
+  ASSERT_EQ(0, memcmp(kKey2048, key_data, sizeof(kKey2048)));
+}
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
new file mode 100644
index 0000000..513736d
--- /dev/null
+++ b/libcutils/Android.bp
@@ -0,0 +1,161 @@
+//
+// Copyright (C) 2008 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.
+//
+
+// some files must not be compiled when building against Mingw
+// they correspond to features not used by our host development tools
+// which are also hard or even impossible to port to native Win32
+libcutils_nonwindows_sources = [
+    "android_get_control_file.cpp",
+    "fs.c",
+    "multiuser.c",
+    "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_headers",
+    vendor_available: true,
+    host_supported: true,
+    export_include_dirs: ["include"],
+    target: {
+        vendor: {
+            export_include_dirs: ["include_vndk"],
+        },
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
+
+cc_library {
+    name: "libcutils",
+    vendor_available: true,
+    host_supported: true,
+    srcs: [
+        "config_utils.c",
+        "fs_config.c",
+        "canned_fs_config.c",
+        "hashmap.c",
+        "iosched_policy.c",
+        "load_file.c",
+        "native_handle.c",
+        "open_memstream.c",
+        "record_stream.c",
+        "sched_policy.cpp",
+        "sockets.cpp",
+        "strdup16to8.c",
+        "strdup8to16.c",
+        "strlcpy.c",
+        "threads.c",
+    ],
+
+    target: {
+        host: {
+            srcs: ["dlmalloc_stubs.c"],
+        },
+        linux_bionic: {
+            enabled: true,
+            exclude_srcs: ["dlmalloc_stubs.c"],
+        },
+        not_windows: {
+            srcs: libcutils_nonwindows_sources + [
+                "ashmem-host.c",
+                "trace-host.c",
+            ],
+        },
+        windows: {
+            srcs: [
+                "socket_inaddr_any_server_windows.c",
+                "socket_network_client_windows.c",
+                "sockets_windows.cpp",
+            ],
+
+            enabled: true,
+            shared: {
+                enabled: false,
+            },
+        },
+
+        android: {
+            srcs: libcutils_nonwindows_sources + [
+                "android_reboot.c",
+                "ashmem-dev.c",
+                "klog.cpp",
+                "partition_utils.c",
+                "properties.cpp",
+                "qtaguid.c",
+                "trace-dev.c",
+                "uevent.c",
+            ],
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
+        },
+
+        android_arm: {
+            srcs: ["arch-arm/memset32.S"],
+        },
+        android_arm64: {
+            srcs: ["arch-arm64/android_memset.S"],
+        },
+
+        android_mips: {
+            srcs: ["arch-mips/android_memset.c"],
+        },
+        android_mips64: {
+            srcs: ["arch-mips/android_memset.c"],
+        },
+
+        android_x86: {
+            srcs: [
+                "arch-x86/android_memset16.S",
+                "arch-x86/android_memset32.S",
+            ],
+        },
+
+        android_x86_64: {
+            srcs: [
+                "arch-x86_64/android_memset16.S",
+                "arch-x86_64/android_memset32.S",
+            ],
+        },
+    },
+
+    shared_libs: ["liblog"],
+    header_libs: [
+        "libcutils_headers",
+        "libutils_headers",
+    ],
+    export_header_lib_headers: ["libcutils_headers"],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-Wextra",
+    ],
+
+    clang: true,
+}
+
+subdirs = ["tests"]
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
deleted file mode 100644
index 0c6e5a1..0000000
--- a/libcutils/Android.mk
+++ /dev/null
@@ -1,151 +0,0 @@
-#
-# Copyright (C) 2008 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 := $(my-dir)
-include $(CLEAR_VARS)
-
-libcutils_common_sources := \
-        atomic.c.arm \
-        config_utils.c \
-        fs_config.c \
-        canned_fs_config.c \
-        hashmap.c \
-        iosched_policy.c \
-        load_file.c \
-        native_handle.c \
-        open_memstream.c \
-        process_name.c \
-        record_stream.c \
-        sched_policy.c \
-        sockets.cpp \
-        strdup16to8.c \
-        strdup8to16.c \
-        strlcpy.c \
-        threads.c \
-
-# some files must not be compiled when building against Mingw
-# they correspond to features not used by our host development tools
-# which are also hard or even impossible to port to native Win32
-libcutils_nonwindows_sources := \
-        fs.c \
-        multiuser.c \
-        socket_inaddr_any_server_unix.c \
-        socket_local_client_unix.c \
-        socket_local_server_unix.c \
-        socket_loopback_client_unix.c \
-        socket_loopback_server_unix.c \
-        socket_network_client_unix.c \
-        sockets_unix.cpp \
-        str_parms.c \
-
-libcutils_nonwindows_host_sources := \
-        ashmem-host.c \
-        trace-host.c \
-
-libcutils_windows_host_sources := \
-        socket_inaddr_any_server_windows.c \
-        socket_network_client_windows.c \
-        sockets_windows.cpp \
-
-# Shared and static library for host
-# Note: when linking this library on Windows, you must also link to Winsock2
-# using "LOCAL_LDLIBS_windows := -lws2_32".
-# ========================================================
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) dlmalloc_stubs.c
-LOCAL_SRC_FILES_darwin := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_linux := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_windows := $(libcutils_windows_host_sources)
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror -Wall -Wextra
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) dlmalloc_stubs.c
-LOCAL_SRC_FILES_darwin := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SRC_FILES_linux := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror -Wall -Wextra
-LOCAL_MULTILIB := both
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-
-
-# Shared and static library for target
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-LOCAL_SRC_FILES := $(libcutils_common_sources) \
-        $(libcutils_nonwindows_sources) \
-        android_reboot.c \
-        ashmem-dev.c \
-        debugger.c \
-        klog.c \
-        partition_utils.c \
-        properties.c \
-        qtaguid.c \
-        trace-dev.c \
-        uevent.c \
-
-LOCAL_SRC_FILES_arm += arch-arm/memset32.S
-LOCAL_SRC_FILES_arm64 += arch-arm64/android_memset.S
-
-LOCAL_SRC_FILES_mips += arch-mips/android_memset.c
-LOCAL_SRC_FILES_mips64 += arch-mips/android_memset.c
-
-LOCAL_SRC_FILES_x86 += \
-        arch-x86/android_memset16.S \
-        arch-x86/android_memset32.S \
-
-LOCAL_SRC_FILES_x86_64 += \
-        arch-x86_64/android_memset16.S \
-        arch-x86_64/android_memset32.S \
-
-LOCAL_C_INCLUDES := $(libcutils_c_includes)
-LOCAL_STATIC_LIBRARIES := liblog
-ifneq ($(ENABLE_CPUSETS),)
-LOCAL_CFLAGS += -DUSE_CPUSETS
-endif
-ifneq ($(ENABLE_SCHEDBOOST),)
-LOCAL_CFLAGS += -DUSE_SCHEDBOOST
-endif
-LOCAL_CFLAGS += -Werror -Wall -Wextra -std=gnu90
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils
-# TODO: remove liblog as whole static library, once we don't have prebuilt that requires
-# liblog symbols present in libcutils.
-LOCAL_WHOLE_STATIC_LIBRARIES := libcutils liblog
-LOCAL_SHARED_LIBRARIES := liblog
-ifneq ($(ENABLE_CPUSETS),)
-LOCAL_CFLAGS += -DUSE_CPUSETS
-endif
-ifneq ($(ENABLE_SCHEDBOOST),)
-LOCAL_CFLAGS += -DUSE_SCHEDBOOST
-endif
-LOCAL_CFLAGS += -Werror -Wall -Wextra
-LOCAL_C_INCLUDES := $(libcutils_c_includes)
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_SHARED_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libcutils/android_get_control_env.h b/libcutils/android_get_control_env.h
new file mode 100644
index 0000000..638c831
--- /dev/null
+++ b/libcutils/android_get_control_env.h
@@ -0,0 +1,33 @@
+/*
+ * 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 __CUTILS_ANDROID_GET_CONTROL_ENV_H
+#define __CUTILS_ANDROID_GET_CONTROL_ENV_H
+
+/* To declare library function hidden and internal */
+#define LIBCUTILS_HIDDEN __attribute__((visibility("hidden")))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+LIBCUTILS_HIDDEN int __android_get_control_from_env(const char* prefix,
+                                                    const char* name);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_ANDROID_GET_CONTROL_ENV_H */
diff --git a/libcutils/android_get_control_file.cpp b/libcutils/android_get_control_file.cpp
new file mode 100644
index 0000000..780d9f1
--- /dev/null
+++ b/libcutils/android_get_control_file.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <cutils/android_get_control_file.h>
+
+#include "android_get_control_env.h"
+
+#ifndef TEMP_FAILURE_RETRY
+#define TEMP_FAILURE_RETRY(exp) (exp) // KISS implementation
+#endif
+
+LIBCUTILS_HIDDEN int __android_get_control_from_env(const char* prefix,
+                                                    const char* name) {
+    if (!prefix || !name) return -1;
+
+    char *key = NULL;
+    if (asprintf(&key, "%s%s", prefix, name) < 0) return -1;
+    if (!key) return -1;
+
+    char *cp = key;
+    while (*cp) {
+        if (!isalnum(*cp)) *cp = '_';
+        ++cp;
+    }
+
+    const char* val = getenv(key);
+    free(key);
+    if (!val) return -1;
+
+    errno = 0;
+    long fd = strtol(val, NULL, 10);
+    if (errno) return -1;
+
+    // validity checking
+    if ((fd < 0) || (fd > INT_MAX)) return -1;
+
+    // Since we are inheriting an fd, it could legitimately exceed _SC_OPEN_MAX
+
+    // Still open?
+#if defined(F_GETFD) // Lowest overhead
+    if (TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD)) < 0) return -1;
+#elif defined(F_GETFL) // Alternate lowest overhead
+    if (TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL)) < 0) return -1;
+#else // Hail Mary pass
+    struct stat s;
+    if (TEMP_FAILURE_RETRY(fstat(fd, &s)) < 0) return -1;
+#endif
+
+    return static_cast<int>(fd);
+}
+
+int android_get_control_file(const char* path) {
+    int fd = __android_get_control_from_env(ANDROID_FILE_ENV_PREFIX, path);
+
+#if defined(__linux__)
+    // Find file path from /proc and make sure it is correct
+    char *proc = NULL;
+    if (asprintf(&proc, "/proc/self/fd/%d", fd) < 0) return -1;
+    if (!proc) return -1;
+
+    size_t len = strlen(path);
+    // readlink() does not guarantee a nul byte, len+2 so we catch truncation.
+    char *buf = static_cast<char *>(calloc(1, len + 2));
+    if (!buf) {
+        free(proc);
+        return -1;
+    }
+    ssize_t ret = TEMP_FAILURE_RETRY(readlink(proc, buf, len + 1));
+    free(proc);
+    int cmp = (len != static_cast<size_t>(ret)) || strcmp(buf, path);
+    free(buf);
+    if (ret < 0) return -1;
+    if (cmp != 0) return -1;
+    // It is what we think it is
+#endif
+
+    return fd;
+}
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index af7e189..a33e45f 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -13,230 +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 has_mount_option(const char* opts, const char* opt_to_find)
-{
-  bool ret = false;
-  char* copy = NULL;
-  char* opt;
-  char* rem;
-
-  while ((opt = strtok_r(copy ? NULL : (copy = strdup(opts)), ",", &rem))) {
-      if (!strcmp(opt, opt_to_find)) {
-          ret = true;
-          break;
-      }
-  }
-
-  free(copy);
-  return ret;
-}
-
-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) &&
-            has_mount_option(mentry->mnt_opts, "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) ||
-                !has_mount_option(mentry->mnt_opts, "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);
-}
-
-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;
-    remount_ro(cb_on_remount);
+    const char* restart_cmd = NULL;
+    char* prop_value;
+
     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;
-
-        default:
-            ret = -1;
+        case ANDROID_RB_POWEROFF:
+            restart_cmd = "shutdown";
+            break;
+        case ANDROID_RB_THERMOFF:
+            restart_cmd = "thermal-shutdown";
+            break;
     }
-
+    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/ashmem-dev.c b/libcutils/ashmem-dev.c
index 4a07d66..92717c0 100644
--- a/libcutils/ashmem-dev.c
+++ b/libcutils/ashmem-dev.c
@@ -23,6 +23,7 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <linux/ashmem.h>
 #include <pthread.h>
 #include <string.h>
 #include <sys/ioctl.h>
@@ -30,8 +31,6 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <linux/ashmem.h>
-
 #include <cutils/ashmem.h>
 #include <log/log.h>
 
@@ -85,7 +84,7 @@
 }
 
 /* Make sure file descriptor references ashmem, negative number means false */
-static int __ashmem_is_ashmem(int fd)
+static int __ashmem_is_ashmem(int fd, int fatal)
 {
     dev_t rdev;
     struct stat st;
@@ -117,22 +116,29 @@
         }
     }
 
-    if (rdev) {
-        LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
-          fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
-          S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
-          major(rdev), minor(rdev));
-    } else {
-        LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
-          fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
-          S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
+    if (fatal) {
+        if (rdev) {
+            LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
+              fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
+              S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
+              major(rdev), minor(rdev));
+        } else {
+            LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
+              fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
+              S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
+        }
+        /* NOTREACHED */
     }
-    /* NOTREACHED */
 
     errno = ENOTTY;
     return -1;
 }
 
+int ashmem_valid(int fd)
+{
+    return __ashmem_is_ashmem(fd, 0) >= 0;
+}
+
 /*
  * ashmem_create_region - creates a new ashmem region and returns the file
  * descriptor, or <0 on error
@@ -175,7 +181,7 @@
 
 int ashmem_set_prot_region(int fd, int prot)
 {
-    int ret = __ashmem_is_ashmem(fd);
+    int ret = __ashmem_is_ashmem(fd, 1);
     if (ret < 0) {
         return ret;
     }
@@ -187,7 +193,7 @@
 {
     struct ashmem_pin pin = { offset, len };
 
-    int ret = __ashmem_is_ashmem(fd);
+    int ret = __ashmem_is_ashmem(fd, 1);
     if (ret < 0) {
         return ret;
     }
@@ -199,7 +205,7 @@
 {
     struct ashmem_pin pin = { offset, len };
 
-    int ret = __ashmem_is_ashmem(fd);
+    int ret = __ashmem_is_ashmem(fd, 1);
     if (ret < 0) {
         return ret;
     }
@@ -209,7 +215,7 @@
 
 int ashmem_get_size_region(int fd)
 {
-    int ret = __ashmem_is_ashmem(fd);
+    int ret = __ashmem_is_ashmem(fd, 1);
     if (ret < 0) {
         return ret;
     }
diff --git a/libcutils/ashmem-host.c b/libcutils/ashmem-host.c
index c85f06b..1f9f753 100644
--- a/libcutils/ashmem-host.c
+++ b/libcutils/ashmem-host.c
@@ -62,12 +62,12 @@
 
 int ashmem_pin_region(int fd __unused, size_t offset __unused, size_t len __unused)
 {
-    return ASHMEM_NOT_PURGED;
+    return 0 /*ASHMEM_NOT_PURGED*/;
 }
 
 int ashmem_unpin_region(int fd __unused, size_t offset __unused, size_t len __unused)
 {
-    return ASHMEM_IS_UNPINNED;
+    return 0 /*ASHMEM_IS_UNPINNED*/;
 }
 
 int ashmem_get_size_region(int fd)
diff --git a/libcutils/atomic.c b/libcutils/atomic.c
deleted file mode 100644
index d34aa00..0000000
--- a/libcutils/atomic.c
+++ /dev/null
@@ -1,26 +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.
- */
-
-/*
- * Generate non-inlined versions of android_atomic functions.
- * Nobody should be using these, but some binary blobs currently (late 2014)
- * are.
- * If you read this in 2015 or later, please try to delete this file.
- */
-
-#define ANDROID_ATOMIC_INLINE
-
-#include <cutils/atomic.h>
diff --git a/libcutils/canned_fs_config.c b/libcutils/canned_fs_config.c
index 5800857..e0e6a34 100644
--- a/libcutils/canned_fs_config.c
+++ b/libcutils/canned_fs_config.c
@@ -14,22 +14,22 @@
  * limitations under the License.
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
 #include <errno.h>
+#include <inttypes.h>
 #include <limits.h>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 
 #include <private/android_filesystem_config.h>
 #include <private/canned_fs_config.h>
 
 typedef struct {
-	const char* path;
-	unsigned uid;
-	unsigned gid;
-	unsigned mode;
-	uint64_t capabilities;
+    const char* path;
+    unsigned uid;
+    unsigned gid;
+    unsigned mode;
+    uint64_t capabilities;
 } Path;
 
 static Path* canned_data = NULL;
@@ -37,81 +37,87 @@
 static int canned_used = 0;
 
 static int path_compare(const void* a, const void* b) {
-	return strcmp(((Path*)a)->path, ((Path*)b)->path);
+    return strcmp(((Path*)a)->path, ((Path*)b)->path);
 }
 
 int load_canned_fs_config(const char* fn) {
-	FILE* f = fopen(fn, "r");
-	if (f == NULL) {
-		fprintf(stderr, "failed to open %s: %s\n", fn, strerror(errno));
-		return -1;
-	}
+    char line[PATH_MAX + 200];
+    FILE* f;
 
-	char line[PATH_MAX + 200];
-	while (fgets(line, sizeof(line), f)) {
-		while (canned_used >= canned_alloc) {
-			canned_alloc = (canned_alloc+1) * 2;
-			canned_data = (Path*) realloc(canned_data, canned_alloc * sizeof(Path));
-		}
-		Path* p = canned_data + canned_used;
-		p->path = strdup(strtok(line, " "));
-		p->uid = atoi(strtok(NULL, " "));
-		p->gid = atoi(strtok(NULL, " "));
-		p->mode = strtol(strtok(NULL, " "), NULL, 8);   // mode is in octal
-		p->capabilities = 0;
+    f = fopen(fn, "r");
+    if (f == NULL) {
+        fprintf(stderr, "failed to open %s: %s\n", fn, strerror(errno));
+        return -1;
+    }
 
-		char* token = NULL;
-		do {
-			token = strtok(NULL, " ");
-			if (token && strncmp(token, "capabilities=", 13) == 0) {
-				p->capabilities = strtoll(token+13, NULL, 0);
-				break;
-			}
-		} while (token);
+    while (fgets(line, sizeof(line), f)) {
+        Path* p;
+        char* token;
 
-		canned_used++;
-	}
+        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, " "));
+        p->gid = atoi(strtok(NULL, " "));
+        p->mode = strtol(strtok(NULL, " "), NULL, 8);   // mode is in octal
+        p->capabilities = 0;
 
-	fclose(f);
+        do {
+            token = strtok(NULL, " ");
+            if (token && strncmp(token, "capabilities=", 13) == 0) {
+                p->capabilities = strtoll(token+13, NULL, 0);
+                break;
+            }
+        } while (token);
 
-	qsort(canned_data, canned_used, sizeof(Path), path_compare);
-	printf("loaded %d fs_config entries\n", canned_used);
+        canned_used++;
+    }
 
-	return 0;
+    fclose(f);
+
+    qsort(canned_data, canned_used, sizeof(Path), path_compare);
+    printf("loaded %d fs_config entries\n", canned_used);
+
+    return 0;
 }
 
 static const int kDebugCannedFsConfig = 0;
 
 void canned_fs_config(const char* path, int dir, const char* target_out_path,
-					  unsigned* uid, unsigned* gid, unsigned* mode, uint64_t* capabilities) {
-	Path key;
+                      unsigned* uid, unsigned* gid, unsigned* mode, uint64_t* capabilities) {
+    Path key, *p;
+
     key.path = path;
-    if (path[0] == '/')
-        key.path++;   // canned paths lack the leading '/'
-	Path* p = (Path*) bsearch(&key, canned_data, canned_used, sizeof(Path), path_compare);
-	if (p == NULL) {
-		fprintf(stderr, "failed to find [%s] in canned fs_config\n", path);
-		exit(1);
-	}
-	*uid = p->uid;
-	*gid = p->gid;
-	*mode = p->mode;
-	*capabilities = p->capabilities;
+    if (path[0] == '/') key.path++; // canned paths lack the leading '/'
+    p = (Path*) bsearch(&key, canned_data, canned_used, sizeof(Path), path_compare);
+    if (p == NULL) {
+        fprintf(stderr, "failed to find [%s] in canned fs_config\n", path);
+        exit(1);
+    }
+    *uid = p->uid;
+    *gid = p->gid;
+    *mode = p->mode;
+    *capabilities = p->capabilities;
 
-	if (kDebugCannedFsConfig) {
-		// for debugging, run the built-in fs_config and compare the results.
+    if (kDebugCannedFsConfig) {
+        // for debugging, run the built-in fs_config and compare the results.
 
-		unsigned c_uid, c_gid, c_mode;
-		uint64_t c_capabilities;
-		fs_config(path, dir, target_out_path, &c_uid, &c_gid, &c_mode, &c_capabilities);
+        unsigned c_uid, c_gid, c_mode;
+        uint64_t c_capabilities;
 
-		if (c_uid != *uid) printf("%s uid %d %d\n", path, *uid, c_uid);
-		if (c_gid != *gid) printf("%s gid %d %d\n", path, *gid, c_gid);
-		if (c_mode != *mode) printf("%s mode 0%o 0%o\n", path, *mode, c_mode);
-		if (c_capabilities != *capabilities)
-			printf("%s capabilities %" PRIx64 " %" PRIx64 "\n",
-				path,
-				*capabilities,
-				c_capabilities);
+        fs_config(path, dir, target_out_path, &c_uid, &c_gid, &c_mode, &c_capabilities);
+
+        if (c_uid != *uid) printf("%s uid %d %d\n", path, *uid, c_uid);
+        if (c_gid != *gid) printf("%s gid %d %d\n", path, *gid, c_gid);
+        if (c_mode != *mode) printf("%s mode 0%o 0%o\n", path, *mode, c_mode);
+        if (c_capabilities != *capabilities) {
+            printf("%s capabilities %" PRIx64 " %" PRIx64 "\n",
+                path,
+                *capabilities,
+                c_capabilities);
         }
+    }
 }
diff --git a/libcutils/debugger.c b/libcutils/debugger.c
deleted file mode 100644
index 3407ec3..0000000
--- a/libcutils/debugger.c
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdbool.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include <cutils/debugger.h>
-#include <cutils/sockets.h>
-
-#define LOG_TAG "DEBUG"
-#include <log/log.h>
-
-static int send_request(int sock_fd, void* msg_ptr, size_t msg_len) {
-  int result = 0;
-  if (TEMP_FAILURE_RETRY(write(sock_fd, msg_ptr, msg_len)) != (ssize_t) msg_len) {
-    result = -1;
-  } else {
-    char ack;
-    if (TEMP_FAILURE_RETRY(read(sock_fd, &ack, 1)) != 1) {
-      result = -1;
-    }
-  }
-  return result;
-}
-
-static int make_dump_request(debugger_action_t action, pid_t tid, int timeout_secs) {
-  debugger_msg_t msg;
-  memset(&msg, 0, sizeof(msg));
-  msg.tid = tid;
-  msg.action = action;
-
-  int sock_fd = socket_local_client(DEBUGGER_SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
-      SOCK_STREAM | SOCK_CLOEXEC);
-  if (sock_fd < 0) {
-    return -1;
-  }
-
-  if (timeout_secs > 0) {
-    struct timeval tm;
-    tm.tv_sec = timeout_secs;
-    tm.tv_usec = 0;
-    if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tm, sizeof(tm)) == -1) {
-      ALOGE("WARNING: Cannot set receive timeout value on socket: %s", strerror(errno));
-    }
-
-    if (setsockopt(sock_fd, SOL_SOCKET, SO_SNDTIMEO, &tm, sizeof(tm)) == -1) {
-      ALOGE("WARNING: Cannot set send timeout value on socket: %s", strerror(errno));
-    }
-  }
-
-  if (send_request(sock_fd, &msg, sizeof(msg)) < 0) {
-    close(sock_fd);
-    return -1;
-  }
-
-  return sock_fd;
-}
-
-int dump_backtrace_to_file(pid_t tid, int fd) {
-  return dump_backtrace_to_file_timeout(tid, fd, 0);
-}
-
-int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs) {
-  int sock_fd = make_dump_request(DEBUGGER_ACTION_DUMP_BACKTRACE, tid, timeout_secs);
-  if (sock_fd < 0) {
-    return -1;
-  }
-
-  /* Write the data read from the socket to the fd. */
-  int result = 0;
-  char buffer[1024];
-  ssize_t n;
-  while ((n = TEMP_FAILURE_RETRY(read(sock_fd, buffer, sizeof(buffer)))) > 0) {
-    if (TEMP_FAILURE_RETRY(write(fd, buffer, n)) != n) {
-      result = -1;
-      break;
-    }
-  }
-  close(sock_fd);
-  return result;
-}
-
-int dump_tombstone(pid_t tid, char* pathbuf, size_t pathlen) {
-  return dump_tombstone_timeout(tid, pathbuf, pathlen, 0);
-}
-
-int dump_tombstone_timeout(pid_t tid, char* pathbuf, size_t pathlen, int timeout_secs) {
-  int sock_fd = make_dump_request(DEBUGGER_ACTION_DUMP_TOMBSTONE, tid, timeout_secs);
-  if (sock_fd < 0) {
-    return -1;
-  }
-
-  /* Read the tombstone file name. */
-  char buffer[100]; /* This is larger than the largest tombstone path. */
-  int result = 0;
-  ssize_t n = TEMP_FAILURE_RETRY(read(sock_fd, buffer, sizeof(buffer) - 1));
-  if (n <= 0) {
-    result = -1;
-  } else {
-    if (pathbuf && pathlen) {
-      if (n >= (ssize_t) pathlen) {
-        n = pathlen - 1;
-      }
-      buffer[n] = '\0';
-      memcpy(pathbuf, buffer, n + 1);
-    }
-  }
-  close(sock_fd);
-  return result;
-}
diff --git a/libcutils/dlmalloc_stubs.c b/libcutils/dlmalloc_stubs.c
index 2db473d..2cff9dd 100644
--- a/libcutils/dlmalloc_stubs.c
+++ b/libcutils/dlmalloc_stubs.c
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "dlmalloc-stubs"
+
 #include "log/log.h"
 
 #define UNUSED __attribute__((__unused__))
diff --git a/libcutils/fs.c b/libcutils/fs.c
index 3f14de7..b253b1c 100644
--- a/libcutils/fs.c
+++ b/libcutils/fs.c
@@ -21,18 +21,19 @@
 #define _ATFILE_SOURCE 1
 #define _GNU_SOURCE 1
 
-#include <cutils/fs.h>
-#include <cutils/log.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
-#include <limits.h>
-#include <stdlib.h>
 #include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <cutils/fs.h>
+#include <log/log.h>
 
 #define ALL_PERMS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
 #define BUF_SIZE 64
@@ -79,7 +80,7 @@
 create:
     create_result = prepare_as_dir
         ? TEMP_FAILURE_RETRY(mkdir(path, mode))
-        : TEMP_FAILURE_RETRY(open(path, O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_RDONLY));
+        : TEMP_FAILURE_RETRY(open(path, O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_RDONLY, 0644));
     if (create_result == -1) {
         if (errno != EEXIST) {
             ALOGE("Failed to %s(%s): %s",
diff --git a/libcutils/fs_config.c b/libcutils/fs_config.c
index 9acfa58..5b9d174 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,86 +101,182 @@
 ** 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" }, // legacy
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/etc/prop.default" },
+    { 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. */
-    { 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" },
+    /* 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),
+                                              "system/bin/logd" },
+    { 00750, AID_ROOT,      AID_SHELL,     CAP_MASK_LONG(CAP_SETUID) |
+                                           CAP_MASK_LONG(CAP_SETGID),
+                                              "system/bin/run-as" },
 
     /* 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" },
 
-    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/uncrypt" },
-    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/install-recovery.sh" },
+    /* Support hostapd administering a network interface. */
+    { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
+                                           CAP_MASK_LONG(CAP_NET_RAW),
+                                              "system/vendor/bin/hostapd" },
+    { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
+                                           CAP_MASK_LONG(CAP_NET_RAW),
+                                              "vendor/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" },
+
+    /* 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),
+                                              "system/bin/webview_zygote32" },
+    { 0750,  AID_ROOT,      AID_ROOT,      CAP_MASK_LONG(CAP_SETUID) |
+                                           CAP_MASK_LONG(CAP_SETGID) |
+                                           CAP_MASK_LONG(CAP_SETPCAP),
+                                              "system/bin/webview_zygote64" },
+
+    /* 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.*" },
     { 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;
@@ -208,11 +293,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++;
@@ -220,41 +304,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);
@@ -262,8 +348,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;
         }
@@ -274,9 +359,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)) {
@@ -284,11 +368,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_get_control_file.h b/libcutils/include/cutils/android_get_control_file.h
new file mode 100644
index 0000000..ed8fbf8
--- /dev/null
+++ b/libcutils/include/cutils/android_get_control_file.h
@@ -0,0 +1,37 @@
+/*
+ * 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 __CUTILS_ANDROID_GET_CONTROL_FILE_H
+#define __CUTILS_ANDROID_GET_CONTROL_FILE_H
+
+#define ANDROID_FILE_ENV_PREFIX "ANDROID_FILE_"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * android_get_control_file - simple helper function to get the file
+ * descriptor of our init-managed file. `path' is the filename path as
+ * given in init.rc. Returns -1 on error.
+ */
+int android_get_control_file(const char* path);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_ANDROID_GET_CONTROL_FILE_H */
diff --git a/libcutils/include/cutils/android_reboot.h b/libcutils/include/cutils/android_reboot.h
new file mode 100644
index 0000000..716567a
--- /dev/null
+++ b/libcutils/include/cutils/android_reboot.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright 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 __CUTILS_ANDROID_REBOOT_H__
+#define __CUTILS_ANDROID_REBOOT_H__
+
+
+__BEGIN_DECLS
+
+/* Commands */
+#define ANDROID_RB_RESTART 0xDEAD0001 /* deprecated. Use RESTART2. */
+#define ANDROID_RB_POWEROFF 0xDEAD0002
+#define ANDROID_RB_RESTART2 0xDEAD0003
+#define ANDROID_RB_THERMOFF 0xDEAD0004
+
+/* Properties */
+#define ANDROID_RB_PROPERTY "sys.powerctl"
+
+/* 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);
+
+__END_DECLS
+
+#endif /* __CUTILS_ANDROID_REBOOT_H__ */
diff --git a/libcutils/include/cutils/ashmem.h b/libcutils/include/cutils/ashmem.h
new file mode 100644
index 0000000..d80caa6
--- /dev/null
+++ b/libcutils/include/cutils/ashmem.h
@@ -0,0 +1,34 @@
+/* cutils/ashmem.h
+ **
+ ** Copyright 2008 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 _CUTILS_ASHMEM_H
+#define _CUTILS_ASHMEM_H
+
+#include <stddef.h>
+
+#if defined(__BIONIC__)
+#include <linux/ashmem.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int ashmem_valid(int fd);
+int ashmem_create_region(const char *name, size_t size);
+int ashmem_set_prot_region(int fd, int prot);
+int ashmem_pin_region(int fd, size_t offset, size_t len);
+int ashmem_unpin_region(int fd, size_t offset, size_t len);
+int ashmem_get_size_region(int fd);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif	/* _CUTILS_ASHMEM_H */
diff --git a/libcutils/include/cutils/atomic.h b/libcutils/include/cutils/atomic.h
new file mode 100644
index 0000000..0c88bfe
--- /dev/null
+++ b/libcutils/include/cutils/atomic.h
@@ -0,0 +1,246 @@
+/*
+ * 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 ANDROID_CUTILS_ATOMIC_H
+#define ANDROID_CUTILS_ATOMIC_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <stdatomic.h>
+
+#ifndef ANDROID_ATOMIC_INLINE
+#define ANDROID_ATOMIC_INLINE static inline
+#endif
+
+/*
+ * A handful of basic atomic operations.
+ * THESE ARE HERE FOR LEGACY REASONS ONLY.  AVOID.
+ *
+ * PREFERRED ALTERNATIVES:
+ * - Use C++/C/pthread locks/mutexes whenever there is not a
+ *   convincing reason to do otherwise.  Note that very clever and
+ *   complicated, but correct, lock-free code is often slower than
+ *   using locks, especially where nontrivial data structures
+ *   are involved.
+ * - C11 stdatomic.h.
+ * - Where supported, C++11 std::atomic<T> .
+ *
+ * PLEASE STOP READING HERE UNLESS YOU ARE TRYING TO UNDERSTAND
+ * OR UPDATE OLD CODE.
+ *
+ * The "acquire" and "release" terms can be defined intuitively in terms
+ * of the placement of memory barriers in a simple lock implementation:
+ *   - wait until compare-and-swap(lock-is-free --> lock-is-held) succeeds
+ *   - barrier
+ *   - [do work]
+ *   - barrier
+ *   - store(lock-is-free)
+ * In very crude terms, the initial (acquire) barrier prevents any of the
+ * "work" from happening before the lock is held, and the later (release)
+ * barrier ensures that all of the work happens before the lock is released.
+ * (Think of cached writes, cache read-ahead, and instruction reordering
+ * around the CAS and store instructions.)
+ *
+ * The barriers must apply to both the compiler and the CPU.  Note it is
+ * legal for instructions that occur before an "acquire" barrier to be
+ * moved down below it, and for instructions that occur after a "release"
+ * barrier to be moved up above it.
+ *
+ * The ARM-driven implementation we use here is short on subtlety,
+ * and actually requests a full barrier from the compiler and the CPU.
+ * The only difference between acquire and release is in whether they
+ * are issued before or after the atomic operation with which they
+ * are associated.  To ease the transition to C/C++ atomic intrinsics,
+ * you should not rely on this, and instead assume that only the minimal
+ * acquire/release protection is provided.
+ *
+ * NOTE: all int32_t* values are expected to be aligned on 32-bit boundaries.
+ * If they are not, atomicity is not guaranteed.
+ */
+
+ANDROID_ATOMIC_INLINE
+volatile atomic_int_least32_t* to_atomic_int_least32_t(volatile const int32_t* addr) {
+#ifdef __cplusplus
+    return reinterpret_cast<volatile atomic_int_least32_t*>(const_cast<volatile int32_t*>(addr));
+#else
+    return (volatile atomic_int_least32_t*)addr;
+#endif
+}
+
+/*
+ * Basic arithmetic and bitwise operations.  These all provide a
+ * barrier with "release" ordering, and return the previous value.
+ *
+ * These have the same characteristics (e.g. what happens on overflow)
+ * as the equivalent non-atomic C operations.
+ */
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_inc(volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+        /* Int32_t, if it exists, is the same as int_least32_t. */
+    return atomic_fetch_add_explicit(a, 1, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_dec(volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return atomic_fetch_sub_explicit(a, 1, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_add(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return atomic_fetch_add_explicit(a, value, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_and(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return atomic_fetch_and_explicit(a, value, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_or(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return atomic_fetch_or_explicit(a, value, memory_order_release);
+}
+
+/*
+ * Perform an atomic load with "acquire" or "release" ordering.
+ *
+ * Note that the notion of a "release" ordering for a load does not
+ * really fit into the C11 or C++11 memory model.  The extra ordering
+ * is normally observable only by code using memory_order_relaxed
+ * atomics, or data races.  In the rare cases in which such ordering
+ * is called for, use memory_order_relaxed atomics and a leading
+ * atomic_thread_fence (typically with memory_order_acquire,
+ * not memory_order_release!) instead.  If you do not understand
+ * this comment, you are in the vast majority, and should not be
+ * using release loads or replacing them with anything other than
+ * locks or default sequentially consistent atomics.
+ */
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_acquire_load(volatile const int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return atomic_load_explicit(a, memory_order_acquire);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_release_load(volatile const int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    atomic_thread_fence(memory_order_seq_cst);
+    /* Any reasonable clients of this interface would probably prefer   */
+    /* something weaker.  But some remaining clients seem to be         */
+    /* abusing this API in strange ways, e.g. by using it as a fence.   */
+    /* Thus we are conservative until we can get rid of remaining       */
+    /* clients (and this function).                                     */
+    return atomic_load_explicit(a, memory_order_relaxed);
+}
+
+/*
+ * Perform an atomic store with "acquire" or "release" ordering.
+ *
+ * Note that the notion of an "acquire" ordering for a store does not
+ * really fit into the C11 or C++11 memory model.  The extra ordering
+ * is normally observable only by code using memory_order_relaxed
+ * atomics, or data races.  In the rare cases in which such ordering
+ * is called for, use memory_order_relaxed atomics and a trailing
+ * atomic_thread_fence (typically with memory_order_release,
+ * not memory_order_acquire!) instead.
+ */
+ANDROID_ATOMIC_INLINE
+void android_atomic_acquire_store(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    atomic_store_explicit(a, value, memory_order_relaxed);
+    atomic_thread_fence(memory_order_seq_cst);
+    /* Again overly conservative to accomodate weird clients.   */
+}
+
+ANDROID_ATOMIC_INLINE
+void android_atomic_release_store(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    atomic_store_explicit(a, value, memory_order_release);
+}
+
+/*
+ * Compare-and-set operation with "acquire" or "release" ordering.
+ *
+ * This returns zero if the new value was successfully stored, which will
+ * only happen when *addr == oldvalue.
+ *
+ * (The return value is inverted from implementations on other platforms,
+ * but matches the ARM ldrex/strex result.)
+ *
+ * Implementations that use the release CAS in a loop may be less efficient
+ * than possible, because we re-issue the memory barrier on each iteration.
+ */
+ANDROID_ATOMIC_INLINE
+int android_atomic_acquire_cas(int32_t oldvalue, int32_t newvalue,
+                           volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return !atomic_compare_exchange_strong_explicit(
+                                          a, &oldvalue, newvalue,
+                                          memory_order_acquire,
+                                          memory_order_acquire);
+}
+
+ANDROID_ATOMIC_INLINE
+int android_atomic_release_cas(int32_t oldvalue, int32_t newvalue,
+                               volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = to_atomic_int_least32_t(addr);
+    return !atomic_compare_exchange_strong_explicit(
+                                          a, &oldvalue, newvalue,
+                                          memory_order_release,
+                                          memory_order_relaxed);
+}
+
+/*
+ * Fence primitives.
+ */
+ANDROID_ATOMIC_INLINE
+void android_compiler_barrier(void)
+{
+    __asm__ __volatile__ ("" : : : "memory");
+    /* Could probably also be:                          */
+    /* atomic_signal_fence(memory_order_seq_cst);       */
+}
+
+ANDROID_ATOMIC_INLINE
+void android_memory_barrier(void)
+{
+    atomic_thread_fence(memory_order_seq_cst);
+}
+
+/*
+ * Aliases for code using an older version of this header.  These are now
+ * deprecated and should not be used.  The definitions will be removed
+ * in a future release.
+ */
+#define android_atomic_write android_atomic_release_store
+#define android_atomic_cmpxchg android_atomic_release_cas
+
+#endif // ANDROID_CUTILS_ATOMIC_H
diff --git a/include/cutils/bitops.h b/libcutils/include/cutils/bitops.h
similarity index 100%
rename from include/cutils/bitops.h
rename to libcutils/include/cutils/bitops.h
diff --git a/include/cutils/compiler.h b/libcutils/include/cutils/compiler.h
similarity index 100%
rename from include/cutils/compiler.h
rename to libcutils/include/cutils/compiler.h
diff --git a/include/cutils/config_utils.h b/libcutils/include/cutils/config_utils.h
similarity index 100%
rename from include/cutils/config_utils.h
rename to libcutils/include/cutils/config_utils.h
diff --git a/include/cutils/fs.h b/libcutils/include/cutils/fs.h
similarity index 100%
rename from include/cutils/fs.h
rename to libcutils/include/cutils/fs.h
diff --git a/include/cutils/hashmap.h b/libcutils/include/cutils/hashmap.h
similarity index 100%
rename from include/cutils/hashmap.h
rename to libcutils/include/cutils/hashmap.h
diff --git a/include/cutils/iosched_policy.h b/libcutils/include/cutils/iosched_policy.h
similarity index 100%
rename from include/cutils/iosched_policy.h
rename to libcutils/include/cutils/iosched_policy.h
diff --git a/include/cutils/jstring.h b/libcutils/include/cutils/jstring.h
similarity index 100%
rename from include/cutils/jstring.h
rename to libcutils/include/cutils/jstring.h
diff --git a/libcutils/include/cutils/klog.h b/libcutils/include/cutils/klog.h
new file mode 100644
index 0000000..5ae6216
--- /dev/null
+++ b/libcutils/include/cutils/klog.h
@@ -0,0 +1,46 @@
+/*
+ * 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 _CUTILS_KLOG_H_
+#define _CUTILS_KLOG_H_
+
+#include <sys/cdefs.h>
+#include <sys/uio.h>
+#include <stdarg.h>
+
+__BEGIN_DECLS
+
+void klog_set_level(int level);
+
+void klog_write(int level, const char *fmt, ...)
+    __attribute__ ((format(printf, 2, 3)));
+void klog_writev(int level, const struct iovec* iov, int iov_count);
+
+__END_DECLS
+
+#define KLOG_ERROR_LEVEL   3
+#define KLOG_WARNING_LEVEL 4
+#define KLOG_NOTICE_LEVEL  5
+#define KLOG_INFO_LEVEL    6
+#define KLOG_DEBUG_LEVEL   7
+
+#define KLOG_ERROR(tag,x...)   klog_write(KLOG_ERROR_LEVEL, "<3>" tag ": " x)
+#define KLOG_WARNING(tag,x...) klog_write(KLOG_WARNING_LEVEL, "<4>" tag ": " x)
+#define KLOG_NOTICE(tag,x...)  klog_write(KLOG_NOTICE_LEVEL, "<5>" tag ": " x)
+#define KLOG_INFO(tag,x...)    klog_write(KLOG_INFO_LEVEL, "<6>" tag ": " x)
+#define KLOG_DEBUG(tag,x...)   klog_write(KLOG_DEBUG_LEVEL, "<7>" tag ": " x)
+
+#endif
diff --git a/include/cutils/list.h b/libcutils/include/cutils/list.h
similarity index 100%
rename from include/cutils/list.h
rename to libcutils/include/cutils/list.h
diff --git a/include/cutils/log.h b/libcutils/include/cutils/log.h
similarity index 100%
rename from include/cutils/log.h
rename to libcutils/include/cutils/log.h
diff --git a/include/cutils/memory.h b/libcutils/include/cutils/memory.h
similarity index 100%
rename from include/cutils/memory.h
rename to libcutils/include/cutils/memory.h
diff --git a/include/cutils/misc.h b/libcutils/include/cutils/misc.h
similarity index 100%
rename from include/cutils/misc.h
rename to libcutils/include/cutils/misc.h
diff --git a/libcutils/include/cutils/multiuser.h b/libcutils/include/cutils/multiuser.h
new file mode 100644
index 0000000..9a2305c
--- /dev/null
+++ b/libcutils/include/cutils/multiuser.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __CUTILS_MULTIUSER_H
+#define __CUTILS_MULTIUSER_H
+
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef uid_t userid_t;
+typedef uid_t appid_t;
+
+extern userid_t multiuser_get_user_id(uid_t uid);
+extern appid_t multiuser_get_app_id(uid_t uid);
+
+extern uid_t multiuser_get_uid(userid_t user_id, appid_t app_id);
+
+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() */
+extern gid_t multiuser_get_shared_app_gid(uid_t uid);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_MULTIUSER_H */
diff --git a/libcutils/include/cutils/native_handle.h b/libcutils/include/cutils/native_handle.h
new file mode 100644
index 0000000..7d6a988
--- /dev/null
+++ b/libcutils/include/cutils/native_handle.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2009 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 NATIVE_HANDLE_H_
+#define NATIVE_HANDLE_H_
+
+#include <stdalign.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Declare a char array for use with native_handle_init */
+#define NATIVE_HANDLE_DECLARE_STORAGE(name, maxFds, maxInts) \
+    alignas(native_handle_t) char name[                            \
+      sizeof(native_handle_t) + sizeof(int) * (maxFds + maxInts)]
+
+typedef struct native_handle
+{
+    int version;        /* sizeof(native_handle_t) */
+    int numFds;         /* number of file-descriptors at &data[0] */
+    int numInts;        /* number of ints at &data[numFds] */
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wzero-length-array"
+#endif
+    int data[0];        /* numFds + numInts ints */
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+} native_handle_t;
+
+/*
+ * native_handle_close
+ * 
+ * closes the file descriptors contained in this native_handle_t
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_close(const native_handle_t* h);
+
+/*
+ * native_handle_init
+ *
+ * Initializes a native_handle_t from storage.  storage must be declared with
+ * NATIVE_HANDLE_DECLARE_STORAGE.  numFds and numInts must not respectively
+ * exceed maxFds and maxInts used to declare the storage.
+ */
+native_handle_t* native_handle_init(char* storage, int numFds, int numInts);
+
+/*
+ * native_handle_create
+ * 
+ * creates a native_handle_t and initializes it. must be destroyed with
+ * native_handle_delete().
+ * 
+ */
+native_handle_t* native_handle_create(int numFds, int numInts);
+
+/*
+ * native_handle_clone
+ *
+ * creates a native_handle_t and initializes it from another native_handle_t.
+ * Must be destroyed with native_handle_delete().
+ *
+ */
+native_handle_t* native_handle_clone(const native_handle_t* handle);
+
+/*
+ * native_handle_delete
+ * 
+ * frees a native_handle_t allocated with native_handle_create().
+ * This ONLY frees the memory allocated for the native_handle_t, but doesn't
+ * close the file descriptors; which can be achieved with native_handle_close().
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_delete(native_handle_t* h);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NATIVE_HANDLE_H_ */
diff --git a/include/cutils/open_memstream.h b/libcutils/include/cutils/open_memstream.h
similarity index 100%
rename from include/cutils/open_memstream.h
rename to libcutils/include/cutils/open_memstream.h
diff --git a/include/cutils/partition_utils.h b/libcutils/include/cutils/partition_utils.h
similarity index 100%
rename from include/cutils/partition_utils.h
rename to libcutils/include/cutils/partition_utils.h
diff --git a/libcutils/include/cutils/properties.h b/libcutils/include/cutils/properties.h
new file mode 100644
index 0000000..b45f58f
--- /dev/null
+++ b/libcutils/include/cutils/properties.h
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef __CUTILS_PROPERTIES_H
+#define __CUTILS_PROPERTIES_H
+
+#include <sys/cdefs.h>
+#include <stddef.h>
+#include <sys/system_properties.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* System properties are *small* name value pairs managed by the
+** property service.  If your data doesn't fit in the provided
+** space it is not appropriate for a system property.
+**
+** WARNING: system/bionic/include/sys/system_properties.h also defines
+**          these, but with different names.  (TODO: fix that)
+*/
+#define PROPERTY_KEY_MAX   PROP_NAME_MAX
+#define PROPERTY_VALUE_MAX  PROP_VALUE_MAX
+
+/* property_get: returns the length of the value which will never be
+** greater than PROPERTY_VALUE_MAX - 1 and will always be zero terminated.
+** (the length does not include the terminating zero).
+**
+** If the property read fails or returns an empty value, the default
+** value is used (if nonnull).
+*/
+int property_get(const char *key, char *value, const char *default_value)
+/* Sometimes we use not-Bionic with this, so we need this check. */
+#if defined(__BIONIC_FORTIFY)
+        __overloadable __RENAME_CLANG(property_get)
+#endif
+        ;
+
+/* property_get_bool: returns the value of key coerced into a
+** boolean. If the property is not set, then the default value is returned.
+**
+* The following is considered to be true (1):
+**   "1", "true", "y", "yes", "on"
+**
+** The following is considered to be false (0):
+**   "0", "false", "n", "no", "off"
+**
+** The conversion is whitespace-sensitive (e.g. " off" will not be false).
+**
+** If no property with this key is set (or the key is NULL) or the boolean
+** conversion fails, the default value is returned.
+**/
+int8_t property_get_bool(const char *key, int8_t default_value);
+
+/* property_get_int64: returns the value of key truncated and coerced into a
+** int64_t. If the property is not set, then the default value is used.
+**
+** The numeric conversion is identical to strtoimax with the base inferred:
+** - All digits up to the first non-digit characters are read
+** - The longest consecutive prefix of digits is converted to a long
+**
+** Valid strings of digits are:
+** - An optional sign character + or -
+** - An optional prefix indicating the base (otherwise base 10 is assumed)
+**   -- 0 prefix is octal
+**   -- 0x / 0X prefix is hex
+**
+** Leading/trailing whitespace is ignored. Overflow/underflow will cause
+** numeric conversion to fail.
+**
+** If no property with this key is set (or the key is NULL) or the numeric
+** conversion fails, the default value is returned.
+**/
+int64_t property_get_int64(const char *key, int64_t default_value);
+
+/* property_get_int32: returns the value of key truncated and coerced into an
+** int32_t. If the property is not set, then the default value is used.
+**
+** The numeric conversion is identical to strtoimax with the base inferred:
+** - All digits up to the first non-digit characters are read
+** - The longest consecutive prefix of digits is converted to a long
+**
+** Valid strings of digits are:
+** - An optional sign character + or -
+** - An optional prefix indicating the base (otherwise base 10 is assumed)
+**   -- 0 prefix is octal
+**   -- 0x / 0X prefix is hex
+**
+** Leading/trailing whitespace is ignored. Overflow/underflow will cause
+** numeric conversion to fail.
+**
+** If no property with this key is set (or the key is NULL) or the numeric
+** conversion fails, the default value is returned.
+**/
+int32_t property_get_int32(const char *key, int32_t default_value);
+
+/* property_set: returns 0 on success, < 0 on failure
+*/
+int property_set(const char *key, const char *value);
+
+int property_list(void (*propfn)(const char *key, const char *value, void *cookie), void *cookie);
+
+#if defined(__BIONIC_FORTIFY)
+#define __property_get_err_str "property_get() called with too small of a buffer"
+
+#if defined(__clang__)
+
+/* Some projects use -Weverything; enable_if is clang-specific.
+** FIXME: This is marked used because we'll otherwise get complaints about an
+** unused static function. This is more robust than marking it unused, since
+** -Wused-but-marked-unused is a thing that will complain if this function is
+** actually used, thus making FORTIFY noisier when an error happens. It's going
+** to go away anyway during our FORTIFY cleanup.
+**/
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgcc-compat"
+__BIONIC_ERROR_FUNCTION_VISIBILITY
+int property_get(const char *key, char *value, const char *default_value)
+        __overloadable
+        __enable_if(__bos(value) != __BIONIC_FORTIFY_UNKNOWN_SIZE &&
+                    __bos(value) < PROPERTY_VALUE_MAX, __property_get_err_str)
+        __errorattr(__property_get_err_str)
+        __attribute__((used));
+#pragma clang diagnostic pop
+
+/* No object size? No FORTIFY.
+*/
+
+#else /* defined(__clang__) */
+
+extern int __property_get_real(const char *, char *, const char *)
+    __asm__(__USER_LABEL_PREFIX__ "property_get");
+__errordecl(__property_get_too_small_error, __property_get_err_str);
+
+__BIONIC_FORTIFY_INLINE
+int property_get(const char *key, char *value, const char *default_value) {
+    size_t bos = __bos(value);
+    if (bos < PROPERTY_VALUE_MAX) {
+        __property_get_too_small_error();
+    }
+    return __property_get_real(key, value, default_value);
+}
+
+#endif /* defined(__clang__) */
+
+#undef __property_get_err_str
+#endif /* defined(__BIONIC_FORTIFY) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libcutils/include/cutils/qtaguid.h b/libcutils/include/cutils/qtaguid.h
new file mode 100644
index 0000000..803fe0d
--- /dev/null
+++ b/libcutils/include/cutils/qtaguid.h
@@ -0,0 +1,68 @@
+/*
+ * 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 __CUTILS_QTAGUID_H
+#define __CUTILS_QTAGUID_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Set tags (and owning UIDs) for network sockets. The socket must be untagged
+ * by calling qtaguid_untagSocket() before closing it, otherwise the qtaguid
+ * module will keep a reference to it even after close.
+ */
+extern int qtaguid_tagSocket(int sockfd, int tag, uid_t uid);
+
+/*
+ * Untag a network socket before closing.
+ */
+extern int qtaguid_untagSocket(int sockfd);
+
+/*
+ * For the given uid, switch counter sets.
+ * The kernel only keeps a limited number of sets.
+ * 2 for now.
+ */
+extern int qtaguid_setCounterSet(int counterSetNum, uid_t uid);
+
+/*
+ * Delete all tag info that relates to the given tag an uid.
+ * If the tag is 0, then ALL info about the uid is freeded.
+ * The delete data also affects active tagged socketd, which are
+ * then untagged.
+ * The calling process can only operate on its own tags.
+ * Unless it is part of the happy AID_NET_BW_ACCT group.
+ * In which case it can clobber everything.
+ */
+extern int qtaguid_deleteTagData(int tag, uid_t uid);
+
+/*
+ * Enable/disable qtaguid functionnality at a lower level.
+ * When pacified, the kernel will accept commands but do nothing.
+ */
+extern int qtaguid_setPacifier(int on);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_QTAG_UID_H */
diff --git a/include/cutils/record_stream.h b/libcutils/include/cutils/record_stream.h
similarity index 100%
rename from include/cutils/record_stream.h
rename to libcutils/include/cutils/record_stream.h
diff --git a/libcutils/include/cutils/sched_policy.h b/libcutils/include/cutils/sched_policy.h
new file mode 100644
index 0000000..15391d9
--- /dev/null
+++ b/libcutils/include/cutils/sched_policy.h
@@ -0,0 +1,81 @@
+/*
+ * 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 __CUTILS_SCHED_POLICY_H
+#define __CUTILS_SCHED_POLICY_H
+
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Check if Linux kernel enables CPUSETS feature.
+ *
+ * Return value: 1 if Linux kernel CONFIG_CPUSETS=y; 0 otherwise.
+ */
+extern bool cpusets_enabled();
+
+/*
+ * Check if Linux kernel enables SCHEDTUNE feature (only available in Android
+ * common kernel or Linaro LSK, not in mainline Linux as of v4.9)
+ *
+ * Return value: 1 if Linux kernel CONFIG_SCHEDTUNE=y; 0 otherwise.
+ */
+extern bool schedboost_enabled();
+
+/* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */
+typedef enum {
+    SP_DEFAULT    = -1,
+    SP_BACKGROUND = 0,
+    SP_FOREGROUND = 1,
+    SP_SYSTEM     = 2,  // can't be used with set_sched_policy()
+    SP_AUDIO_APP  = 3,
+    SP_AUDIO_SYS  = 4,
+    SP_TOP_APP    = 5,
+    SP_CNT,
+    SP_MAX        = SP_CNT - 1,
+    SP_SYSTEM_DEFAULT = SP_FOREGROUND,
+} SchedPolicy;
+
+extern int set_cpuset_policy(int tid, SchedPolicy policy);
+
+/* Assign thread tid to the cgroup associated with the specified policy.
+ * If the thread is a thread group leader, that is it's gettid() == getpid(),
+ * then the other threads in the same thread group are _not_ affected.
+ * On platforms which support gettid(), zero tid means current thread.
+ * Return value: 0 for success, or -errno for error.
+ */
+extern int set_sched_policy(int tid, SchedPolicy policy);
+
+/* Return the policy associated with the cgroup of thread tid via policy pointer.
+ * On platforms which support gettid(), zero tid means current thread.
+ * Return value: 0 for success, or -1 for error and set errno.
+ */
+extern int get_sched_policy(int tid, SchedPolicy *policy);
+
+/* Return a displayable string corresponding to policy.
+ * Return value: non-NULL NUL-terminated name of unspecified length;
+ * the caller is responsible for displaying the useful part of the string.
+ */
+extern const char *get_sched_policy_name(SchedPolicy policy);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_SCHED_POLICY_H */ 
diff --git a/libcutils/include/cutils/sockets.h b/libcutils/include/cutils/sockets.h
new file mode 100644
index 0000000..d724dd6
--- /dev/null
+++ b/libcutils/include/cutils/sockets.h
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef __CUTILS_SOCKETS_H
+#define __CUTILS_SOCKETS_H
+
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+
+#if defined(_WIN32)
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+typedef int  socklen_t;
+typedef SOCKET cutils_socket_t;
+
+#else
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+typedef int cutils_socket_t;
+#define INVALID_SOCKET (-1)
+
+#endif
+
+#define ANDROID_SOCKET_ENV_PREFIX	"ANDROID_SOCKET_"
+#define ANDROID_SOCKET_DIR		"/dev/socket"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * android_get_control_socket - simple helper function to get the file
+ * descriptor of our init-managed Unix domain socket. `name' is the name of the
+ * socket, as given in init.rc. Returns -1 on error.
+ */
+int android_get_control_socket(const char* name);
+
+/*
+ * See also android.os.LocalSocketAddress.Namespace
+ */
+// Linux "abstract" (non-filesystem) namespace
+#define ANDROID_SOCKET_NAMESPACE_ABSTRACT 0
+// Android "reserved" (/dev/socket) namespace
+#define ANDROID_SOCKET_NAMESPACE_RESERVED 1
+// Normal filesystem namespace
+#define ANDROID_SOCKET_NAMESPACE_FILESYSTEM 2
+
+/*
+ * Functions to create sockets for some common usages.
+ *
+ * All these functions are implemented for Unix, but only a few are implemented
+ * for Windows. Those which are can be identified by the cutils_socket_t
+ * return type. The idea is to be able to use this return value with the
+ * standard Unix socket functions on any platform.
+ *
+ * On Unix the returned cutils_socket_t is a standard int file descriptor and
+ * can always be used as normal with all file descriptor functions.
+ *
+ * On Windows utils_socket_t is an unsigned int pointer, and is only valid
+ * with functions that specifically take a socket, e.g. send(), sendto(),
+ * recv(), and recvfrom(). General file descriptor functions such as read(),
+ * write(), and close() will not work with utils_socket_t and will require
+ * special handling.
+ *
+ * These functions return INVALID_SOCKET (-1) on failure for all platforms.
+ */
+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,
+                                int type);
+int socket_local_client(const char* name, int namespaceId, int type);
+cutils_socket_t socket_inaddr_any_server(int port, int type);
+
+/*
+ * Closes a cutils_socket_t. Windows doesn't allow calling close() on a socket
+ * so this is a cross-platform way to close a cutils_socket_t.
+ *
+ * Returns 0 on success.
+ */
+int socket_close(cutils_socket_t sock);
+
+/*
+ * Sets socket receive timeout using SO_RCVTIMEO. Setting |timeout_ms| to 0
+ * disables receive timeouts.
+ *
+ * Return 0 on success.
+ */
+int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms);
+
+/*
+ * Returns the local port the socket is bound to or -1 on error.
+ */
+int socket_get_local_port(cutils_socket_t sock);
+
+/*
+ * Sends to a socket from multiple buffers; wraps writev() on Unix or WSASend()
+ * on Windows. This can give significant speedup compared to calling send()
+ * multiple times.
+ *
+ * Example usage:
+ *   cutils_socket_buffer_t buffers[2] = { {data0, len0}, {data1, len1} };
+ *   socket_send_buffers(sock, buffers, 2);
+ *
+ * If you try to pass more than SOCKET_SEND_BUFFERS_MAX_BUFFERS buffers into
+ * this function it will return -1 without sending anything.
+ *
+ * Returns the number of bytes written or -1 on error.
+ */
+typedef struct {
+  const void* data;
+  size_t length;
+} cutils_socket_buffer_t;
+
+#define SOCKET_SEND_BUFFERS_MAX_BUFFERS 16
+
+ssize_t socket_send_buffers(cutils_socket_t sock,
+                            const cutils_socket_buffer_t* buffers,
+                            size_t num_buffers);
+
+/*
+ * socket_peer_is_trusted - Takes a socket which is presumed to be a
+ * connected local socket (e.g. AF_LOCAL) and returns whether the peer
+ * (the userid that owns the process on the other end of that socket)
+ * is one of the two trusted userids, root or shell.
+ *
+ * Note: This only works as advertised on the Android OS and always
+ * just returns true when called on other operating systems.
+ */
+extern bool socket_peer_is_trusted(int fd);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CUTILS_SOCKETS_H */
diff --git a/include/cutils/str_parms.h b/libcutils/include/cutils/str_parms.h
similarity index 100%
rename from include/cutils/str_parms.h
rename to libcutils/include/cutils/str_parms.h
diff --git a/include/cutils/threads.h b/libcutils/include/cutils/threads.h
similarity index 100%
rename from include/cutils/threads.h
rename to libcutils/include/cutils/threads.h
diff --git a/libcutils/include/cutils/trace.h b/libcutils/include/cutils/trace.h
new file mode 100644
index 0000000..fcbdc9b
--- /dev/null
+++ b/libcutils/include/cutils/trace.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBS_CUTILS_TRACE_H
+#define _LIBS_CUTILS_TRACE_H
+
+#include <inttypes.h>
+#include <stdatomic.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <cutils/compiler.h>
+
+__BEGIN_DECLS
+
+/**
+ * The ATRACE_TAG macro can be defined before including this header to trace
+ * using one of the tags defined below.  It must be defined to one of the
+ * following ATRACE_TAG_* macros.  The trace tag is used to filter tracing in
+ * userland to avoid some of the runtime cost of tracing when it is not desired.
+ *
+ * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always
+ * being enabled - this should ONLY be done for debug code, as userland tracing
+ * has a performance cost even when the trace is not being recorded.  Defining
+ * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result
+ * in the tracing always being disabled.
+ *
+ * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing
+ * within a hardware module.  For example a camera hardware module would set:
+ * #define ATRACE_TAG  (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
+ *
+ * Keep these in sync with frameworks/base/core/java/android/os/Trace.java.
+ */
+#define ATRACE_TAG_NEVER            0       // This tag is never enabled.
+#define ATRACE_TAG_ALWAYS           (1<<0)  // This tag is always enabled.
+#define ATRACE_TAG_GRAPHICS         (1<<1)
+#define ATRACE_TAG_INPUT            (1<<2)
+#define ATRACE_TAG_VIEW             (1<<3)
+#define ATRACE_TAG_WEBVIEW          (1<<4)
+#define ATRACE_TAG_WINDOW_MANAGER   (1<<5)
+#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6)
+#define ATRACE_TAG_SYNC_MANAGER     (1<<7)
+#define ATRACE_TAG_AUDIO            (1<<8)
+#define ATRACE_TAG_VIDEO            (1<<9)
+#define ATRACE_TAG_CAMERA           (1<<10)
+#define ATRACE_TAG_HAL              (1<<11)
+#define ATRACE_TAG_APP              (1<<12)
+#define ATRACE_TAG_RESOURCES        (1<<13)
+#define ATRACE_TAG_DALVIK           (1<<14)
+#define ATRACE_TAG_RS               (1<<15)
+#define ATRACE_TAG_BIONIC           (1<<16)
+#define ATRACE_TAG_POWER            (1<<17)
+#define ATRACE_TAG_PACKAGE_MANAGER  (1<<18)
+#define ATRACE_TAG_SYSTEM_SERVER    (1<<19)
+#define ATRACE_TAG_DATABASE         (1<<20)
+#define ATRACE_TAG_NETWORK          (1<<21)
+#define ATRACE_TAG_ADB              (1<<22)
+#define ATRACE_TAG_LAST             ATRACE_TAG_ADB
+
+// Reserved for initialization.
+#define ATRACE_TAG_NOT_READY        (1ULL<<63)
+
+#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST)
+
+#ifndef ATRACE_TAG
+#define ATRACE_TAG ATRACE_TAG_NEVER
+#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK
+#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h
+#endif
+
+/**
+ * Opens the trace file for writing and reads the property for initial tags.
+ * The atrace.tags.enableflags property sets the tags to trace.
+ * This function should not be explicitly called, the first call to any normal
+ * trace function will cause it to be run safely.
+ */
+void atrace_setup();
+
+/**
+ * If tracing is ready, set atrace_enabled_tags to the system property
+ * debug.atrace.tags.enableflags. Can be used as a sysprop change callback.
+ */
+void atrace_update_tags();
+
+/**
+ * Set whether the process is debuggable.  By default the process is not
+ * considered debuggable.  If the process is not debuggable then application-
+ * level tracing is not allowed unless the ro.debuggable system property is
+ * set to '1'.
+ */
+void atrace_set_debuggable(bool debuggable);
+
+/**
+ * Set whether tracing is enabled for the current process.  This is used to
+ * prevent tracing within the Zygote process.
+ */
+void atrace_set_tracing_enabled(bool enabled);
+
+/**
+ * Flag indicating whether setup has been completed, initialized to 0.
+ * Nonzero indicates setup has completed.
+ * Note: This does NOT indicate whether or not setup was successful.
+ */
+extern atomic_bool atrace_is_ready;
+
+/**
+ * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY.
+ * A value of zero indicates setup has failed.
+ * Any other nonzero value indicates setup has succeeded, and tracing is on.
+ */
+extern uint64_t atrace_enabled_tags;
+
+/**
+ * Handle to the kernel's trace buffer, initialized to -1.
+ * Any other value indicates setup has succeeded, and is a valid fd for tracing.
+ */
+extern int atrace_marker_fd;
+
+/**
+ * atrace_init readies the process for tracing by opening the trace_marker file.
+ * Calling any trace function causes this to be run, so calling it is optional.
+ * This can be explicitly run to avoid setup delay on first trace function.
+ */
+#define ATRACE_INIT() atrace_init()
+static inline void atrace_init()
+{
+    if (CC_UNLIKELY(!atomic_load_explicit(&atrace_is_ready, memory_order_acquire))) {
+        atrace_setup();
+    }
+}
+
+/**
+ * Get the mask of all tags currently enabled.
+ * It can be used as a guard condition around more expensive trace calculations.
+ * Every trace function calls this, which ensures atrace_init is run.
+ */
+#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags()
+static inline uint64_t atrace_get_enabled_tags()
+{
+    atrace_init();
+    return atrace_enabled_tags;
+}
+
+/**
+ * Test if a given tag is currently enabled.
+ * Returns nonzero if the tag is enabled, otherwise zero.
+ * It can be used as a guard condition around more expensive trace calculations.
+ */
+#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG)
+static inline uint64_t atrace_is_tag_enabled(uint64_t tag)
+{
+    return atrace_get_enabled_tags() & tag;
+}
+
+/**
+ * Trace the beginning of a context.  name is used to identify the context.
+ * This is often used to time function execution.
+ */
+#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name)
+static inline void atrace_begin(uint64_t tag, const char* name)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_begin_body(const char*);
+        atrace_begin_body(name);
+    }
+}
+
+/**
+ * Trace the end of a context.
+ * This should match up (and occur after) a corresponding ATRACE_BEGIN.
+ */
+#define ATRACE_END() atrace_end(ATRACE_TAG)
+static inline void atrace_end(uint64_t tag)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_end_body();
+        atrace_end_body();
+    }
+}
+
+/**
+ * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END
+ * contexts, asynchronous events do not need to be nested. The name describes
+ * the event, and the cookie provides a unique identifier for distinguishing
+ * simultaneous events. The name and cookie used to begin an event must be
+ * used to end it.
+ */
+#define ATRACE_ASYNC_BEGIN(name, cookie) \
+    atrace_async_begin(ATRACE_TAG, name, cookie)
+static inline void atrace_async_begin(uint64_t tag, const char* name,
+        int32_t cookie)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_async_begin_body(const char*, int32_t);
+        atrace_async_begin_body(name, cookie);
+    }
+}
+
+/**
+ * Trace the end of an asynchronous event.
+ * This should have a corresponding ATRACE_ASYNC_BEGIN.
+ */
+#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie)
+static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_async_end_body(const char*, int32_t);
+        atrace_async_end_body(name, cookie);
+    }
+}
+
+/**
+ * Traces an integer counter value.  name is used to identify the counter.
+ * This can be used to track how a value changes over time.
+ */
+#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value)
+static inline void atrace_int(uint64_t tag, const char* name, int32_t value)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_int_body(const char*, int32_t);
+        atrace_int_body(name, value);
+    }
+}
+
+/**
+ * Traces a 64-bit integer counter value.  name is used to identify the
+ * counter. This can be used to track how a value changes over time.
+ */
+#define ATRACE_INT64(name, value) atrace_int64(ATRACE_TAG, name, value)
+static inline void atrace_int64(uint64_t tag, const char* name, int64_t value)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_int64_body(const char*, int64_t);
+        atrace_int64_body(name, value);
+    }
+}
+
+__END_DECLS
+
+#endif // _LIBS_CUTILS_TRACE_H
diff --git a/include/cutils/uevent.h b/libcutils/include/cutils/uevent.h
similarity index 100%
rename from include/cutils/uevent.h
rename to libcutils/include/cutils/uevent.h
diff --git a/libcutils/include/private/android_filesystem_capability.h b/libcutils/include/private/android_filesystem_capability.h
new file mode 100644
index 0000000..0227b1d
--- /dev/null
+++ b/libcutils/include/private/android_filesystem_capability.h
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Taken from linux/capability.h, with minor modifications
+ */
+
+#ifndef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_FILESYSTEM_CAPABILITY_H
+#define _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_FILESYSTEM_CAPABILITY_H
+
+#include <stdint.h>
+
+#define __user
+#define __u32 uint32_t
+#define __le32 uint32_t
+
+#define _LINUX_CAPABILITY_VERSION_1 0x19980330
+#define _LINUX_CAPABILITY_U32S_1 1
+#define _LINUX_CAPABILITY_VERSION_2 0x20071026
+#define _LINUX_CAPABILITY_U32S_2 2
+#define _LINUX_CAPABILITY_VERSION_3 0x20080522
+#define _LINUX_CAPABILITY_U32S_3 2
+
+typedef struct __user_cap_header_struct {
+    __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;
+
+#define VFS_CAP_REVISION_MASK 0xFF000000
+#define VFS_CAP_REVISION_SHIFT 24
+#define VFS_CAP_FLAGS_MASK ~VFS_CAP_REVISION_MASK
+#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 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 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];
+};
+
+#define _LINUX_CAPABILITY_VERSION _LINUX_CAPABILITY_VERSION_1
+#define _LINUX_CAPABILITY_U32S _LINUX_CAPABILITY_U32S_1
+#define CAP_CHOWN 0
+#define CAP_DAC_OVERRIDE 1
+#define CAP_DAC_READ_SEARCH 2
+#define CAP_FOWNER 3
+#define CAP_FSETID 4
+#define CAP_KILL 5
+#define CAP_SETGID 6
+#define CAP_SETUID 7
+#define CAP_SETPCAP 8
+#define CAP_LINUX_IMMUTABLE 9
+#define CAP_NET_BIND_SERVICE 10
+#define CAP_NET_BROADCAST 11
+#define CAP_NET_ADMIN 12
+#define CAP_NET_RAW 13
+#define CAP_IPC_LOCK 14
+#define CAP_IPC_OWNER 15
+#define CAP_SYS_MODULE 16
+#define CAP_SYS_RAWIO 17
+#define CAP_SYS_CHROOT 18
+#define CAP_SYS_PTRACE 19
+#define CAP_SYS_PACCT 20
+#define CAP_SYS_ADMIN 21
+#define CAP_SYS_BOOT 22
+#define CAP_SYS_NICE 23
+#define CAP_SYS_RESOURCE 24
+#define CAP_SYS_TIME 25
+#define CAP_SYS_TTY_CONFIG 26
+#define CAP_MKNOD 27
+#define CAP_LEASE 28
+#define CAP_AUDIT_WRITE 29
+#define CAP_AUDIT_CONTROL 30
+#define CAP_SETFCAP 31
+#define CAP_MAC_OVERRIDE 32
+#define CAP_MAC_ADMIN 33
+#define CAP_SYSLOG 34
+#define CAP_WAKE_ALARM 35
+#define CAP_BLOCK_SUSPEND 36
+#define CAP_AUDIT_READ 37
+#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))
+
+#undef __user
+#undef __u32
+#undef __le32
+
+#endif
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/libcutils/include/private/canned_fs_config.h b/libcutils/include/private/canned_fs_config.h
new file mode 100644
index 0000000..71e1537
--- /dev/null
+++ b/libcutils/include/private/canned_fs_config.h
@@ -0,0 +1,26 @@
+/*
+ * 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 _CANNED_FS_CONFIG_H
+#define _CANNED_FS_CONFIG_H
+
+#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);
+
+#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/android_get_control_file.h b/libcutils/include_vndk/cutils/android_get_control_file.h
new file mode 120000
index 0000000..70d6a3b
--- /dev/null
+++ b/libcutils/include_vndk/cutils/android_get_control_file.h
@@ -0,0 +1 @@
+../../include/cutils/android_get_control_file.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/android_reboot.h b/libcutils/include_vndk/cutils/android_reboot.h
new file mode 120000
index 0000000..9e1bf4c
--- /dev/null
+++ b/libcutils/include_vndk/cutils/android_reboot.h
@@ -0,0 +1 @@
+../../include/cutils/android_reboot.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/ashmem.h b/libcutils/include_vndk/cutils/ashmem.h
new file mode 120000
index 0000000..5c07beb
--- /dev/null
+++ b/libcutils/include_vndk/cutils/ashmem.h
@@ -0,0 +1 @@
+../../include/cutils/ashmem.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/atomic.h b/libcutils/include_vndk/cutils/atomic.h
new file mode 120000
index 0000000..f4f14fe
--- /dev/null
+++ b/libcutils/include_vndk/cutils/atomic.h
@@ -0,0 +1 @@
+../../include/cutils/atomic.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/bitops.h b/libcutils/include_vndk/cutils/bitops.h
new file mode 120000
index 0000000..edbd60c
--- /dev/null
+++ b/libcutils/include_vndk/cutils/bitops.h
@@ -0,0 +1 @@
+../../include/cutils/bitops.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/compiler.h b/libcutils/include_vndk/cutils/compiler.h
new file mode 120000
index 0000000..08ebc10
--- /dev/null
+++ b/libcutils/include_vndk/cutils/compiler.h
@@ -0,0 +1 @@
+../../include/cutils/compiler.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/config_utils.h b/libcutils/include_vndk/cutils/config_utils.h
new file mode 120000
index 0000000..e011738
--- /dev/null
+++ b/libcutils/include_vndk/cutils/config_utils.h
@@ -0,0 +1 @@
+../../include/cutils/config_utils.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/fs.h b/libcutils/include_vndk/cutils/fs.h
new file mode 120000
index 0000000..576bfa3
--- /dev/null
+++ b/libcutils/include_vndk/cutils/fs.h
@@ -0,0 +1 @@
+../../include/cutils/fs.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/hashmap.h b/libcutils/include_vndk/cutils/hashmap.h
new file mode 120000
index 0000000..6b18406
--- /dev/null
+++ b/libcutils/include_vndk/cutils/hashmap.h
@@ -0,0 +1 @@
+../../include/cutils/hashmap.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/iosched_policy.h b/libcutils/include_vndk/cutils/iosched_policy.h
new file mode 120000
index 0000000..26cf333
--- /dev/null
+++ b/libcutils/include_vndk/cutils/iosched_policy.h
@@ -0,0 +1 @@
+../../include/cutils/iosched_policy.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/jstring.h b/libcutils/include_vndk/cutils/jstring.h
new file mode 120000
index 0000000..f3fd546
--- /dev/null
+++ b/libcutils/include_vndk/cutils/jstring.h
@@ -0,0 +1 @@
+../../include/cutils/jstring.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/klog.h b/libcutils/include_vndk/cutils/klog.h
new file mode 120000
index 0000000..8ca85ff
--- /dev/null
+++ b/libcutils/include_vndk/cutils/klog.h
@@ -0,0 +1 @@
+../../include/cutils/klog.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/list.h b/libcutils/include_vndk/cutils/list.h
new file mode 120000
index 0000000..9fa4c90
--- /dev/null
+++ b/libcutils/include_vndk/cutils/list.h
@@ -0,0 +1 @@
+../../include/cutils/list.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/log.h b/libcutils/include_vndk/cutils/log.h
new file mode 100644
index 0000000..21dc11e
--- /dev/null
+++ b/libcutils/include_vndk/cutils/log.h
@@ -0,0 +1,47 @@
+/*Special log.h file for VNDK linking modules*/
+/*
+ * Copyright (C) 2005-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 _LIBS_CUTIL_LOG_H
+#define _LIBS_CUTIL_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/cutils/memory.h b/libcutils/include_vndk/cutils/memory.h
new file mode 120000
index 0000000..e0e7abc
--- /dev/null
+++ b/libcutils/include_vndk/cutils/memory.h
@@ -0,0 +1 @@
+../../include/cutils/memory.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/misc.h b/libcutils/include_vndk/cutils/misc.h
new file mode 120000
index 0000000..db09eb5
--- /dev/null
+++ b/libcutils/include_vndk/cutils/misc.h
@@ -0,0 +1 @@
+../../include/cutils/misc.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/multiuser.h b/libcutils/include_vndk/cutils/multiuser.h
new file mode 120000
index 0000000..524111f
--- /dev/null
+++ b/libcutils/include_vndk/cutils/multiuser.h
@@ -0,0 +1 @@
+../../include/cutils/multiuser.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/native_handle.h b/libcutils/include_vndk/cutils/native_handle.h
new file mode 120000
index 0000000..e324d4e
--- /dev/null
+++ b/libcutils/include_vndk/cutils/native_handle.h
@@ -0,0 +1 @@
+../../include/cutils/native_handle.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/open_memstream.h b/libcutils/include_vndk/cutils/open_memstream.h
new file mode 120000
index 0000000..c894084
--- /dev/null
+++ b/libcutils/include_vndk/cutils/open_memstream.h
@@ -0,0 +1 @@
+../../include/cutils/open_memstream.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/partition_utils.h b/libcutils/include_vndk/cutils/partition_utils.h
new file mode 120000
index 0000000..d9734c8
--- /dev/null
+++ b/libcutils/include_vndk/cutils/partition_utils.h
@@ -0,0 +1 @@
+../../include/cutils/partition_utils.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/properties.h b/libcutils/include_vndk/cutils/properties.h
new file mode 120000
index 0000000..d56118e
--- /dev/null
+++ b/libcutils/include_vndk/cutils/properties.h
@@ -0,0 +1 @@
+../../include/cutils/properties.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/qtaguid.h b/libcutils/include_vndk/cutils/qtaguid.h
new file mode 120000
index 0000000..bc02441
--- /dev/null
+++ b/libcutils/include_vndk/cutils/qtaguid.h
@@ -0,0 +1 @@
+../../include/cutils/qtaguid.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/record_stream.h b/libcutils/include_vndk/cutils/record_stream.h
new file mode 120000
index 0000000..8de6494
--- /dev/null
+++ b/libcutils/include_vndk/cutils/record_stream.h
@@ -0,0 +1 @@
+../../include/cutils/record_stream.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/sched_policy.h b/libcutils/include_vndk/cutils/sched_policy.h
new file mode 120000
index 0000000..ddebdd0
--- /dev/null
+++ b/libcutils/include_vndk/cutils/sched_policy.h
@@ -0,0 +1 @@
+../../include/cutils/sched_policy.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/sockets.h b/libcutils/include_vndk/cutils/sockets.h
new file mode 120000
index 0000000..585250c
--- /dev/null
+++ b/libcutils/include_vndk/cutils/sockets.h
@@ -0,0 +1 @@
+../../include/cutils/sockets.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/str_parms.h b/libcutils/include_vndk/cutils/str_parms.h
new file mode 120000
index 0000000..9c79a8f
--- /dev/null
+++ b/libcutils/include_vndk/cutils/str_parms.h
@@ -0,0 +1 @@
+../../include/cutils/str_parms.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/threads.h b/libcutils/include_vndk/cutils/threads.h
new file mode 120000
index 0000000..99330ff
--- /dev/null
+++ b/libcutils/include_vndk/cutils/threads.h
@@ -0,0 +1 @@
+../../include/cutils/threads.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/trace.h b/libcutils/include_vndk/cutils/trace.h
new file mode 120000
index 0000000..b12e140
--- /dev/null
+++ b/libcutils/include_vndk/cutils/trace.h
@@ -0,0 +1 @@
+../../include/cutils/trace.h
\ No newline at end of file
diff --git a/libcutils/include_vndk/cutils/uevent.h b/libcutils/include_vndk/cutils/uevent.h
new file mode 120000
index 0000000..451283a
--- /dev/null
+++ b/libcutils/include_vndk/cutils/uevent.h
@@ -0,0 +1 @@
+../../include/cutils/uevent.h
\ No newline at end of file
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/iosched_policy.c b/libcutils/iosched_policy.c
index 71bc94b..13c2ceb 100644
--- a/libcutils/iosched_policy.c
+++ b/libcutils/iosched_policy.c
@@ -24,7 +24,8 @@
 #include <cutils/iosched_policy.h>
 
 #if defined(__ANDROID__)
-#include <linux/ioprio.h>
+#define IOPRIO_WHO_PROCESS (1)
+#define IOPRIO_CLASS_SHIFT (13)
 #include <sys/syscall.h>
 #define __android_unused
 #else
diff --git a/libcutils/klog.c b/libcutils/klog.c
deleted file mode 100644
index 7402903..0000000
--- a/libcutils/klog.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2008 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 <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/klog.h>
-
-static int klog_fd = -1;
-static int klog_level = KLOG_DEFAULT_LEVEL;
-
-int klog_get_level(void) {
-    return klog_level;
-}
-
-void klog_set_level(int level) {
-    klog_level = level;
-}
-
-void klog_init(void) {
-    if (klog_fd >= 0) return; /* Already initialized */
-
-    klog_fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC);
-    if (klog_fd >= 0) {
-        return;
-    }
-
-    static const char* name = "/dev/__kmsg__";
-    if (mknod(name, S_IFCHR | 0600, (1 << 8) | 11) == 0) {
-        klog_fd = open(name, O_WRONLY | O_CLOEXEC);
-        unlink(name);
-    }
-}
-
-#define LOG_BUF_MAX 512
-
-void klog_writev(int level, const struct iovec* iov, int iov_count) {
-    if (level > klog_level) return;
-    if (klog_fd < 0) klog_init();
-    if (klog_fd < 0) return;
-    TEMP_FAILURE_RETRY(writev(klog_fd, iov, iov_count));
-}
-
-void klog_write(int level, const char* fmt, ...) {
-    if (level > klog_level) return;
-    char buf[LOG_BUF_MAX];
-    va_list ap;
-    va_start(ap, fmt);
-    vsnprintf(buf, sizeof(buf), fmt, ap);
-    va_end(ap);
-
-    buf[LOG_BUF_MAX - 1] = 0;
-
-    struct iovec iov[1];
-    iov[0].iov_base = buf;
-    iov[0].iov_len = strlen(buf);
-    klog_writev(level, iov, 1);
-}
diff --git a/libcutils/klog.cpp b/libcutils/klog.cpp
new file mode 100644
index 0000000..d301276
--- /dev/null
+++ b/libcutils/klog.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2008 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 <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <cutils/android_get_control_file.h>
+#include <cutils/klog.h>
+
+static int klog_level = KLOG_INFO_LEVEL;
+
+void klog_set_level(int level) {
+    klog_level = level;
+}
+
+static int __open_klog(void) {
+    static const char kmsg_device[] = "/dev/kmsg";
+
+    int ret = android_get_control_file(kmsg_device);
+    if (ret >= 0) return ret;
+    return TEMP_FAILURE_RETRY(open(kmsg_device, O_WRONLY | O_CLOEXEC));
+}
+
+#define LOG_BUF_MAX 512
+
+void klog_writev(int level, const struct iovec* iov, int iov_count) {
+    if (level > klog_level) return;
+
+    static int klog_fd = __open_klog();
+    if (klog_fd == -1) return;
+    TEMP_FAILURE_RETRY(writev(klog_fd, iov, iov_count));
+}
+
+void klog_write(int level, const char* fmt, ...) {
+    if (level > klog_level) return;
+
+    char buf[LOG_BUF_MAX];
+    va_list ap;
+    va_start(ap, fmt);
+    vsnprintf(buf, sizeof(buf), fmt, ap);
+    va_end(ap);
+
+    buf[LOG_BUF_MAX - 1] = 0;
+
+    struct iovec iov[1];
+    iov[0].iov_base = buf;
+    iov[0].iov_len = strlen(buf);
+    klog_writev(level, iov, 1);
+}
diff --git a/libcutils/multiuser.c b/libcutils/multiuser.c
index 0f4427b..61403f4 100644
--- a/libcutils/multiuser.c
+++ b/libcutils/multiuser.c
@@ -15,21 +15,52 @@
  */
 
 #include <cutils/multiuser.h>
+#include <private/android_filesystem_config.h>
 
 userid_t multiuser_get_user_id(uid_t uid) {
-    return uid / MULTIUSER_APP_PER_USER_RANGE;
+    return uid / AID_USER_OFFSET;
 }
 
 appid_t multiuser_get_app_id(uid_t uid) {
-    return uid % MULTIUSER_APP_PER_USER_RANGE;
+    return uid % AID_USER_OFFSET;
 }
 
-uid_t multiuser_get_uid(userid_t userId, appid_t appId) {
-    return userId * MULTIUSER_APP_PER_USER_RANGE + (appId % MULTIUSER_APP_PER_USER_RANGE);
+uid_t multiuser_get_uid(userid_t user_id, appid_t app_id) {
+    return (user_id * AID_USER_OFFSET) + (app_id % AID_USER_OFFSET);
 }
 
-appid_t multiuser_get_shared_app_gid(uid_t id) {
-  return MULTIUSER_FIRST_SHARED_APPLICATION_GID + (id % MULTIUSER_APP_PER_USER_RANGE)
-          - MULTIUSER_FIRST_APPLICATION_UID;
+gid_t multiuser_get_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_CACHE_GID_START);
+    } else {
+        return -1;
+    }
+}
 
+gid_t multiuser_get_ext_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_GID_START);
+    } else {
+        return -1;
+    }
+}
+
+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);
+    } else {
+        return -1;
+    }
+}
+
+gid_t multiuser_get_shared_app_gid(uid_t uid) {
+    return multiuser_get_shared_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
 }
diff --git a/libcutils/native_handle.c b/libcutils/native_handle.c
index 61fa38e..9f4840a 100644
--- a/libcutils/native_handle.c
+++ b/libcutils/native_handle.c
@@ -16,18 +16,32 @@
 
 #define LOG_TAG "NativeHandle"
 
-#include <stdint.h>
 #include <errno.h>
-#include <string.h>
+#include <stdint.h>
 #include <stdlib.h>
+#include <string.h>
 #include <unistd.h>
 
-#include <cutils/log.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)
+{
+    if ((uintptr_t) storage % alignof(native_handle_t)) {
+        return NULL;
+    }
+
+    native_handle_t* handle = (native_handle_t*) storage;
+    handle->version = sizeof(native_handle_t);
+    handle->numFds = numFds;
+    handle->numInts = numInts;
+
+    return handle;
+}
+
 native_handle_t* native_handle_create(int numFds, int numInts)
 {
     if (numFds < 0 || numInts < 0 || numFds > kMaxNativeFds || numInts > kMaxNativeInts) {
@@ -44,6 +58,27 @@
     return h;
 }
 
+native_handle_t* native_handle_clone(const native_handle_t* handle)
+{
+    native_handle_t* clone = native_handle_create(handle->numFds, handle->numInts);
+    int i;
+
+    for (i = 0; i < handle->numFds; i++) {
+        clone->data[i] = dup(handle->data[i]);
+        if (clone->data[i] < 0) {
+            clone->numFds = i;
+            native_handle_close(clone);
+            native_handle_delete(clone);
+            return NULL;
+        }
+    }
+
+    memcpy(&clone->data[handle->numFds], &handle->data[handle->numFds],
+            sizeof(int) * handle->numInts);
+
+    return clone;
+}
+
 int native_handle_delete(native_handle_t* h)
 {
     if (h) {
diff --git a/libcutils/process_name.c b/libcutils/process_name.c
deleted file mode 100644
index 5d28b6f..0000000
--- a/libcutils/process_name.c
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2008 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 <fcntl.h>
-#include <stdlib.h>
-#include <string.h>
-#if defined(__linux__)
-#include <sys/prctl.h>
-#endif
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/process_name.h>
-#if defined(__ANDROID__)
-#include <cutils/properties.h>
-#endif
-
-#define PROCESS_NAME_DEVICE "/sys/qemu_trace/process_name"
-
-static const char* process_name = "unknown";
-#if defined(__ANDROID__)
-static int running_in_emulator = -1;
-#endif
-
-void set_process_name(const char* new_name) {
-#if defined(__ANDROID__)
-    char  propBuf[PROPERTY_VALUE_MAX];
-#endif
-
-    if (new_name == NULL) {
-        return;
-    }
-
-    // We never free the old name. Someone else could be using it.
-    int len = strlen(new_name);
-    char* copy = (char*) malloc(len + 1);
-    strcpy(copy, new_name);
-    process_name = (const char*) copy;
-
-#if defined(__linux__)
-    if (len < 16) {
-        prctl(PR_SET_NAME, (unsigned long) new_name, 0, 0, 0);
-    } else {
-        prctl(PR_SET_NAME, (unsigned long) new_name + len - 15, 0, 0, 0);
-    }
-#endif
-
-#if defined(__ANDROID__)
-    // If we know we are not running in the emulator, then return.
-    if (running_in_emulator == 0) {
-        return;
-    }
-
-    // If the "running_in_emulator" variable has not been initialized,
-    // then do it now.
-    if (running_in_emulator == -1) {
-        property_get("ro.kernel.qemu", propBuf, "");
-        if (propBuf[0] == '1') {
-            running_in_emulator = 1;
-        } else {
-            running_in_emulator = 0;
-            return;
-        }
-    }
-
-    // If the emulator was started with the "-trace file" command line option
-    // then we want to record the process name in the trace even if we are
-    // not currently tracing instructions (so that we will know the process
-    // name when we do start tracing instructions).  We do not need to execute
-    // this code if we are just running in the emulator without the "-trace"
-    // command line option, but we don't know that here and this function
-    // isn't called frequently enough to bother optimizing that case.
-    int fd = open(PROCESS_NAME_DEVICE, O_RDWR);
-    if (fd < 0)
-        return;
-    write(fd, process_name, strlen(process_name) + 1);
-    close(fd);
-#endif
-}
-
-const char* get_process_name(void) {
-    return process_name;
-}
diff --git a/libcutils/properties.c b/libcutils/properties.c
deleted file mode 100644
index 4e46e02..0000000
--- a/libcutils/properties.c
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "properties"
-// #define LOG_NDEBUG 0
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <unistd.h>
-#include <cutils/sockets.h>
-#include <errno.h>
-#include <assert.h>
-
-#include <cutils/properties.h>
-#include <stdbool.h>
-#include <inttypes.h>
-#include <log/log.h>
-
-int8_t property_get_bool(const char *key, int8_t default_value) {
-    if (!key) {
-        return default_value;
-    }
-
-    int8_t result = default_value;
-    char buf[PROPERTY_VALUE_MAX] = {'\0',};
-
-    int len = property_get(key, buf, "");
-    if (len == 1) {
-        char ch = buf[0];
-        if (ch == '0' || ch == 'n') {
-            result = false;
-        } else if (ch == '1' || ch == 'y') {
-            result = true;
-        }
-    } else if (len > 1) {
-         if (!strcmp(buf, "no") || !strcmp(buf, "false") || !strcmp(buf, "off")) {
-            result = false;
-        } else if (!strcmp(buf, "yes") || !strcmp(buf, "true") || !strcmp(buf, "on")) {
-            result = true;
-        }
-    }
-
-    return result;
-}
-
-// Convert string property to int (default if fails); return default value if out of bounds
-static intmax_t property_get_imax(const char *key, intmax_t lower_bound, intmax_t upper_bound,
-        intmax_t default_value) {
-    if (!key) {
-        return default_value;
-    }
-
-    intmax_t result = default_value;
-    char buf[PROPERTY_VALUE_MAX] = {'\0',};
-    char *end = NULL;
-
-    int len = property_get(key, buf, "");
-    if (len > 0) {
-        int tmp = errno;
-        errno = 0;
-
-        // Infer base automatically
-        result = strtoimax(buf, &end, /*base*/0);
-        if ((result == INTMAX_MIN || result == INTMAX_MAX) && errno == ERANGE) {
-            // Over or underflow
-            result = default_value;
-            ALOGV("%s(%s,%" PRIdMAX ") - overflow", __FUNCTION__, key, default_value);
-        } else if (result < lower_bound || result > upper_bound) {
-            // Out of range of requested bounds
-            result = default_value;
-            ALOGV("%s(%s,%" PRIdMAX ") - out of range", __FUNCTION__, key, default_value);
-        } else if (end == buf) {
-            // Numeric conversion failed
-            result = default_value;
-            ALOGV("%s(%s,%" PRIdMAX ") - numeric conversion failed",
-                    __FUNCTION__, key, default_value);
-        }
-
-        errno = tmp;
-    }
-
-    return result;
-}
-
-int64_t property_get_int64(const char *key, int64_t default_value) {
-    return (int64_t)property_get_imax(key, INT64_MIN, INT64_MAX, default_value);
-}
-
-int32_t property_get_int32(const char *key, int32_t default_value) {
-    return (int32_t)property_get_imax(key, INT32_MIN, INT32_MAX, default_value);
-}
-
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
-
-int property_set(const char *key, const char *value)
-{
-    return __system_property_set(key, value);
-}
-
-int property_get(const char *key, char *value, const char *default_value)
-{
-    int len;
-
-    len = __system_property_get(key, value);
-    if(len > 0) {
-        return len;
-    }
-    if(default_value) {
-        len = strlen(default_value);
-        if (len >= PROPERTY_VALUE_MAX) {
-            len = PROPERTY_VALUE_MAX - 1;
-        }
-        memcpy(value, default_value, len);
-        value[len] = '\0';
-    }
-    return len;
-}
-
-struct property_list_callback_data
-{
-    void (*propfn)(const char *key, const char *value, void *cookie);
-    void *cookie;
-};
-
-static void property_list_callback(const prop_info *pi, void *cookie)
-{
-    char name[PROP_NAME_MAX];
-    char value[PROP_VALUE_MAX];
-    struct property_list_callback_data *data = cookie;
-
-    __system_property_read(pi, name, value);
-    data->propfn(name, value, data->cookie);
-}
-
-int property_list(
-        void (*propfn)(const char *key, const char *value, void *cookie),
-        void *cookie)
-{
-    struct property_list_callback_data data = { propfn, cookie };
-    return __system_property_foreach(property_list_callback, &data);
-}
diff --git a/libcutils/properties.cpp b/libcutils/properties.cpp
new file mode 100644
index 0000000..d2645e6
--- /dev/null
+++ b/libcutils/properties.cpp
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2006 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "properties"
+// #define LOG_NDEBUG 0
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <cutils/properties.h>
+#include <cutils/sockets.h>
+#include <log/log.h>
+
+int8_t property_get_bool(const char *key, int8_t default_value) {
+    if (!key) {
+        return default_value;
+    }
+
+    int8_t result = default_value;
+    char buf[PROPERTY_VALUE_MAX] = {'\0'};
+
+    int len = property_get(key, buf, "");
+    if (len == 1) {
+        char ch = buf[0];
+        if (ch == '0' || ch == 'n') {
+            result = false;
+        } else if (ch == '1' || ch == 'y') {
+            result = true;
+        }
+    } else if (len > 1) {
+        if (!strcmp(buf, "no") || !strcmp(buf, "false") || !strcmp(buf, "off")) {
+            result = false;
+        } else if (!strcmp(buf, "yes") || !strcmp(buf, "true") || !strcmp(buf, "on")) {
+            result = true;
+        }
+    }
+
+    return result;
+}
+
+// Convert string property to int (default if fails); return default value if out of bounds
+static intmax_t property_get_imax(const char *key, intmax_t lower_bound, intmax_t upper_bound,
+                                  intmax_t default_value) {
+    if (!key) {
+        return default_value;
+    }
+
+    intmax_t result = default_value;
+    char buf[PROPERTY_VALUE_MAX] = {'\0'};
+    char *end = NULL;
+
+    int len = property_get(key, buf, "");
+    if (len > 0) {
+        int tmp = errno;
+        errno = 0;
+
+        // Infer base automatically
+        result = strtoimax(buf, &end, /*base*/ 0);
+        if ((result == INTMAX_MIN || result == INTMAX_MAX) && errno == ERANGE) {
+            // Over or underflow
+            result = default_value;
+            ALOGV("%s(%s,%" PRIdMAX ") - overflow", __FUNCTION__, key, default_value);
+        } else if (result < lower_bound || result > upper_bound) {
+            // Out of range of requested bounds
+            result = default_value;
+            ALOGV("%s(%s,%" PRIdMAX ") - out of range", __FUNCTION__, key, default_value);
+        } else if (end == buf) {
+            // Numeric conversion failed
+            result = default_value;
+            ALOGV("%s(%s,%" PRIdMAX ") - numeric conversion failed", __FUNCTION__, key,
+                  default_value);
+        }
+
+        errno = tmp;
+    }
+
+    return result;
+}
+
+int64_t property_get_int64(const char *key, int64_t default_value) {
+    return (int64_t)property_get_imax(key, INT64_MIN, INT64_MAX, default_value);
+}
+
+int32_t property_get_int32(const char *key, int32_t default_value) {
+    return (int32_t)property_get_imax(key, INT32_MIN, INT32_MAX, default_value);
+}
+
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+
+int property_set(const char *key, const char *value) {
+    return __system_property_set(key, value);
+}
+
+int property_get(const char *key, char *value, const char *default_value) {
+    int len = __system_property_get(key, value);
+    if (len > 0) {
+        return len;
+    }
+    if (default_value) {
+        len = strnlen(default_value, PROPERTY_VALUE_MAX - 1);
+        memcpy(value, default_value, len);
+        value[len] = '\0';
+    }
+    return len;
+}
+
+struct callback_data {
+    void (*callback)(const char* name, const char* value, void* cookie);
+    void* cookie;
+};
+
+static void trampoline(void* raw_data, const char* name, const char* value, unsigned /*serial*/) {
+    callback_data* data = reinterpret_cast<callback_data*>(raw_data);
+    data->callback(name, value, data->cookie);
+}
+
+static void property_list_callback(const prop_info* pi, void* data) {
+    __system_property_read_callback(pi, trampoline, data);
+}
+
+int property_list(void (*fn)(const char* name, const char* value, void* cookie), void* cookie) {
+    callback_data data = { fn, cookie };
+    return __system_property_foreach(property_list_callback, &data);
+}
diff --git a/libcutils/qtaguid.c b/libcutils/qtaguid.c
index 2fbe02e..22b8325 100644
--- a/libcutils/qtaguid.c
+++ b/libcutils/qtaguid.c
@@ -26,8 +26,8 @@
 #include <string.h>
 #include <unistd.h>
 
-#include <cutils/qtaguid.h>
 #include <log/log.h>
+#include <cutils/qtaguid.h>
 
 static const char* CTRL_PROCPATH = "/proc/net/xt_qtaguid/ctrl";
 static const int CTRL_MAX_INPUT_LEN = 128;
@@ -47,10 +47,7 @@
 
 /* Only call once per process. */
 void qtaguid_resTrack(void) {
-    resTrackFd = TEMP_FAILURE_RETRY(open("/dev/xt_qtaguid", O_RDONLY));
-    if (resTrackFd >=0) {
-        TEMP_FAILURE_RETRY(fcntl(resTrackFd, F_SETFD, FD_CLOEXEC));
-    }
+    resTrackFd = TEMP_FAILURE_RETRY(open("/dev/xt_qtaguid", O_RDONLY | O_CLOEXEC));
 }
 
 /*
@@ -63,7 +60,7 @@
 
     ALOGV("write_ctrl(%s)", cmd);
 
-    fd = TEMP_FAILURE_RETRY(open(CTRL_PROCPATH, O_WRONLY));
+    fd = TEMP_FAILURE_RETRY(open(CTRL_PROCPATH, O_WRONLY | O_CLOEXEC));
     if (fd < 0) {
         return -errno;
     }
@@ -86,7 +83,7 @@
     int param_fd;
     int res;
 
-    param_fd = TEMP_FAILURE_RETRY(open(param_path, O_WRONLY));
+    param_fd = TEMP_FAILURE_RETRY(open(param_path, O_WRONLY | O_CLOEXEC));
     if (param_fd < 0) {
         return -errno;
     }
diff --git a/libcutils/sched_policy.c b/libcutils/sched_policy.c
deleted file mode 100644
index e11eb2e..0000000
--- a/libcutils/sched_policy.c
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
-** Copyright 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.
-*/
-
-#define LOG_TAG "SchedPolicy"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <cutils/sched_policy.h>
-#include <log/log.h>
-
-#define UNUSED __attribute__((__unused__))
-
-/* 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.
- */
-static inline SchedPolicy _policy(SchedPolicy p)
-{
-   return p == SP_DEFAULT ? SP_SYSTEM_DEFAULT : p;
-}
-
-#if defined(__ANDROID__)
-
-#include <pthread.h>
-#include <sched.h>
-#include <sys/prctl.h>
-
-#define POLICY_DEBUG 0
-
-// This prctl is only available in Android kernels.
-#define PR_SET_TIMERSLACK_PID 41
-
-// timer slack value in nS enforced when the thread moves to background
-#define TIMER_SLACK_BG 40000000
-#define TIMER_SLACK_FG 50000
-
-static pthread_once_t the_once = PTHREAD_ONCE_INIT;
-
-static int __sys_supports_schedgroups = -1;
-
-#ifdef USE_CPUSETS
-// 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;
-static int fg_cpuset_fd = -1;
-static int ta_cpuset_fd = -1; // special cpuset for top app
-#endif
-
-// File descriptors open to /dev/stune/../tasks, setup by initialize, or -1 on error
-static int bg_schedboost_fd = -1;
-static int fg_schedboost_fd = -1;
-static int ta_schedboost_fd = -1;
-
-#if defined(USE_CPUSETS) || defined(USE_SCHEDBOOST)
-/* Add tid to the scheduling group defined by the policy */
-static int add_tid_to_cgroup(int tid, int fd)
-{
-    if (fd < 0) {
-        SLOGE("add_tid_to_cgroup failed; fd=%d\n", fd);
-        errno = EINVAL;
-        return -1;
-    }
-
-    // specialized itoa -- works for tid > 0
-    char text[22];
-    char *end = text + sizeof(text) - 1;
-    char *ptr = end;
-    *ptr = '\0';
-    while (tid > 0) {
-        *--ptr = '0' + (tid % 10);
-        tid = tid / 10;
-    }
-
-    if (write(fd, ptr, end - ptr) < 0) {
-        /*
-         * If the thread is in the process of exiting,
-         * don't flag an error
-         */
-        if (errno == ESRCH)
-                return 0;
-        SLOGW("add_tid_to_cgroup failed to write '%s' (%s); fd=%d\n",
-              ptr, strerror(errno), fd);
-        errno = EINVAL;
-        return -1;
-    }
-
-    return 0;
-}
-#endif //defined(USE_CPUSETS) || defined(USE_SCHEDBOOST)
-
-static void __initialize(void) {
-    if (!access("/dev/cpuctl/tasks", F_OK)) {
-        __sys_supports_schedgroups = 1;
-    } else {
-        __sys_supports_schedgroups = 0;
-    }
-
-#ifdef USE_CPUSETS
-    if (!access("/dev/cpuset/tasks", F_OK)) {
-        char* filename;
-        filename = "/dev/cpuset/foreground/tasks";
-        fg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/cpuset/background/tasks";
-        bg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/cpuset/system-background/tasks";
-        system_bg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/cpuset/top-app/tasks";
-        ta_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
-
-#ifdef USE_SCHEDBOOST
-        filename = "/dev/stune/top-app/tasks";
-        ta_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/stune/foreground/tasks";
-        fg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/stune/background/tasks";
-        bg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
-#endif
-    }
-#endif
-}
-
-/*
- * Returns the path under the requested cgroup subsystem (if it exists)
- *
- * The data from /proc/<pid>/cgroup looks (something) like:
- *  2:cpu:/bg_non_interactive
- *  1:cpuacct:/
- *
- * We return the part after the "/", which will be an empty string for
- * the default cgroup.  If the string is longer than "bufLen", the string
- * will be truncated.
- */
-static int getCGroupSubsys(int tid, const char* subsys, char* buf, size_t bufLen)
-{
-#if defined(__ANDROID__)
-    char pathBuf[32];
-    char lineBuf[256];
-    FILE *fp;
-
-    snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
-    if (!(fp = fopen(pathBuf, "r"))) {
-        return -1;
-    }
-
-    while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
-        char *next = lineBuf;
-        char *found_subsys;
-        char *grp;
-        size_t len;
-
-        /* Junk the first field */
-        if (!strsep(&next, ":")) {
-            goto out_bad_data;
-        }
-
-        if (!(found_subsys = strsep(&next, ":"))) {
-            goto out_bad_data;
-        }
-
-        if (strcmp(found_subsys, subsys)) {
-            /* Not the subsys we're looking for */
-            continue;
-        }
-
-        if (!(grp = strsep(&next, ":"))) {
-            goto out_bad_data;
-        }
-        grp++; /* Drop the leading '/' */
-        len = strlen(grp);
-        grp[len-1] = '\0'; /* Drop the trailing '\n' */
-
-        if (bufLen <= len) {
-            len = bufLen - 1;
-        }
-        strncpy(buf, grp, len);
-        buf[len] = '\0';
-        fclose(fp);
-        return 0;
-    }
-
-    SLOGE("Failed to find subsys %s", subsys);
-    fclose(fp);
-    return -1;
- out_bad_data:
-    SLOGE("Bad cgroup data {%s}", lineBuf);
-    fclose(fp);
-    return -1;
-#else
-    errno = ENOSYS;
-    return -1;
-#endif
-}
-
-int get_sched_policy(int tid, SchedPolicy *policy)
-{
-    if (tid == 0) {
-        tid = gettid();
-    }
-    pthread_once(&the_once, __initialize);
-
-    if (__sys_supports_schedgroups) {
-        char grpBuf[32];
-#ifdef USE_CPUSETS
-        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;
-        }
-#endif
-    } 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;
-        }
-    }
-    return 0;
-}
-
-int set_cpuset_policy(int tid, SchedPolicy policy)
-{
-    // in the absence of cpusets, use the old sched policy
-#ifndef USE_CPUSETS
-    return set_sched_policy(tid, policy);
-#else
-    if (tid == 0) {
-        tid = gettid();
-    }
-    policy = _policy(policy);
-    pthread_once(&the_once, __initialize);
-
-    int fd = -1;
-    int boost_fd = -1;
-    switch (policy) {
-    case SP_BACKGROUND:
-        fd = bg_cpuset_fd;
-        boost_fd = bg_schedboost_fd;
-        break;
-    case SP_FOREGROUND:
-    case SP_AUDIO_APP:
-    case SP_AUDIO_SYS:
-        fd = fg_cpuset_fd;
-        boost_fd = fg_schedboost_fd;
-        break;
-    case SP_TOP_APP :
-        fd = ta_cpuset_fd;
-        boost_fd = ta_schedboost_fd;
-        break;
-    case SP_SYSTEM:
-        fd = system_bg_cpuset_fd;
-        break;
-    default:
-        boost_fd = fd = -1;
-        break;
-    }
-
-    if (add_tid_to_cgroup(tid, fd) != 0) {
-        if (errno != ESRCH && errno != ENOENT)
-            return -errno;
-    }
-
-#ifdef USE_SCHEDBOOST
-    if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
-        if (errno != ESRCH && errno != ENOENT)
-            return -errno;
-    }
-#endif
-
-    return 0;
-#endif
-}
-
-int set_sched_policy(int tid, SchedPolicy policy)
-{
-    if (tid == 0) {
-        tid = gettid();
-    }
-    policy = _policy(policy);
-    pthread_once(&the_once, __initialize);
-
-#if POLICY_DEBUG
-    char statfile[64];
-    char statline[1024];
-    char thread_name[255];
-    int fd;
-
-    sprintf(statfile, "/proc/%d/stat", tid);
-    memset(thread_name, 0, sizeof(thread_name));
-
-    fd = open(statfile, O_RDONLY);
-    if (fd >= 0) {
-        int rc = read(fd, statline, 1023);
-        close(fd);
-        statline[rc] = 0;
-        char *p = statline;
-        char *q;
-
-        for (p = statline; *p != '('; p++);
-        p++;
-        for (q = p; *q != ')'; q++);
-
-        strncpy(thread_name, p, (q-p));
-    }
-    switch (policy) {
-    case SP_BACKGROUND:
-        SLOGD("vvv tid %d (%s)", tid, thread_name);
-        break;
-    case SP_FOREGROUND:
-    case SP_AUDIO_APP:
-    case SP_AUDIO_SYS:
-    case SP_TOP_APP:
-        SLOGD("^^^ tid %d (%s)", tid, thread_name);
-        break;
-    case SP_SYSTEM:
-        SLOGD("/// tid %d (%s)", tid, thread_name);
-        break;
-    default:
-        SLOGD("??? tid %d (%s)", tid, thread_name);
-        break;
-    }
-#endif
-
-    if (__sys_supports_schedgroups) {
-        int boost_fd = -1;
-        switch (policy) {
-        case SP_BACKGROUND:
-            boost_fd = bg_schedboost_fd;
-            break;
-        case SP_FOREGROUND:
-        case SP_AUDIO_APP:
-        case SP_AUDIO_SYS:
-            boost_fd = fg_schedboost_fd;
-            break;
-        case SP_TOP_APP:
-            boost_fd = ta_schedboost_fd;
-            break;
-        default:
-            boost_fd = -1;
-            break;
-        }
-
-#ifdef USE_SCHEDBOOST
-        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
-            if (errno != ESRCH && errno != ENOENT)
-                return -errno;
-        }
-#endif
-    } else {
-        struct sched_param param;
-
-        param.sched_priority = 0;
-        sched_setscheduler(tid,
-                           (policy == SP_BACKGROUND) ?
-                           SCHED_BATCH : SCHED_NORMAL,
-                           &param);
-    }
-
-    prctl(PR_SET_TIMERSLACK_PID,
-          policy == SP_BACKGROUND ? TIMER_SLACK_BG : TIMER_SLACK_FG, tid);
-
-    return 0;
-}
-
-#else
-
-/* Stubs for non-Android targets. */
-
-int set_sched_policy(int tid UNUSED, SchedPolicy policy UNUSED)
-{
-    return 0;
-}
-
-int get_sched_policy(int tid UNUSED, SchedPolicy *policy)
-{
-    *policy = SP_SYSTEM_DEFAULT;
-    return 0;
-}
-
-#endif
-
-const char *get_sched_policy_name(SchedPolicy policy)
-{
-    policy = _policy(policy);
-    static const char * const strings[SP_CNT] = {
-       [SP_BACKGROUND] = "bg",
-       [SP_FOREGROUND] = "fg",
-       [SP_SYSTEM]     = "  ",
-       [SP_AUDIO_APP]  = "aa",
-       [SP_AUDIO_SYS]  = "as",
-       [SP_TOP_APP]    = "ta",
-    };
-    if ((policy < SP_CNT) && (strings[policy] != NULL))
-        return strings[policy];
-    else
-        return "error";
-}
diff --git a/libcutils/sched_policy.cpp b/libcutils/sched_policy.cpp
new file mode 100644
index 0000000..3837ca7
--- /dev/null
+++ b/libcutils/sched_policy.cpp
@@ -0,0 +1,472 @@
+/*
+** Copyright 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.
+*/
+
+#define LOG_TAG "SchedPolicy"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <log/log.h>
+#include <cutils/sched_policy.h>
+
+#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.
+ */
+static inline SchedPolicy _policy(SchedPolicy p)
+{
+   return p == SP_DEFAULT ? SP_SYSTEM_DEFAULT : p;
+}
+
+#if defined(__ANDROID__)
+
+#include <pthread.h>
+#include <sched.h>
+#include <sys/prctl.h>
+
+#define POLICY_DEBUG 0
+
+// timer slack value in nS enforced when the thread moves to background
+#define TIMER_SLACK_BG 40000000
+#define TIMER_SLACK_FG 50000
+
+static pthread_once_t the_once = PTHREAD_ONCE_INIT;
+
+static int __sys_supports_timerslack = -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;
+static int fg_cpuset_fd = -1;
+static int ta_cpuset_fd = -1; // special cpuset for top app
+
+// File descriptors open to /dev/stune/../tasks, setup by initialize, or -1 on error
+static int bg_schedboost_fd = -1;
+static int fg_schedboost_fd = -1;
+static int ta_schedboost_fd = -1;
+
+/* Add tid to the scheduling group defined by the policy */
+static int add_tid_to_cgroup(int tid, int fd)
+{
+    if (fd < 0) {
+        SLOGE("add_tid_to_cgroup failed; fd=%d\n", fd);
+        errno = EINVAL;
+        return -1;
+    }
+
+    // specialized itoa -- works for tid > 0
+    char text[22];
+    char *end = text + sizeof(text) - 1;
+    char *ptr = end;
+    *ptr = '\0';
+    while (tid > 0) {
+        *--ptr = '0' + (tid % 10);
+        tid = tid / 10;
+    }
+
+    if (write(fd, ptr, end - ptr) < 0) {
+        /*
+         * If the thread is in the process of exiting,
+         * don't flag an error
+         */
+        if (errno == ESRCH)
+                return 0;
+        SLOGW("add_tid_to_cgroup failed to write '%s' (%s); fd=%d\n",
+              ptr, strerror(errno), fd);
+        errno = EINVAL;
+        return -1;
+    }
+
+    return 0;
+}
+
+/*
+    If CONFIG_CPUSETS for Linux kernel is set, "tasks" can be found under
+    /dev/cpuset mounted in init.rc; otherwise, that file does not exist
+    even though the directory, /dev/cpuset, is still created (by init.rc).
+
+    A couple of other candidates (under cpuset mount directory):
+        notify_on_release
+        release_agent
+
+    Yet another way to decide if cpuset is enabled is to parse
+    /proc/self/status and search for lines begin with "Mems_allowed".
+
+    If CONFIG_PROC_PID_CPUSET is set, the existence "/proc/self/cpuset" can
+    be used to decide if CONFIG_CPUSETS is set, so we don't have a dependency
+    on where init.rc mounts cpuset. That's why we'd better require this
+    configuration be set if CONFIG_CPUSETS is set.
+
+    With runtime check using the following function, build time
+    variables like ENABLE_CPUSETS (used in Android.mk) or cpusets (used
+    in Android.bp) are not needed.
+ */
+
+bool cpusets_enabled() {
+    static bool enabled = (access("/dev/cpuset/tasks", F_OK) == 0);
+
+    return enabled;
+}
+
+/*
+    Similar to CONFIG_CPUSETS above, but with a different configuration
+    CONFIG_SCHEDTUNE that's in Android common Linux kernel and Linaro
+    Stable Kernel (LSK), but not in mainline Linux as of v4.9.
+
+    With runtime check using the following function, build time
+    variables like ENABLE_SCHEDBOOST (used in Android.mk) or schedboost
+    (used in Android.bp) are not needed.
+
+ */
+
+bool schedboost_enabled() {
+    static bool enabled = (access("/dev/stune/tasks", F_OK) == 0);
+
+    return enabled;
+}
+
+static void __initialize() {
+    const char* filename;
+
+    if (cpusets_enabled()) {
+        if (!access("/dev/cpuset/tasks", W_OK)) {
+
+            filename = "/dev/cpuset/foreground/tasks";
+            fg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
+            filename = "/dev/cpuset/background/tasks";
+            bg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
+            filename = "/dev/cpuset/system-background/tasks";
+            system_bg_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
+            filename = "/dev/cpuset/top-app/tasks";
+            ta_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
+
+            if (schedboost_enabled()) {
+                filename = "/dev/stune/top-app/tasks";
+                ta_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
+                filename = "/dev/stune/foreground/tasks";
+                fg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
+                filename = "/dev/stune/background/tasks";
+                bg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
+            }
+        }
+    }
+
+    char buf[64];
+    snprintf(buf, sizeof(buf), "/proc/%d/timerslack_ns", getpid());
+    __sys_supports_timerslack = !access(buf, W_OK);
+}
+
+/*
+ * Returns the path under the requested cgroup subsystem (if it exists)
+ *
+ * The data from /proc/<pid>/cgroup looks (something) like:
+ *  2:cpu:/bg_non_interactive
+ *  1:cpuacct:/
+ *
+ * We return the part after the "/", which will be an empty string for
+ * the default cgroup.  If the string is longer than "bufLen", the string
+ * will be truncated.
+ */
+static int getCGroupSubsys(int tid, const char* subsys, char* buf, size_t bufLen)
+{
+#if defined(__ANDROID__)
+    char pathBuf[32];
+    char lineBuf[256];
+    FILE *fp;
+
+    snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
+    if (!(fp = fopen(pathBuf, "re"))) {
+        return -1;
+    }
+
+    while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
+        char *next = lineBuf;
+        char *found_subsys;
+        char *grp;
+        size_t len;
+
+        /* Junk the first field */
+        if (!strsep(&next, ":")) {
+            goto out_bad_data;
+        }
+
+        if (!(found_subsys = strsep(&next, ":"))) {
+            goto out_bad_data;
+        }
+
+        if (strcmp(found_subsys, subsys)) {
+            /* Not the subsys we're looking for */
+            continue;
+        }
+
+        if (!(grp = strsep(&next, ":"))) {
+            goto out_bad_data;
+        }
+        grp++; /* Drop the leading '/' */
+        len = strlen(grp);
+        grp[len-1] = '\0'; /* Drop the trailing '\n' */
+
+        if (bufLen <= len) {
+            len = bufLen - 1;
+        }
+        strncpy(buf, grp, len);
+        buf[len] = '\0';
+        fclose(fp);
+        return 0;
+    }
+
+    SLOGE("Failed to find subsys %s", subsys);
+    fclose(fp);
+    return -1;
+ out_bad_data:
+    SLOGE("Bad cgroup data {%s}", lineBuf);
+    fclose(fp);
+    return -1;
+#else
+    errno = ENOSYS;
+    return -1;
+#endif
+}
+
+int get_sched_policy(int tid, SchedPolicy *policy)
+{
+    if (tid == 0) {
+        tid = gettid();
+    }
+    pthread_once(&the_once, __initialize);
+
+    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 {
+        // In b/34193533, we removed bg_non_interactive cgroup, so now
+        // all threads are in FOREGROUND cgroup
+        *policy = SP_FOREGROUND;
+    }
+    return 0;
+}
+
+int set_cpuset_policy(int tid, SchedPolicy policy)
+{
+    // in the absence of cpusets, use the old sched policy
+    if (!cpusets_enabled()) {
+        return set_sched_policy(tid, policy);
+    }
+
+    if (tid == 0) {
+        tid = gettid();
+    }
+    policy = _policy(policy);
+    pthread_once(&the_once, __initialize);
+
+    int fd = -1;
+    int boost_fd = -1;
+    switch (policy) {
+    case SP_BACKGROUND:
+        fd = bg_cpuset_fd;
+        boost_fd = bg_schedboost_fd;
+        break;
+    case SP_FOREGROUND:
+    case SP_AUDIO_APP:
+    case SP_AUDIO_SYS:
+        fd = fg_cpuset_fd;
+        boost_fd = fg_schedboost_fd;
+        break;
+    case SP_TOP_APP :
+        fd = ta_cpuset_fd;
+        boost_fd = ta_schedboost_fd;
+        break;
+    case SP_SYSTEM:
+        fd = system_bg_cpuset_fd;
+        break;
+    default:
+        boost_fd = fd = -1;
+        break;
+    }
+
+    if (add_tid_to_cgroup(tid, 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;
+        }
+    }
+
+    return 0;
+}
+
+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));
+        }
+        close(fd);
+        return;
+    }
+}
+
+int set_sched_policy(int tid, SchedPolicy policy)
+{
+    if (tid == 0) {
+        tid = gettid();
+    }
+    policy = _policy(policy);
+    pthread_once(&the_once, __initialize);
+
+#if POLICY_DEBUG
+    char statfile[64];
+    char statline[1024];
+    char thread_name[255];
+
+    snprintf(statfile, sizeof(statfile), "/proc/%d/stat", tid);
+    memset(thread_name, 0, sizeof(thread_name));
+
+    int fd = open(statfile, O_RDONLY | O_CLOEXEC);
+    if (fd >= 0) {
+        int rc = read(fd, statline, 1023);
+        close(fd);
+        statline[rc] = 0;
+        char *p = statline;
+        char *q;
+
+        for (p = statline; *p != '('; p++);
+        p++;
+        for (q = p; *q != ')'; q++);
+
+        strncpy(thread_name, p, (q-p));
+    }
+    switch (policy) {
+    case SP_BACKGROUND:
+        SLOGD("vvv tid %d (%s)", tid, thread_name);
+        break;
+    case SP_FOREGROUND:
+    case SP_AUDIO_APP:
+    case SP_AUDIO_SYS:
+    case SP_TOP_APP:
+        SLOGD("^^^ tid %d (%s)", tid, thread_name);
+        break;
+    case SP_SYSTEM:
+        SLOGD("/// tid %d (%s)", tid, thread_name);
+        break;
+    default:
+        SLOGD("??? tid %d (%s)", tid, thread_name);
+        break;
+    }
+#endif
+
+    if (schedboost_enabled()) {
+        int boost_fd = -1;
+        switch (policy) {
+        case SP_BACKGROUND:
+            boost_fd = bg_schedboost_fd;
+            break;
+        case SP_FOREGROUND:
+        case SP_AUDIO_APP:
+        case SP_AUDIO_SYS:
+            boost_fd = fg_schedboost_fd;
+            break;
+        case SP_TOP_APP:
+            boost_fd = ta_schedboost_fd;
+            break;
+        default:
+            boost_fd = -1;
+            break;
+        }
+
+        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
+            if (errno != ESRCH && errno != ENOENT)
+                return -errno;
+        }
+
+    }
+
+    if (__sys_supports_timerslack) {
+        set_timerslack_ns(tid, policy == SP_BACKGROUND ?
+                               TIMER_SLACK_BG : TIMER_SLACK_FG);
+    }
+
+    return 0;
+}
+
+#else
+
+/* Stubs for non-Android targets. */
+
+int set_sched_policy(int tid UNUSED, SchedPolicy policy UNUSED)
+{
+    return 0;
+}
+
+int get_sched_policy(int tid UNUSED, SchedPolicy *policy)
+{
+    *policy = SP_SYSTEM_DEFAULT;
+    return 0;
+}
+
+#endif
+
+const char *get_sched_policy_name(SchedPolicy policy)
+{
+    policy = _policy(policy);
+    static const char * const strings[SP_CNT] = {
+       [SP_BACKGROUND] = "bg",
+       [SP_FOREGROUND] = "fg",
+       [SP_SYSTEM]     = "  ",
+       [SP_AUDIO_APP]  = "aa",
+       [SP_AUDIO_SYS]  = "as",
+       [SP_TOP_APP]    = "ta",
+    };
+    if ((policy < SP_CNT) && (strings[policy] != NULL))
+        return strings[policy];
+    else
+        return "error";
+}
diff --git a/libcutils/socket_loopback_client_unix.c b/libcutils/socket_loopback_client_unix.c
deleted file mode 100644
index e14cffb..0000000
--- a/libcutils/socket_loopback_client_unix.c
+++ /dev/null
@@ -1,57 +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>
-
-#if !defined(_WIN32)
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#endif
-
-#include <cutils/sockets.h>
-
-/* Connect to port on the loopback IP interface. type is
- * SOCK_STREAM or SOCK_DGRAM. 
- * return is a file descriptor or -1 on error
- */
-int socket_loopback_client(int port, int type)
-{
-    struct sockaddr_in addr;
-    int s;
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sin_family = AF_INET;
-    addr.sin_port = htons(port);
-    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-
-    s = socket(AF_INET, type, 0);
-    if(s < 0) return -1;
-
-    if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
-        close(s);
-        return -1;
-    }
-
-    return s;
-
-}
-
diff --git a/libcutils/socket_loopback_server_unix.c b/libcutils/socket_loopback_server_unix.c
index b600e34..7b92fd6 100644
--- a/libcutils/socket_loopback_server_unix.c
+++ b/libcutils/socket_loopback_server_unix.c
@@ -31,24 +31,18 @@
 
 #include <cutils/sockets.h>
 
-/* open listen() port on loopback interface */
-int socket_loopback_server(int port, int type)
+static int _socket_loopback_server(int family, int type, struct sockaddr * addr, size_t size)
 {
-    struct sockaddr_in addr;
     int s, n;
 
-    memset(&addr, 0, sizeof(addr));
-    addr.sin_family = AF_INET;
-    addr.sin_port = htons(port);
-    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-
-    s = socket(AF_INET, type, 0);
-    if(s < 0) return -1;
+    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, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+    if(bind(s, addr, size) < 0) {
         close(s);
         return -1;
     }
@@ -60,10 +54,35 @@
 
         if (ret < 0) {
             close(s);
-            return -1; 
+            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/socket_network_client_unix.c b/libcutils/socket_network_client_unix.c
index 3300b8f..37851b1 100644
--- a/libcutils/socket_network_client_unix.c
+++ b/libcutils/socket_network_client_unix.c
@@ -59,64 +59,64 @@
         return -1;
     }
 
-    // TODO: try all the addresses if there's more than one?
-    int family = addrs[0].ai_family;
-    int protocol = addrs[0].ai_protocol;
-    socklen_t addr_len = addrs[0].ai_addrlen;
-    struct sockaddr_storage addr;
-    memcpy(&addr, addrs[0].ai_addr, addr_len);
+    int result = -1;
+    for (struct addrinfo* addr = addrs; addr != NULL; addr = addr->ai_next) {
+        // The Mac doesn't have SOCK_NONBLOCK.
+        int s = socket(addr->ai_family, type, addr->ai_protocol);
+        if (s == -1 || toggle_O_NONBLOCK(s) == -1) return -1;
+
+        int rc = connect(s, addr->ai_addr, addr->ai_addrlen);
+        if (rc == 0) {
+            result = toggle_O_NONBLOCK(s);
+            break;
+        } else if (rc == -1 && errno != EINPROGRESS) {
+            close(s);
+            continue;
+        }
+
+        fd_set r_set;
+        FD_ZERO(&r_set);
+        FD_SET(s, &r_set);
+        fd_set w_set = r_set;
+
+        struct timeval ts;
+        ts.tv_sec = timeout;
+        ts.tv_usec = 0;
+        if ((rc = select(s + 1, &r_set, &w_set, NULL, (timeout != 0) ? &ts : NULL)) == -1) {
+            close(s);
+            break;
+        }
+        if (rc == 0) {  // we had a timeout
+            errno = ETIMEDOUT;
+            close(s);
+            break;
+        }
+
+        int error = 0;
+        socklen_t len = sizeof(error);
+        if (FD_ISSET(s, &r_set) || FD_ISSET(s, &w_set)) {
+            if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
+                close(s);
+                break;
+            }
+        } else {
+            close(s);
+            break;
+        }
+
+        if (error) {  // check if we had a socket error
+            // TODO: Update the timeout.
+            errno = error;
+            close(s);
+            continue;
+        }
+
+        result = toggle_O_NONBLOCK(s);
+        break;
+    }
 
     freeaddrinfo(addrs);
-
-    // The Mac doesn't have SOCK_NONBLOCK.
-    int s = socket(family, type, protocol);
-    if (s == -1 || toggle_O_NONBLOCK(s) == -1) return -1;
-
-    int rc = connect(s, (const struct sockaddr*) &addr, addr_len);
-    if (rc == 0) {
-        return toggle_O_NONBLOCK(s);
-    } else if (rc == -1 && errno != EINPROGRESS) {
-        close(s);
-        return -1;
-    }
-
-    fd_set r_set;
-    FD_ZERO(&r_set);
-    FD_SET(s, &r_set);
-    fd_set w_set = r_set;
-
-    struct timeval ts;
-    ts.tv_sec = timeout;
-    ts.tv_usec = 0;
-    if ((rc = select(s + 1, &r_set, &w_set, NULL, (timeout != 0) ? &ts : NULL)) == -1) {
-        close(s);
-        return -1;
-    }
-    if (rc == 0) {   // we had a timeout
-        errno = ETIMEDOUT;
-        close(s);
-        return -1;
-    }
-
-    int error = 0;
-    socklen_t len = sizeof(error);
-    if (FD_ISSET(s, &r_set) || FD_ISSET(s, &w_set)) {
-        if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
-            close(s);
-            return -1;
-        }
-    } else {
-        close(s);
-        return -1;
-    }
-
-    if (error) {  // check if we had a socket error
-        errno = error;
-        close(s);
-        return -1;
-    }
-
-    return toggle_O_NONBLOCK(s);
+    return result;
 }
 
 int socket_network_client(const char* host, int port, int type) {
diff --git a/libcutils/sockets.cpp b/libcutils/sockets.cpp
index d9ab146..23a447b 100644
--- a/libcutils/sockets.cpp
+++ b/libcutils/sockets.cpp
@@ -31,10 +31,6 @@
 
 #include <cutils/sockets.h>
 
-#if !defined(_WIN32)
-#include <netinet/in.h>
-#endif
-
 int socket_get_local_port(cutils_socket_t sock) {
     sockaddr_storage addr;
     socklen_t addr_size = sizeof(addr);
diff --git a/libcutils/sockets_unix.cpp b/libcutils/sockets_unix.cpp
index 8747d69..e91f358 100644
--- a/libcutils/sockets_unix.cpp
+++ b/libcutils/sockets_unix.cpp
@@ -14,12 +14,27 @@
  * limitations under the License.
  */
 
-#include <cutils/sockets.h>
+#define LOG_TAG "socket-unix"
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
 #include <sys/uio.h>
+#include <sys/un.h>
+#include <time.h>
+#include <unistd.h>
 
+#include <cutils/android_get_control_file.h>
+#include <cutils/sockets.h>
 #include <log/log.h>
 
+#include "android_get_control_env.h"
+
+#ifndef TEMP_FAILURE_RETRY
+#define TEMP_FAILURE_RETRY(exp) (exp) // KISS implementation
+#endif
+
 #if defined(__ANDROID__)
 /* For the socket trust (credentials) check */
 #include <private/android_filesystem_config.h>
@@ -77,3 +92,24 @@
 
     return writev(sock, iovec_buffers, num_buffers);
 }
+
+int android_get_control_socket(const char* name) {
+    int fd = __android_get_control_from_env(ANDROID_SOCKET_ENV_PREFIX, name);
+
+    if (fd < 0) return fd;
+
+    // Compare to UNIX domain socket name, must match!
+    struct sockaddr_un addr;
+    socklen_t addrlen = sizeof(addr);
+    int ret = TEMP_FAILURE_RETRY(getsockname(fd, (struct sockaddr *)&addr, &addrlen));
+    if (ret < 0) return -1;
+    char *path = NULL;
+    if (asprintf(&path, ANDROID_SOCKET_DIR "/%s", name) < 0) return -1;
+    if (!path) return -1;
+    int cmp = strcmp(addr.sun_path, path);
+    free(path);
+    if (cmp != 0) return -1;
+
+    // It is what we think it is
+    return fd;
+}
diff --git a/libcutils/sockets_windows.cpp b/libcutils/sockets_windows.cpp
index ed6b1a7..3064c70 100644
--- a/libcutils/sockets_windows.cpp
+++ b/libcutils/sockets_windows.cpp
@@ -84,3 +84,7 @@
 
     return -1;
 }
+
+int android_get_control_socket(const char* name) {
+    return -1;
+}
diff --git a/libcutils/strdup8to16.c b/libcutils/strdup8to16.c
index 63e5ca4..c23cf8b 100644
--- a/libcutils/strdup8to16.c
+++ b/libcutils/strdup8to16.c
@@ -27,7 +27,7 @@
 #define UTF16_REPLACEMENT_CHAR 0xfffd
 
 /* Clever trick from Dianne that returns 1-4 depending on leading bit sequence*/
-#define UTF8_SEQ_LENGTH(ch) (((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1)
+#define UTF8_SEQ_LENGTH(ch) (((0xe5000000 >> (((ch) >> 3) & 0x1e)) & 3) + 1)
 
 /* note: macro expands to multiple lines */
 #define UTF8_SHIFT_AND_MASK(unicode, byte)  \
diff --git a/libcutils/tests/Android.bp b/libcutils/tests/Android.bp
new file mode 100644
index 0000000..718d76b
--- /dev/null
+++ b/libcutils/tests/Android.bp
@@ -0,0 +1,86 @@
+// 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.
+
+cc_defaults {
+    name: "libcutils_test_default",
+    srcs: ["sockets_test.cpp"],
+
+    target: {
+        android: {
+            srcs: [
+                "AshmemTest.cpp",
+                "MemsetTest.cpp",
+                "PropertiesTest.cpp",
+                "sched_policy_test.cpp",
+                "trace-dev_test.cpp",
+                "test_str_parms.cpp",
+                "android_get_control_socket_test.cpp",
+                "android_get_control_file_test.cpp",
+                "multiuser_test.cpp"
+            ],
+        },
+
+        not_windows: {
+            srcs: [
+                "test_str_parms.cpp",
+            ],
+        },
+    },
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+}
+
+test_libraries = [
+    "libcutils",
+    "liblog",
+    "libbase",
+]
+
+cc_test {
+    name: "libcutils_test",
+    defaults: ["libcutils_test_default"],
+    host_supported: true,
+    shared_libs: test_libraries,
+}
+
+cc_test {
+    name: "libcutils_test_static",
+    defaults: ["libcutils_test_default"],
+    static_libs: ["libc"] + test_libraries,
+    stl: "libc++_static",
+
+    target: {
+        android: {
+            static_executable: true,
+        },
+        windows: {
+            host_ldlibs: ["-lws2_32"],
+
+            enabled: true,
+        },
+    },
+}
diff --git a/libcutils/tests/Android.mk b/libcutils/tests/Android.mk
deleted file mode 100644
index 52cf5f4..0000000
--- a/libcutils/tests/Android.mk
+++ /dev/null
@@ -1,81 +0,0 @@
-# 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.
-
-LOCAL_PATH := $(call my-dir)
-
-test_src_files := \
-    sockets_test.cpp \
-
-test_src_files_nonwindows := \
-    test_str_parms.cpp \
-
-test_target_only_src_files := \
-    MemsetTest.cpp \
-    PropertiesTest.cpp \
-    trace-dev_test.cpp \
-
-test_libraries := libcutils liblog libbase
-
-
-#
-# Target.
-#
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test
-LOCAL_SRC_FILES := $(test_src_files) $(test_target_only_src_files)
-LOCAL_SHARED_LIBRARIES := $(test_libraries)
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test_static
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_SRC_FILES := $(test_src_files) $(test_target_only_src_files)
-LOCAL_STATIC_LIBRARIES := libc $(test_libraries)
-LOCAL_CXX_STL := libc++_static
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
-
-
-#
-# Host.
-#
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test
-LOCAL_SRC_FILES := $(test_src_files) $(test_src_files_nonwindows)
-LOCAL_SHARED_LIBRARIES := $(test_libraries)
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_HOST_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test_static
-LOCAL_SRC_FILES := $(test_src_files)
-LOCAL_SRC_FILES_darwin := $(test_src_files_nonwindows)
-LOCAL_SRC_FILES_linux := $(test_src_files_nonwindows)
-LOCAL_STATIC_LIBRARIES := $(test_libraries)
-LOCAL_LDLIBS_windows := -lws2_32
-LOCAL_CXX_STL := libc++_static
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libcutils/tests/AshmemTest.cpp b/libcutils/tests/AshmemTest.cpp
new file mode 100644
index 0000000..51c679f
--- /dev/null
+++ b/libcutils/tests/AshmemTest.cpp
@@ -0,0 +1,177 @@
+/*
+ * 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 <cutils/ashmem.h>
+#include <gtest/gtest.h>
+#include <android-base/unique_fd.h>
+
+using android::base::unique_fd;
+
+void TestCreateRegion(size_t size, unique_fd &fd, int prot) {
+    fd = unique_fd(ashmem_create_region(nullptr, size));
+    ASSERT_TRUE(fd >= 0);
+    ASSERT_TRUE(ashmem_valid(fd));
+    ASSERT_EQ(size, static_cast<size_t>(ashmem_get_size_region(fd)));
+    ASSERT_EQ(0, ashmem_set_prot_region(fd, prot));
+}
+
+void TestMmap(const unique_fd &fd, size_t size, int prot, void **region) {
+    *region = mmap(nullptr, size, prot, MAP_SHARED, fd, 0);
+    ASSERT_NE(MAP_FAILED, *region);
+}
+
+void TestProtDenied(const unique_fd &fd, size_t size, int prot) {
+    EXPECT_EQ(MAP_FAILED, mmap(nullptr, size, prot, MAP_SHARED, fd, 0));
+}
+
+void FillData(uint8_t* data, size_t dataLen) {
+    for (size_t i = 0; i < dataLen; i++) {
+        data[i] = i & 0xFF;
+    }
+}
+
+TEST(AshmemTest, BasicTest) {
+    constexpr size_t size = PAGE_SIZE;
+    uint8_t data[size];
+    FillData(data, size);
+
+    unique_fd fd;
+    ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_READ | PROT_WRITE));
+
+    void *region1;
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ | PROT_WRITE, &region1));
+
+    memcpy(region1, &data, size);
+    ASSERT_EQ(0, memcmp(region1, &data, size));
+
+    EXPECT_EQ(0, munmap(region1, size));
+
+    void *region2;
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ, &region2));
+    ASSERT_EQ(0, memcmp(region2, &data, size));
+    EXPECT_EQ(0, munmap(region2, size));
+}
+
+TEST(AshmemTest, ForkTest) {
+    constexpr size_t size = PAGE_SIZE;
+    uint8_t data[size];
+    FillData(data, size);
+
+    unique_fd fd;
+    ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_READ | PROT_WRITE));
+
+    void *region1;
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ | PROT_WRITE, &region1));
+
+    memcpy(region1, &data, size);
+    ASSERT_EQ(0, memcmp(region1, &data, size));
+    EXPECT_EQ(0, munmap(region1, size));
+
+    ASSERT_EXIT({
+        void *region2 = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+        if (region2 == MAP_FAILED) {
+            _exit(1);
+        }
+        if (memcmp(region2, &data, size) != 0) {
+            _exit(2);
+        }
+        memset(region2, 0, size);
+        munmap(region2, size);
+        _exit(0);
+    }, ::testing::ExitedWithCode(0),"");
+
+    memset(&data, 0, size);
+    void *region2;
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ | PROT_WRITE, &region2));
+    ASSERT_EQ(0, memcmp(region2, &data, size));
+    EXPECT_EQ(0, munmap(region2, size));
+}
+
+TEST(AshmemTest, ProtTest) {
+    unique_fd fd;
+    constexpr size_t size = PAGE_SIZE;
+    void *region;
+
+    ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_READ));
+    TestProtDenied(fd, size, PROT_WRITE);
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_READ, &region));
+    EXPECT_EQ(0, munmap(region, size));
+
+    ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_WRITE));
+    TestProtDenied(fd, size, PROT_READ);
+    ASSERT_NO_FATAL_FAILURE(TestMmap(fd, size, PROT_WRITE, &region));
+    EXPECT_EQ(0, munmap(region, size));
+}
+
+TEST(AshmemTest, ForkProtTest) {
+    unique_fd fd;
+    constexpr size_t size = PAGE_SIZE;
+
+    int protFlags[] = { PROT_READ, PROT_WRITE };
+    for (int i = 0; i < 2; i++) {
+        ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd, PROT_READ | PROT_WRITE));
+        ASSERT_EXIT({
+            if (ashmem_set_prot_region(fd, protFlags[i]) >= 0) {
+                _exit(0);
+            } else {
+                _exit(1);
+            }
+        }, ::testing::ExitedWithCode(0), "");
+        ASSERT_NO_FATAL_FAILURE(TestProtDenied(fd, size, protFlags[1-i]));
+    }
+}
+
+TEST(AshmemTest, ForkMultiRegionTest) {
+    constexpr size_t size = PAGE_SIZE;
+    uint8_t data[size];
+    FillData(data, size);
+
+    constexpr int nRegions = 16;
+    unique_fd fd[nRegions];
+    for (int i = 0; i < nRegions; i++) {
+        ASSERT_NO_FATAL_FAILURE(TestCreateRegion(size, fd[i], PROT_READ | PROT_WRITE));
+        void *region;
+        ASSERT_NO_FATAL_FAILURE(TestMmap(fd[i], size, PROT_READ | PROT_WRITE, &region));
+        memcpy(region, &data, size);
+        ASSERT_EQ(0, memcmp(region, &data, size));
+        EXPECT_EQ(0, munmap(region, size));
+    }
+
+    ASSERT_EXIT({
+        for (int i = 0; i < nRegions; i++) {
+            void *region = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd[i], 0);
+            if (region == MAP_FAILED) {
+                _exit(1);
+            }
+            if (memcmp(region, &data, size) != 0) {
+                munmap(region, size);
+                _exit(2);
+            }
+            memset(region, 0, size);
+            munmap(region, size);
+        }
+        _exit(0);
+    }, ::testing::ExitedWithCode(0), "");
+
+    memset(&data, 0, size);
+    for (int i = 0; i < nRegions; i++) {
+        void *region;
+        ASSERT_NO_FATAL_FAILURE(TestMmap(fd[i], size, PROT_READ | PROT_WRITE, &region));
+        ASSERT_EQ(0, memcmp(region, &data, size));
+        EXPECT_EQ(0, munmap(region, size));
+    }
+}
diff --git a/libcutils/tests/PropertiesTest.cpp b/libcutils/tests/PropertiesTest.cpp
index 659821c..7921972 100644
--- a/libcutils/tests/PropertiesTest.cpp
+++ b/libcutils/tests/PropertiesTest.cpp
@@ -15,20 +15,22 @@
  */
 
 #define LOG_TAG "Properties_test"
-#include <utils/Log.h>
-#include <gtest/gtest.h>
 
-#include <cutils/properties.h>
 #include <limits.h>
-#include <string>
-#include <sstream>
+
 #include <iostream>
+#include <sstream>
+#include <string>
+
+#include <android/log.h>
+#include <android-base/macros.h>
+#include <cutils/properties.h>
+#include <gtest/gtest.h>
 
 namespace android {
 
 #define STRINGIFY_INNER(x) #x
 #define STRINGIFY(x) STRINGIFY_INNER(x)
-#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
 #define ASSERT_OK(x) ASSERT_EQ(0, (x))
 #define EXPECT_OK(x) EXPECT_EQ(0, (x))
 
@@ -85,7 +87,7 @@
     }
 
     void ResetValue(unsigned char c = 0xFF) {
-        for (size_t i = 0; i < ARRAY_SIZE(mValue); ++i) {
+        for (size_t i = 0; i < arraysize(mValue); ++i) {
             mValue[i] = (char) c;
         }
     }
@@ -106,14 +108,14 @@
         ResetValue();
 
         // Since the value is null, default value will be returned
-        int len = property_get(PROPERTY_TEST_KEY, mValue, PROPERTY_TEST_VALUE_DEFAULT);
+        size_t len = property_get(PROPERTY_TEST_KEY, mValue, PROPERTY_TEST_VALUE_DEFAULT);
         EXPECT_EQ(strlen(PROPERTY_TEST_VALUE_DEFAULT), len);
         EXPECT_STREQ(PROPERTY_TEST_VALUE_DEFAULT, mValue);
     }
 
     // Trivial case => get returns what was set
     {
-        int len = SetAndGetProperty("hello_world");
+        size_t len = SetAndGetProperty("hello_world");
         EXPECT_EQ(strlen("hello_world"), len) << "hello_world key";
         EXPECT_STREQ("hello_world", mValue);
         ResetValue();
@@ -122,7 +124,7 @@
     // Set to empty string => get returns default always
     {
         const char* EMPTY_STRING_DEFAULT = "EMPTY_STRING";
-        int len = SetAndGetProperty("", EMPTY_STRING_DEFAULT);
+        size_t len = SetAndGetProperty("", EMPTY_STRING_DEFAULT);
         EXPECT_EQ(strlen(EMPTY_STRING_DEFAULT), len) << "empty key";
         EXPECT_STREQ(EMPTY_STRING_DEFAULT, mValue);
         ResetValue();
@@ -147,7 +149,7 @@
 
         // Expect that the value set fails since it's too long
         EXPECT_GT(0, property_set(PROPERTY_TEST_KEY, oneLongerString.c_str()));
-        int len = property_get(PROPERTY_TEST_KEY, mValue, PROPERTY_TEST_VALUE_DEFAULT);
+        size_t len = property_get(PROPERTY_TEST_KEY, mValue, PROPERTY_TEST_VALUE_DEFAULT);
 
         EXPECT_EQ(strlen(VALID_TEST_VALUE), len) << "set should've failed";
         EXPECT_STREQ(VALID_TEST_VALUE, mValue);
@@ -157,19 +159,68 @@
 
 TEST_F(PropertiesTest, GetString) {
 
-    // Try to use a default value that's too long => set fails
+    // Try to use a default value that's too long => get truncates the value
     {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, ""));
 
-        std::string maxLengthString = std::string(PROPERTY_VALUE_MAX-1, 'a');
+        std::string maxLengthString = std::string(PROPERTY_VALUE_MAX - 1, 'a');
         std::string oneLongerString = std::string(PROPERTY_VALUE_MAX, 'a');
 
         // Expect that the value is truncated since it's too long (by 1)
         int len = property_get(PROPERTY_TEST_KEY, mValue, oneLongerString.c_str());
-        EXPECT_EQ(PROPERTY_VALUE_MAX-1, len);
+        EXPECT_EQ(PROPERTY_VALUE_MAX - 1, len);
         EXPECT_STREQ(maxLengthString.c_str(), mValue);
         ResetValue();
     }
+
+    // Try to use a default value that's the max length => get succeeds
+    {
+        ASSERT_OK(property_set(PROPERTY_TEST_KEY, ""));
+
+        std::string maxLengthString = std::string(PROPERTY_VALUE_MAX - 1, 'b');
+
+        // Expect that the value matches maxLengthString
+        int len = property_get(PROPERTY_TEST_KEY, mValue, maxLengthString.c_str());
+        EXPECT_EQ(PROPERTY_VALUE_MAX - 1, len);
+        EXPECT_STREQ(maxLengthString.c_str(), mValue);
+        ResetValue();
+    }
+
+    // Try to use a default value of length one => get succeeds
+    {
+        ASSERT_OK(property_set(PROPERTY_TEST_KEY, ""));
+
+        std::string oneCharString = std::string(1, 'c');
+
+        // Expect that the value matches oneCharString
+        int len = property_get(PROPERTY_TEST_KEY, mValue, oneCharString.c_str());
+        EXPECT_EQ(1, len);
+        EXPECT_STREQ(oneCharString.c_str(), mValue);
+        ResetValue();
+    }
+
+    // Try to use a default value of length zero => get succeeds
+    {
+        ASSERT_OK(property_set(PROPERTY_TEST_KEY, ""));
+
+        std::string zeroCharString = std::string(0, 'd');
+
+        // Expect that the value matches oneCharString
+        int len = property_get(PROPERTY_TEST_KEY, mValue, zeroCharString.c_str());
+        EXPECT_EQ(0, len);
+        EXPECT_STREQ(zeroCharString.c_str(), mValue);
+        ResetValue();
+    }
+
+    // Try to use a NULL default value => get returns 0
+    {
+        ASSERT_OK(property_set(PROPERTY_TEST_KEY, ""));
+
+        // Expect a return value of 0
+        int len = property_get(PROPERTY_TEST_KEY, mValue, NULL);
+        EXPECT_EQ(0, len);
+        ResetValue();
+    }
 }
 
 TEST_F(PropertiesTest, GetBool) {
@@ -177,7 +228,7 @@
      * TRUE
      */
     const char *valuesTrue[] = { "1", "true", "y", "yes", "on", };
-    for (size_t i = 0; i < ARRAY_SIZE(valuesTrue); ++i) {
+    for (size_t i = 0; i < arraysize(valuesTrue); ++i) {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, valuesTrue[i]));
         bool val = property_get_bool(PROPERTY_TEST_KEY, /*default_value*/false);
         EXPECT_TRUE(val) << "Property should've been TRUE for value: '" << valuesTrue[i] << "'";
@@ -187,7 +238,7 @@
      * FALSE
      */
     const char *valuesFalse[] = { "0", "false", "n", "no", "off", };
-    for (size_t i = 0; i < ARRAY_SIZE(valuesFalse); ++i) {
+    for (size_t i = 0; i < arraysize(valuesFalse); ++i) {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, valuesFalse[i]));
         bool val = property_get_bool(PROPERTY_TEST_KEY, /*default_value*/true);
         EXPECT_FALSE(val) << "Property shoud've been FALSE For string value: '" << valuesFalse[i] << "'";
@@ -200,7 +251,7 @@
             "+1", "  1  ", "  true", "  true  ", "  y  ", "  yes", "yes  ",
             "+0", "-0", "00", "  00  ", "  false", "false  ",
     };
-    for (size_t i = 0; i < ARRAY_SIZE(valuesNeither); ++i) {
+    for (size_t i = 0; i < arraysize(valuesNeither); ++i) {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, valuesNeither[i]));
 
         // The default value should always be used
@@ -249,9 +300,9 @@
         DEFAULT_VALUE, DEFAULT_VALUE,
     };
 
-    ASSERT_EQ(ARRAY_SIZE(setValues), ARRAY_SIZE(getValues));
+    ASSERT_EQ(arraysize(setValues), arraysize(getValues));
 
-    for (size_t i = 0; i < ARRAY_SIZE(setValues); ++i) {
+    for (size_t i = 0; i < arraysize(setValues); ++i) {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, setValues[i]));
 
         int64_t val = property_get_int64(PROPERTY_TEST_KEY, DEFAULT_VALUE);
@@ -296,9 +347,9 @@
         DEFAULT_VALUE, DEFAULT_VALUE,
     };
 
-    ASSERT_EQ(ARRAY_SIZE(setValues), ARRAY_SIZE(getValues));
+    ASSERT_EQ(arraysize(setValues), arraysize(getValues));
 
-    for (size_t i = 0; i < ARRAY_SIZE(setValues); ++i) {
+    for (size_t i = 0; i < arraysize(setValues); ++i) {
         ASSERT_OK(property_set(PROPERTY_TEST_KEY, setValues[i]));
 
         int32_t val = property_get_int32(PROPERTY_TEST_KEY, DEFAULT_VALUE);
diff --git a/libcutils/tests/android_get_control_file_test.cpp b/libcutils/tests/android_get_control_file_test.cpp
new file mode 100644
index 0000000..6c6fd2a
--- /dev/null
+++ b/libcutils/tests/android_get_control_file_test.cpp
@@ -0,0 +1,50 @@
+/*
+ * 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 <ctype.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <time.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <android-base/test_utils.h>
+#include <cutils/android_get_control_file.h>
+#include <gtest/gtest.h>
+
+TEST(FilesTest, android_get_control_file) {
+    TemporaryFile tf;
+    ASSERT_GE(tf.fd, 0);
+
+    std::string key(ANDROID_FILE_ENV_PREFIX);
+    key += tf.path;
+
+    std::for_each(key.begin(), key.end(), [] (char& c) { c = isalnum(c) ? c : '_'; });
+
+    EXPECT_EQ(unsetenv(key.c_str()), 0);
+    EXPECT_EQ(android_get_control_file(tf.path), -1);
+
+    EXPECT_EQ(setenv(key.c_str(), android::base::StringPrintf("%d", tf.fd).c_str(), true), 0);
+
+    EXPECT_EQ(android_get_control_file(tf.path), tf.fd);
+    close(tf.fd);
+    EXPECT_EQ(android_get_control_file(tf.path), -1);
+    EXPECT_EQ(unsetenv(key.c_str()), 0);
+    EXPECT_EQ(android_get_control_file(tf.path), -1);
+}
diff --git a/libcutils/tests/android_get_control_socket_test.cpp b/libcutils/tests/android_get_control_socket_test.cpp
new file mode 100644
index 0000000..e586748
--- /dev/null
+++ b/libcutils/tests/android_get_control_socket_test.cpp
@@ -0,0 +1,71 @@
+/*
+ * 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 <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <time.h>
+
+#include <cutils/sockets.h>
+#include <gtest/gtest.h>
+
+#ifndef SOCK_NONBLOCK
+#define SOCK_NONBLOCK 0
+#endif
+
+#ifndef SOCK_CLOEXEC
+#define SOCK_CLOEXEC 0
+#endif
+
+TEST(SocketsTest, android_get_control_socket) {
+    static const char key[] = ANDROID_SOCKET_ENV_PREFIX "SocketsTest_android_get_control_socket";
+    static const char* name = key + strlen(ANDROID_SOCKET_ENV_PREFIX);
+
+    EXPECT_EQ(unsetenv(key), 0);
+    EXPECT_EQ(android_get_control_socket(name), -1);
+
+    int fd;
+    ASSERT_GE(fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0), 0);
+#ifdef F_GETFL
+    int flags;
+    ASSERT_GE(flags = fcntl(fd, F_GETFL), 0);
+    ASSERT_GE(fcntl(fd, F_SETFL, flags | O_NONBLOCK), 0);
+#endif
+    EXPECT_EQ(android_get_control_socket(name), -1);
+
+    struct sockaddr_un addr;
+    memset(&addr, 0, sizeof(addr));
+    addr.sun_family = AF_UNIX;
+    snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", name);
+    unlink(addr.sun_path);
+
+    EXPECT_EQ(bind(fd, (struct sockaddr*)&addr, sizeof(addr)), 0);
+    EXPECT_EQ(android_get_control_socket(name), -1);
+
+    char val[32];
+    snprintf(val, sizeof(val), "%d", fd);
+    EXPECT_EQ(setenv(key, val, true), 0);
+
+    EXPECT_EQ(android_get_control_socket(name), fd);
+    socket_close(fd);
+    EXPECT_EQ(android_get_control_socket(name), -1);
+    EXPECT_EQ(unlink(addr.sun_path), 0);
+    EXPECT_EQ(android_get_control_socket(name), -1);
+    EXPECT_EQ(unsetenv(key), 0);
+    EXPECT_EQ(android_get_control_socket(name), -1);
+}
diff --git a/libcutils/tests/multiuser_test.cpp b/libcutils/tests/multiuser_test.cpp
new file mode 100644
index 0000000..2f9d854
--- /dev/null
+++ b/libcutils/tests/multiuser_test.cpp
@@ -0,0 +1,85 @@
+/*
+ * 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 <cutils/multiuser.h>
+#include <gtest/gtest.h>
+
+static constexpr auto ERR_GID = static_cast<gid_t>(-1);
+
+TEST(MultiuserTest, TestMerge) {
+    EXPECT_EQ(0U, multiuser_get_uid(0, 0));
+    EXPECT_EQ(1000U, multiuser_get_uid(0, 1000));
+    EXPECT_EQ(10000U, multiuser_get_uid(0, 10000));
+    EXPECT_EQ(50000U, multiuser_get_uid(0, 50000));
+    EXPECT_EQ(1000000U, multiuser_get_uid(10, 0));
+    EXPECT_EQ(1001000U, multiuser_get_uid(10, 1000));
+    EXPECT_EQ(1010000U, multiuser_get_uid(10, 10000));
+    EXPECT_EQ(1050000U, multiuser_get_uid(10, 50000));
+}
+
+TEST(MultiuserTest, TestSplitUser) {
+    EXPECT_EQ(0U, multiuser_get_user_id(0));
+    EXPECT_EQ(0U, multiuser_get_user_id(1000));
+    EXPECT_EQ(0U, multiuser_get_user_id(10000));
+    EXPECT_EQ(0U, multiuser_get_user_id(50000));
+    EXPECT_EQ(10U, multiuser_get_user_id(1000000));
+    EXPECT_EQ(10U, multiuser_get_user_id(1001000));
+    EXPECT_EQ(10U, multiuser_get_user_id(1010000));
+    EXPECT_EQ(10U, multiuser_get_user_id(1050000));
+}
+
+TEST(MultiuserTest, TestSplitApp) {
+    EXPECT_EQ(0U, multiuser_get_app_id(0));
+    EXPECT_EQ(1000U, multiuser_get_app_id(1000));
+    EXPECT_EQ(10000U, multiuser_get_app_id(10000));
+    EXPECT_EQ(50000U, multiuser_get_app_id(50000));
+    EXPECT_EQ(0U, multiuser_get_app_id(1000000));
+    EXPECT_EQ(1000U, multiuser_get_app_id(1001000));
+    EXPECT_EQ(10000U, multiuser_get_app_id(1010000));
+    EXPECT_EQ(50000U, multiuser_get_app_id(1050000));
+}
+
+TEST(MultiuserTest, TestCache) {
+    EXPECT_EQ(ERR_GID, multiuser_get_cache_gid(0, 0));
+    EXPECT_EQ(ERR_GID, multiuser_get_cache_gid(0, 1000));
+    EXPECT_EQ(20000U, multiuser_get_cache_gid(0, 10000));
+    EXPECT_EQ(ERR_GID, multiuser_get_cache_gid(0, 50000));
+    EXPECT_EQ(1020000U, multiuser_get_cache_gid(10, 10000));
+}
+
+TEST(MultiuserTest, TestExt) {
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_gid(0, 0));
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_gid(0, 1000));
+    EXPECT_EQ(30000U, multiuser_get_ext_gid(0, 10000));
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_gid(0, 50000));
+    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));
+    EXPECT_EQ(50000U, multiuser_get_shared_gid(0, 10000));
+    EXPECT_EQ(ERR_GID, multiuser_get_shared_gid(0, 50000));
+    EXPECT_EQ(1050000U, multiuser_get_shared_gid(10, 10000));
+}
diff --git a/libcutils/tests/sched_policy_test.cpp b/libcutils/tests/sched_policy_test.cpp
new file mode 100644
index 0000000..173174a
--- /dev/null
+++ b/libcutils/tests/sched_policy_test.cpp
@@ -0,0 +1,98 @@
+/*
+ * 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 <algorithm>
+#include <chrono>
+#include <thread>
+#include <vector>
+
+#include <sys/capability.h>
+
+#include <cutils/sched_policy.h>
+
+#include <gtest/gtest.h>
+
+bool hasCapSysNice() {
+    __user_cap_header_struct header;
+    memset(&header, 0, sizeof(header));
+    header.version = _LINUX_CAPABILITY_VERSION_3;
+
+    __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3];
+    if (capget(&header, &caps[0])) {
+        GTEST_LOG_(WARNING) << "failed to get process capabilities";
+        return false;
+    }
+
+    auto nice_idx = CAP_TO_INDEX(CAP_SYS_NICE);
+    auto nice_mask = CAP_TO_MASK(CAP_SYS_NICE);
+    return caps[nice_idx].effective & nice_mask;
+}
+
+long long medianSleepTime() {
+    std::vector<long long> sleepTimes;
+    constexpr size_t numSamples = 100;
+
+    for (size_t i = 0; i < numSamples; i++) {
+        auto start = std::chrono::steady_clock::now();
+        std::this_thread::sleep_for(std::chrono::nanoseconds(1));
+        auto end = std::chrono::steady_clock::now();
+
+        auto diff = end - start;
+        sleepTimes.push_back(diff.count());
+    }
+
+    constexpr auto median = numSamples / 2;
+    std::nth_element(sleepTimes.begin(), sleepTimes.begin() + median,
+            sleepTimes.end());
+    return sleepTimes[median];
+}
+
+TEST(SchedPolicy, set_sched_policy) {
+    if (!hasCapSysNice()) {
+        GTEST_LOG_(INFO) << "skipping test that requires CAP_SYS_NICE";
+        return;
+    }
+
+    // A measureable effect of scheduling policy is that the kernel has 800x
+    // greater slack time in waking up a sleeping background thread.
+    //
+    // Look for 100x difference in how long FB and BG threads actually sleep
+    // when trying to sleep for 1 ns.  This difference is large enough not
+    // to happen by chance, but small enough (compared to 800x) to keep inherent
+    // fuzziness in scheduler behavior from causing false negatives.
+    const unsigned int BG_FG_SLACK_FACTOR = 100;
+
+    ASSERT_EQ(0, set_sched_policy(0, SP_BACKGROUND));
+    auto bgSleepTime = medianSleepTime();
+
+    ASSERT_EQ(0, set_sched_policy(0, SP_FOREGROUND));
+    auto fgSleepTime = medianSleepTime();
+    ASSERT_GT(bgSleepTime, fgSleepTime * BG_FG_SLACK_FACTOR);
+}
+
+TEST(SchedPolicy, get_sched_policy) {
+    SchedPolicy policy;
+    ASSERT_EQ(0, get_sched_policy(0, &policy));
+
+    const char *policyName = get_sched_policy_name(policy);
+    EXPECT_NE(nullptr, policyName);
+    EXPECT_STRNE("error", policyName);
+
+    ASSERT_EQ(0, set_sched_policy(0, SP_BACKGROUND));
+    SchedPolicy newPolicy;
+    ASSERT_EQ(0, get_sched_policy(0, &newPolicy));
+    EXPECT_EQ(SP_BACKGROUND, newPolicy);
+}
diff --git a/libcutils/tests/sockets_test.cpp b/libcutils/tests/sockets_test.cpp
index 0f682a2..b762ac1 100644
--- a/libcutils/tests/sockets_test.cpp
+++ b/libcutils/tests/sockets_test.cpp
@@ -18,10 +18,12 @@
 // IPv6 capabilities. These tests assume that no UDP packets are lost, which
 // should be the case for loopback communication, but is not guaranteed.
 
-#include <cutils/sockets.h>
-
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
 #include <time.h>
 
+#include <cutils/sockets.h>
 #include <gtest/gtest.h>
 
 // Makes sure the passed sockets are valid, sends data between them, and closes
@@ -99,7 +101,7 @@
     // should always be able to read its port.
     for (int port : {10000, 12345, 15999, 20202, 25000}) {
         for (int type : {SOCK_DGRAM, SOCK_STREAM}) {
-            server = socket_inaddr_any_server(port, SOCK_DGRAM);
+            server = socket_inaddr_any_server(port, type);
             if (server != INVALID_SOCKET) {
                 EXPECT_EQ(port, socket_get_local_port(server));
             }
diff --git a/libcutils/trace-dev.c b/libcutils/trace-dev.c
index 778e4f0..d45e5a9 100644
--- a/libcutils/trace-dev.c
+++ b/libcutils/trace-dev.c
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "cutils-trace"
+
 #include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
@@ -23,12 +25,12 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
+
 #include <cutils/compiler.h>
 #include <cutils/properties.h>
 #include <cutils/trace.h>
-
-#define LOG_TAG "cutils-trace"
 #include <log/log.h>
+#include <log/log_properties.h>
 
 /**
  * Maximum size of a message that can be logged to the trace buffer.
@@ -85,16 +87,9 @@
 // Determine whether application-level tracing is enabled for this process.
 static bool atrace_is_app_tracing_enabled()
 {
-    bool sys_debuggable = false;
-    char value[PROPERTY_VALUE_MAX];
+    bool sys_debuggable = __android_log_is_debuggable();
     bool result = false;
 
-    // Check whether the system is debuggable.
-    property_get("ro.debuggable", value, "0");
-    if (value[0] == '1') {
-        sys_debuggable = true;
-    }
-
     if (sys_debuggable || atrace_is_debuggable) {
         // Check whether tracing is enabled for this process.
         FILE * file = fopen("/proc/self/cmdline", "re");
@@ -196,6 +191,12 @@
     write(atrace_marker_fd, buf, len);
 }
 
+void atrace_end_body()
+{
+    char c = 'E';
+    write(atrace_marker_fd, &c, 1);
+}
+
 #define WRITE_MSG(format_begin, format_end, pid, name, value) { \
     char buf[ATRACE_MESSAGE_LENGTH]; \
     int len = snprintf(buf, sizeof(buf), format_begin "%s" format_end, pid, \
diff --git a/libcutils/trace-host.c b/libcutils/trace-host.c
index 6478e3e..05842cd 100644
--- a/libcutils/trace-host.c
+++ b/libcutils/trace-host.c
@@ -29,6 +29,7 @@
 void atrace_update_tags() { }
 void atrace_setup() { }
 void atrace_begin_body(const char* name __unused) { }
+void atrace_end_body() { }
 void atrace_async_begin_body(const char* name __unused, int32_t cookie __unused) { }
 void atrace_async_end_body(const char* name __unused, int32_t cookie __unused) { }
 void atrace_int_body(const char* name __unused, int32_t value __unused) { }
diff --git a/libcutils/uevent.c b/libcutils/uevent.c
index de5d227..f548dca 100644
--- a/libcutils/uevent.c
+++ b/libcutils/uevent.c
@@ -116,7 +116,12 @@
     if(s < 0)
         return -1;
 
-    setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, &buf_sz, sizeof(buf_sz));
+    /* buf_sz should be less than net.core.rmem_max for this to succeed */
+    if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &buf_sz, sizeof(buf_sz)) < 0) {
+        close(s);
+        return -1;
+    }
+
     setsockopt(s, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
 
     if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
diff --git a/libdiskconfig/Android.bp b/libdiskconfig/Android.bp
new file mode 100644
index 0000000..088981a
--- /dev/null
+++ b/libdiskconfig/Android.bp
@@ -0,0 +1,33 @@
+cc_library {
+    name: "libdiskconfig",
+    vendor_available: true,
+    srcs: [
+        "diskconfig.c",
+        "diskutils.c",
+        "write_lst.c",
+        "config_mbr.c",
+    ],
+
+    shared_libs: [
+        "libcutils",
+        "liblog",
+    ],
+    cflags: ["-Werror"],
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+        linux: {
+            cflags: [
+                "-O2",
+                "-g",
+                "-W",
+                "-Wall",
+                "-D_LARGEFILE64_SOURCE",
+            ],
+        },
+    },
+}
diff --git a/libdiskconfig/Android.mk b/libdiskconfig/Android.mk
deleted file mode 100644
index 624e385..0000000
--- a/libdiskconfig/Android.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-commonSources := \
-	diskconfig.c \
-	diskutils.c \
-	write_lst.c \
-	config_mbr.c
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(commonSources)
-LOCAL_MODULE := libdiskconfig
-LOCAL_MODULE_TAGS := optional
-LOCAL_SYSTEM_SHARED_LIBRARIES := libcutils liblog libc
-LOCAL_CFLAGS := -Werror
-include $(BUILD_SHARED_LIBRARY)
-
-ifeq ($(HOST_OS),linux)
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(commonSources)
-LOCAL_MODULE := libdiskconfig_host
-LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS := -O2 -g -W -Wall -Werror -D_LARGEFILE64_SOURCE
-include $(BUILD_HOST_STATIC_LIBRARY)
-endif # HOST_OS == linux
diff --git a/libdiskconfig/config_mbr.c b/libdiskconfig/config_mbr.c
index 7b6ca1c..ace9bbf 100644
--- a/libdiskconfig/config_mbr.c
+++ b/libdiskconfig/config_mbr.c
@@ -16,15 +16,14 @@
  */
 
 #define LOG_TAG "config_mbr"
+
 #include <stdint.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdio.h>
-
-#include <cutils/log.h>
 
 #include <diskconfig/diskconfig.h>
-
+#include <log/log.h>
 
 /* start and len are in LBA units */
 static void
diff --git a/libdiskconfig/diskconfig.c b/libdiskconfig/diskconfig.c
index 1167d4b..c7e1b43 100644
--- a/libdiskconfig/diskconfig.c
+++ b/libdiskconfig/diskconfig.c
@@ -20,21 +20,19 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <linux/fs.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
 #include <sys/ioctl.h>
 #include <sys/stat.h>
-
-#include <linux/fs.h>
+#include <unistd.h>
 
 #include <cutils/config_utils.h>
 #include <log/log.h>
 
 #include <diskconfig/diskconfig.h>
 
-
 static int
 parse_len(const char *str, uint64_t *plen)
 {
diff --git a/libdiskconfig/diskutils.c b/libdiskconfig/diskutils.c
index 5d0ee62..fe1b4c1 100644
--- a/libdiskconfig/diskutils.c
+++ b/libdiskconfig/diskutils.c
@@ -23,8 +23,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
 #include <sys/stat.h>
+#include <unistd.h>
 
 #include <log/log.h>
 
diff --git a/libdiskconfig/dump_diskconfig.c b/libdiskconfig/dump_diskconfig.c
index 75256f6..3c4f620 100644
--- a/libdiskconfig/dump_diskconfig.c
+++ b/libdiskconfig/dump_diskconfig.c
@@ -16,9 +16,10 @@
  */
 
 #define LOG_TAG "dump_diskconfig"
+
 #include <stdio.h>
 
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include "diskconfig.h"
 
diff --git a/include/diskconfig/diskconfig.h b/libdiskconfig/include/diskconfig/diskconfig.h
similarity index 100%
rename from include/diskconfig/diskconfig.h
rename to libdiskconfig/include/diskconfig/diskconfig.h
diff --git a/libdiskconfig/write_lst.c b/libdiskconfig/write_lst.c
index 90b1c82..c3d5c0a 100644
--- a/libdiskconfig/write_lst.c
+++ b/libdiskconfig/write_lst.c
@@ -16,15 +16,15 @@
  */
 
 #define LOG_TAG "write_lst"
-#include <sys/types.h>
+
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <sys/types.h>
 #include <unistd.h>
 
-#include <cutils/log.h>
-
 #include <diskconfig/diskconfig.h>
+#include <log/log.h>
 
 struct write_list *
 alloc_wl(uint32_t data_len)
diff --git a/libgrallocusage/Android.bp b/libgrallocusage/Android.bp
new file mode 100644
index 0000000..54bfee5
--- /dev/null
+++ b/libgrallocusage/Android.bp
@@ -0,0 +1,29 @@
+// 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.
+
+cc_library_static {
+    name: "libgrallocusage",
+    cppflags: [
+        "-Weverything",
+        "-Werror",
+        "-Wno-c++98-compat-pedantic",
+        // Hide errors in headers we include
+        "-Wno-global-constructors",
+        "-Wno-exit-time-destructors",
+        "-Wno-padded",
+    ],
+    srcs: ["GrallocUsageConversion.cpp"],
+    export_include_dirs: ["include"],
+    shared_libs: ["android.hardware.graphics.allocator@2.0"],
+}
diff --git a/libgrallocusage/GrallocUsageConversion.cpp b/libgrallocusage/GrallocUsageConversion.cpp
new file mode 100644
index 0000000..05c8ec4
--- /dev/null
+++ b/libgrallocusage/GrallocUsageConversion.cpp
@@ -0,0 +1,67 @@
+/*
+ * 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 <grallocusage/GrallocUsageConversion.h>
+
+#include <hardware/gralloc.h>
+#include <hardware/gralloc1.h>
+
+void android_convertGralloc0To1Usage(int32_t usage, uint64_t* producerUsage,
+                                     uint64_t* consumerUsage) {
+    constexpr uint64_t PRODUCER_MASK =
+        GRALLOC1_PRODUCER_USAGE_CPU_READ |
+        /* GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN | */
+        GRALLOC1_PRODUCER_USAGE_CPU_WRITE |
+        /* GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN | */
+        GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET | GRALLOC1_PRODUCER_USAGE_PROTECTED |
+        GRALLOC1_PRODUCER_USAGE_CAMERA | GRALLOC1_PRODUCER_USAGE_VIDEO_DECODER |
+        GRALLOC1_PRODUCER_USAGE_SENSOR_DIRECT_DATA;
+    constexpr uint64_t CONSUMER_MASK =
+        GRALLOC1_CONSUMER_USAGE_CPU_READ |
+        /* GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN | */
+        GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE | GRALLOC1_CONSUMER_USAGE_HWCOMPOSER |
+        GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET | GRALLOC1_CONSUMER_USAGE_CURSOR |
+        GRALLOC1_CONSUMER_USAGE_VIDEO_ENCODER | GRALLOC1_CONSUMER_USAGE_CAMERA |
+        GRALLOC1_CONSUMER_USAGE_RENDERSCRIPT | GRALLOC1_CONSUMER_USAGE_GPU_DATA_BUFFER;
+    *producerUsage = static_cast<uint64_t>(usage) & PRODUCER_MASK;
+    *consumerUsage = static_cast<uint64_t>(usage) & CONSUMER_MASK;
+    if ((static_cast<uint32_t>(usage) & GRALLOC_USAGE_SW_READ_OFTEN) == GRALLOC_USAGE_SW_READ_OFTEN) {
+        *producerUsage |= GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN;
+        *consumerUsage |= GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN;
+    }
+    if ((static_cast<uint32_t>(usage) & GRALLOC_USAGE_SW_WRITE_OFTEN) ==
+        GRALLOC_USAGE_SW_WRITE_OFTEN) {
+        *producerUsage |= GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN;
+    }
+}
+
+int32_t android_convertGralloc1To0Usage(uint64_t producerUsage, uint64_t consumerUsage) {
+    static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
+                      uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
+                  "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN bits to match");
+    uint64_t merged = producerUsage | consumerUsage;
+    if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
+        GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
+        merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
+        merged |= GRALLOC_USAGE_SW_READ_OFTEN;
+    }
+    if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
+        GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
+        merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
+        merged |= GRALLOC_USAGE_SW_WRITE_OFTEN;
+    }
+    return static_cast<int32_t>(merged);
+}
diff --git a/libgrallocusage/MODULE_LICENSE_APACHE2 b/libgrallocusage/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/libgrallocusage/MODULE_LICENSE_APACHE2
diff --git a/libgrallocusage/NOTICE b/libgrallocusage/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/libgrallocusage/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2005-2008, 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.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/libgrallocusage/include/grallocusage/GrallocUsageConversion.h b/libgrallocusage/include/grallocusage/GrallocUsageConversion.h
new file mode 100644
index 0000000..5c94343
--- /dev/null
+++ b/libgrallocusage/include/grallocusage/GrallocUsageConversion.h
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_GRALLOCUSAGE_GRALLOC_USAGE_CONVERSION_H
+#define ANDROID_GRALLOCUSAGE_GRALLOC_USAGE_CONVERSION_H 1
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Conversion functions are out-of-line so that users don't have to be exposed to
+// android/hardware/graphics/allocator/2.0/types.h and link against
+// android.hardware.graphics.allocator@2.0 to get that in their search path.
+
+// Convert a 32-bit gralloc0 usage mask to a producer/consumer pair of 64-bit usage masks as used
+// by android.hardware.graphics.allocator@2.0 (and gralloc1). This conversion properly handles the
+// mismatch between a.h.g.allocator@2.0's CPU_{READ,WRITE}_OFTEN and gralloc0's
+// SW_{READ,WRITE}_OFTEN.
+void android_convertGralloc0To1Usage(int32_t usage, uint64_t* producerUsage,
+                                     uint64_t* consumerUsage);
+
+// Convert a producer/consumer pair of 64-bit usage masks as used by
+// android.hardware.graphics.allocator@2.0 (and gralloc1) to a 32-bit gralloc0 usage mask. This
+// conversion properly handles the mismatch between a.h.g.allocator@2.0's CPU_{READ,WRITE}_OFTEN
+// and gralloc0's SW_{READ,WRITE}_OFTEN.
+int32_t android_convertGralloc1To0Usage(uint64_t producerUsage, uint64_t consumerUsage);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // ANDROID_GRALLOCUSAGE_GRALLOC_USAGE_CONVERSION_H
diff --git a/libion/Android.bp b/libion/Android.bp
new file mode 100644
index 0000000..6f267e4
--- /dev/null
+++ b/libion/Android.bp
@@ -0,0 +1,26 @@
+
+cc_library {
+    name: "libion",
+		vendor_available: true,
+    srcs: ["ion.c"],
+    shared_libs: ["liblog"],
+    local_include_dirs: [
+        "include",
+        "kernel-headers",
+    ],
+    export_include_dirs: [
+        "include",
+        "kernel-headers",
+    ],
+    cflags: ["-Werror"],
+}
+
+cc_binary {
+    name: "iontest",
+    srcs: ["ion_test.c"],
+    static_libs: ["libion"],
+    shared_libs: ["liblog"],
+    cflags: ["-Werror"],
+}
+
+subdirs = ["tests"]
diff --git a/libion/Android.mk b/libion/Android.mk
deleted file mode 100644
index 6562cd3..0000000
--- a/libion/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := ion.c
-LOCAL_MODULE := libion
-LOCAL_MODULE_TAGS := optional
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
-LOCAL_CFLAGS := -Werror
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := ion.c ion_test.c
-LOCAL_MODULE := iontest
-LOCAL_MODULE_TAGS := optional tests
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror
-include $(BUILD_EXECUTABLE)
-
-include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/libion/ion.c b/libion/ion.c
index d1984bd..9aaa6f2 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -19,21 +19,22 @@
  */
 #define LOG_TAG "ion"
 
-#include <cutils/log.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <linux/ion.h>
 #include <stdio.h>
 #include <string.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/types.h>
+#include <unistd.h>
 
-#include <linux/ion.h>
 #include <ion/ion.h>
+#include <log/log.h>
 
 int ion_open()
 {
-    int fd = open("/dev/ion", O_RDWR);
+    int fd = open("/dev/ion", O_RDONLY | O_CLOEXEC);
     if (fd < 0)
         ALOGE("open /dev/ion failed!\n");
     return fd;
diff --git a/libion/kernel-headers/linux/ion.h b/libion/kernel-headers/linux/ion.h
index 5af39d0..3c28080 100644
--- a/libion/kernel-headers/linux/ion.h
+++ b/libion/kernel-headers/linux/ion.h
@@ -38,7 +38,7 @@
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define ION_HEAP_CARVEOUT_MASK (1 << ION_HEAP_TYPE_CARVEOUT)
 #define ION_HEAP_TYPE_DMA_MASK (1 << ION_HEAP_TYPE_DMA)
-#define ION_NUM_HEAP_IDS sizeof(unsigned int) * 8
+#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
 #define ION_FLAG_CACHED 1
 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 #define ION_FLAG_CACHED_NEEDS_SYNC 2
diff --git a/libion/tests/Android.bp b/libion/tests/Android.bp
new file mode 100644
index 0000000..4428848
--- /dev/null
+++ b/libion/tests/Android.bp
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2013 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_test {
+    name: "ion-unit-tests",
+    clang: true,
+    cflags: [
+        "-g",
+        "-Wall",
+        "-Werror",
+        "-Wno-missing-field-initializers",
+    ],
+    shared_libs: ["libion"],
+    srcs: [
+        "ion_test_fixture.cpp",
+        "allocate_test.cpp",
+        "formerly_valid_handle_test.cpp",
+        "invalid_values_test.cpp",
+        "map_test.cpp",
+        "device_test.cpp",
+        "exit_test.cpp",
+    ],
+}
diff --git a/libion/tests/Android.mk b/libion/tests/Android.mk
deleted file mode 100644
index 894f90e..0000000
--- a/libion/tests/Android.mk
+++ /dev/null
@@ -1,32 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := ion-unit-tests
-LOCAL_CFLAGS += -g -Wall -Werror -std=gnu++11 -Wno-missing-field-initializers
-LOCAL_SHARED_LIBRARIES += libion
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/../kernel-headers
-LOCAL_SRC_FILES := \
-	ion_test_fixture.cpp \
-	allocate_test.cpp \
-	formerly_valid_handle_test.cpp \
-	invalid_values_test.cpp \
-	map_test.cpp \
-	device_test.cpp \
-	exit_test.cpp
-include $(BUILD_NATIVE_TEST)
diff --git a/libion/tests/allocate_test.cpp b/libion/tests/allocate_test.cpp
index e26b302..3c4524e 100644
--- a/libion/tests/allocate_test.cpp
+++ b/libion/tests/allocate_test.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <memory>
 #include <sys/mman.h>
 
 #include <gtest/gtest.h>
@@ -90,7 +91,7 @@
 
 TEST_F(Allocate, Zeroed)
 {
-    void *zeroes = calloc(4096, 1);
+    auto zeroes_ptr = std::make_unique<char[]>(4096);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -125,14 +126,11 @@
         ptr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, map_fd, 0);
         ASSERT_TRUE(ptr != NULL);
 
-        ASSERT_EQ(0, memcmp(ptr, zeroes, 4096));
+        ASSERT_EQ(0, memcmp(ptr, zeroes_ptr.get(), 4096));
 
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(zeroes);
-
 }
 
 TEST_F(Allocate, Large)
diff --git a/libion/tests/device_test.cpp b/libion/tests/device_test.cpp
index 6f6e1bd..eb3f7b6 100644
--- a/libion/tests/device_test.cpp
+++ b/libion/tests/device_test.cpp
@@ -15,6 +15,7 @@
  */
 
 #include <fcntl.h>
+#include <memory>
 #include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -45,7 +46,7 @@
 void Device::SetUp()
 {
     IonAllHeapsTest::SetUp();
-    m_deviceFd = open("/dev/ion-test", O_RDWR);
+    m_deviceFd = open("/dev/ion-test", O_RDONLY);
     ASSERT_GE(m_deviceFd, 0);
 }
 
@@ -133,8 +134,8 @@
 
 TEST_F(Device, KernelReadCached)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -161,14 +162,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, KernelWriteCached)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -195,14 +194,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMAReadCached)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -227,14 +224,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMAWriteCached)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -261,14 +256,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, KernelReadCachedNeedsSync)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -295,14 +288,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, KernelWriteCachedNeedsSync)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -329,14 +320,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMAReadCachedNeedsSync)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -363,14 +352,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMAWriteCachedNeedsSync)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -399,13 +386,11 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 TEST_F(Device, KernelRead)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -432,14 +417,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, KernelWrite)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -466,14 +449,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMARead)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
@@ -498,14 +479,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, DMAWrite)
 {
-    void *alloc = malloc(8192 + 1024);
-    void *buf = (void *)(ALIGN((unsigned long)alloc, 4096) + 1024);
+    auto alloc_ptr = std::make_unique<char[]>(8192 + 1024);
+    void *buf = (void *)(ALIGN((unsigned long)alloc_ptr.get(), 4096) + 1024);
 
     for (int i = 0; i < 4096; i++)
         ((char *)buf)[i] = i;
@@ -532,13 +511,12 @@
         ASSERT_EQ(0, munmap(ptr, 4096));
         ASSERT_EQ(0, close(map_fd));
     }
-
-    free(alloc);
 }
 
 TEST_F(Device, IsCached)
 {
-    void *buf = malloc(4096);
+    auto buf_ptr = std::make_unique<char[]>(4096);
+    void *buf = buf_ptr.get();
 
     for (unsigned int heapMask : m_allHeaps) {
         SCOPED_TRACE(::testing::Message() << "heap " << heapMask);
diff --git a/liblog/.clang-format b/liblog/.clang-format
new file mode 100644
index 0000000..9db87a8
--- /dev/null
+++ b/liblog/.clang-format
@@ -0,0 +1,9 @@
+BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: false
+
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+PointerAlignment: Left
+PenaltyExcessCharacter: 32
+
+Cpp11BracedListStyle: false
diff --git a/liblog/Android.bp b/liblog/Android.bp
index 9c68fca..e74aa82 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -15,29 +15,31 @@
 //
 
 liblog_sources = [
+    "config_read.c",
+    "config_write.c",
+    "local_logger.c",
     "log_event_list.c",
     "log_event_write.c",
-    "logger_write.c",
-    "config_write.c",
-    "logger_name.c",
+    "log_ratelimit.cpp",
     "logger_lock.c",
+    "logger_name.c",
+    "logger_read.c",
+    "logger_write.c",
+    "logprint.c",
+    "stderr_write.c",
 ]
 liblog_host_sources = [
     "fake_log_device.c",
-    //"event.logtags",
     "fake_writer.c",
 ]
 liblog_target_sources = [
-    "event_tag_map.c",
-    "config_read.c",
+    "event_tag_map.cpp",
     "log_time.cpp",
-    "log_is_loggable.c",
-    "logprint.c",
+    "properties.c",
     "pmsg_reader.c",
     "pmsg_writer.c",
     "logd_reader.c",
     "logd_writer.c",
-    "logger_read.c",
 ]
 
 // Shared and static library for host and device
@@ -56,7 +58,9 @@
         android: {
             srcs: liblog_target_sources,
             // AddressSanitizer runtime library depends on liblog.
-            sanitize: ["never"],
+            sanitize: {
+                address: false,
+            },
         },
         android_arm: {
             // TODO: This is to work around b/24465209. Remove after root cause is fixed
@@ -67,13 +71,18 @@
             enabled: true,
         },
         not_windows: {
-            srcs: ["event_tag_map.c"],
+            srcs: ["event_tag_map.cpp"],
         },
         linux: {
             host_ldlibs: ["-lrt"],
         },
+        linux_bionic: {
+            enabled: true,
+        },
     },
 
+    export_include_dirs: ["include"],
+
     cflags: [
         "-Werror",
         "-fvisibility=hidden",
@@ -83,9 +92,31 @@
         //       's/^\([0-9]*\)[ \t]*liblog[ \t].*/-DLIBLOG_LOG_TAG=\1/p' \
         //       $(LOCAL_PATH)/event.logtags)
         // so make sure we do not regret hard-coding it as follows:
-        "-DLIBLOG_LOG_TAG=1005",
+        "-DLIBLOG_LOG_TAG=1006",
         "-DSNET_EVENT_LOG_TAG=1397638484",
     ],
+    logtags: ["event.logtags"],
     compile_multilib: "both",
-    stl: "none",
+}
+
+ndk_headers {
+    name: "liblog_headers",
+    from: "include/android",
+    to: "android",
+    srcs: ["include/android/log.h"],
+    license: "NOTICE",
+}
+
+ndk_library {
+    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/Android.mk b/liblog/Android.mk
index b24b489..6c4dff5 100644
--- a/liblog/Android.mk
+++ b/liblog/Android.mk
@@ -1,85 +1,3 @@
-#
-# Copyright (C) 2008-2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
 LOCAL_PATH := $(my-dir)
-include $(CLEAR_VARS)
-
-# This is what we want to do:
-#  liblog_cflags := $(shell \
-#   sed -n \
-#       's/^\([0-9]*\)[ \t]*liblog[ \t].*/-DLIBLOG_LOG_TAG=\1/p' \
-#       $(LOCAL_PATH)/event.logtags)
-# so make sure we do not regret hard-coding it as follows:
-liblog_cflags := -DLIBLOG_LOG_TAG=1005
-liblog_cflags += -DSNET_EVENT_LOG_TAG=1397638484
-
-liblog_sources := log_event_list.c log_event_write.c logger_write.c
-liblog_sources += config_write.c logger_name.c logger_lock.c
-liblog_host_sources := $(liblog_sources) fake_log_device.c event.logtags
-liblog_host_sources += fake_writer.c
-liblog_target_sources := $(liblog_sources) event_tag_map.c
-liblog_target_sources += config_read.c log_time.cpp log_is_loggable.c logprint.c
-liblog_target_sources += pmsg_reader.c pmsg_writer.c
-liblog_target_sources += logd_reader.c logd_writer.c logger_read.c
-
-# Shared and static library for host
-# ========================================================
-LOCAL_MODULE := liblog
-LOCAL_SRC_FILES := $(liblog_host_sources)
-# some files must not be compiled when building against Mingw
-# they correspond to features not used by our host development tools
-# which are also hard or even impossible to port to native Win32
-LOCAL_SRC_FILES_darwin := event_tag_map.c
-LOCAL_SRC_FILES_linux := event_tag_map.c
-LOCAL_SRC_FILES_windows := uio.c
-LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1 -Werror -fvisibility=hidden $(liblog_cflags)
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := liblog
-LOCAL_WHOLE_STATIC_LIBRARIES := liblog
-LOCAL_LDLIBS_linux := -lrt
-LOCAL_MULTILIB := both
-LOCAL_CXX_STL := none
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-
-# Shared and static library for target
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := liblog
-LOCAL_SRC_FILES := $(liblog_target_sources)
-LOCAL_CFLAGS := -Werror -fvisibility=hidden $(liblog_cflags)
-# AddressSanitizer runtime library depends on liblog.
-LOCAL_SANITIZE := never
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := liblog
-LOCAL_WHOLE_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS := -Werror -fvisibility=hidden $(liblog_cflags)
-
-# TODO: This is to work around b/24465209. Remove after root cause is fixed
-LOCAL_LDFLAGS_arm := -Wl,--hash-style=both
-
-LOCAL_SANITIZE := never
-LOCAL_CXX_STL := none
-
-include $(BUILD_SHARED_LIBRARY)
 
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/liblog/README b/liblog/README
index df1e68c..5a845be 100644
--- a/liblog/README
+++ b/liblog/README
@@ -1,11 +1,17 @@
-LIBLOG(3)               Android NDK Programming Manual               LIBLOG(3)
+LIBLOG(3)          Android Internal NDK Programming Manual           LIBLOG(3)
 
 
 
 NAME
-       liblog - Android NDK logger interfaces
+       liblog - Android Internal NDK logger interfaces
 
 SYNOPSIS
+       /*
+        * Please limit to 24 characters for runtime is loggable,
+        * 16 characters for persist is loggable, and logcat pretty
+        * alignment with limit of 7 characters.
+        */
+       #define LOG_TAG "yourtag"
        #include <log/log.h>
 
        ALOG(android_priority, tag, format, ...)
@@ -56,9 +62,7 @@
        LOG_EVENT_INT(tag, value)
        LOG_EVENT_LONG(tag, value)
 
-       Link with -llog
-
-       #include <log/logger.h>
+       clockid_t android_log_clockid()
 
        log_id_t android_logger_get_id(struct logger *logger)
        int android_logger_clear(struct logger *logger)
@@ -66,21 +70,49 @@
        int android_logger_get_log_readable_size(struct logger *logger)
        int android_logger_get_log_version(struct logger *logger)
 
-       struct  logger_list  *android_logger_list_alloc(int  mode, unsigned int
-       tail, pid_t pid)
-       struct  logger  *android_logger_open(struct  logger_list  *logger_list,
-       log_id_t id)
-       struct  logger_list  *android_logger_list_open(log_id_t  id,  int mode,
-       unsigned int tail, pid_t pid)
-
-       int android_logger_list_read(struct  logger_list  *logger_list,  struct
-       log_msg *log_msg
-
+       struct logger_list *android_logger_list_alloc(int mode,
+                                                     unsigned int tail,
+                                                     pid_t pid)
+       struct logger *android_logger_open(struct logger_list *logger_list,
+                                          log_id_t id)
+       struct logger_list *android_logger_list_open(log_id_t id, int mode,
+                                                    unsigned int tail,
+                                                    pid_t pid)
+       int android_logger_list_read(struct logger_list *logger_list,
+                                    struct log_msg *log_msg)
        void android_logger_list_free(struct logger_list *logger_list)
 
        log_id_t android_name_to_log_id(const char *logName)
        const char *android_log_id_to_name(log_id_t log_id)
 
+       android_log_context create_android_logger(uint32_t tag)
+
+       int android_log_write_list_begin(android_log_context ctx)
+       int android_log_write_list_end(android_log_context ctx)
+
+       int android_log_write_int32(android_log_context ctx, int32_t value)
+       int android_log_write_int64(android_log_context ctx, int64_t value)
+       int android_log_write_string8(android_log_context ctx,
+                                     const char *value)
+       int android_log_write_string8_len(android_log_context ctx,
+                                         const char *value, size_t maxlen)
+       int android_log_write_float32(android_log_context ctx, float value)
+
+       int android_log_write_list(android_log_context ctx,
+                                  log_id_t id = LOG_ID_EVENTS)
+
+       android_log_context create_android_log_parser(const char *msg,
+                                                     size_t len)
+       android_log_list_element android_log_read_next(android_log_context ctx)
+       android_log_list_element android_log_peek_next(android_log_context ctx)
+
+       int android_log_destroy(android_log_context *ctx)
+
+       #include <log/log_transport.h>
+
+       int android_set_log_transport(int transport_flag)
+       int android_get_log_transport()
+
        Link with -llog
 
 DESCRIPTION
@@ -135,6 +167,13 @@
        when  opening  the  sub-log.    It  is  recommended  to  open  the  log
        ANDROID_LOG_RDONLY in these cases.
 
+       android_set_log_transport()  selects  transport  filters.  Argument  is
+       either LOGGER_DEFAULT, LOGGER_LOGD, LOGGER_NULL or LOGGER_LOCAL. Log to
+       logger daemon for default or logd, drop contents on floor,  or log into
+       local   memory   respectively.       Both   android_set_log_transport()
+       and android_get_log_transport() return the current  transport mask,  or
+       a negative errno for any problems.
+
 ERRORS
        If messages fail, a negative error code will be returned to the caller.
 
@@ -163,8 +202,8 @@
        library retries on EINTR, -EINTR should never be returned.
 
 SEE ALSO
-       syslogd(8)
+       syslogd(8), klogd, auditd(8)
 
 
 
-                                  24 Jan 2014                        LIBLOG(3)
+                                  08 Feb 2017                        LIBLOG(3)
diff --git a/liblog/config_read.c b/liblog/config_read.c
index 1f54152..ca80c80 100644
--- a/liblog/config_read.c
+++ b/liblog/config_read.c
@@ -14,49 +14,73 @@
  * limitations under the License.
  */
 
+#include <log/log_transport.h>
+
 #include "config_read.h"
 #include "logger.h"
 
-LIBLOG_HIDDEN struct listnode __android_log_transport_read =
-    { &__android_log_transport_read, &__android_log_transport_read };
-LIBLOG_HIDDEN struct listnode __android_log_persist_read =
-    { &__android_log_persist_read, &__android_log_persist_read };
+LIBLOG_HIDDEN struct listnode __android_log_transport_read = {
+  &__android_log_transport_read, &__android_log_transport_read
+};
+LIBLOG_HIDDEN struct listnode __android_log_persist_read = {
+  &__android_log_persist_read, &__android_log_persist_read
+};
 
 static void __android_log_add_transport(
-        struct listnode *list, struct android_log_transport_read *transport) {
-    size_t i;
+    struct listnode* list, struct android_log_transport_read* transport) {
+  size_t i;
 
-    /* Try to keep one functioning transport for each log buffer id */
-    for (i = LOG_ID_MIN; i < LOG_ID_MAX; i++) {
-        struct android_log_transport_read *transp;
+  /* Try to keep one functioning transport for each log buffer id */
+  for (i = LOG_ID_MIN; i < LOG_ID_MAX; i++) {
+    struct android_log_transport_read* transp;
 
-        if (list_empty(list)) {
-            if (!transport->available || ((*transport->available)(i) >= 0)) {
-                list_add_tail(list, &transport->node);
-                return;
-            }
-        } else {
-            read_transport_for_each(transp, list) {
-                if (!transp->available) {
-                    return;
-                }
-                if (((*transp->available)(i) < 0) &&
-                        (!transport->available ||
-                            ((*transport->available)(i) >= 0))) {
-                    list_add_tail(list, &transport->node);
-                    return;
-                }
-            }
+    if (list_empty(list)) {
+      if (!transport->available || ((*transport->available)(i) >= 0)) {
+        list_add_tail(list, &transport->node);
+        return;
+      }
+    } else {
+      read_transport_for_each(transp, list) {
+        if (!transp->available) {
+          return;
         }
+        if (((*transp->available)(i) < 0) &&
+            (!transport->available || ((*transport->available)(i) >= 0))) {
+          list_add_tail(list, &transport->node);
+          return;
+        }
+      }
     }
+  }
 }
 
 LIBLOG_HIDDEN void __android_log_config_read() {
+  if (__android_log_transport & LOGGER_LOCAL) {
+    extern struct android_log_transport_read localLoggerRead;
+
+    __android_log_add_transport(&__android_log_transport_read, &localLoggerRead);
+  }
+
 #if (FAKE_LOG_DEVICE == 0)
+  if ((__android_log_transport == LOGGER_DEFAULT) ||
+      (__android_log_transport & LOGGER_LOGD)) {
     extern struct android_log_transport_read logdLoggerRead;
     extern struct android_log_transport_read pmsgLoggerRead;
 
     __android_log_add_transport(&__android_log_transport_read, &logdLoggerRead);
     __android_log_add_transport(&__android_log_persist_read, &pmsgLoggerRead);
+  }
 #endif
 }
+
+LIBLOG_HIDDEN void __android_log_config_read_close() {
+  struct android_log_transport_read* transport;
+  struct listnode* n;
+
+  read_transport_for_each_safe(transport, n, &__android_log_transport_read) {
+    list_remove(&transport->node);
+  }
+  read_transport_for_each_safe(transport, n, &__android_log_persist_read) {
+    list_remove(&transport->node);
+  }
+}
diff --git a/liblog/config_read.h b/liblog/config_read.h
index 67f4c20..7b29fa4 100644
--- a/liblog/config_read.h
+++ b/liblog/config_read.h
@@ -26,24 +26,29 @@
 extern LIBLOG_HIDDEN struct listnode __android_log_transport_read;
 extern LIBLOG_HIDDEN struct listnode __android_log_persist_read;
 
-#define read_transport_for_each(transp, transports)                         \
-    for (transp = node_to_item((transports)->next,                          \
-                               struct android_log_transport_read, node);    \
-         (transp != node_to_item(transports,                                \
-                                 struct android_log_transport_read, node)); \
-         transp = node_to_item(transp->node.next,                           \
-                               struct android_log_transport_read, node))    \
+#define read_transport_for_each(transp, transports)                           \
+  for ((transp) = node_to_item((transports)->next,                            \
+                               struct android_log_transport_read, node);      \
+       ((transp) != node_to_item((transports),                                \
+                                 struct android_log_transport_read, node)) && \
+       ((transp) != node_to_item((transp)->node.next,                         \
+                                 struct android_log_transport_read, node));   \
+       (transp) = node_to_item((transp)->node.next,                           \
+                               struct android_log_transport_read, node))
 
-#define read_transport_for_each_safe(transp, n, transports)                 \
-    for (transp = node_to_item((transports)->next,                          \
-                               struct android_log_transport_read, node),    \
-         n = transp->node.next;                                             \
-         (transp != node_to_item(transports,                                \
-                                 struct android_log_transport_read, node)); \
-         transp = node_to_item(n, struct android_log_transport_read, node), \
-         n = transp->node.next)
+#define read_transport_for_each_safe(transp, n, transports)                   \
+  for ((transp) = node_to_item((transports)->next,                            \
+                               struct android_log_transport_read, node),      \
+      (n) = (transp)->node.next;                                              \
+       ((transp) != node_to_item((transports),                                \
+                                 struct android_log_transport_read, node)) && \
+       ((transp) !=                                                           \
+        node_to_item((n), struct android_log_transport_read, node));          \
+       (transp) = node_to_item((n), struct android_log_transport_read, node), \
+      (n) = (transp)->node.next)
 
 LIBLOG_HIDDEN void __android_log_config_read();
+LIBLOG_HIDDEN void __android_log_config_read_close();
 
 __END_DECLS
 
diff --git a/liblog/config_write.c b/liblog/config_write.c
index d689f63..0a8b52f 100644
--- a/liblog/config_write.c
+++ b/liblog/config_write.c
@@ -14,53 +14,105 @@
  * limitations under the License.
  */
 
+#include <log/log_transport.h>
+
 #include "config_write.h"
 #include "logger.h"
 
-LIBLOG_HIDDEN struct listnode __android_log_transport_write =
-    { &__android_log_transport_write, &__android_log_transport_write };
-LIBLOG_HIDDEN struct listnode __android_log_persist_write =
-    { &__android_log_persist_write, &__android_log_persist_write};
+LIBLOG_HIDDEN struct listnode __android_log_transport_write = {
+  &__android_log_transport_write, &__android_log_transport_write
+};
+LIBLOG_HIDDEN struct listnode __android_log_persist_write = {
+  &__android_log_persist_write, &__android_log_persist_write
+};
 
 static void __android_log_add_transport(
-        struct listnode *list, struct android_log_transport_write *transport) {
-    size_t i;
+    struct listnode* list, struct android_log_transport_write* transport) {
+  size_t i;
 
-    /* Try to keep one functioning transport for each log buffer id */
-    for (i = LOG_ID_MIN; i < LOG_ID_MAX; i++) {
-        struct android_log_transport_write *transp;
+  /* Try to keep one functioning transport for each log buffer id */
+  for (i = LOG_ID_MIN; i < LOG_ID_MAX; i++) {
+    struct android_log_transport_write* transp;
 
-        if (list_empty(list)) {
-            if (!transport->available || ((*transport->available)(i) >= 0)) {
-                list_add_tail(list, &transport->node);
-                return;
-            }
-        } else {
-            write_transport_for_each(transp, list) {
-                if (!transp->available) {
-                    return;
-                }
-                if (((*transp->available)(i) < 0) &&
-                        (!transport->available ||
-                            ((*transport->available)(i) >= 0))) {
-                    list_add_tail(list, &transport->node);
-                    return;
-                }
-            }
+    if (list_empty(list)) {
+      if (!transport->available || ((*transport->available)(i) >= 0)) {
+        list_add_tail(list, &transport->node);
+        return;
+      }
+    } else {
+      write_transport_for_each(transp, list) {
+        if (!transp->available) {
+          return;
         }
+        if (((*transp->available)(i) < 0) &&
+            (!transport->available || ((*transport->available)(i) >= 0))) {
+          list_add_tail(list, &transport->node);
+          return;
+        }
+      }
     }
+  }
 }
 
 LIBLOG_HIDDEN void __android_log_config_write() {
+  if (__android_log_transport & LOGGER_LOCAL) {
+    extern struct android_log_transport_write localLoggerWrite;
+
+    __android_log_add_transport(&__android_log_transport_write,
+                                &localLoggerWrite);
+  }
+
+  if ((__android_log_transport == LOGGER_DEFAULT) ||
+      (__android_log_transport & LOGGER_LOGD)) {
 #if (FAKE_LOG_DEVICE == 0)
     extern struct android_log_transport_write logdLoggerWrite;
     extern struct android_log_transport_write pmsgLoggerWrite;
 
-    __android_log_add_transport(&__android_log_transport_write, &logdLoggerWrite);
+    __android_log_add_transport(&__android_log_transport_write,
+                                &logdLoggerWrite);
     __android_log_add_transport(&__android_log_persist_write, &pmsgLoggerWrite);
 #else
     extern struct android_log_transport_write fakeLoggerWrite;
 
-    __android_log_add_transport(&__android_log_transport_write, &fakeLoggerWrite);
+    __android_log_add_transport(&__android_log_transport_write,
+                                &fakeLoggerWrite);
 #endif
+  }
+
+  if (__android_log_transport & LOGGER_STDERR) {
+    extern struct android_log_transport_write stderrLoggerWrite;
+
+    /*
+     * stderr logger should be primary if we can be the only one, or if
+     * already in the primary list.  Otherwise land in the persist list.
+     * Remember we can be called here if we are already initialized.
+     */
+    if (list_empty(&__android_log_transport_write)) {
+      __android_log_add_transport(&__android_log_transport_write,
+                                  &stderrLoggerWrite);
+    } else {
+      struct android_log_transport_write* transp;
+      write_transport_for_each(transp, &__android_log_transport_write) {
+        if (transp == &stderrLoggerWrite) {
+          return;
+        }
+      }
+      __android_log_add_transport(&__android_log_persist_write,
+                                  &stderrLoggerWrite);
+    }
+  }
+}
+
+LIBLOG_HIDDEN void __android_log_config_write_close() {
+  struct android_log_transport_write* transport;
+  struct listnode* n;
+
+  write_transport_for_each_safe(transport, n, &__android_log_transport_write) {
+    transport->logMask = 0;
+    list_remove(&transport->node);
+  }
+  write_transport_for_each_safe(transport, n, &__android_log_persist_write) {
+    transport->logMask = 0;
+    list_remove(&transport->node);
+  }
 }
diff --git a/liblog/config_write.h b/liblog/config_write.h
index 3a02a4e..db1a083 100644
--- a/liblog/config_write.h
+++ b/liblog/config_write.h
@@ -26,24 +26,29 @@
 extern LIBLOG_HIDDEN struct listnode __android_log_transport_write;
 extern LIBLOG_HIDDEN struct listnode __android_log_persist_write;
 
-#define write_transport_for_each(transp, transports)                         \
-    for (transp = node_to_item((transports)->next,                           \
-                               struct android_log_transport_write, node);    \
-         (transp != node_to_item(transports,                                 \
-                                 struct android_log_transport_write, node)); \
-         transp = node_to_item(transp->node.next,                            \
-                               struct android_log_transport_write, node))    \
+#define write_transport_for_each(transp, transports)                           \
+  for ((transp) = node_to_item((transports)->next,                             \
+                               struct android_log_transport_write, node);      \
+       ((transp) != node_to_item((transports),                                 \
+                                 struct android_log_transport_write, node)) && \
+       ((transp) != node_to_item((transp)->node.next,                          \
+                                 struct android_log_transport_write, node));   \
+       (transp) = node_to_item((transp)->node.next,                            \
+                               struct android_log_transport_write, node))
 
-#define write_transport_for_each_safe(transp, n, transports)                 \
-    for (transp = node_to_item((transports)->next,                           \
-                               struct android_log_transport_write, node),    \
-         n = transp->node.next;                                              \
-         (transp != node_to_item(transports,                                 \
-                                 struct android_log_transport_write, node)); \
-         transp = node_to_item(n, struct android_log_transport_write, node), \
-         n = transp->node.next)
+#define write_transport_for_each_safe(transp, n, transports)                   \
+  for ((transp) = node_to_item((transports)->next,                             \
+                               struct android_log_transport_write, node),      \
+      (n) = (transp)->node.next;                                               \
+       ((transp) != node_to_item((transports),                                 \
+                                 struct android_log_transport_write, node)) && \
+       ((transp) !=                                                            \
+        node_to_item((n), struct android_log_transport_write, node));          \
+       (transp) = node_to_item((n), struct android_log_transport_write, node), \
+      (n) = (transp)->node.next)
 
 LIBLOG_HIDDEN void __android_log_config_write();
+LIBLOG_HIDDEN void __android_log_config_write_close();
 
 __END_DECLS
 
diff --git a/liblog/event.logtags b/liblog/event.logtags
index 72ecab1..301e885 100644
--- a/liblog/event.logtags
+++ b/liblog/event.logtags
@@ -33,4 +33,4 @@
 #
 # TODO: generate ".java" and ".h" files with integer constants from this file.
 
-1005  liblog (dropped|1)
+1006  liblog (dropped|1)
diff --git a/liblog/event_tag_map.c b/liblog/event_tag_map.c
deleted file mode 100644
index 345f0d3..0000000
--- a/liblog/event_tag_map.c
+++ /dev/null
@@ -1,428 +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.
- */
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-
-#include <log/event_tag_map.h>
-#include <log/log.h>
-
-#include "log_portability.h"
-
-#define OUT_TAG "EventTagMap"
-
-/*
- * Single entry.
- */
-typedef struct EventTag {
-    unsigned int    tagIndex;
-    const char*     tagStr;
-} EventTag;
-
-/*
- * Map.
- */
-struct EventTagMap {
-    /* memory-mapped source file; we get strings from here */
-    void*           mapAddr;
-    size_t          mapLen;
-
-    /* array of event tags, sorted numerically by tag index */
-    EventTag*       tagArray;
-    int             numTags;
-};
-
-/* fwd */
-static int processFile(EventTagMap* map);
-static int countMapLines(const EventTagMap* map);
-static int parseMapLines(EventTagMap* map);
-static int scanTagLine(char** pData, EventTag* tag, int lineNum);
-static int sortTags(EventTagMap* map);
-
-
-/*
- * Open the map file and allocate a structure to manage it.
- *
- * We create a private mapping because we want to terminate the log tag
- * strings with '\0'.
- */
-LIBLOG_ABI_PUBLIC EventTagMap* android_openEventTagMap(const char* fileName)
-{
-    EventTagMap* newTagMap;
-    off_t end;
-    int fd = -1;
-
-    newTagMap = calloc(1, sizeof(EventTagMap));
-    if (newTagMap == NULL)
-        return NULL;
-
-    fd = open(fileName, O_RDONLY | O_CLOEXEC);
-    if (fd < 0) {
-        fprintf(stderr, "%s: unable to open map '%s': %s\n",
-            OUT_TAG, fileName, strerror(errno));
-        goto fail;
-    }
-
-    end = lseek(fd, 0L, SEEK_END);
-    (void) lseek(fd, 0L, SEEK_SET);
-    if (end < 0) {
-        fprintf(stderr, "%s: unable to seek map '%s'\n", OUT_TAG, fileName);
-        goto fail;
-    }
-
-    newTagMap->mapAddr = mmap(NULL, end, PROT_READ | PROT_WRITE, MAP_PRIVATE,
-                                fd, 0);
-    if (newTagMap->mapAddr == MAP_FAILED) {
-        fprintf(stderr, "%s: mmap(%s) failed: %s\n",
-            OUT_TAG, fileName, strerror(errno));
-        goto fail;
-    }
-    newTagMap->mapLen = end;
-
-    if (processFile(newTagMap) != 0)
-        goto fail;
-
-    if (fd >= 0)
-      close(fd);
-
-    return newTagMap;
-
-fail:
-    android_closeEventTagMap(newTagMap);
-    if (fd >= 0)
-        close(fd);
-    return NULL;
-}
-
-/*
- * Close the map.
- */
-LIBLOG_ABI_PUBLIC void android_closeEventTagMap(EventTagMap* map)
-{
-    if (map == NULL)
-        return;
-
-    munmap(map->mapAddr, map->mapLen);
-    free(map);
-}
-
-/*
- * Look up an entry in the map.
- *
- * The entries are sorted by tag number, so we can do a binary search.
- */
-LIBLOG_ABI_PUBLIC const char* android_lookupEventTag(const EventTagMap* map,
-                                                     int tag)
-{
-    int hi, lo, mid;
-
-    lo = 0;
-    hi = map->numTags-1;
-
-    while (lo <= hi) {
-        int cmp;
-
-        mid = (lo+hi)/2;
-        cmp = map->tagArray[mid].tagIndex - tag;
-        if (cmp < 0) {
-            /* tag is bigger */
-            lo = mid + 1;
-        } else if (cmp > 0) {
-            /* tag is smaller */
-            hi = mid - 1;
-        } else {
-            /* found */
-            return map->tagArray[mid].tagStr;
-        }
-    }
-
-    return NULL;
-}
-
-
-
-/*
- * Determine whether "c" is a whitespace char.
- */
-static inline int isCharWhitespace(char c)
-{
-    return (c == ' ' || c == '\n' || c == '\r' || c == '\t');
-}
-
-/*
- * Determine whether "c" is a valid tag char.
- */
-static inline int isCharValidTag(char c)
-{
-    return ((c >= 'A' && c <= 'Z') ||
-            (c >= 'a' && c <= 'z') ||
-            (c >= '0' && c <= '9') ||
-            (c == '_'));
-}
-
-/*
- * Determine whether "c" is a valid decimal digit.
- */
-static inline int isCharDigit(char c)
-{
-    return (c >= '0' && c <= '9');
-}
-
-
-/*
- * Crunch through the file, parsing the contents and creating a tag index.
- */
-static int processFile(EventTagMap* map)
-{
-    /* get a tag count */
-    map->numTags = countMapLines(map);
-    if (map->numTags < 0)
-        return -1;
-
-    //printf("+++ found %d tags\n", map->numTags);
-
-    /* allocate storage for the tag index array */
-    map->tagArray = calloc(1, sizeof(EventTag) * map->numTags);
-    if (map->tagArray == NULL)
-        return -1;
-
-    /* parse the file, null-terminating tag strings */
-    if (parseMapLines(map) != 0) {
-        fprintf(stderr, "%s: file parse failed\n", OUT_TAG);
-        return -1;
-    }
-
-    /* sort the tags and check for duplicates */
-    if (sortTags(map) != 0)
-        return -1;
-
-    return 0;
-}
-
-/*
- * Run through all lines in the file, determining whether they're blank,
- * comments, or possibly have a tag entry.
- *
- * This is a very "loose" scan.  We don't try to detect syntax errors here.
- * The later pass is more careful, but the number of tags found there must
- * match the number of tags found here.
- *
- * Returns the number of potential tag entries found.
- */
-static int countMapLines(const EventTagMap* map)
-{
-    int numTags, unknown;
-    const char* cp;
-    const char* endp;
-
-    cp = (const char*) map->mapAddr;
-    endp = cp + map->mapLen;
-
-    numTags = 0;
-    unknown = 1;
-    while (cp < endp) {
-        if (*cp == '\n') {
-            unknown = 1;
-        } else if (unknown) {
-            if (isCharDigit(*cp)) {
-                /* looks like a tag to me */
-                numTags++;
-                unknown = 0;
-            } else if (isCharWhitespace(*cp)) {
-                /* might be leading whitespace before tag num, keep going */
-            } else {
-                /* assume comment; second pass can complain in detail */
-                unknown = 0;
-            }
-        } else {
-            /* we've made up our mind; just scan to end of line */
-        }
-        cp++;
-    }
-
-    return numTags;
-}
-
-/*
- * Parse the tags out of the file.
- */
-static int parseMapLines(EventTagMap* map)
-{
-    int tagNum, lineStart, lineNum;
-    char* cp;
-    char* endp;
-
-    cp = (char*) map->mapAddr;
-    endp = cp + map->mapLen;
-
-    /* insist on EOL at EOF; simplifies parsing and null-termination */
-    if (*(endp-1) != '\n') {
-        fprintf(stderr, "%s: map file missing EOL on last line\n", OUT_TAG);
-        return -1;
-    }
-
-    tagNum = 0;
-    lineStart = 1;
-    lineNum = 1;
-    while (cp < endp) {
-        //printf("{%02x}", *cp); fflush(stdout);
-        if (*cp == '\n') {
-            lineStart = 1;
-            lineNum++;
-        } else if (lineStart) {
-            if (*cp == '#') {
-                /* comment; just scan to end */
-                lineStart = 0;
-            } else if (isCharDigit(*cp)) {
-                /* looks like a tag; scan it out */
-                if (tagNum >= map->numTags) {
-                    fprintf(stderr,
-                        "%s: more tags than expected (%d)\n", OUT_TAG, tagNum);
-                    return -1;
-                }
-                if (scanTagLine(&cp, &map->tagArray[tagNum], lineNum) != 0)
-                    return -1;
-                tagNum++;
-                lineNum++;      // we eat the '\n'
-                /* leave lineStart==1 */
-            } else if (isCharWhitespace(*cp)) {
-                /* looks like leading whitespace; keep scanning */
-            } else {
-                fprintf(stderr,
-                    "%s: unexpected chars (0x%02x) in tag number on line %d\n",
-                    OUT_TAG, *cp, lineNum);
-                return -1;
-            }
-        } else {
-            /* this is a blank or comment line */
-        }
-        cp++;
-    }
-
-    if (tagNum != map->numTags) {
-        fprintf(stderr, "%s: parsed %d tags, expected %d\n",
-            OUT_TAG, tagNum, map->numTags);
-        return -1;
-    }
-
-    return 0;
-}
-
-/*
- * Scan one tag line.
- *
- * "*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).
- *
- * Returns 0 on success, nonzero on failure.
- */
-static int scanTagLine(char** pData, EventTag* tag, int lineNum)
-{
-    char* cp = *pData;
-    char* startp;
-    char* endp;
-    unsigned long val;
-
-    startp = cp;
-    while (isCharDigit(*++cp))
-        ;
-    *cp = '\0';
-
-    val = strtoul(startp, &endp, 10);
-    assert(endp == cp);
-    if (endp != cp)
-        fprintf(stderr, "ARRRRGH\n");
-
-    tag->tagIndex = val;
-
-    while (*++cp != '\n' && isCharWhitespace(*cp))
-        ;
-
-    if (*cp == '\n') {
-        fprintf(stderr,
-            "%s: missing tag string on line %d\n", OUT_TAG, lineNum);
-        return -1;
-    }
-
-    tag->tagStr = cp;
-
-    while (isCharValidTag(*++cp))
-        ;
-
-    if (*cp == '\n') {
-        /* null terminate and return */
-        *cp = '\0';
-    } else if (isCharWhitespace(*cp)) {
-        /* CRLF or trailin spaces; zap this char, then scan for the '\n' */
-        *cp = '\0';
-
-        /* just ignore the rest of the line till \n
-        TODO: read the tag description that follows the tag name
-        */
-        while (*++cp != '\n') {
-        }
-    } else {
-        fprintf(stderr,
-            "%s: invalid tag chars on line %d\n", OUT_TAG, lineNum);
-        return -1;
-    }
-
-    *pData = cp;
-
-    //printf("+++ Line %d: got %d '%s'\n", lineNum, tag->tagIndex, tag->tagStr);
-    return 0;
-}
-
-/*
- * Compare two EventTags.
- */
-static int compareEventTags(const void* v1, const void* v2)
-{
-    const EventTag* tag1 = (const EventTag*) v1;
-    const EventTag* tag2 = (const EventTag*) v2;
-
-    return tag1->tagIndex - tag2->tagIndex;
-}
-
-/*
- * Sort the EventTag array so we can do fast lookups by tag index.  After
- * the sort we do a quick check for duplicate tag indices.
- *
- * Returns 0 on success.
- */
-static int sortTags(EventTagMap* map)
-{
-    int i;
-
-    qsort(map->tagArray, map->numTags, sizeof(EventTag), compareEventTags);
-
-    for (i = 1; i < map->numTags; i++) {
-        if (map->tagArray[i].tagIndex == map->tagArray[i-1].tagIndex) {
-            fprintf(stderr, "%s: duplicate tag entries (%d:%s and %d:%s)\n",
-                OUT_TAG,
-                map->tagArray[i].tagIndex, map->tagArray[i].tagStr,
-                map->tagArray[i-1].tagIndex, map->tagArray[i-1].tagStr);
-            return -1;
-        }
-    }
-
-    return 0;
-}
diff --git a/liblog/event_tag_map.cpp b/liblog/event_tag_map.cpp
new file mode 100644
index 0000000..231f4d9
--- /dev/null
+++ b/liblog/event_tag_map.cpp
@@ -0,0 +1,642 @@
+/*
+ * Copyright (C) 2007-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 <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+
+#include <experimental/string_view>
+#include <functional>
+#include <string>
+#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>
+
+#include "log_portability.h"
+#include "logd_reader.h"
+
+#define OUT_TAG "EventTagMap"
+
+class MapString {
+ private:
+  const std::string* alloc;                  // HAS-AN
+  const std::experimental::string_view str;  // HAS-A
+
+ public:
+  operator const std::experimental::string_view() const {
+    return str;
+  }
+
+  const char* data() const {
+    return str.data();
+  }
+  size_t length() const {
+    return str.length();
+  }
+
+  bool operator==(const MapString& rval) const {
+    if (length() != rval.length()) return false;
+    if (length() == 0) return true;
+    return fastcmp<strncmp>(data(), rval.data(), length()) == 0;
+  }
+  bool operator!=(const MapString& rval) const {
+    return !(*this == rval);
+  }
+
+  MapString(const char* str, size_t len) : alloc(NULL), str(str, len) {
+  }
+  explicit MapString(const std::string& str)
+      : alloc(new std::string(str)), str(alloc->data(), alloc->length()) {
+  }
+  MapString(MapString&& rval)
+      : alloc(rval.alloc), str(rval.data(), rval.length()) {
+    rval.alloc = NULL;
+  }
+  explicit MapString(const MapString& rval)
+      : alloc(rval.alloc ? new std::string(*rval.alloc) : NULL),
+        str(alloc ? alloc->data() : rval.data(), rval.length()) {
+  }
+
+  ~MapString() {
+    if (alloc) delete alloc;
+  }
+};
+
+// Hash for MapString
+template <>
+struct std::hash<MapString>
+    : public std::unary_function<const MapString&, size_t> {
+  size_t operator()(const MapString& __t) const noexcept {
+    if (!__t.length()) return 0;
+    return std::hash<std::experimental::string_view>()(
+        std::experimental::string_view(__t));
+  }
+};
+
+typedef std::pair<MapString, MapString> TagFmt;
+
+template <>
+struct std::hash<TagFmt> : public std::unary_function<const TagFmt&, size_t> {
+  size_t operator()(const TagFmt& __t) const noexcept {
+    // Tag is typically unique.  Will cost us an extra 100ns for the
+    // unordered_map lookup if we instead did a hash that combined
+    // both of tag and fmt members, e.g.:
+    //
+    // return std::hash<MapString>()(__t.first) ^
+    //        std::hash<MapString>()(__t.second);
+    return std::hash<MapString>()(__t.first);
+  }
+};
+
+// Map
+struct EventTagMap {
+#define NUM_MAPS 2
+  // memory-mapped source file; we get strings from here
+  void* mapAddr[NUM_MAPS];
+  size_t mapLen[NUM_MAPS];
+
+ private:
+  std::unordered_map<uint32_t, TagFmt> Idx2TagFmt;
+  std::unordered_map<TagFmt, uint32_t> TagFmt2Idx;
+  std::unordered_map<MapString, uint32_t> Tag2Idx;
+  // protect unordered sets
+  android::RWLock rwlock;
+
+ public:
+  EventTagMap() {
+    memset(mapAddr, 0, sizeof(mapAddr));
+    memset(mapLen, 0, sizeof(mapLen));
+  }
+
+  ~EventTagMap() {
+    Idx2TagFmt.clear();
+    TagFmt2Idx.clear();
+    Tag2Idx.clear();
+    for (size_t which = 0; which < NUM_MAPS; ++which) {
+      if (mapAddr[which]) {
+        munmap(mapAddr[which], mapLen[which]);
+        mapAddr[which] = 0;
+      }
+    }
+  }
+
+  bool emplaceUnique(uint32_t tag, const TagFmt& tagfmt, bool verbose = false);
+  const TagFmt* find(uint32_t tag) const;
+  int find(TagFmt&& tagfmt) const;
+  int find(MapString&& tag) const;
+};
+
+bool EventTagMap::emplaceUnique(uint32_t tag, const TagFmt& tagfmt,
+                                bool verbose) {
+  bool ret = true;
+  static const char errorFormat[] =
+      OUT_TAG ": duplicate tag entries %" PRIu32 ":%.*s:%.*s and %" PRIu32
+              ":%.*s:%.*s)\n";
+  android::RWLock::AutoWLock writeLock(rwlock);
+  {
+    std::unordered_map<uint32_t, TagFmt>::const_iterator it;
+    it = Idx2TagFmt.find(tag);
+    if (it != Idx2TagFmt.end()) {
+      if (verbose) {
+        fprintf(stderr, errorFormat, it->first, (int)it->second.first.length(),
+                it->second.first.data(), (int)it->second.second.length(),
+                it->second.second.data(), tag, (int)tagfmt.first.length(),
+                tagfmt.first.data(), (int)tagfmt.second.length(),
+                tagfmt.second.data());
+      }
+      ret = false;
+    } else {
+      Idx2TagFmt.emplace(std::make_pair(tag, tagfmt));
+    }
+  }
+
+  {
+    std::unordered_map<TagFmt, uint32_t>::const_iterator it;
+    it = TagFmt2Idx.find(tagfmt);
+    if (it != TagFmt2Idx.end()) {
+      if (verbose) {
+        fprintf(stderr, errorFormat, it->second, (int)it->first.first.length(),
+                it->first.first.data(), (int)it->first.second.length(),
+                it->first.second.data(), tag, (int)tagfmt.first.length(),
+                tagfmt.first.data(), (int)tagfmt.second.length(),
+                tagfmt.second.data());
+      }
+      ret = false;
+    } else {
+      TagFmt2Idx.emplace(std::make_pair(tagfmt, tag));
+    }
+  }
+
+  {
+    std::unordered_map<MapString, uint32_t>::const_iterator it;
+    it = Tag2Idx.find(tagfmt.first);
+    if (!tagfmt.second.length() && (it != Tag2Idx.end())) {
+      Tag2Idx.erase(it);
+      it = Tag2Idx.end();
+    }
+    if (it == Tag2Idx.end()) {
+      Tag2Idx.emplace(std::make_pair(tagfmt.first, tag));
+    }
+  }
+
+  return ret;
+}
+
+const TagFmt* EventTagMap::find(uint32_t tag) const {
+  std::unordered_map<uint32_t, TagFmt>::const_iterator it;
+  android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+  it = Idx2TagFmt.find(tag);
+  if (it == Idx2TagFmt.end()) return NULL;
+  return &(it->second);
+}
+
+int EventTagMap::find(TagFmt&& tagfmt) const {
+  std::unordered_map<TagFmt, uint32_t>::const_iterator it;
+  android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+  it = TagFmt2Idx.find(std::move(tagfmt));
+  if (it == TagFmt2Idx.end()) return -1;
+  return it->second;
+}
+
+int EventTagMap::find(MapString&& tag) const {
+  std::unordered_map<MapString, uint32_t>::const_iterator it;
+  android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+  it = Tag2Idx.find(std::move(tag));
+  if (it == Tag2Idx.end()) return -1;
+  return it->second;
+}
+
+// Scan one tag line.
+//
+// "*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).
+//
+// lineNum = 0 removes verbose comments and requires us to cache the
+// content rather than make direct raw references since the content
+// will disappear after the call. A non-zero lineNum means we own the
+// 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) {
+    if (lineNum) {
+      fprintf(stderr, OUT_TAG ": malformed tag number on line %d\n", lineNum);
+    }
+    errno = EINVAL;
+    return -1;
+  }
+
+  uint32_t tagIndex = val;
+  if (tagIndex != val) {
+    if (lineNum) {
+      fprintf(stderr, OUT_TAG ": tag number too large on line %d\n", lineNum);
+    }
+    errno = ERANGE;
+    return -1;
+  }
+
+  while ((*++cp != '\n') && isspace(*cp)) {
+  }
+
+  if (*cp == '\n') {
+    if (lineNum) {
+      fprintf(stderr, OUT_TAG ": missing tag string on line %d\n", lineNum);
+    }
+    errno = EINVAL;
+    return -1;
+  }
+
+  const char* tag = cp;
+  // Determine whether "c" is a valid tag char.
+  while (isalnum(*++cp) || (*cp == '_')) {
+  }
+  size_t tagLen = cp - tag;
+
+  if (!isspace(*cp)) {
+    if (lineNum) {
+      fprintf(stderr, OUT_TAG ": invalid tag chars on line %d\n", lineNum);
+    }
+    errno = EINVAL;
+    return -1;
+  }
+
+  while (isspace(*cp) && (*cp != '\n')) ++cp;
+  const char* fmt = NULL;
+  size_t fmtLen = 0;
+  if (*cp != '#') {
+    fmt = cp;
+    while ((*cp != '\n') && (*cp != '#')) ++cp;
+    while ((cp > fmt) && isspace(*(cp - 1))) --cp;
+    fmtLen = cp - fmt;
+  }
+
+  // KISS Only report identicals if they are global
+  // Ideally we want to check if there are identicals
+  // recorded for the same uid, but recording that
+  // unused detail in our database is too burdensome.
+  bool verbose = true;
+  while ((*cp != '#') && (*cp != '\n')) ++cp;
+  if (*cp == '#') {
+    do {
+      ++cp;
+    } while (isspace(*cp) && (*cp != '\n'));
+    verbose = !!fastcmp<strncmp>(cp, "uid=", strlen("uid="));
+  }
+
+  while (*cp != '\n') ++cp;
+#ifdef DEBUG
+  fprintf(stderr, "%d: %p: %.*s\n", lineNum, tag, (int)(cp - *pData), *pData);
+#endif
+  *pData = cp;
+
+  if (lineNum) {
+    if (map->emplaceUnique(tagIndex,
+                           TagFmt(std::make_pair(MapString(tag, tagLen),
+                                                 MapString(fmt, fmtLen))),
+                           verbose)) {
+      return 0;
+    }
+  } else {
+    // cache
+    if (map->emplaceUnique(
+            tagIndex,
+            TagFmt(std::make_pair(MapString(std::string(tag, tagLen)),
+                                  MapString(std::string(fmt, fmtLen)))))) {
+      return 0;
+    }
+  }
+  errno = EMLINK;
+  return -1;
+}
+
+static const char* eventTagFiles[NUM_MAPS] = {
+  EVENT_TAG_MAP_FILE, "/dev/event-log-tags",
+};
+
+// Parse the tags out of the file.
+static int parseMapLines(EventTagMap* map, size_t which) {
+  char* cp = static_cast<char*>(map->mapAddr[which]);
+  size_t len = map->mapLen[which];
+  char* endp = cp + len;
+
+  // insist on EOL at EOF; simplifies parsing and null-termination
+  if (!len || (*(endp - 1) != '\n')) {
+#ifdef DEBUG
+    fprintf(stderr, OUT_TAG ": map file %zu[%zu] missing EOL on last line\n",
+            which, len);
+#endif
+    if (which) {  // do not propagate errors for other files
+      return 0;
+    }
+    errno = EINVAL;
+    return -1;
+  }
+
+  bool lineStart = true;
+  int lineNum = 1;
+  while (cp < endp) {
+    if (*cp == '\n') {
+      lineStart = true;
+      lineNum++;
+    } else if (lineStart) {
+      if (*cp == '#') {
+        // comment; just scan to end
+        lineStart = false;
+      } else if (isdigit(*cp)) {
+        // looks like a tag; scan it out
+        if (scanTagLine(map, &cp, lineNum) != 0) {
+          if (!which || (errno != EMLINK)) {
+            return -1;
+          }
+        }
+        lineNum++;  // we eat the '\n'
+                    // leave lineStart==true
+      } else if (isspace(*cp)) {
+        // looks like leading whitespace; keep scanning
+      } else {
+        fprintf(stderr,
+                OUT_TAG
+                ": unexpected chars (0x%02x) in tag number on line %d\n",
+                *cp, lineNum);
+        errno = EINVAL;
+        return -1;
+      }
+    } else {
+      // this is a blank or comment line
+    }
+    cp++;
+  }
+
+  return 0;
+}
+
+// Open the map file and allocate a structure to manage it.
+//
+// We create a private mapping because we want to terminate the log tag
+// strings with '\0'.
+LIBLOG_ABI_PUBLIC EventTagMap* android_openEventTagMap(const char* fileName) {
+  EventTagMap* newTagMap;
+  off_t end[NUM_MAPS];
+  int save_errno, fd[NUM_MAPS];
+  size_t which;
+
+  memset(fd, -1, sizeof(fd));
+  memset(end, 0, sizeof(end));
+
+  for (which = 0; which < NUM_MAPS; ++which) {
+    const char* tagfile = fileName ? fileName : eventTagFiles[which];
+
+    fd[which] = open(tagfile, O_RDONLY | O_CLOEXEC);
+    if (fd[which] < 0) {
+      if (!which) {
+        save_errno = errno;
+        fprintf(stderr, OUT_TAG ": unable to open map '%s': %s\n", tagfile,
+                strerror(save_errno));
+        goto fail_errno;
+      }
+      continue;
+    }
+    end[which] = lseek(fd[which], 0L, SEEK_END);
+    save_errno = errno;
+    (void)lseek(fd[which], 0L, SEEK_SET);
+    if (!which && (end[0] < 0)) {
+      fprintf(stderr, OUT_TAG ": unable to seek map '%s' %s\n", tagfile,
+              strerror(save_errno));
+      goto fail_close;
+    }
+    if (fileName) break;  // Only allow one as specified
+  }
+
+  newTagMap = new EventTagMap;
+  if (newTagMap == NULL) {
+    save_errno = errno;
+    goto fail_close;
+  }
+
+  for (which = 0; which < NUM_MAPS; ++which) {
+    if (fd[which] >= 0) {
+      newTagMap->mapAddr[which] =
+          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]);
+      fd[which] = -1;
+      if ((newTagMap->mapAddr[which] != MAP_FAILED) &&
+          (newTagMap->mapAddr[which] != NULL)) {
+        newTagMap->mapLen[which] = end[which];
+      } else if (!which) {
+        const char* tagfile = fileName ? fileName : eventTagFiles[which];
+
+        fprintf(stderr, OUT_TAG ": mmap(%s) failed: %s\n", tagfile,
+                strerror(save_errno));
+        goto fail_unmap;
+      }
+    }
+  }
+
+  for (which = 0; which < NUM_MAPS; ++which) {
+    if (parseMapLines(newTagMap, which) != 0) {
+      delete newTagMap;
+      return NULL;
+    }
+  }
+
+  return newTagMap;
+
+fail_unmap:
+  save_errno = EINVAL;
+  delete newTagMap;
+fail_close:
+  for (which = 0; which < NUM_MAPS; ++which) close(fd[which]);
+fail_errno:
+  errno = save_errno;
+  return NULL;
+}
+
+// Close the map.
+LIBLOG_ABI_PUBLIC void android_closeEventTagMap(EventTagMap* map) {
+  if (map) delete map;
+}
+
+// Cache miss, go to logd to acquire a public reference.
+// Because we lack access to a SHARED PUBLIC /dev/event-log-tags file map?
+static const TagFmt* __getEventTag(EventTagMap* map, unsigned int tag) {
+  // call event tag service to arrange for a new tag
+  char* buf = NULL;
+  // Can not use android::base::StringPrintf, asprintf + free instead.
+  static const char command_template[] = "getEventTag id=%u";
+  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;
+      } else {
+        size = ret;
+      }
+    } else {
+      size = ret;
+    }
+    // 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
+      if ((buf != cp) && (val > 0) && (*cp == '\n')) {  // truncation OK
+        ++cp;
+        if (!scanTagLine(map, &cp, 0)) {
+          free(buf);
+          return map->find(tag);
+        }
+      }
+    }
+    free(buf);
+  }
+  return NULL;
+}
+
+// Look up an entry in the map.
+LIBLOG_ABI_PUBLIC const char* android_lookupEventTag_len(const EventTagMap* map,
+                                                         size_t* len,
+                                                         unsigned int tag) {
+  if (len) *len = 0;
+  const TagFmt* str = map->find(tag);
+  if (!str) {
+    str = __getEventTag(const_cast<EventTagMap*>(map), tag);
+  }
+  if (!str) return NULL;
+  if (len) *len = str->first.length();
+  return str->first.data();
+}
+
+// Look up an entry in the map.
+LIBLOG_ABI_PUBLIC const char* android_lookupEventFormat_len(
+    const EventTagMap* map, size_t* len, unsigned int tag) {
+  if (len) *len = 0;
+  const TagFmt* str = map->find(tag);
+  if (!str) {
+    str = __getEventTag(const_cast<EventTagMap*>(map), tag);
+  }
+  if (!str) return NULL;
+  if (len) *len = str->second.length();
+  return str->second.data();
+}
+
+// This function is deprecated and replaced with android_lookupEventTag_len
+// since it will cause the map to change from Shared and backed by a file,
+// to Private Dirty and backed up by swap, albeit highly compressible. By
+// deprecating this function everywhere, we save 100s of MB of memory space.
+LIBLOG_ABI_PUBLIC const char* android_lookupEventTag(const EventTagMap* map,
+                                                     unsigned int tag) {
+  size_t len;
+  const char* tagStr = android_lookupEventTag_len(map, &len, tag);
+
+  if (!tagStr) return tagStr;
+  char* cp = const_cast<char*>(tagStr);
+  cp += len;
+  if (*cp) *cp = '\0';  // Trigger copy on write :-( and why deprecated.
+  return tagStr;
+}
+
+// Look up tagname, generate one if necessary, and return a tag
+LIBLOG_ABI_PUBLIC int android_lookupEventTagNum(EventTagMap* map,
+                                                const char* tagname,
+                                                const char* format, int prio) {
+  size_t len = strlen(tagname);
+  if (!len) {
+    errno = EINVAL;
+    return -1;
+  }
+
+  if ((prio != ANDROID_LOG_UNKNOWN) && (prio < ANDROID_LOG_SILENT) &&
+      !__android_log_is_loggable_len(prio, tagname, len,
+                                     __android_log_is_debuggable()
+                                         ? ANDROID_LOG_VERBOSE
+                                         : ANDROID_LOG_DEBUG)) {
+    errno = EPERM;
+    return -1;
+  }
+
+  if (!format) format = "";
+  ssize_t fmtLen = strlen(format);
+  int ret = map->find(TagFmt(
+      std::make_pair(MapString(tagname, len), MapString(format, fmtLen))));
+  if (ret != -1) return ret;
+
+  // call event tag service to arrange for a new tag
+  char* buf = NULL;
+  // Can not use android::base::StringPrintf, asprintf + free instead.
+  static const char command_template[] = "getEventTag name=%s format=\"%s\"";
+  ret = asprintf(&buf, command_template, tagname, format);
+  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;
+      } else {
+        size = ret;
+      }
+    } else {
+      size = ret;
+    }
+    // Ask event log tag service for an allocation
+    if (__send_log_msg(buf, size) >= 0) {
+      buf[size - 1] = '\0';
+      unsigned long val = strtoul(buf, &cp, 10);        // return size
+      if ((buf != cp) && (val > 0) && (*cp == '\n')) {  // truncation OK
+        val = strtoul(cp + 1, &cp, 10);                 // allocated tag number
+        if ((val > 0) && (val < UINT32_MAX) && (*cp == '\t')) {
+          free(buf);
+          ret = val;
+          // cache
+          map->emplaceUnique(ret, TagFmt(std::make_pair(
+                                      MapString(std::string(tagname, len)),
+                                      MapString(std::string(format, fmtLen)))));
+          return ret;
+        }
+      }
+    }
+    free(buf);
+  }
+
+  // Hail Mary
+  ret = map->find(MapString(tagname, len));
+  if (ret == -1) errno = ESRCH;
+  return ret;
+}
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
index cc67f3e..ae7a334 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -25,17 +25,21 @@
 #if !defined(_WIN32)
 #include <pthread.h>
 #endif
+#include <stdint.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <time.h>
 
-#include <log/logd.h>
+#include <android/log.h>
+#include <log/uio.h>
 
 #include "fake_log_device.h"
 #include "log_portability.h"
 
-#define kMaxTagLen  16      /* from the long-dead utils/Log.cpp */
+#define kMaxTagLen 16 /* from the long-dead utils/Log.cpp */
 
-#define kTagSetSize 16      /* arbitrary */
+#define kTagSetSize 16 /* arbitrary */
 
 #if 0
 #define TRACE(...) printf("fake_log_device: " __VA_ARGS__)
@@ -45,45 +49,43 @@
 
 /* from the long-dead utils/Log.cpp */
 typedef enum {
-    FORMAT_OFF = 0,
-    FORMAT_BRIEF,
-    FORMAT_PROCESS,
-    FORMAT_TAG,
-    FORMAT_THREAD,
-    FORMAT_RAW,
-    FORMAT_TIME,
-    FORMAT_THREADTIME,
-    FORMAT_LONG
+  FORMAT_OFF = 0,
+  FORMAT_BRIEF,
+  FORMAT_PROCESS,
+  FORMAT_TAG,
+  FORMAT_THREAD,
+  FORMAT_RAW,
+  FORMAT_TIME,
+  FORMAT_THREADTIME,
+  FORMAT_LONG
 } LogFormat;
 
-
 /*
  * Log driver state.
  */
 typedef struct LogState {
-    /* the fake fd that's seen by the user */
-    int     fakeFd;
+  /* the fake fd that's seen by the user */
+  int fakeFd;
 
-    /* a printable name for this fake device */
-    char   debugName[sizeof("/dev/log/security")];
+  /* a printable name for this fake device */
+  char debugName[sizeof("/dev/log/security")];
 
-    /* nonzero if this is a binary log */
-    int     isBinary;
+  /* nonzero if this is a binary log */
+  int isBinary;
 
-    /* global minimum priority */
-    int     globalMinPriority;
+  /* global minimum priority */
+  int globalMinPriority;
 
-    /* output format */
-    LogFormat outputFormat;
+  /* output format */
+  LogFormat outputFormat;
 
-    /* tags and priorities */
-    struct {
-        char    tag[kMaxTagLen];
-        int     minPriority;
-    } tagSet[kTagSetSize];
+  /* tags and priorities */
+  struct {
+    char tag[kMaxTagLen];
+    int minPriority;
+  } tagSet[kTagSetSize];
 } LogState;
 
-
 #if !defined(_WIN32)
 /*
  * Locking.  Since we're emulating a device, we need to be prepared
@@ -93,28 +95,25 @@
  */
 static pthread_mutex_t fakeLogDeviceLock = PTHREAD_MUTEX_INITIALIZER;
 
-static void lock()
-{
-    /*
-     * If we trigger a signal handler in the middle of locked activity and the
-     * signal handler logs a message, we could get into a deadlock state.
-     */
-    pthread_mutex_lock(&fakeLogDeviceLock);
+static void lock() {
+  /*
+   * If we trigger a signal handler in the middle of locked activity and the
+   * signal handler logs a message, we could get into a deadlock state.
+   */
+  pthread_mutex_lock(&fakeLogDeviceLock);
 }
 
-static void unlock()
-{
-    pthread_mutex_unlock(&fakeLogDeviceLock);
+static void unlock() {
+  pthread_mutex_unlock(&fakeLogDeviceLock);
 }
 
-#else   // !defined(_WIN32)
+#else  // !defined(_WIN32)
 
 #define lock() ((void)0)
 #define unlock() ((void)0)
 
 #endif  // !defined(_WIN32)
 
-
 /*
  * File descriptor management.
  */
@@ -126,45 +125,42 @@
  * Allocate an fd and associate a new LogState with it.
  * The fd is available via the fakeFd field of the return value.
  */
-static LogState *createLogState()
-{
-    size_t i;
+static LogState* createLogState() {
+  size_t i;
 
-    for (i = 0; i < (sizeof(openLogTable) / sizeof(openLogTable[0])); i++) {
-        if (openLogTable[i].fakeFd == 0) {
-            openLogTable[i].fakeFd = FAKE_FD_BASE + i;
-            return &openLogTable[i];
-        }
+  for (i = 0; i < (sizeof(openLogTable) / sizeof(openLogTable[0])); i++) {
+    if (openLogTable[i].fakeFd == 0) {
+      openLogTable[i].fakeFd = FAKE_FD_BASE + i;
+      return &openLogTable[i];
     }
-    return NULL;
+  }
+  return NULL;
 }
 
 /*
  * Translate an fd to a LogState.
  */
-static LogState *fdToLogState(int fd)
-{
-    if (fd >= FAKE_FD_BASE && fd < FAKE_FD_BASE + MAX_OPEN_LOGS) {
-        return &openLogTable[fd - FAKE_FD_BASE];
-    }
-    return NULL;
+static LogState* fdToLogState(int fd) {
+  if (fd >= FAKE_FD_BASE && fd < FAKE_FD_BASE + MAX_OPEN_LOGS) {
+    return &openLogTable[fd - FAKE_FD_BASE];
+  }
+  return NULL;
 }
 
 /*
  * Unregister the fake fd and free the memory it pointed to.
  */
-static void deleteFakeFd(int fd)
-{
-    LogState *ls;
+static void deleteFakeFd(int fd) {
+  LogState* ls;
 
-    lock();
+  lock();
 
-    ls = fdToLogState(fd);
-    if (ls != NULL) {
-        memset(&openLogTable[fd - FAKE_FD_BASE], 0, sizeof(openLogTable[0]));
-    }
+  ls = fdToLogState(fd);
+  if (ls != NULL) {
+    memset(&openLogTable[fd - FAKE_FD_BASE], 0, sizeof(openLogTable[0]));
+  }
 
-    unlock();
+  unlock();
 }
 
 /*
@@ -180,145 +176,154 @@
  * We also want to check ANDROID_PRINTF_LOG to determine how the output
  * will look.
  */
-static void configureInitialState(const char* pathName, LogState* logState)
-{
-    static const int kDevLogLen = sizeof("/dev/log/") - 1;
+static void configureInitialState(const char* pathName, LogState* logState) {
+  static const int kDevLogLen = sizeof("/dev/log/") - 1;
 
-    strncpy(logState->debugName, pathName, sizeof(logState->debugName));
-    logState->debugName[sizeof(logState->debugName) - 1] = '\0';
+  strncpy(logState->debugName, pathName, sizeof(logState->debugName));
+  logState->debugName[sizeof(logState->debugName) - 1] = '\0';
 
-    /* identify binary logs */
-    if (!strcmp(pathName + kDevLogLen, "events") ||
-            !strcmp(pathName + kDevLogLen, "security")) {
-        logState->isBinary = 1;
-    }
+  /* identify binary logs */
+  if (!strcmp(pathName + kDevLogLen, "events") ||
+      !strcmp(pathName + kDevLogLen, "security")) {
+    logState->isBinary = 1;
+  }
 
-    /* global min priority defaults to "info" level */
-    logState->globalMinPriority = ANDROID_LOG_INFO;
+  /* global min priority defaults to "info" level */
+  logState->globalMinPriority = ANDROID_LOG_INFO;
 
-    /*
-     * This is based on the the long-dead utils/Log.cpp code.
-     */
-    const char* tags = getenv("ANDROID_LOG_TAGS");
-    TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
-    if (tags != NULL) {
-        int entry = 0;
+  /*
+   * This is based on the the long-dead utils/Log.cpp code.
+   */
+  const char* tags = getenv("ANDROID_LOG_TAGS");
+  TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
+  if (tags != NULL) {
+    int entry = 0;
 
-        while (*tags != '\0') {
-            char tagName[kMaxTagLen];
-            int i, minPrio;
+    while (*tags != '\0') {
+      char tagName[kMaxTagLen];
+      int i, minPrio;
 
-            while (isspace(*tags))
-                tags++;
+      while (isspace(*tags)) tags++;
 
-            i = 0;
-            while (*tags != '\0' && !isspace(*tags) && *tags != ':' &&
-                    i < kMaxTagLen) {
-                tagName[i++] = *tags++;
-            }
-            if (i == kMaxTagLen) {
-                TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen-1);
-                return;
-            }
-            tagName[i] = '\0';
+      i = 0;
+      while (*tags != '\0' && !isspace(*tags) && *tags != ':' &&
+             i < kMaxTagLen) {
+        tagName[i++] = *tags++;
+      }
+      if (i == kMaxTagLen) {
+        TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen - 1);
+        return;
+      }
+      tagName[i] = '\0';
 
-            /* default priority, if there's no ":" part; also zero out '*' */
+      /* default priority, if there's no ":" part; also zero out '*' */
+      minPrio = ANDROID_LOG_VERBOSE;
+      if (tagName[0] == '*' && tagName[1] == '\0') {
+        minPrio = ANDROID_LOG_DEBUG;
+        tagName[0] = '\0';
+      }
+
+      if (*tags == ':') {
+        tags++;
+        if (*tags >= '0' && *tags <= '9') {
+          if (*tags >= ('0' + ANDROID_LOG_SILENT))
             minPrio = ANDROID_LOG_VERBOSE;
-            if (tagName[0] == '*' && tagName[1] == '\0') {
-                minPrio = ANDROID_LOG_DEBUG;
-                tagName[0] = '\0';
-            }
-
-            if (*tags == ':') {
-                tags++;
-                if (*tags >= '0' && *tags <= '9') {
-                    if (*tags >= ('0' + ANDROID_LOG_SILENT))
-                        minPrio = ANDROID_LOG_VERBOSE;
-                    else
-                        minPrio = *tags - '\0';
-                } else {
-                    switch (*tags) {
-                    case 'v':   minPrio = ANDROID_LOG_VERBOSE;  break;
-                    case 'd':   minPrio = ANDROID_LOG_DEBUG;    break;
-                    case 'i':   minPrio = ANDROID_LOG_INFO;     break;
-                    case 'w':   minPrio = ANDROID_LOG_WARN;     break;
-                    case 'e':   minPrio = ANDROID_LOG_ERROR;    break;
-                    case 'f':   minPrio = ANDROID_LOG_FATAL;    break;
-                    case 's':   minPrio = ANDROID_LOG_SILENT;   break;
-                    default:    minPrio = ANDROID_LOG_DEFAULT;  break;
-                    }
-                }
-
-                tags++;
-                if (*tags != '\0' && !isspace(*tags)) {
-                    TRACE("ERROR: garbage in tag env; expected whitespace\n");
-                    TRACE("       env='%s'\n", tags);
-                    return;
-                }
-            }
-
-            if (tagName[0] == 0) {
-                logState->globalMinPriority = minPrio;
-                TRACE("+++ global min prio %d\n", logState->globalMinPriority);
-            } else {
-                logState->tagSet[entry].minPriority = minPrio;
-                strcpy(logState->tagSet[entry].tag, tagName);
-                TRACE("+++ entry %d: %s:%d\n",
-                    entry,
-                    logState->tagSet[entry].tag,
-                    logState->tagSet[entry].minPriority);
-                entry++;
-            }
+          else
+            minPrio = *tags - '\0';
+        } else {
+          switch (*tags) {
+            case 'v':
+              minPrio = ANDROID_LOG_VERBOSE;
+              break;
+            case 'd':
+              minPrio = ANDROID_LOG_DEBUG;
+              break;
+            case 'i':
+              minPrio = ANDROID_LOG_INFO;
+              break;
+            case 'w':
+              minPrio = ANDROID_LOG_WARN;
+              break;
+            case 'e':
+              minPrio = ANDROID_LOG_ERROR;
+              break;
+            case 'f':
+              minPrio = ANDROID_LOG_FATAL;
+              break;
+            case 's':
+              minPrio = ANDROID_LOG_SILENT;
+              break;
+            default:
+              minPrio = ANDROID_LOG_DEFAULT;
+              break;
+          }
         }
+
+        tags++;
+        if (*tags != '\0' && !isspace(*tags)) {
+          TRACE("ERROR: garbage in tag env; expected whitespace\n");
+          TRACE("       env='%s'\n", tags);
+          return;
+        }
+      }
+
+      if (tagName[0] == 0) {
+        logState->globalMinPriority = minPrio;
+        TRACE("+++ global min prio %d\n", logState->globalMinPriority);
+      } else {
+        logState->tagSet[entry].minPriority = minPrio;
+        strcpy(logState->tagSet[entry].tag, tagName);
+        TRACE("+++ entry %d: %s:%d\n", entry, logState->tagSet[entry].tag,
+              logState->tagSet[entry].minPriority);
+        entry++;
+      }
     }
+  }
 
+  /*
+   * Taken from the long-dead utils/Log.cpp
+   */
+  const char* fstr = getenv("ANDROID_PRINTF_LOG");
+  LogFormat format;
+  if (fstr == NULL) {
+    format = FORMAT_BRIEF;
+  } else {
+    if (strcmp(fstr, "brief") == 0)
+      format = FORMAT_BRIEF;
+    else if (strcmp(fstr, "process") == 0)
+      format = FORMAT_PROCESS;
+    else if (strcmp(fstr, "tag") == 0)
+      format = FORMAT_PROCESS;
+    else if (strcmp(fstr, "thread") == 0)
+      format = FORMAT_PROCESS;
+    else if (strcmp(fstr, "raw") == 0)
+      format = FORMAT_PROCESS;
+    else if (strcmp(fstr, "time") == 0)
+      format = FORMAT_PROCESS;
+    else if (strcmp(fstr, "long") == 0)
+      format = FORMAT_PROCESS;
+    else
+      format = (LogFormat)atoi(fstr);  // really?!
+  }
 
-    /*
-     * Taken from the long-dead utils/Log.cpp
-     */
-    const char* fstr = getenv("ANDROID_PRINTF_LOG");
-    LogFormat format;
-    if (fstr == NULL) {
-        format = FORMAT_BRIEF;
-    } else {
-        if (strcmp(fstr, "brief") == 0)
-            format = FORMAT_BRIEF;
-        else if (strcmp(fstr, "process") == 0)
-            format = FORMAT_PROCESS;
-        else if (strcmp(fstr, "tag") == 0)
-            format = FORMAT_PROCESS;
-        else if (strcmp(fstr, "thread") == 0)
-            format = FORMAT_PROCESS;
-        else if (strcmp(fstr, "raw") == 0)
-            format = FORMAT_PROCESS;
-        else if (strcmp(fstr, "time") == 0)
-            format = FORMAT_PROCESS;
-        else if (strcmp(fstr, "long") == 0)
-            format = FORMAT_PROCESS;
-        else
-            format = (LogFormat) atoi(fstr);        // really?!
-    }
-
-    logState->outputFormat = format;
+  logState->outputFormat = format;
 }
 
 /*
  * Return a human-readable string for the priority level.  Always returns
  * a valid string.
  */
-static const char* getPriorityString(int priority)
-{
-    /* the first character of each string should be unique */
-    static const char* priorityStrings[] = {
-        "Verbose", "Debug", "Info", "Warn", "Error", "Assert"
-    };
-    int idx;
+static const char* getPriorityString(int priority) {
+  /* the first character of each string should be unique */
+  static const char* priorityStrings[] = { "Verbose", "Debug", "Info",
+                                           "Warn",    "Error", "Assert" };
+  int idx;
 
-    idx = (int)priority - (int)ANDROID_LOG_VERBOSE;
-    if (idx < 0 ||
-            idx >= (int)(sizeof(priorityStrings) / sizeof(priorityStrings[0])))
-        return "?unknown?";
-    return priorityStrings[idx];
+  idx = (int)priority - (int)ANDROID_LOG_VERBOSE;
+  if (idx < 0 ||
+      idx >= (int)(sizeof(priorityStrings) / sizeof(priorityStrings[0])))
+    return "?unknown?";
+  return priorityStrings[idx];
 }
 
 #if defined(_WIN32)
@@ -326,227 +331,229 @@
  * WIN32 does not have writev().
  * Make up something to replace it.
  */
-static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) {
-    ssize_t result = 0;
-    const struct iovec* end = iov + iovcnt;
-    for (; iov < end; iov++) {
-        ssize_t w = write(fd, iov->iov_base, iov->iov_len);
-        if (w != (ssize_t) iov->iov_len) {
-            if (w < 0)
-                return w;
-            return result + w;
-        }
-        result += w;
+static ssize_t fake_writev(int fd, const struct iovec* iov, int iovcnt) {
+  ssize_t result = 0;
+  const struct iovec* end = iov + iovcnt;
+  for (; iov < end; iov++) {
+    ssize_t w = write(fd, iov->iov_base, iov->iov_len);
+    if (w != (ssize_t)iov->iov_len) {
+      if (w < 0) return w;
+      return result + w;
     }
-    return result;
+    result += w;
+  }
+  return result;
 }
 
 #define writev fake_writev
 #endif
 
-
 /*
  * Write a filtered log message to stderr.
  *
  * Log format parsing taken from the long-dead utils/Log.cpp.
  */
-static void showLog(LogState *state,
-        int logPrio, const char* tag, const char* msg)
-{
+static void showLog(LogState* state, int logPrio, const char* tag,
+                    const char* msg) {
 #if !defined(_WIN32)
-    struct tm tmBuf;
+  struct tm tmBuf;
 #endif
-    struct tm* ptm;
-    char timeBuf[32];
-    char prefixBuf[128], suffixBuf[128];
-    char priChar;
-    time_t when;
+  struct tm* ptm;
+  char timeBuf[32];
+  char prefixBuf[128], suffixBuf[128];
+  char priChar;
+  time_t when;
 #if !defined(_WIN32)
-    pid_t pid, tid;
+  pid_t pid, tid;
 #else
-    uint32_t pid, tid;
+  uint32_t pid, tid;
 #endif
 
-    TRACE("LOG %d: %s %s", logPrio, tag, msg);
+  TRACE("LOG %d: %s %s", logPrio, tag, msg);
 
-    priChar = getPriorityString(logPrio)[0];
-    when = time(NULL);
-    pid = tid = getpid();       // find gettid()?
+  priChar = getPriorityString(logPrio)[0];
+  when = time(NULL);
+  pid = tid = getpid();  // find gettid()?
 
-    /*
-     * Get the current date/time in pretty form
-     *
-     * It's often useful when examining a log with "less" to jump to
-     * a specific point in the file by searching for the date/time stamp.
-     * For this reason it's very annoying to have regexp meta characters
-     * in the time stamp.  Don't use forward slashes, parenthesis,
-     * brackets, asterisks, or other special chars here.
-     */
+/*
+ * Get the current date/time in pretty form
+ *
+ * It's often useful when examining a log with "less" to jump to
+ * a specific point in the file by searching for the date/time stamp.
+ * For this reason it's very annoying to have regexp meta characters
+ * in the time stamp.  Don't use forward slashes, parenthesis,
+ * brackets, asterisks, or other special chars here.
+ */
 #if !defined(_WIN32)
-    ptm = localtime_r(&when, &tmBuf);
+  ptm = localtime_r(&when, &tmBuf);
 #else
-    ptm = localtime(&when);
+  ptm = localtime(&when);
 #endif
-    //strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
-    strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
+  // strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
+  strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
 
-    /*
-     * Construct a buffer containing the log header and log message.
-     */
-    size_t prefixLen, suffixLen;
+  /*
+   * Construct a buffer containing the log header and log message.
+   */
+  size_t prefixLen, suffixLen;
 
-    switch (state->outputFormat) {
+  switch (state->outputFormat) {
     case FORMAT_TAG:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%c/%-8s: ", priChar, tag);
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
+      prefixLen =
+          snprintf(prefixBuf, sizeof(prefixBuf), "%c/%-8s: ", priChar, tag);
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
     case FORMAT_PROCESS:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%c(%5d) ", priChar, pid);
-        suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
-            "  (%s)\n", tag);
-        break;
+      prefixLen =
+          snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d) ", priChar, pid);
+      suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "  (%s)\n", tag);
+      break;
     case FORMAT_THREAD:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%c(%5d:%5d) ", priChar, pid, tid);
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
+      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d:%5d) ",
+                           priChar, pid, tid);
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
     case FORMAT_RAW:
-        prefixBuf[0] = 0; prefixLen = 0;
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
+      prefixBuf[0] = 0;
+      prefixLen = 0;
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
     case FORMAT_TIME:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%s %-8s\n\t", timeBuf, tag);
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
+      prefixLen =
+          snprintf(prefixBuf, sizeof(prefixBuf), "%s %-8s\n\t", timeBuf, tag);
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
     case FORMAT_THREADTIME:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%s %5d %5d %c %-8s \n\t", timeBuf, pid, tid, priChar, tag);
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
+      prefixLen =
+          snprintf(prefixBuf, sizeof(prefixBuf), "%s %5d %5d %c %-8s \n\t",
+                   timeBuf, pid, tid, priChar, tag);
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
     case FORMAT_LONG:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "[ %s %5d:%5d %c/%-8s ]\n",
-            timeBuf, pid, tid, priChar, tag);
-        strcpy(suffixBuf, "\n\n"); suffixLen = 2;
-        break;
+      prefixLen =
+          snprintf(prefixBuf, sizeof(prefixBuf), "[ %s %5d:%5d %c/%-8s ]\n",
+                   timeBuf, pid, tid, priChar, tag);
+      strcpy(suffixBuf, "\n\n");
+      suffixLen = 2;
+      break;
     default:
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%c/%-8s(%5d): ", priChar, tag, pid);
-        strcpy(suffixBuf, "\n"); suffixLen = 1;
-        break;
-     }
+      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+                           "%c/%-8s(%5d): ", priChar, tag, pid);
+      strcpy(suffixBuf, "\n");
+      suffixLen = 1;
+      break;
+  }
 
-    /*
-     * Figure out how many lines there will be.
-     */
-    const char* end = msg + strlen(msg);
-    size_t numLines = 0;
-    const char* p = msg;
-    while (p < end) {
-        if (*p++ == '\n') numLines++;
+  /*
+   * Figure out how many lines there will be.
+   */
+  const char* end = msg + strlen(msg);
+  size_t numLines = 0;
+  const char* p = msg;
+  while (p < end) {
+    if (*p++ == '\n') numLines++;
+  }
+  if (p > msg && *(p - 1) != '\n') {
+    numLines++;
+  }
+
+  /*
+   * Create an array of iovecs large enough to write all of
+   * the lines with a prefix and a suffix.
+   */
+  const size_t INLINE_VECS = 64;
+  const size_t MAX_LINES = ((size_t)~0) / (3 * sizeof(struct iovec*));
+  struct iovec stackVec[INLINE_VECS];
+  struct iovec* vec = stackVec;
+  size_t numVecs;
+
+  if (numLines > MAX_LINES) numLines = MAX_LINES;
+
+  numVecs = numLines * 3;  // 3 iovecs per line.
+  if (numVecs > INLINE_VECS) {
+    vec = (struct iovec*)malloc(sizeof(struct iovec) * numVecs);
+    if (vec == NULL) {
+      msg = "LOG: write failed, no memory";
+      numVecs = INLINE_VECS;
+      numLines = numVecs / 3;
+      vec = stackVec;
     }
-    if (p > msg && *(p-1) != '\n') {
-        numLines++;
+  }
+
+  /*
+   * Fill in the iovec pointers.
+   */
+  p = msg;
+  struct iovec* v = vec;
+  int totalLen = 0;
+  while (numLines > 0 && p < end) {
+    if (prefixLen > 0) {
+      v->iov_base = prefixBuf;
+      v->iov_len = prefixLen;
+      totalLen += prefixLen;
+      v++;
     }
-
-    /*
-     * Create an array of iovecs large enough to write all of
-     * the lines with a prefix and a suffix.
-     */
-    const size_t INLINE_VECS = 64;
-    const size_t MAX_LINES   = ((size_t)~0)/(3*sizeof(struct iovec*));
-    struct iovec stackVec[INLINE_VECS];
-    struct iovec* vec = stackVec;
-    size_t numVecs;
-
-    if (numLines > MAX_LINES)
-        numLines = MAX_LINES;
-
-    numVecs = numLines * 3;  // 3 iovecs per line.
-    if (numVecs > INLINE_VECS) {
-        vec = (struct iovec*)malloc(sizeof(struct iovec)*numVecs);
-        if (vec == NULL) {
-            msg = "LOG: write failed, no memory";
-            numVecs = INLINE_VECS;
-            numLines = numVecs / 3;
-            vec = stackVec;
-        }
+    const char* start = p;
+    while (p < end && *p != '\n') {
+      p++;
     }
-
-    /*
-     * Fill in the iovec pointers.
-     */
-    p = msg;
-    struct iovec* v = vec;
-    int totalLen = 0;
-    while (numLines > 0 && p < end) {
-        if (prefixLen > 0) {
-            v->iov_base = prefixBuf;
-            v->iov_len = prefixLen;
-            totalLen += prefixLen;
-            v++;
-        }
-        const char* start = p;
-        while (p < end && *p != '\n') {
-            p++;
-        }
-        if ((p-start) > 0) {
-            v->iov_base = (void*)start;
-            v->iov_len = p-start;
-            totalLen += p-start;
-            v++;
-        }
-        if (*p == '\n') p++;
-        if (suffixLen > 0) {
-            v->iov_base = suffixBuf;
-            v->iov_len = suffixLen;
-            totalLen += suffixLen;
-            v++;
-        }
-        numLines -= 1;
+    if ((p - start) > 0) {
+      v->iov_base = (void*)start;
+      v->iov_len = p - start;
+      totalLen += p - start;
+      v++;
     }
-
-    /*
-     * Write the entire message to the log file with a single writev() call.
-     * We need to use this rather than a collection of printf()s on a FILE*
-     * because of multi-threading and multi-process issues.
-     *
-     * If the file was not opened with O_APPEND, this will produce interleaved
-     * output when called on the same file from multiple processes.
-     *
-     * If the file descriptor is actually a network socket, the writev()
-     * call may return with a partial write.  Putting the writev() call in
-     * a loop can result in interleaved data.  This can be alleviated
-     * somewhat by wrapping the writev call in the Mutex.
-     */
-
-    for(;;) {
-        int cc = writev(fileno(stderr), vec, v-vec);
-
-        if (cc == totalLen) break;
-
-        if (cc < 0) {
-            if(errno == EINTR) continue;
-
-                /* can't really log the failure; for now, throw out a stderr */
-            fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
-            break;
-        } else {
-                /* shouldn't happen when writing to file or tty */
-            fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
-            break;
-        }
+    if (*p == '\n') p++;
+    if (suffixLen > 0) {
+      v->iov_base = suffixBuf;
+      v->iov_len = suffixLen;
+      totalLen += suffixLen;
+      v++;
     }
+    numLines -= 1;
+  }
 
-    /* if we allocated storage for the iovecs, free it */
-    if (vec != stackVec)
-        free(vec);
+  /*
+   * Write the entire message to the log file with a single writev() call.
+   * We need to use this rather than a collection of printf()s on a FILE*
+   * because of multi-threading and multi-process issues.
+   *
+   * If the file was not opened with O_APPEND, this will produce interleaved
+   * output when called on the same file from multiple processes.
+   *
+   * If the file descriptor is actually a network socket, the writev()
+   * call may return with a partial write.  Putting the writev() call in
+   * a loop can result in interleaved data.  This can be alleviated
+   * somewhat by wrapping the writev call in the Mutex.
+   */
+
+  for (;;) {
+    int cc = writev(fileno(stderr), vec, v - vec);
+
+    if (cc == totalLen) break;
+
+    if (cc < 0) {
+      if (errno == EINTR) continue;
+
+      /* can't really log the failure; for now, throw out a stderr */
+      fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
+      break;
+    } else {
+      /* shouldn't happen when writing to file or tty */
+      fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
+      break;
+    }
+  }
+
+  /* if we allocated storage for the iovecs, free it */
+  if (vec != stackVec) free(vec);
 }
 
-
 /*
  * Receive a log message.  We happen to know that "vector" has three parts:
  *
@@ -554,137 +561,135 @@
  *  tag (N bytes -- null-terminated ASCII string)
  *  message (N bytes -- null-terminated ASCII string)
  */
-static ssize_t logWritev(int fd, const struct iovec* vector, int count)
-{
-    LogState* state;
+static ssize_t logWritev(int fd, const struct iovec* vector, int count) {
+  LogState* state;
 
-    /* Make sure that no-one frees the LogState while we're using it.
-     * Also guarantees that only one thread is in showLog() at a given
-     * time (if it matters).
-     */
-    lock();
+  /* Make sure that no-one frees the LogState while we're using it.
+   * Also guarantees that only one thread is in showLog() at a given
+   * time (if it matters).
+   */
+  lock();
 
-    state = fdToLogState(fd);
-    if (state == NULL) {
-        errno = EBADF;
-        goto error;
+  state = fdToLogState(fd);
+  if (state == NULL) {
+    errno = EBADF;
+    goto error;
+  }
+
+  if (state->isBinary) {
+    TRACE("%s: ignoring binary log\n", state->debugName);
+    goto bail;
+  }
+
+  if (count != 3) {
+    TRACE("%s: writevLog with count=%d not expected\n", state->debugName, count);
+    goto error;
+  }
+
+  /* pull out the three fields */
+  int logPrio = *(const char*)vector[0].iov_base;
+  const char* tag = (const char*)vector[1].iov_base;
+  const char* msg = (const char*)vector[2].iov_base;
+
+  /* see if this log tag is configured */
+  int i;
+  int minPrio = state->globalMinPriority;
+  for (i = 0; i < kTagSetSize; i++) {
+    if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
+      break; /* reached end of configured values */
+
+    if (strcmp(state->tagSet[i].tag, tag) == 0) {
+      // TRACE("MATCH tag '%s'\n", tag);
+      minPrio = state->tagSet[i].minPriority;
+      break;
     }
+  }
 
-    if (state->isBinary) {
-        TRACE("%s: ignoring binary log\n", state->debugName);
-        goto bail;
-    }
-
-    if (count != 3) {
-        TRACE("%s: writevLog with count=%d not expected\n",
-            state->debugName, count);
-        goto error;
-    }
-
-    /* pull out the three fields */
-    int logPrio = *(const char*)vector[0].iov_base;
-    const char* tag = (const char*) vector[1].iov_base;
-    const char* msg = (const char*) vector[2].iov_base;
-
-    /* see if this log tag is configured */
-    int i;
-    int minPrio = state->globalMinPriority;
-    for (i = 0; i < kTagSetSize; i++) {
-        if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
-            break;      /* reached end of configured values */
-
-        if (strcmp(state->tagSet[i].tag, tag) == 0) {
-            //TRACE("MATCH tag '%s'\n", tag);
-            minPrio = state->tagSet[i].minPriority;
-            break;
-        }
-    }
-
-    if (logPrio >= minPrio) {
-        showLog(state, logPrio, tag, msg);
-    } else {
-        //TRACE("+++ NOLOG(%d): %s %s", logPrio, tag, msg);
-    }
+  if (logPrio >= minPrio) {
+    showLog(state, logPrio, tag, msg);
+  } else {
+    // TRACE("+++ NOLOG(%d): %s %s", logPrio, tag, msg);
+  }
 
 bail:
-    unlock();
-    return vector[0].iov_len + vector[1].iov_len + vector[2].iov_len;
+  unlock();
+  int len = 0;
+  for (i = 0; i < count; ++i) {
+    len += vector[i].iov_len;
+  }
+  return len;
+
 error:
-    unlock();
-    return -1;
+  unlock();
+  return -1;
 }
 
 /*
  * Free up our state and close the fake descriptor.
  */
-static int logClose(int fd)
-{
-    deleteFakeFd(fd);
-    return 0;
+static int logClose(int fd) {
+  deleteFakeFd(fd);
+  return 0;
 }
 
 /*
  * Open a log output device and return a fake fd.
  */
-static int logOpen(const char* pathName, int flags __unused)
-{
-    LogState *logState;
-    int fd = -1;
+static int logOpen(const char* pathName, int flags __unused) {
+  LogState* logState;
+  int fd = -1;
 
-    lock();
+  lock();
 
-    logState = createLogState();
-    if (logState != NULL) {
-        configureInitialState(pathName, logState);
-        fd = logState->fakeFd;
-    } else  {
-        errno = ENFILE;
-    }
+  logState = createLogState();
+  if (logState != NULL) {
+    configureInitialState(pathName, logState);
+    fd = logState->fakeFd;
+  } else {
+    errno = ENFILE;
+  }
 
-    unlock();
+  unlock();
 
-    return fd;
+  return fd;
 }
 
-
 /*
  * Runtime redirection.  If this binary is running in the simulator,
  * just pass log messages to the emulated device.  If it's running
  * outside of the simulator, write the log messages to stderr.
  */
 
-static int (*redirectOpen)(const char *pathName, int flags) = NULL;
+static int (*redirectOpen)(const char* pathName, int flags) = NULL;
 static int (*redirectClose)(int fd) = NULL;
-static ssize_t (*redirectWritev)(int fd, const struct iovec* vector, int count)
-        = NULL;
+static ssize_t (*redirectWritev)(int fd, const struct iovec* vector,
+                                 int count) = NULL;
 
-static void setRedirects()
-{
-    const char *ws;
+static void setRedirects() {
+  const char* ws;
 
-    /* Wrapsim sets this environment variable on children that it's
-     * created using its LD_PRELOAD wrapper.
-     */
-    ws = getenv("ANDROID_WRAPSIM");
-    if (ws != NULL && strcmp(ws, "1") == 0) {
-        /* We're running inside wrapsim, so we can just write to the device. */
-        redirectOpen = (int (*)(const char *pathName, int flags))open;
-        redirectClose = close;
-        redirectWritev = writev;
-    } else {
-        /* There's no device to delegate to; handle the logging ourselves. */
-        redirectOpen = logOpen;
-        redirectClose = logClose;
-        redirectWritev = logWritev;
-    }
+  /* Wrapsim sets this environment variable on children that it's
+   * created using its LD_PRELOAD wrapper.
+   */
+  ws = getenv("ANDROID_WRAPSIM");
+  if (ws != NULL && strcmp(ws, "1") == 0) {
+    /* We're running inside wrapsim, so we can just write to the device. */
+    redirectOpen = (int (*)(const char* pathName, int flags))open;
+    redirectClose = close;
+    redirectWritev = writev;
+  } else {
+    /* There's no device to delegate to; handle the logging ourselves. */
+    redirectOpen = logOpen;
+    redirectClose = logClose;
+    redirectWritev = logWritev;
+  }
 }
 
-LIBLOG_HIDDEN int fakeLogOpen(const char *pathName, int flags)
-{
-    if (redirectOpen == NULL) {
-        setRedirects();
-    }
-    return redirectOpen(pathName, flags);
+LIBLOG_HIDDEN int fakeLogOpen(const char* pathName, int flags) {
+  if (redirectOpen == NULL) {
+    setRedirects();
+  }
+  return redirectOpen(pathName, flags);
 }
 
 /*
@@ -698,23 +703,37 @@
  * call is in the exit handler. Logging can continue in the exit handler to
  * help debug HOST tools ...
  */
-LIBLOG_HIDDEN int fakeLogClose(int fd)
-{
-    /* Assume that open() was called first. */
-    return redirectClose(fd);
+LIBLOG_HIDDEN int fakeLogClose(int fd) {
+  /* Assume that open() was called first. */
+  return redirectClose(fd);
 }
 
-LIBLOG_HIDDEN ssize_t fakeLogWritev(int fd,
-                                    const struct iovec* vector, int count)
-{
-    /* Assume that open() was called first. */
-    return redirectWritev(fd, vector, count);
+LIBLOG_HIDDEN ssize_t fakeLogWritev(int fd, const struct iovec* vector,
+                                    int count) {
+  /* Assume that open() was called first. */
+  return redirectWritev(fd, vector, count);
+}
+
+LIBLOG_HIDDEN ssize_t __send_log_msg(char* buf __unused,
+                                     size_t buf_size __unused) {
+  return -ENODEV;
 }
 
 LIBLOG_ABI_PUBLIC int __android_log_is_loggable(int prio,
-                                                const char *tag __unused,
-                                                int def)
-{
-    int logLevel = def;
-    return logLevel >= 0 && prio >= logLevel;
+                                                const char* tag __unused,
+                                                int def) {
+  int logLevel = def;
+  return logLevel >= 0 && prio >= logLevel;
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_is_loggable_len(int prio,
+                                                    const char* tag __unused,
+                                                    size_t len __unused,
+                                                    int def) {
+  int logLevel = def;
+  return logLevel >= 0 && prio >= logLevel;
+}
+
+LIBLOG_ABI_PRIVATE int __android_log_is_debuggable() {
+  return 1;
 }
diff --git a/liblog/fake_log_device.h b/liblog/fake_log_device.h
index 4529b5d..462d026 100644
--- a/liblog/fake_log_device.h
+++ b/liblog/fake_log_device.h
@@ -23,9 +23,9 @@
 
 struct iovec;
 
-LIBLOG_HIDDEN int fakeLogOpen(const char *pathName, int flags);
+LIBLOG_HIDDEN int fakeLogOpen(const char* pathName, int flags);
 LIBLOG_HIDDEN int fakeLogClose(int fd);
-LIBLOG_HIDDEN ssize_t fakeLogWritev(int fd,
-                                    const struct iovec* vector, int count);
+LIBLOG_HIDDEN ssize_t fakeLogWritev(int fd, const struct iovec* vector,
+                                    int count);
 
-#endif // _LIBLOG_FAKE_LOG_DEVICE_H
+#endif  // _LIBLOG_FAKE_LOG_DEVICE_H
diff --git a/liblog/fake_writer.c b/liblog/fake_writer.c
index dab8bc5..969661a 100644
--- a/liblog/fake_writer.c
+++ b/liblog/fake_writer.c
@@ -27,56 +27,77 @@
 
 static int fakeOpen();
 static void fakeClose();
-static int fakeWrite(log_id_t log_id, struct timespec *ts,
-                     struct iovec *vec, size_t nr);
+static int fakeWrite(log_id_t log_id, struct timespec* ts, struct iovec* vec,
+                     size_t nr);
 
 static int logFds[(int)LOG_ID_MAX] = { -1, -1, -1, -1, -1, -1 };
 
 LIBLOG_HIDDEN struct android_log_transport_write fakeLoggerWrite = {
-    .node = { &fakeLoggerWrite.node, &fakeLoggerWrite.node },
-    .context.private = &logFds,
-    .name = "fake",
-    .available = NULL,
-    .open = fakeOpen,
-    .close = fakeClose,
-    .write = fakeWrite,
+  .node = { &fakeLoggerWrite.node, &fakeLoggerWrite.node },
+  .context.priv = &logFds,
+  .name = "fake",
+  .available = NULL,
+  .open = fakeOpen,
+  .close = fakeClose,
+  .write = fakeWrite,
 };
 
 static int fakeOpen() {
-    int i;
+  int i;
 
-    for (i = 0; i < LOG_ID_MAX; i++) {
-        char buf[sizeof("/dev/log_security")];
-        snprintf(buf, sizeof(buf), "/dev/log_%s", android_log_id_to_name(i));
-        logFds[i] = fakeLogOpen(buf, O_WRONLY);
+  for (i = 0; i < LOG_ID_MAX; i++) {
+    /*
+     * Known maximum size string, plus an 8 character margin to deal with
+     * possible independent changes to android_log_id_to_name().
+     */
+    char buf[sizeof("/dev/log_security") + 8];
+    if (logFds[i] >= 0) {
+      continue;
     }
-    return 0;
+    snprintf(buf, sizeof(buf), "/dev/log_%s", android_log_id_to_name(i));
+    logFds[i] = fakeLogOpen(buf, O_WRONLY);
+    if (logFds[i] < 0) {
+      fprintf(stderr, "fakeLogOpen(%s, O_WRONLY) failed\n", buf);
+    }
+  }
+  return 0;
 }
 
 static void fakeClose() {
-    int i;
+  int i;
 
-    for (i = 0; i < LOG_ID_MAX; i++) {
-        fakeLogClose(logFds[i]);
-        logFds[i] = -1;
-    }
+  for (i = 0; i < LOG_ID_MAX; i++) {
+    fakeLogClose(logFds[i]);
+    logFds[i] = -1;
+  }
 }
 
-static int fakeWrite(log_id_t log_id, struct timespec *ts __unused,
-                      struct iovec *vec, size_t nr)
-{
-    ssize_t ret;
-    int logFd;
+static int fakeWrite(log_id_t log_id, struct timespec* ts __unused,
+                     struct iovec* vec, size_t nr) {
+  ssize_t ret;
+  size_t i;
+  int logFd, len;
 
-    if (/*(int)log_id >= 0 &&*/ (int)log_id >= (int)LOG_ID_MAX) {
-        return -EBADF;
-    }
+  if (/*(int)log_id >= 0 &&*/ (int)log_id >= (int)LOG_ID_MAX) {
+    return -EINVAL;
+  }
 
-    logFd = logFds[(int)log_id];
-    ret = TEMP_FAILURE_RETRY(fakeLogWritev(logFd, vec, nr));
-    if (ret < 0) {
-        ret = -errno;
-    }
+  len = 0;
+  for (i = 0; i < nr; ++i) {
+    len += vec[i].iov_len;
+  }
 
-    return ret;
+  if (len > LOGGER_ENTRY_MAX_PAYLOAD) {
+    len = LOGGER_ENTRY_MAX_PAYLOAD;
+  }
+
+  logFd = logFds[(int)log_id];
+  ret = TEMP_FAILURE_RETRY(fakeLogWritev(logFd, vec, nr));
+  if (ret < 0) {
+    ret = -errno;
+  } else if (ret > len) {
+    ret = len;
+  }
+
+  return ret;
 }
diff --git a/liblog/include/android/log.h b/liblog/include/android/log.h
new file mode 100644
index 0000000..15fba8b
--- /dev/null
+++ b/liblog/include/android/log.h
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2009 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_LOG_H
+#define _ANDROID_LOG_H
+
+/******************************************************************
+ *
+ * IMPORTANT NOTICE:
+ *
+ *   This file is part of Android's set of stable system headers
+ *   exposed by the Android NDK (Native Development Kit) since
+ *   platform release 1.5
+ *
+ *   Third-party source AND binary code relies on the definitions
+ *   here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
+ *
+ *   - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
+ *   - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
+ *   - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
+ *   - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
+ */
+
+/*
+ * Support routines to send messages to the Android in-kernel log buffer,
+ * which can later be accessed through the 'logcat' utility.
+ *
+ * Each log message must have
+ *   - a priority
+ *   - a log tag
+ *   - some text
+ *
+ * The tag normally corresponds to the component that emits the log message,
+ * and should be reasonably small.
+ *
+ * Log message text may be truncated to less than an implementation-specific
+ * limit (e.g. 1023 characters max).
+ *
+ * Note that a newline character ("\n") will be appended automatically to your
+ * log message, if not already there. It is not possible to send several
+ * messages and have them appear on a single line in logcat.
+ *
+ * PLEASE USE LOGS WITH MODERATION:
+ *
+ *  - Sending log messages eats CPU and slow down your application and the
+ *    system.
+ *
+ *  - The circular log buffer is pretty small (<64KB), sending many messages
+ *    might push off other important log messages from the rest of the system.
+ *
+ *  - In release builds, only send log messages to account for exceptional
+ *    conditions.
+ *
+ * NOTE: These functions MUST be implemented by /system/lib/liblog.so
+ */
+
+#include <stdarg.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Android log priority values, in ascending priority order.
+ */
+typedef enum android_LogPriority {
+  ANDROID_LOG_UNKNOWN = 0,
+  ANDROID_LOG_DEFAULT, /* only for SetMinPriority() */
+  ANDROID_LOG_VERBOSE,
+  ANDROID_LOG_DEBUG,
+  ANDROID_LOG_INFO,
+  ANDROID_LOG_WARN,
+  ANDROID_LOG_ERROR,
+  ANDROID_LOG_FATAL,
+  ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
+} android_LogPriority;
+
+/*
+ * Send a simple string to the log.
+ */
+int __android_log_write(int prio, const char* tag, const char* text);
+
+/*
+ * Send a formatted string to the log, used like printf(fmt,...)
+ */
+int __android_log_print(int prio, const char* tag, const char* fmt, ...)
+#if defined(__GNUC__)
+#ifdef __USE_MINGW_ANSI_STDIO
+#if __USE_MINGW_ANSI_STDIO
+    __attribute__((__format__(gnu_printf, 3, 4)))
+#else
+    __attribute__((__format__(printf, 3, 4)))
+#endif
+#else
+    __attribute__((__format__(printf, 3, 4)))
+#endif
+#endif
+    ;
+
+/*
+ * A variant of __android_log_print() that takes a va_list to list
+ * additional parameters.
+ */
+int __android_log_vprint(int prio, const char* tag, const char* fmt, va_list ap)
+#if defined(__GNUC__)
+#ifdef __USE_MINGW_ANSI_STDIO
+#if __USE_MINGW_ANSI_STDIO
+    __attribute__((__format__(gnu_printf, 3, 0)))
+#else
+    __attribute__((__format__(printf, 3, 0)))
+#endif
+#else
+    __attribute__((__format__(printf, 3, 0)))
+#endif
+#endif
+    ;
+
+/*
+ * Log an assertion failure and abort the process to have a chance
+ * to inspect it if a debugger is attached. This uses the FATAL priority.
+ */
+void __android_log_assert(const char* cond, const char* tag, const char* fmt,
+                          ...)
+#if defined(__GNUC__)
+    __attribute__((__noreturn__))
+#ifdef __USE_MINGW_ANSI_STDIO
+#if __USE_MINGW_ANSI_STDIO
+    __attribute__((__format__(gnu_printf, 3, 4)))
+#else
+    __attribute__((__format__(printf, 3, 4)))
+#endif
+#else
+    __attribute__((__format__(printf, 3, 4)))
+#endif
+#endif
+    ;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ANDROID_LOG_H */
diff --git a/liblog/include/log/event_tag_map.h b/liblog/include/log/event_tag_map.h
new file mode 100644
index 0000000..8dd9157
--- /dev/null
+++ b/liblog/include/log/event_tag_map.h
@@ -0,0 +1,73 @@
+/*
+ * 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_EVENTTAGMAP_H
+#define _LIBS_CUTILS_EVENTTAGMAP_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define EVENT_TAG_MAP_FILE "/system/etc/event-log-tags"
+
+struct EventTagMap;
+typedef struct EventTagMap EventTagMap;
+
+/*
+ * Open the specified file as an event log tag map.
+ *
+ * Returns NULL on failure.
+ */
+EventTagMap* android_openEventTagMap(const char* fileName);
+
+/*
+ * Close the map.
+ */
+void android_closeEventTagMap(EventTagMap* map);
+
+/*
+ * Look up a tag by index.  Returns the tag string, or NULL if not found.
+ */
+const char* android_lookupEventTag(const EventTagMap* map, unsigned int tag)
+    __attribute__((
+        deprecated("use android_lookupEventTag_len() instead to minimize "
+                   "MAP_PRIVATE copy-on-write memory impact")));
+
+/*
+ * Look up a tag by index.  Returns the tag string & string length, or NULL if
+ * not found.  Returned string is not guaranteed to be nul terminated.
+ */
+const char* android_lookupEventTag_len(const EventTagMap* map, size_t* len,
+                                       unsigned int tag);
+
+/*
+ * Look up a format by index. Returns the format string & string length,
+ * or NULL if not found. Returned string is not guaranteed to be nul terminated.
+ */
+const char* android_lookupEventFormat_len(const EventTagMap* map, size_t* len,
+                                          unsigned int tag);
+
+/*
+ * Look up tagname, generate one if necessary, and return a tag
+ */
+int android_lookupEventTagNum(EventTagMap* map, const char* tagname,
+                              const char* format, int prio);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /*_LIBS_CUTILS_EVENTTAGMAP_H*/
diff --git a/liblog/include/log/log.h b/liblog/include/log/log.h
new file mode 100644
index 0000000..6758c84
--- /dev/null
+++ b/liblog/include/log/log.h
@@ -0,0 +1,270 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_H
+#define _LIBS_LOG_LOG_H
+
+/* Too many in the ecosystem assume these are included */
+#if !defined(_WIN32)
+#include <pthread.h>
+#endif
+#include <stdint.h> /* uint16_t, int32_t */
+#include <stdio.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <android/log.h>
+#include <log/log_id.h>
+#include <log/log_main.h>
+#include <log/log_radio.h>
+#include <log/log_read.h>
+#include <log/log_system.h>
+#include <log/log_time.h>
+#include <log/uio.h> /* helper to define iovec for portability */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * LOG_TAG is the local tag used for the following simplified
+ * logging macros.  You can change this preprocessor definition
+ * before using the other macros to change the tag.
+ */
+
+#ifndef LOG_TAG
+#define LOG_TAG NULL
+#endif
+
+/*
+ * Normally we strip the effects of ALOGV (VERBOSE messages),
+ * LOG_FATAL and LOG_FATAL_IF (FATAL assert messages) from the
+ * release builds be defining NDEBUG.  You can modify this (for
+ * example with "#define LOG_NDEBUG 0" at the top of your source
+ * file) to change that behavior.
+ */
+
+#ifndef LOG_NDEBUG
+#ifdef NDEBUG
+#define LOG_NDEBUG 1
+#else
+#define LOG_NDEBUG 0
+#endif
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * This file uses ", ## __VA_ARGS__" zero-argument token pasting to
+ * work around issues with debug-only syntax errors in assertions
+ * that are missing format strings.  See commit
+ * 19299904343daf191267564fe32e6cd5c165cd42
+ */
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * Event logging.
+ */
+
+/*
+ * The following should not be used directly.
+ */
+
+int __android_log_bwrite(int32_t tag, const void* payload, size_t len);
+int __android_log_btwrite(int32_t tag, char type, const void* payload,
+                          size_t len);
+int __android_log_bswrite(int32_t tag, const char* payload);
+
+#define android_bWriteLog(tag, payload, len) \
+  __android_log_bwrite(tag, payload, len)
+#define android_btWriteLog(tag, type, payload, len) \
+  __android_log_btwrite(tag, type, payload, len)
+
+/*
+ * Event log entry types.
+ */
+#ifndef __AndroidEventLogType_defined
+#define __AndroidEventLogType_defined
+typedef enum {
+  /* Special markers for android_log_list_element type */
+  EVENT_TYPE_LIST_STOP = '\n', /* declare end of list  */
+  EVENT_TYPE_UNKNOWN = '?',    /* protocol error       */
+
+  /* must match with declaration in java/android/android/util/EventLog.java */
+  EVENT_TYPE_INT = 0,  /* int32_t */
+  EVENT_TYPE_LONG = 1, /* int64_t */
+  EVENT_TYPE_STRING = 2,
+  EVENT_TYPE_LIST = 3,
+  EVENT_TYPE_FLOAT = 4,
+} AndroidEventLogType;
+#endif
+#define sizeof_AndroidEventLogType sizeof(typeof_AndroidEventLogType)
+#define typeof_AndroidEventLogType unsigned char
+
+#ifndef LOG_EVENT_INT
+#define LOG_EVENT_INT(_tag, _value)                                          \
+  {                                                                          \
+    int intBuf = _value;                                                     \
+    (void)android_btWriteLog(_tag, EVENT_TYPE_INT, &intBuf, sizeof(intBuf)); \
+  }
+#endif
+#ifndef LOG_EVENT_LONG
+#define LOG_EVENT_LONG(_tag, _value)                                            \
+  {                                                                             \
+    long long longBuf = _value;                                                 \
+    (void)android_btWriteLog(_tag, EVENT_TYPE_LONG, &longBuf, sizeof(longBuf)); \
+  }
+#endif
+#ifndef LOG_EVENT_FLOAT
+#define LOG_EVENT_FLOAT(_tag, _value)                           \
+  {                                                             \
+    float floatBuf = _value;                                    \
+    (void)android_btWriteLog(_tag, EVENT_TYPE_FLOAT, &floatBuf, \
+                             sizeof(floatBuf));                 \
+  }
+#endif
+#ifndef LOG_EVENT_STRING
+#define LOG_EVENT_STRING(_tag, _value) \
+  (void)__android_log_bswrite(_tag, _value);
+#endif
+
+#ifdef __linux__
+
+#ifndef __ANDROID_USE_LIBLOG_CLOCK_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_CLOCK_INTERFACE 1
+#elif __ANDROID_API__ > 22 /* > Lollipop */
+#define __ANDROID_USE_LIBLOG_CLOCK_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_CLOCK_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_CLOCK_INTERFACE
+clockid_t android_log_clockid();
+#endif
+
+#endif /* __linux__ */
+
+/* --------------------------------------------------------------------- */
+
+#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
+#elif __ANDROID_API__ > 18 /* > JellyBean */
+#define __ANDROID_USE_LIBLOG_CLOSE_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_CLOSE_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_CLOSE_INTERFACE
+/*
+ * Release any logger resources (a new log write will immediately re-acquire)
+ *
+ * May be used to clean up File descriptors after a Fork, the resources are
+ * all O_CLOEXEC so wil self clean on exec().
+ */
+void __android_log_close();
+#endif
+
+#ifndef __ANDROID_USE_LIBLOG_RATELIMIT_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_RATELIMIT_INTERFACE 1
+#elif __ANDROID_API__ > 25 /* > OC */
+#define __ANDROID_USE_LIBLOG_RATELIMIT_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_RATELIMIT_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_RATELIMIT_INTERFACE
+
+/*
+ * if last is NULL, caller _must_ provide a consistent value for seconds.
+ *
+ * Return -1 if we can not acquire a lock, which below will permit the logging,
+ * error on allowing a log message through.
+ */
+int __android_log_ratelimit(time_t seconds, time_t* last);
+
+/*
+ * Usage:
+ *
+ *   // Global default and state
+ *   IF_ALOG_RATELIMIT() {
+ *      ALOG*(...);
+ *   }
+ *
+ *   // local state, 10 seconds ratelimit
+ *   static time_t local_state;
+ *   IF_ALOG_RATELIMIT_LOCAL(10, &local_state) {
+ *     ALOG*(...);
+ *   }
+ */
+
+#define IF_ALOG_RATELIMIT() if (__android_log_ratelimit(0, NULL) > 0)
+#define IF_ALOG_RATELIMIT_LOCAL(seconds, state) \
+  if (__android_log_ratelimit(seconds, state) > 0)
+
+#else
+
+/* No ratelimiting as API unsupported */
+#define IF_ALOG_RATELIMIT() if (1)
+#define IF_ALOG_RATELIMIT_LOCAL(...) if (1)
+
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_LOG_H */
diff --git a/liblog/include/log/log_event_list.h b/liblog/include/log/log_event_list.h
new file mode 100644
index 0000000..55953fc
--- /dev/null
+++ b/liblog/include/log/log_event_list.h
@@ -0,0 +1,306 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_EVENT_LIST_H
+#define _LIBS_LOG_EVENT_LIST_H
+
+#include <stdint.h>
+
+#if (defined(__cplusplus) && defined(_USING_LIBCXX))
+extern "C++" {
+#include <string>
+}
+#endif
+
+#include <log/log.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef __ANDROID_USE_LIBLOG_EVENT_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_EVENT_INTERFACE 1
+#elif __ANDROID_API__ > 23 /* > Marshmallow */
+#define __ANDROID_USE_LIBLOG_EVENT_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_EVENT_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_EVENT_INTERFACE
+
+/* For manipulating lists of events. */
+
+#define ANDROID_MAX_LIST_NEST_DEPTH 8
+
+/*
+ * The opaque context used to manipulate lists of events.
+ */
+#ifndef __android_log_context_defined
+#define __android_log_context_defined
+typedef struct android_log_context_internal* android_log_context;
+#endif
+
+/*
+ * Elements returned when reading a list of events.
+ */
+#ifndef __android_log_list_element_defined
+#define __android_log_list_element_defined
+typedef struct {
+  AndroidEventLogType type;
+  uint16_t complete;
+  uint16_t len;
+  union {
+    int32_t int32;
+    int64_t int64;
+    char* string;
+    float float32;
+  } data;
+} android_log_list_element;
+#endif
+
+/*
+ * Creates a context associated with an event tag to write elements to
+ * the list of events.
+ */
+android_log_context create_android_logger(uint32_t tag);
+
+/* All lists must be braced by a begin and end call */
+/*
+ * NB: If the first level braces are missing when specifying multiple
+ *     elements, we will manufacturer a list to embrace it for your API
+ *     convenience. For a single element, it will remain solitary.
+ */
+int android_log_write_list_begin(android_log_context ctx);
+int android_log_write_list_end(android_log_context ctx);
+
+int android_log_write_int32(android_log_context ctx, int32_t value);
+int android_log_write_int64(android_log_context ctx, int64_t value);
+int android_log_write_string8(android_log_context ctx, const char* value);
+int android_log_write_string8_len(android_log_context ctx, const char* value,
+                                  size_t maxlen);
+int android_log_write_float32(android_log_context ctx, float value);
+
+/* Submit the composed list context to the specified logger id */
+/* NB: LOG_ID_EVENTS and LOG_ID_SECURITY only valid binary buffers */
+int android_log_write_list(android_log_context ctx, log_id_t id);
+
+/*
+ * Creates a context from a raw buffer representing a list of events to be read.
+ */
+android_log_context create_android_log_parser(const char* msg, size_t len);
+
+android_log_list_element android_log_read_next(android_log_context ctx);
+android_log_list_element android_log_peek_next(android_log_context ctx);
+
+/* Finished with reader or writer context */
+int android_log_destroy(android_log_context* ctx);
+
+#ifdef __cplusplus
+#ifndef __class_android_log_event_list_defined
+#define __class_android_log_event_list_defined
+/* android_log_list C++ helpers */
+extern "C++" {
+class android_log_event_list {
+  friend class __android_log_event_list;
+
+ private:
+  android_log_context ctx;
+  int ret;
+
+  android_log_event_list(const android_log_event_list&) = delete;
+  void operator=(const android_log_event_list&) = delete;
+
+ public:
+  explicit android_log_event_list(int tag) : ret(0) {
+    ctx = create_android_logger(static_cast<uint32_t>(tag));
+  }
+  explicit android_log_event_list(log_msg& log_msg) : ret(0) {
+    ctx = create_android_log_parser(log_msg.msg() + sizeof(uint32_t),
+                                    log_msg.entry.len - sizeof(uint32_t));
+  }
+  ~android_log_event_list() {
+    android_log_destroy(&ctx);
+  }
+
+  int close() {
+    int retval = android_log_destroy(&ctx);
+    if (retval < 0) ret = retval;
+    return retval;
+  }
+
+  /* To allow above C calls to use this class as parameter */
+  operator android_log_context() const {
+    return ctx;
+  }
+
+  int status() const {
+    return ret;
+  }
+
+  int begin() {
+    int retval = android_log_write_list_begin(ctx);
+    if (retval < 0) ret = retval;
+    return ret;
+  }
+  int end() {
+    int retval = android_log_write_list_end(ctx);
+    if (retval < 0) ret = retval;
+    return ret;
+  }
+
+  android_log_event_list& operator<<(int32_t value) {
+    int retval = android_log_write_int32(ctx, value);
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+  android_log_event_list& operator<<(uint32_t value) {
+    int retval = android_log_write_int32(ctx, static_cast<int32_t>(value));
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+  android_log_event_list& operator<<(int64_t value) {
+    int retval = android_log_write_int64(ctx, value);
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+  android_log_event_list& operator<<(uint64_t value) {
+    int retval = android_log_write_int64(ctx, static_cast<int64_t>(value));
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+  android_log_event_list& operator<<(const char* value) {
+    int retval = android_log_write_string8(ctx, value);
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+#if defined(_USING_LIBCXX)
+  android_log_event_list& operator<<(const std::string& value) {
+    int retval =
+        android_log_write_string8_len(ctx, value.data(), value.length());
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+#endif
+
+  android_log_event_list& operator<<(float value) {
+    int retval = android_log_write_float32(ctx, value);
+    if (retval < 0) ret = retval;
+    return *this;
+  }
+
+  int write(log_id_t id = LOG_ID_EVENTS) {
+    int retval = android_log_write_list(ctx, id);
+    if (retval < 0) ret = retval;
+    return ret;
+  }
+
+  int operator<<(log_id_t id) {
+    int retval = android_log_write_list(ctx, id);
+    if (retval < 0) ret = retval;
+    android_log_destroy(&ctx);
+    return ret;
+  }
+
+  /*
+   * Append<Type> methods removes any integer promotion
+   * confusion, and adds access to string with length.
+   * Append methods are also added for all types for
+   * convenience.
+   */
+
+  bool AppendInt(int32_t value) {
+    int retval = android_log_write_int32(ctx, value);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+  bool AppendLong(int64_t value) {
+    int retval = android_log_write_int64(ctx, value);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+  bool AppendString(const char* value) {
+    int retval = android_log_write_string8(ctx, value);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+  bool AppendString(const char* value, size_t len) {
+    int retval = android_log_write_string8_len(ctx, value, len);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+#if defined(_USING_LIBCXX)
+  bool AppendString(const std::string& value) {
+    int retval =
+        android_log_write_string8_len(ctx, value.data(), value.length());
+    if (retval < 0) ret = retval;
+    return ret;
+  }
+
+  bool Append(const std::string& value) {
+    int retval =
+        android_log_write_string8_len(ctx, value.data(), value.length());
+    if (retval < 0) ret = retval;
+    return ret;
+  }
+#endif
+
+  bool AppendFloat(float value) {
+    int retval = android_log_write_float32(ctx, value);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+  template <typename Tvalue>
+  bool Append(Tvalue value) {
+    *this << value;
+    return ret >= 0;
+  }
+
+  bool Append(const char* value, size_t len) {
+    int retval = android_log_write_string8_len(ctx, value, len);
+    if (retval < 0) ret = retval;
+    return ret >= 0;
+  }
+
+  android_log_list_element read() {
+    return android_log_read_next(ctx);
+  }
+  android_log_list_element peek() {
+    return android_log_peek_next(ctx);
+  }
+};
+}
+#endif
+#endif
+
+#endif /* __ANDROID_USE_LIBLOG_EVENT_INTERFACE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_EVENT_LIST_H */
diff --git a/liblog/include/log/log_id.h b/liblog/include/log/log_id.h
new file mode 100644
index 0000000..7bfa277
--- /dev/null
+++ b/liblog/include/log/log_id.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_ID_H
+#define _LIBS_LOG_LOG_ID_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef log_id_t_defined
+#define log_id_t_defined
+typedef enum log_id {
+  LOG_ID_MIN = 0,
+
+  LOG_ID_MAIN = 0,
+  LOG_ID_RADIO = 1,
+  LOG_ID_EVENTS = 2,
+  LOG_ID_SYSTEM = 3,
+  LOG_ID_CRASH = 4,
+  LOG_ID_SECURITY = 5,
+  LOG_ID_KERNEL = 6, /* place last, third-parties can not use it */
+
+  LOG_ID_MAX
+} log_id_t;
+#endif
+#define sizeof_log_id_t sizeof(typeof_log_id_t)
+#define typeof_log_id_t unsigned char
+
+/*
+ * Send a simple string to the log.
+ */
+int __android_log_buf_write(int bufID, int prio, const char* tag,
+                            const char* text);
+int __android_log_buf_print(int bufID, int prio, const char* tag,
+                            const char* fmt, ...)
+#if defined(__GNUC__)
+    __attribute__((__format__(printf, 4, 5)))
+#endif
+    ;
+
+/*
+ * log_id_t helpers
+ */
+log_id_t android_name_to_log_id(const char* logName);
+const char* android_log_id_to_name(log_id_t log_id);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_LOG_ID_H */
diff --git a/liblog/include/log/log_main.h b/liblog/include/log/log_main.h
new file mode 100644
index 0000000..da16158
--- /dev/null
+++ b/liblog/include/log/log_main.h
@@ -0,0 +1,392 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_MAIN_H
+#define _LIBS_LOG_LOG_MAIN_H
+
+#include <android/log.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Normally we strip the effects of ALOGV (VERBOSE messages),
+ * LOG_FATAL and LOG_FATAL_IF (FATAL assert messages) from the
+ * release builds be defining NDEBUG.  You can modify this (for
+ * example with "#define LOG_NDEBUG 0" at the top of your source
+ * file) to change that behavior.
+ */
+
+#ifndef LOG_NDEBUG
+#ifdef NDEBUG
+#define LOG_NDEBUG 1
+#else
+#define LOG_NDEBUG 0
+#endif
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * This file uses ", ## __VA_ARGS__" zero-argument token pasting to
+ * work around issues with debug-only syntax errors in assertions
+ * that are missing format strings.  See commit
+ * 19299904343daf191267564fe32e6cd5c165cd42
+ */
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
+#endif
+
+#ifndef __predict_false
+#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
+#endif
+
+#define android_writeLog(prio, tag, text) __android_log_write(prio, tag, text)
+
+#define android_printLog(prio, tag, ...) \
+  __android_log_print(prio, tag, __VA_ARGS__)
+
+#define android_vprintLog(prio, cond, tag, ...) \
+  __android_log_vprint(prio, tag, __VA_ARGS__)
+
+/*
+ * Log macro that allows you to specify a number for the priority.
+ */
+#ifndef LOG_PRI
+#define LOG_PRI(priority, tag, ...) android_printLog(priority, tag, __VA_ARGS__)
+#endif
+
+/*
+ * Log macro that allows you to pass in a varargs ("args" is a va_list).
+ */
+#ifndef LOG_PRI_VA
+#define LOG_PRI_VA(priority, tag, fmt, args) \
+  android_vprintLog(priority, NULL, tag, fmt, args)
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/* XXX Macros to work around syntax errors in places where format string
+ * arg is not passed to ALOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF
+ * (happens only in debug builds).
+ */
+
+/* Returns 2nd arg.  Used to substitute default value if caller's vararg list
+ * is empty.
+ */
+#define __android_second(dummy, second, ...) second
+
+/* If passed multiple args, returns ',' followed by all but 1st arg, otherwise
+ * returns nothing.
+ */
+#define __android_rest(first, ...) , ##__VA_ARGS__
+
+#define android_printAssert(cond, tag, ...)                     \
+  __android_log_assert(cond, tag,                               \
+                       __android_second(0, ##__VA_ARGS__, NULL) \
+                           __android_rest(__VA_ARGS__))
+
+/*
+ * Log a fatal error.  If the given condition fails, this stops program
+ * execution like a normal assertion, but also generating the given message.
+ * It is NOT stripped from release builds.  Note that the condition test
+ * is -inverted- from the normal assert() semantics.
+ */
+#ifndef LOG_ALWAYS_FATAL_IF
+#define LOG_ALWAYS_FATAL_IF(cond, ...)                              \
+  ((__predict_false(cond))                                          \
+       ? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
+       : (void)0)
+#endif
+
+#ifndef LOG_ALWAYS_FATAL
+#define LOG_ALWAYS_FATAL(...) \
+  (((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
+#endif
+
+/*
+ * Versions of LOG_ALWAYS_FATAL_IF and LOG_ALWAYS_FATAL that
+ * are stripped out of release builds.
+ */
+
+#if LOG_NDEBUG
+
+#ifndef LOG_FATAL_IF
+#define LOG_FATAL_IF(cond, ...) ((void)0)
+#endif
+#ifndef LOG_FATAL
+#define LOG_FATAL(...) ((void)0)
+#endif
+
+#else
+
+#ifndef LOG_FATAL_IF
+#define LOG_FATAL_IF(cond, ...) LOG_ALWAYS_FATAL_IF(cond, ##__VA_ARGS__)
+#endif
+#ifndef LOG_FATAL
+#define LOG_FATAL(...) LOG_ALWAYS_FATAL(__VA_ARGS__)
+#endif
+
+#endif
+
+/*
+ * Assertion that generates a log message when the assertion fails.
+ * Stripped out of release builds.  Uses the current LOG_TAG.
+ */
+#ifndef ALOG_ASSERT
+#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ##__VA_ARGS__)
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * C/C++ logging functions.  See the logging documentation for API details.
+ *
+ * We'd like these to be available from C code (in case we import some from
+ * somewhere), so this has a C interface.
+ *
+ * The output will be correct when the log file is shared between multiple
+ * threads and/or multiple processes so long as the operating system
+ * supports O_APPEND.  These calls have mutex-protected data structures
+ * and so are NOT reentrant.  Do not use LOG in a signal handler.
+ */
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * Simplified macro to send a verbose log message using the current LOG_TAG.
+ */
+#ifndef ALOGV
+#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
+#if LOG_NDEBUG
+#define ALOGV(...)          \
+  do {                      \
+    if (0) {                \
+      __ALOGV(__VA_ARGS__); \
+    }                       \
+  } while (0)
+#else
+#define ALOGV(...) __ALOGV(__VA_ARGS__)
+#endif
+#endif
+
+#ifndef ALOGV_IF
+#if LOG_NDEBUG
+#define ALOGV_IF(cond, ...) ((void)0)
+#else
+#define ALOGV_IF(cond, ...)                                                  \
+  ((__predict_false(cond)) ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
+                           : (void)0)
+#endif
+#endif
+
+/*
+ * Simplified macro to send a debug log message using the current LOG_TAG.
+ */
+#ifndef ALOGD
+#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
+#endif
+
+#ifndef ALOGD_IF
+#define ALOGD_IF(cond, ...)                                                \
+  ((__predict_false(cond)) ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
+                           : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an info log message using the current LOG_TAG.
+ */
+#ifndef ALOGI
+#define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
+#endif
+
+#ifndef ALOGI_IF
+#define ALOGI_IF(cond, ...)                                               \
+  ((__predict_false(cond)) ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
+                           : (void)0)
+#endif
+
+/*
+ * Simplified macro to send a warning log message using the current LOG_TAG.
+ */
+#ifndef ALOGW
+#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
+#endif
+
+#ifndef ALOGW_IF
+#define ALOGW_IF(cond, ...)                                               \
+  ((__predict_false(cond)) ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
+                           : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an error log message using the current LOG_TAG.
+ */
+#ifndef ALOGE
+#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
+#endif
+
+#ifndef ALOGE_IF
+#define ALOGE_IF(cond, ...)                                                \
+  ((__predict_false(cond)) ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
+                           : (void)0)
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * Conditional based on whether the current LOG_TAG is enabled at
+ * verbose priority.
+ */
+#ifndef IF_ALOGV
+#if LOG_NDEBUG
+#define IF_ALOGV() if (false)
+#else
+#define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG)
+#endif
+#endif
+
+/*
+ * Conditional based on whether the current LOG_TAG is enabled at
+ * debug priority.
+ */
+#ifndef IF_ALOGD
+#define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG)
+#endif
+
+/*
+ * Conditional based on whether the current LOG_TAG is enabled at
+ * info priority.
+ */
+#ifndef IF_ALOGI
+#define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG)
+#endif
+
+/*
+ * Conditional based on whether the current LOG_TAG is enabled at
+ * warn priority.
+ */
+#ifndef IF_ALOGW
+#define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG)
+#endif
+
+/*
+ * Conditional based on whether the current LOG_TAG is enabled at
+ * error priority.
+ */
+#ifndef IF_ALOGE
+#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ * Basic log message macro.
+ *
+ * Example:
+ *  ALOG(LOG_WARN, NULL, "Failed with error %d", errno);
+ *
+ * The second argument may be NULL or "" to indicate the "global" tag.
+ */
+#ifndef ALOG
+#define ALOG(priority, tag, ...) LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
+#endif
+
+/*
+ * Conditional given a desired logging priority and tag.
+ */
+#ifndef IF_ALOG
+#define IF_ALOG(priority, tag) if (android_testLog(ANDROID_##priority, tag))
+#endif
+
+/* --------------------------------------------------------------------- */
+
+/*
+ *    IF_ALOG uses android_testLog, but IF_ALOG can be overridden.
+ *    android_testLog will remain constant in its purpose as a wrapper
+ *        for Android logging filter policy, and can be subject to
+ *        change. It can be reused by the developers that override
+ *        IF_ALOG as a convenient means to reimplement their policy
+ *        over Android.
+ */
+
+#ifndef __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE 2
+#elif __ANDROID_API__ > 24 /* > Nougat */
+#define __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE 2
+#elif __ANDROID_API__ > 22 /* > Lollipop */
+#define __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE
+
+/*
+ * Use the per-tag properties "log.tag.<tagname>" to generate a runtime
+ * result of non-zero to expose a log. prio is ANDROID_LOG_VERBOSE to
+ * ANDROID_LOG_FATAL. default_prio if no property. Undefined behavior if
+ * any other value.
+ */
+int __android_log_is_loggable(int prio, const char* tag, int default_prio);
+
+#if __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE > 1
+#include <sys/types.h>
+
+int __android_log_is_loggable_len(int prio, const char* tag, size_t len,
+                                  int default_prio);
+
+#if LOG_NDEBUG /* Production */
+#define android_testLog(prio, tag)                                           \
+  (__android_log_is_loggable_len(prio, tag, (tag && *tag) ? strlen(tag) : 0, \
+                                 ANDROID_LOG_DEBUG) != 0)
+#else
+#define android_testLog(prio, tag)                                           \
+  (__android_log_is_loggable_len(prio, tag, (tag && *tag) ? strlen(tag) : 0, \
+                                 ANDROID_LOG_VERBOSE) != 0)
+#endif
+
+#else
+
+#if LOG_NDEBUG /* Production */
+#define android_testLog(prio, tag) \
+  (__android_log_is_loggable(prio, tag, ANDROID_LOG_DEBUG) != 0)
+#else
+#define android_testLog(prio, tag) \
+  (__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE) != 0)
+#endif
+
+#endif
+
+#else /* __ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE */
+
+#define android_testLog(prio, tag) (1)
+
+#endif /* !__ANDROID_USE_LIBLOG_LOGGABLE_INTERFACE */
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_LOG_MAIN_H */
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_radio.h b/liblog/include/log/log_radio.h
new file mode 100644
index 0000000..bd629fe
--- /dev/null
+++ b/liblog/include/log/log_radio.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_RADIO_H
+#define _LIBS_LOG_LOG_RADIO_H
+
+#include <android/log.h>
+#include <log/log_id.h>
+
+/*
+ * Normally we strip the effects of ALOGV (VERBOSE messages),
+ * LOG_FATAL and LOG_FATAL_IF (FATAL assert messages) from the
+ * release builds be defining NDEBUG.  You can modify this (for
+ * example with "#define LOG_NDEBUG 0" at the top of your source
+ * file) to change that behavior.
+ */
+
+#ifndef LOG_NDEBUG
+#ifdef NDEBUG
+#define LOG_NDEBUG 1
+#else
+#define LOG_NDEBUG 0
+#endif
+#endif
+
+/* --------------------------------------------------------------------- */
+
+#ifndef __predict_false
+#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
+#endif
+
+/*
+ * Simplified macro to send a verbose radio log message using current LOG_TAG.
+ */
+#ifndef RLOGV
+#define __RLOGV(...)                                                         \
+  ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, \
+                                 __VA_ARGS__))
+#if LOG_NDEBUG
+#define RLOGV(...)          \
+  do {                      \
+    if (0) {                \
+      __RLOGV(__VA_ARGS__); \
+    }                       \
+  } while (0)
+#else
+#define RLOGV(...) __RLOGV(__VA_ARGS__)
+#endif
+#endif
+
+#ifndef RLOGV_IF
+#if LOG_NDEBUG
+#define RLOGV_IF(cond, ...) ((void)0)
+#else
+#define RLOGV_IF(cond, ...)                                                \
+  ((__predict_false(cond))                                                 \
+       ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, \
+                                        LOG_TAG, __VA_ARGS__))             \
+       : (void)0)
+#endif
+#endif
+
+/*
+ * Simplified macro to send a debug radio log message using  current LOG_TAG.
+ */
+#ifndef RLOGD
+#define RLOGD(...)                                                         \
+  ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef RLOGD_IF
+#define RLOGD_IF(cond, ...)                                              \
+  ((__predict_false(cond))                                               \
+       ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, \
+                                        LOG_TAG, __VA_ARGS__))           \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an info radio log message using  current LOG_TAG.
+ */
+#ifndef RLOGI
+#define RLOGI(...)                                                        \
+  ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef RLOGI_IF
+#define RLOGI_IF(cond, ...)                                             \
+  ((__predict_false(cond))                                              \
+       ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, \
+                                        LOG_TAG, __VA_ARGS__))          \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send a warning radio log message using current LOG_TAG.
+ */
+#ifndef RLOGW
+#define RLOGW(...)                                                        \
+  ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef RLOGW_IF
+#define RLOGW_IF(cond, ...)                                             \
+  ((__predict_false(cond))                                              \
+       ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, \
+                                        LOG_TAG, __VA_ARGS__))          \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an error radio log message using current LOG_TAG.
+ */
+#ifndef RLOGE
+#define RLOGE(...)                                                         \
+  ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef RLOGE_IF
+#define RLOGE_IF(cond, ...)                                              \
+  ((__predict_false(cond))                                               \
+       ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, \
+                                        LOG_TAG, __VA_ARGS__))           \
+       : (void)0)
+#endif
+
+#endif /* _LIBS_LOG_LOG_RADIO_H */
diff --git a/liblog/include/log/log_read.h b/liblog/include/log/log_read.h
new file mode 100644
index 0000000..d118563
--- /dev/null
+++ b/liblog/include/log/log_read.h
@@ -0,0 +1,277 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_READ_H
+#define _LIBS_LOG_LOG_READ_H
+
+/* deal with possible sys/cdefs.h conflict with fcntl.h */
+#ifdef __unused
+#define __unused_defined __unused
+#undef __unused
+#endif
+
+#include <fcntl.h> /* Pick up O_* macros */
+
+/* restore definitions from above */
+#ifdef __unused_defined
+#define __unused __attribute__((__unused__))
+#endif
+
+#include <stdint.h>
+
+#include <log/log_id.h>
+#include <log/log_time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Native log reading interface section. See logcat for sample code.
+ *
+ * The preferred API is an exec of logcat. Likely uses of this interface
+ * are if native code suffers from exec or filtration being too costly,
+ * access to raw information, or parsing is an issue.
+ */
+
+/*
+ * The userspace structure for version 1 of the logger_entry ABI.
+ */
+#ifndef __struct_logger_entry_defined
+#define __struct_logger_entry_defined
+struct logger_entry {
+  uint16_t len;   /* length of the payload */
+  uint16_t __pad; /* no matter what, we get 2 bytes of padding */
+  int32_t pid;    /* generating process's pid */
+  int32_t tid;    /* generating process's tid */
+  int32_t sec;    /* seconds since Epoch */
+  int32_t nsec;   /* nanoseconds */
+#ifndef __cplusplus
+  char msg[0]; /* the entry's payload */
+#endif
+};
+#endif
+
+/*
+ * The userspace structure for version 2 of the logger_entry ABI.
+ */
+#ifndef __struct_logger_entry_v2_defined
+#define __struct_logger_entry_v2_defined
+struct logger_entry_v2 {
+  uint16_t len;      /* length of the payload */
+  uint16_t hdr_size; /* sizeof(struct logger_entry_v2) */
+  int32_t pid;       /* generating process's pid */
+  int32_t tid;       /* generating process's tid */
+  int32_t sec;       /* seconds since Epoch */
+  int32_t nsec;      /* nanoseconds */
+  uint32_t euid;     /* effective UID of logger */
+#ifndef __cplusplus
+  char msg[0]; /* the entry's payload */
+#endif
+} __attribute__((__packed__));
+#endif
+
+/*
+ * The userspace structure for version 3 of the logger_entry ABI.
+ */
+#ifndef __struct_logger_entry_v3_defined
+#define __struct_logger_entry_v3_defined
+struct logger_entry_v3 {
+  uint16_t len;      /* length of the payload */
+  uint16_t hdr_size; /* sizeof(struct logger_entry_v3) */
+  int32_t pid;       /* generating process's pid */
+  int32_t tid;       /* generating process's tid */
+  int32_t sec;       /* seconds since Epoch */
+  int32_t nsec;      /* nanoseconds */
+  uint32_t lid;      /* log id of the payload */
+#ifndef __cplusplus
+  char msg[0]; /* the entry's payload */
+#endif
+} __attribute__((__packed__));
+#endif
+
+/*
+ * The userspace structure for version 4 of the logger_entry ABI.
+ */
+#ifndef __struct_logger_entry_v4_defined
+#define __struct_logger_entry_v4_defined
+struct logger_entry_v4 {
+  uint16_t len;      /* length of the payload */
+  uint16_t hdr_size; /* sizeof(struct logger_entry_v4) */
+  int32_t pid;       /* generating process's pid */
+  uint32_t tid;      /* generating process's tid */
+  uint32_t sec;      /* seconds since Epoch */
+  uint32_t nsec;     /* nanoseconds */
+  uint32_t lid;      /* log id of the payload, bottom 4 bits currently */
+  uint32_t uid;      /* generating process's uid */
+#ifndef __cplusplus
+  char msg[0]; /* the entry's payload */
+#endif
+};
+#endif
+
+/*
+ * The maximum size of the log entry payload that can be
+ * written to the logger. An attempt to write more than
+ * this amount will result in a truncated log entry.
+ */
+#define LOGGER_ENTRY_MAX_PAYLOAD 4068
+
+/*
+ * The maximum size of a log entry which can be read.
+ * An attempt to read less than this amount may result
+ * in read() returning EINVAL.
+ */
+#define LOGGER_ENTRY_MAX_LEN (5 * 1024)
+
+#ifndef __struct_log_msg_defined
+#define __struct_log_msg_defined
+struct log_msg {
+  union {
+    unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1];
+    struct logger_entry_v4 entry;
+    struct logger_entry_v4 entry_v4;
+    struct logger_entry_v3 entry_v3;
+    struct logger_entry_v2 entry_v2;
+    struct logger_entry entry_v1;
+  } __attribute__((aligned(4)));
+#ifdef __cplusplus
+  /* Matching log_time operators */
+  bool operator==(const log_msg& T) const {
+    return (entry.sec == T.entry.sec) && (entry.nsec == T.entry.nsec);
+  }
+  bool operator!=(const log_msg& T) const {
+    return !(*this == T);
+  }
+  bool operator<(const log_msg& T) const {
+    return (entry.sec < T.entry.sec) ||
+           ((entry.sec == T.entry.sec) && (entry.nsec < T.entry.nsec));
+  }
+  bool operator>=(const log_msg& T) const {
+    return !(*this < T);
+  }
+  bool operator>(const log_msg& T) const {
+    return (entry.sec > T.entry.sec) ||
+           ((entry.sec == T.entry.sec) && (entry.nsec > T.entry.nsec));
+  }
+  bool operator<=(const log_msg& T) const {
+    return !(*this > T);
+  }
+  uint64_t nsec() const {
+    return static_cast<uint64_t>(entry.sec) * NS_PER_SEC + entry.nsec;
+  }
+
+  /* packet methods */
+  log_id_t id() {
+    return static_cast<log_id_t>(entry.lid);
+  }
+  char* msg() {
+    unsigned short hdr_size = entry.hdr_size;
+    if (!hdr_size) {
+      hdr_size = sizeof(entry_v1);
+    }
+    if ((hdr_size < sizeof(entry_v1)) || (hdr_size > sizeof(entry))) {
+      return NULL;
+    }
+    return reinterpret_cast<char*>(buf) + hdr_size;
+  }
+  unsigned int len() {
+    return (entry.hdr_size ? entry.hdr_size
+                           : static_cast<uint16_t>(sizeof(entry_v1))) +
+           entry.len;
+  }
+#endif
+};
+#endif
+
+#ifndef __ANDROID_USE_LIBLOG_READER_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_READER_INTERFACE 3
+#elif __ANDROID_API__ > 23 /* > Marshmallow */
+#define __ANDROID_USE_LIBLOG_READER_INTERFACE 3
+#elif __ANDROID_API__ > 22 /* > Lollipop */
+#define __ANDROID_USE_LIBLOG_READER_INTERFACE 2
+#elif __ANDROID_API__ > 19 /* > KitKat */
+#define __ANDROID_USE_LIBLOG_READER_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_READER_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_READER_INTERFACE
+
+struct logger;
+
+log_id_t android_logger_get_id(struct logger* logger);
+
+int android_logger_clear(struct logger* logger);
+long android_logger_get_log_size(struct logger* logger);
+int android_logger_set_log_size(struct logger* logger, unsigned long size);
+long android_logger_get_log_readable_size(struct logger* logger);
+int android_logger_get_log_version(struct logger* logger);
+
+struct logger_list;
+
+#if __ANDROID_USE_LIBLOG_READER_INTERFACE > 1
+ssize_t android_logger_get_statistics(struct logger_list* logger_list,
+                                      char* buf, size_t len);
+ssize_t android_logger_get_prune_list(struct logger_list* logger_list,
+                                      char* buf, size_t len);
+int android_logger_set_prune_list(struct logger_list* logger_list, char* buf,
+                                  size_t len);
+#endif
+
+#define ANDROID_LOG_RDONLY O_RDONLY
+#define ANDROID_LOG_WRONLY O_WRONLY
+#define ANDROID_LOG_RDWR O_RDWR
+#define ANDROID_LOG_ACCMODE O_ACCMODE
+#ifndef O_NONBLOCK
+#define ANDROID_LOG_NONBLOCK 0x00000800
+#else
+#define ANDROID_LOG_NONBLOCK O_NONBLOCK
+#endif
+#if __ANDROID_USE_LIBLOG_READER_INTERFACE > 2
+#define ANDROID_LOG_WRAP 0x40000000 /* Block until buffer about to wrap */
+#define ANDROID_LOG_WRAP_DEFAULT_TIMEOUT 7200 /* 2 hour default */
+#endif
+#if __ANDROID_USE_LIBLOG_READER_INTERFACE > 1
+#define ANDROID_LOG_PSTORE 0x80000000
+#endif
+
+struct logger_list* android_logger_list_alloc(int mode, unsigned int tail,
+                                              pid_t pid);
+struct logger_list* android_logger_list_alloc_time(int mode, log_time start,
+                                                   pid_t pid);
+void android_logger_list_free(struct logger_list* logger_list);
+/* In the purest sense, the following two are orthogonal interfaces */
+int android_logger_list_read(struct logger_list* logger_list,
+                             struct log_msg* log_msg);
+
+/* Multiple log_id_t opens */
+struct logger* android_logger_open(struct logger_list* logger_list, log_id_t id);
+#define android_logger_close android_logger_free
+/* Single log_id_t open */
+struct logger_list* android_logger_list_open(log_id_t id, int mode,
+                                             unsigned int tail, pid_t pid);
+#define android_logger_list_close android_logger_list_free
+
+#endif /* __ANDROID_USE_LIBLOG_READER_INTERFACE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_LOG_H */
diff --git a/liblog/include/log/log_system.h b/liblog/include/log/log_system.h
new file mode 100644
index 0000000..3b5ae22
--- /dev/null
+++ b/liblog/include/log/log_system.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_SYSTEM_H
+#define _LIBS_LOG_LOG_SYSTEM_H
+
+#include <android/log.h>
+#include <log/log_id.h>
+
+/*
+ * Normally we strip the effects of ALOGV (VERBOSE messages),
+ * LOG_FATAL and LOG_FATAL_IF (FATAL assert messages) from the
+ * release builds be defining NDEBUG.  You can modify this (for
+ * example with "#define LOG_NDEBUG 0" at the top of your source
+ * file) to change that behavior.
+ */
+
+#ifndef LOG_NDEBUG
+#ifdef NDEBUG
+#define LOG_NDEBUG 1
+#else
+#define LOG_NDEBUG 0
+#endif
+#endif
+
+#ifndef __predict_false
+#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
+#endif
+
+/*
+ * Simplified macro to send a verbose system log message using current LOG_TAG.
+ */
+#ifndef SLOGV
+#define __SLOGV(...)                                                          \
+  ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, \
+                                 __VA_ARGS__))
+#if LOG_NDEBUG
+#define SLOGV(...)          \
+  do {                      \
+    if (0) {                \
+      __SLOGV(__VA_ARGS__); \
+    }                       \
+  } while (0)
+#else
+#define SLOGV(...) __SLOGV(__VA_ARGS__)
+#endif
+#endif
+
+#ifndef SLOGV_IF
+#if LOG_NDEBUG
+#define SLOGV_IF(cond, ...) ((void)0)
+#else
+#define SLOGV_IF(cond, ...)                                                 \
+  ((__predict_false(cond))                                                  \
+       ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, \
+                                        LOG_TAG, __VA_ARGS__))              \
+       : (void)0)
+#endif
+#endif
+
+/*
+ * Simplified macro to send a debug system log message using current LOG_TAG.
+ */
+#ifndef SLOGD
+#define SLOGD(...)                                                          \
+  ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef SLOGD_IF
+#define SLOGD_IF(cond, ...)                                               \
+  ((__predict_false(cond))                                                \
+       ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, \
+                                        LOG_TAG, __VA_ARGS__))            \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an info system log message using current LOG_TAG.
+ */
+#ifndef SLOGI
+#define SLOGI(...)                                                         \
+  ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef SLOGI_IF
+#define SLOGI_IF(cond, ...)                                              \
+  ((__predict_false(cond))                                               \
+       ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, \
+                                        LOG_TAG, __VA_ARGS__))           \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send a warning system log message using current LOG_TAG.
+ */
+#ifndef SLOGW
+#define SLOGW(...)                                                         \
+  ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef SLOGW_IF
+#define SLOGW_IF(cond, ...)                                              \
+  ((__predict_false(cond))                                               \
+       ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, \
+                                        LOG_TAG, __VA_ARGS__))           \
+       : (void)0)
+#endif
+
+/*
+ * Simplified macro to send an error system log message using current LOG_TAG.
+ */
+#ifndef SLOGE
+#define SLOGE(...)                                                          \
+  ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, \
+                                 __VA_ARGS__))
+#endif
+
+#ifndef SLOGE_IF
+#define SLOGE_IF(cond, ...)                                               \
+  ((__predict_false(cond))                                                \
+       ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, \
+                                        LOG_TAG, __VA_ARGS__))            \
+       : (void)0)
+#endif
+
+#endif /* _LIBS_LOG_LOG_SYSTEM_H */
diff --git a/liblog/include/log/log_time.h b/liblog/include/log/log_time.h
new file mode 100644
index 0000000..9ece0b3
--- /dev/null
+++ b/liblog/include/log/log_time.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOG_LOG_TIME_H
+#define _LIBS_LOG_LOG_TIME_H
+
+#include <stdint.h>
+#include <time.h>
+
+/* struct log_time is a wire-format variant of struct timespec */
+#define NS_PER_SEC 1000000000ULL
+
+#ifndef __struct_log_time_defined
+#define __struct_log_time_defined
+
+#ifdef __cplusplus
+
+/*
+ * NB: we did NOT define a copy constructor. This will result in structure
+ * no longer being compatible with pass-by-value which is desired
+ * efficient behavior. Also, pass-by-reference breaks C/C++ ABI.
+ */
+struct log_time {
+ public:
+  uint32_t tv_sec; /* good to Feb 5 2106 */
+  uint32_t tv_nsec;
+
+  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)) {
+  }
+  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
+  static const timespec EPOCH;
+#endif
+  log_time() {
+  }
+#ifdef __linux__
+  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
+  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) |
+             (static_cast<uint32_t>(c[3]) << 24);
+    tv_nsec = c[4] | (static_cast<uint32_t>(c[5]) << 8) |
+              (static_cast<uint32_t>(c[6]) << 16) |
+              (static_cast<uint32_t>(c[7]) << 24);
+  }
+
+  /* timespec */
+  bool operator==(const timespec& T) const {
+    return (tv_sec == static_cast<uint32_t>(T.tv_sec)) &&
+           (tv_nsec == static_cast<uint32_t>(T.tv_nsec));
+  }
+  bool operator!=(const timespec& T) const {
+    return !(*this == T);
+  }
+  bool operator<(const timespec& T) const {
+    return (tv_sec < static_cast<uint32_t>(T.tv_sec)) ||
+           ((tv_sec == static_cast<uint32_t>(T.tv_sec)) &&
+            (tv_nsec < static_cast<uint32_t>(T.tv_nsec)));
+  }
+  bool operator>=(const timespec& T) const {
+    return !(*this < T);
+  }
+  bool operator>(const timespec& T) const {
+    return (tv_sec > static_cast<uint32_t>(T.tv_sec)) ||
+           ((tv_sec == static_cast<uint32_t>(T.tv_sec)) &&
+            (tv_nsec > static_cast<uint32_t>(T.tv_nsec)));
+  }
+  bool operator<=(const timespec& T) const {
+    return !(*this > T);
+  }
+
+#ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+  log_time operator-=(const timespec& T);
+  log_time operator-(const timespec& T) const {
+    log_time local(*this);
+    return local -= T;
+  }
+  log_time operator+=(const timespec& T);
+  log_time operator+(const timespec& T) const {
+    log_time local(*this);
+    return local += T;
+  }
+#endif
+
+  /* log_time */
+  bool operator==(const log_time& T) const {
+    return (tv_sec == T.tv_sec) && (tv_nsec == T.tv_nsec);
+  }
+  bool operator!=(const log_time& T) const {
+    return !(*this == T);
+  }
+  bool operator<(const log_time& T) const {
+    return (tv_sec < T.tv_sec) ||
+           ((tv_sec == T.tv_sec) && (tv_nsec < T.tv_nsec));
+  }
+  bool operator>=(const log_time& T) const {
+    return !(*this < T);
+  }
+  bool operator>(const log_time& T) const {
+    return (tv_sec > T.tv_sec) ||
+           ((tv_sec == T.tv_sec) && (tv_nsec > T.tv_nsec));
+  }
+  bool operator<=(const log_time& T) const {
+    return !(*this > T);
+  }
+
+#ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+  log_time operator-=(const log_time& T);
+  log_time operator-(const log_time& T) const {
+    log_time local(*this);
+    return local -= T;
+  }
+  log_time operator+=(const log_time& T);
+  log_time operator+(const log_time& T) const {
+    log_time local(*this);
+    return local += T;
+  }
+#endif
+
+  uint64_t nsec() const {
+    return static_cast<uint64_t>(tv_sec) * NS_PER_SEC + tv_nsec;
+  }
+
+#ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+  static const char default_format[];
+
+  /* Add %#q for the fraction of a second to the standard library functions */
+  char* strptime(const char* s, const char* format = default_format);
+#endif
+} __attribute__((__packed__));
+
+#else
+
+typedef struct log_time {
+  uint32_t tv_sec;
+  uint32_t tv_nsec;
+} __attribute__((__packed__)) log_time;
+
+#endif
+
+#endif
+
+#endif /* _LIBS_LOG_LOG_TIME_H */
diff --git a/liblog/include/log/log_transport.h b/liblog/include/log/log_transport.h
new file mode 100644
index 0000000..80b30db
--- /dev/null
+++ b/liblog/include/log/log_transport.h
@@ -0,0 +1,37 @@
+/*
+**
+** 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_TRANSPORT_H
+#define _LIBS_LOG_TRANSPORT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Logging transports, bit mask to select features. Function returns selection.
+ */
+/* clang-format off */
+#define LOGGER_DEFAULT 0x00
+#define LOGGER_LOGD    0x01
+#define LOGGER_KERNEL  0x02 /* Reserved/Deprecated */
+#define LOGGER_NULL    0x04 /* Does not release resources of other selections */
+#define LOGGER_LOCAL   0x08 /* logs sent to local memory */
+#define LOGGER_STDERR  0x10 /* logs sent to stderr */
+/* clang-format on */
+
+/* Both return the selected transport flag mask, or negative errno */
+int android_set_log_transport(int transport_flag);
+int android_get_log_transport();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_TRANSPORT_H */
diff --git a/liblog/include/log/logd.h b/liblog/include/log/logd.h
new file mode 100644
index 0000000..77400ca
--- /dev/null
+++ b/liblog/include/log/logd.h
@@ -0,0 +1,5 @@
+#ifndef _LIBS_LOG_LOGD_H
+#define _LIBS_LOG_LOGD_H
+#include <log/log.h>
+#warning "Deprecated: do not include log/logd.h, use log/log.h instead"
+#endif /*_LIBS_LOG_LOGD_H*/
diff --git a/liblog/include/log/logger.h b/liblog/include/log/logger.h
new file mode 100644
index 0000000..1bf2d17
--- /dev/null
+++ b/liblog/include/log/logger.h
@@ -0,0 +1,5 @@
+#ifndef _LIBS_LOG_LOGGER_H
+#define _LIBS_LOG_LOGGER_H
+#include <log/log.h>
+#warning "Deprecated: do not include log/logger.h, use log/log.h instead"
+#endif /*_LIBS_LOG_LOGGER_H*/
diff --git a/liblog/include/log/logprint.h b/liblog/include/log/logprint.h
new file mode 100644
index 0000000..ca58bc7
--- /dev/null
+++ b/liblog/include/log/logprint.h
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef _LOGPRINT_H
+#define _LOGPRINT_H
+
+#include <pthread.h>
+
+#include <android/log.h>
+#include <log/event_tag_map.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+  /* Verbs */
+  FORMAT_OFF = 0,
+  FORMAT_BRIEF,
+  FORMAT_PROCESS,
+  FORMAT_TAG,
+  FORMAT_THREAD,
+  FORMAT_RAW,
+  FORMAT_TIME,
+  FORMAT_THREADTIME,
+  FORMAT_LONG,
+  /* Adverbs. The following are modifiers to above format verbs */
+  FORMAT_MODIFIER_COLOR,     /* converts priority to color */
+  FORMAT_MODIFIER_TIME_USEC, /* switches from msec to usec time precision */
+  FORMAT_MODIFIER_PRINTABLE, /* converts non-printable to printable escapes */
+  FORMAT_MODIFIER_YEAR,      /* Adds year to date */
+  FORMAT_MODIFIER_ZONE,      /* Adds zone to date, + UTC */
+  FORMAT_MODIFIER_EPOCH,     /* Print time as seconds since Jan 1 1970 */
+  FORMAT_MODIFIER_MONOTONIC, /* Print cpu time as seconds since start */
+  FORMAT_MODIFIER_UID,       /* Adds uid */
+  FORMAT_MODIFIER_DESCRIPT,  /* Adds descriptive */
+  /* private, undocumented */
+  FORMAT_MODIFIER_TIME_NSEC, /* switches from msec to nsec time precision */
+} AndroidLogPrintFormat;
+
+typedef struct AndroidLogFormat_t AndroidLogFormat;
+
+typedef struct AndroidLogEntry_t {
+  time_t tv_sec;
+  long tv_nsec;
+  android_LogPriority priority;
+  int32_t uid;
+  int32_t pid;
+  int32_t tid;
+  const char* tag;
+  size_t tagLen;
+  size_t messageLen;
+  const char* message;
+} AndroidLogEntry;
+
+AndroidLogFormat* android_log_format_new();
+
+void android_log_format_free(AndroidLogFormat* p_format);
+
+/* currently returns 0 if format is a modifier, 1 if not */
+int android_log_setPrintFormat(AndroidLogFormat* p_format,
+                               AndroidLogPrintFormat format);
+
+/**
+ * Returns FORMAT_OFF on invalid string
+ */
+AndroidLogPrintFormat android_log_formatFromString(const char* s);
+
+/**
+ * filterExpression: a single filter expression
+ * eg "AT:d"
+ *
+ * returns 0 on success and -1 on invalid expression
+ *
+ * Assumes single threaded execution
+ *
+ */
+
+int android_log_addFilterRule(AndroidLogFormat* p_format,
+                              const char* filterExpression);
+
+/**
+ * filterString: a whitespace-separated set of filter expressions
+ * eg "AT:d *:i"
+ *
+ * returns 0 on success and -1 on invalid expression
+ *
+ * Assumes single threaded execution
+ *
+ */
+
+int android_log_addFilterString(AndroidLogFormat* p_format,
+                                const char* filterString);
+
+/**
+ * returns 1 if this log line should be printed based on its priority
+ * and tag, and 0 if it should not
+ */
+int android_log_shouldPrintLine(AndroidLogFormat* p_format, const char* tag,
+                                android_LogPriority pri);
+
+/**
+ * Splits a wire-format buffer into an AndroidLogEntry
+ * entry allocated by caller. Pointers will point directly into buf
+ *
+ * Returns 0 on success and -1 on invalid wire format (entry will be
+ * in unspecified state)
+ */
+int android_log_processLogBuffer(struct logger_entry* buf,
+                                 AndroidLogEntry* entry);
+
+/**
+ * Like android_log_processLogBuffer, but for binary logs.
+ *
+ * If "map" is non-NULL, it will be used to convert the log tag number
+ * into a string.
+ */
+int android_log_processBinaryLogBuffer(struct logger_entry* buf,
+                                       AndroidLogEntry* entry,
+                                       const EventTagMap* map, char* messageBuf,
+                                       int messageBufLen);
+
+/**
+ * Formats a log message into a buffer
+ *
+ * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
+ * If return value != defaultBuffer, caller must call free()
+ * Returns NULL on malloc error
+ */
+
+char* android_log_formatLogLine(AndroidLogFormat* p_format, char* defaultBuffer,
+                                size_t defaultBufferSize,
+                                const AndroidLogEntry* p_line,
+                                size_t* p_outLength);
+
+/**
+ * Either print or do not print log line, based on filter
+ *
+ * Assumes single threaded execution
+ *
+ */
+int android_log_printLogLine(AndroidLogFormat* p_format, int fd,
+                             const AndroidLogEntry* entry);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /*_LOGPRINT_H*/
diff --git a/liblog/include/log/uio.h b/liblog/include/log/uio.h
new file mode 100644
index 0000000..a492bae
--- /dev/null
+++ b/liblog/include/log/uio.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2007-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 _LIBS_CUTILS_UIO_H
+#define _LIBS_CUTILS_UIO_H
+
+#if !defined(_WIN32)
+
+#include <sys/uio.h>
+
+#else
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//
+// Implementation of sys/uio.h for Win32.
+//
+
+#include <stddef.h>
+
+struct iovec {
+  void* iov_base;
+  size_t iov_len;
+};
+
+extern int readv(int fd, struct iovec* vecs, int count);
+extern int writev(int fd, const struct iovec* vecs, int count);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#endif /* _LIBS_UTILS_UIO_H */
diff --git a/liblog/include/private/android_logger.h b/liblog/include/private/android_logger.h
new file mode 100644
index 0000000..965de37
--- /dev/null
+++ b/liblog/include/private/android_logger.h
@@ -0,0 +1,193 @@
+/*
+ * 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.
+ */
+
+/* This file is used to define the internal protocol for the Android Logger */
+
+#ifndef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+#define _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+
+/* Android private interfaces */
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#if (defined(__cplusplus) && defined(_USING_LIBCXX))
+extern "C++" {
+#include <string>
+}
+#endif
+
+#include <log/log.h>
+#include <log/log_event_list.h>
+
+#define LOGGER_MAGIC 'l'
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/* Header Structure to pstore */
+typedef struct __attribute__((__packed__)) {
+  uint8_t magic;
+  uint16_t len;
+  uint16_t uid;
+  uint16_t pid;
+} android_pmsg_log_header_t;
+
+/* Header Structure to logd, and second header for pstore */
+typedef struct __attribute__((__packed__)) {
+  typeof_log_id_t id;
+  uint16_t tid;
+  log_time realtime;
+} android_log_header_t;
+
+/* Event Header Structure to logd */
+typedef struct __attribute__((__packed__)) {
+  int32_t tag;  // Little Endian Order
+} android_event_header_t;
+
+/* Event payload EVENT_TYPE_INT */
+typedef struct __attribute__((__packed__)) {
+  int8_t type;   // EVENT_TYPE_INT
+  int32_t data;  // Little Endian Order
+} android_event_int_t;
+
+/* Event with single EVENT_TYPE_INT */
+typedef struct __attribute__((__packed__)) {
+  android_event_header_t header;
+  android_event_int_t payload;
+} android_log_event_int_t;
+
+/* Event payload EVENT_TYPE_LONG */
+typedef struct __attribute__((__packed__)) {
+  int8_t type;   // EVENT_TYPE_LONG
+  int64_t data;  // Little Endian Order
+} android_event_long_t;
+
+/* Event with single EVENT_TYPE_LONG */
+typedef struct __attribute__((__packed__)) {
+  android_event_header_t header;
+  android_event_long_t payload;
+} android_log_event_long_t;
+
+/*
+ * Event payload EVENT_TYPE_STRING
+ *
+ * Danger: do not embed this structure into another structure.
+ * This structure uses a flexible array member, and when
+ * compiled using g++, __builtin_object_size(data, 1) returns
+ * a bad value. This is possibly a g++ bug, or a bug due to
+ * the fact that flexible array members are not supported
+ * in C++.
+ * http://stackoverflow.com/questions/4412749/are-flexible-array-members-valid-in-c
+ */
+
+typedef struct __attribute__((__packed__)) {
+  int8_t type;     // EVENT_TYPE_STRING;
+  int32_t length;  // Little Endian Order
+  char data[];
+} android_event_string_t;
+
+/* Event with single EVENT_TYPE_STRING */
+typedef struct __attribute__((__packed__)) {
+  android_event_header_t header;
+  int8_t type;     // EVENT_TYPE_STRING;
+  int32_t length;  // Little Endian Order
+  char data[];
+} android_log_event_string_t;
+
+#define ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE 256 /* 1MB file */
+#define ANDROID_LOG_PMSG_FILE_SEQUENCE 1000
+
+ssize_t __android_log_pmsg_file_write(log_id_t logId, char prio,
+                                      const char* filename, const char* buf,
+                                      size_t len);
+
+#define LOG_ID_ANY ((log_id_t)-1)
+#define ANDROID_LOG_ANY ANDROID_LOG_UNKNOWN
+
+/* first 5 arguments match __android_log_msg_file_write, a cast is safe */
+typedef ssize_t (*__android_log_pmsg_file_read_fn)(log_id_t logId, char prio,
+                                                   const char* filename,
+                                                   const char* buf, size_t len,
+                                                   void* arg);
+
+ssize_t __android_log_pmsg_file_read(log_id_t logId, char prio,
+                                     const char* prefix,
+                                     __android_log_pmsg_file_read_fn fn,
+                                     void* arg);
+
+int __android_log_security_bwrite(int32_t tag, const void* payload, size_t len);
+int __android_log_security_bswrite(int32_t tag, const char* payload);
+int __android_log_security(); /* Device Owner is present */
+
+#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    */
+#define BOOL_DEFAULT_FLAG_PERSIST 0x2 /* <key>, persist.<key>, ro.<key>  */
+#define BOOL_DEFAULT_FLAG_ENG 0x4     /* off for user                    */
+#define BOOL_DEFAULT_FLAG_SVELTE 0x8  /* off for low_ram                 */
+bool __android_logger_property_get_bool(const char* key, int flag);
+
+#define LOG_BUFFER_SIZE (256 * 1024) /* Tuned with ro.logd.size per-platform \
+                                      */
+#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
+#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
+unsigned long __android_logger_get_buffer_size(log_id_t logId);
+bool __android_logger_valid_buffer_size(unsigned long value);
+
+/* Retrieve the composed event buffer */
+int android_log_write_list_buffer(android_log_context ctx, const char** msg);
+
+#ifdef __cplusplus
+#ifdef __class_android_log_event_list_defined
+#ifndef __class_android_log_event_list_private_defined
+#define __class_android_log_event_list_private_defined
+/* android_log_context C++ helpers */
+extern "C++" {
+class __android_log_event_list : public android_log_event_list {
+  __android_log_event_list(const android_log_event_list&) = delete;
+  void operator=(const __android_log_event_list&) = delete;
+
+ public:
+  explicit __android_log_event_list(int tag) : android_log_event_list(tag) {
+  }
+  explicit __android_log_event_list(log_msg& log_msg)
+      : android_log_event_list(log_msg) {
+  }
+
+#if defined(_USING_LIBCXX)
+  operator std::string() {
+    if (ret) return std::string("");
+    const char* cp = NULL;
+    ssize_t len = android_log_write_list_buffer(ctx, &cp);
+    if (len < 0) ret = len;
+    if (!cp || (len <= 0)) return std::string("");
+    return std::string(cp, len);
+  }
+#endif
+};
+}
+#endif
+#endif
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_ */
diff --git a/liblog/include_vndk/android b/liblog/include_vndk/android
new file mode 120000
index 0000000..a3c0320
--- /dev/null
+++ b/liblog/include_vndk/android
@@ -0,0 +1 @@
+../include/android
\ No newline at end of file
diff --git a/liblog/include_vndk/log/log.h b/liblog/include_vndk/log/log.h
new file mode 100644
index 0000000..f93b377
--- /dev/null
+++ b/liblog/include_vndk/log/log.h
@@ -0,0 +1,23 @@
+/*Special log.h file for VNDK linking modules*/
+
+#ifndef _LIBS_LOG_LOG_H
+#define _LIBS_LOG_LOG_H
+
+#include <android/log.h>
+#include <log/log_id.h>
+#include <log/log_main.h>
+#include <log/log_radio.h>
+#include <log/log_read.h>
+#include <log/log_time.h>
+
+/*
+ * LOG_TAG is the local tag used for the following simplified
+ * logging macros.  You can change this preprocessor definition
+ * before using the other macros to change the tag.
+ */
+
+#ifndef LOG_TAG
+#define LOG_TAG NULL
+#endif
+
+#endif /*_LIBS_LOG_LOG_H*/
diff --git a/liblog/include_vndk/log/log_id.h b/liblog/include_vndk/log/log_id.h
new file mode 120000
index 0000000..dce92b9
--- /dev/null
+++ b/liblog/include_vndk/log/log_id.h
@@ -0,0 +1 @@
+../../include/log/log_id.h
\ No newline at end of file
diff --git a/liblog/include_vndk/log/log_main.h b/liblog/include_vndk/log/log_main.h
new file mode 120000
index 0000000..f2ec018
--- /dev/null
+++ b/liblog/include_vndk/log/log_main.h
@@ -0,0 +1 @@
+../../include/log/log_main.h
\ No newline at end of file
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_radio.h b/liblog/include_vndk/log/log_radio.h
new file mode 120000
index 0000000..1e12b32
--- /dev/null
+++ b/liblog/include_vndk/log/log_radio.h
@@ -0,0 +1 @@
+../../include/log/log_radio.h
\ No newline at end of file
diff --git a/liblog/include_vndk/log/log_read.h b/liblog/include_vndk/log/log_read.h
new file mode 120000
index 0000000..01de8b9
--- /dev/null
+++ b/liblog/include_vndk/log/log_read.h
@@ -0,0 +1 @@
+../../include/log/log_read.h
\ No newline at end of file
diff --git a/liblog/include_vndk/log/log_time.h b/liblog/include_vndk/log/log_time.h
new file mode 120000
index 0000000..abfe439
--- /dev/null
+++ b/liblog/include_vndk/log/log_time.h
@@ -0,0 +1 @@
+../../include/log/log_time.h
\ No newline at end of file
diff --git a/liblog/liblog.map.txt b/liblog/liblog.map.txt
new file mode 100644
index 0000000..58fb148
--- /dev/null
+++ b/liblog/liblog.map.txt
@@ -0,0 +1,43 @@
+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;
+  local:
+    *;
+};
+
+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_is_loggable;
+};
+
+LIBLOG_O {
+  global:
+    __android_log_is_loggable_len;
+    __android_log_is_debuggable; # vndk
+};
diff --git a/liblog/local_logger.c b/liblog/local_logger.c
new file mode 100644
index 0000000..522867d
--- /dev/null
+++ b/liblog/local_logger.c
@@ -0,0 +1,549 @@
+/*
+ * 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 <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#if !defined(__MINGW32__)
+#include <pwd.h>
+#endif
+#include <log/uio.h>
+#include <sched.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+
+#include <cutils/list.h> /* template, no library dependency */
+#include <log/log_transport.h>
+#include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
+#include <system/thread_defs.h>
+
+#include "config_read.h"
+#include "config_write.h"
+#include "log_portability.h"
+#include "logger.h"
+
+static const char baseServiceName[] = "android.logd";
+
+static int writeToLocalInit();
+static int writeToLocalAvailable(log_id_t logId);
+static void writeToLocalReset();
+static int writeToLocalWrite(log_id_t logId, struct timespec* ts,
+                             struct iovec* vec, size_t nr);
+
+LIBLOG_HIDDEN struct android_log_transport_write localLoggerWrite = {
+  .node = { &localLoggerWrite.node, &localLoggerWrite.node },
+  .context.priv = NULL,
+  .name = "local",
+  .available = writeToLocalAvailable,
+  .open = writeToLocalInit,
+  .close = writeToLocalReset,
+  .write = writeToLocalWrite,
+};
+
+static int writeToLocalVersion(struct android_log_logger* logger,
+                               struct android_log_transport_context* transp);
+static int writeToLocalRead(struct android_log_logger_list* logger_list,
+                            struct android_log_transport_context* transp,
+                            struct log_msg* log_msg);
+static int writeToLocalPoll(struct android_log_logger_list* logger_list,
+                            struct android_log_transport_context* transp);
+static void writeToLocalClose(struct android_log_logger_list* logger_list,
+                              struct android_log_transport_context* transp);
+static int writeToLocalClear(struct android_log_logger* logger,
+                             struct android_log_transport_context* transp);
+static ssize_t writeToLocalGetSize(struct android_log_logger* logger,
+                                   struct android_log_transport_context* transp);
+static ssize_t writeToLocalSetSize(
+    struct android_log_logger* logger,
+    struct android_log_transport_context* transp __unused, size_t size);
+static ssize_t writeToLocalGetReadbleSize(
+    struct android_log_logger* logger,
+    struct android_log_transport_context* transp);
+
+struct android_log_transport_read localLoggerRead = {
+  .node = { &localLoggerRead.node, &localLoggerRead.node },
+  .name = "local",
+  .available = writeToLocalAvailable,
+  .version = writeToLocalVersion,
+  .read = writeToLocalRead,
+  .poll = writeToLocalPoll,
+  .close = writeToLocalClose,
+  .clear = writeToLocalClear,
+  .getSize = writeToLocalGetSize,
+  .setSize = writeToLocalSetSize,
+  .getReadableSize = writeToLocalGetReadbleSize,
+  .getPrune = NULL,
+  .setPrune = NULL,
+  .getStats = NULL,
+};
+
+struct LogBufferElement {
+  struct listnode node;
+  log_id_t logId;
+  pid_t tid;
+  log_time timestamp;
+  unsigned short len;
+  char msg[];
+};
+
+static const size_t MAX_SIZE_DEFAULT = 32768;
+
+/*
+ * Number of log buffers we support with the following assumption:
+ *  . . .
+ *   LOG_ID_SECURITY = 5, // security logs go to the system logs only
+ *   LOG_ID_KERNEL = 6,   // place last, third-parties can not use it
+ *   LOG_ID_MAX
+ * } log_id_t;
+ *
+ * Confirm the following should <log/log_id.h> be adjusted in the future.
+ */
+#define NUMBER_OF_LOG_BUFFERS \
+  ((LOG_ID_SECURITY == (LOG_ID_MAX - 2)) ? LOG_ID_SECURITY : LOG_ID_KERNEL)
+#define BLOCK_LOG_BUFFERS(id) \
+  (((id) == LOG_ID_SECURITY) || ((id) == LOG_ID_KERNEL))
+
+static struct LogBuffer {
+  struct listnode head;
+  pthread_rwlock_t listLock;
+  char* serviceName; /* Also indicates ready by having a value */
+  /* Order and proximity important for memset */
+  size_t number[NUMBER_OF_LOG_BUFFERS];         /* clear memset          */
+  size_t size[NUMBER_OF_LOG_BUFFERS];           /* clear memset          */
+  size_t totalSize[NUMBER_OF_LOG_BUFFERS];      /* init memset           */
+  size_t maxSize[NUMBER_OF_LOG_BUFFERS];        /* init MAX_SIZE_DEFAULT */
+  struct listnode* last[NUMBER_OF_LOG_BUFFERS]; /* init &head            */
+} logbuf = {
+  .head = { &logbuf.head, &logbuf.head }, .listLock = PTHREAD_RWLOCK_INITIALIZER,
+};
+
+static void LogBufferInit(struct LogBuffer* log) {
+  size_t i;
+
+  pthread_rwlock_wrlock(&log->listLock);
+  list_init(&log->head);
+  memset(log->number, 0,
+         sizeof(log->number) + sizeof(log->size) + sizeof(log->totalSize));
+  for (i = 0; i < NUMBER_OF_LOG_BUFFERS; ++i) {
+    log->maxSize[i] = MAX_SIZE_DEFAULT;
+    log->last[i] = &log->head;
+  }
+#ifdef __BIONIC__
+  asprintf(&log->serviceName, "%s@%d:%d", baseServiceName, __android_log_uid(),
+           getpid());
+#else
+  char buffer[sizeof(baseServiceName) + 1 + 5 + 1 + 5 + 8];
+  snprintf(buffer, sizeof(buffer), "%s@%d:%d", baseServiceName,
+           __android_log_uid(), getpid());
+  log->serviceName = strdup(buffer);
+#endif
+  pthread_rwlock_unlock(&log->listLock);
+}
+
+static void LogBufferClear(struct LogBuffer* log) {
+  size_t i;
+  struct listnode* node;
+
+  pthread_rwlock_wrlock(&log->listLock);
+  memset(log->number, 0, sizeof(log->number) + sizeof(log->size));
+  for (i = 0; i < NUMBER_OF_LOG_BUFFERS; ++i) {
+    log->last[i] = &log->head;
+  }
+  while ((node = list_head(&log->head)) != &log->head) {
+    struct LogBufferElement* element;
+
+    element = node_to_item(node, struct LogBufferElement, node);
+    list_remove(node);
+    free(element);
+  }
+  pthread_rwlock_unlock(&log->listLock);
+}
+
+static inline void LogBufferFree(struct LogBuffer* log) {
+  pthread_rwlock_wrlock(&log->listLock);
+  free(log->serviceName);
+  log->serviceName = NULL;
+  pthread_rwlock_unlock(&log->listLock);
+  LogBufferClear(log);
+}
+
+static int LogBufferLog(struct LogBuffer* log,
+                        struct LogBufferElement* element) {
+  log_id_t logId = element->logId;
+
+  pthread_rwlock_wrlock(&log->listLock);
+  log->number[logId]++;
+  log->size[logId] += element->len;
+  log->totalSize[logId] += element->len;
+  /* prune entry(s) until enough space is available */
+  if (log->last[logId] == &log->head) {
+    log->last[logId] = list_tail(&log->head);
+  }
+  while (log->size[logId] > log->maxSize[logId]) {
+    struct listnode* node = log->last[logId];
+    struct LogBufferElement* e;
+    struct android_log_logger_list* logger_list;
+
+    e = node_to_item(node, struct LogBufferElement, node);
+    log->number[logId]--;
+    log->size[logId] -= e->len;
+    logger_list_rdlock();
+    logger_list_for_each(logger_list) {
+      struct android_log_transport_context* transp;
+
+      transport_context_for_each(transp, logger_list) {
+        if ((transp->transport == &localLoggerRead) &&
+            (transp->context.node == node)) {
+          if (node == &log->head) {
+            transp->context.node = &log->head;
+          } else {
+            transp->context.node = node->next;
+          }
+        }
+      }
+    }
+    logger_list_unlock();
+    if (node != &log->head) {
+      log->last[logId] = node->prev;
+    }
+    list_remove(node);
+    free(e);
+  }
+  /* add entry to list */
+  list_add_head(&log->head, &element->node);
+  /* ToDo: wake up all readers */
+  pthread_rwlock_unlock(&log->listLock);
+
+  return element->len;
+}
+
+/*
+ * return zero if permitted to log directly to logd,
+ * return 1 if binder server started and
+ * return negative error number if failed to start binder server.
+ */
+static int writeToLocalInit() {
+  pthread_attr_t attr;
+  struct LogBuffer* log;
+
+  if (writeToLocalAvailable(LOG_ID_MAIN) < 0) {
+    return -EPERM;
+  }
+
+  log = &logbuf;
+  if (!log->serviceName) {
+    LogBufferInit(log);
+  }
+
+  if (!log->serviceName) {
+    LogBufferFree(log);
+    return -ENOMEM;
+  }
+
+  return EPERM; /* successful local-only logging */
+}
+
+static void writeToLocalReset() {
+  LogBufferFree(&logbuf);
+}
+
+static int writeToLocalAvailable(log_id_t logId) {
+#if !defined(__MINGW32__)
+  uid_t uid;
+#endif
+
+  if ((logId >= NUMBER_OF_LOG_BUFFERS) || BLOCK_LOG_BUFFERS(logId)) {
+    return -EINVAL;
+  }
+
+/* Android hard coded permitted, system goes to logd */
+#if !defined(__MINGW32__)
+  if (__android_log_transport == LOGGER_DEFAULT) {
+    uid = __android_log_uid();
+    if ((uid < AID_APP) && (getpwuid(uid) != NULL)) {
+      return -EPERM;
+    }
+  }
+#endif
+
+  /* ToDo: Ask package manager for LOGD permissions */
+  /* Assume we do _not_ have permissions to go to LOGD, so must go local */
+  return 0;
+}
+
+static int writeToLocalWrite(log_id_t logId, struct timespec* ts,
+                             struct iovec* vec, size_t nr) {
+  size_t len, i;
+  struct LogBufferElement* element;
+
+  if ((logId >= NUMBER_OF_LOG_BUFFERS) || BLOCK_LOG_BUFFERS(logId)) {
+    return -EINVAL;
+  }
+
+  len = 0;
+  for (i = 0; i < nr; ++i) {
+    len += vec[i].iov_len;
+  }
+
+  if (len > LOGGER_ENTRY_MAX_PAYLOAD) {
+    len = LOGGER_ENTRY_MAX_PAYLOAD;
+  }
+  element = (struct LogBufferElement*)calloc(
+      1, sizeof(struct LogBufferElement) + len + 1);
+  if (!element) {
+    return errno ? -errno : -ENOMEM;
+  }
+  element->timestamp.tv_sec = ts->tv_sec;
+  element->timestamp.tv_nsec = ts->tv_nsec;
+#ifdef __BIONIC__
+  element->tid = gettid();
+#else
+  element->tid = getpid();
+#endif
+  element->logId = logId;
+  element->len = len;
+
+  char* cp = element->msg;
+  for (i = 0; i < nr; ++i) {
+    size_t iov_len = vec[i].iov_len;
+    if (iov_len > len) {
+      iov_len = len;
+    }
+    memcpy(cp, vec[i].iov_base, iov_len);
+    len -= iov_len;
+    if (len == 0) {
+      break;
+    }
+    cp += iov_len;
+  }
+
+  return LogBufferLog(&logbuf, element);
+}
+
+static int writeToLocalVersion(struct android_log_logger* logger __unused,
+                               struct android_log_transport_context* transp
+                                   __unused) {
+  return 3;
+}
+
+/* within reader lock, serviceName already validated */
+static struct listnode* writeToLocalNode(
+    struct android_log_logger_list* logger_list,
+    struct android_log_transport_context* transp) {
+  struct listnode* node;
+  unsigned logMask;
+  unsigned int tail;
+
+  node = transp->context.node;
+  if (node) {
+    return node;
+  }
+
+  if (!logger_list->tail) {
+    return transp->context.node = &logbuf.head;
+  }
+
+  logMask = transp->logMask;
+  tail = logger_list->tail;
+
+  for (node = list_head(&logbuf.head); node != &logbuf.head; node = node->next) {
+    struct LogBufferElement* element;
+    log_id_t logId;
+
+    element = node_to_item(node, struct LogBufferElement, node);
+    logId = element->logId;
+
+    if ((logMask & (1 << logId)) && !--tail) {
+      node = node->next;
+      break;
+    }
+  }
+  return transp->context.node = node;
+}
+
+static int writeToLocalRead(struct android_log_logger_list* logger_list,
+                            struct android_log_transport_context* transp,
+                            struct log_msg* log_msg) {
+  int ret;
+  struct listnode* node;
+  unsigned logMask;
+
+  pthread_rwlock_rdlock(&logbuf.listLock);
+  if (!logbuf.serviceName) {
+    pthread_rwlock_unlock(&logbuf.listLock);
+    return (logger_list->mode & ANDROID_LOG_NONBLOCK) ? -ENODEV : 0;
+  }
+
+  logMask = transp->logMask;
+
+  node = writeToLocalNode(logger_list, transp);
+
+  ret = 0;
+
+  while (node != list_head(&logbuf.head)) {
+    struct LogBufferElement* element;
+    log_id_t logId;
+
+    node = node->prev;
+    element = node_to_item(node, struct LogBufferElement, node);
+    logId = element->logId;
+
+    if (logMask & (1 << logId)) {
+      ret = log_msg->entry_v3.len = element->len;
+      log_msg->entry_v3.hdr_size = sizeof(log_msg->entry_v3);
+      log_msg->entry_v3.pid = getpid();
+      log_msg->entry_v3.tid = element->tid;
+      log_msg->entry_v3.sec = element->timestamp.tv_sec;
+      log_msg->entry_v3.nsec = element->timestamp.tv_nsec;
+      log_msg->entry_v3.lid = logId;
+      memcpy(log_msg->entry_v3.msg, element->msg, ret);
+      ret += log_msg->entry_v3.hdr_size;
+      break;
+    }
+  }
+
+  transp->context.node = node;
+
+  /* ToDo: if blocking, and no entry, put reader to sleep */
+  pthread_rwlock_unlock(&logbuf.listLock);
+  return ret;
+}
+
+static int writeToLocalPoll(struct android_log_logger_list* logger_list,
+                            struct android_log_transport_context* transp) {
+  int ret = (logger_list->mode & ANDROID_LOG_NONBLOCK) ? -ENODEV : 0;
+
+  pthread_rwlock_rdlock(&logbuf.listLock);
+
+  if (logbuf.serviceName) {
+    unsigned logMask = transp->logMask;
+    struct listnode* node = writeToLocalNode(logger_list, transp);
+
+    ret = (node != list_head(&logbuf.head));
+    if (ret) {
+      do {
+        ret = !!(logMask &
+                 (1 << (node_to_item(node->prev, struct LogBufferElement, node))
+                           ->logId));
+      } while (!ret && ((node = node->prev) != list_head(&logbuf.head)));
+    }
+
+    transp->context.node = node;
+  }
+
+  pthread_rwlock_unlock(&logbuf.listLock);
+
+  return ret;
+}
+
+static void writeToLocalClose(struct android_log_logger_list* logger_list
+                                  __unused,
+                              struct android_log_transport_context* transp) {
+  pthread_rwlock_wrlock(&logbuf.listLock);
+  transp->context.node = list_head(&logbuf.head);
+  pthread_rwlock_unlock(&logbuf.listLock);
+}
+
+static int writeToLocalClear(struct android_log_logger* logger,
+                             struct android_log_transport_context* unused
+                                 __unused) {
+  log_id_t logId = logger->logId;
+  struct listnode *node, *n;
+
+  if ((logId >= NUMBER_OF_LOG_BUFFERS) || BLOCK_LOG_BUFFERS(logId)) {
+    return -EINVAL;
+  }
+
+  pthread_rwlock_wrlock(&logbuf.listLock);
+  logbuf.number[logId] = 0;
+  logbuf.last[logId] = &logbuf.head;
+  list_for_each_safe(node, n, &logbuf.head) {
+    struct LogBufferElement* element;
+    element = node_to_item(node, struct LogBufferElement, node);
+
+    if (logId == element->logId) {
+      struct android_log_logger_list* logger_list;
+
+      logger_list_rdlock();
+      logger_list_for_each(logger_list) {
+        struct android_log_transport_context* transp;
+
+        transport_context_for_each(transp, logger_list) {
+          if ((transp->transport == &localLoggerRead) &&
+              (transp->context.node == node)) {
+            transp->context.node = node->next;
+          }
+        }
+      }
+      logger_list_unlock();
+      list_remove(node);
+      free(element);
+    }
+  }
+
+  pthread_rwlock_unlock(&logbuf.listLock);
+
+  return 0;
+}
+
+static ssize_t writeToLocalGetSize(struct android_log_logger* logger,
+                                   struct android_log_transport_context* transp
+                                       __unused) {
+  ssize_t ret = -EINVAL;
+  log_id_t logId = logger->logId;
+
+  if ((logId < NUMBER_OF_LOG_BUFFERS) && !BLOCK_LOG_BUFFERS(logId)) {
+    pthread_rwlock_rdlock(&logbuf.listLock);
+    ret = logbuf.maxSize[logId];
+    pthread_rwlock_unlock(&logbuf.listLock);
+  }
+
+  return ret;
+}
+
+static ssize_t writeToLocalSetSize(
+    struct android_log_logger* logger,
+    struct android_log_transport_context* transp __unused, size_t size) {
+  ssize_t ret = -EINVAL;
+
+  if ((size > LOGGER_ENTRY_MAX_LEN) || (size < (4 * 1024 * 1024))) {
+    log_id_t logId = logger->logId;
+    if ((logId < NUMBER_OF_LOG_BUFFERS) || !BLOCK_LOG_BUFFERS(logId)) {
+      pthread_rwlock_wrlock(&logbuf.listLock);
+      ret = logbuf.maxSize[logId] = size;
+      pthread_rwlock_unlock(&logbuf.listLock);
+    }
+  }
+
+  return ret;
+}
+
+static ssize_t writeToLocalGetReadbleSize(
+    struct android_log_logger* logger,
+    struct android_log_transport_context* transp __unused) {
+  ssize_t ret = -EINVAL;
+  log_id_t logId = logger->logId;
+
+  if ((logId < NUMBER_OF_LOG_BUFFERS) && !BLOCK_LOG_BUFFERS(logId)) {
+    pthread_rwlock_rdlock(&logbuf.listLock);
+    ret = logbuf.serviceName ? (ssize_t)logbuf.size[logId] : -EBADF;
+    pthread_rwlock_unlock(&logbuf.listLock);
+  }
+
+  return ret;
+}
diff --git a/liblog/log_event_list.c b/liblog/log_event_list.c
index 64d9024..59ea5ef 100644
--- a/liblog/log_event_list.c
+++ b/liblog/log_event_list.c
@@ -22,278 +22,274 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <log/log.h>
-#include <log/logger.h>
+#include <log/log_event_list.h>
+#include <private/android_logger.h>
 
 #include "log_portability.h"
 
 #define MAX_EVENT_PAYLOAD (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(int32_t))
 
 typedef struct {
-    uint32_t tag;
-    unsigned pos; /* Read/write position into buffer */
-    unsigned count[ANDROID_MAX_LIST_NEST_DEPTH + 1]; /* Number of elements   */
-    unsigned list[ANDROID_MAX_LIST_NEST_DEPTH + 1];  /* pos for list counter */
-    unsigned list_nest_depth;
-    unsigned len; /* Length or raw buffer. */
-    bool overflow;
-    bool list_stop; /* next call decrement list_nest_depth and issue a stop */
-    enum {
-        kAndroidLoggerRead = 1,
-        kAndroidLoggerWrite = 2,
-    } read_write_flag;
-    uint8_t storage[LOGGER_ENTRY_MAX_PAYLOAD];
+  uint32_t tag;
+  unsigned pos; /* Read/write position into buffer */
+  unsigned count[ANDROID_MAX_LIST_NEST_DEPTH + 1]; /* Number of elements   */
+  unsigned list[ANDROID_MAX_LIST_NEST_DEPTH + 1];  /* pos for list counter */
+  unsigned list_nest_depth;
+  unsigned len; /* Length or raw buffer. */
+  bool overflow;
+  bool list_stop; /* next call decrement list_nest_depth and issue a stop */
+  enum {
+    kAndroidLoggerRead = 1,
+    kAndroidLoggerWrite = 2,
+  } read_write_flag;
+  uint8_t storage[LOGGER_ENTRY_MAX_PAYLOAD];
 } android_log_context_internal;
 
 LIBLOG_ABI_PUBLIC android_log_context create_android_logger(uint32_t tag) {
-    size_t needed, i;
-    android_log_context_internal *context;
+  size_t needed, i;
+  android_log_context_internal* context;
 
-    context = calloc(1, sizeof(android_log_context_internal));
-    if (!context) {
-        return NULL;
-    }
-    context->tag = tag;
-    context->read_write_flag = kAndroidLoggerWrite;
-    needed = sizeof(uint8_t) + sizeof(uint8_t);
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        context->overflow = true;
-    }
-    /* Everything is a list */
-    context->storage[context->pos + 0] = EVENT_TYPE_LIST;
-    context->list[0] = context->pos + 1;
-    context->pos += needed;
+  context = calloc(1, sizeof(android_log_context_internal));
+  if (!context) {
+    return NULL;
+  }
+  context->tag = tag;
+  context->read_write_flag = kAndroidLoggerWrite;
+  needed = sizeof(uint8_t) + sizeof(uint8_t);
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    context->overflow = true;
+  }
+  /* Everything is a list */
+  context->storage[context->pos + 0] = EVENT_TYPE_LIST;
+  context->list[0] = context->pos + 1;
+  context->pos += needed;
 
-    return (android_log_context)context;
+  return (android_log_context)context;
 }
 
-LIBLOG_ABI_PUBLIC android_log_context create_android_log_parser(
-        const char *msg,
-        size_t len) {
-    android_log_context_internal *context;
-    size_t i;
+LIBLOG_ABI_PUBLIC android_log_context create_android_log_parser(const char* msg,
+                                                                size_t len) {
+  android_log_context_internal* context;
+  size_t i;
 
-    context = calloc(1, sizeof(android_log_context_internal));
-    if (!context) {
-        return NULL;
-    }
-    len = (len <= MAX_EVENT_PAYLOAD) ? len : MAX_EVENT_PAYLOAD;
-    context->len = len;
-    memcpy(context->storage, msg, len);
-    context->read_write_flag = kAndroidLoggerRead;
+  context = calloc(1, sizeof(android_log_context_internal));
+  if (!context) {
+    return NULL;
+  }
+  len = (len <= MAX_EVENT_PAYLOAD) ? len : MAX_EVENT_PAYLOAD;
+  context->len = len;
+  memcpy(context->storage, msg, len);
+  context->read_write_flag = kAndroidLoggerRead;
 
-    return (android_log_context)context;
+  return (android_log_context)context;
 }
 
-LIBLOG_ABI_PUBLIC int android_log_destroy(android_log_context *ctx) {
-    android_log_context_internal *context;
+LIBLOG_ABI_PUBLIC int android_log_destroy(android_log_context* ctx) {
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)*ctx;
-    if (!context) {
-        return -EBADF;
-    }
-    memset(context, 0, sizeof(*context));
-    free(context);
-    *ctx = NULL;
-    return 0;
+  context = (android_log_context_internal*)*ctx;
+  if (!context) {
+    return -EBADF;
+  }
+  memset(context, 0, sizeof(*context));
+  free(context);
+  *ctx = NULL;
+  return 0;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_list_begin(android_log_context ctx) {
-    size_t needed;
-    android_log_context_internal *context;
+  size_t needed;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context ||
-            (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
-    }
-    if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
-        context->overflow = true;
-        return -EOVERFLOW;
-    }
-    needed = sizeof(uint8_t) + sizeof(uint8_t);
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        context->overflow = true;
-        return -EIO;
-    }
-    context->count[context->list_nest_depth]++;
-    context->list_nest_depth++;
-    if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
-        context->overflow = true;
-        return -EOVERFLOW;
-    }
-    if (context->overflow) {
-        return -EIO;
-    }
-    context->storage[context->pos + 0] = EVENT_TYPE_LIST;
-    context->storage[context->pos + 1] = 0;
-    context->list[context->list_nest_depth] = context->pos + 1;
-    context->count[context->list_nest_depth] = 0;
-    context->pos += needed;
-    return 0;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
+    context->overflow = true;
+    return -EOVERFLOW;
+  }
+  needed = sizeof(uint8_t) + sizeof(uint8_t);
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    context->overflow = true;
+    return -EIO;
+  }
+  context->count[context->list_nest_depth]++;
+  context->list_nest_depth++;
+  if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
+    context->overflow = true;
+    return -EOVERFLOW;
+  }
+  if (context->overflow) {
+    return -EIO;
+  }
+  context->storage[context->pos + 0] = EVENT_TYPE_LIST;
+  context->storage[context->pos + 1] = 0;
+  context->list[context->list_nest_depth] = context->pos + 1;
+  context->count[context->list_nest_depth] = 0;
+  context->pos += needed;
+  return 0;
 }
 
-static inline void copy4LE(uint8_t *buf, uint32_t val)
-{
-    buf[0] = val & 0xFF;
-    buf[1] = (val >> 8) & 0xFF;
-    buf[2] = (val >> 16) & 0xFF;
-    buf[3] = (val >> 24) & 0xFF;
+static inline void copy4LE(uint8_t* buf, uint32_t val) {
+  buf[0] = val & 0xFF;
+  buf[1] = (val >> 8) & 0xFF;
+  buf[2] = (val >> 16) & 0xFF;
+  buf[3] = (val >> 24) & 0xFF;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_int32(android_log_context ctx,
                                               int32_t value) {
-    size_t needed;
-    android_log_context_internal *context;
+  size_t needed;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
-    }
-    if (context->overflow) {
-        return -EIO;
-    }
-    needed = sizeof(uint8_t) + sizeof(value);
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        context->overflow = true;
-        return -EIO;
-    }
-    context->count[context->list_nest_depth]++;
-    context->storage[context->pos + 0] = EVENT_TYPE_INT;
-    copy4LE(&context->storage[context->pos + 1], value);
-    context->pos += needed;
-    return 0;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->overflow) {
+    return -EIO;
+  }
+  needed = sizeof(uint8_t) + sizeof(value);
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    context->overflow = true;
+    return -EIO;
+  }
+  context->count[context->list_nest_depth]++;
+  context->storage[context->pos + 0] = EVENT_TYPE_INT;
+  copy4LE(&context->storage[context->pos + 1], value);
+  context->pos += needed;
+  return 0;
 }
 
-static inline void copy8LE(uint8_t *buf, uint64_t val)
-{
-    buf[0] = val & 0xFF;
-    buf[1] = (val >> 8) & 0xFF;
-    buf[2] = (val >> 16) & 0xFF;
-    buf[3] = (val >> 24) & 0xFF;
-    buf[4] = (val >> 32) & 0xFF;
-    buf[5] = (val >> 40) & 0xFF;
-    buf[6] = (val >> 48) & 0xFF;
-    buf[7] = (val >> 56) & 0xFF;
+static inline void copy8LE(uint8_t* buf, uint64_t val) {
+  buf[0] = val & 0xFF;
+  buf[1] = (val >> 8) & 0xFF;
+  buf[2] = (val >> 16) & 0xFF;
+  buf[3] = (val >> 24) & 0xFF;
+  buf[4] = (val >> 32) & 0xFF;
+  buf[5] = (val >> 40) & 0xFF;
+  buf[6] = (val >> 48) & 0xFF;
+  buf[7] = (val >> 56) & 0xFF;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_int64(android_log_context ctx,
                                               int64_t value) {
-    size_t needed;
-    android_log_context_internal *context;
+  size_t needed;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
-    }
-    if (context->overflow) {
-        return -EIO;
-    }
-    needed = sizeof(uint8_t) + sizeof(value);
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        context->overflow = true;
-        return -EIO;
-    }
-    context->count[context->list_nest_depth]++;
-    context->storage[context->pos + 0] = EVENT_TYPE_LONG;
-    copy8LE(&context->storage[context->pos + 1], value);
-    context->pos += needed;
-    return 0;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->overflow) {
+    return -EIO;
+  }
+  needed = sizeof(uint8_t) + sizeof(value);
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    context->overflow = true;
+    return -EIO;
+  }
+  context->count[context->list_nest_depth]++;
+  context->storage[context->pos + 0] = EVENT_TYPE_LONG;
+  copy8LE(&context->storage[context->pos + 1], value);
+  context->pos += needed;
+  return 0;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_string8_len(android_log_context ctx,
-                                                    const char *value,
+                                                    const char* value,
                                                     size_t maxlen) {
-    size_t needed;
-    ssize_t len;
-    android_log_context_internal *context;
+  size_t needed;
+  ssize_t len;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->overflow) {
+    return -EIO;
+  }
+  if (!value) {
+    value = "";
+  }
+  len = strnlen(value, maxlen);
+  needed = sizeof(uint8_t) + sizeof(int32_t) + len;
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    /* Truncate string for delivery */
+    len = MAX_EVENT_PAYLOAD - context->pos - 1 - sizeof(int32_t);
+    if (len <= 0) {
+      context->overflow = true;
+      return -EIO;
     }
-    if (context->overflow) {
-        return -EIO;
-    }
-    if (!value) {
-        value = "";
-    }
-    len = strnlen(value, maxlen);
-    needed = sizeof(uint8_t) + sizeof(int32_t) + len;
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        /* Truncate string for delivery */
-        len = MAX_EVENT_PAYLOAD - context->pos - 1 - sizeof(int32_t);
-        if (len <= 0) {
-            context->overflow = true;
-            return -EIO;
-        }
-    }
-    context->count[context->list_nest_depth]++;
-    context->storage[context->pos + 0] = EVENT_TYPE_STRING;
-    copy4LE(&context->storage[context->pos + 1], len);
-    if (len) {
-        memcpy(&context->storage[context->pos + 5], value, len);
-    }
-    context->pos += needed;
-    return len;
+  }
+  context->count[context->list_nest_depth]++;
+  context->storage[context->pos + 0] = EVENT_TYPE_STRING;
+  copy4LE(&context->storage[context->pos + 1], len);
+  if (len) {
+    memcpy(&context->storage[context->pos + 5], value, len);
+  }
+  context->pos += needed;
+  return len;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_string8(android_log_context ctx,
-                                                const char *value) {
-    return android_log_write_string8_len(ctx, value, MAX_EVENT_PAYLOAD);
+                                                const char* value) {
+  return android_log_write_string8_len(ctx, value, MAX_EVENT_PAYLOAD);
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_float32(android_log_context ctx,
                                                 float value) {
-    size_t needed;
-    uint32_t ivalue;
-    android_log_context_internal *context;
+  size_t needed;
+  uint32_t ivalue;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
-    }
-    if (context->overflow) {
-        return -EIO;
-    }
-    needed = sizeof(uint8_t) + sizeof(ivalue);
-    if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
-        context->overflow = true;
-        return -EIO;
-    }
-    ivalue = *(uint32_t *)&value;
-    context->count[context->list_nest_depth]++;
-    context->storage[context->pos + 0] = EVENT_TYPE_FLOAT;
-    copy4LE(&context->storage[context->pos + 1], ivalue);
-    context->pos += needed;
-    return 0;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->overflow) {
+    return -EIO;
+  }
+  needed = sizeof(uint8_t) + sizeof(ivalue);
+  if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
+    context->overflow = true;
+    return -EIO;
+  }
+  ivalue = *(uint32_t*)&value;
+  context->count[context->list_nest_depth]++;
+  context->storage[context->pos + 0] = EVENT_TYPE_FLOAT;
+  copy4LE(&context->storage[context->pos + 1], ivalue);
+  context->pos += needed;
+  return 0;
 }
 
 LIBLOG_ABI_PUBLIC int android_log_write_list_end(android_log_context ctx) {
-    android_log_context_internal *context;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
-    }
-    if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
-        context->overflow = true;
-        context->list_nest_depth--;
-        return -EOVERFLOW;
-    }
-    if (!context->list_nest_depth) {
-        context->overflow = true;
-        return -EOVERFLOW;
-    }
-    if (context->list[context->list_nest_depth] <= 0) {
-        context->list_nest_depth--;
-        context->overflow = true;
-        return -EOVERFLOW;
-    }
-    context->storage[context->list[context->list_nest_depth]] =
-        context->count[context->list_nest_depth];
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) {
+    context->overflow = true;
     context->list_nest_depth--;
-    return 0;
+    return -EOVERFLOW;
+  }
+  if (!context->list_nest_depth) {
+    context->overflow = true;
+    return -EOVERFLOW;
+  }
+  if (context->list[context->list_nest_depth] <= 0) {
+    context->list_nest_depth--;
+    context->overflow = true;
+    return -EOVERFLOW;
+  }
+  context->storage[context->list[context->list_nest_depth]] =
+      context->count[context->list_nest_depth];
+  context->list_nest_depth--;
+  return 0;
 }
 
 /*
@@ -301,54 +297,84 @@
  */
 LIBLOG_ABI_PUBLIC int android_log_write_list(android_log_context ctx,
                                              log_id_t id) {
-    android_log_context_internal *context;
-    const char *msg;
-    ssize_t len;
+  android_log_context_internal* context;
+  const char* msg;
+  ssize_t len;
 
-    if ((id != LOG_ID_EVENTS) && (id != LOG_ID_SECURITY)) {
-        return -EINVAL;
-    }
+  if ((id != LOG_ID_EVENTS) && (id != LOG_ID_SECURITY)) {
+    return -EINVAL;
+  }
 
-    context = (android_log_context_internal *)ctx;
-    if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
-        return -EBADF;
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->list_nest_depth) {
+    return -EIO;
+  }
+  /* NB: if there was overflow, then log is truncated. Nothing reported */
+  context->storage[1] = context->count[0];
+  len = context->len = context->pos;
+  msg = (const char*)context->storage;
+  /* it's not a list */
+  if (context->count[0] <= 1) {
+    len -= sizeof(uint8_t) + sizeof(uint8_t);
+    if (len < 0) {
+      len = 0;
     }
-    if (context->list_nest_depth) {
-        return -EIO;
+    msg += sizeof(uint8_t) + sizeof(uint8_t);
+  }
+  return (id == LOG_ID_EVENTS)
+             ? __android_log_bwrite(context->tag, msg, len)
+             : __android_log_security_bwrite(context->tag, msg, len);
+}
+
+LIBLOG_ABI_PRIVATE int android_log_write_list_buffer(android_log_context ctx,
+                                                     const char** buffer) {
+  android_log_context_internal* context;
+  const char* msg;
+  ssize_t len;
+
+  context = (android_log_context_internal*)ctx;
+  if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
+    return -EBADF;
+  }
+  if (context->list_nest_depth) {
+    return -EIO;
+  }
+  if (buffer == NULL) {
+    return -EFAULT;
+  }
+  /* NB: if there was overflow, then log is truncated. Nothing reported */
+  context->storage[1] = context->count[0];
+  len = context->len = context->pos;
+  msg = (const char*)context->storage;
+  /* it's not a list */
+  if (context->count[0] <= 1) {
+    len -= sizeof(uint8_t) + sizeof(uint8_t);
+    if (len < 0) {
+      len = 0;
     }
-    /* NB: if there was overflow, then log is truncated. Nothing reported */
-    context->storage[1] = context->count[0];
-    len = context->len = context->pos;
-    msg = (const char *)context->storage;
-    /* it'snot a list */
-    if (context->count[0] <= 1) {
-        len -= sizeof(uint8_t) + sizeof(uint8_t);
-        if (len < 0) {
-            len = 0;
-        }
-        msg += sizeof(uint8_t) + sizeof(uint8_t);
-    }
-    return (id == LOG_ID_EVENTS) ?
-        __android_log_bwrite(context->tag, msg, len) :
-        __android_log_security_bwrite(context->tag, msg, len);
+    msg += sizeof(uint8_t) + sizeof(uint8_t);
+  }
+  *buffer = msg;
+  return len;
 }
 
 /*
  * Extract a 4-byte value from a byte stream.
  */
-static inline uint32_t get4LE(const uint8_t* src)
-{
-    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+static inline uint32_t get4LE(const uint8_t* src) {
+  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
 
 /*
  * Extract an 8-byte value from a byte stream.
  */
-static inline uint64_t get8LE(const uint8_t* src)
-{
-    uint32_t low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
-    uint32_t high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
-    return ((uint64_t) high << 32) | (uint64_t) low;
+static inline uint64_t get8LE(const uint8_t* src) {
+  uint32_t low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+  uint32_t high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
+  return ((uint64_t)high << 32) | (uint64_t)low;
 }
 
 /*
@@ -359,181 +385,181 @@
  * (although it won't crash).
  */
 static android_log_list_element android_log_read_next_internal(
-        android_log_context ctx, int peek) {
-    android_log_list_element elem;
-    unsigned pos;
-    android_log_context_internal *context;
+    android_log_context ctx, int peek) {
+  android_log_list_element elem;
+  unsigned pos;
+  android_log_context_internal* context;
 
-    context = (android_log_context_internal *)ctx;
+  context = (android_log_context_internal*)ctx;
 
-    memset(&elem, 0, sizeof(elem));
+  memset(&elem, 0, sizeof(elem));
 
-    /* Nothing to parse from this context, so return complete. */
-    if (!context || (kAndroidLoggerRead != context->read_write_flag) ||
-            (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) ||
-            (context->count[context->list_nest_depth] >=
-                (MAX_EVENT_PAYLOAD / (sizeof(uint8_t) + sizeof(uint8_t))))) {
-        elem.type = EVENT_TYPE_UNKNOWN;
-        if (context &&
-                (context->list_stop ||
-                ((context->list_nest_depth <= ANDROID_MAX_LIST_NEST_DEPTH) &&
-                    !context->count[context->list_nest_depth]))) {
-            elem.type = EVENT_TYPE_LIST_STOP;
+  /* Nothing to parse from this context, so return complete. */
+  if (!context || (kAndroidLoggerRead != context->read_write_flag) ||
+      (context->list_nest_depth > ANDROID_MAX_LIST_NEST_DEPTH) ||
+      (context->count[context->list_nest_depth] >=
+       (MAX_EVENT_PAYLOAD / (sizeof(uint8_t) + sizeof(uint8_t))))) {
+    elem.type = EVENT_TYPE_UNKNOWN;
+    if (context && (context->list_stop ||
+                    ((context->list_nest_depth <= ANDROID_MAX_LIST_NEST_DEPTH) &&
+                     !context->count[context->list_nest_depth]))) {
+      elem.type = EVENT_TYPE_LIST_STOP;
+    }
+    elem.complete = true;
+    return elem;
+  }
+
+  /*
+   * Use a different variable to update the position in case this
+   * operation is a "peek".
+   */
+  pos = context->pos;
+  if (context->list_stop) {
+    elem.type = EVENT_TYPE_LIST_STOP;
+    elem.complete = !context->count[0] &&
+                    (!context->list_nest_depth ||
+                     ((context->list_nest_depth == 1) && !context->count[1]));
+    if (!peek) {
+      /* Suck in superfluous stop */
+      if (context->storage[pos] == EVENT_TYPE_LIST_STOP) {
+        context->pos = pos + 1;
+      }
+      if (context->list_nest_depth) {
+        --context->list_nest_depth;
+        if (context->count[context->list_nest_depth]) {
+          context->list_stop = false;
         }
-        elem.complete = true;
-        return elem;
+      } else {
+        context->list_stop = false;
+      }
     }
+    return elem;
+  }
+  if ((pos + 1) > context->len) {
+    elem.type = EVENT_TYPE_UNKNOWN;
+    elem.complete = true;
+    return elem;
+  }
 
-    /*
-     * Use a different variable to update the position in case this
-     * operation is a "peek".
-     */
-    pos = context->pos;
-    if (context->list_stop) {
-        elem.type = EVENT_TYPE_LIST_STOP;
-        elem.complete = !context->count[0] && (!context->list_nest_depth ||
-            ((context->list_nest_depth == 1) && !context->count[1]));
-        if (!peek) {
-            /* Suck in superfluous stop */
-            if (context->storage[pos] == EVENT_TYPE_LIST_STOP) {
-                context->pos = pos + 1;
-            }
-            if (context->list_nest_depth) {
-                --context->list_nest_depth;
-                if (context->count[context->list_nest_depth]) {
-                    context->list_stop = false;
-                }
-            } else {
-                context->list_stop = false;
-            }
-        }
-        return elem;
-    }
-    if ((pos + 1) > context->len) {
-        elem.type = EVENT_TYPE_UNKNOWN;
-        elem.complete = true;
-        return elem;
-    }
-
-    elem.type = context->storage[pos++];
-    switch ((int)elem.type) {
+  elem.type = context->storage[pos++];
+  switch ((int)elem.type) {
     case EVENT_TYPE_FLOAT:
-        /* Rely on union to translate elem.data.int32 into elem.data.float32 */
-        /* FALLTHRU */
+    /* Rely on union to translate elem.data.int32 into elem.data.float32 */
+    /* FALLTHRU */
     case EVENT_TYPE_INT:
-        elem.len = sizeof(int32_t);
-        if ((pos + elem.len) > context->len) {
-            elem.type = EVENT_TYPE_UNKNOWN;
-            return elem;
-        }
-        elem.data.int32 = get4LE(&context->storage[pos]);
-        /* common tangeable object suffix */
-        pos += elem.len;
-        elem.complete = !context->list_nest_depth && !context->count[0];
-        if (!peek) {
-            if (!context->count[context->list_nest_depth] ||
-                    !--(context->count[context->list_nest_depth])) {
-                context->list_stop = true;
-            }
-            context->pos = pos;
-        }
+      elem.len = sizeof(int32_t);
+      if ((pos + elem.len) > context->len) {
+        elem.type = EVENT_TYPE_UNKNOWN;
         return elem;
+      }
+      elem.data.int32 = get4LE(&context->storage[pos]);
+      /* common tangeable object suffix */
+      pos += elem.len;
+      elem.complete = !context->list_nest_depth && !context->count[0];
+      if (!peek) {
+        if (!context->count[context->list_nest_depth] ||
+            !--(context->count[context->list_nest_depth])) {
+          context->list_stop = true;
+        }
+        context->pos = pos;
+      }
+      return elem;
 
     case EVENT_TYPE_LONG:
-        elem.len = sizeof(int64_t);
-        if ((pos + elem.len) > context->len) {
-            elem.type = EVENT_TYPE_UNKNOWN;
-            return elem;
-        }
-        elem.data.int64 = get8LE(&context->storage[pos]);
-        /* common tangeable object suffix */
-        pos += elem.len;
-        elem.complete = !context->list_nest_depth && !context->count[0];
-        if (!peek) {
-            if (!context->count[context->list_nest_depth] ||
-                    !--(context->count[context->list_nest_depth])) {
-                context->list_stop = true;
-            }
-            context->pos = pos;
-        }
+      elem.len = sizeof(int64_t);
+      if ((pos + elem.len) > context->len) {
+        elem.type = EVENT_TYPE_UNKNOWN;
         return elem;
+      }
+      elem.data.int64 = get8LE(&context->storage[pos]);
+      /* common tangeable object suffix */
+      pos += elem.len;
+      elem.complete = !context->list_nest_depth && !context->count[0];
+      if (!peek) {
+        if (!context->count[context->list_nest_depth] ||
+            !--(context->count[context->list_nest_depth])) {
+          context->list_stop = true;
+        }
+        context->pos = pos;
+      }
+      return elem;
 
     case EVENT_TYPE_STRING:
-        if ((pos + sizeof(int32_t)) > context->len) {
-            elem.type = EVENT_TYPE_UNKNOWN;
-            elem.complete = true;
-            return elem;
-        }
-        elem.len = get4LE(&context->storage[pos]);
-        pos += sizeof(int32_t);
-        if ((pos + elem.len) > context->len) {
-            elem.len = context->len - pos; /* truncate string */
-            elem.complete = true;
-            if (!elem.len) {
-                elem.type = EVENT_TYPE_UNKNOWN;
-                return elem;
-            }
-        }
-        elem.data.string = (char *)&context->storage[pos];
-        /* common tangeable object suffix */
-        pos += elem.len;
-        elem.complete = !context->list_nest_depth && !context->count[0];
-        if (!peek) {
-            if (!context->count[context->list_nest_depth] ||
-                    !--(context->count[context->list_nest_depth])) {
-                context->list_stop = true;
-            }
-            context->pos = pos;
-        }
+      if ((pos + sizeof(int32_t)) > context->len) {
+        elem.type = EVENT_TYPE_UNKNOWN;
+        elem.complete = true;
         return elem;
+      }
+      elem.len = get4LE(&context->storage[pos]);
+      pos += sizeof(int32_t);
+      if ((pos + elem.len) > context->len) {
+        elem.len = context->len - pos; /* truncate string */
+        elem.complete = true;
+        if (!elem.len) {
+          elem.type = EVENT_TYPE_UNKNOWN;
+          return elem;
+        }
+      }
+      elem.data.string = (char*)&context->storage[pos];
+      /* common tangeable object suffix */
+      pos += elem.len;
+      elem.complete = !context->list_nest_depth && !context->count[0];
+      if (!peek) {
+        if (!context->count[context->list_nest_depth] ||
+            !--(context->count[context->list_nest_depth])) {
+          context->list_stop = true;
+        }
+        context->pos = pos;
+      }
+      return elem;
 
     case EVENT_TYPE_LIST:
-        if ((pos + sizeof(uint8_t)) > context->len) {
-            elem.type = EVENT_TYPE_UNKNOWN;
-            elem.complete = true;
-            return elem;
-        }
-        elem.complete = context->list_nest_depth >= ANDROID_MAX_LIST_NEST_DEPTH;
-        if (peek) {
-            return elem;
-        }
-        if (context->count[context->list_nest_depth]) {
-            context->count[context->list_nest_depth]--;
-        }
-        context->list_stop = !context->storage[pos];
-        context->list_nest_depth++;
-        if (context->list_nest_depth <= ANDROID_MAX_LIST_NEST_DEPTH) {
-            context->count[context->list_nest_depth] = context->storage[pos];
-        }
-        context->pos = pos + sizeof(uint8_t);
+      if ((pos + sizeof(uint8_t)) > context->len) {
+        elem.type = EVENT_TYPE_UNKNOWN;
+        elem.complete = true;
         return elem;
+      }
+      elem.complete = context->list_nest_depth >= ANDROID_MAX_LIST_NEST_DEPTH;
+      if (peek) {
+        return elem;
+      }
+      if (context->count[context->list_nest_depth]) {
+        context->count[context->list_nest_depth]--;
+      }
+      context->list_stop = !context->storage[pos];
+      context->list_nest_depth++;
+      if (context->list_nest_depth <= ANDROID_MAX_LIST_NEST_DEPTH) {
+        context->count[context->list_nest_depth] = context->storage[pos];
+      }
+      context->pos = pos + sizeof(uint8_t);
+      return elem;
 
     case EVENT_TYPE_LIST_STOP: /* Suprise Newline terminates lists. */
+      if (!peek) {
+        context->pos = pos;
+      }
+      elem.type = EVENT_TYPE_UNKNOWN;
+      elem.complete = !context->list_nest_depth;
+      if (context->list_nest_depth > 0) {
+        elem.type = EVENT_TYPE_LIST_STOP;
         if (!peek) {
-            context->pos = pos;
+          context->list_nest_depth--;
         }
-        elem.type = EVENT_TYPE_UNKNOWN;
-        elem.complete = !context->list_nest_depth;
-        if (context->list_nest_depth > 0) {
-            elem.type = EVENT_TYPE_LIST_STOP;
-            if (!peek) {
-                context->list_nest_depth--;
-            }
-        }
-        return elem;
+      }
+      return elem;
 
     default:
-        elem.type = EVENT_TYPE_UNKNOWN;
-        return elem;
-    }
+      elem.type = EVENT_TYPE_UNKNOWN;
+      return elem;
+  }
 }
 
-LIBLOG_ABI_PUBLIC android_log_list_element android_log_read_next(
-        android_log_context ctx) {
-    return android_log_read_next_internal(ctx, 0);
+LIBLOG_ABI_PUBLIC android_log_list_element
+android_log_read_next(android_log_context ctx) {
+  return android_log_read_next_internal(ctx, 0);
 }
 
-LIBLOG_ABI_PUBLIC android_log_list_element android_log_peek_next(
-        android_log_context ctx) {
-    return android_log_read_next_internal(ctx, 1);
+LIBLOG_ABI_PUBLIC android_log_list_element
+android_log_peek_next(android_log_context ctx) {
+  return android_log_read_next_internal(ctx, 1);
 }
diff --git a/liblog/log_event_write.c b/liblog/log_event_write.c
index b9827a1..45a6f37 100644
--- a/liblog/log_event_write.c
+++ b/liblog/log_event_write.c
@@ -15,38 +15,37 @@
  */
 
 #include <errno.h>
+#include <stdint.h>
 
 #include <log/log.h>
+#include <log/log_event_list.h>
 
 #include "log_portability.h"
 
 #define MAX_SUBTAG_LEN 32
 
-LIBLOG_ABI_PUBLIC int __android_log_error_write(
-        int tag,
-        const char *subTag,
-        int32_t uid,
-        const char *data, uint32_t dataLen)
-{
-    int ret = -EINVAL;
+LIBLOG_ABI_PUBLIC int __android_log_error_write(int tag, const char* subTag,
+                                                int32_t uid, const char* data,
+                                                uint32_t dataLen) {
+  int ret = -EINVAL;
 
-    if (subTag && (data || !dataLen)) {
-        android_log_context ctx = create_android_logger(tag);
+  if (subTag && (data || !dataLen)) {
+    android_log_context ctx = create_android_logger(tag);
 
-        ret = -ENOMEM;
-        if (ctx) {
-            ret = android_log_write_string8_len(ctx, subTag, MAX_SUBTAG_LEN);
-            if (ret >= 0) {
-                ret = android_log_write_int32(ctx, uid);
-                if (ret >= 0) {
-                    ret = android_log_write_string8_len(ctx, data, dataLen);
-                    if (ret >= 0) {
-                        ret = android_log_write_list(ctx, LOG_ID_EVENTS);
-                    }
-                }
-            }
-            android_log_destroy(&ctx);
+    ret = -ENOMEM;
+    if (ctx) {
+      ret = android_log_write_string8_len(ctx, subTag, MAX_SUBTAG_LEN);
+      if (ret >= 0) {
+        ret = android_log_write_int32(ctx, uid);
+        if (ret >= 0) {
+          ret = android_log_write_string8_len(ctx, data, dataLen);
+          if (ret >= 0) {
+            ret = android_log_write_list(ctx, LOG_ID_EVENTS);
+          }
         }
+      }
+      android_log_destroy(&ctx);
     }
-    return ret;
+  }
+  return ret;
 }
diff --git a/liblog/log_is_loggable.c b/liblog/log_is_loggable.c
deleted file mode 100644
index bd8d5af..0000000
--- a/liblog/log_is_loggable.c
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
-** Copyright 2014, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#include <ctype.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
-
-#include <android/log.h>
-
-#include "log_portability.h"
-
-static pthread_mutex_t lock_loggable = PTHREAD_MUTEX_INITIALIZER;
-
-static int lock()
-{
-    /*
-     * If we trigger a signal handler in the middle of locked activity and the
-     * signal handler logs a message, we could get into a deadlock state.
-     */
-    /*
-     *  Any contention, and we can turn around and use the non-cached method
-     * in less time than the system call associated with a mutex to deal with
-     * the contention.
-     */
-    return pthread_mutex_trylock(&lock_loggable);
-}
-
-static void unlock()
-{
-    pthread_mutex_unlock(&lock_loggable);
-}
-
-struct cache {
-    const prop_info *pinfo;
-    uint32_t serial;
-    unsigned char c;
-};
-
-static int check_cache(struct cache *cache)
-{
-    return cache->pinfo
-        && __system_property_serial(cache->pinfo) != cache->serial;
-}
-
-#define BOOLEAN_TRUE 0xFF
-#define BOOLEAN_FALSE 0xFE
-
-static void refresh_cache(struct cache *cache, const char *key)
-{
-    char buf[PROP_VALUE_MAX];
-
-    if (!cache->pinfo) {
-        cache->pinfo = __system_property_find(key);
-        if (!cache->pinfo) {
-            return;
-        }
-    }
-    cache->serial = __system_property_serial(cache->pinfo);
-    __system_property_read(cache->pinfo, 0, buf);
-    switch(buf[0]) {
-    case 't': case 'T':
-        cache->c = strcasecmp(buf + 1, "rue") ? buf[0] : BOOLEAN_TRUE;
-        break;
-    case 'f': case 'F':
-        cache->c = strcasecmp(buf + 1, "alse") ? buf[0] : BOOLEAN_FALSE;
-        break;
-    default:
-        cache->c = buf[0];
-    }
-}
-
-static int __android_log_level(const char *tag, int default_prio)
-{
-    /* sizeof() is used on this array below */
-    static const char log_namespace[] = "persist.log.tag.";
-    static const size_t base_offset = 8; /* skip "persist." */
-    /* calculate the size of our key temporary buffer */
-    const size_t taglen = (tag && *tag) ? strlen(tag) : 0;
-    /* sizeof(log_namespace) = strlen(log_namespace) + 1 */
-    char key[sizeof(log_namespace) + taglen]; /* may be > PROPERTY_KEY_MAX */
-    char *kp;
-    size_t i;
-    char c = 0;
-    /*
-     * Single layer cache of four properties. Priorities are:
-     *    log.tag.<tag>
-     *    persist.log.tag.<tag>
-     *    log.tag
-     *    persist.log.tag
-     * 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 uint32_t global_serial;
-    /* some compilers erroneously see uninitialized use. !not_locked */
-    uint32_t current_global_serial = 0;
-    static struct cache tag_cache[2];
-    static struct cache global_cache[2];
-    int change_detected;
-    int global_change_detected;
-    int not_locked;
-
-    strcpy(key, log_namespace);
-
-    global_change_detected = change_detected = not_locked = lock();
-
-    if (!not_locked) {
-        /*
-         *  check all known serial numbers to changes.
-         */
-        for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
-            if (check_cache(&tag_cache[i])) {
-                change_detected = 1;
-            }
-        }
-        for (i = 0; i < (sizeof(global_cache) / sizeof(global_cache[0])); ++i) {
-            if (check_cache(&global_cache[i])) {
-                global_change_detected = 1;
-            }
-        }
-
-        current_global_serial = __system_property_area_serial();
-        if (current_global_serial != global_serial) {
-            change_detected = 1;
-            global_change_detected = 1;
-        }
-    }
-
-    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, sizeof(last_tag) - 1)) {
-                /* invalidate log.tag.<tag> cache */
-                for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
-                    tag_cache[i].pinfo = NULL;
-                    tag_cache[i].c = '\0';
-                }
-                last_tag[0] = '\0';
-                local_change_detected = 1;
-            }
-            if (!last_tag[0]) {
-                strncpy(last_tag, tag, sizeof(last_tag));
-            }
-        }
-        strcpy(key + sizeof(log_namespace) - 1, tag);
-
-        kp = key;
-        for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
-            struct cache *cache = &tag_cache[i];
-            struct cache temp_cache;
-
-            if (not_locked) {
-                temp_cache.pinfo = NULL;
-                temp_cache.c = '\0';
-                cache = &temp_cache;
-            }
-            if (local_change_detected) {
-                refresh_cache(cache, kp);
-            }
-
-            if (cache->c) {
-                c = cache->c;
-                break;
-            }
-
-            kp = key + base_offset;
-        }
-    }
-
-    switch (toupper(c)) { /* if invalid, resort to global */
-    case 'V':
-    case 'D':
-    case 'I':
-    case 'W':
-    case 'E':
-    case 'F': /* Not officially supported */
-    case 'A':
-    case 'S':
-    case BOOLEAN_FALSE: /* Not officially supported */
-        break;
-    default:
-        /* clear '.' after log.tag */
-        key[sizeof(log_namespace) - 2] = '\0';
-
-        kp = key;
-        for (i = 0; i < (sizeof(global_cache) / sizeof(global_cache[0])); ++i) {
-            struct cache *cache = &global_cache[i];
-            struct cache temp_cache;
-
-            if (not_locked) {
-                temp_cache = *cache;
-                if (temp_cache.pinfo != cache->pinfo) { /* check atomic */
-                    temp_cache.pinfo = NULL;
-                    temp_cache.c = '\0';
-                }
-                cache = &temp_cache;
-            }
-            if (global_change_detected) {
-                refresh_cache(cache, kp);
-            }
-
-            if (cache->c) {
-                c = cache->c;
-                break;
-            }
-
-            kp = key + base_offset;
-        }
-        break;
-    }
-
-    if (!not_locked) {
-        global_serial = current_global_serial;
-        unlock();
-    }
-
-    switch (toupper(c)) {
-    case 'V': return ANDROID_LOG_VERBOSE;
-    case 'D': return ANDROID_LOG_DEBUG;
-    case 'I': return ANDROID_LOG_INFO;
-    case 'W': return ANDROID_LOG_WARN;
-    case 'E': return ANDROID_LOG_ERROR;
-    case 'F': /* FALLTHRU */ /* Not officially supported */
-    case 'A': return ANDROID_LOG_FATAL;
-    case BOOLEAN_FALSE: /* FALLTHRU */ /* Not Officially supported */
-    case 'S': return -1; /* ANDROID_LOG_SUPPRESS */
-    }
-    return default_prio;
-}
-
-LIBLOG_ABI_PUBLIC int __android_log_is_loggable(int prio, const char *tag,
-                                                int default_prio)
-{
-    int logLevel = __android_log_level(tag, default_prio);
-    return logLevel >= 0 && prio >= logLevel;
-}
-
-LIBLOG_HIDDEN int __android_log_is_debuggable()
-{
-    static uint32_t serial;
-    static struct cache tag_cache;
-    static const char key[] = "ro.debuggable";
-    int ret;
-
-    if (tag_cache.c) { /* ro property does not change after set */
-        ret = tag_cache.c == '1';
-    } else if (lock()) {
-        struct cache temp_cache = { NULL, -1, '\0' };
-        refresh_cache(&temp_cache, key);
-        ret = temp_cache.c == '1';
-    } else {
-        int change_detected = check_cache(&tag_cache);
-        uint32_t current_serial = __system_property_area_serial();
-        if (current_serial != serial) {
-            change_detected = 1;
-        }
-        if (change_detected) {
-            refresh_cache(&tag_cache, key);
-            serial = current_serial;
-        }
-        ret = tag_cache.c == '1';
-
-        unlock();
-    }
-
-    return ret;
-}
-
-/*
- * For properties that are read often, but generally remain constant.
- * Since a change is rare, we will accept a trylock failure gracefully.
- * Use a separate lock from is_loggable to keep contention down b/25563384.
- */
-struct cache2 {
-    pthread_mutex_t lock;
-    uint32_t serial;
-    const char *key_persist;
-    struct cache cache_persist;
-    const char *key_ro;
-    struct cache cache_ro;
-    unsigned char (*const evaluate)(const struct cache2 *self);
-};
-
-static inline unsigned char do_cache2(struct cache2 *self)
-{
-    uint32_t current_serial;
-    int change_detected;
-    unsigned char c;
-
-    if (pthread_mutex_trylock(&self->lock)) {
-        /* We are willing to accept some race in this context */
-        return self->evaluate(self);
-    }
-
-    change_detected = check_cache(&self->cache_persist)
-                   || check_cache(&self->cache_ro);
-    current_serial = __system_property_area_serial();
-    if (current_serial != self->serial) {
-        change_detected = 1;
-    }
-    if (change_detected) {
-        refresh_cache(&self->cache_persist, self->key_persist);
-        refresh_cache(&self->cache_ro, self->key_ro);
-        self->serial = current_serial;
-    }
-    c = self->evaluate(self);
-
-    pthread_mutex_unlock(&self->lock);
-
-    return c;
-}
-
-static unsigned char evaluate_persist_ro(const struct cache2 *self)
-{
-    unsigned char c = self->cache_persist.c;
-
-    if (c) {
-        return c;
-    }
-
-    return self->cache_ro.c;
-}
-
-/*
- * Timestamp state generally remains constant, but can change at any time
- * to handle developer requirements.
- */
-LIBLOG_ABI_PUBLIC clockid_t android_log_clockid()
-{
-    static struct cache2 clockid = {
-        PTHREAD_MUTEX_INITIALIZER,
-        0,
-        "persist.logd.timestamp",
-        { NULL, -1, '\0' },
-        "ro.logd.timestamp",
-        { NULL, -1, '\0' },
-        evaluate_persist_ro
-    };
-
-    return (tolower(do_cache2(&clockid)) == 'm')
-        ? CLOCK_MONOTONIC
-        : CLOCK_REALTIME;
-}
-
-/*
- * Security state generally remains constant, but the DO must be able
- * to turn off logging should it become spammy after an attack is detected.
- */
-static unsigned char evaluate_security(const struct cache2 *self)
-{
-    unsigned char c = self->cache_ro.c;
-
-    return (c != BOOLEAN_FALSE) && c && (self->cache_persist.c == BOOLEAN_TRUE);
-}
-
-LIBLOG_ABI_PUBLIC int __android_log_security()
-{
-    static struct cache2 security = {
-        PTHREAD_MUTEX_INITIALIZER,
-        0,
-        "persist.logd.security",
-        { NULL, -1, BOOLEAN_FALSE },
-        "ro.device_owner",
-        { NULL, -1, BOOLEAN_FALSE },
-        evaluate_security
-    };
-
-    return do_cache2(&security);
-}
diff --git a/liblog/log_portability.h b/liblog/log_portability.h
index 3ad2060..88805c7 100644
--- a/liblog/log_portability.h
+++ b/liblog/log_portability.h
@@ -46,7 +46,7 @@
 #if defined(_WIN32)
 #define LIBLOG_WEAK static /* Accept that it is totally private */
 #else
-#define LIBLOG_WEAK __attribute__((weak,visibility("default")))
+#define LIBLOG_WEAK __attribute__((weak, visibility("default")))
 #endif
 
 /* possible missing definitions in sys/cdefs.h */
@@ -54,8 +54,8 @@
 /* DECLS */
 #ifndef __BEGIN_DECLS
 #if defined(__cplusplus)
-#define __BEGIN_DECLS           extern "C" {
-#define __END_DECLS             }
+#define __BEGIN_DECLS extern "C" {
+#define __END_DECLS }
 #else
 #define __BEGIN_DECLS
 #define __END_DECLS
@@ -64,19 +64,21 @@
 
 /* Unused argument. For C code only, remove symbol name for C++ */
 #ifndef __unused
-#define __unused        __attribute__((__unused__))
+#define __unused __attribute__((__unused__))
 #endif
 
 /* possible missing definitions in unistd.h */
 
 #ifndef TEMP_FAILURE_RETRY
 /* Used to retry syscalls that can return EINTR. */
-#define TEMP_FAILURE_RETRY(exp) ({         \
+#define TEMP_FAILURE_RETRY(exp)            \
+  ({                                       \
     __typeof__(exp) _rc;                   \
     do {                                   \
-        _rc = (exp);                       \
+      _rc = (exp);                         \
     } while (_rc == -1 && errno == EINTR); \
-    _rc; })
+    _rc;                                   \
+  })
 #endif
 
 #endif /* _LIBLOG_PORTABILITY_H__ */
diff --git a/liblog/log_ratelimit.cpp b/liblog/log_ratelimit.cpp
new file mode 100644
index 0000000..33770dd
--- /dev/null
+++ b/liblog/log_ratelimit.cpp
@@ -0,0 +1,86 @@
+/*
+** Copyright 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 <pthread.h>
+#include <time.h>
+
+#include <log/log.h>
+
+#include "log_portability.h"
+
+// Global default if 'last' argument in __android_log_ratelimit is NULL
+static time_t g_last_clock;
+// Global above can not deal well with callers playing games with the
+// seconds argument, so we will also hold on to the maximum value
+// ever provided and use that to gain consistency.  If the caller
+// provides their own 'last' argument, then they can play such games
+// of varying the 'seconds' argument to their pleasure.
+static time_t g_last_seconds;
+static const time_t last_seconds_default = 10;
+static const time_t last_seconds_max = 24 * 60 * 60;  // maximum of a day
+static const time_t last_seconds_min = 2;             // granularity
+// Lock to protect last_clock and last_seconds, but also 'last'
+// argument (not NULL) as supplied to __android_log_ratelimit.
+static pthread_mutex_t lock_ratelimit = PTHREAD_MUTEX_INITIALIZER;
+
+// if last is NULL, caller _must_ provide a consistent value for
+// seconds, otherwise we will take the maximum ever issued and hold
+// on to that.  Preserves value of non-zero errno.  Return -1 if we
+// can not acquire a lock, 0 if we are not to log a message, and 1
+// if we are ok to log a message.  Caller should check > 0 for true.
+LIBLOG_ABI_PUBLIC int __android_log_ratelimit(time_t seconds, time_t* last) {
+  int save_errno = errno;
+
+  // Two reasons for trylock failure:
+  //   1. In a signal handler. Must prevent deadlock
+  //   2. Too many threads calling __android_log_ratelimit.
+  //      Bonus to not print if they race here because that
+  //      dovetails the goal of ratelimiting. One may print
+  //      and the others will wait their turn ...
+  if (pthread_mutex_trylock(&lock_ratelimit)) {
+    if (save_errno) errno = save_errno;
+    return -1;
+  }
+
+  if (seconds == 0) {
+    seconds = last_seconds_default;
+  } else if (seconds < last_seconds_min) {
+    seconds = last_seconds_min;
+  } else if (seconds > last_seconds_max) {
+    seconds = last_seconds_max;
+  }
+
+  if (!last) {
+    if (g_last_seconds > seconds) {
+      seconds = g_last_seconds;
+    } else if (g_last_seconds < seconds) {
+      g_last_seconds = seconds;
+    }
+    last = &g_last_clock;
+  }
+
+  time_t now = time(NULL);
+  if ((now == (time_t)-1) || ((*last + seconds) > now)) {
+    pthread_mutex_unlock(&lock_ratelimit);
+    if (save_errno) errno = save_errno;
+    return 0;
+  }
+  *last = now;
+  pthread_mutex_unlock(&lock_ratelimit);
+  if (save_errno) errno = save_errno;
+  return 1;
+}
diff --git a/liblog/log_time.cpp b/liblog/log_time.cpp
index d2bf181..ae376be 100644
--- a/liblog/log_time.cpp
+++ b/liblog/log_time.cpp
@@ -19,7 +19,7 @@
 #include <stdio.h>
 #include <string.h>
 
-#include <log/log_read.h>
+#include <private/android_logger.h>
 
 #include "log_portability.h"
 
@@ -28,164 +28,164 @@
 
 // Add %#q for fractional seconds to standard strptime function
 
-LIBLOG_ABI_PRIVATE char *log_time::strptime(const char *s, const char *format) {
-    time_t now;
+LIBLOG_ABI_PRIVATE char* log_time::strptime(const char* s, const char* format) {
+  time_t now;
 #ifdef __linux__
-    *this = log_time(CLOCK_REALTIME);
-    now = tv_sec;
+  *this = log_time(CLOCK_REALTIME);
+  now = tv_sec;
 #else
-    time(&now);
-    tv_sec = now;
-    tv_nsec = 0;
+  time(&now);
+  tv_sec = now;
+  tv_nsec = 0;
 #endif
 
-    struct tm *ptm;
+  struct tm* ptm;
 #if !defined(_WIN32)
-    struct tm tmBuf;
-    ptm = localtime_r(&now, &tmBuf);
+  struct tm tmBuf;
+  ptm = localtime_r(&now, &tmBuf);
 #else
-    ptm = localtime(&now);
+  ptm = localtime(&now);
 #endif
 
-    char fmt[strlen(format) + 1];
-    strcpy(fmt, format);
+  char fmt[strlen(format) + 1];
+  strcpy(fmt, format);
 
-    char *ret = const_cast<char *> (s);
-    char *cp;
-    for (char *f = cp = fmt; ; ++cp) {
-        if (!*cp) {
-            if (f != cp) {
-                ret = ::strptime(ret, f, ptm);
-            }
-            break;
-        }
-        if (*cp != '%') {
-            continue;
-        }
-        char *e = cp;
-        ++e;
+  char* ret = const_cast<char*>(s);
+  char* cp;
+  for (char* f = cp = fmt;; ++cp) {
+    if (!*cp) {
+      if (f != cp) {
+        ret = ::strptime(ret, f, ptm);
+      }
+      break;
+    }
+    if (*cp != '%') {
+      continue;
+    }
+    char* e = cp;
+    ++e;
 #if (defined(__BIONIC__))
-        if (*e == 's') {
-            *cp = '\0';
-            if (*f) {
-                ret = ::strptime(ret, f, ptm);
-                if (!ret) {
-                    break;
-                }
-            }
-            tv_sec = 0;
-            while (isdigit(*ret)) {
-                tv_sec = tv_sec * 10 + *ret - '0';
-                ++ret;
-            }
-            now = tv_sec;
-#if !defined(_WIN32)
-            ptm = localtime_r(&now, &tmBuf);
-#else
-            ptm = localtime(&now);
-#endif
-        } else
-#endif
-        {
-            unsigned num = 0;
-            while (isdigit(*e)) {
-                num = num * 10 + *e - '0';
-                ++e;
-            }
-            if (*e != 'q') {
-                continue;
-            }
-            *cp = '\0';
-            if (*f) {
-                ret = ::strptime(ret, f, ptm);
-                if (!ret) {
-                    break;
-                }
-            }
-            unsigned long mul = NS_PER_SEC;
-            if (num == 0) {
-                num = INT_MAX;
-            }
-            tv_nsec = 0;
-            while (isdigit(*ret) && num && (mul > 1)) {
-                --num;
-                mul /= 10;
-                tv_nsec = tv_nsec + (*ret - '0') * mul;
-                ++ret;
-            }
+    if (*e == 's') {
+      *cp = '\0';
+      if (*f) {
+        ret = ::strptime(ret, f, ptm);
+        if (!ret) {
+          break;
         }
-        f = cp = e;
-        ++f;
-    }
-
-    if (ret) {
-        tv_sec = mktime(ptm);
-        return ret;
-    }
-
-    // Upon error, place a known value into the class, the current time.
-#ifdef __linux__
-    *this = log_time(CLOCK_REALTIME);
+      }
+      tv_sec = 0;
+      while (isdigit(*ret)) {
+        tv_sec = tv_sec * 10 + *ret - '0';
+        ++ret;
+      }
+      now = tv_sec;
+#if !defined(_WIN32)
+      ptm = localtime_r(&now, &tmBuf);
 #else
-    time(&now);
-    tv_sec = now;
-    tv_nsec = 0;
+      ptm = localtime(&now);
 #endif
+    } else
+#endif
+    {
+      unsigned num = 0;
+      while (isdigit(*e)) {
+        num = num * 10 + *e - '0';
+        ++e;
+      }
+      if (*e != 'q') {
+        continue;
+      }
+      *cp = '\0';
+      if (*f) {
+        ret = ::strptime(ret, f, ptm);
+        if (!ret) {
+          break;
+        }
+      }
+      unsigned long mul = NS_PER_SEC;
+      if (num == 0) {
+        num = INT_MAX;
+      }
+      tv_nsec = 0;
+      while (isdigit(*ret) && num && (mul > 1)) {
+        --num;
+        mul /= 10;
+        tv_nsec = tv_nsec + (*ret - '0') * mul;
+        ++ret;
+      }
+    }
+    f = cp = e;
+    ++f;
+  }
+
+  if (ret) {
+    tv_sec = mktime(ptm);
     return ret;
+  }
+
+// Upon error, place a known value into the class, the current time.
+#ifdef __linux__
+  *this = log_time(CLOCK_REALTIME);
+#else
+  time(&now);
+  tv_sec = now;
+  tv_nsec = 0;
+#endif
+  return ret;
 }
 
-LIBLOG_ABI_PRIVATE log_time log_time::operator-= (const timespec &T) {
-    // No concept of negative time, clamp to EPOCH
-    if (*this <= T) {
-        return *this = EPOCH;
-    }
+LIBLOG_ABI_PRIVATE log_time log_time::operator-=(const timespec& T) {
+  // No concept of negative time, clamp to EPOCH
+  if (*this <= T) {
+    return *this = EPOCH;
+  }
 
-    if (this->tv_nsec < (unsigned long int)T.tv_nsec) {
-        --this->tv_sec;
-        this->tv_nsec = NS_PER_SEC + this->tv_nsec - T.tv_nsec;
-    } else {
-        this->tv_nsec -= T.tv_nsec;
-    }
-    this->tv_sec -= T.tv_sec;
+  if (this->tv_nsec < (unsigned long int)T.tv_nsec) {
+    --this->tv_sec;
+    this->tv_nsec = NS_PER_SEC + this->tv_nsec - T.tv_nsec;
+  } else {
+    this->tv_nsec -= T.tv_nsec;
+  }
+  this->tv_sec -= T.tv_sec;
 
-    return *this;
+  return *this;
 }
 
-LIBLOG_ABI_PRIVATE log_time log_time::operator+= (const timespec &T) {
-    this->tv_nsec += (unsigned long int)T.tv_nsec;
-    if (this->tv_nsec >= NS_PER_SEC) {
-        this->tv_nsec -= NS_PER_SEC;
-        ++this->tv_sec;
-    }
-    this->tv_sec += T.tv_sec;
+LIBLOG_ABI_PRIVATE log_time log_time::operator+=(const timespec& T) {
+  this->tv_nsec += (unsigned long int)T.tv_nsec;
+  if (this->tv_nsec >= NS_PER_SEC) {
+    this->tv_nsec -= NS_PER_SEC;
+    ++this->tv_sec;
+  }
+  this->tv_sec += T.tv_sec;
 
-    return *this;
+  return *this;
 }
 
-LIBLOG_ABI_PRIVATE log_time log_time::operator-= (const log_time &T) {
-    // No concept of negative time, clamp to EPOCH
-    if (*this <= T) {
-        return *this = EPOCH;
-    }
+LIBLOG_ABI_PRIVATE log_time log_time::operator-=(const log_time& T) {
+  // No concept of negative time, clamp to EPOCH
+  if (*this <= T) {
+    return *this = EPOCH;
+  }
 
-    if (this->tv_nsec < T.tv_nsec) {
-        --this->tv_sec;
-        this->tv_nsec = NS_PER_SEC + this->tv_nsec - T.tv_nsec;
-    } else {
-        this->tv_nsec -= T.tv_nsec;
-    }
-    this->tv_sec -= T.tv_sec;
+  if (this->tv_nsec < T.tv_nsec) {
+    --this->tv_sec;
+    this->tv_nsec = NS_PER_SEC + this->tv_nsec - T.tv_nsec;
+  } else {
+    this->tv_nsec -= T.tv_nsec;
+  }
+  this->tv_sec -= T.tv_sec;
 
-    return *this;
+  return *this;
 }
 
-LIBLOG_ABI_PRIVATE log_time log_time::operator+= (const log_time &T) {
-    this->tv_nsec += T.tv_nsec;
-    if (this->tv_nsec >= NS_PER_SEC) {
-        this->tv_nsec -= NS_PER_SEC;
-        ++this->tv_sec;
-    }
-    this->tv_sec += T.tv_sec;
+LIBLOG_ABI_PRIVATE log_time log_time::operator+=(const log_time& T) {
+  this->tv_nsec += T.tv_nsec;
+  if (this->tv_nsec >= NS_PER_SEC) {
+    this->tv_nsec -= NS_PER_SEC;
+    ++this->tv_sec;
+  }
+  this->tv_sec += T.tv_sec;
 
-    return *this;
+  return *this;
 }
diff --git a/liblog/logd_reader.c b/liblog/logd_reader.c
index b894349..600f4bb 100644
--- a/liblog/logd_reader.c
+++ b/liblog/logd_reader.c
@@ -24,106 +24,103 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/socket.h>
 #include <sys/un.h>
 #include <time.h>
 #include <unistd.h>
 
 #include <cutils/sockets.h>
-#include <log/logd.h>
-#include <log/logger.h>
-#include <log/log_read.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
 #include "config_read.h"
 #include "log_portability.h"
+#include "logd_reader.h"
 #include "logger.h"
 
 /* branchless on many architectures. */
-#define min(x,y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
+#define min(x, y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
 
 static int logdAvailable(log_id_t LogId);
-static int logdVersion(struct android_log_logger *logger,
-                       struct android_log_transport_context *transp);
-static int logdRead(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp,
-                    struct log_msg *log_msg);
-static int logdPoll(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp);
-static void logdClose(struct android_log_logger_list *logger_list,
-                      struct android_log_transport_context *transp);
-static int logdClear(struct android_log_logger *logger,
-                     struct android_log_transport_context *transp);
-static ssize_t logdSetSize(struct android_log_logger *logger,
-                           struct android_log_transport_context *transp,
+static int logdVersion(struct android_log_logger* logger,
+                       struct android_log_transport_context* transp);
+static int logdRead(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp,
+                    struct log_msg* log_msg);
+static int logdPoll(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp);
+static void logdClose(struct android_log_logger_list* logger_list,
+                      struct android_log_transport_context* transp);
+static int logdClear(struct android_log_logger* logger,
+                     struct android_log_transport_context* transp);
+static ssize_t logdSetSize(struct android_log_logger* logger,
+                           struct android_log_transport_context* transp,
                            size_t size);
-static ssize_t logdGetSize(struct android_log_logger *logger,
-                           struct android_log_transport_context *transp);
-static ssize_t logdGetReadableSize(struct android_log_logger *logger,
-                                   struct android_log_transport_context *transp);
-static ssize_t logdGetPrune(struct android_log_logger_list *logger,
-                            struct android_log_transport_context *transp,
-                            char *buf, size_t len);
-static ssize_t logdSetPrune(struct android_log_logger_list *logger,
-                            struct android_log_transport_context *transp,
-                            char *buf, size_t len);
-static ssize_t logdGetStats(struct android_log_logger_list *logger,
-                            struct android_log_transport_context *transp,
-                            char *buf, size_t len);
+static ssize_t logdGetSize(struct android_log_logger* logger,
+                           struct android_log_transport_context* transp);
+static ssize_t logdGetReadableSize(struct android_log_logger* logger,
+                                   struct android_log_transport_context* transp);
+static ssize_t logdGetPrune(struct android_log_logger_list* logger,
+                            struct android_log_transport_context* transp,
+                            char* buf, size_t len);
+static ssize_t logdSetPrune(struct android_log_logger_list* logger,
+                            struct android_log_transport_context* transp,
+                            char* buf, size_t len);
+static ssize_t logdGetStats(struct android_log_logger_list* logger,
+                            struct android_log_transport_context* transp,
+                            char* buf, size_t len);
 
 LIBLOG_HIDDEN struct android_log_transport_read logdLoggerRead = {
-    .node = { &logdLoggerRead.node, &logdLoggerRead.node },
-    .name = "logd",
-    .available = logdAvailable,
-    .version = logdVersion,
-    .read = logdRead,
-    .poll = logdPoll,
-    .close = logdClose,
-    .clear = logdClear,
-    .getSize = logdGetSize,
-    .setSize = logdSetSize,
-    .getReadableSize = logdGetReadableSize,
-    .getPrune = logdGetPrune,
-    .setPrune = logdSetPrune,
-    .getStats = logdGetStats,
+  .node = { &logdLoggerRead.node, &logdLoggerRead.node },
+  .name = "logd",
+  .available = logdAvailable,
+  .version = logdVersion,
+  .read = logdRead,
+  .poll = logdPoll,
+  .close = logdClose,
+  .clear = logdClear,
+  .getSize = logdGetSize,
+  .setSize = logdSetSize,
+  .getReadableSize = logdGetReadableSize,
+  .getPrune = logdGetPrune,
+  .setPrune = logdSetPrune,
+  .getStats = logdGetStats,
 };
 
-static int logdAvailable(log_id_t logId)
-{
-    if (logId > LOG_ID_KERNEL) {
-        return -EINVAL;
+static int logdAvailable(log_id_t logId) {
+  if (logId >= LOG_ID_MAX) {
+    return -EINVAL;
+  }
+  if (logId == LOG_ID_SECURITY) {
+    uid_t uid = __android_log_uid();
+    if (uid != AID_SYSTEM) {
+      return -EPERM;
     }
-    if (logId == LOG_ID_SECURITY) {
-        uid_t uid = __android_log_uid();
-        if (uid != AID_SYSTEM) {
-            return -EPERM;
-        }
-    }
-    if (access("/dev/socket/logdw", W_OK) == 0) {
-        return 0;
-    }
-    return -EBADF;
+  }
+  if (access("/dev/socket/logdw", W_OK) == 0) {
+    return 0;
+  }
+  return -EBADF;
 }
 
 /* Private copy of ../libcutils/socket_local_client.c prevent library loops */
 
 #if defined(_WIN32)
 
-LIBLOG_WEAK int socket_local_client(const char *name, int namespaceId, int type)
-{
-    errno = ENOSYS;
-    return -ENOSYS;
+LIBLOG_WEAK int socket_local_client(const char* name, int namespaceId,
+                                    int type) {
+  errno = ENOSYS;
+  return -ENOSYS;
 }
 
 #else /* !_WIN32 */
 
-#include <sys/socket.h>
-#include <sys/un.h>
 #include <sys/select.h>
+#include <sys/socket.h>
 #include <sys/types.h>
+#include <sys/un.h>
 
 /* Private copy of ../libcutils/socket_local.h prevent library loops */
 #define FILESYSTEM_SOCKET_PREFIX "/tmp/"
@@ -133,78 +130,77 @@
 #define LISTEN_BACKLOG 4
 
 /* Documented in header file. */
-LIBLOG_WEAK int socket_make_sockaddr_un(const char *name, int namespaceId,
-                                        struct sockaddr_un *p_addr,
-                                        socklen_t *alen)
-{
-    memset (p_addr, 0, sizeof (*p_addr));
-    size_t namelen;
+LIBLOG_WEAK int socket_make_sockaddr_un(const char* name, int namespaceId,
+                                        struct sockaddr_un* p_addr,
+                                        socklen_t* alen) {
+  memset(p_addr, 0, sizeof(*p_addr));
+  size_t namelen;
 
-    switch (namespaceId) {
+  switch (namespaceId) {
     case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
 #if defined(__linux__)
-        namelen  = strlen(name);
+      namelen = strlen(name);
 
-        /* Test with length +1 for the *initial* '\0'. */
-        if ((namelen + 1) > sizeof(p_addr->sun_path)) {
-            goto error;
-        }
+      /* Test with length +1 for the *initial* '\0'. */
+      if ((namelen + 1) > sizeof(p_addr->sun_path)) {
+        goto error;
+      }
 
-        /*
-         * Note: The path in this case is *not* supposed to be
-         * '\0'-terminated. ("man 7 unix" for the gory details.)
-         */
+      /*
+       * Note: The path in this case is *not* supposed to be
+       * '\0'-terminated. ("man 7 unix" for the gory details.)
+       */
 
-        p_addr->sun_path[0] = 0;
-        memcpy(p_addr->sun_path + 1, name, namelen);
+      p_addr->sun_path[0] = 0;
+      memcpy(p_addr->sun_path + 1, name, namelen);
 #else
-        /* this OS doesn't have the Linux abstract namespace */
+      /* this OS doesn't have the Linux abstract namespace */
 
-        namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
-        /* unix_path_max appears to be missing on linux */
-        if (namelen > sizeof(*p_addr)
-                - offsetof(struct sockaddr_un, sun_path) - 1) {
-            goto error;
-        }
+      namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
+      /* unix_path_max appears to be missing on linux */
+      if (namelen >
+          sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) {
+        goto error;
+      }
 
-        strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
-        strcat(p_addr->sun_path, name);
+      strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
+      strcat(p_addr->sun_path, name);
 #endif
-        break;
+      break;
 
     case ANDROID_SOCKET_NAMESPACE_RESERVED:
-        namelen = strlen(name) + strlen(ANDROID_RESERVED_SOCKET_PREFIX);
-        /* unix_path_max appears to be missing on linux */
-        if (namelen > sizeof(*p_addr)
-                - offsetof(struct sockaddr_un, sun_path) - 1) {
-            goto error;
-        }
+      namelen = strlen(name) + strlen(ANDROID_RESERVED_SOCKET_PREFIX);
+      /* unix_path_max appears to be missing on linux */
+      if (namelen >
+          sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) {
+        goto error;
+      }
 
-        strcpy(p_addr->sun_path, ANDROID_RESERVED_SOCKET_PREFIX);
-        strcat(p_addr->sun_path, name);
-        break;
+      strcpy(p_addr->sun_path, ANDROID_RESERVED_SOCKET_PREFIX);
+      strcat(p_addr->sun_path, name);
+      break;
 
     case ANDROID_SOCKET_NAMESPACE_FILESYSTEM:
-        namelen = strlen(name);
-        /* unix_path_max appears to be missing on linux */
-        if (namelen > sizeof(*p_addr)
-                - offsetof(struct sockaddr_un, sun_path) - 1) {
-            goto error;
-        }
+      namelen = strlen(name);
+      /* unix_path_max appears to be missing on linux */
+      if (namelen >
+          sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) {
+        goto error;
+      }
 
-        strcpy(p_addr->sun_path, name);
-        break;
+      strcpy(p_addr->sun_path, name);
+      break;
 
     default:
-        /* invalid namespace id */
-        return -1;
-    }
+      /* invalid namespace id */
+      return -1;
+  }
 
-    p_addr->sun_family = AF_LOCAL;
-    *alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1;
-    return 0;
+  p_addr->sun_family = AF_LOCAL;
+  *alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1;
+  return 0;
 error:
-    return -1;
+  return -1;
 }
 
 /**
@@ -214,457 +210,441 @@
  *
  * Used by AndroidSocketImpl
  */
-LIBLOG_WEAK int socket_local_client_connect(int fd, const char *name,
-                                            int namespaceId, int type __unused)
-{
-    struct sockaddr_un addr;
-    socklen_t alen;
-    int err;
+LIBLOG_WEAK int socket_local_client_connect(int fd, const char* name,
+                                            int namespaceId, int type __unused) {
+  struct sockaddr_un addr;
+  socklen_t alen;
+  int err;
 
-    err = socket_make_sockaddr_un(name, namespaceId, &addr, &alen);
+  err = socket_make_sockaddr_un(name, namespaceId, &addr, &alen);
 
-    if (err < 0) {
-        goto error;
-    }
+  if (err < 0) {
+    goto error;
+  }
 
-    if(connect(fd, (struct sockaddr *) &addr, alen) < 0) {
-        goto error;
-    }
+  if (connect(fd, (struct sockaddr*)&addr, alen) < 0) {
+    goto error;
+  }
 
-    return fd;
+  return fd;
 
 error:
-    return -1;
+  return -1;
 }
 
 /**
  * connect to peer named "name"
  * returns fd or -1 on error
  */
-LIBLOG_WEAK int socket_local_client(const char *name, int namespaceId, int type)
-{
-    int s;
+LIBLOG_WEAK int socket_local_client(const char* name, int namespaceId,
+                                    int type) {
+  int s;
 
-    s = socket(AF_LOCAL, type, 0);
-    if(s < 0) return -1;
+  s = socket(AF_LOCAL, type, 0);
+  if (s < 0) return -1;
 
-    if ( 0 > socket_local_client_connect(s, name, namespaceId, type)) {
-        close(s);
-        return -1;
-    }
+  if (0 > socket_local_client_connect(s, name, namespaceId, type)) {
+    close(s);
+    return -1;
+  }
 
-    return s;
+  return s;
 }
 
 #endif /* !_WIN32 */
 /* End of ../libcutils/socket_local_client.c */
 
 /* worker for sending the command to the logger */
-static ssize_t send_log_msg(struct android_log_logger *logger,
-                            const char *msg, char *buf, size_t buf_size)
-{
-    ssize_t ret;
-    size_t len;
-    char *cp;
-    int errno_save = 0;
-    int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                   SOCK_STREAM);
-    if (sock < 0) {
-        return sock;
+static ssize_t send_log_msg(struct android_log_logger* logger, const char* msg,
+                            char* buf, size_t buf_size) {
+  ssize_t ret;
+  size_t len;
+  char* cp;
+  int errno_save = 0;
+  int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
+                                 SOCK_STREAM);
+  if (sock < 0) {
+    return sock;
+  }
+
+  if (msg) {
+    snprintf(buf, buf_size, msg, logger ? logger->logId : (unsigned)-1);
+  }
+
+  len = strlen(buf) + 1;
+  ret = TEMP_FAILURE_RETRY(write(sock, buf, len));
+  if (ret <= 0) {
+    goto done;
+  }
+
+  len = buf_size;
+  cp = buf;
+  while ((ret = TEMP_FAILURE_RETRY(read(sock, cp, len))) > 0) {
+    struct pollfd p;
+
+    if (((size_t)ret == len) || (buf_size < PAGE_SIZE)) {
+      break;
     }
 
-    if (msg) {
-        snprintf(buf, buf_size, msg, logger ? logger->logId : (unsigned) -1);
-    }
+    len -= ret;
+    cp += ret;
 
-    len = strlen(buf) + 1;
-    ret = TEMP_FAILURE_RETRY(write(sock, buf, len));
+    memset(&p, 0, sizeof(p));
+    p.fd = sock;
+    p.events = POLLIN;
+
+    /* Give other side 20ms to refill pipe */
+    ret = TEMP_FAILURE_RETRY(poll(&p, 1, 20));
+
     if (ret <= 0) {
-        goto done;
+      break;
     }
 
-    len = buf_size;
-    cp = buf;
-    while ((ret = TEMP_FAILURE_RETRY(read(sock, cp, len))) > 0) {
-        struct pollfd p;
-
-        if (((size_t)ret == len) || (buf_size < PAGE_SIZE)) {
-            break;
-        }
-
-        len -= ret;
-        cp += ret;
-
-        memset(&p, 0, sizeof(p));
-        p.fd = sock;
-        p.events = POLLIN;
-
-        /* Give other side 20ms to refill pipe */
-        ret = TEMP_FAILURE_RETRY(poll(&p, 1, 20));
-
-        if (ret <= 0) {
-            break;
-        }
-
-        if (!(p.revents & POLLIN)) {
-            ret = 0;
-            break;
-        }
+    if (!(p.revents & POLLIN)) {
+      ret = 0;
+      break;
     }
+  }
 
-    if (ret >= 0) {
-        ret += buf_size - len;
-    }
+  if (ret >= 0) {
+    ret += buf_size - len;
+  }
 
 done:
-    if ((ret == -1) && errno) {
-        errno_save = errno;
-    }
-    close(sock);
-    if (errno_save) {
-        errno = errno_save;
-    }
+  if ((ret == -1) && errno) {
+    errno_save = errno;
+  }
+  close(sock);
+  if (errno_save) {
+    errno = errno_save;
+  }
+  return ret;
+}
+
+LIBLOG_HIDDEN ssize_t __send_log_msg(char* buf, size_t buf_size) {
+  return send_log_msg(NULL, NULL, buf, buf_size);
+}
+
+static int check_log_success(char* buf, ssize_t ret) {
+  if (ret < 0) {
     return ret;
+  }
+
+  if (strncmp(buf, "success", 7)) {
+    errno = EINVAL;
+    return -1;
+  }
+
+  return 0;
 }
 
-static int check_log_success(char *buf, ssize_t ret)
-{
-    if (ret < 0) {
-        return ret;
-    }
+static int logdClear(struct android_log_logger* logger,
+                     struct android_log_transport_context* transp __unused) {
+  char buf[512];
 
-    if (strncmp(buf, "success", 7)) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    return 0;
-}
-
-static int logdClear(struct android_log_logger *logger,
-                     struct android_log_transport_context *transp __unused)
-{
-    char buf[512];
-
-    return check_log_success(buf,
-        send_log_msg(logger, "clear %d", buf, sizeof(buf)));
+  return check_log_success(buf,
+                           send_log_msg(logger, "clear %d", buf, sizeof(buf)));
 }
 
 /* returns the total size of the log's ring buffer */
-static ssize_t logdGetSize(struct android_log_logger *logger,
-                           struct android_log_transport_context *transp __unused)
-{
-    char buf[512];
+static ssize_t logdGetSize(struct android_log_logger* logger,
+                           struct android_log_transport_context* transp __unused) {
+  char buf[512];
 
-    ssize_t ret = send_log_msg(logger, "getLogSize %d", buf, sizeof(buf));
-    if (ret < 0) {
-        return ret;
-    }
+  ssize_t ret = send_log_msg(logger, "getLogSize %d", buf, sizeof(buf));
+  if (ret < 0) {
+    return ret;
+  }
 
-    if ((buf[0] < '0') || ('9' < buf[0])) {
-        return -1;
-    }
+  if ((buf[0] < '0') || ('9' < buf[0])) {
+    return -1;
+  }
 
-    return atol(buf);
+  return atol(buf);
 }
 
-static ssize_t logdSetSize(
-        struct android_log_logger *logger,
-        struct android_log_transport_context *transp __unused,
-        size_t size)
-{
-    char buf[512];
+static ssize_t logdSetSize(struct android_log_logger* logger,
+                           struct android_log_transport_context* transp __unused,
+                           size_t size) {
+  char buf[512];
 
-    snprintf(buf, sizeof(buf), "setLogSize %d %zu", logger->logId, size);
+  snprintf(buf, sizeof(buf), "setLogSize %d %zu", logger->logId, size);
 
-    return check_log_success(buf, send_log_msg(NULL, NULL, buf, sizeof(buf)));
+  return check_log_success(buf, send_log_msg(NULL, NULL, buf, sizeof(buf)));
 }
 
 /*
  * returns the readable size of the log's ring buffer (that is, amount of the
  * log consumed)
  */
-static ssize_t logdGetReadableSize(
-       struct android_log_logger *logger,
-       struct android_log_transport_context *transp __unused)
-{
-    char buf[512];
+static ssize_t logdGetReadableSize(struct android_log_logger* logger,
+                                   struct android_log_transport_context* transp
+                                       __unused) {
+  char buf[512];
 
-    ssize_t ret = send_log_msg(logger, "getLogSizeUsed %d", buf, sizeof(buf));
-    if (ret < 0) {
-        return ret;
-    }
+  ssize_t ret = send_log_msg(logger, "getLogSizeUsed %d", buf, sizeof(buf));
+  if (ret < 0) {
+    return ret;
+  }
 
-    if ((buf[0] < '0') || ('9' < buf[0])) {
-        return -1;
-    }
+  if ((buf[0] < '0') || ('9' < buf[0])) {
+    return -1;
+  }
 
-    return atol(buf);
+  return atol(buf);
 }
 
 /*
  * returns the logger version
  */
-static int logdVersion(
-        struct android_log_logger *logger __unused,
-        struct android_log_transport_context *transp __unused)
-{
-    uid_t uid = __android_log_uid();
-    return ((uid != AID_ROOT) && (uid != AID_LOG) && (uid != AID_SYSTEM)) ? 3 : 4;
+static int logdVersion(struct android_log_logger* logger __unused,
+                       struct android_log_transport_context* transp __unused) {
+  uid_t uid = __android_log_uid();
+  return ((uid != AID_ROOT) && (uid != AID_LOG) && (uid != AID_SYSTEM)) ? 3 : 4;
 }
 
 /*
  * returns statistics
  */
-static ssize_t logdGetStats(struct android_log_logger_list *logger_list,
-                            struct android_log_transport_context *transp __unused,
-                            char *buf, size_t len)
-{
-    struct android_log_logger *logger;
-    char *cp = buf;
-    size_t remaining = len;
-    size_t n;
+static ssize_t logdGetStats(struct android_log_logger_list* logger_list,
+                            struct android_log_transport_context* transp __unused,
+                            char* buf, size_t len) {
+  struct android_log_logger* logger;
+  char* cp = buf;
+  size_t remaining = len;
+  size_t n;
 
-    n = snprintf(cp, remaining, "getStatistics");
+  n = snprintf(cp, remaining, "getStatistics");
+  n = min(n, remaining);
+  remaining -= n;
+  cp += n;
+
+  logger_for_each(logger, logger_list) {
+    n = snprintf(cp, remaining, " %d", logger->logId);
     n = min(n, remaining);
     remaining -= n;
     cp += n;
+  }
 
-    logger_for_each(logger, logger_list) {
-        n = snprintf(cp, remaining, " %d", logger->logId);
-        n = min(n, remaining);
-        remaining -= n;
-        cp += n;
-    }
+  if (logger_list->pid) {
+    snprintf(cp, remaining, " pid=%u", logger_list->pid);
+  }
 
-    if (logger_list->pid) {
-        snprintf(cp, remaining, " pid=%u", logger_list->pid);
-    }
-
-    return send_log_msg(NULL, NULL, buf, len);
+  return send_log_msg(NULL, NULL, buf, len);
 }
 
-static ssize_t logdGetPrune(
-        struct android_log_logger_list *logger_list __unused,
-        struct android_log_transport_context *transp __unused,
-        char *buf, size_t len)
-{
-    return send_log_msg(NULL, "getPruneList", buf, len);
+static ssize_t logdGetPrune(struct android_log_logger_list* logger_list __unused,
+                            struct android_log_transport_context* transp __unused,
+                            char* buf, size_t len) {
+  return send_log_msg(NULL, "getPruneList", buf, len);
 }
 
-static ssize_t logdSetPrune(
-        struct android_log_logger_list *logger_list __unused,
-        struct android_log_transport_context *transp __unused,
-        char *buf, size_t len)
-{
-    const char cmd[] = "setPruneList ";
-    const size_t cmdlen = sizeof(cmd) - 1;
+static ssize_t logdSetPrune(struct android_log_logger_list* logger_list __unused,
+                            struct android_log_transport_context* transp __unused,
+                            char* buf, size_t len) {
+  const char cmd[] = "setPruneList ";
+  const size_t cmdlen = sizeof(cmd) - 1;
 
-    if (strlen(buf) > (len - cmdlen)) {
-        return -ENOMEM; /* KISS */
-    }
-    memmove(buf + cmdlen, buf, len - cmdlen);
-    buf[len - 1] = '\0';
-    memcpy(buf, cmd, cmdlen);
+  if (strlen(buf) > (len - cmdlen)) {
+    return -ENOMEM; /* KISS */
+  }
+  memmove(buf + cmdlen, buf, len - cmdlen);
+  buf[len - 1] = '\0';
+  memcpy(buf, cmd, cmdlen);
 
-    return check_log_success(buf, send_log_msg(NULL, NULL, buf, len));
+  return check_log_success(buf, send_log_msg(NULL, NULL, buf, len));
 }
 
-
-static void caught_signal(int signum __unused)
-{
+static void caught_signal(int signum __unused) {
 }
 
-static int logdOpen(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp)
-{
-    struct android_log_logger *logger;
-    struct sigaction ignore;
-    struct sigaction old_sigaction;
-    unsigned int old_alarm = 0;
-    char buffer[256], *cp, c;
-    int e, ret, remaining;
+static int logdOpen(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp) {
+  struct android_log_logger* logger;
+  struct sigaction ignore;
+  struct sigaction old_sigaction;
+  unsigned int old_alarm = 0;
+  char buffer[256], *cp, c;
+  int e, ret, remaining, sock;
 
-    int sock = transp->context.sock;
-    if (sock > 0) {
-        return sock;
-    }
+  if (!logger_list) {
+    return -EINVAL;
+  }
 
-    if (!logger_list) {
-        return -EINVAL;
-    }
+  sock = atomic_load(&transp->context.sock);
+  if (sock > 0) {
+    return sock;
+  }
 
-    sock = socket_local_client("logdr",
-                               ANDROID_SOCKET_NAMESPACE_RESERVED,
-                               SOCK_SEQPACKET);
-    if (sock == 0) {
-        /* Guarantee not file descriptor zero */
-        int newsock = socket_local_client("logdr",
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                   SOCK_SEQPACKET);
-        close(sock);
-        sock = newsock;
+  sock = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
+                             SOCK_SEQPACKET);
+  if (sock == 0) {
+    /* Guarantee not file descriptor zero */
+    int newsock = socket_local_client(
+        "logdr", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET);
+    close(sock);
+    sock = newsock;
+  }
+  if (sock <= 0) {
+    if ((sock == -1) && errno) {
+      return -errno;
     }
-    if (sock <= 0) {
-        if ((sock == -1) && errno) {
-            return -errno;
-        }
-        return sock;
-    }
+    return sock;
+  }
 
-    strcpy(buffer, (logger_list->mode & ANDROID_LOG_NONBLOCK) ?
-            "dumpAndClose" : "stream");
-    cp = buffer + strlen(buffer);
+  strcpy(buffer, (logger_list->mode & ANDROID_LOG_NONBLOCK) ? "dumpAndClose"
+                                                            : "stream");
+  cp = buffer + strlen(buffer);
 
-    strcpy(cp, " lids");
-    cp += 5;
-    c = '=';
-    remaining = sizeof(buffer) - (cp - buffer);
-    logger_for_each(logger, logger_list) {
-        ret = snprintf(cp, remaining, "%c%u", c, logger->logId);
-        ret = min(ret, remaining);
-        remaining -= ret;
-        cp += ret;
-        c = ',';
-    }
+  strcpy(cp, " lids");
+  cp += 5;
+  c = '=';
+  remaining = sizeof(buffer) - (cp - buffer);
+  logger_for_each(logger, logger_list) {
+    ret = snprintf(cp, remaining, "%c%u", c, logger->logId);
+    ret = min(ret, remaining);
+    remaining -= ret;
+    cp += ret;
+    c = ',';
+  }
 
-    if (logger_list->tail) {
-        ret = snprintf(cp, remaining, " tail=%u", logger_list->tail);
-        ret = min(ret, remaining);
-        remaining -= ret;
-        cp += ret;
-    }
+  if (logger_list->tail) {
+    ret = snprintf(cp, remaining, " tail=%u", logger_list->tail);
+    ret = min(ret, remaining);
+    remaining -= ret;
+    cp += ret;
+  }
 
-    if (logger_list->start.tv_sec || logger_list->start.tv_nsec) {
-        if (logger_list->mode & ANDROID_LOG_WRAP) {
-            // ToDo: alternate API to allow timeout to be adjusted.
-            ret = snprintf(cp, remaining, " timeout=%u",
-                           ANDROID_LOG_WRAP_DEFAULT_TIMEOUT);
-            ret = min(ret, remaining);
-            remaining -= ret;
-            cp += ret;
-        }
-        ret = snprintf(cp, remaining, " start=%" PRIu32 ".%09" PRIu32,
-                       logger_list->start.tv_sec,
-                       logger_list->start.tv_nsec);
-        ret = min(ret, remaining);
-        remaining -= ret;
-        cp += ret;
+  if (logger_list->start.tv_sec || logger_list->start.tv_nsec) {
+    if (logger_list->mode & ANDROID_LOG_WRAP) {
+      // ToDo: alternate API to allow timeout to be adjusted.
+      ret = snprintf(cp, remaining, " timeout=%u",
+                     ANDROID_LOG_WRAP_DEFAULT_TIMEOUT);
+      ret = min(ret, remaining);
+      remaining -= ret;
+      cp += ret;
     }
+    ret = snprintf(cp, remaining, " start=%" PRIu32 ".%09" PRIu32,
+                   logger_list->start.tv_sec, logger_list->start.tv_nsec);
+    ret = min(ret, remaining);
+    remaining -= ret;
+    cp += ret;
+  }
 
-    if (logger_list->pid) {
-        ret = snprintf(cp, remaining, " pid=%u", logger_list->pid);
-        ret = min(ret, remaining);
-        cp += ret;
-    }
+  if (logger_list->pid) {
+    ret = snprintf(cp, remaining, " pid=%u", logger_list->pid);
+    ret = min(ret, remaining);
+    cp += ret;
+  }
 
-    if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-        /* Deal with an unresponsive logd */
-        memset(&ignore, 0, sizeof(ignore));
-        ignore.sa_handler = caught_signal;
-        sigemptyset(&ignore.sa_mask);
-        /* particularily useful if tombstone is reporting for logd */
-        sigaction(SIGALRM, &ignore, &old_sigaction);
-        old_alarm = alarm(30);
+  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
+    /* Deal with an unresponsive logd */
+    memset(&ignore, 0, sizeof(ignore));
+    ignore.sa_handler = caught_signal;
+    sigemptyset(&ignore.sa_mask);
+    /* particularily useful if tombstone is reporting for logd */
+    sigaction(SIGALRM, &ignore, &old_sigaction);
+    old_alarm = alarm(30);
+  }
+  ret = write(sock, buffer, cp - buffer);
+  e = errno;
+  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
+    if (e == EINTR) {
+      e = ETIMEDOUT;
     }
-    ret = write(sock, buffer, cp - buffer);
-    e = errno;
-    if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-        if (e == EINTR) {
-            e = ETIMEDOUT;
-        }
-        alarm(old_alarm);
-        sigaction(SIGALRM, &old_sigaction, NULL);
-    }
+    alarm(old_alarm);
+    sigaction(SIGALRM, &old_sigaction, NULL);
+  }
 
-    if (ret <= 0) {
-        close(sock);
-        if ((ret == -1) && e) {
-            return -e;
-        }
-        if (ret == 0) {
-            return -EIO;
-        }
-        return ret;
+  if (ret <= 0) {
+    close(sock);
+    if ((ret == -1) && e) {
+      return -e;
     }
+    if (ret == 0) {
+      return -EIO;
+    }
+    return ret;
+  }
 
-    return transp->context.sock = sock;
+  ret = atomic_exchange(&transp->context.sock, sock);
+  if ((ret > 0) && (ret != sock)) {
+    close(ret);
+  }
+  return sock;
 }
 
 /* Read from the selected logs */
-static int logdRead(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp,
-                    struct log_msg *log_msg)
-{
-    int ret, e;
-    struct sigaction ignore;
-    struct sigaction old_sigaction;
-    unsigned int old_alarm = 0;
+static int logdRead(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp,
+                    struct log_msg* log_msg) {
+  int ret, e;
+  struct sigaction ignore;
+  struct sigaction old_sigaction;
+  unsigned int old_alarm = 0;
 
-    ret = logdOpen(logger_list, transp);
-    if (ret < 0) {
-        return ret;
-    }
-
-    memset(log_msg, 0, sizeof(*log_msg));
-
-    if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-        memset(&ignore, 0, sizeof(ignore));
-        ignore.sa_handler = caught_signal;
-        sigemptyset(&ignore.sa_mask);
-        /* particularily useful if tombstone is reporting for logd */
-        sigaction(SIGALRM, &ignore, &old_sigaction);
-        old_alarm = alarm(30);
-    }
-
-    /* NOTE: SOCK_SEQPACKET guarantees we read exactly one full entry */
-    ret = recv(ret, log_msg, LOGGER_ENTRY_MAX_LEN, 0);
-    e = errno;
-
-    if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-        if ((ret == 0) || (e == EINTR)) {
-            e = EAGAIN;
-            ret = -1;
-        }
-        alarm(old_alarm);
-        sigaction(SIGALRM, &old_sigaction, NULL);
-    }
-
-    if ((ret == -1) && e) {
-        return -e;
-    }
+  ret = logdOpen(logger_list, transp);
+  if (ret < 0) {
     return ret;
+  }
+
+  memset(log_msg, 0, sizeof(*log_msg));
+
+  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
+    memset(&ignore, 0, sizeof(ignore));
+    ignore.sa_handler = caught_signal;
+    sigemptyset(&ignore.sa_mask);
+    /* particularily useful if tombstone is reporting for logd */
+    sigaction(SIGALRM, &ignore, &old_sigaction);
+    old_alarm = alarm(30);
+  }
+
+  /* NOTE: SOCK_SEQPACKET guarantees we read exactly one full entry */
+  ret = recv(ret, log_msg, LOGGER_ENTRY_MAX_LEN, 0);
+  e = errno;
+
+  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
+    if ((ret == 0) || (e == EINTR)) {
+      e = EAGAIN;
+      ret = -1;
+    }
+    alarm(old_alarm);
+    sigaction(SIGALRM, &old_sigaction, NULL);
+  }
+
+  if ((ret == -1) && e) {
+    return -e;
+  }
+  return ret;
 }
 
-static int logdPoll(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp)
-{
-    struct pollfd p;
+static int logdPoll(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp) {
+  struct pollfd p;
 
-    int ret = logdOpen(logger_list, transp);
-    if (ret < 0) {
-        return ret;
-    }
-
-    memset(&p, 0, sizeof(p));
-    p.fd = ret;
-    p.events = POLLIN;
-    ret = poll(&p, 1, 20);
-    if ((ret > 0) && !(p.revents & POLLIN)) {
-        ret = 0;
-    }
-    if ((ret == -1) && errno) {
-        return -errno;
-    }
+  int ret = logdOpen(logger_list, transp);
+  if (ret < 0) {
     return ret;
+  }
+
+  memset(&p, 0, sizeof(p));
+  p.fd = ret;
+  p.events = POLLIN;
+  ret = poll(&p, 1, 20);
+  if ((ret > 0) && !(p.revents & POLLIN)) {
+    ret = 0;
+  }
+  if ((ret == -1) && errno) {
+    return -errno;
+  }
+  return ret;
 }
 
 /* Close all the logs */
-static void logdClose(struct android_log_logger_list *logger_list __unused,
-                      struct android_log_transport_context *transp)
-{
-    if (transp->context.sock > 0) {
-        close (transp->context.sock);
-        transp->context.sock = -1;
-    }
+static void logdClose(struct android_log_logger_list* logger_list __unused,
+                      struct android_log_transport_context* transp) {
+  int sock = atomic_exchange(&transp->context.sock, -1);
+  if (sock > 0) {
+    close(sock);
+  }
 }
diff --git a/liblog/logd_reader.h b/liblog/logd_reader.h
new file mode 100644
index 0000000..8ebb1ae
--- /dev/null
+++ b/liblog/logd_reader.h
@@ -0,0 +1,30 @@
+/*
+ * 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 _LIBLOG_LOGD_READER_H__
+#define _LIBLOG_LOGD_READER_H__
+
+#include <unistd.h>
+
+#include "log_portability.h"
+
+__BEGIN_DECLS
+
+LIBLOG_HIDDEN ssize_t __send_log_msg(char* buf, size_t buf_size);
+
+__END_DECLS
+
+#endif /* _LIBLOG_LOGD_READER_H__ */
diff --git a/liblog/logd_writer.c b/liblog/logd_writer.c
index 059f170..e0e3eca 100644
--- a/liblog/logd_writer.c
+++ b/liblog/logd_writer.c
@@ -24,17 +24,14 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/socket.h>
 #include <sys/un.h>
 #include <time.h>
 #include <unistd.h>
 
 #include <cutils/sockets.h>
-#include <log/logd.h>
-#include <log/logger.h>
-#include <log/log_read.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
@@ -43,219 +40,251 @@
 #include "logger.h"
 
 /* branchless on many architectures. */
-#define min(x,y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
+#define min(x, y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
 
 static int logdAvailable(log_id_t LogId);
 static int logdOpen();
 static void logdClose();
-static int logdWrite(log_id_t logId, struct timespec *ts,
-                     struct iovec *vec, size_t nr);
+static int logdWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                     size_t nr);
 
 LIBLOG_HIDDEN struct android_log_transport_write logdLoggerWrite = {
-    .node = { &logdLoggerWrite.node, &logdLoggerWrite.node },
-    .context.sock = -1,
-    .name = "logd",
-    .available = logdAvailable,
-    .open = logdOpen,
-    .close = logdClose,
-    .write = logdWrite,
+  .node = { &logdLoggerWrite.node, &logdLoggerWrite.node },
+  .context.sock = -EBADF,
+  .name = "logd",
+  .available = logdAvailable,
+  .open = logdOpen,
+  .close = logdClose,
+  .write = logdWrite,
 };
 
 /* log_init_lock assumed */
-static int logdOpen()
-{
-    int i, ret = 0;
+static int logdOpen() {
+  int i, ret = 0;
 
-    if (logdLoggerWrite.context.sock < 0) {
-        i = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0));
-        if (i < 0) {
-            ret = -errno;
-        } else if (TEMP_FAILURE_RETRY(fcntl(i, F_SETFL, O_NONBLOCK)) < 0) {
-            ret = -errno;
-            close(i);
-        } else {
-            struct sockaddr_un un;
-            memset(&un, 0, sizeof(struct sockaddr_un));
-            un.sun_family = AF_UNIX;
-            strcpy(un.sun_path, "/dev/socket/logdw");
+  i = atomic_load(&logdLoggerWrite.context.sock);
+  if (i < 0) {
+    int sock = TEMP_FAILURE_RETRY(
+        socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
+    if (sock < 0) {
+      ret = -errno;
+    } else {
+      struct sockaddr_un un;
+      memset(&un, 0, sizeof(struct sockaddr_un));
+      un.sun_family = AF_UNIX;
+      strcpy(un.sun_path, "/dev/socket/logdw");
 
-            if (TEMP_FAILURE_RETRY(connect(i, (struct sockaddr *)&un,
-                                           sizeof(struct sockaddr_un))) < 0) {
-                ret = -errno;
-                close(i);
-            } else {
-                logdLoggerWrite.context.sock = i;
-            }
-        }
-    }
-
-    return ret;
-}
-
-static void logdClose()
-{
-    if (logdLoggerWrite.context.sock >= 0) {
-        close(logdLoggerWrite.context.sock);
-        logdLoggerWrite.context.sock = -1;
-    }
-}
-
-static int logdAvailable(log_id_t logId)
-{
-    if (logId > LOG_ID_SECURITY) {
-        return -EINVAL;
-    }
-    if (logdLoggerWrite.context.sock < 0) {
-        if (access("/dev/socket/logdw", W_OK) == 0) {
-            return 0;
-        }
-        return -EBADF;
-    }
-    return 1;
-}
-
-static int logdWrite(log_id_t logId, struct timespec *ts,
-                     struct iovec *vec, size_t nr)
-{
-    ssize_t ret;
-    static const unsigned headerLength = 1;
-    struct iovec newVec[nr + headerLength];
-    android_log_header_t header;
-    size_t i, payloadSize;
-    static atomic_int_fast32_t dropped;
-    static atomic_int_fast32_t droppedSecurity;
-
-    if (logdLoggerWrite.context.sock < 0) {
-        return -EBADF;
-    }
-
-    /* logd, after initialization and priv drop */
-    if (__android_log_uid() == AID_LOGD) {
-        /*
-         * ignore log messages we send to ourself (logd).
-         * Such log messages are often generated by libraries we depend on
-         * which use standard Android logging.
-         */
-        return 0;
-    }
-
-    /*
-     *  struct {
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
-
-    header.tid = gettid();
-    header.realtime.tv_sec = ts->tv_sec;
-    header.realtime.tv_nsec = ts->tv_nsec;
-
-    newVec[0].iov_base = (unsigned char *)&header;
-    newVec[0].iov_len  = sizeof(header);
-
-    if (logdLoggerWrite.context.sock > 0) {
-        int32_t snapshot = atomic_exchange_explicit(&droppedSecurity, 0,
-                                                    memory_order_relaxed);
-        if (snapshot) {
-            android_log_event_int_t buffer;
-
-            header.id = LOG_ID_SECURITY;
-            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
-            buffer.payload.type = EVENT_TYPE_INT;
-            buffer.payload.data = htole32(snapshot);
-
-            newVec[headerLength].iov_base = &buffer;
-            newVec[headerLength].iov_len  = sizeof(buffer);
-
-            ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, 2));
-            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
-                atomic_fetch_add_explicit(&droppedSecurity, snapshot,
-                                          memory_order_relaxed);
-            }
-        }
-        snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
-        if (snapshot && __android_log_is_loggable(ANDROID_LOG_INFO,
-                                                  "liblog",
-                                                  ANDROID_LOG_VERBOSE)) {
-            android_log_event_int_t buffer;
-
-            header.id = LOG_ID_EVENTS;
-            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
-            buffer.payload.type = EVENT_TYPE_INT;
-            buffer.payload.data = htole32(snapshot);
-
-            newVec[headerLength].iov_base = &buffer;
-            newVec[headerLength].iov_len  = sizeof(buffer);
-
-            ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, 2));
-            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
-                atomic_fetch_add_explicit(&dropped, snapshot,
-                                          memory_order_relaxed);
-            }
-        }
-    }
-
-    header.id = logId;
-
-    for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
-        newVec[i].iov_base = vec[i - headerLength].iov_base;
-        payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
-
-        if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
-            newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
-            if (newVec[i].iov_len) {
-                ++i;
-            }
+      if (TEMP_FAILURE_RETRY(connect(sock, (struct sockaddr*)&un,
+                                     sizeof(struct sockaddr_un))) < 0) {
+        ret = -errno;
+        switch (ret) {
+          case -ENOTCONN:
+          case -ECONNREFUSED:
+          case -ENOENT:
+            i = atomic_exchange(&logdLoggerWrite.context.sock, ret);
+          /* FALLTHRU */
+          default:
             break;
         }
+        close(sock);
+      } else {
+        ret = atomic_exchange(&logdLoggerWrite.context.sock, sock);
+        if ((ret >= 0) && (ret != sock)) {
+          close(ret);
+        }
+        ret = 0;
+      }
+    }
+  }
+
+  return ret;
+}
+
+static void __logdClose(int negative_errno) {
+  int sock = atomic_exchange(&logdLoggerWrite.context.sock, negative_errno);
+  if (sock >= 0) {
+    close(sock);
+  }
+}
+
+static void logdClose() {
+  __logdClose(-EBADF);
+}
+
+static int logdAvailable(log_id_t logId) {
+  if (logId >= LOG_ID_MAX || logId == LOG_ID_KERNEL) {
+    return -EINVAL;
+  }
+  if (atomic_load(&logdLoggerWrite.context.sock) < 0) {
+    if (access("/dev/socket/logdw", W_OK) == 0) {
+      return 0;
+    }
+    return -EBADF;
+  }
+  return 1;
+}
+
+static int logdWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                     size_t nr) {
+  ssize_t ret;
+  int sock;
+  static const unsigned headerLength = 1;
+  struct iovec newVec[nr + headerLength];
+  android_log_header_t header;
+  size_t i, payloadSize;
+  static atomic_int_fast32_t dropped;
+  static atomic_int_fast32_t droppedSecurity;
+
+  sock = atomic_load(&logdLoggerWrite.context.sock);
+  if (sock < 0) switch (sock) {
+      case -ENOTCONN:
+      case -ECONNREFUSED:
+      case -ENOENT:
+        break;
+      default:
+        return -EBADF;
     }
 
+  /* logd, after initialization and priv drop */
+  if (__android_log_uid() == AID_LOGD) {
     /*
-     * The write below could be lost, but will never block.
-     *
-     * ENOTCONN occurs if logd dies.
-     * EAGAIN occurs if logd is overloaded.
+     * ignore log messages we send to ourself (logd).
+     * Such log messages are often generated by libraries we depend on
+     * which use standard Android logging.
      */
-    ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, i));
+    return 0;
+  }
+
+  /*
+   *  struct {
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
+
+  header.tid = gettid();
+  header.realtime.tv_sec = ts->tv_sec;
+  header.realtime.tv_nsec = ts->tv_nsec;
+
+  newVec[0].iov_base = (unsigned char*)&header;
+  newVec[0].iov_len = sizeof(header);
+
+  if (sock >= 0) {
+    int32_t snapshot =
+        atomic_exchange_explicit(&droppedSecurity, 0, memory_order_relaxed);
+    if (snapshot) {
+      android_log_event_int_t buffer;
+
+      header.id = LOG_ID_SECURITY;
+      buffer.header.tag = htole32(LIBLOG_LOG_TAG);
+      buffer.payload.type = EVENT_TYPE_INT;
+      buffer.payload.data = htole32(snapshot);
+
+      newVec[headerLength].iov_base = &buffer;
+      newVec[headerLength].iov_len = sizeof(buffer);
+
+      ret = TEMP_FAILURE_RETRY(writev(sock, newVec, 2));
+      if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
+        atomic_fetch_add_explicit(&droppedSecurity, snapshot,
+                                  memory_order_relaxed);
+      }
+    }
+    snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
+    if (snapshot &&
+        __android_log_is_loggable_len(ANDROID_LOG_INFO, "liblog",
+                                      strlen("liblog"), ANDROID_LOG_VERBOSE)) {
+      android_log_event_int_t buffer;
+
+      header.id = LOG_ID_EVENTS;
+      buffer.header.tag = htole32(LIBLOG_LOG_TAG);
+      buffer.payload.type = EVENT_TYPE_INT;
+      buffer.payload.data = htole32(snapshot);
+
+      newVec[headerLength].iov_base = &buffer;
+      newVec[headerLength].iov_len = sizeof(buffer);
+
+      ret = TEMP_FAILURE_RETRY(writev(sock, newVec, 2));
+      if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
+        atomic_fetch_add_explicit(&dropped, snapshot, memory_order_relaxed);
+      }
+    }
+  }
+
+  header.id = logId;
+
+  for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
+    newVec[i].iov_base = vec[i - headerLength].iov_base;
+    payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
+
+    if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
+      newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
+      if (newVec[i].iov_len) {
+        ++i;
+      }
+      break;
+    }
+  }
+
+  /*
+   * The write below could be lost, but will never block.
+   *
+   * ENOTCONN occurs if logd has died.
+   * ENOENT occurs if logd is not running and socket is missing.
+   * ECONNREFUSED occurs if we can not reconnect to logd.
+   * EAGAIN occurs if logd is overloaded.
+   */
+  if (sock < 0) {
+    ret = sock;
+  } else {
+    ret = TEMP_FAILURE_RETRY(writev(sock, newVec, i));
     if (ret < 0) {
+      ret = -errno;
+    }
+  }
+  switch (ret) {
+    case -ENOTCONN:
+    case -ECONNREFUSED:
+    case -ENOENT:
+      if (__android_log_trylock()) {
+        return ret; /* in a signal handler? try again when less stressed */
+      }
+      __logdClose(ret);
+      ret = logdOpen();
+      __android_log_unlock();
+
+      if (ret < 0) {
+        return ret;
+      }
+
+      ret = TEMP_FAILURE_RETRY(
+          writev(atomic_load(&logdLoggerWrite.context.sock), newVec, i));
+      if (ret < 0) {
         ret = -errno;
-        if (ret == -ENOTCONN) {
-            __android_log_lock();
-            logdClose();
-            ret = logdOpen();
-            __android_log_unlock();
+      }
+    /* FALLTHRU */
+    default:
+      break;
+  }
 
-            if (ret < 0) {
-                return ret;
-            }
-
-            ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, i));
-            if (ret < 0) {
-                ret = -errno;
-            }
-        }
+  if (ret > (ssize_t)sizeof(header)) {
+    ret -= sizeof(header);
+  } else if (ret == -EAGAIN) {
+    atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
+    if (logId == LOG_ID_SECURITY) {
+      atomic_fetch_add_explicit(&droppedSecurity, 1, memory_order_relaxed);
     }
+  }
 
-    if (ret > (ssize_t)sizeof(header)) {
-        ret -= sizeof(header);
-    } else if (ret == -EAGAIN) {
-        atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
-        if (logId == LOG_ID_SECURITY) {
-            atomic_fetch_add_explicit(&droppedSecurity, 1,
-                                      memory_order_relaxed);
-        }
-    }
-
-    return ret;
+  return ret;
 }
diff --git a/liblog/logger.h b/liblog/logger.h
index 0964756..246b33c 100644
--- a/liblog/logger.h
+++ b/liblog/logger.h
@@ -17,13 +17,12 @@
 #ifndef _LIBLOG_LOGGER_H__
 #define _LIBLOG_LOGGER_H__
 
+#include <stdatomic.h>
 #include <stdbool.h>
-#include <log/uio.h>
 
 #include <cutils/list.h>
 #include <log/log.h>
-#include <log/log_read.h>
-#include <log/logger.h>
+#include <log/uio.h>
 
 #include "log_portability.h"
 
@@ -31,22 +30,25 @@
 
 /* Union, sock or fd of zero is not allowed unless static initialized */
 union android_log_context {
-  void *private;
-  int sock;
-  int fd;
-  struct listnode *node;
+  void* priv;
+  atomic_int sock;
+  atomic_int fd;
+  struct listnode* node;
+  atomic_uintptr_t atomic_pointer;
 };
 
 struct android_log_transport_write {
   struct listnode node;
-  const char *name;
-  unsigned logMask; /* cache of available success */
+  const char* name;                  /* human name to describe the transport */
+  unsigned logMask;                  /* mask cache of available() success */
   union android_log_context context; /* Initialized by static allocation */
 
-  int (*available)(log_id_t logId);
-  int (*open)();
-  void (*close)();
-  int (*write)(log_id_t logId, struct timespec *ts, struct iovec *vec, size_t nr);
+  int (*available)(log_id_t logId); /* Does not cause resources to be taken */
+  int (*open)();   /* can be called multiple times, reusing current resources */
+  void (*close)(); /* free up resources */
+  /* write log to transport, returns number of bytes propagated, or -errno */
+  int (*write)(log_id_t logId, struct timespec* ts, struct iovec* vec,
+               size_t nr);
 };
 
 struct android_log_logger_list;
@@ -55,47 +57,48 @@
 
 struct android_log_transport_read {
   struct listnode node;
-  const char *name;
+  const char* name; /* human name to describe the transport */
 
+  /* Does not cause resources to be taken */
   int (*available)(log_id_t logId);
-  int (*version)(struct android_log_logger *logger,
-                 struct android_log_transport_context *transp);
-  void (*close)(struct android_log_logger_list *logger_list,
-                struct android_log_transport_context *transp);
-
+  int (*version)(struct android_log_logger* logger,
+                 struct android_log_transport_context* transp);
+  /* Release resources taken by the following interfaces */
+  void (*close)(struct android_log_logger_list* logger_list,
+                struct android_log_transport_context* transp);
   /*
-   * Expect all to instantiate open on any call, so we do not have
-   * an expicit open call
+   * Expect all to instantiate open automagically on any call,
+   * so we do not have an explicit open call.
    */
-  int (*read)(struct android_log_logger_list *logger_list,
-              struct android_log_transport_context *transp,
-              struct log_msg *log_msg);
-  /* Assumption is only called if not ANDROID_LOG_NONBLOCK */
-  int (*poll)(struct android_log_logger_list *logger_list,
-              struct android_log_transport_context *transp);
+  int (*read)(struct android_log_logger_list* logger_list,
+              struct android_log_transport_context* transp,
+              struct log_msg* log_msg);
+  /* Must only be called if not ANDROID_LOG_NONBLOCK (blocking) */
+  int (*poll)(struct android_log_logger_list* logger_list,
+              struct android_log_transport_context* transp);
 
-  int (*clear)(struct android_log_logger *logger,
-               struct android_log_transport_context *transp);
-  ssize_t (*setSize)(struct android_log_logger *logger,
-                     struct android_log_transport_context *transp,
-                     size_t size);
-  ssize_t (*getSize)(struct android_log_logger *logger,
-                     struct android_log_transport_context *transp);
-  ssize_t (*getReadableSize)(struct android_log_logger *logger,
-                             struct android_log_transport_context *transp);
+  int (*clear)(struct android_log_logger* logger,
+               struct android_log_transport_context* transp);
+  ssize_t (*setSize)(struct android_log_logger* logger,
+                     struct android_log_transport_context* transp, size_t size);
+  ssize_t (*getSize)(struct android_log_logger* logger,
+                     struct android_log_transport_context* transp);
+  ssize_t (*getReadableSize)(struct android_log_logger* logger,
+                             struct android_log_transport_context* transp);
 
-  ssize_t (*getPrune)(struct android_log_logger_list *logger_list,
-                      struct android_log_transport_context *transp,
-                      char *buf, size_t len);
-  ssize_t (*setPrune)(struct android_log_logger_list *logger_list,
-                      struct android_log_transport_context *transp,
-                      char *buf, size_t len);
-  ssize_t (*getStats)(struct android_log_logger_list *logger_list,
-                      struct android_log_transport_context *transp,
-                      char *buf, size_t len);
+  ssize_t (*getPrune)(struct android_log_logger_list* logger_list,
+                      struct android_log_transport_context* transp, char* buf,
+                      size_t len);
+  ssize_t (*setPrune)(struct android_log_logger_list* logger_list,
+                      struct android_log_transport_context* transp, char* buf,
+                      size_t len);
+  ssize_t (*getStats)(struct android_log_logger_list* logger_list,
+                      struct android_log_transport_context* transp, char* buf,
+                      size_t len);
 };
 
 struct android_log_logger_list {
+  struct listnode node;
   struct listnode logger;
   struct listnode transport;
   int mode;
@@ -106,7 +109,7 @@
 
 struct android_log_logger {
   struct listnode node;
-  struct android_log_logger_list *parent;
+  struct android_log_logger_list* parent;
 
   log_id_t logId;
 };
@@ -114,49 +117,83 @@
 struct android_log_transport_context {
   struct listnode node;
   union android_log_context context; /* zero init per-transport context */
-  struct android_log_logger_list *parent;
+  struct android_log_logger_list* parent;
 
-  struct android_log_transport_read *transport;
-  unsigned logMask;
-  int ret;
-  struct log_msg logMsg; /* valid is logMsg.len != 0 */
+  struct android_log_transport_read* transport;
+  unsigned logMask;      /* mask of requested log buffers */
+  int ret;               /* return value associated with following data */
+  struct log_msg logMsg; /* peek at upcoming data, valid if logMsg.len != 0 */
 };
 
 /* assumes caller has structures read-locked, single threaded, or fenced */
-#define transport_context_for_each(transp, logger_list)              \
-  for (transp = node_to_item((logger_list)->transport.next,          \
-                             struct android_log_transport_context,   \
-                             node);                                  \
-       (transp != node_to_item(&(logger_list)->transport,            \
-                               struct android_log_transport_context, \
-                               node)) &&                             \
-           (transp->parent == (logger_list));                        \
-       transp = node_to_item(transp->node.next,                      \
-                             struct android_log_transport_context, node))
+#define transport_context_for_each(transp, logger_list)                          \
+  for ((transp) = node_to_item((logger_list)->transport.next,                    \
+                               struct android_log_transport_context, node);      \
+       ((transp) != node_to_item(&(logger_list)->transport,                      \
+                                 struct android_log_transport_context, node)) && \
+       ((transp)->parent == (logger_list));                                      \
+       (transp) = node_to_item((transp)->node.next,                              \
+                               struct android_log_transport_context, node))
 
 #define logger_for_each(logp, logger_list)                          \
-    for (logp = node_to_item((logger_list)->logger.next,            \
+  for ((logp) = node_to_item((logger_list)->logger.next,            \
                              struct android_log_logger, node);      \
-         (logp != node_to_item(&(logger_list)->logger,              \
+       ((logp) != node_to_item(&(logger_list)->logger,              \
                                struct android_log_logger, node)) && \
-             (logp->parent == (logger_list));                       \
-         logp = node_to_item((logp)->node.next,                     \
-                             struct android_log_logger, node))
+       ((logp)->parent == (logger_list));                           \
+       (logp) =                                                     \
+           node_to_item((logp)->node.next, struct android_log_logger, node))
+
+/*
+ *    Global list of log readers.
+ *
+ * Usage case: search out transport contexts for all readers
+ */
+
+LIBLOG_HIDDEN struct listnode __android_log_readers;
+
+#if defined(_WIN32)
+#define logger_list_rdlock()
+#define logger_list_wrlock()
+#define logger_list_unlock()
+#else
+LIBLOG_HIDDEN pthread_rwlock_t __android_log_readers_lock;
+
+#define logger_list_rdlock() pthread_rwlock_rdlock(&__android_log_readers_lock)
+#define logger_list_wrlock() pthread_rwlock_wrlock(&__android_log_readers_lock)
+#define logger_list_unlock() pthread_rwlock_unlock(&__android_log_readers_lock)
+#endif
+
+/* Must be called with logger_list_rdlock() or logger_list_wrlock() held */
+#define logger_list_for_each(logger_list)                                     \
+  for ((logger_list) = node_to_item(&__android_log_readers,                   \
+                                    struct android_log_logger_list, node);    \
+       (logger_list) != node_to_item(&__android_log_readers,                  \
+                                     struct android_log_logger_list, node) && \
+       (logger_list) != node_to_item((logger_list)->node.next,                \
+                                     struct android_log_logger_list, node);   \
+       (logger_list) = node_to_item((logger_list)->node.next,                 \
+                                    struct android_log_logger_list, node))
 
 /* OS specific dribs and drabs */
 
 #if defined(_WIN32)
 #include <private/android_filesystem_config.h>
 typedef uint32_t uid_t;
-static inline uid_t __android_log_uid() { return AID_SYSTEM; }
+static inline uid_t __android_log_uid() {
+  return AID_SYSTEM;
+}
 #else
-static inline uid_t __android_log_uid() { return getuid(); }
+static inline uid_t __android_log_uid() {
+  return getuid();
+}
 #endif
 
 LIBLOG_HIDDEN void __android_log_lock();
 LIBLOG_HIDDEN int __android_log_trylock();
 LIBLOG_HIDDEN void __android_log_unlock();
-LIBLOG_HIDDEN int __android_log_is_debuggable();
+
+LIBLOG_HIDDEN int __android_log_transport;
 
 __END_DECLS
 
diff --git a/liblog/logger_lock.c b/liblog/logger_lock.c
index 14feee0..d4e3a75 100644
--- a/liblog/logger_lock.c
+++ b/liblog/logger_lock.c
@@ -28,29 +28,26 @@
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
-LIBLOG_HIDDEN void __android_log_lock()
-{
+LIBLOG_HIDDEN void __android_log_lock() {
 #if !defined(_WIN32)
-    /*
-     * If we trigger a signal handler in the middle of locked activity and the
-     * signal handler logs a message, we could get into a deadlock state.
-     */
-    pthread_mutex_lock(&log_init_lock);
+  /*
+   * If we trigger a signal handler in the middle of locked activity and the
+   * signal handler logs a message, we could get into a deadlock state.
+   */
+  pthread_mutex_lock(&log_init_lock);
 #endif
 }
 
-LIBLOG_HIDDEN int __android_log_trylock()
-{
+LIBLOG_HIDDEN int __android_log_trylock() {
 #if !defined(_WIN32)
-    return pthread_mutex_trylock(&log_init_lock);
+  return pthread_mutex_trylock(&log_init_lock);
 #else
-    return 0;
+  return 0;
 #endif
 }
 
-LIBLOG_HIDDEN void __android_log_unlock()
-{
+LIBLOG_HIDDEN void __android_log_unlock() {
 #if !defined(_WIN32)
-    pthread_mutex_unlock(&log_init_lock);
+  pthread_mutex_unlock(&log_init_lock);
 #endif
 }
diff --git a/liblog/logger_name.c b/liblog/logger_name.c
index b7ccac5..a5a83e0 100644
--- a/liblog/logger_name.c
+++ b/liblog/logger_name.c
@@ -17,49 +17,48 @@
 #include <string.h>
 
 #include <log/log.h>
-#include <log/logger.h>
 
 #include "log_portability.h"
 
 /* In the future, we would like to make this list extensible */
-static const char *LOG_NAME[LOG_ID_MAX] = {
-    [LOG_ID_MAIN] = "main",
-    [LOG_ID_RADIO] = "radio",
-    [LOG_ID_EVENTS] = "events",
-    [LOG_ID_SYSTEM] = "system",
-    [LOG_ID_CRASH] = "crash",
-    [LOG_ID_SECURITY] = "security",
-    [LOG_ID_KERNEL] = "kernel",
+static const char* LOG_NAME[LOG_ID_MAX] = {
+  /* clang-format off */
+  [LOG_ID_MAIN] = "main",
+  [LOG_ID_RADIO] = "radio",
+  [LOG_ID_EVENTS] = "events",
+  [LOG_ID_SYSTEM] = "system",
+  [LOG_ID_CRASH] = "crash",
+  [LOG_ID_SECURITY] = "security",
+  [LOG_ID_KERNEL] = "kernel",
+  /* clang-format on */
 };
 
-LIBLOG_ABI_PUBLIC const char *android_log_id_to_name(log_id_t log_id)
-{
-    if (log_id >= LOG_ID_MAX) {
-        log_id = LOG_ID_MAIN;
-    }
-    return LOG_NAME[log_id];
+LIBLOG_ABI_PUBLIC const char* android_log_id_to_name(log_id_t log_id) {
+  if (log_id >= LOG_ID_MAX) {
+    log_id = LOG_ID_MAIN;
+  }
+  return LOG_NAME[log_id];
 }
 
-LIBLOG_ABI_PUBLIC log_id_t android_name_to_log_id(const char *logName)
-{
-    const char *b;
-    int ret;
+LIBLOG_ABI_PUBLIC log_id_t android_name_to_log_id(const char* logName) {
+  const char* b;
+  int ret;
 
-    if (!logName) {
-        return -1; /* NB: log_id_t is unsigned */
-    }
-    b = strrchr(logName, '/');
-    if (!b) {
-        b = logName;
-    } else {
-        ++b;
-    }
+  if (!logName) {
+    return -1; /* NB: log_id_t is unsigned */
+  }
+  b = strrchr(logName, '/');
+  if (!b) {
+    b = logName;
+  } else {
+    ++b;
+  }
 
-    for(ret = LOG_ID_MIN; ret < LOG_ID_MAX; ++ret) {
-        const char *l = LOG_NAME[ret];
-        if (l && !strcmp(b, l)) {
-            return ret;
-        }
+  for (ret = LOG_ID_MIN; ret < LOG_ID_MAX; ++ret) {
+    const char* l = LOG_NAME[ret];
+    if (l && !strcmp(b, l)) {
+      return ret;
     }
-    return -1;   /* should never happen */
+  }
+  return -1; /* should never happen */
 }
diff --git a/liblog/logger_read.c b/liblog/logger_read.c
index 0d6ba08..0fd6efa 100644
--- a/liblog/logger_read.c
+++ b/liblog/logger_read.c
@@ -23,9 +23,8 @@
 #include <string.h>
 #include <unistd.h>
 
+#include <android/log.h>
 #include <cutils/list.h>
-#include <log/log.h>
-#include <log/logger.h>
 #include <private/android_filesystem_config.h>
 
 #include "config_read.h"
@@ -34,135 +33,128 @@
 
 /* android_logger_alloc unimplemented, no use case */
 /* android_logger_free not exported */
-static void android_logger_free(struct logger *logger)
-{
-    struct android_log_logger *logger_internal =
-            (struct android_log_logger *)logger;
+static void android_logger_free(struct logger* logger) {
+  struct android_log_logger* logger_internal =
+      (struct android_log_logger*)logger;
 
-    if (!logger_internal) {
-        return;
-    }
+  if (!logger_internal) {
+    return;
+  }
 
-    list_remove(&logger_internal->node);
+  list_remove(&logger_internal->node);
 
-    free(logger_internal);
+  free(logger_internal);
 }
 
 /* android_logger_alloc unimplemented, no use case */
 
 /* method for getting the associated sublog id */
-LIBLOG_ABI_PUBLIC log_id_t android_logger_get_id(struct logger *logger)
-{
-    return ((struct android_log_logger *)logger)->logId;
+LIBLOG_ABI_PUBLIC log_id_t android_logger_get_id(struct logger* logger) {
+  return ((struct android_log_logger*)logger)->logId;
 }
 
-static int init_transport_context(struct android_log_logger_list *logger_list)
-{
-    struct android_log_transport_read *transport;
-    struct listnode *node;
+static int init_transport_context(struct android_log_logger_list* logger_list) {
+  struct android_log_transport_read* transport;
+  struct listnode* node;
 
-    if (!logger_list) {
-        return -EINVAL;
-    }
+  if (!logger_list) {
+    return -EINVAL;
+  }
 
-    if (list_empty(&logger_list->logger)) {
-        return -EINVAL;
-    }
+  if (list_empty(&logger_list->logger)) {
+    return -EINVAL;
+  }
 
-    if (!list_empty(&logger_list->transport)) {
-        return 0;
-    }
-
-    __android_log_lock();
-    /* mini __write_to_log_initialize() to populate transports */
-    if (list_empty(&__android_log_transport_read) &&
-            list_empty(&__android_log_persist_read)) {
-        __android_log_config_read();
-    }
-    __android_log_unlock();
-
-    node = (logger_list->mode & ANDROID_LOG_PSTORE) ?
-            &__android_log_persist_read : &__android_log_transport_read;
-
-    read_transport_for_each(transport, node) {
-        struct android_log_transport_context *transp;
-        struct android_log_logger *logger;
-        unsigned logMask = 0;
-
-        logger_for_each(logger, logger_list) {
-            log_id_t logId = logger->logId;
-
-            if ((logId == LOG_ID_SECURITY) &&
-                    (__android_log_uid() != AID_SYSTEM)) {
-                continue;
-            }
-            if (transport->read &&
-                    (!transport->available ||
-                        (transport->available(logId) >= 0))) {
-                logMask |= 1 << logId;
-            }
-        }
-        if (!logMask) {
-            continue;
-        }
-        transp = calloc(1, sizeof(*transp));
-        if (!transp) {
-            return -ENOMEM;
-        }
-        transp->parent = logger_list;
-        transp->transport = transport;
-        transp->logMask = logMask;
-        transp->ret = 1;
-        list_add_tail(&logger_list->transport, &transp->node);
-    }
-    if (list_empty(&logger_list->transport)) {
-        return -ENODEV;
-    }
+  if (!list_empty(&logger_list->transport)) {
     return 0;
+  }
+
+  __android_log_lock();
+  /* mini __write_to_log_initialize() to populate transports */
+  if (list_empty(&__android_log_transport_read) &&
+      list_empty(&__android_log_persist_read)) {
+    __android_log_config_read();
+  }
+  __android_log_unlock();
+
+  node = (logger_list->mode & ANDROID_LOG_PSTORE)
+             ? &__android_log_persist_read
+             : &__android_log_transport_read;
+
+  read_transport_for_each(transport, node) {
+    struct android_log_transport_context* transp;
+    struct android_log_logger* logger;
+    unsigned logMask = 0;
+
+    logger_for_each(logger, logger_list) {
+      log_id_t logId = logger->logId;
+
+      if ((logId == LOG_ID_SECURITY) && (__android_log_uid() != AID_SYSTEM)) {
+        continue;
+      }
+      if (transport->read &&
+          (!transport->available || (transport->available(logId) >= 0))) {
+        logMask |= 1 << logId;
+      }
+    }
+    if (!logMask) {
+      continue;
+    }
+    transp = calloc(1, sizeof(*transp));
+    if (!transp) {
+      return -ENOMEM;
+    }
+    transp->parent = logger_list;
+    transp->transport = transport;
+    transp->logMask = logMask;
+    transp->ret = 1;
+    list_add_tail(&logger_list->transport, &transp->node);
+  }
+  if (list_empty(&logger_list->transport)) {
+    return -ENODEV;
+  }
+  return 0;
 }
 
-#define LOGGER_FUNCTION(logger, def, func, args...)                           \
-    ssize_t ret = -EINVAL;                                                    \
-    struct android_log_transport_context *transp;                             \
-    struct android_log_logger *logger_internal =                              \
-            (struct android_log_logger *)logger;                              \
-                                                                              \
-    if (!logger_internal) {                                                   \
-        return ret;                                                           \
-    }                                                                         \
-    ret = init_transport_context(logger_internal->parent);                    \
-    if (ret < 0) {                                                            \
-        return ret;                                                           \
-    }                                                                         \
-                                                                              \
-    ret = (def);                                                              \
-    transport_context_for_each(transp, logger_internal->parent) {             \
-        if ((transp->logMask & (1 << logger_internal->logId)) &&              \
-                transp->transport && transp->transport->func) {               \
-            ssize_t retval = (transp->transport->func)(logger_internal,       \
-                                                       transp, ## args);      \
-            if ((ret >= 0) || (ret == (def))) {                               \
-                ret = retval;                                                 \
-            }                                                                 \
-        }                                                                     \
-    }                                                                         \
-    return ret
+#define LOGGER_FUNCTION(logger, def, func, args...)                   \
+  ssize_t ret = -EINVAL;                                              \
+  struct android_log_transport_context* transp;                       \
+  struct android_log_logger* logger_internal =                        \
+      (struct android_log_logger*)(logger);                           \
+                                                                      \
+  if (!logger_internal) {                                             \
+    return ret;                                                       \
+  }                                                                   \
+  ret = init_transport_context(logger_internal->parent);              \
+  if (ret < 0) {                                                      \
+    return ret;                                                       \
+  }                                                                   \
+                                                                      \
+  ret = (def);                                                        \
+  transport_context_for_each(transp, logger_internal->parent) {       \
+    if ((transp->logMask & (1 << logger_internal->logId)) &&          \
+        transp->transport && transp->transport->func) {               \
+      ssize_t retval =                                                \
+          (transp->transport->func)(logger_internal, transp, ##args); \
+      if ((ret >= 0) || (ret == (def))) {                             \
+        ret = retval;                                                 \
+      }                                                               \
+    }                                                                 \
+  }                                                                   \
+  return ret
 
-LIBLOG_ABI_PUBLIC int android_logger_clear(struct logger *logger)
-{
-    LOGGER_FUNCTION(logger, -ENODEV, clear);
+LIBLOG_ABI_PUBLIC int android_logger_clear(struct logger* logger) {
+  LOGGER_FUNCTION(logger, -ENODEV, clear);
 }
 
 /* returns the total size of the log's ring buffer */
-LIBLOG_ABI_PUBLIC long android_logger_get_log_size(struct logger *logger)
-{
-    LOGGER_FUNCTION(logger, -ENODEV, getSize);
+LIBLOG_ABI_PUBLIC long android_logger_get_log_size(struct logger* logger) {
+  LOGGER_FUNCTION(logger, -ENODEV, getSize);
 }
 
-LIBLOG_ABI_PUBLIC int android_logger_set_log_size(struct logger *logger,
-                                                  unsigned long size)
-{
-    LOGGER_FUNCTION(logger, -ENODEV, setSize, size);
+LIBLOG_ABI_PUBLIC int android_logger_set_log_size(struct logger* logger,
+                                                  unsigned long size) {
+  LOGGER_FUNCTION(logger, -ENODEV, setSize, size);
 }
 
 /*
@@ -170,310 +162,338 @@
  * log consumed)
  */
 LIBLOG_ABI_PUBLIC long android_logger_get_log_readable_size(
-        struct logger *logger)
-{
-    LOGGER_FUNCTION(logger, -ENODEV, getReadableSize);
+    struct logger* logger) {
+  LOGGER_FUNCTION(logger, -ENODEV, getReadableSize);
 }
 
 /*
  * returns the logger version
  */
-LIBLOG_ABI_PUBLIC int android_logger_get_log_version(struct logger *logger)
-{
-    LOGGER_FUNCTION(logger, 4, version);
+LIBLOG_ABI_PUBLIC int android_logger_get_log_version(struct logger* logger) {
+  LOGGER_FUNCTION(logger, 4, version);
 }
 
-#define LOGGER_LIST_FUNCTION(logger_list, def, func, args...)                 \
-    struct android_log_transport_context *transp;                             \
-    struct android_log_logger_list *logger_list_internal =                    \
-            (struct android_log_logger_list *)logger_list;                    \
-                                                                              \
-    ssize_t ret = init_transport_context(logger_list_internal);               \
-    if (ret < 0) {                                                            \
-        return ret;                                                           \
-    }                                                                         \
-                                                                              \
-    ret = (def);                                                              \
-    transport_context_for_each(transp, logger_list_internal) {                \
-        if (transp->transport && (transp->transport->func)) {                 \
-            ssize_t retval = (transp->transport->func)(logger_list_internal,  \
-                                                       transp, ## args);      \
-            if ((ret >= 0) || (ret == (def))) {                               \
-                ret = retval;                                                 \
-            }                                                                 \
-        }                                                                     \
-    }                                                                         \
-    return ret
+#define LOGGER_LIST_FUNCTION(logger_list, def, func, args...)              \
+  struct android_log_transport_context* transp;                            \
+  struct android_log_logger_list* logger_list_internal =                   \
+      (struct android_log_logger_list*)(logger_list);                      \
+                                                                           \
+  ssize_t ret = init_transport_context(logger_list_internal);              \
+  if (ret < 0) {                                                           \
+    return ret;                                                            \
+  }                                                                        \
+                                                                           \
+  ret = (def);                                                             \
+  transport_context_for_each(transp, logger_list_internal) {               \
+    if (transp->transport && (transp->transport->func)) {                  \
+      ssize_t retval =                                                     \
+          (transp->transport->func)(logger_list_internal, transp, ##args); \
+      if ((ret >= 0) || (ret == (def))) {                                  \
+        ret = retval;                                                      \
+      }                                                                    \
+    }                                                                      \
+  }                                                                        \
+  return ret
 
 /*
  * returns statistics
  */
 LIBLOG_ABI_PUBLIC ssize_t android_logger_get_statistics(
-        struct logger_list *logger_list,
-        char *buf, size_t len)
-{
-    LOGGER_LIST_FUNCTION(logger_list, -ENODEV, getStats, buf, len);
+    struct logger_list* logger_list, char* buf, size_t len) {
+  LOGGER_LIST_FUNCTION(logger_list, -ENODEV, getStats, buf, len);
 }
 
 LIBLOG_ABI_PUBLIC ssize_t android_logger_get_prune_list(
-        struct logger_list *logger_list,
-        char *buf, size_t len)
-{
-    LOGGER_LIST_FUNCTION(logger_list, -ENODEV, getPrune, buf, len);
+    struct logger_list* logger_list, char* buf, size_t len) {
+  LOGGER_LIST_FUNCTION(logger_list, -ENODEV, getPrune, buf, len);
 }
 
 LIBLOG_ABI_PUBLIC int android_logger_set_prune_list(
-        struct logger_list *logger_list,
-        char *buf, size_t len)
-{
-    LOGGER_LIST_FUNCTION(logger_list, -ENODEV, setPrune, buf, len);
+    struct logger_list* logger_list, char* buf, size_t len) {
+  LOGGER_LIST_FUNCTION(logger_list, -ENODEV, setPrune, buf, len);
 }
 
-LIBLOG_ABI_PUBLIC struct logger_list *android_logger_list_alloc(
-        int mode,
-        unsigned int tail,
-        pid_t pid)
-{
-    struct android_log_logger_list *logger_list;
+LIBLOG_HIDDEN struct listnode __android_log_readers = { &__android_log_readers,
+                                                        &__android_log_readers };
+#if !defined(_WIN32)
+LIBLOG_HIDDEN pthread_rwlock_t __android_log_readers_lock =
+    PTHREAD_RWLOCK_INITIALIZER;
+#endif
 
-    logger_list = calloc(1, sizeof(*logger_list));
-    if (!logger_list) {
-        return NULL;
-    }
+LIBLOG_ABI_PUBLIC struct logger_list* android_logger_list_alloc(
+    int mode, unsigned int tail, pid_t pid) {
+  struct android_log_logger_list* logger_list;
 
-    list_init(&logger_list->logger);
-    list_init(&logger_list->transport);
-    logger_list->mode = mode;
-    logger_list->tail = tail;
-    logger_list->pid = pid;
+  logger_list = calloc(1, sizeof(*logger_list));
+  if (!logger_list) {
+    return NULL;
+  }
 
-    return (struct logger_list *)logger_list;
+  list_init(&logger_list->logger);
+  list_init(&logger_list->transport);
+  logger_list->mode = mode;
+  logger_list->tail = tail;
+  logger_list->pid = pid;
+
+  logger_list_wrlock();
+  list_add_tail(&__android_log_readers, &logger_list->node);
+  logger_list_unlock();
+
+  return (struct logger_list*)logger_list;
 }
 
-LIBLOG_ABI_PUBLIC struct logger_list *android_logger_list_alloc_time(
-        int mode,
-        log_time start,
-        pid_t pid)
-{
-    struct android_log_logger_list *logger_list;
+LIBLOG_ABI_PUBLIC struct logger_list* android_logger_list_alloc_time(
+    int mode, log_time start, pid_t pid) {
+  struct android_log_logger_list* logger_list;
 
-    logger_list = calloc(1, sizeof(*logger_list));
-    if (!logger_list) {
-        return NULL;
-    }
+  logger_list = calloc(1, sizeof(*logger_list));
+  if (!logger_list) {
+    return NULL;
+  }
 
-    list_init(&logger_list->logger);
-    list_init(&logger_list->transport);
-    logger_list->mode = mode;
-    logger_list->start = start;
-    logger_list->pid = pid;
+  list_init(&logger_list->logger);
+  list_init(&logger_list->transport);
+  logger_list->mode = mode;
+  logger_list->start = start;
+  logger_list->pid = pid;
 
-    return (struct logger_list *)logger_list;
+  logger_list_wrlock();
+  list_add_tail(&__android_log_readers, &logger_list->node);
+  logger_list_unlock();
+
+  return (struct logger_list*)logger_list;
 }
 
 /* android_logger_list_register unimplemented, no use case */
 /* android_logger_list_unregister unimplemented, no use case */
 
 /* Open the named log and add it to the logger list */
-LIBLOG_ABI_PUBLIC struct logger *android_logger_open(
-        struct logger_list *logger_list,
-        log_id_t logId)
-{
-    struct android_log_logger_list *logger_list_internal =
-            (struct android_log_logger_list *)logger_list;
-    struct android_log_logger *logger;
+LIBLOG_ABI_PUBLIC struct logger* android_logger_open(
+    struct logger_list* logger_list, log_id_t logId) {
+  struct android_log_logger_list* logger_list_internal =
+      (struct android_log_logger_list*)logger_list;
+  struct android_log_logger* logger;
 
-    if (!logger_list_internal || (logId >= LOG_ID_MAX)) {
-        goto err;
+  if (!logger_list_internal || (logId >= LOG_ID_MAX)) {
+    goto err;
+  }
+
+  logger_for_each(logger, logger_list_internal) {
+    if (logger->logId == logId) {
+      goto ok;
     }
+  }
 
-    logger_for_each(logger, logger_list_internal) {
-        if (logger->logId == logId) {
-            goto ok;
-        }
-    }
+  logger = calloc(1, sizeof(*logger));
+  if (!logger) {
+    goto err;
+  }
 
-    logger = calloc(1, sizeof(*logger));
-    if (!logger) {
-        goto err;
-    }
+  logger->logId = logId;
+  list_add_tail(&logger_list_internal->logger, &logger->node);
+  logger->parent = logger_list_internal;
 
-    logger->logId = logId;
-    list_add_tail(&logger_list_internal->logger, &logger->node);
-    logger->parent = logger_list_internal;
+  /* Reset known transports to re-evaluate, we just added one */
+  while (!list_empty(&logger_list_internal->transport)) {
+    struct listnode* node = list_head(&logger_list_internal->transport);
+    struct android_log_transport_context* transp =
+        node_to_item(node, struct android_log_transport_context, node);
 
-    /* Reset known transports to re-evaluate, we just added one */
-    while (!list_empty(&logger_list_internal->transport)) {
-        struct listnode *node = list_head(&logger_list_internal->transport);
-        struct android_log_transport_context *transp =
-                node_to_item(node, struct android_log_transport_context, node);
-
-        list_remove(&transp->node);
-        free(transp);
-    }
-    goto ok;
+    list_remove(&transp->node);
+    free(transp);
+  }
+  goto ok;
 
 err:
-    logger = NULL;
+  logger = NULL;
 ok:
-    return (struct logger *)logger;
+  return (struct logger*)logger;
 }
 
 /* Open the single named log and make it part of a new logger list */
-LIBLOG_ABI_PUBLIC struct logger_list *android_logger_list_open(
-        log_id_t logId,
-        int mode,
-        unsigned int tail,
-        pid_t pid)
-{
-    struct logger_list *logger_list =
-            android_logger_list_alloc(mode, tail, pid);
+LIBLOG_ABI_PUBLIC struct logger_list* android_logger_list_open(
+    log_id_t logId, int mode, unsigned int tail, pid_t pid) {
+  struct logger_list* logger_list = android_logger_list_alloc(mode, tail, pid);
 
-    if (!logger_list) {
-        return NULL;
+  if (!logger_list) {
+    return NULL;
+  }
+
+  if (!android_logger_open(logger_list, logId)) {
+    android_logger_list_free(logger_list);
+    return NULL;
+  }
+
+  return logger_list;
+}
+
+/* Validate log_msg packet, read function has already been null checked */
+static int android_transport_read(struct android_log_logger_list* logger_list,
+                                  struct android_log_transport_context* transp,
+                                  struct log_msg* log_msg) {
+  int ret = (*transp->transport->read)(logger_list, transp, log_msg);
+
+  if (ret > (int)sizeof(*log_msg)) {
+    ret = sizeof(*log_msg);
+  }
+
+  transp->ret = ret;
+
+  /* propagate errors, or make sure len & hdr_size members visible */
+  if (ret < (int)(sizeof(log_msg->entry.len) + sizeof(log_msg->entry.hdr_size))) {
+    if (ret >= (int)sizeof(log_msg->entry.len)) {
+      log_msg->entry.len = 0;
     }
+    return ret;
+  }
 
-    if (!android_logger_open(logger_list, logId)) {
-        android_logger_list_free(logger_list);
-        return NULL;
-    }
+  /* hdr_size correction (logger_entry -> logger_entry_v2+ conversion) */
+  if (log_msg->entry_v2.hdr_size == 0) {
+    log_msg->entry_v2.hdr_size = sizeof(struct logger_entry);
+  }
+  if ((log_msg->entry_v2.hdr_size < sizeof(log_msg->entry_v1)) ||
+      (log_msg->entry_v2.hdr_size > sizeof(log_msg->entry))) {
+    return -EINVAL;
+  }
 
-    return logger_list;
+  /* len validation */
+  if (ret <= log_msg->entry_v2.hdr_size) {
+    log_msg->entry.len = 0;
+  } else {
+    log_msg->entry.len = ret - log_msg->entry_v2.hdr_size;
+  }
+
+  return ret;
 }
 
 /* Read from the selected logs */
-LIBLOG_ABI_PUBLIC int android_logger_list_read(struct logger_list *logger_list,
-                                               struct log_msg *log_msg)
-{
-    struct android_log_transport_context *transp;
-    struct android_log_logger_list *logger_list_internal =
-            (struct android_log_logger_list *)logger_list;
+LIBLOG_ABI_PUBLIC int android_logger_list_read(struct logger_list* logger_list,
+                                               struct log_msg* log_msg) {
+  struct android_log_transport_context* transp;
+  struct android_log_logger_list* logger_list_internal =
+      (struct android_log_logger_list*)logger_list;
 
-    int ret = init_transport_context(logger_list_internal);
-    if (ret < 0) {
-        return ret;
-    }
+  int ret = init_transport_context(logger_list_internal);
+  if (ret < 0) {
+    return ret;
+  }
 
-    /* at least one transport */
-    transp = node_to_item(logger_list_internal->transport.next,
-                          struct android_log_transport_context, node);
+  /* at least one transport */
+  transp = node_to_item(logger_list_internal->transport.next,
+                        struct android_log_transport_context, node);
 
-    /* more than one transport? */
-    if (transp->node.next != &logger_list_internal->transport) {
-        /* Poll and merge sort the entries if from multiple transports */
-        struct android_log_transport_context *oldest = NULL;
-        int ret;
-        int polled = 0;
-        do {
-            if (polled) {
-                sched_yield();
+  /* more than one transport? */
+  if (transp->node.next != &logger_list_internal->transport) {
+    /* Poll and merge sort the entries if from multiple transports */
+    struct android_log_transport_context* oldest = NULL;
+    int ret;
+    int polled = 0;
+    do {
+      if (polled) {
+        sched_yield();
+      }
+      ret = -1000;
+      polled = 0;
+      do {
+        int retval = transp->ret;
+        if ((retval > 0) && !transp->logMsg.entry.len) {
+          if (!transp->transport->read) {
+            retval = transp->ret = 0;
+          } else if ((logger_list_internal->mode & ANDROID_LOG_NONBLOCK) ||
+                     !transp->transport->poll) {
+            retval = android_transport_read(logger_list_internal, transp,
+                                            &transp->logMsg);
+          } else {
+            int pollval =
+                (*transp->transport->poll)(logger_list_internal, transp);
+            if (pollval <= 0) {
+              sched_yield();
+              pollval = (*transp->transport->poll)(logger_list_internal, transp);
             }
-            ret = -1000;
-            polled = 0;
-            do {
-                int retval = transp->ret;
-                if ((retval > 0) && !transp->logMsg.entry.len) {
-                    if (!transp->transport->read) {
-                        retval = transp->ret = 0;
-                    } else if ((logger_list_internal->mode &
-                                ANDROID_LOG_NONBLOCK) ||
-                            !transp->transport->poll) {
-                        retval = transp->ret = (*transp->transport->read)(
-                                logger_list_internal,
-                                transp,
-                                &transp->logMsg);
-                    } else {
-                        int pollval = (*transp->transport->poll)(
-                                logger_list_internal, transp);
-                        if (pollval <= 0) {
-                            sched_yield();
-                            pollval = (*transp->transport->poll)(
-                                    logger_list_internal, transp);
-                        }
-                        polled = 1;
-                        if (pollval < 0) {
-                            if ((pollval == -EINTR) || (pollval == -EAGAIN)) {
-                                return -EAGAIN;
-                            }
-                            retval = transp->ret = pollval;
-                        } else if (pollval > 0) {
-                            retval = transp->ret = (*transp->transport->read)(
-                                    logger_list_internal,
-                                    transp,
-                                    &transp->logMsg);
-                        }
-                    }
-                }
-                if (ret < retval) {
-                    ret = retval;
-                }
-                if ((transp->ret > 0) && transp->logMsg.entry.len &&
-                        (!oldest ||
-                            (oldest->logMsg.entry.sec >
-                                transp->logMsg.entry.sec) ||
-                            ((oldest->logMsg.entry.sec ==
-                                    transp->logMsg.entry.sec) &&
-                                (oldest->logMsg.entry.nsec >
-                                    transp->logMsg.entry.nsec)))) {
-                    oldest = transp;
-                }
-                transp = node_to_item(transp->node.next,
-                                      struct android_log_transport_context,
-                                      node);
-            } while (transp != node_to_item(
-                    &logger_list_internal->transport,
-                    struct android_log_transport_context,
-                    node));
-            if (!oldest &&
-                    (logger_list_internal->mode & ANDROID_LOG_NONBLOCK)) {
-                return (ret < 0) ? ret : -EAGAIN;
+            polled = 1;
+            if (pollval < 0) {
+              if ((pollval == -EINTR) || (pollval == -EAGAIN)) {
+                return -EAGAIN;
+              }
+              retval = transp->ret = pollval;
+            } else if (pollval > 0) {
+              retval = android_transport_read(logger_list_internal, transp,
+                                              &transp->logMsg);
             }
-            transp = node_to_item(logger_list_internal->transport.next,
-                                  struct android_log_transport_context, node);
-        } while (!oldest && (ret > 0));
-        if (!oldest) {
-            return ret;
+          }
         }
-        memcpy(log_msg, &oldest->logMsg, oldest->logMsg.entry.len +
-                    (oldest->logMsg.entry.hdr_size ?
-                        oldest->logMsg.entry.hdr_size :
-                        sizeof(struct logger_entry)));
-        oldest->logMsg.entry.len = 0; /* Mark it as copied */
-        return oldest->ret;
+        if (ret < retval) {
+          ret = retval;
+        }
+        if ((transp->ret > 0) && transp->logMsg.entry.len &&
+            (!oldest || (oldest->logMsg.entry.sec > transp->logMsg.entry.sec) ||
+             ((oldest->logMsg.entry.sec == transp->logMsg.entry.sec) &&
+              (oldest->logMsg.entry.nsec > transp->logMsg.entry.nsec)))) {
+          oldest = transp;
+        }
+        transp = node_to_item(transp->node.next,
+                              struct android_log_transport_context, node);
+      } while (transp != node_to_item(&logger_list_internal->transport,
+                                      struct android_log_transport_context,
+                                      node));
+      if (!oldest && (logger_list_internal->mode & ANDROID_LOG_NONBLOCK)) {
+        return (ret < 0) ? ret : -EAGAIN;
+      }
+      transp = node_to_item(logger_list_internal->transport.next,
+                            struct android_log_transport_context, node);
+    } while (!oldest && (ret > 0));
+    if (!oldest) {
+      return ret;
     }
+    // ret is a positive value less than sizeof(struct log_msg)
+    ret = oldest->ret;
+    if (ret < oldest->logMsg.entry.hdr_size) {
+      // zero truncated header fields.
+      memset(log_msg, 0,
+             (oldest->logMsg.entry.hdr_size > sizeof(oldest->logMsg)
+                  ? sizeof(oldest->logMsg)
+                  : oldest->logMsg.entry.hdr_size));
+    }
+    memcpy(log_msg, &oldest->logMsg, ret);
+    oldest->logMsg.entry.len = 0; /* Mark it as copied */
+    return ret;
+  }
 
-    /* if only one, no need to copy into transport_context and merge-sort */
-    return (transp->transport->read)(logger_list_internal, transp, log_msg);
+  /* if only one, no need to copy into transport_context and merge-sort */
+  return android_transport_read(logger_list_internal, transp, log_msg);
 }
 
 /* Close all the logs */
-LIBLOG_ABI_PUBLIC void android_logger_list_free(struct logger_list *logger_list)
-{
-    struct android_log_logger_list *logger_list_internal =
-            (struct android_log_logger_list *)logger_list;
+LIBLOG_ABI_PUBLIC void android_logger_list_free(struct logger_list* logger_list) {
+  struct android_log_logger_list* logger_list_internal =
+      (struct android_log_logger_list*)logger_list;
 
-    if (logger_list_internal == NULL) {
-        return;
+  if (logger_list_internal == NULL) {
+    return;
+  }
+
+  logger_list_wrlock();
+  list_remove(&logger_list_internal->node);
+  logger_list_unlock();
+
+  while (!list_empty(&logger_list_internal->transport)) {
+    struct listnode* node = list_head(&logger_list_internal->transport);
+    struct android_log_transport_context* transp =
+        node_to_item(node, struct android_log_transport_context, node);
+
+    if (transp->transport && transp->transport->close) {
+      (*transp->transport->close)(logger_list_internal, transp);
     }
+    list_remove(&transp->node);
+    free(transp);
+  }
 
-    while (!list_empty(&logger_list_internal->transport)) {
-        struct listnode *node = list_head(&logger_list_internal->transport);
-        struct android_log_transport_context *transp =
-                node_to_item(node, struct android_log_transport_context, node);
+  while (!list_empty(&logger_list_internal->logger)) {
+    struct listnode* node = list_head(&logger_list_internal->logger);
+    struct android_log_logger* logger =
+        node_to_item(node, struct android_log_logger, node);
+    android_logger_free((struct logger*)logger);
+  }
 
-        if (transp->transport && transp->transport->close) {
-            (*transp->transport->close)(logger_list_internal, transp);
-        }
-        list_remove(&transp->node);
-        free(transp);
-    }
-
-    while (!list_empty(&logger_list_internal->logger)) {
-        struct listnode *node = list_head(&logger_list_internal->logger);
-        struct android_log_logger *logger =
-                node_to_item(node, struct android_log_logger, node);
-        android_logger_free((struct logger *)logger);
-    }
-
-    free(logger_list_internal);
+  free(logger_list_internal);
 }
diff --git a/liblog/logger_write.c b/liblog/logger_write.c
index c7b5a84..d322c0f 100644
--- a/liblog/logger_write.c
+++ b/liblog/logger_write.c
@@ -25,20 +25,20 @@
 #endif
 
 #include <log/event_tag_map.h>
-#include <log/logd.h>
-#include <log/logger.h>
-#include <log/log_read.h>
+#include <log/log_transport.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
+#include "config_read.h" /* __android_log_config_read_close() definition */
 #include "config_write.h"
 #include "log_portability.h"
 #include "logger.h"
 
 #define LOG_BUF_SIZE 1024
 
-static int __write_to_log_init(log_id_t, struct iovec *vec, size_t nr);
-static int (*write_to_log)(log_id_t, struct iovec *vec, size_t nr) = __write_to_log_init;
+static int __write_to_log_init(log_id_t, struct iovec* vec, size_t nr);
+static int (*write_to_log)(log_id_t, struct iovec* vec,
+                           size_t nr) = __write_to_log_init;
 
 /*
  * This is used by the C++ code to decide if it should write logs through
@@ -46,475 +46,487 @@
  * the simulator rather than a desktop tool and want to use the device.
  */
 static enum {
-    kLogUninitialized, kLogNotAvailable, kLogAvailable
+  kLogUninitialized,
+  kLogNotAvailable,
+  kLogAvailable
 } g_log_status = kLogUninitialized;
 
-static int check_log_uid_permissions()
-{
-#if defined(__BIONIC__)
-    uid_t uid = __android_log_uid();
+static int check_log_uid_permissions() {
+#if defined(__ANDROID__)
+  uid_t uid = __android_log_uid();
 
-    /* Matches clientHasLogCredentials() in logd */
+  /* Matches clientHasLogCredentials() in logd */
+  if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
+    uid = geteuid();
     if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
-        uid = geteuid();
-        if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
-            gid_t gid = getgid();
-            if ((gid != AID_SYSTEM) &&
-                    (gid != AID_ROOT) &&
-                    (gid != AID_LOG)) {
-                gid = getegid();
-                if ((gid != AID_SYSTEM) &&
-                        (gid != AID_ROOT) &&
-                        (gid != AID_LOG)) {
-                    int num_groups;
-                    gid_t *groups;
+      gid_t gid = getgid();
+      if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
+        gid = getegid();
+        if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
+          int num_groups;
+          gid_t* groups;
 
-                    num_groups = getgroups(0, NULL);
-                    if (num_groups <= 0) {
-                        return -EPERM;
-                    }
-                    groups = calloc(num_groups, sizeof(gid_t));
-                    if (!groups) {
-                        return -ENOMEM;
-                    }
-                    num_groups = getgroups(num_groups, groups);
-                    while (num_groups > 0) {
-                        if (groups[num_groups - 1] == AID_LOG) {
-                            break;
-                        }
-                        --num_groups;
-                    }
-                    free(groups);
-                    if (num_groups <= 0) {
-                        return -EPERM;
-                    }
-                }
+          num_groups = getgroups(0, NULL);
+          if (num_groups <= 0) {
+            return -EPERM;
+          }
+          groups = calloc(num_groups, sizeof(gid_t));
+          if (!groups) {
+            return -ENOMEM;
+          }
+          num_groups = getgroups(num_groups, groups);
+          while (num_groups > 0) {
+            if (groups[num_groups - 1] == AID_LOG) {
+              break;
             }
+            --num_groups;
+          }
+          free(groups);
+          if (num_groups <= 0) {
+            return -EPERM;
+          }
         }
+      }
     }
+  }
 #endif
-    return 0;
+  return 0;
 }
 
 static void __android_log_cache_available(
-        struct android_log_transport_write *node)
-{
-    size_t i;
+    struct android_log_transport_write* node) {
+  size_t i;
 
+  if (node->logMask) {
+    return;
+  }
+
+  for (i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
+    if (node->write && (i != LOG_ID_KERNEL) &&
+        ((i != LOG_ID_SECURITY) || (check_log_uid_permissions() == 0)) &&
+        (!node->available || ((*node->available)(i) >= 0))) {
+      node->logMask |= 1 << i;
+    }
+  }
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_dev_available() {
+  struct android_log_transport_write* node;
+
+  if (list_empty(&__android_log_transport_write)) {
+    return kLogUninitialized;
+  }
+
+  write_transport_for_each(node, &__android_log_transport_write) {
+    __android_log_cache_available(node);
     if (node->logMask) {
-        return;
+      return kLogAvailable;
     }
-
-    for (i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
-        if (node->write &&
-                (i != LOG_ID_KERNEL) &&
-                ((i != LOG_ID_SECURITY) ||
-                    (check_log_uid_permissions() == 0)) &&
-                (!node->available || ((*node->available)(i) >= 0))) {
-            node->logMask |= 1 << i;
-        }
-    }
+  }
+  return kLogNotAvailable;
 }
 
-LIBLOG_ABI_PUBLIC int __android_log_dev_available()
-{
-    struct android_log_transport_write *node;
+#if defined(__ANDROID__)
+static atomic_uintptr_t tagMap;
+#endif
 
-    if (list_empty(&__android_log_transport_write)) {
-        return kLogUninitialized;
-    }
-
-    write_transport_for_each(node, &__android_log_transport_write) {
-        __android_log_cache_available(node);
-        if (node->logMask) {
-            return kLogAvailable;
-        }
-    }
-    return kLogNotAvailable;
-}
 /*
  * Release any logger resources. A new log write will immediately re-acquire.
  */
-LIBLOG_ABI_PUBLIC void __android_log_close()
-{
-    struct android_log_transport_write *transport;
+LIBLOG_ABI_PUBLIC void __android_log_close() {
+  struct android_log_transport_write* transport;
+#if defined(__ANDROID__)
+  EventTagMap* m;
+#endif
 
-    __android_log_lock();
+  __android_log_lock();
 
-    write_to_log = __write_to_log_init;
+  write_to_log = __write_to_log_init;
 
-    /*
-     * Threads that are actively writing at this point are not held back
-     * by a lock and are at risk of dropping the messages with a return code
-     * -EBADF. Prefer to return error code than add the overhead of a lock to
-     * each log writing call to guarantee delivery. In addition, anyone
-     * calling this is doing so to release the logging resources and shut down,
-     * for them to do so with outstanding log requests in other threads is a
-     * disengenuous use of this function.
-     */
+  /*
+   * Threads that are actively writing at this point are not held back
+   * by a lock and are at risk of dropping the messages with a return code
+   * -EBADF. Prefer to return error code than add the overhead of a lock to
+   * each log writing call to guarantee delivery. In addition, anyone
+   * calling this is doing so to release the logging resources and shut down,
+   * for them to do so with outstanding log requests in other threads is a
+   * disengenuous use of this function.
+   */
 
-    write_transport_for_each(transport, &__android_log_persist_write) {
-        if (transport->close) {
-            (*transport->close)();
-        }
+  write_transport_for_each(transport, &__android_log_persist_write) {
+    if (transport->close) {
+      (*transport->close)();
     }
+  }
 
-    write_transport_for_each(transport, &__android_log_transport_write) {
-        if (transport->close) {
-            (*transport->close)();
-        }
+  write_transport_for_each(transport, &__android_log_transport_write) {
+    if (transport->close) {
+      (*transport->close)();
     }
+  }
 
-    __android_log_unlock();
+  __android_log_config_write_close();
+
+#if defined(__ANDROID__)
+  /*
+   * Additional risk here somewhat mitigated by immediately unlock flushing
+   * the processor cache. The multi-threaded race that we choose to accept,
+   * to minimize locking, is an atomic_load in a writer picking up a value
+   * just prior to entering this routine. There will be an use after free.
+   *
+   * Again, anyone calling this is doing so to release the logging resources
+   * is most probably going to quiesce then shut down; or to restart after
+   * a fork so the risk should be non-existent. For this reason we
+   * choose a mitigation stance for efficiency instead of incuring the cost
+   * of a lock for every log write.
+   */
+  m = (EventTagMap*)atomic_exchange(&tagMap, (uintptr_t)0);
+#endif
+
+  __android_log_unlock();
+
+#if defined(__ANDROID__)
+  if (m != (EventTagMap*)(uintptr_t)-1LL) android_closeEventTagMap(m);
+#endif
 }
 
 /* log_init_lock assumed */
-static int __write_to_log_initialize()
-{
-    struct android_log_transport_write *transport;
-    struct listnode *n;
-    int i = 0, ret = 0;
+static int __write_to_log_initialize() {
+  struct android_log_transport_write* transport;
+  struct listnode* n;
+  int i = 0, ret = 0;
 
-    __android_log_config_write();
-    write_transport_for_each_safe(transport, n, &__android_log_transport_write) {
-        __android_log_cache_available(transport);
-        if (!transport->logMask) {
-            list_remove(&transport->node);
-            continue;
-        }
-        if (!transport->open || ((*transport->open)() < 0)) {
-            if (transport->close) {
-                (*transport->close)();
-            }
-            list_remove(&transport->node);
-            continue;
-        }
-        ++ret;
+  __android_log_config_write();
+  write_transport_for_each_safe(transport, n, &__android_log_transport_write) {
+    __android_log_cache_available(transport);
+    if (!transport->logMask) {
+      list_remove(&transport->node);
+      continue;
     }
-    write_transport_for_each_safe(transport, n, &__android_log_persist_write) {
-        __android_log_cache_available(transport);
-        if (!transport->logMask) {
-            list_remove(&transport->node);
-            continue;
-        }
-        if (!transport->open || ((*transport->open)() < 0)) {
-            if (transport->close) {
-                (*transport->close)();
-            }
-            list_remove(&transport->node);
-            continue;
-        }
-        ++i;
+    if (!transport->open || ((*transport->open)() < 0)) {
+      if (transport->close) {
+        (*transport->close)();
+      }
+      list_remove(&transport->node);
+      continue;
     }
-    if (!ret && !i) {
-        return -ENODEV;
+    ++ret;
+  }
+  write_transport_for_each_safe(transport, n, &__android_log_persist_write) {
+    __android_log_cache_available(transport);
+    if (!transport->logMask) {
+      list_remove(&transport->node);
+      continue;
     }
+    if (!transport->open || ((*transport->open)() < 0)) {
+      if (transport->close) {
+        (*transport->close)();
+      }
+      list_remove(&transport->node);
+      continue;
+    }
+    ++i;
+  }
+  if (!ret && !i) {
+    return -ENODEV;
+  }
 
-    return ret;
+  return ret;
 }
 
 /*
  * Extract a 4-byte value from a byte stream. le32toh open coded
  */
-static inline uint32_t get4LE(const uint8_t* src)
-{
-    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+static inline uint32_t get4LE(const uint8_t* src) {
+  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
 
-static int __write_to_log_daemon(log_id_t log_id, struct iovec *vec, size_t nr)
-{
-    struct android_log_transport_write *node;
-    int ret;
-    struct timespec ts;
-    size_t len, i;
+static int __write_to_log_daemon(log_id_t log_id, struct iovec* vec, size_t nr) {
+  struct android_log_transport_write* node;
+  int ret;
+  struct timespec ts;
+  size_t len, i;
 
-    for (len = i = 0; i < nr; ++i) {
-        len += vec[i].iov_len;
-    }
-    if (!len) {
-        return -EINVAL;
+  for (len = i = 0; i < nr; ++i) {
+    len += vec[i].iov_len;
+  }
+  if (!len) {
+    return -EINVAL;
+  }
+
+#if defined(__ANDROID__)
+  clock_gettime(android_log_clockid(), &ts);
+
+  if (log_id == LOG_ID_SECURITY) {
+    if (vec[0].iov_len < 4) {
+      return -EINVAL;
     }
 
-#if defined(__BIONIC__)
-    if (log_id == LOG_ID_SECURITY) {
-        if (vec[0].iov_len < 4) {
-            return -EINVAL;
-        }
+    ret = check_log_uid_permissions();
+    if (ret < 0) {
+      return ret;
+    }
+    if (!__android_log_security()) {
+      /* If only we could reset downstream logd counter */
+      return -EPERM;
+    }
+  } else if (log_id == LOG_ID_EVENTS) {
+    const char* tag;
+    size_t len;
+    EventTagMap *m, *f;
 
-        ret = check_log_uid_permissions();
-        if (ret < 0) {
-            return ret;
-        }
-        if (!__android_log_security()) {
-            /* If only we could reset downstream logd counter */
-            return -EPERM;
-        }
-    } else if (log_id == LOG_ID_EVENTS) {
-        static atomic_uintptr_t map;
-        const char *tag;
-        EventTagMap *m, *f;
+    if (vec[0].iov_len < 4) {
+      return -EINVAL;
+    }
 
-        if (vec[0].iov_len < 4) {
-            return -EINVAL;
-        }
+    tag = NULL;
+    len = 0;
+    f = NULL;
+    m = (EventTagMap*)atomic_load(&tagMap);
 
-        tag = NULL;
-        f = NULL;
-        m = (EventTagMap *)atomic_load(&map);
-
-        if (!m) {
-            ret = __android_log_trylock();
-            m = (EventTagMap *)atomic_load(&map); /* trylock flush cache */
-            if (!m) {
-                m = android_openEventTagMap(EVENT_TAG_MAP_FILE);
-                if (ret) { /* trylock failed, use local copy, mark for close */
-                    f = m;
-                } else {
-                    if (!m) { /* One chance to open map file */
-                        m = (EventTagMap *)(uintptr_t)-1LL;
-                    }
-                    atomic_store(&map, (uintptr_t)m);
-                }
-            }
-            if (!ret) { /* trylock succeeded, unlock */
-                __android_log_unlock();
-            }
+    if (!m) {
+      ret = __android_log_trylock();
+      m = (EventTagMap*)atomic_load(&tagMap); /* trylock flush cache */
+      if (!m) {
+        m = android_openEventTagMap(NULL);
+        if (ret) { /* trylock failed, use local copy, mark for close */
+          f = m;
+        } else {
+          if (!m) { /* One chance to open map file */
+            m = (EventTagMap*)(uintptr_t)-1LL;
+          }
+          atomic_store(&tagMap, (uintptr_t)m);
         }
-        if (m && (m != (EventTagMap *)(uintptr_t)-1LL)) {
-            tag = android_lookupEventTag(m, get4LE(vec[0].iov_base));
-        }
-        ret = __android_log_is_loggable(ANDROID_LOG_INFO,
-                                        tag,
+      }
+      if (!ret) { /* trylock succeeded, unlock */
+        __android_log_unlock();
+      }
+    }
+    if (m && (m != (EventTagMap*)(uintptr_t)-1LL)) {
+      tag = android_lookupEventTag_len(m, &len, get4LE(vec[0].iov_base));
+    }
+    ret = __android_log_is_loggable_len(ANDROID_LOG_INFO, tag, len,
                                         ANDROID_LOG_VERBOSE);
-        if (f) { /* local copy marked for close */
-            android_closeEventTagMap(f);
-        }
-        if (!ret) {
-            return -EPERM;
-        }
-    } else {
-        /* Validate the incoming tag, tag content can not split across iovec */
-        char prio = ANDROID_LOG_VERBOSE;
-        const char *tag = vec[0].iov_base;
-        size_t len = vec[0].iov_len;
+    if (f) { /* local copy marked for close */
+      android_closeEventTagMap(f);
+    }
+    if (!ret) {
+      return -EPERM;
+    }
+  } else {
+    /* Validate the incoming tag, tag content can not split across iovec */
+    char prio = ANDROID_LOG_VERBOSE;
+    const char* tag = vec[0].iov_base;
+    size_t len = vec[0].iov_len;
+    if (!tag) {
+      len = 0;
+    }
+    if (len > 0) {
+      prio = *tag;
+      if (len > 1) {
+        --len;
+        ++tag;
+      } else {
+        len = vec[1].iov_len;
+        tag = ((const char*)vec[1].iov_base);
         if (!tag) {
-            len = 0;
+          len = 0;
         }
-        if (len > 0) {
-            prio = *tag;
-            if (len > 1) {
-                --len;
-                ++tag;
-            } else {
-                len = vec[1].iov_len;
-                tag = ((const char *)vec[1].iov_base);
-                if (!tag) {
-                    len = 0;
-                }
-            }
-        }
-        /* tag must be nul terminated */
-        if (strnlen(tag, len) >= len) {
-            tag = NULL;
-        }
-
-        if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
-            return -EPERM;
-        }
+      }
+    }
+    /* tag must be nul terminated */
+    if (tag && strnlen(tag, len) >= len) {
+      tag = NULL;
     }
 
-    clock_gettime(android_log_clockid(), &ts);
+    if (!__android_log_is_loggable_len(prio, tag, len - 1, ANDROID_LOG_VERBOSE)) {
+      return -EPERM;
+    }
+  }
 #else
-    /* simulate clock_gettime(CLOCK_REALTIME, &ts); */
-    {
-        struct timeval tv;
-        gettimeofday(&tv, NULL);
-        ts.tv_sec = tv.tv_sec;
-        ts.tv_nsec = tv.tv_usec * 1000;
-    }
+  /* simulate clock_gettime(CLOCK_REALTIME, &ts); */
+  {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    ts.tv_sec = tv.tv_sec;
+    ts.tv_nsec = tv.tv_usec * 1000;
+  }
 #endif
 
-    ret = 0;
-    i = 1 << log_id;
-    write_transport_for_each(node, &__android_log_transport_write) {
-        if (node->logMask & i) {
-            ssize_t retval;
-            retval = (*node->write)(log_id, &ts, vec, nr);
-            if (ret >= 0) {
-                ret = retval;
-            }
-        }
+  ret = 0;
+  i = 1 << log_id;
+  write_transport_for_each(node, &__android_log_transport_write) {
+    if (node->logMask & i) {
+      ssize_t retval;
+      retval = (*node->write)(log_id, &ts, vec, nr);
+      if (ret >= 0) {
+        ret = retval;
+      }
     }
+  }
 
-    write_transport_for_each(node, &__android_log_persist_write) {
-        if (node->logMask & i) {
-            (void)(*node->write)(log_id, &ts, vec, nr);
-        }
+  write_transport_for_each(node, &__android_log_persist_write) {
+    if (node->logMask & i) {
+      (void)(*node->write)(log_id, &ts, vec, nr);
     }
+  }
 
-    return ret;
+  return ret;
 }
 
-static int __write_to_log_init(log_id_t log_id, struct iovec *vec, size_t nr)
-{
-    __android_log_lock();
+static int __write_to_log_init(log_id_t log_id, struct iovec* vec, size_t nr) {
+  __android_log_lock();
 
-    if (write_to_log == __write_to_log_init) {
-        int ret;
+  if (write_to_log == __write_to_log_init) {
+    int ret;
 
-        ret = __write_to_log_initialize();
-        if (ret < 0) {
-            __android_log_unlock();
-            if (!list_empty(&__android_log_persist_write)) {
-                __write_to_log_daemon(log_id, vec, nr);
-            }
-            return ret;
-        }
-
-        write_to_log = __write_to_log_daemon;
+    ret = __write_to_log_initialize();
+    if (ret < 0) {
+      __android_log_unlock();
+      if (!list_empty(&__android_log_persist_write)) {
+        __write_to_log_daemon(log_id, vec, nr);
+      }
+      return ret;
     }
 
-    __android_log_unlock();
+    write_to_log = __write_to_log_daemon;
+  }
 
-    return write_to_log(log_id, vec, nr);
+  __android_log_unlock();
+
+  return write_to_log(log_id, vec, nr);
 }
 
-LIBLOG_ABI_PUBLIC int __android_log_write(int prio, const char *tag,
-                                          const char *msg)
-{
-    return __android_log_buf_write(LOG_ID_MAIN, prio, tag, msg);
+LIBLOG_ABI_PUBLIC int __android_log_write(int prio, const char* tag,
+                                          const char* msg) {
+  return __android_log_buf_write(LOG_ID_MAIN, prio, tag, msg);
 }
 
 LIBLOG_ABI_PUBLIC int __android_log_buf_write(int bufID, int prio,
-                                              const char *tag, const char *msg)
-{
-    struct iovec vec[3];
-    char tmp_tag[32];
+                                              const char* tag, const char* msg) {
+  struct iovec vec[3];
+  char tmp_tag[32];
 
-    if (!tag)
-        tag = "";
+  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;
-    }
+  /* 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 __BIONIC__
-    if (prio == ANDROID_LOG_FATAL) {
-        android_set_abort_message(msg);
-    }
+  if (prio == ANDROID_LOG_FATAL) {
+    android_set_abort_message(msg);
+  }
 #endif
 
-    vec[0].iov_base = (unsigned char *)&prio;
-    vec[0].iov_len  = 1;
-    vec[1].iov_base = (void *)tag;
-    vec[1].iov_len  = strlen(tag) + 1;
-    vec[2].iov_base = (void *)msg;
-    vec[2].iov_len  = strlen(msg) + 1;
+  vec[0].iov_base = (unsigned char*)&prio;
+  vec[0].iov_len = 1;
+  vec[1].iov_base = (void*)tag;
+  vec[1].iov_len = strlen(tag) + 1;
+  vec[2].iov_base = (void*)msg;
+  vec[2].iov_len = strlen(msg) + 1;
 
-    return write_to_log(bufID, vec, 3);
+  return write_to_log(bufID, vec, 3);
 }
 
-LIBLOG_ABI_PUBLIC int __android_log_vprint(int prio, const char *tag,
-                                           const char *fmt, va_list ap)
-{
-    char buf[LOG_BUF_SIZE];
+LIBLOG_ABI_PUBLIC int __android_log_vprint(int prio, const char* tag,
+                                           const char* fmt, va_list ap) {
+  char buf[LOG_BUF_SIZE];
 
-    vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
+  vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
 
-    return __android_log_write(prio, tag, buf);
+  return __android_log_write(prio, tag, buf);
 }
 
-LIBLOG_ABI_PUBLIC int __android_log_print(int prio, const char *tag,
-                                          const char *fmt, ...)
-{
-    va_list ap;
-    char buf[LOG_BUF_SIZE];
+LIBLOG_ABI_PUBLIC int __android_log_print(int prio, const char* tag,
+                                          const char* fmt, ...) {
+  va_list ap;
+  char buf[LOG_BUF_SIZE];
 
-    va_start(ap, fmt);
-    vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
-    va_end(ap);
+  va_start(ap, fmt);
+  vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
+  va_end(ap);
 
-    return __android_log_write(prio, tag, buf);
+  return __android_log_write(prio, tag, buf);
 }
 
 LIBLOG_ABI_PUBLIC int __android_log_buf_print(int bufID, int prio,
-                                              const char *tag,
-                                              const char *fmt, ...)
-{
-    va_list ap;
-    char buf[LOG_BUF_SIZE];
+                                              const char* tag, const char* fmt,
+                                              ...) {
+  va_list ap;
+  char buf[LOG_BUF_SIZE];
 
+  va_start(ap, fmt);
+  vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
+  va_end(ap);
+
+  return __android_log_buf_write(bufID, prio, tag, buf);
+}
+
+LIBLOG_ABI_PUBLIC void __android_log_assert(const char* cond, const char* tag,
+                                            const char* fmt, ...) {
+  char buf[LOG_BUF_SIZE];
+
+  if (fmt) {
+    va_list ap;
     va_start(ap, fmt);
     vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
     va_end(ap);
+  } else {
+    /* Msg not provided, log condition.  N.B. Do not use cond directly as
+     * format string as it could contain spurious '%' syntax (e.g.
+     * "%d" in "blocks%devs == 0").
+     */
+    if (cond)
+      snprintf(buf, LOG_BUF_SIZE, "Assertion failed: %s", cond);
+    else
+      strcpy(buf, "Unspecified assertion failed");
+  }
 
-    return __android_log_buf_write(bufID, prio, tag, buf);
+  // Log assertion failures to stderr for the benefit of "adb shell" users
+  // and gtests (http://b/23675822).
+  struct iovec iov[2] = {
+    { buf, strlen(buf) }, { (char*)"\n", 1 },
+  };
+  TEMP_FAILURE_RETRY(writev(2, iov, 2));
+
+  __android_log_write(ANDROID_LOG_FATAL, tag, buf);
+  abort(); /* abort so we have a chance to debug the situation */
+           /* NOTREACHED */
 }
 
-LIBLOG_ABI_PUBLIC void __android_log_assert(const char *cond, const char *tag,
-                                            const char *fmt, ...)
-{
-    char buf[LOG_BUF_SIZE];
+LIBLOG_ABI_PUBLIC int __android_log_bwrite(int32_t tag, const void* payload,
+                                           size_t len) {
+  struct iovec vec[2];
 
-    if (fmt) {
-        va_list ap;
-        va_start(ap, fmt);
-        vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
-        va_end(ap);
-    } else {
-        /* Msg not provided, log condition.  N.B. Do not use cond directly as
-         * format string as it could contain spurious '%' syntax (e.g.
-         * "%d" in "blocks%devs == 0").
-         */
-        if (cond)
-            snprintf(buf, LOG_BUF_SIZE, "Assertion failed: %s", cond);
-        else
-            strcpy(buf, "Unspecified assertion failed");
-    }
+  vec[0].iov_base = &tag;
+  vec[0].iov_len = sizeof(tag);
+  vec[1].iov_base = (void*)payload;
+  vec[1].iov_len = len;
 
-    __android_log_write(ANDROID_LOG_FATAL, tag, buf);
-    abort(); /* abort so we have a chance to debug the situation */
-    /* NOTREACHED */
-}
-
-LIBLOG_ABI_PUBLIC int __android_log_bwrite(int32_t tag,
-                                           const void *payload, size_t len)
-{
-    struct iovec vec[2];
-
-    vec[0].iov_base = &tag;
-    vec[0].iov_len = sizeof(tag);
-    vec[1].iov_base = (void*)payload;
-    vec[1].iov_len = len;
-
-    return write_to_log(LOG_ID_EVENTS, vec, 2);
+  return write_to_log(LOG_ID_EVENTS, vec, 2);
 }
 
 LIBLOG_ABI_PUBLIC int __android_log_security_bwrite(int32_t tag,
-                                                    const void *payload,
-                                                    size_t len)
-{
-    struct iovec vec[2];
+                                                    const void* payload,
+                                                    size_t len) {
+  struct iovec vec[2];
 
-    vec[0].iov_base = &tag;
-    vec[0].iov_len = sizeof(tag);
-    vec[1].iov_base = (void*)payload;
-    vec[1].iov_len = len;
+  vec[0].iov_base = &tag;
+  vec[0].iov_len = sizeof(tag);
+  vec[1].iov_base = (void*)payload;
+  vec[1].iov_len = len;
 
-    return write_to_log(LOG_ID_SECURITY, vec, 2);
+  return write_to_log(LOG_ID_SECURITY, vec, 2);
 }
 
 /*
@@ -523,40 +535,38 @@
  * handy if we just want to dump an integer into the log.
  */
 LIBLOG_ABI_PUBLIC int __android_log_btwrite(int32_t tag, char type,
-                                            const void *payload, size_t len)
-{
-    struct iovec vec[3];
+                                            const void* payload, size_t len) {
+  struct iovec vec[3];
 
-    vec[0].iov_base = &tag;
-    vec[0].iov_len = sizeof(tag);
-    vec[1].iov_base = &type;
-    vec[1].iov_len = sizeof(type);
-    vec[2].iov_base = (void*)payload;
-    vec[2].iov_len = len;
+  vec[0].iov_base = &tag;
+  vec[0].iov_len = sizeof(tag);
+  vec[1].iov_base = &type;
+  vec[1].iov_len = sizeof(type);
+  vec[2].iov_base = (void*)payload;
+  vec[2].iov_len = len;
 
-    return write_to_log(LOG_ID_EVENTS, vec, 3);
+  return write_to_log(LOG_ID_EVENTS, vec, 3);
 }
 
 /*
  * Like __android_log_bwrite, but used for writing strings to the
  * event log.
  */
-LIBLOG_ABI_PUBLIC int __android_log_bswrite(int32_t tag, const char *payload)
-{
-    struct iovec vec[4];
-    char type = EVENT_TYPE_STRING;
-    uint32_t len = strlen(payload);
+LIBLOG_ABI_PUBLIC int __android_log_bswrite(int32_t tag, const char* payload) {
+  struct iovec vec[4];
+  char type = EVENT_TYPE_STRING;
+  uint32_t len = strlen(payload);
 
-    vec[0].iov_base = &tag;
-    vec[0].iov_len = sizeof(tag);
-    vec[1].iov_base = &type;
-    vec[1].iov_len = sizeof(type);
-    vec[2].iov_base = &len;
-    vec[2].iov_len = sizeof(len);
-    vec[3].iov_base = (void*)payload;
-    vec[3].iov_len = len;
+  vec[0].iov_base = &tag;
+  vec[0].iov_len = sizeof(tag);
+  vec[1].iov_base = &type;
+  vec[1].iov_len = sizeof(type);
+  vec[2].iov_base = &len;
+  vec[2].iov_len = sizeof(len);
+  vec[3].iov_base = (void*)payload;
+  vec[3].iov_len = len;
 
-    return write_to_log(LOG_ID_EVENTS, vec, 4);
+  return write_to_log(LOG_ID_EVENTS, vec, 4);
 }
 
 /*
@@ -564,20 +574,100 @@
  * security log.
  */
 LIBLOG_ABI_PUBLIC int __android_log_security_bswrite(int32_t tag,
-                                                     const char *payload)
-{
-    struct iovec vec[4];
-    char type = EVENT_TYPE_STRING;
-    uint32_t len = strlen(payload);
+                                                     const char* payload) {
+  struct iovec vec[4];
+  char type = EVENT_TYPE_STRING;
+  uint32_t len = strlen(payload);
 
-    vec[0].iov_base = &tag;
-    vec[0].iov_len = sizeof(tag);
-    vec[1].iov_base = &type;
-    vec[1].iov_len = sizeof(type);
-    vec[2].iov_base = &len;
-    vec[2].iov_len = sizeof(len);
-    vec[3].iov_base = (void*)payload;
-    vec[3].iov_len = len;
+  vec[0].iov_base = &tag;
+  vec[0].iov_len = sizeof(tag);
+  vec[1].iov_base = &type;
+  vec[1].iov_len = sizeof(type);
+  vec[2].iov_base = &len;
+  vec[2].iov_len = sizeof(len);
+  vec[3].iov_base = (void*)payload;
+  vec[3].iov_len = len;
 
-    return write_to_log(LOG_ID_SECURITY, vec, 4);
+  return write_to_log(LOG_ID_SECURITY, vec, 4);
+}
+
+static int __write_to_log_null(log_id_t log_id, struct iovec* vec, size_t nr) {
+  size_t len, i;
+
+  if ((log_id < LOG_ID_MIN) || (log_id >= LOG_ID_MAX)) {
+    return -EINVAL;
+  }
+
+  for (len = i = 0; i < nr; ++i) {
+    len += vec[i].iov_len;
+  }
+  if (!len) {
+    return -EINVAL;
+  }
+  return len;
+}
+
+/* Following functions need access to our internal write_to_log status */
+
+LIBLOG_HIDDEN int __android_log_transport;
+
+LIBLOG_ABI_PUBLIC int android_set_log_transport(int transport_flag) {
+  int retval;
+
+  if (transport_flag < 0) {
+    return -EINVAL;
+  }
+
+  retval = LOGGER_NULL;
+
+  __android_log_lock();
+
+  if (transport_flag & LOGGER_NULL) {
+    write_to_log = __write_to_log_null;
+
+    __android_log_unlock();
+
+    return retval;
+  }
+
+  __android_log_transport &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
+
+  transport_flag &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
+
+  if (__android_log_transport != transport_flag) {
+    __android_log_transport = transport_flag;
+    __android_log_config_write_close();
+    __android_log_config_read_close();
+
+    write_to_log = __write_to_log_init;
+    /* generically we only expect these two values for write_to_log */
+  } else if ((write_to_log != __write_to_log_init) &&
+             (write_to_log != __write_to_log_daemon)) {
+    write_to_log = __write_to_log_init;
+  }
+
+  retval = __android_log_transport;
+
+  __android_log_unlock();
+
+  return retval;
+}
+
+LIBLOG_ABI_PUBLIC int android_get_log_transport() {
+  int ret = LOGGER_DEFAULT;
+
+  __android_log_lock();
+  if (write_to_log == __write_to_log_null) {
+    ret = LOGGER_NULL;
+  } else {
+    __android_log_transport &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
+    ret = __android_log_transport;
+    if ((write_to_log != __write_to_log_init) &&
+        (write_to_log != __write_to_log_daemon)) {
+      ret = -EINVAL;
+    }
+  }
+  __android_log_unlock();
+
+  return ret;
 }
diff --git a/liblog/logprint.c b/liblog/logprint.c
index c8457f4..2ade7b0 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -16,72 +16,88 @@
 */
 
 #define _GNU_SOURCE /* for asprintf */
+#ifndef __MINGW32__
+#define HAVE_STRSEP
+#endif
 
-#include <arpa/inet.h>
 #include <assert.h>
 #include <ctype.h>
 #include <errno.h>
+#include <inttypes.h>
+#ifndef __MINGW32__
+#include <pwd.h>
+#endif
 #include <stdbool.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <inttypes.h>
 #include <sys/param.h>
+#include <sys/types.h>
 
 #include <cutils/list.h>
-#include <log/logd.h>
+#include <log/log.h>
 #include <log/logprint.h>
-#include <private/android_filesystem_config.h>
 
 #include "log_portability.h"
 
 #define MS_PER_NSEC 1000000
 #define US_PER_NSEC 1000
 
+#ifndef MIN
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
+#endif
+
 typedef struct FilterInfo_t {
-    char *mTag;
-    android_LogPriority mPri;
-    struct FilterInfo_t *p_next;
+  char* mTag;
+  android_LogPriority mPri;
+  struct FilterInfo_t* p_next;
 } FilterInfo;
 
 struct AndroidLogFormat_t {
-    android_LogPriority global_pri;
-    FilterInfo *filters;
-    AndroidLogPrintFormat format;
-    bool colored_output;
-    bool usec_time_output;
-    bool printable_output;
-    bool year_output;
-    bool zone_output;
-    bool epoch_output;
-    bool monotonic_output;
-    bool uid_output;
+  android_LogPriority global_pri;
+  FilterInfo* filters;
+  AndroidLogPrintFormat format;
+  bool colored_output;
+  bool usec_time_output;
+  bool nsec_time_output;
+  bool printable_output;
+  bool year_output;
+  bool zone_output;
+  bool epoch_output;
+  bool monotonic_output;
+  bool uid_output;
+  bool descriptive_output;
 };
 
 /*
+ * API issues prevent us from exposing "descriptive" in AndroidLogFormat_t
+ * during android_log_processBinaryLogBuffer(), so we break layering.
+ */
+static bool descriptive_output = false;
+
+/*
  *  gnome-terminal color tags
  *    See http://misc.flogisoft.com/bash/tip_colors_and_formatting
  *    for ideas on how to set the forground color of the text for xterm.
  *    The color manipulation character stream is defined as:
  *      ESC [ 3 8 ; 5 ; <color#> m
  */
-#define ANDROID_COLOR_BLUE     75
+#define ANDROID_COLOR_BLUE 75
 #define ANDROID_COLOR_DEFAULT 231
-#define ANDROID_COLOR_GREEN    40
-#define ANDROID_COLOR_ORANGE  166
-#define ANDROID_COLOR_RED     196
-#define ANDROID_COLOR_YELLOW  226
+#define ANDROID_COLOR_GREEN 40
+#define ANDROID_COLOR_ORANGE 166
+#define ANDROID_COLOR_RED 196
+#define ANDROID_COLOR_YELLOW 226
 
-static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
-{
-    FilterInfo *p_ret;
+static FilterInfo* filterinfo_new(const char* tag, android_LogPriority pri) {
+  FilterInfo* p_ret;
 
-    p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
-    p_ret->mTag = strdup(tag);
-    p_ret->mPri = pri;
+  p_ret = (FilterInfo*)calloc(1, sizeof(FilterInfo));
+  p_ret->mTag = strdup(tag);
+  p_ret->mPri = pri;
 
-    return p_ret;
+  return p_ret;
 }
 
 /* balance to above, filterinfo_free left unimplemented */
@@ -90,187 +106,193 @@
  * Note: also accepts 0-9 priorities
  * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
  */
-static android_LogPriority filterCharToPri (char c)
-{
-    android_LogPriority pri;
+static android_LogPriority filterCharToPri(char c) {
+  android_LogPriority pri;
 
-    c = tolower(c);
+  c = tolower(c);
 
-    if (c >= '0' && c <= '9') {
-        if (c >= ('0'+ANDROID_LOG_SILENT)) {
-            pri = ANDROID_LOG_VERBOSE;
-        } else {
-            pri = (android_LogPriority)(c - '0');
-        }
-    } else if (c == 'v') {
-        pri = ANDROID_LOG_VERBOSE;
-    } else if (c == 'd') {
-        pri = ANDROID_LOG_DEBUG;
-    } else if (c == 'i') {
-        pri = ANDROID_LOG_INFO;
-    } else if (c == 'w') {
-        pri = ANDROID_LOG_WARN;
-    } else if (c == 'e') {
-        pri = ANDROID_LOG_ERROR;
-    } else if (c == 'f') {
-        pri = ANDROID_LOG_FATAL;
-    } else if (c == 's') {
-        pri = ANDROID_LOG_SILENT;
-    } else if (c == '*') {
-        pri = ANDROID_LOG_DEFAULT;
+  if (c >= '0' && c <= '9') {
+    if (c >= ('0' + ANDROID_LOG_SILENT)) {
+      pri = ANDROID_LOG_VERBOSE;
     } else {
-        pri = ANDROID_LOG_UNKNOWN;
+      pri = (android_LogPriority)(c - '0');
     }
+  } else if (c == 'v') {
+    pri = ANDROID_LOG_VERBOSE;
+  } else if (c == 'd') {
+    pri = ANDROID_LOG_DEBUG;
+  } else if (c == 'i') {
+    pri = ANDROID_LOG_INFO;
+  } else if (c == 'w') {
+    pri = ANDROID_LOG_WARN;
+  } else if (c == 'e') {
+    pri = ANDROID_LOG_ERROR;
+  } else if (c == 'f') {
+    pri = ANDROID_LOG_FATAL;
+  } else if (c == 's') {
+    pri = ANDROID_LOG_SILENT;
+  } else if (c == '*') {
+    pri = ANDROID_LOG_DEFAULT;
+  } else {
+    pri = ANDROID_LOG_UNKNOWN;
+  }
 
-    return pri;
+  return pri;
 }
 
-static char filterPriToChar (android_LogPriority pri)
-{
-    switch (pri) {
-        case ANDROID_LOG_VERBOSE:       return 'V';
-        case ANDROID_LOG_DEBUG:         return 'D';
-        case ANDROID_LOG_INFO:          return 'I';
-        case ANDROID_LOG_WARN:          return 'W';
-        case ANDROID_LOG_ERROR:         return 'E';
-        case ANDROID_LOG_FATAL:         return 'F';
-        case ANDROID_LOG_SILENT:        return 'S';
+static char filterPriToChar(android_LogPriority pri) {
+  switch (pri) {
+    /* clang-format off */
+    case ANDROID_LOG_VERBOSE: return 'V';
+    case ANDROID_LOG_DEBUG:   return 'D';
+    case ANDROID_LOG_INFO:    return 'I';
+    case ANDROID_LOG_WARN:    return 'W';
+    case ANDROID_LOG_ERROR:   return 'E';
+    case ANDROID_LOG_FATAL:   return 'F';
+    case ANDROID_LOG_SILENT:  return 'S';
 
-        case ANDROID_LOG_DEFAULT:
-        case ANDROID_LOG_UNKNOWN:
-        default:                        return '?';
-    }
+    case ANDROID_LOG_DEFAULT:
+    case ANDROID_LOG_UNKNOWN:
+    default:                  return '?';
+    /* clang-format on */
+  }
 }
 
-static int colorFromPri (android_LogPriority pri)
-{
-    switch (pri) {
-        case ANDROID_LOG_VERBOSE:       return ANDROID_COLOR_DEFAULT;
-        case ANDROID_LOG_DEBUG:         return ANDROID_COLOR_BLUE;
-        case ANDROID_LOG_INFO:          return ANDROID_COLOR_GREEN;
-        case ANDROID_LOG_WARN:          return ANDROID_COLOR_ORANGE;
-        case ANDROID_LOG_ERROR:         return ANDROID_COLOR_RED;
-        case ANDROID_LOG_FATAL:         return ANDROID_COLOR_RED;
-        case ANDROID_LOG_SILENT:        return ANDROID_COLOR_DEFAULT;
+static int colorFromPri(android_LogPriority pri) {
+  switch (pri) {
+    /* clang-format off */
+    case ANDROID_LOG_VERBOSE: return ANDROID_COLOR_DEFAULT;
+    case ANDROID_LOG_DEBUG:   return ANDROID_COLOR_BLUE;
+    case ANDROID_LOG_INFO:    return ANDROID_COLOR_GREEN;
+    case ANDROID_LOG_WARN:    return ANDROID_COLOR_ORANGE;
+    case ANDROID_LOG_ERROR:   return ANDROID_COLOR_RED;
+    case ANDROID_LOG_FATAL:   return ANDROID_COLOR_RED;
+    case ANDROID_LOG_SILENT:  return ANDROID_COLOR_DEFAULT;
 
-        case ANDROID_LOG_DEFAULT:
-        case ANDROID_LOG_UNKNOWN:
-        default:                        return ANDROID_COLOR_DEFAULT;
-    }
+    case ANDROID_LOG_DEFAULT:
+    case ANDROID_LOG_UNKNOWN:
+    default:                  return ANDROID_COLOR_DEFAULT;
+    /* clang-format on */
+  }
 }
 
-static android_LogPriority filterPriForTag(
-        AndroidLogFormat *p_format, const char *tag)
-{
-    FilterInfo *p_curFilter;
+static android_LogPriority filterPriForTag(AndroidLogFormat* p_format,
+                                           const char* tag) {
+  FilterInfo* p_curFilter;
 
-    for (p_curFilter = p_format->filters
-            ; p_curFilter != NULL
-            ; p_curFilter = p_curFilter->p_next
-    ) {
-        if (0 == strcmp(tag, p_curFilter->mTag)) {
-            if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
-                return p_format->global_pri;
-            } else {
-                return p_curFilter->mPri;
-            }
-        }
+  for (p_curFilter = p_format->filters; p_curFilter != NULL;
+       p_curFilter = p_curFilter->p_next) {
+    if (0 == strcmp(tag, p_curFilter->mTag)) {
+      if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
+        return p_format->global_pri;
+      } else {
+        return p_curFilter->mPri;
+      }
     }
+  }
 
-    return p_format->global_pri;
+  return p_format->global_pri;
 }
 
 /**
  * returns 1 if this log line should be printed based on its priority
  * and tag, and 0 if it should not
  */
-LIBLOG_ABI_PUBLIC int android_log_shouldPrintLine (
-        AndroidLogFormat *p_format,
-        const char *tag,
-        android_LogPriority pri)
-{
-    return pri >= filterPriForTag(p_format, tag);
+LIBLOG_ABI_PUBLIC int android_log_shouldPrintLine(AndroidLogFormat* p_format,
+                                                  const char* tag,
+                                                  android_LogPriority pri) {
+  return pri >= filterPriForTag(p_format, tag);
 }
 
-LIBLOG_ABI_PUBLIC AndroidLogFormat *android_log_format_new()
-{
-    AndroidLogFormat *p_ret;
+LIBLOG_ABI_PUBLIC AndroidLogFormat* android_log_format_new() {
+  AndroidLogFormat* p_ret;
 
-    p_ret = calloc(1, sizeof(AndroidLogFormat));
+  p_ret = calloc(1, sizeof(AndroidLogFormat));
 
-    p_ret->global_pri = ANDROID_LOG_VERBOSE;
-    p_ret->format = FORMAT_BRIEF;
-    p_ret->colored_output = false;
-    p_ret->usec_time_output = false;
-    p_ret->printable_output = false;
-    p_ret->year_output = false;
-    p_ret->zone_output = false;
-    p_ret->epoch_output = false;
-    p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
-    p_ret->uid_output = false;
+  p_ret->global_pri = ANDROID_LOG_VERBOSE;
+  p_ret->format = FORMAT_BRIEF;
+  p_ret->colored_output = false;
+  p_ret->usec_time_output = false;
+  p_ret->nsec_time_output = false;
+  p_ret->printable_output = false;
+  p_ret->year_output = false;
+  p_ret->zone_output = false;
+  p_ret->epoch_output = false;
+#ifdef __ANDROID__
+  p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
+#else
+  p_ret->monotonic_output = false;
+#endif
+  p_ret->uid_output = false;
+  p_ret->descriptive_output = false;
+  descriptive_output = false;
 
-    return p_ret;
+  return p_ret;
 }
 
 static list_declare(convertHead);
 
-LIBLOG_ABI_PUBLIC void android_log_format_free(AndroidLogFormat *p_format)
-{
-    FilterInfo *p_info, *p_info_old;
+LIBLOG_ABI_PUBLIC void android_log_format_free(AndroidLogFormat* p_format) {
+  FilterInfo *p_info, *p_info_old;
 
-    p_info = p_format->filters;
+  p_info = p_format->filters;
 
-    while (p_info != NULL) {
-        p_info_old = p_info;
-        p_info = p_info->p_next;
+  while (p_info != NULL) {
+    p_info_old = p_info;
+    p_info = p_info->p_next;
 
-        free(p_info_old);
-    }
+    free(p_info_old);
+  }
 
-    free(p_format);
+  free(p_format);
 
-    /* Free conversion resource, can always be reconstructed */
-    while (!list_empty(&convertHead)) {
-        struct listnode *node = list_head(&convertHead);
-        list_remove(node);
-        free(node);
-    }
+  /* Free conversion resource, can always be reconstructed */
+  while (!list_empty(&convertHead)) {
+    struct listnode* node = list_head(&convertHead);
+    list_remove(node);
+    free(node);
+  }
 }
 
-LIBLOG_ABI_PUBLIC int android_log_setPrintFormat(
-        AndroidLogFormat *p_format,
-        AndroidLogPrintFormat format)
-{
-    switch (format) {
+LIBLOG_ABI_PUBLIC int android_log_setPrintFormat(AndroidLogFormat* p_format,
+                                                 AndroidLogPrintFormat format) {
+  switch (format) {
     case FORMAT_MODIFIER_COLOR:
-        p_format->colored_output = true;
-        return 0;
+      p_format->colored_output = true;
+      return 0;
     case FORMAT_MODIFIER_TIME_USEC:
-        p_format->usec_time_output = true;
-        return 0;
+      p_format->usec_time_output = true;
+      return 0;
+    case FORMAT_MODIFIER_TIME_NSEC:
+      p_format->nsec_time_output = true;
+      return 0;
     case FORMAT_MODIFIER_PRINTABLE:
-        p_format->printable_output = true;
-        return 0;
+      p_format->printable_output = true;
+      return 0;
     case FORMAT_MODIFIER_YEAR:
-        p_format->year_output = true;
-        return 0;
+      p_format->year_output = true;
+      return 0;
     case FORMAT_MODIFIER_ZONE:
-        p_format->zone_output = !p_format->zone_output;
-        return 0;
+      p_format->zone_output = !p_format->zone_output;
+      return 0;
     case FORMAT_MODIFIER_EPOCH:
-        p_format->epoch_output = true;
-        return 0;
+      p_format->epoch_output = true;
+      return 0;
     case FORMAT_MODIFIER_MONOTONIC:
-        p_format->monotonic_output = true;
-        return 0;
+      p_format->monotonic_output = true;
+      return 0;
     case FORMAT_MODIFIER_UID:
-        p_format->uid_output = true;
-        return 0;
+      p_format->uid_output = true;
+      return 0;
+    case FORMAT_MODIFIER_DESCRIPT:
+      p_format->descriptive_output = true;
+      descriptive_output = true;
+      return 0;
     default:
-        break;
-    }
-    p_format->format = format;
-    return 1;
+      break;
+  }
+  p_format->format = format;
+  return 1;
 }
 
 static const char tz[] = "TZ";
@@ -279,60 +301,65 @@
 /**
  * Returns FORMAT_OFF on invalid string
  */
-LIBLOG_ABI_PUBLIC AndroidLogPrintFormat android_log_formatFromString(
-        const char * formatString)
-{
-    static AndroidLogPrintFormat format;
+LIBLOG_ABI_PUBLIC AndroidLogPrintFormat
+android_log_formatFromString(const char* formatString) {
+  static AndroidLogPrintFormat format;
 
-    if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
-    else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
-    else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
-    else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
-    else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
-    else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
-    else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
-    else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
-    else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
-    else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
-    else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
-    else if (strcmp(formatString, "year") == 0) format = FORMAT_MODIFIER_YEAR;
-    else if (strcmp(formatString, "zone") == 0) format = FORMAT_MODIFIER_ZONE;
-    else if (strcmp(formatString, "epoch") == 0) format = FORMAT_MODIFIER_EPOCH;
-    else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
-    else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
-    else {
-        extern char *tzname[2];
-        static const char gmt[] = "GMT";
-        char *cp = getenv(tz);
-        if (cp) {
-            cp = strdup(cp);
-        }
-        setenv(tz, formatString, 1);
-        /*
-         * Run tzset here to determine if the timezone is legitimate. If the
-         * zone is GMT, check if that is what was asked for, if not then
-         * did not match any on the system; report an error to caller.
-         */
-        tzset();
-        if (!tzname[0]
-                || ((!strcmp(tzname[0], utc)
-                        || !strcmp(tzname[0], gmt)) /* error? */
-                    && strcasecmp(formatString, utc)
-                    && strcasecmp(formatString, gmt))) { /* ok */
-            if (cp) {
-                setenv(tz, cp, 1);
-            } else {
-                unsetenv(tz);
-            }
-            tzset();
-            format = FORMAT_OFF;
-        } else {
-            format = FORMAT_MODIFIER_ZONE;
-        }
-        free(cp);
+  /* clang-format off */
+  if (!strcmp(formatString, "brief")) format = FORMAT_BRIEF;
+  else if (!strcmp(formatString, "process")) format = FORMAT_PROCESS;
+  else if (!strcmp(formatString, "tag")) format = FORMAT_TAG;
+  else if (!strcmp(formatString, "thread")) format = FORMAT_THREAD;
+  else if (!strcmp(formatString, "raw")) format = FORMAT_RAW;
+  else if (!strcmp(formatString, "time")) format = FORMAT_TIME;
+  else if (!strcmp(formatString, "threadtime")) format = FORMAT_THREADTIME;
+  else if (!strcmp(formatString, "long")) format = FORMAT_LONG;
+  else if (!strcmp(formatString, "color")) format = FORMAT_MODIFIER_COLOR;
+  else if (!strcmp(formatString, "colour")) format = FORMAT_MODIFIER_COLOR;
+  else if (!strcmp(formatString, "usec")) format = FORMAT_MODIFIER_TIME_USEC;
+  else if (!strcmp(formatString, "nsec")) format = FORMAT_MODIFIER_TIME_NSEC;
+  else if (!strcmp(formatString, "printable")) format = FORMAT_MODIFIER_PRINTABLE;
+  else if (!strcmp(formatString, "year")) format = FORMAT_MODIFIER_YEAR;
+  else if (!strcmp(formatString, "zone")) format = FORMAT_MODIFIER_ZONE;
+  else if (!strcmp(formatString, "epoch")) format = FORMAT_MODIFIER_EPOCH;
+  else if (!strcmp(formatString, "monotonic")) format = FORMAT_MODIFIER_MONOTONIC;
+  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];
+    static const char gmt[] = "GMT";
+    char* cp = getenv(tz);
+    if (cp) {
+      cp = strdup(cp);
     }
+    setenv(tz, formatString, 1);
+    /*
+     * Run tzset here to determine if the timezone is legitimate. If the
+     * zone is GMT, check if that is what was asked for, if not then
+     * did not match any on the system; report an error to caller.
+     */
+    tzset();
+    if (!tzname[0] ||
+        ((!strcmp(tzname[0], utc) || !strcmp(tzname[0], gmt)) /* error? */
+         && strcasecmp(formatString, utc) &&
+         strcasecmp(formatString, gmt))) { /* ok */
+      if (cp) {
+        setenv(tz, cp, 1);
+      } else {
+        unsetenv(tz);
+      }
+      tzset();
+      format = FORMAT_OFF;
+    } else {
+      format = FORMAT_MODIFIER_ZONE;
+    }
+    free(cp);
+  }
+#endif
 
-    return format;
+  return format;
 }
 
 /**
@@ -344,73 +371,91 @@
  * Assumes single threaded execution
  */
 
-LIBLOG_ABI_PUBLIC int android_log_addFilterRule(
-        AndroidLogFormat *p_format,
-        const char *filterExpression)
-{
-    size_t tagNameLength;
-    android_LogPriority pri = ANDROID_LOG_DEFAULT;
+LIBLOG_ABI_PUBLIC int android_log_addFilterRule(AndroidLogFormat* p_format,
+                                                const char* filterExpression) {
+  size_t tagNameLength;
+  android_LogPriority pri = ANDROID_LOG_DEFAULT;
 
-    tagNameLength = strcspn(filterExpression, ":");
+  tagNameLength = strcspn(filterExpression, ":");
 
-    if (tagNameLength == 0) {
-        goto error;
+  if (tagNameLength == 0) {
+    goto error;
+  }
+
+  if (filterExpression[tagNameLength] == ':') {
+    pri = filterCharToPri(filterExpression[tagNameLength + 1]);
+
+    if (pri == ANDROID_LOG_UNKNOWN) {
+      goto error;
+    }
+  }
+
+  if (0 == strncmp("*", filterExpression, tagNameLength)) {
+    /*
+     * This filter expression refers to the global filter
+     * The default level for this is DEBUG if the priority
+     * is unspecified
+     */
+    if (pri == ANDROID_LOG_DEFAULT) {
+      pri = ANDROID_LOG_DEBUG;
     }
 
-    if(filterExpression[tagNameLength] == ':') {
-        pri = filterCharToPri(filterExpression[tagNameLength+1]);
-
-        if (pri == ANDROID_LOG_UNKNOWN) {
-            goto error;
-        }
+    p_format->global_pri = pri;
+  } else {
+    /*
+     * for filter expressions that don't refer to the global
+     * filter, the default is verbose if the priority is unspecified
+     */
+    if (pri == ANDROID_LOG_DEFAULT) {
+      pri = ANDROID_LOG_VERBOSE;
     }
 
-    if(0 == strncmp("*", filterExpression, tagNameLength)) {
-        /*
-         * This filter expression refers to the global filter
-         * The default level for this is DEBUG if the priority
-         * is unspecified
-         */
-        if (pri == ANDROID_LOG_DEFAULT) {
-            pri = ANDROID_LOG_DEBUG;
-        }
-
-        p_format->global_pri = pri;
-    } else {
-        /*
-         * for filter expressions that don't refer to the global
-         * filter, the default is verbose if the priority is unspecified
-         */
-        if (pri == ANDROID_LOG_DEFAULT) {
-            pri = ANDROID_LOG_VERBOSE;
-        }
-
-        char *tagName;
+    char* tagName;
 
 /*
  * Presently HAVE_STRNDUP is never defined, so the second case is always taken
- * Darwin doesn't have strnup, everything else does
+ * Darwin doesn't have strndup, everything else does
  */
 #ifdef HAVE_STRNDUP
-        tagName = strndup(filterExpression, tagNameLength);
+    tagName = strndup(filterExpression, tagNameLength);
 #else
-        /* a few extra bytes copied... */
-        tagName = strdup(filterExpression);
-        tagName[tagNameLength] = '\0';
+    /* a few extra bytes copied... */
+    tagName = strdup(filterExpression);
+    tagName[tagNameLength] = '\0';
 #endif /*HAVE_STRNDUP*/
 
-        FilterInfo *p_fi = filterinfo_new(tagName, pri);
-        free(tagName);
+    FilterInfo* p_fi = filterinfo_new(tagName, pri);
+    free(tagName);
 
-        p_fi->p_next = p_format->filters;
-        p_format->filters = p_fi;
-    }
+    p_fi->p_next = p_format->filters;
+    p_format->filters = p_fi;
+  }
 
-    return 0;
+  return 0;
 error:
-    return -1;
+  return -1;
 }
 
+#ifndef HAVE_STRSEP
+/* KISS replacement helper for below */
+static char* strsep(char** stringp, const char* delim) {
+  char* token;
+  char* ret = *stringp;
+
+  if (!ret || !*ret) {
+    return NULL;
+  }
+  token = strpbrk(ret, delim);
+  if (token) {
+    *token = '\0';
+    ++token;
+  } else {
+    token = ret + strlen(ret);
+  }
+  *stringp = token;
+  return ret;
+}
+#endif
 
 /**
  * filterString: a comma/whitespace-separated set of filter expressions
@@ -422,33 +467,30 @@
  * Assumes single threaded execution
  *
  */
+LIBLOG_ABI_PUBLIC int android_log_addFilterString(AndroidLogFormat* p_format,
+                                                  const char* filterString) {
+  char* filterStringCopy = strdup(filterString);
+  char* p_cur = filterStringCopy;
+  char* p_ret;
+  int err;
 
-LIBLOG_ABI_PUBLIC int android_log_addFilterString(
-        AndroidLogFormat *p_format,
-        const char *filterString)
-{
-    char *filterStringCopy = strdup (filterString);
-    char *p_cur = filterStringCopy;
-    char *p_ret;
-    int err;
+  /* Yes, I'm using strsep */
+  while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
+    /* ignore whitespace-only entries */
+    if (p_ret[0] != '\0') {
+      err = android_log_addFilterRule(p_format, p_ret);
 
-    /* Yes, I'm using strsep */
-    while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
-        /* ignore whitespace-only entries */
-        if(p_ret[0] != '\0') {
-            err = android_log_addFilterRule(p_format, p_ret);
-
-            if (err < 0) {
-                goto error;
-            }
-        }
+      if (err < 0) {
+        goto error;
+      }
     }
+  }
 
-    free (filterStringCopy);
-    return 0;
+  free(filterStringCopy);
+  return 0;
 error:
-    free (filterStringCopy);
-    return -1;
+  free(filterStringCopy);
+  return -1;
 }
 
 /**
@@ -458,107 +500,125 @@
  * Returns 0 on success and -1 on invalid wire format (entry will be
  * in unspecified state)
  */
-LIBLOG_ABI_PUBLIC int android_log_processLogBuffer(
-        struct logger_entry *buf,
-        AndroidLogEntry *entry)
-{
-    entry->tv_sec = buf->sec;
-    entry->tv_nsec = buf->nsec;
-    entry->uid = -1;
-    entry->pid = buf->pid;
-    entry->tid = buf->tid;
+LIBLOG_ABI_PUBLIC int android_log_processLogBuffer(struct logger_entry* buf,
+                                                   AndroidLogEntry* entry) {
+  entry->message = NULL;
+  entry->messageLen = 0;
 
+  entry->tv_sec = buf->sec;
+  entry->tv_nsec = buf->nsec;
+  entry->uid = -1;
+  entry->pid = buf->pid;
+  entry->tid = buf->tid;
+
+  /*
+   * format: <priority:1><tag:N>\0<message:N>\0
+   *
+   * tag str
+   *   starts at buf->msg+1
+   * msg
+   *   starts at buf->msg+1+len(tag)+1
+   *
+   * The message may have been truncated by the kernel log driver.
+   * When that happens, we must null-terminate the message ourselves.
+   */
+  if (buf->len < 3) {
     /*
-     * format: <priority:1><tag:N>\0<message:N>\0
-     *
-     * tag str
-     *   starts at buf->msg+1
-     * msg
-     *   starts at buf->msg+1+len(tag)+1
-     *
-     * The message may have been truncated by the kernel log driver.
-     * When that happens, we must null-terminate the message ourselves.
+     * An well-formed entry must consist of at least a priority
+     * and two null characters
      */
-    if (buf->len < 3) {
-        /*
-         * An well-formed entry must consist of at least a priority
-         * and two null characters
-         */
-        fprintf(stderr, "+++ LOG: entry too small\n");
-        return -1;
-    }
+    fprintf(stderr, "+++ LOG: entry too small\n");
+    return -1;
+  }
 
-    int msgStart = -1;
-    int msgEnd = -1;
+  int msgStart = -1;
+  int msgEnd = -1;
 
-    int i;
-    char *msg = buf->msg;
-    struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
-    if (buf2->hdr_size) {
-        msg = ((char *)buf2) + buf2->hdr_size;
-        if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
-            entry->uid = ((struct logger_entry_v4 *)buf)->uid;
-        }
+  int i;
+  char* msg = buf->msg;
+  struct logger_entry_v2* buf2 = (struct logger_entry_v2*)buf;
+  if (buf2->hdr_size) {
+    if ((buf2->hdr_size < sizeof(((struct log_msg*)NULL)->entry_v1)) ||
+        (buf2->hdr_size > sizeof(((struct log_msg*)NULL)->entry))) {
+      fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
+      return -1;
     }
+    msg = ((char*)buf2) + buf2->hdr_size;
+    if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
+      entry->uid = ((struct logger_entry_v4*)buf)->uid;
+    }
+  }
+  for (i = 1; i < buf->len; i++) {
+    if (msg[i] == '\0') {
+      if (msgStart == -1) {
+        msgStart = i + 1;
+      } else {
+        msgEnd = i;
+        break;
+      }
+    }
+  }
+
+  if (msgStart == -1) {
+    /* +++ LOG: malformed log message, DYB */
     for (i = 1; i < buf->len; i++) {
-        if (msg[i] == '\0') {
-            if (msgStart == -1) {
-                msgStart = i + 1;
-            } else {
-                msgEnd = i;
-                break;
-            }
-        }
+      /* odd characters in tag? */
+      if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
+        msg[i] = '\0';
+        msgStart = i + 1;
+        break;
+      }
     }
-
     if (msgStart == -1) {
-        /* +++ LOG: malformed log message, DYB */
-        for (i = 1; i < buf->len; i++) {
-            /* odd characters in tag? */
-            if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
-                msg[i] = '\0';
-                msgStart = i + 1;
-                break;
-            }
-        }
-        if (msgStart == -1) {
-            msgStart = buf->len - 1; /* All tag, no message, print truncates */
-        }
+      msgStart = buf->len - 1; /* All tag, no message, print truncates */
     }
-    if (msgEnd == -1) {
-        /* incoming message not null-terminated; force it */
-        msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
-        msg[msgEnd] = '\0';
-    }
+  }
+  if (msgEnd == -1) {
+    /* incoming message not null-terminated; force it */
+    msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
+    msg[msgEnd] = '\0';
+  }
 
-    entry->priority = msg[0];
-    entry->tag = msg + 1;
-    entry->message = msg + msgStart;
-    entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
+  entry->priority = msg[0];
+  entry->tag = msg + 1;
+  entry->tagLen = msgStart - 1;
+  entry->message = msg + msgStart;
+  entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
 
-    return 0;
+  return 0;
 }
 
 /*
  * Extract a 4-byte value from a byte stream.
  */
-static inline uint32_t get4LE(const uint8_t* src)
-{
-    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+static inline uint32_t get4LE(const uint8_t* src) {
+  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
 
 /*
  * Extract an 8-byte value from a byte stream.
  */
-static inline uint64_t get8LE(const uint8_t* src)
-{
-    uint32_t low, high;
+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;
+  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;
 }
 
+static bool findChar(const char** cp, size_t* len, int c) {
+  while ((*len) && isspace(*(*cp))) {
+    ++(*cp);
+    --(*len);
+  }
+  if (c == INT_MAX) return *len;
+  if ((*len) && (*(*cp) == c)) {
+    ++(*cp);
+    --(*len);
+    return true;
+  }
+  return false;
+}
 
 /*
  * Recursively convert binary log data to printable form.
@@ -571,175 +631,338 @@
  *
  * Returns 0 on success, 1 on buffer full, -1 on failure.
  */
+enum objectType {
+  TYPE_OBJECTS = '1',
+  TYPE_BYTES = '2',
+  TYPE_MILLISECONDS = '3',
+  TYPE_ALLOCATIONS = '4',
+  TYPE_ID = '5',
+  TYPE_PERCENT = '6'
+};
+
 static int android_log_printBinaryEvent(const unsigned char** pEventData,
-    size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
-{
-    const unsigned char* eventData = *pEventData;
-    size_t eventDataLen = *pEventDataLen;
-    char* outBuf = *pOutBuf;
-    size_t outBufLen = *pOutBufLen;
-    unsigned char type;
-    size_t outCount;
-    int result = 0;
+                                        size_t* pEventDataLen, char** pOutBuf,
+                                        size_t* pOutBufLen, const char** fmtStr,
+                                        size_t* fmtLen) {
+  const unsigned char* eventData = *pEventData;
+  size_t eventDataLen = *pEventDataLen;
+  char* outBuf = *pOutBuf;
+  char* outBufSave = outBuf;
+  size_t outBufLen = *pOutBufLen;
+  size_t outBufLenSave = outBufLen;
+  unsigned char type;
+  size_t outCount;
+  int result = 0;
+  const char* cp;
+  size_t len;
+  int64_t lval;
 
-    if (eventDataLen < 1)
-        return -1;
-    type = *eventData++;
-    eventDataLen--;
+  if (eventDataLen < 1) return -1;
 
-    switch (type) {
-    case EVENT_TYPE_INT:
-        /* 32-bit signed int */
-        {
-            int ival;
+  type = *eventData++;
+  eventDataLen--;
 
-            if (eventDataLen < 4)
-                return -1;
-            ival = get4LE(eventData);
-            eventData += 4;
-            eventDataLen -= 4;
+  cp = NULL;
+  len = 0;
+  if (fmtStr && *fmtStr && fmtLen && *fmtLen && **fmtStr) {
+    cp = *fmtStr;
+    len = *fmtLen;
+  }
+  /*
+   * event.logtag format specification:
+   *
+   * Optionally, after the tag names can be put a description for the value(s)
+   * of the tag. Description are in the format
+   *    (<name>|data type[|data unit])
+   * Multiple values are separated by commas.
+   *
+   * The data type is a number from the following values:
+   * 1: int
+   * 2: long
+   * 3: string
+   * 4: list
+   * 5: float
+   *
+   * The data unit is a number taken from the following list:
+   * 1: Number of objects
+   * 2: Number of bytes
+   * 3: Number of milliseconds
+   * 4: Number of allocations
+   * 5: Id
+   * 6: Percent
+   * Default value for data of type int/long is 2 (bytes).
+   */
+  if (!cp || !findChar(&cp, &len, '(')) {
+    len = 0;
+  } else {
+    char* outBufLastSpace = NULL;
 
-            outCount = snprintf(outBuf, outBufLen, "%d", ival);
-            if (outCount < outBufLen) {
-                outBuf += outCount;
-                outBufLen -= outCount;
-            } else {
-                /* halt output */
-                goto no_room;
-            }
-        }
-        break;
-    case EVENT_TYPE_LONG:
-        /* 64-bit signed long */
-        {
-            uint64_t lval;
-
-            if (eventDataLen < 8)
-                return -1;
-            lval = get8LE(eventData);
-            eventData += 8;
-            eventDataLen -= 8;
-
-            outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
-            if (outCount < outBufLen) {
-                outBuf += outCount;
-                outBufLen -= outCount;
-            } else {
-                /* halt output */
-                goto no_room;
-            }
-        }
-        break;
-    case EVENT_TYPE_FLOAT:
-        /* float */
-        {
-            uint32_t ival;
-            float fval;
-
-            if (eventDataLen < 4)
-                return -1;
-            ival = get4LE(eventData);
-            fval = *(float*)&ival;
-            eventData += 4;
-            eventDataLen -= 4;
-
-            outCount = snprintf(outBuf, outBufLen, "%f", fval);
-            if (outCount < outBufLen) {
-                outBuf += outCount;
-                outBufLen -= outCount;
-            } else {
-                /* halt output */
-                goto no_room;
-            }
-        }
-        break;
-    case EVENT_TYPE_STRING:
-        /* UTF-8 chars, not NULL-terminated */
-        {
-            unsigned int strLen;
-
-            if (eventDataLen < 4)
-                return -1;
-            strLen = get4LE(eventData);
-            eventData += 4;
-            eventDataLen -= 4;
-
-            if (eventDataLen < strLen)
-                return -1;
-
-            if (strLen < outBufLen) {
-                memcpy(outBuf, eventData, strLen);
-                outBuf += strLen;
-                outBufLen -= strLen;
-            } else if (outBufLen > 0) {
-                /* copy what we can */
-                memcpy(outBuf, eventData, outBufLen);
-                outBuf += outBufLen;
-                outBufLen -= outBufLen;
-                goto no_room;
-            }
-            eventData += strLen;
-            eventDataLen -= strLen;
-            break;
-        }
-    case EVENT_TYPE_LIST:
-        /* N items, all different types */
-        {
-            unsigned char count;
-            int i;
-
-            if (eventDataLen < 1)
-                return -1;
-
-            count = *eventData++;
-            eventDataLen--;
-
-            if (outBufLen > 0) {
-                *outBuf++ = '[';
-                outBufLen--;
-            } else {
-                goto no_room;
-            }
-
-            for (i = 0; i < count; i++) {
-                result = android_log_printBinaryEvent(&eventData, &eventDataLen,
-                        &outBuf, &outBufLen);
-                if (result != 0)
-                    goto bail;
-
-                if (i < count-1) {
-                    if (outBufLen > 0) {
-                        *outBuf++ = ',';
-                        outBufLen--;
-                    } else {
-                        goto no_room;
-                    }
-                }
-            }
-
-            if (outBufLen > 0) {
-                *outBuf++ = ']';
-                outBufLen--;
-            } else {
-                goto no_room;
-            }
-        }
-        break;
-    default:
-        fprintf(stderr, "Unknown binary event type %d\n", type);
-        return -1;
+    findChar(&cp, &len, INT_MAX);
+    while (len && *cp && (*cp != '|') && (*cp != ')')) {
+      if (outBufLen <= 0) {
+        /* halt output */
+        goto no_room;
+      }
+      outBufLastSpace = isspace(*cp) ? outBuf : NULL;
+      *outBuf = *cp;
+      ++outBuf;
+      ++cp;
+      --outBufLen;
+      --len;
+    }
+    if (outBufLastSpace) {
+      outBufLen += outBuf - outBufLastSpace;
+      outBuf = outBufLastSpace;
+    }
+    if (outBufLen <= 0) {
+      /* halt output */
+      goto no_room;
+    }
+    if (outBufSave != outBuf) {
+      *outBuf = '=';
+      ++outBuf;
+      --outBufLen;
     }
 
+    if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
+      static const unsigned char typeTable[] = {
+        EVENT_TYPE_INT, EVENT_TYPE_LONG, EVENT_TYPE_STRING, EVENT_TYPE_LIST,
+        EVENT_TYPE_FLOAT
+      };
+
+      if ((*cp >= '1') &&
+          (*cp < (char)('1' + (sizeof(typeTable) / sizeof(typeTable[0])))) &&
+          (type != typeTable[(size_t)(*cp - '1')]))
+        len = 0;
+
+      if (len) {
+        ++cp;
+        --len;
+      } else {
+        /* reset the format */
+        outBuf = outBufSave;
+        outBufLen = outBufLenSave;
+      }
+    }
+  }
+  outCount = 0;
+  lval = 0;
+  switch (type) {
+    case EVENT_TYPE_INT:
+      /* 32-bit signed int */
+      {
+        int32_t ival;
+
+        if (eventDataLen < 4) return -1;
+        ival = get4LE(eventData);
+        eventData += 4;
+        eventDataLen -= 4;
+
+        lval = ival;
+      }
+      goto pr_lval;
+    case EVENT_TYPE_LONG:
+      /* 64-bit signed long */
+      if (eventDataLen < 8) return -1;
+      lval = get8LE(eventData);
+      eventData += 8;
+      eventDataLen -= 8;
+    pr_lval:
+      outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
+      if (outCount < outBufLen) {
+        outBuf += outCount;
+        outBufLen -= outCount;
+      } else {
+        /* halt output */
+        goto no_room;
+      }
+      break;
+    case EVENT_TYPE_FLOAT:
+      /* float */
+      {
+        uint32_t ival;
+        float fval;
+
+        if (eventDataLen < 4) return -1;
+        ival = get4LE(eventData);
+        fval = *(float*)&ival;
+        eventData += 4;
+        eventDataLen -= 4;
+
+        outCount = snprintf(outBuf, outBufLen, "%f", fval);
+        if (outCount < outBufLen) {
+          outBuf += outCount;
+          outBufLen -= outCount;
+        } else {
+          /* halt output */
+          goto no_room;
+        }
+      }
+      break;
+    case EVENT_TYPE_STRING:
+      /* UTF-8 chars, not NULL-terminated */
+      {
+        unsigned int strLen;
+
+        if (eventDataLen < 4) return -1;
+        strLen = get4LE(eventData);
+        eventData += 4;
+        eventDataLen -= 4;
+
+        if (eventDataLen < strLen) {
+          result = -1; /* mark truncated */
+          strLen = eventDataLen;
+        }
+
+        if (cp && (strLen == 0)) {
+          /* reset the format if no content */
+          outBuf = outBufSave;
+          outBufLen = outBufLenSave;
+        }
+        if (strLen < outBufLen) {
+          memcpy(outBuf, eventData, strLen);
+          outBuf += strLen;
+          outBufLen -= strLen;
+        } else {
+          if (outBufLen > 0) {
+            /* copy what we can */
+            memcpy(outBuf, eventData, outBufLen);
+            outBuf += outBufLen;
+            outBufLen -= outBufLen;
+          }
+          if (!result) result = 1; /* if not truncated, return no room */
+        }
+        eventData += strLen;
+        eventDataLen -= strLen;
+        if (result != 0) goto bail;
+        break;
+      }
+    case EVENT_TYPE_LIST:
+      /* N items, all different types */
+      {
+        unsigned char count;
+        int i;
+
+        if (eventDataLen < 1) return -1;
+
+        count = *eventData++;
+        eventDataLen--;
+
+        if (outBufLen <= 0) goto no_room;
+
+        *outBuf++ = '[';
+        outBufLen--;
+
+        for (i = 0; i < count; i++) {
+          result = android_log_printBinaryEvent(
+              &eventData, &eventDataLen, &outBuf, &outBufLen, fmtStr, fmtLen);
+          if (result != 0) goto bail;
+
+          if (i < (count - 1)) {
+            if (outBufLen <= 0) goto no_room;
+            *outBuf++ = ',';
+            outBufLen--;
+          }
+        }
+
+        if (outBufLen <= 0) goto no_room;
+
+        *outBuf++ = ']';
+        outBufLen--;
+      }
+      break;
+    default:
+      fprintf(stderr, "Unknown binary event type %d\n", type);
+      return -1;
+  }
+  if (cp && len) {
+    if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
+      switch (*cp) {
+        case TYPE_OBJECTS:
+          outCount = 0;
+          /* outCount = snprintf(outBuf, outBufLen, " objects"); */
+          break;
+        case TYPE_BYTES:
+          if ((lval != 0) && ((lval % 1024) == 0)) {
+            /* repaint with multiplier */
+            static const char suffixTable[] = { 'K', 'M', 'G', 'T' };
+            size_t idx = 0;
+            outBuf -= outCount;
+            outBufLen += outCount;
+            do {
+              lval /= 1024;
+              if ((lval % 1024) != 0) break;
+            } while (++idx <
+                     ((sizeof(suffixTable) / sizeof(suffixTable[0])) - 1));
+            outCount = snprintf(outBuf, outBufLen, "%" PRId64 "%cB", lval,
+                                suffixTable[idx]);
+          } else {
+            outCount = snprintf(outBuf, outBufLen, "B");
+          }
+          break;
+        case TYPE_MILLISECONDS:
+          if (((lval <= -1000) || (1000 <= lval)) &&
+              (outBufLen || (outBuf[-1] == '0'))) {
+            /* repaint as (fractional) seconds, possibly saving space */
+            if (outBufLen) outBuf[0] = outBuf[-1];
+            outBuf[-1] = outBuf[-2];
+            outBuf[-2] = outBuf[-3];
+            outBuf[-3] = '.';
+            while ((outBufLen == 0) || (*outBuf == '0')) {
+              --outBuf;
+              ++outBufLen;
+            }
+            if (*outBuf != '.') {
+              ++outBuf;
+              --outBufLen;
+            }
+            outCount = snprintf(outBuf, outBufLen, "s");
+          } else {
+            outCount = snprintf(outBuf, outBufLen, "ms");
+          }
+          break;
+        case TYPE_ALLOCATIONS:
+          outCount = 0;
+          /* outCount = snprintf(outBuf, outBufLen, " allocations"); */
+          break;
+        case TYPE_ID:
+          outCount = 0;
+          break;
+        case TYPE_PERCENT:
+          outCount = snprintf(outBuf, outBufLen, "%%");
+          break;
+        default: /* ? */
+          outCount = 0;
+          break;
+      }
+      ++cp;
+      --len;
+      if (outCount < outBufLen) {
+        outBuf += outCount;
+        outBufLen -= outCount;
+      } else if (outCount) {
+        /* halt output */
+        goto no_room;
+      }
+    }
+    if (!findChar(&cp, &len, ')')) len = 0;
+    if (!findChar(&cp, &len, ',')) len = 0;
+  }
+
 bail:
-    *pEventData = eventData;
-    *pEventDataLen = eventDataLen;
-    *pOutBuf = outBuf;
-    *pOutBufLen = outBufLen;
-    return result;
+  *pEventData = eventData;
+  *pEventDataLen = eventDataLen;
+  *pOutBuf = outBuf;
+  *pOutBufLen = outBufLen;
+  if (cp) {
+    *fmtStr = cp;
+    *fmtLen = len;
+  }
+  return result;
 
 no_room:
-    result = 1;
-    goto bail;
+  result = 1;
+  goto bail;
 }
 
 /**
@@ -751,111 +974,144 @@
  * here.
  */
 LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
-        struct logger_entry *buf,
-        AndroidLogEntry *entry,
-        const EventTagMap *map,
-        char *messageBuf, int messageBufLen)
-{
-    size_t inCount;
-    unsigned int tagIndex;
-    const unsigned char* eventData;
+    struct logger_entry* buf, AndroidLogEntry* entry,
+    const EventTagMap* map __unused, /* only on !__ANDROID__ */
+    char* messageBuf, int messageBufLen) {
+  size_t inCount;
+  uint32_t tagIndex;
+  const unsigned char* eventData;
 
-    entry->tv_sec = buf->sec;
-    entry->tv_nsec = buf->nsec;
-    entry->priority = ANDROID_LOG_INFO;
-    entry->uid = -1;
-    entry->pid = buf->pid;
-    entry->tid = buf->tid;
+  entry->message = NULL;
+  entry->messageLen = 0;
 
-    /*
-     * Pull the tag out, fill in some additional details based on incoming
-     * buffer version (v3 adds lid, v4 adds uid).
-     */
-    eventData = (const unsigned char*) buf->msg;
-    struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
-    if (buf2->hdr_size) {
-        eventData = ((unsigned char *)buf2) + buf2->hdr_size;
-        if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
-                (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
-            entry->priority = ANDROID_LOG_WARN;
-        }
-        if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
-            entry->uid = ((struct logger_entry_v4 *)buf)->uid;
-        }
+  entry->tv_sec = buf->sec;
+  entry->tv_nsec = buf->nsec;
+  entry->priority = ANDROID_LOG_INFO;
+  entry->uid = -1;
+  entry->pid = buf->pid;
+  entry->tid = buf->tid;
+
+  /*
+   * Pull the tag out, fill in some additional details based on incoming
+   * buffer version (v3 adds lid, v4 adds uid).
+   */
+  eventData = (const unsigned char*)buf->msg;
+  struct logger_entry_v2* buf2 = (struct logger_entry_v2*)buf;
+  if (buf2->hdr_size) {
+    if ((buf2->hdr_size < sizeof(((struct log_msg*)NULL)->entry_v1)) ||
+        (buf2->hdr_size > sizeof(((struct log_msg*)NULL)->entry))) {
+      fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
+      return -1;
     }
-    inCount = buf->len;
-    if (inCount < 4)
-        return -1;
-    tagIndex = get4LE(eventData);
-    eventData += 4;
-    inCount -= 4;
-
-    if (map != NULL) {
-        entry->tag = android_lookupEventTag(map, tagIndex);
-    } else {
-        entry->tag = NULL;
+    eventData = ((unsigned char*)buf2) + buf2->hdr_size;
+    if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
+        (((struct logger_entry_v3*)buf)->lid == LOG_ID_SECURITY)) {
+      entry->priority = ANDROID_LOG_WARN;
     }
-
-    /*
-     * If we don't have a map, or didn't find the tag number in the map,
-     * stuff a generated tag value into the start of the output buffer and
-     * shift the buffer pointers down.
-     */
-    if (entry->tag == NULL) {
-        int tagLen;
-
-        tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
-        entry->tag = messageBuf;
-        messageBuf += tagLen+1;
-        messageBufLen -= tagLen+1;
+    if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
+      entry->uid = ((struct logger_entry_v4*)buf)->uid;
     }
+  }
+  inCount = buf->len;
+  if (inCount < 4) return -1;
+  tagIndex = get4LE(eventData);
+  eventData += 4;
+  inCount -= 4;
 
-    /*
-     * Format the event log data into the buffer.
-     */
-    char* outBuf = messageBuf;
-    size_t outRemaining = messageBufLen-1;      /* leave one for nul byte */
-    int result;
+  entry->tagLen = 0;
+  entry->tag = NULL;
+#ifdef __ANDROID__
+  if (map != NULL) {
+    entry->tag = android_lookupEventTag_len(map, &entry->tagLen, tagIndex);
+  }
+#endif
+
+  /*
+   * If we don't have a map, or didn't find the tag number in the map,
+   * stuff a generated tag value into the start of the output buffer and
+   * shift the buffer pointers down.
+   */
+  if (entry->tag == NULL) {
+    size_t tagLen;
+
+    tagLen = snprintf(messageBuf, messageBufLen, "[%" PRIu32 "]", tagIndex);
+    if (tagLen >= (size_t)messageBufLen) {
+      tagLen = messageBufLen - 1;
+    }
+    entry->tag = messageBuf;
+    entry->tagLen = tagLen;
+    messageBuf += tagLen + 1;
+    messageBufLen -= tagLen + 1;
+  }
+
+  /*
+   * Format the event log data into the buffer.
+   */
+  const char* fmtStr = NULL;
+  size_t fmtLen = 0;
+#ifdef __ANDROID__
+  if (descriptive_output && map) {
+    fmtStr = android_lookupEventFormat_len(map, &fmtLen, tagIndex);
+  }
+#endif
+
+  char* outBuf = messageBuf;
+  size_t outRemaining = messageBufLen - 1; /* leave one for nul byte */
+  int result = 0;
+
+  if ((inCount > 0) || fmtLen) {
     result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
-                &outRemaining);
-    if (result < 0) {
-        fprintf(stderr, "Binary log entry conversion failed\n");
-        return -1;
-    } else if (result == 1) {
-        if (outBuf > messageBuf) {
-            /* leave an indicator */
-            *(outBuf-1) = '!';
-        } else {
-            /* no room to output anything at all */
-            *outBuf++ = '!';
-            outRemaining--;
-        }
-        /* pretend we ate all the data */
-        inCount = 0;
+                                          &outRemaining, &fmtStr, &fmtLen);
+  }
+  if ((result == 1) && fmtStr) {
+    /* We overflowed :-(, let's repaint the line w/o format dressings */
+    eventData = (const unsigned char*)buf->msg;
+    if (buf2->hdr_size) {
+      eventData = ((unsigned char*)buf2) + buf2->hdr_size;
     }
-
-    /* eat the silly terminating '\n' */
-    if (inCount == 1 && *eventData == '\n') {
-        eventData++;
-        inCount--;
+    eventData += 4;
+    outBuf = messageBuf;
+    outRemaining = messageBufLen - 1;
+    result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
+                                          &outRemaining, NULL, NULL);
+  }
+  if (result < 0) {
+    fprintf(stderr, "Binary log entry conversion failed\n");
+  }
+  if (result) {
+    if (!outRemaining) {
+      /* make space to leave an indicator */
+      --outBuf;
+      ++outRemaining;
     }
+    *outBuf++ = (result < 0) ? '!' : '^'; /* Error or Truncation? */
+    outRemaining--;
+    /* pretend we ate all the data to prevent log stutter */
+    inCount = 0;
+    if (result > 0) result = 0;
+  }
 
-    if (inCount != 0) {
-        fprintf(stderr,
-            "Warning: leftover binary log data (%zu bytes)\n", inCount);
-    }
+  /* eat the silly terminating '\n' */
+  if (inCount == 1 && *eventData == '\n') {
+    eventData++;
+    inCount--;
+  }
 
-    /*
-     * Terminate the buffer.  The NUL byte does not count as part of
-     * entry->messageLen.
-     */
-    *outBuf = '\0';
-    entry->messageLen = outBuf - messageBuf;
-    assert(entry->messageLen == (messageBufLen-1) - outRemaining);
+  if (inCount != 0) {
+    fprintf(stderr, "Warning: leftover binary log data (%zu bytes)\n", inCount);
+  }
 
-    entry->message = messageBuf;
+  /*
+   * Terminate the buffer.  The NUL byte does not count as part of
+   * entry->messageLen.
+   */
+  *outBuf = '\0';
+  entry->messageLen = outBuf - messageBuf;
+  assert(entry->messageLen == (messageBufLen - 1) - outRemaining);
 
-    return 0;
+  entry->message = messageBuf;
+
+  return result;
 }
 
 /*
@@ -870,388 +1126,379 @@
  * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
  * propagate globally.
  */
-LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
-{
-    const char *cur = src;
-    const char first_char = *cur++;
-    static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
-    int32_t mask, to_ignore_mask;
-    size_t num_to_read;
-    uint32_t utf32;
+LIBLOG_WEAK ssize_t utf8_character_length(const char* src, size_t len) {
+  const char* cur = src;
+  const char first_char = *cur++;
+  static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
+  int32_t mask, to_ignore_mask;
+  size_t num_to_read;
+  uint32_t utf32;
 
-    if ((first_char & 0x80) == 0) { /* ASCII */
-        return first_char ? 1 : -1;
-    }
+  if ((first_char & 0x80) == 0) { /* ASCII */
+    return first_char ? 1 : -1;
+  }
 
-    /*
-     * (UTF-8's character must not be like 10xxxxxx,
-     *  but 110xxxxx, 1110xxxx, ... or 1111110x)
-     */
-    if ((first_char & 0x40) == 0) {
-        return -1;
-    }
+  /*
+   * (UTF-8's character must not be like 10xxxxxx,
+   *  but 110xxxxx, 1110xxxx, ... or 1111110x)
+   */
+  if ((first_char & 0x40) == 0) {
+    return -1;
+  }
 
-    for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
-         num_to_read < 5 && (first_char & mask);
-         num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
-        if (num_to_read > len) {
-            return -1;
-        }
-        if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
-            return -1;
-        }
-        utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
+  for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
+       num_to_read < 5 && (first_char & mask);
+       num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
+    if (num_to_read > len) {
+      return -1;
     }
-    /* "first_char" must be (110xxxxx - 11110xxx) */
-    if (num_to_read >= 5) {
-        return -1;
+    if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
+      return -1;
     }
-    to_ignore_mask |= mask;
-    utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
-    if (utf32 > kUnicodeMaxCodepoint) {
-        return -1;
-    }
-    return num_to_read;
+    utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
+  }
+  /* "first_char" must be (110xxxxx - 11110xxx) */
+  if (num_to_read >= 5) {
+    return -1;
+  }
+  to_ignore_mask |= mask;
+  utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
+  if (utf32 > kUnicodeMaxCodepoint) {
+    return -1;
+  }
+  return num_to_read;
 }
 
 /*
  * Convert to printable from message to p buffer, return string length. If p is
  * NULL, do not copy, but still return the expected string length.
  */
-static size_t convertPrintable(char *p, const char *message, size_t messageLen)
-{
-    char *begin = p;
-    bool print = p != NULL;
+static size_t convertPrintable(char* p, const char* message, size_t messageLen) {
+  char* begin = p;
+  bool print = p != NULL;
 
-    while (messageLen) {
-        char buf[6];
-        ssize_t len = sizeof(buf) - 1;
-        if ((size_t)len > messageLen) {
-            len = messageLen;
+  while (messageLen) {
+    char buf[6];
+    ssize_t len = sizeof(buf) - 1;
+    if ((size_t)len > messageLen) {
+      len = messageLen;
+    }
+    len = utf8_character_length(message, len);
+
+    if (len < 0) {
+      snprintf(buf, sizeof(buf),
+               ((messageLen > 1) && isdigit(message[1])) ? "\\%03o" : "\\%o",
+               *message & 0377);
+      len = 1;
+    } else {
+      buf[0] = '\0';
+      if (len == 1) {
+        if (*message == '\a') {
+          strcpy(buf, "\\a");
+        } else if (*message == '\b') {
+          strcpy(buf, "\\b");
+        } else if (*message == '\t') {
+          strcpy(buf, "\t"); /* Do not escape tabs */
+        } else if (*message == '\v') {
+          strcpy(buf, "\\v");
+        } else if (*message == '\f') {
+          strcpy(buf, "\\f");
+        } else if (*message == '\r') {
+          strcpy(buf, "\\r");
+        } else if (*message == '\\') {
+          strcpy(buf, "\\\\");
+        } else if ((*message < ' ') || (*message & 0x80)) {
+          snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
         }
-        len = utf8_character_length(message, len);
+      }
+      if (!buf[0]) {
+        strncpy(buf, message, len);
+        buf[len] = '\0';
+      }
+    }
+    if (print) {
+      strcpy(p, buf);
+    }
+    p += strlen(buf);
+    message += len;
+    messageLen -= len;
+  }
+  return p - begin;
+}
 
-        if (len < 0) {
-            snprintf(buf, sizeof(buf),
-                     ((messageLen > 1) && isdigit(message[1]))
-                         ? "\\%03o"
-                         : "\\%o",
-                     *message & 0377);
-            len = 1;
+static char* readSeconds(char* e, struct timespec* t) {
+  unsigned long multiplier;
+  char* p;
+  t->tv_sec = strtoul(e, &p, 10);
+  if (*p != '.') {
+    return NULL;
+  }
+  t->tv_nsec = 0;
+  multiplier = NS_PER_SEC;
+  while (isdigit(*++p) && (multiplier /= 10)) {
+    t->tv_nsec += (*p - '0') * multiplier;
+  }
+  return p;
+}
+
+static struct timespec* sumTimespec(struct timespec* left,
+                                    struct timespec* right) {
+  left->tv_nsec += right->tv_nsec;
+  left->tv_sec += right->tv_sec;
+  if (left->tv_nsec >= (long)NS_PER_SEC) {
+    left->tv_nsec -= NS_PER_SEC;
+    left->tv_sec += 1;
+  }
+  return left;
+}
+
+static struct timespec* subTimespec(struct timespec* result,
+                                    struct timespec* left,
+                                    struct timespec* right) {
+  result->tv_nsec = left->tv_nsec - right->tv_nsec;
+  result->tv_sec = left->tv_sec - right->tv_sec;
+  if (result->tv_nsec < 0) {
+    result->tv_nsec += NS_PER_SEC;
+    result->tv_sec -= 1;
+  }
+  return result;
+}
+
+static long long nsecTimespec(struct timespec* now) {
+  return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
+}
+
+#ifdef __ANDROID__
+static void convertMonotonic(struct timespec* result,
+                             const AndroidLogEntry* entry) {
+  struct listnode* node;
+  struct conversionList {
+    struct listnode node; /* first */
+    struct timespec time;
+    struct timespec convert;
+  } * list, *next;
+  struct timespec time, convert;
+
+  /* If we do not have a conversion list, build one up */
+  if (list_empty(&convertHead)) {
+    bool suspended_pending = false;
+    struct timespec suspended_monotonic = { 0, 0 };
+    struct timespec suspended_diff = { 0, 0 };
+
+    /*
+     * Read dmesg for _some_ synchronization markers and insert
+     * Anything in the Android Logger before the dmesg logging span will
+     * be highly suspect regarding the monotonic time calculations.
+     */
+    FILE* p = popen("/system/bin/dmesg", "re");
+    if (p) {
+      char* line = NULL;
+      size_t len = 0;
+      while (getline(&line, &len, p) > 0) {
+        static const char suspend[] = "PM: suspend entry ";
+        static const char resume[] = "PM: suspend exit ";
+        static const char healthd[] = "healthd";
+        static const char battery[] = ": battery ";
+        static const char suspended[] = "Suspended for ";
+        struct timespec monotonic;
+        struct tm tm;
+        char *cp, *e = line;
+        bool add_entry = true;
+
+        if (*e == '<') {
+          while (*e && (*e != '>')) {
+            ++e;
+          }
+          if (*e != '>') {
+            continue;
+          }
+        }
+        if (*e != '[') {
+          continue;
+        }
+        while (*++e == ' ') {
+          ;
+        }
+        e = readSeconds(e, &monotonic);
+        if (!e || (*e != ']')) {
+          continue;
+        }
+
+        if ((e = strstr(e, suspend))) {
+          e += sizeof(suspend) - 1;
+        } else if ((e = strstr(line, resume))) {
+          e += sizeof(resume) - 1;
+        } else if (((e = strstr(line, healthd))) &&
+                   ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
+          /* NB: healthd is roughly 150us late, worth the price to
+           * deal with ntp-induced or hardware clock drift. */
+          e += sizeof(battery) - 1;
+        } else if ((e = strstr(line, suspended))) {
+          e += sizeof(suspended) - 1;
+          e = readSeconds(e, &time);
+          if (!e) {
+            continue;
+          }
+          add_entry = false;
+          suspended_pending = true;
+          suspended_monotonic = monotonic;
+          suspended_diff = time;
         } else {
-            buf[0] = '\0';
-            if (len == 1) {
-                if (*message == '\a') {
-                    strcpy(buf, "\\a");
-                } else if (*message == '\b') {
-                    strcpy(buf, "\\b");
-                } else if (*message == '\t') {
-                    strcpy(buf, "\t"); // Do not escape tabs
-                } else if (*message == '\v') {
-                    strcpy(buf, "\\v");
-                } else if (*message == '\f') {
-                    strcpy(buf, "\\f");
-                } else if (*message == '\r') {
-                    strcpy(buf, "\\r");
-                } else if (*message == '\\') {
-                    strcpy(buf, "\\\\");
-                } else if ((*message < ' ') || (*message & 0x80)) {
-                    snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
-                }
-            }
-            if (!buf[0]) {
-                strncpy(buf, message, len);
-                buf[len] = '\0';
-            }
+          continue;
         }
-        if (print) {
-            strcpy(p, buf);
+        if (add_entry) {
+          /* look for "????-??-?? ??:??:??.????????? UTC" */
+          cp = strstr(e, " UTC");
+          if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
+            continue;
+          }
+          e = cp - 29;
+          cp = readSeconds(cp - 10, &time);
+          if (!cp) {
+            continue;
+          }
+          cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
+          if (!cp) {
+            continue;
+          }
+          cp = getenv(tz);
+          if (cp) {
+            cp = strdup(cp);
+          }
+          setenv(tz, utc, 1);
+          time.tv_sec = mktime(&tm);
+          if (cp) {
+            setenv(tz, cp, 1);
+            free(cp);
+          } else {
+            unsetenv(tz);
+          }
+          list = calloc(1, sizeof(struct conversionList));
+          list_init(&list->node);
+          list->time = time;
+          subTimespec(&list->convert, &time, &monotonic);
+          list_add_tail(&convertHead, &list->node);
         }
-        p += strlen(buf);
-        message += len;
-        messageLen -= len;
-    }
-    return p - begin;
-}
-
-static char *readSeconds(char *e, struct timespec *t)
-{
-    unsigned long multiplier;
-    char *p;
-    t->tv_sec = strtoul(e, &p, 10);
-    if (*p != '.') {
-        return NULL;
-    }
-    t->tv_nsec = 0;
-    multiplier = NS_PER_SEC;
-    while (isdigit(*++p) && (multiplier /= 10)) {
-        t->tv_nsec += (*p - '0') * multiplier;
-    }
-    return p;
-}
-
-static struct timespec *sumTimespec(struct timespec *left,
-                                    struct timespec *right)
-{
-    left->tv_nsec += right->tv_nsec;
-    left->tv_sec += right->tv_sec;
-    if (left->tv_nsec >= (long)NS_PER_SEC) {
-        left->tv_nsec -= NS_PER_SEC;
-        left->tv_sec += 1;
-    }
-    return left;
-}
-
-static struct timespec *subTimespec(struct timespec *result,
-                                    struct timespec *left,
-                                    struct timespec *right)
-{
-    result->tv_nsec = left->tv_nsec - right->tv_nsec;
-    result->tv_sec = left->tv_sec - right->tv_sec;
-    if (result->tv_nsec < 0) {
-        result->tv_nsec += NS_PER_SEC;
-        result->tv_sec -= 1;
-    }
-    return result;
-}
-
-static long long nsecTimespec(struct timespec *now)
-{
-    return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
-}
-
-static void convertMonotonic(struct timespec *result,
-                             const AndroidLogEntry *entry)
-{
-    struct listnode *node;
-    struct conversionList {
-        struct listnode node; /* first */
-        struct timespec time;
-        struct timespec convert;
-    } *list, *next;
-    struct timespec time, convert;
-
-    /* If we do not have a conversion list, build one up */
-    if (list_empty(&convertHead)) {
-        bool suspended_pending = false;
-        struct timespec suspended_monotonic = { 0, 0 };
-        struct timespec suspended_diff = { 0, 0 };
-
-        /*
-         * Read dmesg for _some_ synchronization markers and insert
-         * Anything in the Android Logger before the dmesg logging span will
-         * be highly suspect regarding the monotonic time calculations.
-         */
-        FILE *p = popen("/system/bin/dmesg", "re");
-        if (p) {
-            char *line = NULL;
-            size_t len = 0;
-            while (getline(&line, &len, p) > 0) {
-                static const char suspend[] = "PM: suspend entry ";
-                static const char resume[] = "PM: suspend exit ";
-                static const char healthd[] = "healthd";
-                static const char battery[] = ": battery ";
-                static const char suspended[] = "Suspended for ";
-                struct timespec monotonic;
-                struct tm tm;
-                char *cp, *e = line;
-                bool add_entry = true;
-
-                if (*e == '<') {
-                    while (*e && (*e != '>')) {
-                        ++e;
-                    }
-                    if (*e != '>') {
-                        continue;
-                    }
-                }
-                if (*e != '[') {
-                    continue;
-                }
-                while (*++e == ' ') {
-                    ;
-                }
-                e = readSeconds(e, &monotonic);
-                if (!e || (*e != ']')) {
-                    continue;
-                }
-
-                if ((e = strstr(e, suspend))) {
-                    e += sizeof(suspend) - 1;
-                } else if ((e = strstr(line, resume))) {
-                    e += sizeof(resume) - 1;
-                } else if (((e = strstr(line, healthd)))
-                        && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
-                    /* NB: healthd is roughly 150us late, worth the price to
-                     * deal with ntp-induced or hardware clock drift. */
-                    e += sizeof(battery) - 1;
-                } else if ((e = strstr(line, suspended))) {
-                    e += sizeof(suspended) - 1;
-                    e = readSeconds(e, &time);
-                    if (!e) {
-                        continue;
-                    }
-                    add_entry = false;
-                    suspended_pending = true;
-                    suspended_monotonic = monotonic;
-                    suspended_diff = time;
-                } else {
-                    continue;
-                }
-                if (add_entry) {
-                    /* look for "????-??-?? ??:??:??.????????? UTC" */
-                    cp = strstr(e, " UTC");
-                    if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
-                        continue;
-                    }
-                    e = cp - 29;
-                    cp = readSeconds(cp - 10, &time);
-                    if (!cp) {
-                        continue;
-                    }
-                    cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
-                    if (!cp) {
-                        continue;
-                    }
-                    cp = getenv(tz);
-                    if (cp) {
-                        cp = strdup(cp);
-                    }
-                    setenv(tz, utc, 1);
-                    time.tv_sec = mktime(&tm);
-                    if (cp) {
-                        setenv(tz, cp, 1);
-                        free(cp);
-                    } else {
-                        unsetenv(tz);
-                    }
-                    list = calloc(1, sizeof(struct conversionList));
-                    list_init(&list->node);
-                    list->time = time;
-                    subTimespec(&list->convert, &time, &monotonic);
-                    list_add_tail(&convertHead, &list->node);
-                }
-                if (suspended_pending && !list_empty(&convertHead)) {
-                    list = node_to_item(list_tail(&convertHead),
-                                        struct conversionList, node);
-                    if (subTimespec(&time,
-                                    subTimespec(&time,
-                                                &list->time,
-                                                &list->convert),
-                                    &suspended_monotonic)->tv_sec > 0) {
-                        /* resume, what is convert factor before? */
-                        subTimespec(&convert, &list->convert, &suspended_diff);
-                    } else {
-                        /* suspend */
-                        convert = list->convert;
-                    }
-                    time = suspended_monotonic;
-                    sumTimespec(&time, &convert);
-                    /* breakpoint just before sleep */
-                    list = calloc(1, sizeof(struct conversionList));
-                    list_init(&list->node);
-                    list->time = time;
-                    list->convert = convert;
-                    list_add_tail(&convertHead, &list->node);
-                    /* breakpoint just after sleep */
-                    list = calloc(1, sizeof(struct conversionList));
-                    list_init(&list->node);
-                    list->time = time;
-                    sumTimespec(&list->time, &suspended_diff);
-                    list->convert = convert;
-                    sumTimespec(&list->convert, &suspended_diff);
-                    list_add_tail(&convertHead, &list->node);
-                    suspended_pending = false;
-                }
-            }
-            pclose(p);
-        }
-        /* last entry is our current time conversion */
-        list = calloc(1, sizeof(struct conversionList));
-        list_init(&list->node);
-        clock_gettime(CLOCK_REALTIME, &list->time);
-        clock_gettime(CLOCK_MONOTONIC, &convert);
-        clock_gettime(CLOCK_MONOTONIC, &time);
-        /* Correct for instant clock_gettime latency (syscall or ~30ns) */
-        subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
-        /* Calculate conversion factor */
-        subTimespec(&list->convert, &list->time, &time);
-        list_add_tail(&convertHead, &list->node);
-        if (suspended_pending) {
-            /* manufacture a suspend @ point before */
+        if (suspended_pending && !list_empty(&convertHead)) {
+          list = node_to_item(list_tail(&convertHead), struct conversionList,
+                              node);
+          if (subTimespec(&time, subTimespec(&time, &list->time, &list->convert),
+                          &suspended_monotonic)
+                  ->tv_sec > 0) {
+            /* resume, what is convert factor before? */
             subTimespec(&convert, &list->convert, &suspended_diff);
-            time = suspended_monotonic;
-            sumTimespec(&time, &convert);
-            /* breakpoint just after sleep */
-            list = calloc(1, sizeof(struct conversionList));
-            list_init(&list->node);
-            list->time = time;
-            sumTimespec(&list->time, &suspended_diff);
-            list->convert = convert;
-            sumTimespec(&list->convert, &suspended_diff);
-            list_add_head(&convertHead, &list->node);
-            /* breakpoint just before sleep */
-            list = calloc(1, sizeof(struct conversionList));
-            list_init(&list->node);
-            list->time = time;
-            list->convert = convert;
-            list_add_head(&convertHead, &list->node);
+          } else {
+            /* suspend */
+            convert = list->convert;
+          }
+          time = suspended_monotonic;
+          sumTimespec(&time, &convert);
+          /* breakpoint just before sleep */
+          list = calloc(1, sizeof(struct conversionList));
+          list_init(&list->node);
+          list->time = time;
+          list->convert = convert;
+          list_add_tail(&convertHead, &list->node);
+          /* breakpoint just after sleep */
+          list = calloc(1, sizeof(struct conversionList));
+          list_init(&list->node);
+          list->time = time;
+          sumTimespec(&list->time, &suspended_diff);
+          list->convert = convert;
+          sumTimespec(&list->convert, &suspended_diff);
+          list_add_tail(&convertHead, &list->node);
+          suspended_pending = false;
         }
+      }
+      pclose(p);
     }
+    /* last entry is our current time conversion */
+    list = calloc(1, sizeof(struct conversionList));
+    list_init(&list->node);
+    clock_gettime(CLOCK_REALTIME, &list->time);
+    clock_gettime(CLOCK_MONOTONIC, &convert);
+    clock_gettime(CLOCK_MONOTONIC, &time);
+    /* Correct for instant clock_gettime latency (syscall or ~30ns) */
+    subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
+    /* Calculate conversion factor */
+    subTimespec(&list->convert, &list->time, &time);
+    list_add_tail(&convertHead, &list->node);
+    if (suspended_pending) {
+      /* manufacture a suspend @ point before */
+      subTimespec(&convert, &list->convert, &suspended_diff);
+      time = suspended_monotonic;
+      sumTimespec(&time, &convert);
+      /* breakpoint just after sleep */
+      list = calloc(1, sizeof(struct conversionList));
+      list_init(&list->node);
+      list->time = time;
+      sumTimespec(&list->time, &suspended_diff);
+      list->convert = convert;
+      sumTimespec(&list->convert, &suspended_diff);
+      list_add_head(&convertHead, &list->node);
+      /* breakpoint just before sleep */
+      list = calloc(1, sizeof(struct conversionList));
+      list_init(&list->node);
+      list->time = time;
+      list->convert = convert;
+      list_add_head(&convertHead, &list->node);
+    }
+  }
 
-    /* Find the breakpoint in the conversion list */
-    list = node_to_item(list_head(&convertHead), struct conversionList, node);
-    next = NULL;
-    list_for_each(node, &convertHead) {
-        next = node_to_item(node, struct conversionList, node);
-        if (entry->tv_sec < next->time.tv_sec) {
-            break;
-        } else if (entry->tv_sec == next->time.tv_sec) {
-            if (entry->tv_nsec < next->time.tv_nsec) {
-                break;
-            }
+  /* Find the breakpoint in the conversion list */
+  list = node_to_item(list_head(&convertHead), struct conversionList, node);
+  next = NULL;
+  list_for_each(node, &convertHead) {
+    next = node_to_item(node, struct conversionList, node);
+    if (entry->tv_sec < next->time.tv_sec) {
+      break;
+    } else if (entry->tv_sec == next->time.tv_sec) {
+      if (entry->tv_nsec < next->time.tv_nsec) {
+        break;
+      }
+    }
+    list = next;
+  }
+
+  /* blend time from one breakpoint to the next */
+  convert = list->convert;
+  if (next) {
+    unsigned long long total, run;
+
+    total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
+    time.tv_sec = entry->tv_sec;
+    time.tv_nsec = entry->tv_nsec;
+    run = nsecTimespec(subTimespec(&time, &time, &list->time));
+    if (run < total) {
+      long long crun;
+
+      float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
+      f *= run;
+      f /= total;
+      crun = f;
+      convert.tv_sec += crun / (long long)NS_PER_SEC;
+      if (crun < 0) {
+        convert.tv_nsec -= (-crun) % NS_PER_SEC;
+        if (convert.tv_nsec < 0) {
+          convert.tv_nsec += NS_PER_SEC;
+          convert.tv_sec -= 1;
         }
-        list = next;
-    }
-
-    /* blend time from one breakpoint to the next */
-    convert = list->convert;
-    if (next) {
-        unsigned long long total, run;
-
-        total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
-        time.tv_sec = entry->tv_sec;
-        time.tv_nsec = entry->tv_nsec;
-        run = nsecTimespec(subTimespec(&time, &time, &list->time));
-        if (run < total) {
-            long long crun;
-
-            float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
-            f *= run;
-            f /= total;
-            crun = f;
-            convert.tv_sec += crun / (long long)NS_PER_SEC;
-            if (crun < 0) {
-                convert.tv_nsec -= (-crun) % NS_PER_SEC;
-                if (convert.tv_nsec < 0) {
-                    convert.tv_nsec += NS_PER_SEC;
-                    convert.tv_sec -= 1;
-                }
-            } else {
-                convert.tv_nsec += crun % NS_PER_SEC;
-                if (convert.tv_nsec >= (long)NS_PER_SEC) {
-                    convert.tv_nsec -= NS_PER_SEC;
-                    convert.tv_sec += 1;
-                }
-            }
+      } else {
+        convert.tv_nsec += crun % NS_PER_SEC;
+        if (convert.tv_nsec >= (long)NS_PER_SEC) {
+          convert.tv_nsec -= NS_PER_SEC;
+          convert.tv_sec += 1;
         }
+      }
     }
+  }
 
-    /* Apply the correction factor */
-    result->tv_sec = entry->tv_sec;
-    result->tv_nsec = entry->tv_nsec;
-    subTimespec(result, result, &convert);
+  /* Apply the correction factor */
+  result->tv_sec = entry->tv_sec;
+  result->tv_nsec = entry->tv_nsec;
+  subTimespec(result, result, &convert);
 }
+#endif
 
 /**
  * Formats a log message into a buffer
@@ -1261,289 +1508,295 @@
  * Returns NULL on malloc error
  */
 
-LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
-        AndroidLogFormat *p_format,
-        char *defaultBuffer,
-        size_t defaultBufferSize,
-        const AndroidLogEntry *entry,
-        size_t *p_outLength)
-{
+LIBLOG_ABI_PUBLIC char* android_log_formatLogLine(AndroidLogFormat* p_format,
+                                                  char* defaultBuffer,
+                                                  size_t defaultBufferSize,
+                                                  const AndroidLogEntry* entry,
+                                                  size_t* p_outLength) {
 #if !defined(_WIN32)
-    struct tm tmBuf;
+  struct tm tmBuf;
 #endif
-    struct tm* ptm;
-    char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
-    char prefixBuf[128], suffixBuf[128];
-    char priChar;
-    int prefixSuffixIsHeaderFooter = 0;
-    char *ret;
-    time_t now;
-    unsigned long nsec;
+  struct tm* ptm;
+  /* good margin, 23+nul for msec, 26+nul for usec, 29+nul to nsec */
+  char timeBuf[64];
+  char prefixBuf[128], suffixBuf[128];
+  char priChar;
+  int prefixSuffixIsHeaderFooter = 0;
+  char* ret;
+  time_t now;
+  unsigned long nsec;
 
-    priChar = filterPriToChar(entry->priority);
-    size_t prefixLen = 0, suffixLen = 0;
-    size_t len;
+  priChar = filterPriToChar(entry->priority);
+  size_t prefixLen = 0, suffixLen = 0;
+  size_t len;
 
-    /*
-     * Get the current date/time in pretty form
-     *
-     * It's often useful when examining a log with "less" to jump to
-     * a specific point in the file by searching for the date/time stamp.
-     * For this reason it's very annoying to have regexp meta characters
-     * in the time stamp.  Don't use forward slashes, parenthesis,
-     * brackets, asterisks, or other special chars here.
-     *
-     * The caller may have affected the timezone environment, this is
-     * expected to be sensitive to that.
-     */
-    now = entry->tv_sec;
-    nsec = entry->tv_nsec;
-    if (p_format->monotonic_output) {
-        // prevent convertMonotonic from being called if logd is monotonic
-        if (android_log_clockid() != CLOCK_MONOTONIC) {
-            struct timespec time;
-            convertMonotonic(&time, entry);
-            now = time.tv_sec;
-            nsec = time.tv_nsec;
-        }
+  /*
+   * Get the current date/time in pretty form
+   *
+   * It's often useful when examining a log with "less" to jump to
+   * a specific point in the file by searching for the date/time stamp.
+   * For this reason it's very annoying to have regexp meta characters
+   * in the time stamp.  Don't use forward slashes, parenthesis,
+   * brackets, asterisks, or other special chars here.
+   *
+   * The caller may have affected the timezone environment, this is
+   * expected to be sensitive to that.
+   */
+  now = entry->tv_sec;
+  nsec = entry->tv_nsec;
+#if __ANDROID__
+  if (p_format->monotonic_output) {
+    /* prevent convertMonotonic from being called if logd is monotonic */
+    if (android_log_clockid() != CLOCK_MONOTONIC) {
+      struct timespec time;
+      convertMonotonic(&time, entry);
+      now = time.tv_sec;
+      nsec = time.tv_nsec;
     }
-    if (now < 0) {
-        nsec = NS_PER_SEC - nsec;
-    }
-    if (p_format->epoch_output || p_format->monotonic_output) {
-        ptm = NULL;
-        snprintf(timeBuf, sizeof(timeBuf),
-                 p_format->monotonic_output ? "%6lld" : "%19lld",
-                 (long long)now);
-    } else {
+  }
+#endif
+  if (now < 0) {
+    nsec = NS_PER_SEC - nsec;
+  }
+  if (p_format->epoch_output || p_format->monotonic_output) {
+    ptm = NULL;
+    snprintf(timeBuf, sizeof(timeBuf),
+             p_format->monotonic_output ? "%6lld" : "%19lld", (long long)now);
+  } else {
 #if !defined(_WIN32)
-        ptm = localtime_r(&now, &tmBuf);
+    ptm = localtime_r(&now, &tmBuf);
 #else
-        ptm = localtime(&now);
+    ptm = localtime(&now);
 #endif
-        strftime(timeBuf, sizeof(timeBuf),
-                 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
-                 ptm);
-    }
-    len = strlen(timeBuf);
-    if (p_format->usec_time_output) {
-        len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
-                        ".%06ld", nsec / US_PER_NSEC);
+    strftime(timeBuf, sizeof(timeBuf),
+             &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3], ptm);
+  }
+  len = strlen(timeBuf);
+  if (p_format->nsec_time_output) {
+    len += snprintf(timeBuf + len, sizeof(timeBuf) - len, ".%09ld", nsec);
+  } else if (p_format->usec_time_output) {
+    len += snprintf(timeBuf + len, sizeof(timeBuf) - len, ".%06ld",
+                    nsec / US_PER_NSEC);
+  } else {
+    len += snprintf(timeBuf + len, sizeof(timeBuf) - len, ".%03ld",
+                    nsec / MS_PER_NSEC);
+  }
+  if (p_format->zone_output && ptm) {
+    strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
+  }
+
+  /*
+   * Construct a buffer containing the log header and log message.
+   */
+  if (p_format->colored_output) {
+    prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
+                         colorFromPri(entry->priority));
+    prefixLen = MIN(prefixLen, sizeof(prefixBuf));
+    suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
+    suffixLen = MIN(suffixLen, sizeof(suffixBuf));
+  }
+
+  char uid[16];
+  uid[0] = '\0';
+  if (p_format->uid_output) {
+    if (entry->uid >= 0) {
+/*
+ * This code is Android specific, bionic guarantees that
+ * calls to non-reentrant getpwuid() are thread safe.
+ */
+#if !defined(__MINGW32__)
+#if (FAKE_LOG_DEVICE == 0)
+#ifndef __BIONIC__
+#warning \
+    "This code assumes that getpwuid is thread safe, only true with Bionic!"
+#endif
+#endif
+      struct passwd* pwd = getpwuid(entry->uid);
+      if (pwd && (strlen(pwd->pw_name) <= 5)) {
+        snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
+      } else
+#endif
+      {
+        /* Not worth parsing package list, names all longer than 5 */
+        snprintf(uid, sizeof(uid), "%5d:", entry->uid);
+      }
     } else {
-        len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
-                        ".%03ld", nsec / MS_PER_NSEC);
+      snprintf(uid, sizeof(uid), "      ");
     }
-    if (p_format->zone_output && ptm) {
-        strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
-    }
+  }
 
-    /*
-     * Construct a buffer containing the log header and log message.
-     */
-    if (p_format->colored_output) {
-        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
-                             colorFromPri(entry->priority));
-        prefixLen = MIN(prefixLen, sizeof(prefixBuf));
-        suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
-        suffixLen = MIN(suffixLen, sizeof(suffixBuf));
-    }
+  switch (p_format->format) {
+    case FORMAT_TAG:
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%c/%-8.*s: ", priChar, (int)entry->tagLen, entry->tag);
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+    case FORMAT_PROCESS:
+      len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
+                     "  (%.*s)\n", (int)entry->tagLen, entry->tag);
+      suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%c(%s%5d) ", priChar, uid, entry->pid);
+      break;
+    case FORMAT_THREAD:
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+    case FORMAT_RAW:
+      prefixBuf[prefixLen] = 0;
+      len = 0;
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+    case FORMAT_TIME:
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%s %c/%-8.*s(%s%5d): ", timeBuf, priChar,
+                     (int)entry->tagLen, entry->tag, uid, entry->pid);
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+    case FORMAT_THREADTIME:
+      ret = strchr(uid, ':');
+      if (ret) {
+        *ret = ' ';
+      }
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%s %s%5d %5d %c %-8.*s: ", timeBuf, uid, entry->pid,
+                     entry->tid, priChar, (int)entry->tagLen, entry->tag);
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+    case FORMAT_LONG:
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "[ %s %s%5d:%5d %c/%-8.*s ]\n", timeBuf, uid, entry->pid,
+                     entry->tid, priChar, (int)entry->tagLen, entry->tag);
+      strcpy(suffixBuf + suffixLen, "\n\n");
+      suffixLen += 2;
+      prefixSuffixIsHeaderFooter = 1;
+      break;
+    case FORMAT_BRIEF:
+    default:
+      len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                     "%c/%-8.*s(%s%5d): ", priChar, (int)entry->tagLen,
+                     entry->tag, uid, entry->pid);
+      strcpy(suffixBuf + suffixLen, "\n");
+      ++suffixLen;
+      break;
+  }
 
-    char uid[16];
-    uid[0] = '\0';
-    if (p_format->uid_output) {
-        if (entry->uid >= 0) {
-            const struct android_id_info *info = android_ids;
-            size_t i;
+  /* snprintf has a weird return value.   It returns what would have been
+   * written given a large enough buffer.  In the case that the prefix is
+   * longer then our buffer(128), it messes up the calculations below
+   * possibly causing heap corruption.  To avoid this we double check and
+   * set the length at the maximum (size minus null byte)
+   */
+  prefixLen += len;
+  if (prefixLen >= sizeof(prefixBuf)) {
+    prefixLen = sizeof(prefixBuf) - 1;
+    prefixBuf[sizeof(prefixBuf) - 1] = '\0';
+  }
+  if (suffixLen >= sizeof(suffixBuf)) {
+    suffixLen = sizeof(suffixBuf) - 1;
+    suffixBuf[sizeof(suffixBuf) - 2] = '\n';
+    suffixBuf[sizeof(suffixBuf) - 1] = '\0';
+  }
 
-            for (i = 0; i < android_id_count; ++i) {
-                if (info->aid == (unsigned int)entry->uid) {
-                    break;
-                }
-                ++info;
-            }
-            if ((i < android_id_count) && (strlen(info->name) <= 5)) {
-                 snprintf(uid, sizeof(uid), "%5s:", info->name);
-            } else {
-                 // Not worth parsing package list, names all longer than 5
-                 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
-            }
-        } else {
-            snprintf(uid, sizeof(uid), "      ");
-        }
-    }
+  /* the following code is tragically unreadable */
 
-    switch (p_format->format) {
-        case FORMAT_TAG:
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%c/%-8s: ", priChar, entry->tag);
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-        case FORMAT_PROCESS:
-            len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
-                "  (%s)\n", entry->tag);
-            suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%c(%s%5d) ", priChar, uid, entry->pid);
-            break;
-        case FORMAT_THREAD:
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-        case FORMAT_RAW:
-            prefixBuf[prefixLen] = 0;
-            len = 0;
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-        case FORMAT_TIME:
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%s %c/%-8s(%s%5d): ", timeBuf, priChar, entry->tag,
-                uid, entry->pid);
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-        case FORMAT_THREADTIME:
-            ret = strchr(uid, ':');
-            if (ret) {
-                *ret = ' ';
-            }
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%s %s%5d %5d %c %-8s: ", timeBuf,
-                uid, entry->pid, entry->tid, priChar, entry->tag);
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-        case FORMAT_LONG:
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "[ %s %s%5d:%5d %c/%-8s ]\n",
-                timeBuf, uid, entry->pid, entry->tid, priChar, entry->tag);
-            strcpy(suffixBuf + suffixLen, "\n\n");
-            suffixLen += 2;
-            prefixSuffixIsHeaderFooter = 1;
-            break;
-        case FORMAT_BRIEF:
-        default:
-            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
-                "%c/%-8s(%s%5d): ", priChar, entry->tag, uid, entry->pid);
-            strcpy(suffixBuf + suffixLen, "\n");
-            ++suffixLen;
-            break;
-    }
+  size_t numLines;
+  char* p;
+  size_t bufferSize;
+  const char* pm;
 
-    /* snprintf has a weird return value.   It returns what would have been
-     * written given a large enough buffer.  In the case that the prefix is
-     * longer then our buffer(128), it messes up the calculations below
-     * possibly causing heap corruption.  To avoid this we double check and
-     * set the length at the maximum (size minus null byte)
-     */
-    prefixLen += len;
-    if (prefixLen >= sizeof(prefixBuf)) {
-        prefixLen = sizeof(prefixBuf) - 1;
-        prefixBuf[sizeof(prefixBuf) - 1] = '\0';
-    }
-    if (suffixLen >= sizeof(suffixBuf)) {
-        suffixLen = sizeof(suffixBuf) - 1;
-        suffixBuf[sizeof(suffixBuf) - 2] = '\n';
-        suffixBuf[sizeof(suffixBuf) - 1] = '\0';
-    }
-
-    /* the following code is tragically unreadable */
-
-    size_t numLines;
-    char *p;
-    size_t bufferSize;
-    const char *pm;
-
-    if (prefixSuffixIsHeaderFooter) {
-        /* we're just wrapping message with a header/footer */
-        numLines = 1;
-    } else {
-        pm = entry->message;
-        numLines = 0;
-
-        /*
-         * The line-end finding here must match the line-end finding
-         * in for ( ... numLines...) loop below
-         */
-        while (pm < (entry->message + entry->messageLen)) {
-            if (*pm++ == '\n') numLines++;
-        }
-        /* plus one line for anything not newline-terminated at the end */
-        if (pm > entry->message && *(pm-1) != '\n') numLines++;
-    }
-
-    /*
-     * this is an upper bound--newlines in message may be counted
-     * extraneously
-     */
-    bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
-    if (p_format->printable_output) {
-        /* Calculate extra length to convert non-printable to printable */
-        bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
-    } else {
-        bufferSize += entry->messageLen;
-    }
-
-    if (defaultBufferSize >= bufferSize) {
-        ret = defaultBuffer;
-    } else {
-        ret = (char *)malloc(bufferSize);
-
-        if (ret == NULL) {
-            return ret;
-        }
-    }
-
-    ret[0] = '\0';       /* to start strcat off */
-
-    p = ret;
+  if (prefixSuffixIsHeaderFooter) {
+    /* we're just wrapping message with a header/footer */
+    numLines = 1;
+  } else {
     pm = entry->message;
+    numLines = 0;
 
-    if (prefixSuffixIsHeaderFooter) {
-        strcat(p, prefixBuf);
-        p += prefixLen;
-        if (p_format->printable_output) {
-            p += convertPrintable(p, entry->message, entry->messageLen);
-        } else {
-            strncat(p, entry->message, entry->messageLen);
-            p += entry->messageLen;
-        }
-        strcat(p, suffixBuf);
-        p += suffixLen;
+    /*
+     * The line-end finding here must match the line-end finding
+     * in for ( ... numLines...) loop below
+     */
+    while (pm < (entry->message + entry->messageLen)) {
+      if (*pm++ == '\n') numLines++;
+    }
+    /* plus one line for anything not newline-terminated at the end */
+    if (pm > entry->message && *(pm - 1) != '\n') numLines++;
+  }
+
+  /*
+   * this is an upper bound--newlines in message may be counted
+   * extraneously
+   */
+  bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
+  if (p_format->printable_output) {
+    /* Calculate extra length to convert non-printable to printable */
+    bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
+  } else {
+    bufferSize += entry->messageLen;
+  }
+
+  if (defaultBufferSize >= bufferSize) {
+    ret = defaultBuffer;
+  } else {
+    ret = (char*)malloc(bufferSize);
+
+    if (ret == NULL) {
+      return ret;
+    }
+  }
+
+  ret[0] = '\0'; /* to start strcat off */
+
+  p = ret;
+  pm = entry->message;
+
+  if (prefixSuffixIsHeaderFooter) {
+    strcat(p, prefixBuf);
+    p += prefixLen;
+    if (p_format->printable_output) {
+      p += convertPrintable(p, entry->message, entry->messageLen);
     } else {
-        do {
-            const char *lineStart;
-            size_t lineLen;
-            lineStart = pm;
-
-            /* Find the next end-of-line in message */
-            while (pm < (entry->message + entry->messageLen)
-                    && *pm != '\n') pm++;
-            lineLen = pm - lineStart;
-
-            strcat(p, prefixBuf);
-            p += prefixLen;
-            if (p_format->printable_output) {
-                p += convertPrintable(p, lineStart, lineLen);
-            } else {
-                strncat(p, lineStart, lineLen);
-                p += lineLen;
-            }
-            strcat(p, suffixBuf);
-            p += suffixLen;
-
-            if (*pm == '\n') pm++;
-        } while (pm < (entry->message + entry->messageLen));
+      strncat(p, entry->message, entry->messageLen);
+      p += entry->messageLen;
     }
+    strcat(p, suffixBuf);
+    p += suffixLen;
+  } else {
+    do {
+      const char* lineStart;
+      size_t lineLen;
+      lineStart = pm;
 
-    if (p_outLength != NULL) {
-        *p_outLength = p - ret;
-    }
+      /* Find the next end-of-line in message */
+      while (pm < (entry->message + entry->messageLen) && *pm != '\n') pm++;
+      lineLen = pm - lineStart;
 
-    return ret;
+      strcat(p, prefixBuf);
+      p += prefixLen;
+      if (p_format->printable_output) {
+        p += convertPrintable(p, lineStart, lineLen);
+      } else {
+        strncat(p, lineStart, lineLen);
+        p += lineLen;
+      }
+      strcat(p, suffixBuf);
+      p += suffixLen;
+
+      if (*pm == '\n') pm++;
+    } while (pm < (entry->message + entry->messageLen));
+  }
+
+  if (p_outLength != NULL) {
+    *p_outLength = p - ret;
+  }
+
+  return ret;
 }
 
 /**
@@ -1552,42 +1805,38 @@
  * Returns count bytes written
  */
 
-LIBLOG_ABI_PUBLIC int android_log_printLogLine(
-        AndroidLogFormat *p_format,
-        int fd,
-        const AndroidLogEntry *entry)
-{
-    int ret;
-    char defaultBuffer[512];
-    char *outBuffer = NULL;
-    size_t totalLen;
+LIBLOG_ABI_PUBLIC int android_log_printLogLine(AndroidLogFormat* p_format,
+                                               int fd,
+                                               const AndroidLogEntry* entry) {
+  int ret;
+  char defaultBuffer[512];
+  char* outBuffer = NULL;
+  size_t totalLen;
 
-    outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
-            sizeof(defaultBuffer), entry, &totalLen);
+  outBuffer = android_log_formatLogLine(
+      p_format, defaultBuffer, sizeof(defaultBuffer), entry, &totalLen);
 
-    if (!outBuffer)
-        return -1;
+  if (!outBuffer) return -1;
 
-    do {
-        ret = write(fd, outBuffer, totalLen);
-    } while (ret < 0 && errno == EINTR);
+  do {
+    ret = write(fd, outBuffer, totalLen);
+  } while (ret < 0 && errno == EINTR);
 
-    if (ret < 0) {
-        fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
-        ret = 0;
-        goto done;
-    }
+  if (ret < 0) {
+    fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
+    ret = 0;
+    goto done;
+  }
 
-    if (((size_t)ret) < totalLen) {
-        fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
-                (int)totalLen);
-        goto done;
-    }
+  if (((size_t)ret) < totalLen) {
+    fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret, (int)totalLen);
+    goto done;
+  }
 
 done:
-    if (outBuffer != defaultBuffer) {
-        free(outBuffer);
-    }
+  if (outBuffer != defaultBuffer) {
+    free(outBuffer);
+  }
 
-    return ret;
+  return ret;
 }
diff --git a/liblog/pmsg_reader.c b/liblog/pmsg_reader.c
index 2e4fc5d..c3ed8a2 100644
--- a/liblog/pmsg_reader.c
+++ b/liblog/pmsg_reader.c
@@ -29,559 +29,571 @@
 #include "logger.h"
 
 static int pmsgAvailable(log_id_t logId);
-static int pmsgVersion(struct android_log_logger *logger,
-                       struct android_log_transport_context *transp);
-static int pmsgRead(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp,
-                    struct log_msg *log_msg);
-static void pmsgClose(struct android_log_logger_list *logger_list,
-                      struct android_log_transport_context *transp);
-static int pmsgClear(struct android_log_logger *logger,
-                     struct android_log_transport_context *transp);
+static int pmsgVersion(struct android_log_logger* logger,
+                       struct android_log_transport_context* transp);
+static int pmsgRead(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp,
+                    struct log_msg* log_msg);
+static void pmsgClose(struct android_log_logger_list* logger_list,
+                      struct android_log_transport_context* transp);
+static int pmsgClear(struct android_log_logger* logger,
+                     struct android_log_transport_context* transp);
 
 LIBLOG_HIDDEN struct android_log_transport_read pmsgLoggerRead = {
-    .node = { &pmsgLoggerRead.node, &pmsgLoggerRead.node },
-    .name = "pmsg",
-    .available = pmsgAvailable,
-    .version = pmsgVersion,
-    .read = pmsgRead,
-    .poll = NULL,
-    .close = pmsgClose,
-    .clear = pmsgClear,
-    .setSize = NULL,
-    .getSize = NULL,
-    .getReadableSize = NULL,
-    .getPrune = NULL,
-    .setPrune = NULL,
-    .getStats = NULL,
+  .node = { &pmsgLoggerRead.node, &pmsgLoggerRead.node },
+  .name = "pmsg",
+  .available = pmsgAvailable,
+  .version = pmsgVersion,
+  .read = pmsgRead,
+  .poll = NULL,
+  .close = pmsgClose,
+  .clear = pmsgClear,
+  .setSize = NULL,
+  .getSize = NULL,
+  .getReadableSize = NULL,
+  .getPrune = NULL,
+  .setPrune = NULL,
+  .getStats = NULL,
 };
 
-static int pmsgAvailable(log_id_t logId)
-{
-    if (logId > LOG_ID_SECURITY) {
-        return -EINVAL;
-    }
-    if (access("/dev/pmsg0", W_OK) == 0) {
-        return 0;
-    }
-    return -EBADF;
+static int pmsgAvailable(log_id_t logId) {
+  if (logId > LOG_ID_SECURITY) {
+    return -EINVAL;
+  }
+  if (access("/dev/pmsg0", W_OK) == 0) {
+    return 0;
+  }
+  return -EBADF;
 }
 
 /* Determine the credentials of the caller */
-static bool uid_has_log_permission(uid_t uid)
-{
-    return (uid == AID_SYSTEM) || (uid == AID_LOG) || (uid == AID_ROOT);
+static bool uid_has_log_permission(uid_t uid) {
+  return (uid == AID_SYSTEM) || (uid == AID_LOG) || (uid == AID_ROOT) ||
+         (uid == AID_LOGD);
 }
 
-static uid_t get_best_effective_uid()
-{
-    uid_t euid;
-    uid_t uid;
-    gid_t gid;
-    ssize_t i;
-    static uid_t last_uid = (uid_t) -1;
+static uid_t get_best_effective_uid() {
+  uid_t euid;
+  uid_t uid;
+  gid_t gid;
+  ssize_t i;
+  static uid_t last_uid = (uid_t)-1;
 
-    if (last_uid != (uid_t) -1) {
-        return last_uid;
-    }
-    uid = __android_log_uid();
-    if (uid_has_log_permission(uid)) {
-        return last_uid = uid;
-    }
-    euid = geteuid();
-    if (uid_has_log_permission(euid)) {
-        return last_uid = euid;
-    }
-    gid = getgid();
-    if (uid_has_log_permission(gid)) {
-        return last_uid = gid;
-    }
-    gid = getegid();
-    if (uid_has_log_permission(gid)) {
-        return last_uid = gid;
-    }
-    i = getgroups((size_t) 0, NULL);
-    if (i > 0) {
-        gid_t list[i];
-
-        getgroups(i, list);
-        while (--i >= 0) {
-            if (uid_has_log_permission(list[i])) {
-                return last_uid = list[i];
-            }
-        }
-    }
+  if (last_uid != (uid_t)-1) {
+    return last_uid;
+  }
+  uid = __android_log_uid();
+  if (uid_has_log_permission(uid)) {
     return last_uid = uid;
+  }
+  euid = geteuid();
+  if (uid_has_log_permission(euid)) {
+    return last_uid = euid;
+  }
+  gid = getgid();
+  if (uid_has_log_permission(gid)) {
+    return last_uid = gid;
+  }
+  gid = getegid();
+  if (uid_has_log_permission(gid)) {
+    return last_uid = gid;
+  }
+  i = getgroups((size_t)0, NULL);
+  if (i > 0) {
+    gid_t list[i];
+
+    getgroups(i, list);
+    while (--i >= 0) {
+      if (uid_has_log_permission(list[i])) {
+        return last_uid = list[i];
+      }
+    }
+  }
+  return last_uid = uid;
 }
 
-static int pmsgClear(struct android_log_logger *logger __unused,
-                     struct android_log_transport_context *transp __unused)
-{
-    if (uid_has_log_permission(get_best_effective_uid())) {
-        return unlink("/sys/fs/pstore/pmsg-ramoops-0");
-    }
-    errno = EPERM;
-    return -1;
+static int pmsgClear(struct android_log_logger* logger __unused,
+                     struct android_log_transport_context* transp __unused) {
+  if (uid_has_log_permission(get_best_effective_uid())) {
+    return unlink("/sys/fs/pstore/pmsg-ramoops-0");
+  }
+  errno = EPERM;
+  return -1;
 }
 
 /*
  * returns the logger version
  */
-static int pmsgVersion(struct android_log_logger *logger __unused,
-                       struct android_log_transport_context *transp __unused)
-{
-    return 4;
+static int pmsgVersion(struct android_log_logger* logger __unused,
+                       struct android_log_transport_context* transp __unused) {
+  return 4;
 }
 
-static int pmsgRead(struct android_log_logger_list *logger_list,
-                    struct android_log_transport_context *transp,
-                    struct log_msg *log_msg)
-{
-    ssize_t ret;
-    off_t current, next;
-    uid_t uid;
-    struct android_log_logger *logger;
-    struct __attribute__((__packed__)) {
-        android_pmsg_log_header_t p;
-        android_log_header_t l;
-    } buf;
-    static uint8_t preread_count;
-    bool is_system;
+static int pmsgRead(struct android_log_logger_list* logger_list,
+                    struct android_log_transport_context* transp,
+                    struct log_msg* log_msg) {
+  ssize_t ret;
+  off_t current, next;
+  uid_t uid;
+  struct android_log_logger* logger;
+  struct __attribute__((__packed__)) {
+    android_pmsg_log_header_t p;
+    android_log_header_t l;
+    uint8_t prio;
+  } buf;
+  static uint8_t preread_count;
+  bool is_system;
 
-    memset(log_msg, 0, sizeof(*log_msg));
+  memset(log_msg, 0, sizeof(*log_msg));
 
-    if (transp->context.fd <= 0) {
-        int fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
+  if (atomic_load(&transp->context.fd) <= 0) {
+    int i, fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
 
-        if (fd < 0) {
-            return -errno;
+    if (fd < 0) {
+      return -errno;
+    }
+    if (fd == 0) { /* Argggg */
+      fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
+      close(0);
+      if (fd < 0) {
+        return -errno;
+      }
+    }
+    i = atomic_exchange(&transp->context.fd, fd);
+    if ((i > 0) && (i != fd)) {
+      close(i);
+    }
+    preread_count = 0;
+  }
+
+  while (1) {
+    int fd;
+
+    if (preread_count < sizeof(buf)) {
+      fd = atomic_load(&transp->context.fd);
+      if (fd <= 0) {
+        return -EBADF;
+      }
+      ret = TEMP_FAILURE_RETRY(
+          read(fd, &buf.p.magic + preread_count, sizeof(buf) - preread_count));
+      if (ret < 0) {
+        return -errno;
+      }
+      preread_count += ret;
+    }
+    if (preread_count != sizeof(buf)) {
+      return preread_count ? -EIO : -EAGAIN;
+    }
+    if ((buf.p.magic != LOGGER_MAGIC) || (buf.p.len <= sizeof(buf)) ||
+        (buf.p.len > (sizeof(buf) + LOGGER_ENTRY_MAX_PAYLOAD)) ||
+        (buf.l.id >= LOG_ID_MAX) || (buf.l.realtime.tv_nsec >= NS_PER_SEC) ||
+        ((buf.l.id != LOG_ID_EVENTS) && (buf.l.id != LOG_ID_SECURITY) &&
+         ((buf.prio == ANDROID_LOG_UNKNOWN) ||
+          (buf.prio == ANDROID_LOG_DEFAULT) ||
+          (buf.prio >= ANDROID_LOG_SILENT)))) {
+      do {
+        memmove(&buf.p.magic, &buf.p.magic + 1, --preread_count);
+      } while (preread_count && (buf.p.magic != LOGGER_MAGIC));
+      continue;
+    }
+    preread_count = 0;
+
+    if ((transp->logMask & (1 << buf.l.id)) &&
+        ((!logger_list->start.tv_sec && !logger_list->start.tv_nsec) ||
+         ((logger_list->start.tv_sec <= buf.l.realtime.tv_sec) &&
+          ((logger_list->start.tv_sec != buf.l.realtime.tv_sec) ||
+           (logger_list->start.tv_nsec <= buf.l.realtime.tv_nsec)))) &&
+        (!logger_list->pid || (logger_list->pid == buf.p.pid))) {
+      uid = get_best_effective_uid();
+      is_system = uid_has_log_permission(uid);
+      if (is_system || (uid == buf.p.uid)) {
+        char* msg = is_system ? log_msg->entry_v4.msg : log_msg->entry_v3.msg;
+        *msg = buf.prio;
+        fd = atomic_load(&transp->context.fd);
+        if (fd <= 0) {
+          return -EBADF;
         }
-        if (fd == 0) { /* Argggg */
-            fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
-            close(0);
-            if (fd < 0) {
-                return -errno;
-            }
+        ret = TEMP_FAILURE_RETRY(
+            read(fd, msg + sizeof(buf.prio), buf.p.len - sizeof(buf)));
+        if (ret < 0) {
+          return -errno;
         }
-        transp->context.fd = fd;
-        preread_count = 0;
+        if (ret != (ssize_t)(buf.p.len - sizeof(buf))) {
+          return -EIO;
+        }
+
+        log_msg->entry_v4.len = buf.p.len - sizeof(buf) + sizeof(buf.prio);
+        log_msg->entry_v4.hdr_size =
+            is_system ? sizeof(log_msg->entry_v4) : sizeof(log_msg->entry_v3);
+        log_msg->entry_v4.pid = buf.p.pid;
+        log_msg->entry_v4.tid = buf.l.tid;
+        log_msg->entry_v4.sec = buf.l.realtime.tv_sec;
+        log_msg->entry_v4.nsec = buf.l.realtime.tv_nsec;
+        log_msg->entry_v4.lid = buf.l.id;
+        if (is_system) {
+          log_msg->entry_v4.uid = buf.p.uid;
+        }
+
+        return ret + sizeof(buf.prio) + log_msg->entry_v4.hdr_size;
+      }
     }
 
-    while(1) {
-        if (preread_count < sizeof(buf)) {
-            ret = TEMP_FAILURE_RETRY(read(transp->context.fd,
-                                          &buf.p.magic + preread_count,
-                                          sizeof(buf) - preread_count));
-            if (ret < 0) {
-                return -errno;
-            }
-            preread_count += ret;
-        }
-        if (preread_count != sizeof(buf)) {
-            return preread_count ? -EIO : -EAGAIN;
-        }
-        if ((buf.p.magic != LOGGER_MAGIC)
-         || (buf.p.len <= sizeof(buf))
-         || (buf.p.len > (sizeof(buf) + LOGGER_ENTRY_MAX_PAYLOAD))
-         || (buf.l.id >= LOG_ID_MAX)
-         || (buf.l.realtime.tv_nsec >= NS_PER_SEC)) {
-            do {
-                memmove(&buf.p.magic, &buf.p.magic + 1, --preread_count);
-            } while (preread_count && (buf.p.magic != LOGGER_MAGIC));
-            continue;
-        }
-        preread_count = 0;
-
-        if ((transp->logMask & (1 << buf.l.id)) &&
-                ((!logger_list->start.tv_sec && !logger_list->start.tv_nsec) ||
-                    ((logger_list->start.tv_sec <= buf.l.realtime.tv_sec) &&
-                        ((logger_list->start.tv_sec != buf.l.realtime.tv_sec) ||
-                            (logger_list->start.tv_nsec <=
-                                buf.l.realtime.tv_nsec)))) &&
-                (!logger_list->pid || (logger_list->pid == buf.p.pid))) {
-            uid = get_best_effective_uid();
-            is_system = uid_has_log_permission(uid);
-            if (is_system || (uid == buf.p.uid)) {
-                ret = TEMP_FAILURE_RETRY(read(transp->context.fd,
-                                          is_system ?
-                                              log_msg->entry_v4.msg :
-                                              log_msg->entry_v3.msg,
-                                          buf.p.len - sizeof(buf)));
-                if (ret < 0) {
-                    return -errno;
-                }
-                if (ret != (ssize_t)(buf.p.len - sizeof(buf))) {
-                    return -EIO;
-                }
-
-                log_msg->entry_v4.len = buf.p.len - sizeof(buf);
-                log_msg->entry_v4.hdr_size = is_system ?
-                    sizeof(log_msg->entry_v4) :
-                    sizeof(log_msg->entry_v3);
-                log_msg->entry_v4.pid = buf.p.pid;
-                log_msg->entry_v4.tid = buf.l.tid;
-                log_msg->entry_v4.sec = buf.l.realtime.tv_sec;
-                log_msg->entry_v4.nsec = buf.l.realtime.tv_nsec;
-                log_msg->entry_v4.lid = buf.l.id;
-                if (is_system) {
-                    log_msg->entry_v4.uid = buf.p.uid;
-                }
-
-                return ret + log_msg->entry_v4.hdr_size;
-            }
-        }
-
-        current = TEMP_FAILURE_RETRY(lseek(transp->context.fd,
-                                           (off_t)0, SEEK_CUR));
-        if (current < 0) {
-            return -errno;
-        }
-        next = TEMP_FAILURE_RETRY(lseek(transp->context.fd,
-                                        (off_t)(buf.p.len - sizeof(buf)),
-                                        SEEK_CUR));
-        if (next < 0) {
-            return -errno;
-        }
-        if ((next - current) != (ssize_t)(buf.p.len - sizeof(buf))) {
-            return -EIO;
-        }
+    fd = atomic_load(&transp->context.fd);
+    if (fd <= 0) {
+      return -EBADF;
     }
+    current = TEMP_FAILURE_RETRY(lseek(fd, (off_t)0, SEEK_CUR));
+    if (current < 0) {
+      return -errno;
+    }
+    fd = atomic_load(&transp->context.fd);
+    if (fd <= 0) {
+      return -EBADF;
+    }
+    next = TEMP_FAILURE_RETRY(
+        lseek(fd, (off_t)(buf.p.len - sizeof(buf)), SEEK_CUR));
+    if (next < 0) {
+      return -errno;
+    }
+    if ((next - current) != (ssize_t)(buf.p.len - sizeof(buf))) {
+      return -EIO;
+    }
+  }
 }
 
-static void pmsgClose(struct android_log_logger_list *logger_list __unused,
-                      struct android_log_transport_context *transp) {
-    if (transp->context.fd > 0) {
-        close (transp->context.fd);
-    }
-    transp->context.fd = 0;
+static void pmsgClose(struct android_log_logger_list* logger_list __unused,
+                      struct android_log_transport_context* transp) {
+  int fd = atomic_exchange(&transp->context.fd, 0);
+  if (fd > 0) {
+    close(fd);
+  }
 }
 
-LIBLOG_ABI_PRIVATE ssize_t __android_log_pmsg_file_read(
-        log_id_t logId,
-        char prio,
-        const char *prefix,
-        __android_log_pmsg_file_read_fn fn, void *arg) {
-    ssize_t ret;
-    struct android_log_logger_list logger_list;
-    struct android_log_transport_context transp;
-    struct content {
-        struct listnode node;
-        union {
-            struct logger_entry_v4 entry;
-            struct logger_entry_v4 entry_v4;
-            struct logger_entry_v3 entry_v3;
-            struct logger_entry_v2 entry_v2;
-            struct logger_entry    entry_v1;
-        };
-    } *content;
-    struct names {
-        struct listnode node;
-        struct listnode content;
-        log_id_t id;
-        char prio;
-        char name[];
-    } *names;
-    struct listnode name_list;
-    struct listnode *node, *n;
-    size_t len, prefix_len;
+LIBLOG_ABI_PRIVATE ssize_t
+__android_log_pmsg_file_read(log_id_t logId, char prio, const char* prefix,
+                             __android_log_pmsg_file_read_fn fn, void* arg) {
+  ssize_t ret;
+  struct android_log_logger_list logger_list;
+  struct android_log_transport_context transp;
+  struct content {
+    struct listnode node;
+    union {
+      struct logger_entry_v4 entry;
+      struct logger_entry_v4 entry_v4;
+      struct logger_entry_v3 entry_v3;
+      struct logger_entry_v2 entry_v2;
+      struct logger_entry entry_v1;
+    };
+  } * content;
+  struct names {
+    struct listnode node;
+    struct listnode content;
+    log_id_t id;
+    char prio;
+    char name[];
+  } * names;
+  struct listnode name_list;
+  struct listnode *node, *n;
+  size_t len, prefix_len;
 
-    if (!fn) {
-        return -EINVAL;
+  if (!fn) {
+    return -EINVAL;
+  }
+
+  /* Add just enough clues in logger_list and transp to make API function */
+  memset(&logger_list, 0, sizeof(logger_list));
+  memset(&transp, 0, sizeof(transp));
+
+  logger_list.mode =
+      ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK | ANDROID_LOG_RDONLY;
+  transp.logMask = (unsigned)-1;
+  if (logId != LOG_ID_ANY) {
+    transp.logMask = (1 << logId);
+  }
+  transp.logMask &=
+      ~((1 << LOG_ID_KERNEL) | (1 << LOG_ID_EVENTS) | (1 << LOG_ID_SECURITY));
+  if (!transp.logMask) {
+    return -EINVAL;
+  }
+
+  /* Initialize name list */
+  list_init(&name_list);
+
+  ret = SSIZE_MAX;
+
+  /* Validate incoming prefix, shift until it contains only 0 or 1 : or / */
+  prefix_len = 0;
+  if (prefix) {
+    const char *prev = NULL, *last = NULL, *cp = prefix;
+    while ((cp = strpbrk(cp, "/:"))) {
+      prev = last;
+      last = cp;
+      cp = cp + 1;
+    }
+    if (prev) {
+      prefix = prev + 1;
+    }
+    prefix_len = strlen(prefix);
+  }
+
+  /* Read the file content */
+  while (pmsgRead(&logger_list, &transp, &transp.logMsg) > 0) {
+    char* cp;
+    size_t hdr_size = transp.logMsg.entry.hdr_size
+                          ? transp.logMsg.entry.hdr_size
+                          : sizeof(transp.logMsg.entry_v1);
+    char* msg = (char*)&transp.logMsg + hdr_size;
+    char* split = NULL;
+
+    if ((hdr_size < sizeof(transp.logMsg.entry_v1)) ||
+        (hdr_size > sizeof(transp.logMsg.entry))) {
+      continue;
+    }
+    /* Check for invalid sequence number */
+    if ((transp.logMsg.entry.nsec % ANDROID_LOG_PMSG_FILE_SEQUENCE) ||
+        ((transp.logMsg.entry.nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
+         ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE)) {
+      continue;
     }
 
-    /* Add just enough clues in logger_list and transp to make API function */
-    memset(&logger_list, 0, sizeof(logger_list));
-    memset(&transp, 0, sizeof(transp));
-
-    logger_list.mode = ANDROID_LOG_PSTORE |
-                       ANDROID_LOG_NONBLOCK |
-                       ANDROID_LOG_RDONLY;
-    transp.logMask = (unsigned)-1;
-    if (logId != LOG_ID_ANY) {
-        transp.logMask = (1 << logId);
+    /* Determine if it has <dirbase>:<filebase> format for tag */
+    len = transp.logMsg.entry.len - sizeof(prio);
+    for (cp = msg + sizeof(prio); *cp && isprint(*cp) && !isspace(*cp) && --len;
+         ++cp) {
+      if (*cp == ':') {
+        if (split) {
+          break;
+        }
+        split = cp;
+      }
     }
-    transp.logMask &= ~((1 << LOG_ID_KERNEL) |
-                        (1 << LOG_ID_EVENTS) |
-                        (1 << LOG_ID_SECURITY));
-    if (!transp.logMask) {
-        return -EINVAL;
+    if (*cp || !split) {
+      continue;
     }
 
-    /* Initialize name list */
-    list_init(&name_list);
-
-    ret = SSIZE_MAX;
-
-    /* Validate incoming prefix, shift until it contains only 0 or 1 : or / */
-    prefix_len = 0;
-    if (prefix) {
-        const char *prev = NULL, *last = NULL, *cp = prefix;
-        while ((cp = strpbrk(cp, "/:"))) {
-            prev = last;
-            last = cp;
-            cp = cp + 1;
-        }
-        if (prev) {
-            prefix = prev + 1;
-        }
-        prefix_len = strlen(prefix);
+    /* Filters */
+    if (prefix_len && strncmp(msg + sizeof(prio), prefix, prefix_len)) {
+      size_t offset;
+      /*
+       *   Allow : to be a synonym for /
+       * Things we do dealing with const char * and do not alloc
+       */
+      split = strchr(prefix, ':');
+      if (split) {
+        continue;
+      }
+      split = strchr(prefix, '/');
+      if (!split) {
+        continue;
+      }
+      offset = split - prefix;
+      if ((msg[offset + sizeof(prio)] != ':') ||
+          strncmp(msg + sizeof(prio), prefix, offset)) {
+        continue;
+      }
+      ++offset;
+      if ((prefix_len > offset) && strncmp(&msg[offset + sizeof(prio)],
+                                           split + 1, prefix_len - offset)) {
+        continue;
+      }
     }
 
-    /* Read the file content */
-    while (pmsgRead(&logger_list, &transp, &transp.logMsg) > 0) {
-        char *cp;
-        size_t hdr_size = transp.logMsg.entry.hdr_size ?
-            transp.logMsg.entry.hdr_size : sizeof(transp.logMsg.entry_v1);
-        char *msg = (char *)&transp.logMsg + hdr_size;
-        char *split = NULL;
-
-        /* Check for invalid sequence number */
-        if ((transp.logMsg.entry.nsec % ANDROID_LOG_PMSG_FILE_SEQUENCE) ||
-                ((transp.logMsg.entry.nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
-                    ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE)) {
-            continue;
-        }
-
-        /* Determine if it has <dirbase>:<filebase> format for tag */
-        len = transp.logMsg.entry.len - sizeof(prio);
-        for (cp = msg + sizeof(prio);
-                *cp && isprint(*cp) && !isspace(*cp) && --len;
-                ++cp) {
-            if (*cp == ':') {
-                if (split) {
-                    break;
-                }
-                split = cp;
-            }
-        }
-        if (*cp || !split) {
-            continue;
-        }
-
-        /* Filters */
-        if (prefix_len && strncmp(msg + sizeof(prio), prefix, prefix_len)) {
-            size_t offset;
-            /*
-             *   Allow : to be a synonym for /
-             * Things we do dealing with const char * and do not alloc
-             */
-            split = strchr(prefix, ':');
-            if (split) {
-                continue;
-            }
-            split = strchr(prefix, '/');
-            if (!split) {
-                continue;
-            }
-            offset = split - prefix;
-            if ((msg[offset + sizeof(prio)] != ':') ||
-                    strncmp(msg + sizeof(prio), prefix, offset)) {
-                continue;
-            }
-            ++offset;
-            if ((prefix_len > offset) &&
-                    strncmp(&msg[offset + sizeof(prio)], split + 1, prefix_len - offset)) {
-                continue;
-            }
-        }
-
-        if ((prio != ANDROID_LOG_ANY) && (*msg < prio)) {
-            continue;
-        }
-
-        /* check if there is an existing entry */
-        list_for_each(node, &name_list) {
-            names = node_to_item(node, struct names, node);
-            if (!strcmp(names->name, msg + sizeof(prio)) &&
-                    (names->id == transp.logMsg.entry.lid) &&
-                    (names->prio == *msg)) {
-                break;
-            }
-        }
-
-        /* We do not have an existing entry, create and add one */
-        if (node == &name_list) {
-            static const char numbers[] = "0123456789";
-            unsigned long long nl;
-
-            len = strlen(msg + sizeof(prio)) + 1;
-            names = calloc(1, sizeof(*names) + len);
-            if (!names) {
-                ret = -ENOMEM;
-                break;
-            }
-            strcpy(names->name, msg + sizeof(prio));
-            names->id = transp.logMsg.entry.lid;
-            names->prio = *msg;
-            list_init(&names->content);
-            /*
-             * Insert in reverse numeric _then_ alpha sorted order as
-             * representative of log rotation:
-             *
-             *   log.10
-             *   klog.10
-             *   . . .
-             *   log.2
-             *   klog.2
-             *   log.1
-             *   klog.1
-             *   log
-             *   klog
-             *
-             * thus when we present the content, we are provided the oldest
-             * first, which when 'refreshed' could spill off the end of the
-             * pmsg FIFO but retaining the newest data for last with best
-             * chances to survive.
-             */
-            nl = 0;
-            cp = strpbrk(names->name, numbers);
-            if (cp) {
-                nl = strtoull(cp, NULL, 10);
-            }
-            list_for_each_reverse(node, &name_list) {
-                struct names *a_name = node_to_item(node, struct names, node);
-                const char *r = a_name->name;
-                int compare = 0;
-
-                unsigned long long nr = 0;
-                cp = strpbrk(r, numbers);
-                if (cp) {
-                    nr = strtoull(cp, NULL, 10);
-                }
-                if (nr != nl) {
-                    compare = (nl > nr) ? 1 : -1;
-                }
-                if (compare == 0) {
-                    compare = strcmp(names->name, r);
-                }
-                if (compare <= 0) {
-                    break;
-                }
-            }
-            list_add_head(node, &names->node);
-        }
-
-        /* Remove any file fragments that match our sequence number */
-        list_for_each_safe(node, n, &names->content) {
-            content = node_to_item(node, struct content, node);
-            if (transp.logMsg.entry.nsec == content->entry.nsec) {
-                list_remove(&content->node);
-                free(content);
-            }
-        }
-
-        /* Add content */
-        content = calloc(1, sizeof(content->node) +
-                hdr_size + transp.logMsg.entry.len);
-        if (!content) {
-            ret = -ENOMEM;
-            break;
-        }
-        memcpy(&content->entry, &transp.logMsg.entry,
-               hdr_size + transp.logMsg.entry.len);
-
-        /* Insert in sequence number sorted order, to ease reconstruction */
-        list_for_each_reverse(node, &names->content) {
-            if ((node_to_item(node, struct content, node))->entry.nsec <
-                    transp.logMsg.entry.nsec) {
-                break;
-            }
-        }
-        list_add_head(node, &content->node);
+    if ((prio != ANDROID_LOG_ANY) && (*msg < prio)) {
+      continue;
     }
-    pmsgClose(&logger_list, &transp);
 
-    /* Progress through all the collected files */
-    list_for_each_safe(node, n, &name_list) {
-        struct listnode *content_node, *m;
-        char *buf;
-        size_t sequence, tag_len;
-
-        names = node_to_item(node, struct names, node);
-
-        /* Construct content into a linear buffer */
-        buf = NULL;
-        len = 0;
-        sequence = 0;
-        tag_len = strlen(names->name) + sizeof(char); /* tag + nul */
-        list_for_each_safe(content_node, m, &names->content) {
-            ssize_t add_len;
-
-            content = node_to_item(content_node, struct content, node);
-            add_len = content->entry.len - tag_len - sizeof(prio);
-            if (add_len <= 0) {
-                list_remove(content_node);
-                free(content);
-                continue;
-            }
-
-            if (!buf) {
-                buf = malloc(sizeof(char));
-                if (!buf) {
-                    ret = -ENOMEM;
-                    list_remove(content_node);
-                    free(content);
-                    continue;
-                }
-                *buf = '\0';
-            }
-
-            /* Missing sequence numbers */
-            while (sequence < content->entry.nsec) {
-                /* plus space for enforced nul */
-                buf = realloc(buf, len + sizeof(char) + sizeof(char));
-                if (!buf) {
-                    break;
-                }
-                buf[len] = '\f'; /* Mark missing content with a form feed */
-                buf[++len] = '\0';
-                sequence += ANDROID_LOG_PMSG_FILE_SEQUENCE;
-            }
-            if (!buf) {
-                ret = -ENOMEM;
-                list_remove(content_node);
-                free(content);
-                continue;
-            }
-            /* plus space for enforced nul */
-            buf = realloc(buf, len + add_len + sizeof(char));
-            if (!buf) {
-                ret = -ENOMEM;
-                list_remove(content_node);
-                free(content);
-                continue;
-            }
-            memcpy(buf + len,
-                   (char *)&content->entry + content->entry.hdr_size +
-                       tag_len + sizeof(prio),
-                   add_len);
-            len += add_len;
-            buf[len] = '\0'; /* enforce trailing hidden nul */
-            sequence = content->entry.nsec + ANDROID_LOG_PMSG_FILE_SEQUENCE;
-
-            list_remove(content_node);
-            free(content);
-        }
-        if (buf) {
-            if (len) {
-                /* Buffer contains enforced trailing nul just beyond length */
-                ssize_t r;
-                *strchr(names->name, ':') = '/'; /* Convert back to filename */
-                r = (*fn)(names->id, names->prio, names->name, buf, len, arg);
-                if ((ret >= 0) && (r > 0)) {
-                    if (ret == SSIZE_MAX) {
-                        ret = r;
-                    } else {
-                        ret += r;
-                    }
-                } else if (r < ret) {
-                    ret = r;
-                }
-            }
-            free(buf);
-        }
-        list_remove(node);
-        free(names);
+    /* check if there is an existing entry */
+    list_for_each(node, &name_list) {
+      names = node_to_item(node, struct names, node);
+      if (!strcmp(names->name, msg + sizeof(prio)) &&
+          (names->id == transp.logMsg.entry.lid) && (names->prio == *msg)) {
+        break;
+      }
     }
-    return (ret == SSIZE_MAX) ? -ENOENT : ret;
+
+    /* We do not have an existing entry, create and add one */
+    if (node == &name_list) {
+      static const char numbers[] = "0123456789";
+      unsigned long long nl;
+
+      len = strlen(msg + sizeof(prio)) + 1;
+      names = calloc(1, sizeof(*names) + len);
+      if (!names) {
+        ret = -ENOMEM;
+        break;
+      }
+      strcpy(names->name, msg + sizeof(prio));
+      names->id = transp.logMsg.entry.lid;
+      names->prio = *msg;
+      list_init(&names->content);
+      /*
+       * Insert in reverse numeric _then_ alpha sorted order as
+       * representative of log rotation:
+       *
+       *   log.10
+       *   klog.10
+       *   . . .
+       *   log.2
+       *   klog.2
+       *   log.1
+       *   klog.1
+       *   log
+       *   klog
+       *
+       * thus when we present the content, we are provided the oldest
+       * first, which when 'refreshed' could spill off the end of the
+       * pmsg FIFO but retaining the newest data for last with best
+       * chances to survive.
+       */
+      nl = 0;
+      cp = strpbrk(names->name, numbers);
+      if (cp) {
+        nl = strtoull(cp, NULL, 10);
+      }
+      list_for_each_reverse(node, &name_list) {
+        struct names* a_name = node_to_item(node, struct names, node);
+        const char* r = a_name->name;
+        int compare = 0;
+
+        unsigned long long nr = 0;
+        cp = strpbrk(r, numbers);
+        if (cp) {
+          nr = strtoull(cp, NULL, 10);
+        }
+        if (nr != nl) {
+          compare = (nl > nr) ? 1 : -1;
+        }
+        if (compare == 0) {
+          compare = strcmp(names->name, r);
+        }
+        if (compare <= 0) {
+          break;
+        }
+      }
+      list_add_head(node, &names->node);
+    }
+
+    /* Remove any file fragments that match our sequence number */
+    list_for_each_safe(node, n, &names->content) {
+      content = node_to_item(node, struct content, node);
+      if (transp.logMsg.entry.nsec == content->entry.nsec) {
+        list_remove(&content->node);
+        free(content);
+      }
+    }
+
+    /* Add content */
+    content =
+        calloc(1, sizeof(content->node) + hdr_size + transp.logMsg.entry.len);
+    if (!content) {
+      ret = -ENOMEM;
+      break;
+    }
+    memcpy(&content->entry, &transp.logMsg.entry,
+           hdr_size + transp.logMsg.entry.len);
+
+    /* Insert in sequence number sorted order, to ease reconstruction */
+    list_for_each_reverse(node, &names->content) {
+      if ((node_to_item(node, struct content, node))->entry.nsec <
+          transp.logMsg.entry.nsec) {
+        break;
+      }
+    }
+    list_add_head(node, &content->node);
+  }
+  pmsgClose(&logger_list, &transp);
+
+  /* Progress through all the collected files */
+  list_for_each_safe(node, n, &name_list) {
+    struct listnode *content_node, *m;
+    char* buf;
+    size_t sequence, tag_len;
+
+    names = node_to_item(node, struct names, node);
+
+    /* Construct content into a linear buffer */
+    buf = NULL;
+    len = 0;
+    sequence = 0;
+    tag_len = strlen(names->name) + sizeof(char); /* tag + nul */
+    list_for_each_safe(content_node, m, &names->content) {
+      ssize_t add_len;
+
+      content = node_to_item(content_node, struct content, node);
+      add_len = content->entry.len - tag_len - sizeof(prio);
+      if (add_len <= 0) {
+        list_remove(content_node);
+        free(content);
+        continue;
+      }
+
+      if (!buf) {
+        buf = malloc(sizeof(char));
+        if (!buf) {
+          ret = -ENOMEM;
+          list_remove(content_node);
+          free(content);
+          continue;
+        }
+        *buf = '\0';
+      }
+
+      /* Missing sequence numbers */
+      while (sequence < content->entry.nsec) {
+        /* plus space for enforced nul */
+        buf = realloc(buf, len + sizeof(char) + sizeof(char));
+        if (!buf) {
+          break;
+        }
+        buf[len] = '\f'; /* Mark missing content with a form feed */
+        buf[++len] = '\0';
+        sequence += ANDROID_LOG_PMSG_FILE_SEQUENCE;
+      }
+      if (!buf) {
+        ret = -ENOMEM;
+        list_remove(content_node);
+        free(content);
+        continue;
+      }
+      /* plus space for enforced nul */
+      buf = realloc(buf, len + add_len + sizeof(char));
+      if (!buf) {
+        ret = -ENOMEM;
+        list_remove(content_node);
+        free(content);
+        continue;
+      }
+      memcpy(buf + len,
+             (char*)&content->entry + content->entry.hdr_size + tag_len +
+                 sizeof(prio),
+             add_len);
+      len += add_len;
+      buf[len] = '\0'; /* enforce trailing hidden nul */
+      sequence = content->entry.nsec + ANDROID_LOG_PMSG_FILE_SEQUENCE;
+
+      list_remove(content_node);
+      free(content);
+    }
+    if (buf) {
+      if (len) {
+        /* Buffer contains enforced trailing nul just beyond length */
+        ssize_t r;
+        *strchr(names->name, ':') = '/'; /* Convert back to filename */
+        r = (*fn)(names->id, names->prio, names->name, buf, len, arg);
+        if ((ret >= 0) && (r > 0)) {
+          if (ret == SSIZE_MAX) {
+            ret = r;
+          } else {
+            ret += r;
+          }
+        } else if (r < ret) {
+          ret = r;
+        }
+      }
+      free(buf);
+    }
+    list_remove(node);
+    free(names);
+  }
+  return (ret == SSIZE_MAX) ? -ENOENT : ret;
 }
diff --git a/liblog/pmsg_writer.c b/liblog/pmsg_writer.c
index 944feba..dc42856 100644
--- a/liblog/pmsg_writer.c
+++ b/liblog/pmsg_writer.c
@@ -20,14 +20,13 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
 #include <time.h>
 
-#include <log/log.h>
-#include <log/logger.h>
-
+#include <log/log_properties.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
@@ -38,147 +37,149 @@
 static int pmsgOpen();
 static void pmsgClose();
 static int pmsgAvailable(log_id_t logId);
-static int pmsgWrite(log_id_t logId, struct timespec *ts,
-                      struct iovec *vec, size_t nr);
+static int pmsgWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                     size_t nr);
 
 LIBLOG_HIDDEN struct android_log_transport_write pmsgLoggerWrite = {
-    .node = { &pmsgLoggerWrite.node, &pmsgLoggerWrite.node },
-    .context.fd = -1,
-    .name = "pmsg",
-    .available = pmsgAvailable,
-    .open = pmsgOpen,
-    .close = pmsgClose,
-    .write = pmsgWrite,
+  .node = { &pmsgLoggerWrite.node, &pmsgLoggerWrite.node },
+  .context.fd = -1,
+  .name = "pmsg",
+  .available = pmsgAvailable,
+  .open = pmsgOpen,
+  .close = pmsgClose,
+  .write = pmsgWrite,
 };
 
-static int pmsgOpen()
-{
-    if (pmsgLoggerWrite.context.fd < 0) {
-        pmsgLoggerWrite.context.fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY | O_CLOEXEC));
-    }
+static int pmsgOpen() {
+  int fd = atomic_load(&pmsgLoggerWrite.context.fd);
+  if (fd < 0) {
+    int i;
 
-    return pmsgLoggerWrite.context.fd;
+    fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY | O_CLOEXEC));
+    i = atomic_exchange(&pmsgLoggerWrite.context.fd, fd);
+    if ((i >= 0) && (i != fd)) {
+      close(i);
+    }
+  }
+
+  return fd;
 }
 
-static void pmsgClose()
-{
-    if (pmsgLoggerWrite.context.fd >= 0) {
-        close(pmsgLoggerWrite.context.fd);
-        pmsgLoggerWrite.context.fd = -1;
-    }
+static void pmsgClose() {
+  int fd = atomic_exchange(&pmsgLoggerWrite.context.fd, -1);
+  if (fd >= 0) {
+    close(fd);
+  }
 }
 
-static int pmsgAvailable(log_id_t logId)
-{
-    if (logId > LOG_ID_SECURITY) {
-        return -EINVAL;
+static int pmsgAvailable(log_id_t logId) {
+  if (logId > LOG_ID_SECURITY) {
+    return -EINVAL;
+  }
+  if ((logId != LOG_ID_SECURITY) && (logId != LOG_ID_EVENTS) &&
+      !__android_log_is_debuggable()) {
+    return -EINVAL;
+  }
+  if (atomic_load(&pmsgLoggerWrite.context.fd) < 0) {
+    if (access("/dev/pmsg0", W_OK) == 0) {
+      return 0;
     }
-    if ((logId != LOG_ID_SECURITY) &&
-            (logId != LOG_ID_EVENTS) &&
-            !__android_log_is_debuggable()) {
-        return -EINVAL;
-    }
-    if (pmsgLoggerWrite.context.fd < 0) {
-        if (access("/dev/pmsg0", W_OK) == 0) {
-            return 0;
-        }
-        return -EBADF;
-    }
-    return 1;
+    return -EBADF;
+  }
+  return 1;
 }
 
 /*
  * Extract a 4-byte value from a byte stream.
  */
-static inline uint32_t get4LE(const uint8_t* src)
-{
-    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+static inline uint32_t get4LE(const uint8_t* src) {
+  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
 
-static int pmsgWrite(log_id_t logId, struct timespec *ts,
-                      struct iovec *vec, size_t nr)
-{
-    static const unsigned headerLength = 2;
-    struct iovec newVec[nr + headerLength];
-    android_log_header_t header;
-    android_pmsg_log_header_t pmsgHeader;
-    size_t i, payloadSize;
-    ssize_t ret;
+static int pmsgWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                     size_t nr) {
+  static const unsigned headerLength = 2;
+  struct iovec newVec[nr + headerLength];
+  android_log_header_t header;
+  android_pmsg_log_header_t pmsgHeader;
+  size_t i, payloadSize;
+  ssize_t ret;
 
-    if ((logId == LOG_ID_EVENTS) && !__android_log_is_debuggable()) {
-        if (vec[0].iov_len < 4) {
-            return -EINVAL;
-        }
-
-        if (SNET_EVENT_LOG_TAG != get4LE(vec[0].iov_base)) {
-            return -EPERM;
-        }
+  if ((logId == LOG_ID_EVENTS) && !__android_log_is_debuggable()) {
+    if (vec[0].iov_len < 4) {
+      return -EINVAL;
     }
 
-    if (pmsgLoggerWrite.context.fd < 0) {
-        return -EBADF;
+    if (SNET_EVENT_LOG_TAG != get4LE(vec[0].iov_base)) {
+      return -EPERM;
     }
+  }
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsgHeader;
-     *      // what we provide to file
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  if (atomic_load(&pmsgLoggerWrite.context.fd) < 0) {
+    return -EBADF;
+  }
 
-    pmsgHeader.magic = LOGGER_MAGIC;
-    pmsgHeader.len = sizeof(pmsgHeader) + sizeof(header);
-    pmsgHeader.uid = __android_log_uid();
-    pmsgHeader.pid = getpid();
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsgHeader;
+   *      // what we provide to file
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    header.id = logId;
-    header.tid = gettid();
-    header.realtime.tv_sec = ts->tv_sec;
-    header.realtime.tv_nsec = ts->tv_nsec;
+  pmsgHeader.magic = LOGGER_MAGIC;
+  pmsgHeader.len = sizeof(pmsgHeader) + sizeof(header);
+  pmsgHeader.uid = __android_log_uid();
+  pmsgHeader.pid = getpid();
 
-    newVec[0].iov_base   = (unsigned char *)&pmsgHeader;
-    newVec[0].iov_len    = sizeof(pmsgHeader);
-    newVec[1].iov_base   = (unsigned char *)&header;
-    newVec[1].iov_len    = sizeof(header);
+  header.id = logId;
+  header.tid = gettid();
+  header.realtime.tv_sec = ts->tv_sec;
+  header.realtime.tv_nsec = ts->tv_nsec;
 
-    for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
-        newVec[i].iov_base = vec[i - headerLength].iov_base;
-        payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
+  newVec[0].iov_base = (unsigned char*)&pmsgHeader;
+  newVec[0].iov_len = sizeof(pmsgHeader);
+  newVec[1].iov_base = (unsigned char*)&header;
+  newVec[1].iov_len = sizeof(header);
 
-        if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
-            newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
-            if (newVec[i].iov_len) {
-                ++i;
-            }
-            payloadSize = LOGGER_ENTRY_MAX_PAYLOAD;
-            break;
-        }
+  for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
+    newVec[i].iov_base = vec[i - headerLength].iov_base;
+    payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
+
+    if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
+      newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
+      if (newVec[i].iov_len) {
+        ++i;
+      }
+      payloadSize = LOGGER_ENTRY_MAX_PAYLOAD;
+      break;
     }
-    pmsgHeader.len += payloadSize;
+  }
+  pmsgHeader.len += payloadSize;
 
-    ret = TEMP_FAILURE_RETRY(writev(pmsgLoggerWrite.context.fd, newVec, i));
-    if (ret < 0) {
-        ret = errno ? -errno : -ENOTCONN;
-    }
+  ret = TEMP_FAILURE_RETRY(
+      writev(atomic_load(&pmsgLoggerWrite.context.fd), newVec, i));
+  if (ret < 0) {
+    ret = errno ? -errno : -ENOTCONN;
+  }
 
-    if (ret > (ssize_t)(sizeof(header) + sizeof(pmsgHeader))) {
-        ret -= sizeof(header) - sizeof(pmsgHeader);
-    }
+  if (ret > (ssize_t)(sizeof(header) + sizeof(pmsgHeader))) {
+    ret -= sizeof(header) - sizeof(pmsgHeader);
+  }
 
-    return ret;
+  return ret;
 }
 
 /*
@@ -191,103 +192,116 @@
  * Will hijack the header.realtime.tv_nsec field for a sequence number in usec.
  */
 
-static inline const char *strnrchr(const char *buf, size_t len, char c) {
-    const char *cp = buf + len;
-    while ((--cp > buf) && (*cp != c));
-    if (cp <= buf) {
-        return buf + len;
-    }
-    return cp;
+static inline const char* strnrchr(const char* buf, size_t len, char c) {
+  const char* cp = buf + len;
+  while ((--cp > buf) && (*cp != c))
+    ;
+  if (cp <= buf) {
+    return buf + len;
+  }
+  return cp;
 }
 
 /* Write a buffer as filename references (tag = <basedir>:<basename>) */
-LIBLOG_ABI_PRIVATE ssize_t __android_log_pmsg_file_write(
-        log_id_t logId,
-        char prio,
-        const char *filename,
-        const char *buf, size_t len) {
-    int fd;
-    size_t length, packet_len;
-    const char *tag;
-    char *cp, *slash;
-    struct timespec ts;
-    struct iovec vec[3];
+LIBLOG_ABI_PRIVATE ssize_t __android_log_pmsg_file_write(log_id_t logId,
+                                                         char prio,
+                                                         const char* filename,
+                                                         const char* buf,
+                                                         size_t len) {
+  bool weOpened;
+  size_t length, packet_len;
+  const char* tag;
+  char *cp, *slash;
+  struct timespec ts;
+  struct iovec vec[3];
 
-    /* Make sure the logId value is not a bad idea */
-    if ((logId == LOG_ID_KERNEL) ||       /* Verbotten */
-            (logId == LOG_ID_EVENTS) ||   /* Do not support binary content */
-            (logId == LOG_ID_SECURITY) || /* Bad idea to allow */
-            ((unsigned)logId >= 32)) {    /* fit within logMask on arch32 */
-        return -EINVAL;
-    }
+  /* Make sure the logId value is not a bad idea */
+  if ((logId == LOG_ID_KERNEL) ||   /* Verbotten */
+      (logId == LOG_ID_EVENTS) ||   /* Do not support binary content */
+      (logId == LOG_ID_SECURITY) || /* Bad idea to allow */
+      ((unsigned)logId >= 32)) {    /* fit within logMask on arch32 */
+    return -EINVAL;
+  }
 
-    clock_gettime(android_log_clockid(), &ts);
+  clock_gettime(android_log_clockid(), &ts);
 
-    cp = strdup(filename);
-    if (!cp) {
-        return -ENOMEM;
-    }
+  cp = strdup(filename);
+  if (!cp) {
+    return -ENOMEM;
+  }
 
-    fd = pmsgLoggerWrite.context.fd;
-    if (fd < 0) {
-        __android_log_lock();
-        fd = pmsgOpen();
-        __android_log_unlock();
-        if (fd < 0) {
-            return -EBADF;
-        }
-    }
-
-    tag = cp;
+  tag = cp;
+  slash = strrchr(cp, '/');
+  if (slash) {
+    *slash = ':';
     slash = strrchr(cp, '/');
     if (slash) {
-        *slash = ':';
-        slash = strrchr(cp, '/');
-        if (slash) {
-            tag = slash + 1;
-        }
+      tag = slash + 1;
+    }
+  }
+
+  length = strlen(tag) + 1;
+  packet_len = LOGGER_ENTRY_MAX_PAYLOAD - sizeof(char) - length;
+
+  vec[0].iov_base = &prio;
+  vec[0].iov_len = sizeof(char);
+  vec[1].iov_base = (unsigned char*)tag;
+  vec[1].iov_len = length;
+
+  weOpened = false;
+  for (ts.tv_nsec = 0, length = len; length;
+       ts.tv_nsec += ANDROID_LOG_PMSG_FILE_SEQUENCE) {
+    ssize_t ret;
+    size_t transfer;
+
+    if ((ts.tv_nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
+        ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE) {
+      len -= length;
+      break;
     }
 
-    length = strlen(tag) + 1;
-    packet_len = LOGGER_ENTRY_MAX_PAYLOAD - sizeof(char) - length;
-
-    vec[0].iov_base = &prio;
-    vec[0].iov_len  = sizeof(char);
-    vec[1].iov_base = (unsigned char *)tag;
-    vec[1].iov_len  = length;
-
-    for (ts.tv_nsec = 0, length = len;
-            length;
-            ts.tv_nsec += ANDROID_LOG_PMSG_FILE_SEQUENCE) {
-        ssize_t ret;
-        size_t transfer;
-
-        if ((ts.tv_nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
-                ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE) {
-            len -= length;
-            break;
-        }
-
-        transfer = length;
-        if (transfer > packet_len) {
-            transfer = strnrchr(buf, packet_len - 1, '\n') - buf;
-            if ((transfer < length) && (buf[transfer] == '\n')) {
-                ++transfer;
-            }
-        }
-
-        vec[2].iov_base = (unsigned char *)buf;
-        vec[2].iov_len  = transfer;
-
-        ret = pmsgWrite(logId, &ts, vec, sizeof(vec) / sizeof(vec[0]));
-
-        if (ret <= 0) {
-            free(cp);
-            return ret;
-        }
-        length -= transfer;
-        buf += transfer;
+    transfer = length;
+    if (transfer > packet_len) {
+      transfer = strnrchr(buf, packet_len - 1, '\n') - buf;
+      if ((transfer < length) && (buf[transfer] == '\n')) {
+        ++transfer;
+      }
     }
-    free(cp);
-    return len;
+
+    vec[2].iov_base = (unsigned char*)buf;
+    vec[2].iov_len = transfer;
+
+    if (atomic_load(&pmsgLoggerWrite.context.fd) < 0) {
+      if (!weOpened) { /* Impossible for weOpened = true here */
+        __android_log_lock();
+      }
+      weOpened = atomic_load(&pmsgLoggerWrite.context.fd) < 0;
+      if (!weOpened) {
+        __android_log_unlock();
+      } else if (pmsgOpen() < 0) {
+        __android_log_unlock();
+        free(cp);
+        return -EBADF;
+      }
+    }
+
+    ret = pmsgWrite(logId, &ts, vec, sizeof(vec) / sizeof(vec[0]));
+
+    if (ret <= 0) {
+      if (weOpened) {
+        pmsgClose();
+        __android_log_unlock();
+      }
+      free(cp);
+      return ret ? ret : (len - length);
+    }
+    length -= transfer;
+    buf += transfer;
+  }
+  if (weOpened) {
+    pmsgClose();
+    __android_log_unlock();
+  }
+  free(cp);
+  return len;
 }
diff --git a/liblog/properties.c b/liblog/properties.c
new file mode 100644
index 0000000..11be827
--- /dev/null
+++ b/liblog/properties.c
@@ -0,0 +1,646 @@
+/*
+** Copyright 2014, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#include <ctype.h>
+#include <pthread.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+#include <unistd.h>
+
+#include <private/android_logger.h>
+
+#include "log_portability.h"
+
+static pthread_mutex_t lock_loggable = PTHREAD_MUTEX_INITIALIZER;
+
+static int lock() {
+  /*
+   * If we trigger a signal handler in the middle of locked activity and the
+   * signal handler logs a message, we could get into a deadlock state.
+   */
+  /*
+   *  Any contention, and we can turn around and use the non-cached method
+   * in less time than the system call associated with a mutex to deal with
+   * the contention.
+   */
+  return pthread_mutex_trylock(&lock_loggable);
+}
+
+static void unlock() {
+  pthread_mutex_unlock(&lock_loggable);
+}
+
+struct cache {
+  const prop_info* pinfo;
+  uint32_t serial;
+};
+
+struct cache_char {
+  struct cache cache;
+  unsigned char c;
+};
+
+static int check_cache(struct cache* cache) {
+  return cache->pinfo && __system_property_serial(cache->pinfo) != cache->serial;
+}
+
+#define BOOLEAN_TRUE 0xFF
+#define BOOLEAN_FALSE 0xFE
+
+static void refresh_cache(struct cache_char* cache, const char* key) {
+  char buf[PROP_VALUE_MAX];
+
+  if (!cache->cache.pinfo) {
+    cache->cache.pinfo = __system_property_find(key);
+    if (!cache->cache.pinfo) {
+      return;
+    }
+  }
+  cache->cache.serial = __system_property_serial(cache->cache.pinfo);
+  __system_property_read(cache->cache.pinfo, 0, buf);
+  switch (buf[0]) {
+    case 't':
+    case 'T':
+      cache->c = strcasecmp(buf + 1, "rue") ? buf[0] : BOOLEAN_TRUE;
+      break;
+    case 'f':
+    case 'F':
+      cache->c = strcasecmp(buf + 1, "alse") ? buf[0] : BOOLEAN_FALSE;
+      break;
+    default:
+      cache->c = buf[0];
+  }
+}
+
+static int __android_log_level(const char* tag, size_t len, int default_prio) {
+  /* sizeof() is used on this array below */
+  static const char log_namespace[] = "persist.log.tag.";
+  static const size_t base_offset = 8; /* skip "persist." */
+  /* calculate the size of our key temporary buffer */
+  const size_t taglen = tag ? len : 0;
+  /* sizeof(log_namespace) = strlen(log_namespace) + 1 */
+  char key[sizeof(log_namespace) + taglen];
+  char* kp;
+  size_t i;
+  char c = 0;
+  /*
+   * Single layer cache of four properties. Priorities are:
+   *    log.tag.<tag>
+   *    persist.log.tag.<tag>
+   *    log.tag
+   *    persist.log.tag
+   * Where the missing tag matches all tags and becomes the
+   * system global default. We do not support ro.log.tag* .
+   */
+  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;
+  static struct cache_char tag_cache[2];
+  static struct cache_char global_cache[2];
+  int change_detected;
+  int global_change_detected;
+  int not_locked;
+
+  strcpy(key, log_namespace);
+
+  global_change_detected = change_detected = not_locked = lock();
+
+  if (!not_locked) {
+    /*
+     *  check all known serial numbers to changes.
+     */
+    for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
+      if (check_cache(&tag_cache[i].cache)) {
+        change_detected = 1;
+      }
+    }
+    for (i = 0; i < (sizeof(global_cache) / sizeof(global_cache[0])); ++i) {
+      if (check_cache(&global_cache[i].cache)) {
+        global_change_detected = 1;
+      }
+    }
+
+    current_global_serial = __system_property_area_serial();
+    if (current_global_serial != global_serial) {
+      change_detected = 1;
+      global_change_detected = 1;
+    }
+  }
+
+  if (taglen) {
+    int local_change_detected = change_detected;
+    if (!not_locked) {
+      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';
+        }
+        if (last_tag) last_tag[0] = '\0';
+        local_change_detected = 1;
+      }
+      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';
+        }
+      }
+    }
+    strncpy(key + sizeof(log_namespace) - 1, tag, len);
+    key[sizeof(log_namespace) - 1 + len] = '\0';
+
+    kp = key;
+    for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
+      struct cache_char* cache = &tag_cache[i];
+      struct cache_char temp_cache;
+
+      if (not_locked) {
+        temp_cache.cache.pinfo = NULL;
+        temp_cache.c = '\0';
+        cache = &temp_cache;
+      }
+      if (local_change_detected) {
+        refresh_cache(cache, kp);
+      }
+
+      if (cache->c) {
+        c = cache->c;
+        break;
+      }
+
+      kp = key + base_offset;
+    }
+  }
+
+  switch (toupper(c)) { /* if invalid, resort to global */
+    case 'V':
+    case 'D':
+    case 'I':
+    case 'W':
+    case 'E':
+    case 'F': /* Not officially supported */
+    case 'A':
+    case 'S':
+    case BOOLEAN_FALSE: /* Not officially supported */
+      break;
+    default:
+      /* clear '.' after log.tag */
+      key[sizeof(log_namespace) - 2] = '\0';
+
+      kp = key;
+      for (i = 0; i < (sizeof(global_cache) / sizeof(global_cache[0])); ++i) {
+        struct cache_char* cache = &global_cache[i];
+        struct cache_char temp_cache;
+
+        if (not_locked) {
+          temp_cache = *cache;
+          if (temp_cache.cache.pinfo != cache->cache.pinfo) { /* check atomic */
+            temp_cache.cache.pinfo = NULL;
+            temp_cache.c = '\0';
+          }
+          cache = &temp_cache;
+        }
+        if (global_change_detected) {
+          refresh_cache(cache, kp);
+        }
+
+        if (cache->c) {
+          c = cache->c;
+          break;
+        }
+
+        kp = key + base_offset;
+      }
+      break;
+  }
+
+  if (!not_locked) {
+    global_serial = current_global_serial;
+    unlock();
+  }
+
+  switch (toupper(c)) {
+    /* clang-format off */
+    case 'V': return ANDROID_LOG_VERBOSE;
+    case 'D': return ANDROID_LOG_DEBUG;
+    case 'I': return ANDROID_LOG_INFO;
+    case 'W': return ANDROID_LOG_WARN;
+    case 'E': return ANDROID_LOG_ERROR;
+    case 'F': /* FALLTHRU */ /* Not officially supported */
+    case 'A': return ANDROID_LOG_FATAL;
+    case BOOLEAN_FALSE: /* FALLTHRU */ /* Not Officially supported */
+    case 'S': return -1; /* ANDROID_LOG_SUPPRESS */
+    /* clang-format on */
+  }
+  return default_prio;
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_is_loggable_len(int prio, const char* tag,
+                                                    size_t len,
+                                                    int default_prio) {
+  int logLevel = __android_log_level(tag, len, default_prio);
+  return logLevel >= 0 && prio >= logLevel;
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_is_loggable(int prio, const char* tag,
+                                                int default_prio) {
+  int logLevel =
+      __android_log_level(tag, (tag && *tag) ? strlen(tag) : 0, default_prio);
+  return logLevel >= 0 && prio >= logLevel;
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_is_debuggable() {
+  static uint32_t serial;
+  static struct cache_char tag_cache;
+  static const char key[] = "ro.debuggable";
+  int ret;
+
+  if (tag_cache.c) { /* ro property does not change after set */
+    ret = tag_cache.c == '1';
+  } else if (lock()) {
+    struct cache_char temp_cache = { { NULL, -1 }, '\0' };
+    refresh_cache(&temp_cache, key);
+    ret = temp_cache.c == '1';
+  } else {
+    int change_detected = check_cache(&tag_cache.cache);
+    uint32_t current_serial = __system_property_area_serial();
+    if (current_serial != serial) {
+      change_detected = 1;
+    }
+    if (change_detected) {
+      refresh_cache(&tag_cache, key);
+      serial = current_serial;
+    }
+    ret = tag_cache.c == '1';
+
+    unlock();
+  }
+
+  return ret;
+}
+
+/*
+ * For properties that are read often, but generally remain constant.
+ * Since a change is rare, we will accept a trylock failure gracefully.
+ * Use a separate lock from is_loggable to keep contention down b/25563384.
+ */
+struct cache2_char {
+  pthread_mutex_t lock;
+  uint32_t serial;
+  const char* key_persist;
+  struct cache_char cache_persist;
+  const char* key_ro;
+  struct cache_char cache_ro;
+  unsigned char (*const evaluate)(const struct cache2_char* self);
+};
+
+static inline unsigned char do_cache2_char(struct cache2_char* self) {
+  uint32_t current_serial;
+  int change_detected;
+  unsigned char c;
+
+  if (pthread_mutex_trylock(&self->lock)) {
+    /* We are willing to accept some race in this context */
+    return self->evaluate(self);
+  }
+
+  change_detected = check_cache(&self->cache_persist.cache) ||
+                    check_cache(&self->cache_ro.cache);
+  current_serial = __system_property_area_serial();
+  if (current_serial != self->serial) {
+    change_detected = 1;
+  }
+  if (change_detected) {
+    refresh_cache(&self->cache_persist, self->key_persist);
+    refresh_cache(&self->cache_ro, self->key_ro);
+    self->serial = current_serial;
+  }
+  c = self->evaluate(self);
+
+  pthread_mutex_unlock(&self->lock);
+
+  return c;
+}
+
+static unsigned char evaluate_persist_ro(const struct cache2_char* self) {
+  unsigned char c = self->cache_persist.c;
+
+  if (c) {
+    return c;
+  }
+
+  return self->cache_ro.c;
+}
+
+/*
+ * Timestamp state generally remains constant, but can change at any time
+ * to handle developer requirements.
+ */
+LIBLOG_ABI_PUBLIC clockid_t android_log_clockid() {
+  static struct cache2_char clockid = {
+    PTHREAD_MUTEX_INITIALIZER, 0,
+    "persist.logd.timestamp",  { { NULL, -1 }, '\0' },
+    "ro.logd.timestamp",       { { NULL, -1 }, '\0' },
+    evaluate_persist_ro
+  };
+
+  return (tolower(do_cache2_char(&clockid)) == 'm') ? CLOCK_MONOTONIC
+                                                    : CLOCK_REALTIME;
+}
+
+/*
+ * Security state generally remains constant, but the DO must be able
+ * to turn off logging should it become spammy after an attack is detected.
+ */
+static unsigned char evaluate_security(const struct cache2_char* self) {
+  unsigned char c = self->cache_ro.c;
+
+  return (c != BOOLEAN_FALSE) && c && (self->cache_persist.c == BOOLEAN_TRUE);
+}
+
+LIBLOG_ABI_PUBLIC int __android_log_security() {
+  static struct cache2_char security = {
+    PTHREAD_MUTEX_INITIALIZER, 0,
+    "persist.logd.security",   { { NULL, -1 }, BOOLEAN_FALSE },
+    "ro.device_owner",         { { NULL, -1 }, BOOLEAN_FALSE },
+    evaluate_security
+  };
+
+  return do_cache2_char(&security);
+}
+
+/*
+ * Interface that represents the logd buffer size determination so that others
+ * need not guess our intentions.
+ */
+
+/* Property helper */
+static bool check_flag(const char* prop, const char* flag) {
+  const char* cp = strcasestr(prop, flag);
+  if (!cp) {
+    return false;
+  }
+  /* We only will document comma (,) */
+  static const char sep[] = ",:;|+ \t\f";
+  if ((cp != prop) && !strchr(sep, cp[-1])) {
+    return false;
+  }
+  cp += strlen(flag);
+  return !*cp || !!strchr(sep, *cp);
+}
+
+/* cache structure */
+struct cache_property {
+  struct cache cache;
+  char property[PROP_VALUE_MAX];
+};
+
+static void refresh_cache_property(struct cache_property* cache,
+                                   const char* key) {
+  if (!cache->cache.pinfo) {
+    cache->cache.pinfo = __system_property_find(key);
+    if (!cache->cache.pinfo) {
+      return;
+    }
+  }
+  cache->cache.serial = __system_property_serial(cache->cache.pinfo);
+  __system_property_read(cache->cache.pinfo, 0, cache->property);
+}
+
+/* get boolean with the logger twist that supports eng adjustments */
+LIBLOG_ABI_PRIVATE bool __android_logger_property_get_bool(const char* key,
+                                                           int flag) {
+  struct cache_property property = { { NULL, -1 }, { 0 } };
+  if (flag & BOOL_DEFAULT_FLAG_PERSIST) {
+    char newkey[strlen("persist.") + strlen(key) + 1];
+    snprintf(newkey, sizeof(newkey), "ro.%s", key);
+    refresh_cache_property(&property, newkey);
+    property.cache.pinfo = NULL;
+    property.cache.serial = -1;
+    snprintf(newkey, sizeof(newkey), "persist.%s", key);
+    refresh_cache_property(&property, newkey);
+    property.cache.pinfo = NULL;
+    property.cache.serial = -1;
+  }
+
+  refresh_cache_property(&property, key);
+
+  if (check_flag(property.property, "true")) {
+    return true;
+  }
+  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;
+  }
+  /* this is really a "not" flag */
+  if (check_flag(property.property, "svelte")) {
+    flag |= BOOL_DEFAULT_FLAG_SVELTE;
+  }
+
+  /* Sanity Check */
+  if (flag & (BOOL_DEFAULT_FLAG_SVELTE | BOOL_DEFAULT_FLAG_ENG)) {
+    flag &= ~BOOL_DEFAULT_FLAG_TRUE_FALSE;
+    flag |= BOOL_DEFAULT_TRUE;
+  }
+
+  if ((flag & BOOL_DEFAULT_FLAG_SVELTE) &&
+      __android_logger_property_get_bool("ro.config.low_ram",
+                                         BOOL_DEFAULT_FALSE)) {
+    return false;
+  }
+  if ((flag & BOOL_DEFAULT_FLAG_ENG) && !__android_log_is_debuggable()) {
+    return false;
+  }
+
+  return (flag & BOOL_DEFAULT_FLAG_TRUE_FALSE) != BOOL_DEFAULT_FALSE;
+}
+
+LIBLOG_ABI_PRIVATE bool __android_logger_valid_buffer_size(unsigned long value) {
+  static long pages, pagesize;
+  unsigned long maximum;
+
+  if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
+    return false;
+  }
+
+  if (!pages) {
+    pages = sysconf(_SC_PHYS_PAGES);
+  }
+  if (pages < 1) {
+    return true;
+  }
+
+  if (!pagesize) {
+    pagesize = sysconf(_SC_PAGESIZE);
+    if (pagesize <= 1) {
+      pagesize = PAGE_SIZE;
+    }
+  }
+
+  /* maximum memory impact a somewhat arbitrary ~3% */
+  pages = (pages + 31) / 32;
+  maximum = pages * pagesize;
+
+  if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
+    return true;
+  }
+
+  return value <= maximum;
+}
+
+struct cache2_property_size {
+  pthread_mutex_t lock;
+  uint32_t serial;
+  const char* key_persist;
+  struct cache_property cache_persist;
+  const char* key_ro;
+  struct cache_property cache_ro;
+  unsigned long (*const evaluate)(const struct cache2_property_size* self);
+};
+
+static inline unsigned long do_cache2_property_size(
+    struct cache2_property_size* self) {
+  uint32_t current_serial;
+  int change_detected;
+  unsigned long v;
+
+  if (pthread_mutex_trylock(&self->lock)) {
+    /* We are willing to accept some race in this context */
+    return self->evaluate(self);
+  }
+
+  change_detected = check_cache(&self->cache_persist.cache) ||
+                    check_cache(&self->cache_ro.cache);
+  current_serial = __system_property_area_serial();
+  if (current_serial != self->serial) {
+    change_detected = 1;
+  }
+  if (change_detected) {
+    refresh_cache_property(&self->cache_persist, self->key_persist);
+    refresh_cache_property(&self->cache_ro, self->key_ro);
+    self->serial = current_serial;
+  }
+  v = self->evaluate(self);
+
+  pthread_mutex_unlock(&self->lock);
+
+  return v;
+}
+
+static unsigned long property_get_size_from_cache(
+    const struct cache_property* cache) {
+  char* cp;
+  unsigned long value = strtoul(cache->property, &cp, 10);
+
+  switch (*cp) {
+    case 'm':
+    case 'M':
+      value *= 1024;
+    /* FALLTHRU */
+    case 'k':
+    case 'K':
+      value *= 1024;
+    /* FALLTHRU */
+    case '\0':
+      break;
+
+    default:
+      value = 0;
+  }
+
+  if (!__android_logger_valid_buffer_size(value)) {
+    value = 0;
+  }
+
+  return value;
+}
+
+static unsigned long evaluate_property_get_size(
+    const struct cache2_property_size* self) {
+  unsigned long size = property_get_size_from_cache(&self->cache_persist);
+  if (size) {
+    return size;
+  }
+  return property_get_size_from_cache(&self->cache_ro);
+}
+
+LIBLOG_ABI_PRIVATE unsigned long __android_logger_get_buffer_size(log_id_t logId) {
+  static const char global_tunable[] = "persist.logd.size"; /* Settings App */
+  static const char global_default[] = "ro.logd.size";      /* BoardConfig.mk */
+  static struct cache2_property_size global = {
+    /* clang-format off */
+    PTHREAD_MUTEX_INITIALIZER, 0,
+    global_tunable, { { NULL, -1 }, {} },
+    global_default, { { NULL, -1 }, {} },
+    evaluate_property_get_size
+    /* clang-format on */
+  };
+  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,
+    key_persist, { { NULL, -1 }, {} },
+    key_ro,      { { NULL, -1 }, {} },
+    evaluate_property_get_size
+    /* clang-format on */
+  };
+  unsigned long property_size, default_size;
+
+  default_size = do_cache2_property_size(&global);
+  if (!default_size) {
+    default_size = __android_logger_property_get_bool("ro.config.low_ram",
+                                                      BOOL_DEFAULT_FALSE)
+                       ? LOG_BUFFER_MIN_SIZE /* 64K  */
+                       : LOG_BUFFER_SIZE;    /* 256K */
+  }
+
+  snprintf(key_persist, sizeof(key_persist), "%s.%s", global_tunable,
+           android_log_id_to_name(logId));
+  snprintf(key_ro, sizeof(key_ro), "%s.%s", global_default,
+           android_log_id_to_name(logId));
+  property_size = do_cache2_property_size(&local);
+
+  if (!property_size) {
+    property_size = default_size;
+  }
+
+  if (!property_size) {
+    property_size = LOG_BUFFER_SIZE;
+  }
+
+  return property_size;
+}
diff --git a/liblog/stderr_write.c b/liblog/stderr_write.c
new file mode 100644
index 0000000..dbe5309
--- /dev/null
+++ b/liblog/stderr_write.c
@@ -0,0 +1,212 @@
+/*
+ * 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.
+ */
+
+/*
+ * stderr write handler.  Output is logcat-like, and responds to
+ * logcat's environment variables ANDROID_PRINTF_LOG and
+ * ANDROID_LOG_TAGS to filter output.
+ *
+ * This transport only provides a writer, that means that it does not
+ * provide an End-To-End capability as the logs are effectively _lost_
+ * to the stderr file stream.  The purpose of this transport is to
+ * supply a means for command line tools to report their logging
+ * to the stderr stream, in line with all other activities.
+ */
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <log/event_tag_map.h>
+#include <log/log.h>
+#include <log/logprint.h>
+#include <log/uio.h>
+
+#include "log_portability.h"
+#include "logger.h"
+
+static int stderrOpen();
+static void stderrClose();
+static int stderrAvailable(log_id_t logId);
+static int stderrWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                       size_t nr);
+
+struct stderrContext {
+  AndroidLogFormat* logformat;
+#if defined(__ANDROID__)
+  EventTagMap* eventTagMap;
+#endif
+};
+
+LIBLOG_HIDDEN struct android_log_transport_write stderrLoggerWrite = {
+  .node = { &stderrLoggerWrite.node, &stderrLoggerWrite.node },
+  .context.priv = NULL,
+  .name = "stderr",
+  .available = stderrAvailable,
+  .open = stderrOpen,
+  .close = stderrClose,
+  .write = stderrWrite,
+};
+
+static int stderrOpen() {
+  struct stderrContext* ctx;
+  const char* envStr;
+  bool setFormat;
+
+  if (!stderr || (fileno(stderr) < 0)) {
+    return -EBADF;
+  }
+
+  if (stderrLoggerWrite.context.priv) {
+    return fileno(stderr);
+  }
+
+  ctx = calloc(1, sizeof(struct stderrContext));
+  if (!ctx) {
+    return -ENOMEM;
+  }
+
+  ctx->logformat = android_log_format_new();
+  if (!ctx->logformat) {
+    free(ctx);
+    return -ENOMEM;
+  }
+
+  envStr = getenv("ANDROID_PRINTF_LOG");
+  setFormat = false;
+
+  if (envStr) {
+    char* formats = strdup(envStr);
+    char* sv = NULL;
+    char* arg = formats;
+    while (!!(arg = strtok_r(arg, ",:; \t\n\r\f", &sv))) {
+      AndroidLogPrintFormat format = android_log_formatFromString(arg);
+      arg = NULL;
+      if (format == FORMAT_OFF) {
+        continue;
+      }
+      if (android_log_setPrintFormat(ctx->logformat, format) <= 0) {
+        continue;
+      }
+      setFormat = true;
+    }
+    free(formats);
+  }
+  if (!setFormat) {
+    AndroidLogPrintFormat format = android_log_formatFromString("threadtime");
+    android_log_setPrintFormat(ctx->logformat, format);
+  }
+  envStr = getenv("ANDROID_LOG_TAGS");
+  if (envStr) {
+    android_log_addFilterString(ctx->logformat, envStr);
+  }
+  stderrLoggerWrite.context.priv = ctx;
+
+  return fileno(stderr);
+}
+
+static void stderrClose() {
+  struct stderrContext* ctx = stderrLoggerWrite.context.priv;
+
+  if (ctx) {
+    stderrLoggerWrite.context.priv = NULL;
+    if (ctx->logformat) {
+      android_log_format_free(ctx->logformat);
+      ctx->logformat = NULL;
+    }
+#if defined(__ANDROID__)
+    if (ctx->eventTagMap) {
+      android_closeEventTagMap(ctx->eventTagMap);
+      ctx->eventTagMap = NULL;
+    }
+#endif
+  }
+}
+
+static int stderrAvailable(log_id_t logId) {
+  if ((logId >= LOG_ID_MAX) || (logId == LOG_ID_KERNEL)) {
+    return -EINVAL;
+  }
+  return 1;
+}
+
+static int stderrWrite(log_id_t logId, struct timespec* ts, struct iovec* vec,
+                       size_t nr) {
+  struct log_msg log_msg;
+  AndroidLogEntry entry;
+  char binaryMsgBuf[1024];
+  int err;
+  size_t i;
+  struct stderrContext* ctx = stderrLoggerWrite.context.priv;
+
+  if (!ctx) return -EBADF;
+  if (!vec || !nr) return -EINVAL;
+
+  log_msg.entry.len = 0;
+  log_msg.entry.hdr_size = sizeof(log_msg.entry);
+  log_msg.entry.pid = getpid();
+#ifdef __BIONIC__
+  log_msg.entry.tid = gettid();
+#else
+  log_msg.entry.tid = getpid();
+#endif
+  log_msg.entry.sec = ts->tv_sec;
+  log_msg.entry.nsec = ts->tv_nsec;
+  log_msg.entry.lid = logId;
+  log_msg.entry.uid = __android_log_uid();
+
+  for (i = 0; i < nr; ++i) {
+    size_t len = vec[i].iov_len;
+    if ((log_msg.entry.len + len) > LOGGER_ENTRY_MAX_PAYLOAD) {
+      len = LOGGER_ENTRY_MAX_PAYLOAD - log_msg.entry.len;
+    }
+    if (!len) continue;
+    memcpy(log_msg.entry.msg + log_msg.entry.len, vec[i].iov_base, len);
+    log_msg.entry.len += len;
+  }
+
+  if ((logId == LOG_ID_EVENTS) || (logId == LOG_ID_SECURITY)) {
+#if defined(__ANDROID__)
+    if (!ctx->eventTagMap) {
+      ctx->eventTagMap = android_openEventTagMap(NULL);
+    }
+#endif
+    err = android_log_processBinaryLogBuffer(&log_msg.entry_v1, &entry,
+#if defined(__ANDROID__)
+                                             ctx->eventTagMap,
+#else
+                                             NULL,
+#endif
+                                             binaryMsgBuf, sizeof(binaryMsgBuf));
+  } else {
+    err = android_log_processLogBuffer(&log_msg.entry_v1, &entry);
+  }
+
+  /* print known truncated data, in essence logcat --debug */
+  if ((err < 0) && !entry.message) return -EINVAL;
+
+  if (!android_log_shouldPrintLine(ctx->logformat, entry.tag, entry.priority)) {
+    return log_msg.entry.len;
+  }
+
+  err = android_log_printLogLine(ctx->logformat, fileno(stderr), &entry);
+  if (err < 0) return errno ? -errno : -EINVAL;
+  return log_msg.entry.len;
+}
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index 8229859..0e6432c 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -28,7 +28,6 @@
     -Wall -Wextra \
     -Werror \
     -fno-builtin \
-    -std=gnu++11
 
 benchmark_src_files := \
     benchmark_main.cpp \
@@ -40,7 +39,7 @@
 LOCAL_MODULE := $(test_module_prefix)benchmarks
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(benchmark_c_flags)
-LOCAL_SHARED_LIBRARIES += liblog libm
+LOCAL_SHARED_LIBRARIES += liblog libm libbase
 LOCAL_SRC_FILES := $(benchmark_src_files)
 include $(BUILD_NATIVE_TEST)
 
@@ -54,10 +53,17 @@
     -Wall -Wextra \
     -Werror \
     -fno-builtin \
-    -std=gnu++11
 
 test_src_files := \
-    liblog_test.cpp
+    liblog_test_default.cpp \
+    liblog_test_local.cpp \
+    liblog_test_stderr.cpp \
+    liblog_test_stderr_local.cpp \
+    log_id_test.cpp \
+    log_radio_test.cpp \
+    log_read_test.cpp \
+    log_system_test.cpp \
+    log_time_test.cpp
 
 # to prevent breaking the build if bionic not relatively visible to us
 ifneq ($(wildcard $(LOCAL_PATH)/../../../../bionic/libc/bionic/libc_logging.cpp),)
@@ -73,6 +79,42 @@
 LOCAL_MODULE := $(test_module_prefix)unit-tests
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_SHARED_LIBRARIES := liblog libcutils
+LOCAL_SHARED_LIBRARIES := liblog libcutils libbase
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
+
+cts_executable := CtsLiblogTestCases
+
+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 := liblog libcutils libbase
+LOCAL_STATIC_LIBRARIES := libgtest libgtest_main
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.core.liblog
+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 := liblog libcutils libbase
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+LOCAL_LDLIBS_linux := -lrt
+include $(BUILD_HOST_NATIVE_TEST)
+
+endif  # ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
diff --git a/liblog/tests/AndroidTest.xml b/liblog/tests/AndroidTest.xml
new file mode 100644
index 0000000..427f2b4
--- /dev/null
+++ b/liblog/tests/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?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 Library test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsLiblogTestCases->/data/local/tmp/CtsLiblogTestCases" />
+        <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="CtsLiblogTestCases" />
+        <option name="runtime-hint" value="65s" />
+    </test>
+</configuration>
diff --git a/liblog/tests/benchmark.h b/liblog/tests/benchmark.h
index 7f96e6d..e9280f6 100644
--- a/liblog/tests/benchmark.h
+++ b/liblog/tests/benchmark.h
@@ -38,7 +38,7 @@
   Benchmark(const char* name, void (*fn)(int)) : name_(strdup(name)), fn_(fn) {
     BenchmarkRegister(this);
   }
-  Benchmark(const char* name) : name_(strdup(name)), fn_(NULL) {}
+  explicit Benchmark(const char* name) : name_(strdup(name)), fn_(NULL) {}
 
   virtual ~Benchmark() {
     free(name_);
@@ -141,7 +141,7 @@
 void StopBenchmarkTiming(uint64_t);
 
 #define BENCHMARK(f) \
-    static ::testing::Benchmark* _benchmark_##f __attribute__((unused)) = \
-        (::testing::Benchmark*)::testing::BenchmarkFactory(#f, f)
+    static ::testing::Benchmark* _benchmark_##f __attribute__((unused)) = /* NOLINT */ \
+        (::testing::Benchmark*)::testing::BenchmarkFactory(#f, f) /* NOLINT */
 
 #endif // BIONIC_BENCHMARK_H_
diff --git a/liblog/tests/benchmark_main.cpp b/liblog/tests/benchmark_main.cpp
index e5ef970..7367f1b 100644
--- a/liblog/tests/benchmark_main.cpp
+++ b/liblog/tests/benchmark_main.cpp
@@ -22,8 +22,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#include <string>
 #include <map>
+#include <string>
 #include <vector>
 
 static uint64_t gBytesProcessed;
@@ -32,21 +32,21 @@
 static uint64_t gBenchmarkNum;
 static uint64_t gBenchmarkStartTimeNs;
 
-typedef std::vector< ::testing::Benchmark* > BenchmarkList;
+typedef std::vector< ::testing::Benchmark*> BenchmarkList;
 static BenchmarkList* gBenchmarks;
 
 static int Round(int n) {
   int base = 1;
-  while (base*10 < n) {
+  while (base * 10 < n) {
     base *= 10;
   }
-  if (n < 2*base) {
-    return 2*base;
+  if (n < 2 * base) {
+    return 2 * base;
   }
-  if (n < 5*base) {
-    return 5*base;
+  if (n < 5 * base) {
+    return 5 * base;
   }
-  return 10*base;
+  return 10 * base;
 }
 
 static uint64_t NanoTime() {
@@ -58,20 +58,19 @@
 
 namespace testing {
 
-int PrettyPrintInt(char* str, int len, unsigned int arg)
-{
-  if (arg >= (1<<30) && arg % (1<<30) == 0) {
-    return snprintf(str, len, "%uGi", arg/(1<<30));
-  } else if (arg >= (1<<20) && arg % (1<<20) == 0) {
-    return snprintf(str, len, "%uMi", arg/(1<<20));
-  } else if (arg >= (1<<10) && arg % (1<<10) == 0) {
-    return snprintf(str, len, "%uKi", arg/(1<<10));
+int PrettyPrintInt(char* str, int len, unsigned int arg) {
+  if (arg >= (1 << 30) && arg % (1 << 30) == 0) {
+    return snprintf(str, len, "%uGi", arg / (1 << 30));
+  } else if (arg >= (1 << 20) && arg % (1 << 20) == 0) {
+    return snprintf(str, len, "%uMi", arg / (1 << 20));
+  } else if (arg >= (1 << 10) && arg % (1 << 10) == 0) {
+    return snprintf(str, len, "%uKi", arg / (1 << 10));
   } else if (arg >= 1000000000 && arg % 1000000000 == 0) {
-    return snprintf(str, len, "%uG", arg/1000000000);
+    return snprintf(str, len, "%uG", arg / 1000000000);
   } else if (arg >= 1000000 && arg % 1000000 == 0) {
-    return snprintf(str, len, "%uM", arg/1000000);
+    return snprintf(str, len, "%uM", arg / 1000000);
   } else if (arg >= 1000 && arg % 1000 == 0) {
-    return snprintf(str, len, "%uK", arg/1000);
+    return snprintf(str, len, "%uK", arg / 1000);
   } else {
     return snprintf(str, len, "%u", arg);
   }
@@ -86,7 +85,8 @@
   for (int i = 1; i < argc; i++) {
     regex_t re;
     if (regcomp(&re, argv[i], 0) != 0) {
-      fprintf(stderr, "couldn't compile \"%s\" as a regular expression!\n", argv[i]);
+      fprintf(stderr, "couldn't compile \"%s\" as a regular expression!\n",
+              argv[i]);
       exit(EXIT_FAILURE);
     }
     int match = regexec(&re, b->Name(), 0, NULL, 0);
@@ -111,9 +111,8 @@
   uint64_t StartTimeNs = NanoTime();
   b->RunFn(iterations);
   // Catch us if we fail to log anything.
-  if ((gBenchmarkTotalTimeNs == 0)
-   && (StartTimeNs != 0)
-   && (gBenchmarkStartTimeNs == 0)) {
+  if ((gBenchmarkTotalTimeNs == 0) && (StartTimeNs != 0) &&
+      (gBenchmarkStartTimeNs == 0)) {
     gBenchmarkTotalTimeNs = NanoTime() - StartTimeNs;
   }
 }
@@ -126,12 +125,13 @@
   s = NanoTime() - s;
   while (s < 2e9 && gBenchmarkTotalTimeNs < 1e9 && iterations < 1e9) {
     unsigned last = iterations;
-    if (gBenchmarkTotalTimeNs/iterations == 0) {
+    if (gBenchmarkTotalTimeNs / iterations == 0) {
       iterations = 1e9;
     } else {
-      iterations = 1e9 / (gBenchmarkTotalTimeNs/iterations);
+      iterations = 1e9 / (gBenchmarkTotalTimeNs / iterations);
     }
-    iterations = std::max(last + 1, std::min(iterations + iterations/2, 100*last));
+    iterations =
+        std::max(last + 1, std::min(iterations + iterations / 2, 100 * last));
     iterations = Round(iterations);
     s = NanoTime();
     RunRepeatedly(b, iterations);
@@ -141,30 +141,30 @@
   char throughput[100];
   throughput[0] = '\0';
   if (gBenchmarkTotalTimeNs > 0 && gBytesProcessed > 0) {
-    double mib_processed = static_cast<double>(gBytesProcessed)/1e6;
-    double seconds = static_cast<double>(gBenchmarkTotalTimeNs)/1e9;
-    snprintf(throughput, sizeof(throughput), " %8.2f MiB/s", mib_processed/seconds);
+    double mib_processed = static_cast<double>(gBytesProcessed) / 1e6;
+    double seconds = static_cast<double>(gBenchmarkTotalTimeNs) / 1e9;
+    snprintf(throughput, sizeof(throughput), " %8.2f MiB/s",
+             mib_processed / seconds);
   }
 
   char full_name[100];
   snprintf(full_name, sizeof(full_name), "%s%s%s", b->Name(),
-           b->ArgName() ? "/" : "",
-           b->ArgName() ? b->ArgName() : "");
+           b->ArgName() ? "/" : "", b->ArgName() ? b->ArgName() : "");
 
   uint64_t mean = gBenchmarkTotalTimeNs / iterations;
   uint64_t sdev = 0;
   if (gBenchmarkNum == iterations) {
     mean = gBenchmarkTotalTimeNs / gBenchmarkNum;
-    uint64_t nXvariance = gBenchmarkTotalTimeNsSquared * gBenchmarkNum
-                        - (gBenchmarkTotalTimeNs * gBenchmarkTotalTimeNs);
+    uint64_t nXvariance = gBenchmarkTotalTimeNsSquared * gBenchmarkNum -
+                          (gBenchmarkTotalTimeNs * gBenchmarkTotalTimeNs);
     sdev = (sqrt((double)nXvariance) / gBenchmarkNum / gBenchmarkNum) + 0.5;
   }
   if (mean > (10000 * sdev)) {
     printf("%-25s %10" PRIu64 " %10" PRIu64 "%s\n", full_name,
-            static_cast<uint64_t>(iterations), mean, throughput);
+           static_cast<uint64_t>(iterations), mean, throughput);
   } else {
-    printf("%-25s %10" PRIu64 " %10" PRIu64 "(\317\203%" PRIu64 ")%s\n", full_name,
-           static_cast<uint64_t>(iterations), mean, sdev, throughput);
+    printf("%-25s %10" PRIu64 " %10" PRIu64 "(\317\203%" PRIu64 ")%s\n",
+           full_name, static_cast<uint64_t>(iterations), mean, sdev, throughput);
   }
   fflush(stdout);
 }
diff --git a/liblog/tests/libc_test.cpp b/liblog/tests/libc_test.cpp
index 9dd6f03..329ba85 100644
--- a/liblog/tests/libc_test.cpp
+++ b/liblog/tests/libc_test.cpp
@@ -14,132 +14,36 @@
  * limitations under the License.
  */
 
-#include <fcntl.h>
-#include <sys/cdefs.h>
-
 #include <gtest/gtest.h>
 
-// Should be in bionic test suite, *but* we are using liblog to confirm
-// end-to-end logging, so let the overly cute oedipus complex begin ...
-#include "../../../../bionic/libc/bionic/libc_logging.cpp" // not Standalone
-#define _ANDROID_LOG_H // Priorities redefined
-#define _LIBS_LOG_LOG_H // log ids redefined
-typedef unsigned char log_id_t; // log_id_t missing as a result
-#define _LIBS_LOG_LOG_READ_H // log_time redefined
-
-#include <log/log.h>
-#include <log/logger.h>
-#include <log/log_read.h>
-
-TEST(libc, __libc_android_log_event_int) {
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    struct timespec ts;
-    clock_gettime(CLOCK_MONOTONIC, &ts);
-    int value = ts.tv_nsec;
-
-    __libc_android_log_event_int(0, value);
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.len != (4 + 1 + 4))
-         || ((int)log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        int incoming = (eventData[0] & 0xFF) |
-                      ((eventData[1] & 0xFF) << 8) |
-                      ((eventData[2] & 0xFF) << 16) |
-                      ((eventData[3] & 0xFF) << 24);
-
-        if (incoming != 0) {
-            continue;
-        }
-
-        if (eventData[4] != EVENT_TYPE_INT) {
-            continue;
-        }
-
-        incoming = (eventData[4 + 1 + 0] & 0xFF) |
-                  ((eventData[4 + 1 + 1] & 0xFF) << 8) |
-                  ((eventData[4 + 1 + 2] & 0xFF) << 16) |
-                  ((eventData[4 + 1 + 3] & 0xFF) << 24);
-
-        if (incoming == value) {
-            ++count;
-        }
-    }
-
-    EXPECT_EQ(1, count);
-
-    android_logger_list_close(logger_list);
-}
-
-TEST(libc, __libc_fatal_no_abort) {
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        (log_id_t)LOG_ID_CRASH, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    char b[80];
-    struct timespec ts;
-    clock_gettime(CLOCK_MONOTONIC, &ts);
-
-    __libc_fatal_no_abort("%u.%09u", (unsigned)ts.tv_sec, (unsigned)ts.tv_nsec);
-    snprintf(b, sizeof(b),"%u.%09u", (unsigned)ts.tv_sec, (unsigned)ts.tv_nsec);
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((int)log_msg.id() != LOG_ID_CRASH) {
-            continue;
-        }
-
-        char *data = log_msg.msg();
-
-        if ((*data == ANDROID_LOG_FATAL)
-                && !strcmp(data + 1, "libc")
-                && !strcmp(data + 1 + strlen(data + 1) + 1, b)) {
-            ++count;
-        }
-    }
-
-    EXPECT_EQ(1, count);
-
-    android_logger_list_close(logger_list);
-}
+#include <errno.h>
+#include <stdio.h>
 
 TEST(libc, __pstore_append) {
-    FILE *fp;
-    ASSERT_TRUE(NULL != (fp = fopen("/dev/pmsg0", "a")));
-    static const char message[] = "libc.__pstore_append\n";
-    ASSERT_EQ((size_t)1, fwrite(message, sizeof(message), 1, fp));
-    ASSERT_EQ(0, fclose(fp));
-    fprintf(stderr, "Reboot, ensure string libc.__pstore_append is in /sys/fs/pstore/pmsg-ramoops-0\n");
+#ifdef __ANDROID__
+  FILE* fp;
+  ASSERT_TRUE(NULL != (fp = fopen("/dev/pmsg0", "a")));
+  static const char message[] = "libc.__pstore_append\n";
+  ASSERT_EQ((size_t)1, fwrite(message, sizeof(message), 1, fp));
+  int fflushReturn = fflush(fp);
+  int fflushErrno = fflushReturn ? errno : 0;
+  ASSERT_EQ(0, fflushReturn);
+  ASSERT_EQ(0, fflushErrno);
+  int fcloseReturn = fclose(fp);
+  int fcloseErrno = fcloseReturn ? errno : 0;
+  ASSERT_EQ(0, fcloseReturn);
+  ASSERT_EQ(0, fcloseErrno);
+  if ((fcloseErrno == ENOMEM) || (fflushErrno == ENOMEM)) {
+    fprintf(stderr,
+            "Kernel does not have space allocated to pmsg pstore driver "
+            "configured\n");
+  }
+  if (!fcloseReturn && !fcloseErrno && !fflushReturn && !fflushReturn) {
+    fprintf(stderr,
+            "Reboot, ensure string libc.__pstore_append is in "
+            "/sys/fs/pstore/pmsg-ramoops-0\n");
+  }
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 01fb50f..3f79552 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -15,15 +15,19 @@
  */
 
 #include <fcntl.h>
+#include <inttypes.h>
+#include <poll.h>
 #include <sys/endian.h>
 #include <sys/socket.h>
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <unordered_set>
+
+#include <android-base/file.h>
 #include <cutils/sockets.h>
-#include <log/log.h>
-#include <log/logger.h>
-#include <log/log_read.h>
+#include <log/event_tag_map.h>
+#include <log/log_transport.h>
 #include <private/android_logger.h>
 
 #include "benchmark.h"
@@ -32,16 +36,15 @@
 // non-syscall libs. Since we are benchmarking, or using this in the emergency
 // signal to stuff a terminating code, we do NOT want to introduce
 // a syscall or usleep on EAGAIN retry.
-#define LOG_FAILURE_RETRY(exp) ({  \
-    typeof (exp) _rc;              \
-    do {                           \
-        _rc = (exp);               \
-    } while (((_rc == -1)          \
-           && ((errno == EINTR)    \
-            || (errno == EAGAIN))) \
-          || (_rc == -EINTR)       \
-          || (_rc == -EAGAIN));    \
-    _rc; })
+#define LOG_FAILURE_RETRY(exp)                                           \
+  ({                                                                     \
+    typeof(exp) _rc;                                                     \
+    do {                                                                 \
+      _rc = (exp);                                                       \
+    } while (((_rc == -1) && ((errno == EINTR) || (errno == EAGAIN))) || \
+             (_rc == -EINTR) || (_rc == -EAGAIN));                       \
+    _rc;                                                                 \
+  })
 
 /*
  *	Measure the fastest rate we can reliabley stuff print messages into
@@ -49,15 +52,14 @@
  * wakeup time (2ms?)
  */
 static void BM_log_maximum_retry(int iters) {
-    StartBenchmarkTiming();
+  StartBenchmarkTiming();
 
-    for (int i = 0; i < iters; ++i) {
-        LOG_FAILURE_RETRY(
-            __android_log_print(ANDROID_LOG_INFO,
-                                "BM_log_maximum_retry", "%d", i));
-    }
+  for (int i = 0; i < iters; ++i) {
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum_retry", "%d", i));
+  }
 
-    StopBenchmarkTiming();
+  StopBenchmarkTiming();
 }
 BENCHMARK(BM_log_maximum_retry);
 
@@ -67,26 +69,45 @@
  * time (2ms?)
  */
 static void BM_log_maximum(int iters) {
-    StartBenchmarkTiming();
+  StartBenchmarkTiming();
 
-    for (int i = 0; i < iters; ++i) {
-        __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%d", i);
-    }
+  for (int i = 0; i < iters; ++i) {
+    __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%d", i);
+  }
 
-    StopBenchmarkTiming();
+  StopBenchmarkTiming();
 }
 BENCHMARK(BM_log_maximum);
 
+static void set_log_null() {
+  android_set_log_transport(LOGGER_NULL);
+}
+
+static void set_log_default() {
+  android_set_log_transport(LOGGER_DEFAULT);
+}
+
+static void BM_log_maximum_null(int iters) {
+  set_log_null();
+  BM_log_maximum(iters);
+  set_log_default();
+}
+BENCHMARK(BM_log_maximum_null);
+
 /*
- *	Measure the time it takes to submit the android logging call using
- * discrete acquisition under light load. Expect this to be a pair of
- * syscall periods (2us).
+ *	Measure the time it takes to collect the time using
+ * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * under light load. Expect this to be a syscall period (2us) or
+ * data read time if zero-syscall.
+ *
+ * vdso support in the kernel and the library can allow
+ * clock_gettime to be zero-syscall.
  */
 static void BM_clock_overhead(int iters) {
-    for (int i = 0; i < iters; ++i) {
-       StartBenchmarkTiming();
-       StopBenchmarkTiming();
-    }
+  for (int i = 0; i < iters; ++i) {
+    StartBenchmarkTiming();
+    StopBenchmarkTiming();
+  }
 }
 BENCHMARK(BM_clock_overhead);
 
@@ -94,75 +115,74 @@
  * Measure the time it takes to submit the android logging data to pstore
  */
 static void BM_pmsg_short(int iters) {
+  int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
+  if (pstore_fd < 0) {
+    return;
+  }
 
-    int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
-    if (pstore_fd < 0) {
-        return;
-    }
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsg_header;
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsg_header;
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  struct timespec ts;
+  clock_gettime(android_log_clockid(), &ts);
 
-    struct timespec ts;
-    clock_gettime(android_log_clockid(), &ts);
+  android_pmsg_log_header_t pmsg_header;
+  pmsg_header.magic = LOGGER_MAGIC;
+  pmsg_header.len =
+      sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t);
+  pmsg_header.uid = getuid();
+  pmsg_header.pid = getpid();
 
-    android_pmsg_log_header_t pmsg_header;
-    pmsg_header.magic = LOGGER_MAGIC;
-    pmsg_header.len = sizeof(android_pmsg_log_header_t)
-                    + sizeof(android_log_header_t);
-    pmsg_header.uid = getuid();
-    pmsg_header.pid = getpid();
+  android_log_header_t header;
+  header.tid = gettid();
+  header.realtime.tv_sec = ts.tv_sec;
+  header.realtime.tv_nsec = ts.tv_nsec;
 
-    android_log_header_t header;
-    header.tid = gettid();
-    header.realtime.tv_sec = ts.tv_sec;
-    header.realtime.tv_nsec = ts.tv_nsec;
+  static const unsigned nr = 1;
+  static const unsigned header_length = 2;
+  struct iovec newVec[nr + header_length];
 
-    static const unsigned nr = 1;
-    static const unsigned header_length = 2;
-    struct iovec newVec[nr + header_length];
+  newVec[0].iov_base = (unsigned char*)&pmsg_header;
+  newVec[0].iov_len = sizeof(pmsg_header);
+  newVec[1].iov_base = (unsigned char*)&header;
+  newVec[1].iov_len = sizeof(header);
 
-    newVec[0].iov_base   = (unsigned char *) &pmsg_header;
-    newVec[0].iov_len    = sizeof(pmsg_header);
-    newVec[1].iov_base   = (unsigned char *) &header;
-    newVec[1].iov_len    = sizeof(header);
+  android_log_event_int_t buffer;
 
-    android_log_event_int_t buffer;
+  header.id = LOG_ID_EVENTS;
+  buffer.header.tag = 0;
+  buffer.payload.type = EVENT_TYPE_INT;
+  uint32_t snapshot = 0;
+  buffer.payload.data = htole32(snapshot);
 
-    header.id = LOG_ID_EVENTS;
-    buffer.header.tag = 0;
-    buffer.payload.type = EVENT_TYPE_INT;
-    uint32_t snapshot = 0;
+  newVec[2].iov_base = &buffer;
+  newVec[2].iov_len = sizeof(buffer);
+
+  StartBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    ++snapshot;
     buffer.payload.data = htole32(snapshot);
-
-    newVec[2].iov_base = &buffer;
-    newVec[2].iov_len  = sizeof(buffer);
-
-    StartBenchmarkTiming();
-    for (int i = 0; i < iters; ++i) {
-        ++snapshot;
-        buffer.payload.data = htole32(snapshot);
-        writev(pstore_fd, newVec, nr);
-    }
-    StopBenchmarkTiming();
-    close(pstore_fd);
+    writev(pstore_fd, newVec, nr);
+  }
+  StopBenchmarkTiming();
+  close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short);
 
@@ -171,74 +191,72 @@
  * best case aligned single block.
  */
 static void BM_pmsg_short_aligned(int iters) {
+  int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
+  if (pstore_fd < 0) {
+    return;
+  }
 
-    int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
-    if (pstore_fd < 0) {
-        return;
-    }
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsg_header;
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsg_header;
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  struct timespec ts;
+  clock_gettime(android_log_clockid(), &ts);
 
-    struct timespec ts;
-    clock_gettime(android_log_clockid(), &ts);
+  struct packet {
+    android_pmsg_log_header_t pmsg_header;
+    android_log_header_t header;
+    android_log_event_int_t payload;
+  };
+  alignas(8) char buf[sizeof(struct packet) + 8];
+  memset(buf, 0, sizeof(buf));
+  struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
+  if (((uintptr_t)&buffer->pmsg_header) & 7) {
+    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+  }
 
-    struct packet {
-        android_pmsg_log_header_t pmsg_header;
-        android_log_header_t header;
-        android_log_event_int_t payload;
-    };
-    char buf[sizeof(struct packet) + 8] __aligned(8);
-    memset(buf, 0, sizeof(buf));
-    struct packet *buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
-    if (((uintptr_t)&buffer->pmsg_header) & 7) {
-        fprintf (stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
-    }
+  buffer->pmsg_header.magic = LOGGER_MAGIC;
+  buffer->pmsg_header.len =
+      sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t);
+  buffer->pmsg_header.uid = getuid();
+  buffer->pmsg_header.pid = getpid();
 
-    buffer->pmsg_header.magic = LOGGER_MAGIC;
-    buffer->pmsg_header.len = sizeof(android_pmsg_log_header_t)
-                            + sizeof(android_log_header_t);
-    buffer->pmsg_header.uid = getuid();
-    buffer->pmsg_header.pid = getpid();
+  buffer->header.tid = gettid();
+  buffer->header.realtime.tv_sec = ts.tv_sec;
+  buffer->header.realtime.tv_nsec = ts.tv_nsec;
 
-    buffer->header.tid = gettid();
-    buffer->header.realtime.tv_sec = ts.tv_sec;
-    buffer->header.realtime.tv_nsec = ts.tv_nsec;
+  buffer->header.id = LOG_ID_EVENTS;
+  buffer->payload.header.tag = 0;
+  buffer->payload.payload.type = EVENT_TYPE_INT;
+  uint32_t snapshot = 0;
+  buffer->payload.payload.data = htole32(snapshot);
 
-    buffer->header.id = LOG_ID_EVENTS;
-    buffer->payload.header.tag = 0;
-    buffer->payload.payload.type = EVENT_TYPE_INT;
-    uint32_t snapshot = 0;
+  StartBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
-
-    StartBenchmarkTiming();
-    for (int i = 0; i < iters; ++i) {
-        ++snapshot;
-        buffer->payload.payload.data = htole32(snapshot);
-        write(pstore_fd, &buffer->pmsg_header,
-            sizeof(android_pmsg_log_header_t) +
-            sizeof(android_log_header_t) +
-            sizeof(android_log_event_int_t));
-    }
-    StopBenchmarkTiming();
-    close(pstore_fd);
+    write(pstore_fd, &buffer->pmsg_header,
+          sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
+              sizeof(android_log_event_int_t));
+  }
+  StopBenchmarkTiming();
+  close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short_aligned);
 
@@ -247,74 +265,72 @@
  * best case aligned single block.
  */
 static void BM_pmsg_short_unaligned1(int iters) {
+  int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
+  if (pstore_fd < 0) {
+    return;
+  }
 
-    int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
-    if (pstore_fd < 0) {
-        return;
-    }
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsg_header;
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsg_header;
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  struct timespec ts;
+  clock_gettime(android_log_clockid(), &ts);
 
-    struct timespec ts;
-    clock_gettime(android_log_clockid(), &ts);
+  struct packet {
+    android_pmsg_log_header_t pmsg_header;
+    android_log_header_t header;
+    android_log_event_int_t payload;
+  };
+  alignas(8) char buf[sizeof(struct packet) + 8];
+  memset(buf, 0, sizeof(buf));
+  struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
+  if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
+    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+  }
 
-    struct packet {
-        android_pmsg_log_header_t pmsg_header;
-        android_log_header_t header;
-        android_log_event_int_t payload;
-    };
-    char buf[sizeof(struct packet) + 8] __aligned(8);
-    memset(buf, 0, sizeof(buf));
-    struct packet *buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
-    if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
-        fprintf (stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
-    }
+  buffer->pmsg_header.magic = LOGGER_MAGIC;
+  buffer->pmsg_header.len =
+      sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t);
+  buffer->pmsg_header.uid = getuid();
+  buffer->pmsg_header.pid = getpid();
 
-    buffer->pmsg_header.magic = LOGGER_MAGIC;
-    buffer->pmsg_header.len = sizeof(android_pmsg_log_header_t)
-                            + sizeof(android_log_header_t);
-    buffer->pmsg_header.uid = getuid();
-    buffer->pmsg_header.pid = getpid();
+  buffer->header.tid = gettid();
+  buffer->header.realtime.tv_sec = ts.tv_sec;
+  buffer->header.realtime.tv_nsec = ts.tv_nsec;
 
-    buffer->header.tid = gettid();
-    buffer->header.realtime.tv_sec = ts.tv_sec;
-    buffer->header.realtime.tv_nsec = ts.tv_nsec;
+  buffer->header.id = LOG_ID_EVENTS;
+  buffer->payload.header.tag = 0;
+  buffer->payload.payload.type = EVENT_TYPE_INT;
+  uint32_t snapshot = 0;
+  buffer->payload.payload.data = htole32(snapshot);
 
-    buffer->header.id = LOG_ID_EVENTS;
-    buffer->payload.header.tag = 0;
-    buffer->payload.payload.type = EVENT_TYPE_INT;
-    uint32_t snapshot = 0;
+  StartBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
-
-    StartBenchmarkTiming();
-    for (int i = 0; i < iters; ++i) {
-        ++snapshot;
-        buffer->payload.payload.data = htole32(snapshot);
-        write(pstore_fd, &buffer->pmsg_header,
-            sizeof(android_pmsg_log_header_t) +
-            sizeof(android_log_header_t) +
-            sizeof(android_log_event_int_t));
-    }
-    StopBenchmarkTiming();
-    close(pstore_fd);
+    write(pstore_fd, &buffer->pmsg_header,
+          sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
+              sizeof(android_log_event_int_t));
+  }
+  StopBenchmarkTiming();
+  close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short_unaligned1);
 
@@ -323,71 +339,70 @@
  * best case aligned single block.
  */
 static void BM_pmsg_long_aligned(int iters) {
+  int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
+  if (pstore_fd < 0) {
+    return;
+  }
 
-    int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
-    if (pstore_fd < 0) {
-        return;
-    }
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsg_header;
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsg_header;
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  struct timespec ts;
+  clock_gettime(android_log_clockid(), &ts);
 
-    struct timespec ts;
-    clock_gettime(android_log_clockid(), &ts);
+  struct packet {
+    android_pmsg_log_header_t pmsg_header;
+    android_log_header_t header;
+    android_log_event_int_t payload;
+  };
+  alignas(8) char buf[sizeof(struct packet) + 8 + LOGGER_ENTRY_MAX_PAYLOAD];
+  memset(buf, 0, sizeof(buf));
+  struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
+  if (((uintptr_t)&buffer->pmsg_header) & 7) {
+    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+  }
 
-    struct packet {
-        android_pmsg_log_header_t pmsg_header;
-        android_log_header_t header;
-        android_log_event_int_t payload;
-    };
-    char buf[sizeof(struct packet) + 8 + LOGGER_ENTRY_MAX_PAYLOAD] __aligned(8);
-    memset(buf, 0, sizeof(buf));
-    struct packet *buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
-    if (((uintptr_t)&buffer->pmsg_header) & 7) {
-        fprintf (stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
-    }
+  buffer->pmsg_header.magic = LOGGER_MAGIC;
+  buffer->pmsg_header.len =
+      sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t);
+  buffer->pmsg_header.uid = getuid();
+  buffer->pmsg_header.pid = getpid();
 
-    buffer->pmsg_header.magic = LOGGER_MAGIC;
-    buffer->pmsg_header.len = sizeof(android_pmsg_log_header_t)
-                            + sizeof(android_log_header_t);
-    buffer->pmsg_header.uid = getuid();
-    buffer->pmsg_header.pid = getpid();
+  buffer->header.tid = gettid();
+  buffer->header.realtime.tv_sec = ts.tv_sec;
+  buffer->header.realtime.tv_nsec = ts.tv_nsec;
 
-    buffer->header.tid = gettid();
-    buffer->header.realtime.tv_sec = ts.tv_sec;
-    buffer->header.realtime.tv_nsec = ts.tv_nsec;
+  buffer->header.id = LOG_ID_EVENTS;
+  buffer->payload.header.tag = 0;
+  buffer->payload.payload.type = EVENT_TYPE_INT;
+  uint32_t snapshot = 0;
+  buffer->payload.payload.data = htole32(snapshot);
 
-    buffer->header.id = LOG_ID_EVENTS;
-    buffer->payload.header.tag = 0;
-    buffer->payload.payload.type = EVENT_TYPE_INT;
-    uint32_t snapshot = 0;
+  StartBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
-
-    StartBenchmarkTiming();
-    for (int i = 0; i < iters; ++i) {
-        ++snapshot;
-        buffer->payload.payload.data = htole32(snapshot);
-        write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
-    }
-    StopBenchmarkTiming();
-    close(pstore_fd);
+    write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
+  }
+  StopBenchmarkTiming();
+  close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_long_aligned);
 
@@ -396,107 +411,179 @@
  * best case aligned single block.
  */
 static void BM_pmsg_long_unaligned1(int iters) {
+  int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
+  if (pstore_fd < 0) {
+    return;
+  }
 
-    int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
-    if (pstore_fd < 0) {
-        return;
-    }
+  /*
+   *  struct {
+   *      // what we provide to pstore
+   *      android_pmsg_log_header_t pmsg_header;
+   *      // what we provide to socket
+   *      android_log_header_t header;
+   *      // caller provides
+   *      union {
+   *          struct {
+   *              char     prio;
+   *              char     payload[];
+   *          } string;
+   *          struct {
+   *              uint32_t tag
+   *              char     payload[];
+   *          } binary;
+   *      };
+   *  };
+   */
 
-    /*
-     *  struct {
-     *      // what we provide to pstore
-     *      android_pmsg_log_header_t pmsg_header;
-     *      // what we provide to socket
-     *      android_log_header_t header;
-     *      // caller provides
-     *      union {
-     *          struct {
-     *              char     prio;
-     *              char     payload[];
-     *          } string;
-     *          struct {
-     *              uint32_t tag
-     *              char     payload[];
-     *          } binary;
-     *      };
-     *  };
-     */
+  struct timespec ts;
+  clock_gettime(android_log_clockid(), &ts);
 
-    struct timespec ts;
-    clock_gettime(android_log_clockid(), &ts);
+  struct packet {
+    android_pmsg_log_header_t pmsg_header;
+    android_log_header_t header;
+    android_log_event_int_t payload;
+  };
+  alignas(8) char buf[sizeof(struct packet) + 8 + LOGGER_ENTRY_MAX_PAYLOAD];
+  memset(buf, 0, sizeof(buf));
+  struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
+  if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
+    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+  }
 
-    struct packet {
-        android_pmsg_log_header_t pmsg_header;
-        android_log_header_t header;
-        android_log_event_int_t payload;
-    };
-    char buf[sizeof(struct packet) + 8 + LOGGER_ENTRY_MAX_PAYLOAD] __aligned(8);
-    memset(buf, 0, sizeof(buf));
-    struct packet *buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
-    if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
-        fprintf (stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
-    }
+  buffer->pmsg_header.magic = LOGGER_MAGIC;
+  buffer->pmsg_header.len =
+      sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t);
+  buffer->pmsg_header.uid = getuid();
+  buffer->pmsg_header.pid = getpid();
 
-    buffer->pmsg_header.magic = LOGGER_MAGIC;
-    buffer->pmsg_header.len = sizeof(android_pmsg_log_header_t)
-                            + sizeof(android_log_header_t);
-    buffer->pmsg_header.uid = getuid();
-    buffer->pmsg_header.pid = getpid();
+  buffer->header.tid = gettid();
+  buffer->header.realtime.tv_sec = ts.tv_sec;
+  buffer->header.realtime.tv_nsec = ts.tv_nsec;
 
-    buffer->header.tid = gettid();
-    buffer->header.realtime.tv_sec = ts.tv_sec;
-    buffer->header.realtime.tv_nsec = ts.tv_nsec;
+  buffer->header.id = LOG_ID_EVENTS;
+  buffer->payload.header.tag = 0;
+  buffer->payload.payload.type = EVENT_TYPE_INT;
+  uint32_t snapshot = 0;
+  buffer->payload.payload.data = htole32(snapshot);
 
-    buffer->header.id = LOG_ID_EVENTS;
-    buffer->payload.header.tag = 0;
-    buffer->payload.payload.type = EVENT_TYPE_INT;
-    uint32_t snapshot = 0;
+  StartBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
-
-    StartBenchmarkTiming();
-    for (int i = 0; i < iters; ++i) {
-        ++snapshot;
-        buffer->payload.payload.data = htole32(snapshot);
-        write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
-    }
-    StopBenchmarkTiming();
-    close(pstore_fd);
+    write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
+  }
+  StopBenchmarkTiming();
+  close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_long_unaligned1);
 
 /*
- *	Measure the time it takes to submit the android logging call using
- * discrete acquisition under light load. Expect this to be a dozen or so
- * syscall periods (40us).
+ *	Measure the time it takes to form sprintf plus time using
+ * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * under light load. Expect this to be a syscall period (2us) or sprintf
+ * time if zero-syscall time.
  */
-static void BM_log_overhead(int iters) {
-    for (int i = 0; i < iters; ++i) {
-       StartBenchmarkTiming();
-       __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%d", i);
-       StopBenchmarkTiming();
-       usleep(1000);
-    }
-}
-BENCHMARK(BM_log_overhead);
+/* helper function */
+static void test_print(const char* fmt, ...) {
+  va_list ap;
+  char buf[1024];
 
-static void caught_latency(int /*signum*/)
-{
-    unsigned long long v = 0xDEADBEEFA55A5AA5ULL;
-
-    LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+  va_start(ap, fmt);
+  vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
 }
 
-static unsigned long long caught_convert(char *cp)
-{
-    unsigned long long l = cp[0] & 0xFF;
-    l |= (unsigned long long) (cp[1] & 0xFF) << 8;
-    l |= (unsigned long long) (cp[2] & 0xFF) << 16;
-    l |= (unsigned long long) (cp[3] & 0xFF) << 24;
-    l |= (unsigned long long) (cp[4] & 0xFF) << 32;
-    l |= (unsigned long long) (cp[5] & 0xFF) << 40;
-    l |= (unsigned long long) (cp[6] & 0xFF) << 48;
-    l |= (unsigned long long) (cp[7] & 0xFF) << 56;
-    return l;
+#define logd_yield() sched_yield()  // allow logd to catch up
+#define logd_sleep() usleep(50)     // really allow logd to catch up
+
+/* performance test */
+static void BM_sprintf_overhead(int iters) {
+  for (int i = 0; i < iters; ++i) {
+    StartBenchmarkTiming();
+    test_print("BM_sprintf_overhead:%d", i);
+    StopBenchmarkTiming();
+    logd_yield();
+  }
+}
+BENCHMARK(BM_sprintf_overhead);
+
+/*
+ *	Measure the time it takes to submit the android printing logging call
+ * using discrete acquisition discrete acquisition (StartBenchmarkTiming() ->
+ * StopBenchmarkTiming()) under light load. Expect this to be a dozen or so
+ * syscall periods (40us) plus time to run *printf
+ */
+static void BM_log_print_overhead(int iters) {
+  for (int i = 0; i < iters; ++i) {
+    StartBenchmarkTiming();
+    __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%d", i);
+    StopBenchmarkTiming();
+    logd_yield();
+  }
+}
+BENCHMARK(BM_log_print_overhead);
+
+/*
+ *	Measure the time it takes to submit the android event logging call
+ * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * under light load. Expect this to be a dozen or so syscall periods (40us)
+ */
+static void BM_log_event_overhead(int iters) {
+  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
+    StartBenchmarkTiming();
+    __android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
+    StopBenchmarkTiming();
+    logd_yield();
+  }
+}
+BENCHMARK(BM_log_event_overhead);
+
+static void BM_log_event_overhead_null(int iters) {
+  set_log_null();
+  BM_log_event_overhead(iters);
+  set_log_default();
+}
+BENCHMARK(BM_log_event_overhead_null);
+
+/*
+ *	Measure the time it takes to submit the android event logging call
+ * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * under very-light load (<1% CPU utilization).
+ */
+static void BM_log_light_overhead(int iters) {
+  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
+    StartBenchmarkTiming();
+    __android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
+    StopBenchmarkTiming();
+    usleep(10000);
+  }
+}
+BENCHMARK(BM_log_light_overhead);
+
+static void BM_log_light_overhead_null(int iters) {
+  set_log_null();
+  BM_log_light_overhead(iters);
+  set_log_default();
+}
+BENCHMARK(BM_log_light_overhead_null);
+
+static void caught_latency(int /*signum*/) {
+  unsigned long long v = 0xDEADBEEFA55A5AA5ULL;
+
+  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+}
+
+static unsigned long long caught_convert(char* cp) {
+  unsigned long long l = cp[0] & 0xFF;
+  l |= (unsigned long long)(cp[1] & 0xFF) << 8;
+  l |= (unsigned long long)(cp[2] & 0xFF) << 16;
+  l |= (unsigned long long)(cp[3] & 0xFF) << 24;
+  l |= (unsigned long long)(cp[4] & 0xFF) << 32;
+  l |= (unsigned long long)(cp[5] & 0xFF) << 40;
+  l |= (unsigned long long)(cp[6] & 0xFF) << 48;
+  l |= (unsigned long long)(cp[7] & 0xFF) << 56;
+  return l;
 }
 
 static const int alarm_time = 3;
@@ -507,77 +594,75 @@
  * 4 syscalls (3us).
  */
 static void BM_log_latency(int iters) {
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    struct logger_list * logger_list = android_logger_list_open(LOG_ID_EVENTS,
-        ANDROID_LOG_RDONLY, 0, pid);
+  struct logger_list* logger_list =
+      android_logger_list_open(LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 0, pid);
 
-    if (!logger_list) {
-        fprintf(stderr, "Unable to open events log: %s\n", strerror(errno));
-        exit(EXIT_FAILURE);
-    }
+  if (!logger_list) {
+    fprintf(stderr, "Unable to open events log: %s\n", strerror(errno));
+    exit(EXIT_FAILURE);
+  }
 
-    signal(SIGALRM, caught_latency);
-    alarm(alarm_time);
+  signal(SIGALRM, caught_latency);
+  alarm(alarm_time);
 
-    for (int j = 0, i = 0; i < iters && j < 10*iters; ++i, ++j) {
-        log_time ts;
-        LOG_FAILURE_RETRY((
-            ts = log_time(CLOCK_REALTIME),
-            android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts))));
+  for (int j = 0, i = 0; i < iters && j < 10 * iters; ++i, ++j) {
+    log_time ts;
+    LOG_FAILURE_RETRY((ts = log_time(CLOCK_REALTIME),
+                       android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts))));
 
-        for (;;) {
-            log_msg log_msg;
-            int ret = android_logger_list_read(logger_list, &log_msg);
-            alarm(alarm_time);
+    for (;;) {
+      log_msg log_msg;
+      int ret = android_logger_list_read(logger_list, &log_msg);
+      alarm(alarm_time);
 
-            if (ret <= 0) {
-                iters = i;
-                break;
-            }
-            if ((log_msg.entry.len != (4 + 1 + 8))
-             || (log_msg.id() != LOG_ID_EVENTS)) {
-                continue;
-            }
+      if (ret <= 0) {
+        iters = i;
+        break;
+      }
+      if ((log_msg.entry.len != (4 + 1 + 8)) ||
+          (log_msg.id() != LOG_ID_EVENTS)) {
+        continue;
+      }
 
-            char* eventData = log_msg.msg();
+      char* eventData = log_msg.msg();
 
-            if (eventData[4] != EVENT_TYPE_LONG) {
-                continue;
-            }
-            log_time tx(eventData + 4 + 1);
-            if (ts != tx) {
-                if (0xDEADBEEFA55A5AA5ULL == caught_convert(eventData + 4 + 1)) {
-                    iters = i;
-                    break;
-                }
-                continue;
-            }
-
-            uint64_t start = ts.nsec();
-            uint64_t end = log_msg.nsec();
-            if (end >= start) {
-                StartBenchmarkTiming(start);
-                StopBenchmarkTiming(end);
-            } else {
-                --i;
-            }
-            break;
+      if (!eventData || (eventData[4] != EVENT_TYPE_LONG)) {
+        continue;
+      }
+      log_time tx(eventData + 4 + 1);
+      if (ts != tx) {
+        if (0xDEADBEEFA55A5AA5ULL == caught_convert(eventData + 4 + 1)) {
+          iters = i;
+          break;
         }
+        continue;
+      }
+
+      uint64_t start = ts.nsec();
+      uint64_t end = log_msg.nsec();
+      if (end >= start) {
+        StartBenchmarkTiming(start);
+        StopBenchmarkTiming(end);
+      } else {
+        --i;
+      }
+      break;
     }
+  }
 
-    signal(SIGALRM, SIG_DFL);
-    alarm(0);
+  signal(SIGALRM, SIG_DFL);
+  alarm(0);
 
-    android_logger_list_free(logger_list);
+  android_logger_list_free(logger_list);
 }
 BENCHMARK(BM_log_latency);
 
-static void caught_delay(int /*signum*/)
-{
-    unsigned long long v = 0xDEADBEEFA55A5AA6ULL;
+static void caught_delay(int /*signum*/) {
+  unsigned long long v = 0xDEADBEEFA55A5AA6ULL;
 
-    LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 }
 
 /*
@@ -585,65 +670,64 @@
  * the logs. Expect this to be less than double the process wakeup time (2ms).
  */
 static void BM_log_delay(int iters) {
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    struct logger_list * logger_list = android_logger_list_open(LOG_ID_EVENTS,
-        ANDROID_LOG_RDONLY, 0, pid);
+  struct logger_list* logger_list =
+      android_logger_list_open(LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 0, pid);
 
-    if (!logger_list) {
-        fprintf(stderr, "Unable to open events log: %s\n", strerror(errno));
-        exit(EXIT_FAILURE);
-    }
+  if (!logger_list) {
+    fprintf(stderr, "Unable to open events log: %s\n", strerror(errno));
+    exit(EXIT_FAILURE);
+  }
 
-    signal(SIGALRM, caught_delay);
-    alarm(alarm_time);
+  signal(SIGALRM, caught_delay);
+  alarm(alarm_time);
 
-    StartBenchmarkTiming();
+  StartBenchmarkTiming();
 
-    for (int i = 0; i < iters; ++i) {
-        log_time ts(CLOCK_REALTIME);
+  for (int i = 0; i < iters; ++i) {
+    log_time ts(CLOCK_REALTIME);
 
-        LOG_FAILURE_RETRY(
-            android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+    LOG_FAILURE_RETRY(android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
 
-        for (;;) {
-            log_msg log_msg;
-            int ret = android_logger_list_read(logger_list, &log_msg);
-            alarm(alarm_time);
+    for (;;) {
+      log_msg log_msg;
+      int ret = android_logger_list_read(logger_list, &log_msg);
+      alarm(alarm_time);
 
-            if (ret <= 0) {
-                iters = i;
-                break;
-            }
-            if ((log_msg.entry.len != (4 + 1 + 8))
-             || (log_msg.id() != LOG_ID_EVENTS)) {
-                continue;
-            }
+      if (ret <= 0) {
+        iters = i;
+        break;
+      }
+      if ((log_msg.entry.len != (4 + 1 + 8)) ||
+          (log_msg.id() != LOG_ID_EVENTS)) {
+        continue;
+      }
 
-            char* eventData = log_msg.msg();
+      char* eventData = log_msg.msg();
 
-            if (eventData[4] != EVENT_TYPE_LONG) {
-                continue;
-            }
-            log_time tx(eventData + 4 + 1);
-            if (ts != tx) {
-                if (0xDEADBEEFA55A5AA6ULL == caught_convert(eventData + 4 + 1)) {
-                    iters = i;
-                    break;
-                }
-                continue;
-            }
-
-            break;
+      if (!eventData || (eventData[4] != EVENT_TYPE_LONG)) {
+        continue;
+      }
+      log_time tx(eventData + 4 + 1);
+      if (ts != tx) {
+        if (0xDEADBEEFA55A5AA6ULL == caught_convert(eventData + 4 + 1)) {
+          iters = i;
+          break;
         }
+        continue;
+      }
+
+      break;
     }
+  }
 
-    signal(SIGALRM, SIG_DFL);
-    alarm(0);
+  signal(SIGALRM, SIG_DFL);
+  alarm(0);
 
-    StopBenchmarkTiming();
+  StopBenchmarkTiming();
 
-    android_logger_list_free(logger_list);
+  android_logger_list_free(logger_list);
 }
 BENCHMARK(BM_log_delay);
 
@@ -651,13 +735,16 @@
  *	Measure the time it takes for __android_log_is_loggable.
  */
 static void BM_is_loggable(int iters) {
-    StartBenchmarkTiming();
+  static const char logd[] = "logd";
 
-    for (int i = 0; i < iters; ++i) {
-        __android_log_is_loggable(ANDROID_LOG_WARN, "logd", ANDROID_LOG_VERBOSE);
-    }
+  StartBenchmarkTiming();
 
-    StopBenchmarkTiming();
+  for (int i = 0; i < iters; ++i) {
+    __android_log_is_loggable_len(ANDROID_LOG_WARN, logd, strlen(logd),
+                                  ANDROID_LOG_VERBOSE);
+  }
+
+  StopBenchmarkTiming();
 }
 BENCHMARK(BM_is_loggable);
 
@@ -665,13 +752,13 @@
  *	Measure the time it takes for android_log_clockid.
  */
 static void BM_clockid(int iters) {
-    StartBenchmarkTiming();
+  StartBenchmarkTiming();
 
-    for (int i = 0; i < iters; ++i) {
-        android_log_clockid();
-    }
+  for (int i = 0; i < iters; ++i) {
+    android_log_clockid();
+  }
 
-    StopBenchmarkTiming();
+  StopBenchmarkTiming();
 }
 BENCHMARK(BM_clockid);
 
@@ -679,12 +766,239 @@
  *	Measure the time it takes for __android_log_security.
  */
 static void BM_security(int iters) {
-    StartBenchmarkTiming();
+  StartBenchmarkTiming();
 
-    for (int i = 0; i < iters; ++i) {
-        __android_log_security();
-    }
+  for (int i = 0; i < iters; ++i) {
+    __android_log_security();
+  }
 
-    StopBenchmarkTiming();
+  StopBenchmarkTiming();
 }
 BENCHMARK(BM_security);
+
+// Keep maps around for multiple iterations
+static std::unordered_set<uint32_t> set;
+static EventTagMap* map;
+
+static bool prechargeEventMap() {
+  if (map) return true;
+
+  fprintf(stderr, "Precharge: start\n");
+
+  map = android_openEventTagMap(NULL);
+  for (uint32_t tag = 1; tag < USHRT_MAX; ++tag) {
+    size_t len;
+    if (android_lookupEventTag_len(map, &len, tag) == NULL) continue;
+    set.insert(tag);
+  }
+
+  fprintf(stderr, "Precharge: stop %zu\n", set.size());
+
+  return true;
+}
+
+/*
+ *	Measure the time it takes for android_lookupEventTag_len
+ */
+static void BM_lookupEventTag(int iters) {
+  prechargeEventMap();
+
+  std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+  StartBenchmarkTiming();
+
+  for (int i = 0; i < iters; ++i) {
+    size_t len;
+    android_lookupEventTag_len(map, &len, (*it));
+    ++it;
+    if (it == set.end()) it = set.begin();
+  }
+
+  StopBenchmarkTiming();
+}
+BENCHMARK(BM_lookupEventTag);
+
+/*
+ *	Measure the time it takes for android_lookupEventTag_len
+ */
+static uint32_t notTag = 1;
+
+static void BM_lookupEventTag_NOT(int iters) {
+  prechargeEventMap();
+
+  while (set.find(notTag) != set.end()) {
+    ++notTag;
+    if (notTag >= USHRT_MAX) notTag = 1;
+  }
+
+  StartBenchmarkTiming();
+
+  for (int i = 0; i < iters; ++i) {
+    size_t len;
+    android_lookupEventTag_len(map, &len, notTag);
+  }
+
+  StopBenchmarkTiming();
+
+  ++notTag;
+  if (notTag >= USHRT_MAX) notTag = 1;
+}
+BENCHMARK(BM_lookupEventTag_NOT);
+
+/*
+ *	Measure the time it takes for android_lookupEventFormat_len
+ */
+static void BM_lookupEventFormat(int iters) {
+  prechargeEventMap();
+
+  std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+  StartBenchmarkTiming();
+
+  for (int i = 0; i < iters; ++i) {
+    size_t len;
+    android_lookupEventFormat_len(map, &len, (*it));
+    ++it;
+    if (it == set.end()) it = set.begin();
+  }
+
+  StopBenchmarkTiming();
+}
+BENCHMARK(BM_lookupEventFormat);
+
+/*
+ *	Measure the time it takes for android_lookupEventTagNum plus above
+ */
+static void BM_lookupEventTagNum(int iters) {
+  prechargeEventMap();
+
+  std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+  for (int i = 0; i < iters; ++i) {
+    size_t len;
+    const char* name = android_lookupEventTag_len(map, &len, (*it));
+    std::string Name(name, len);
+    const char* format = android_lookupEventFormat_len(map, &len, (*it));
+    std::string Format(format, len);
+    StartBenchmarkTiming();
+    android_lookupEventTagNum(map, Name.c_str(), Format.c_str(),
+                              ANDROID_LOG_UNKNOWN);
+    StopBenchmarkTiming();
+    ++it;
+    if (it == set.end()) it = set.begin();
+  }
+}
+BENCHMARK(BM_lookupEventTagNum);
+
+// Must be functionally identical to liblog internal __send_log_msg.
+static void send_to_control(char* buf, size_t len) {
+  int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
+                                 SOCK_STREAM);
+  if (sock < 0) return;
+  size_t writeLen = strlen(buf) + 1;
+
+  ssize_t ret = TEMP_FAILURE_RETRY(write(sock, buf, writeLen));
+  if (ret <= 0) {
+    close(sock);
+    return;
+  }
+  while ((ret = read(sock, buf, len)) > 0) {
+    if (((size_t)ret == len) || (len < PAGE_SIZE)) {
+      break;
+    }
+    len -= ret;
+    buf += ret;
+
+    struct pollfd p = {.fd = sock, .events = POLLIN, .revents = 0 };
+
+    ret = poll(&p, 1, 20);
+    if ((ret <= 0) || !(p.revents & POLLIN)) {
+      break;
+    }
+  }
+  close(sock);
+}
+
+static void BM_lookupEventTagNum_logd_new(int iters) {
+  fprintf(stderr,
+          "WARNING: "
+          "This test can cause logd to grow in size and hit DOS limiter\n");
+  // Make copies
+  static const char empty_event_log_tags[] = "# content owned by logd\n";
+  static const char dev_event_log_tags_path[] = "/dev/event-log-tags";
+  std::string dev_event_log_tags;
+  if (android::base::ReadFileToString(dev_event_log_tags_path,
+                                      &dev_event_log_tags) &&
+      (dev_event_log_tags.length() == 0)) {
+    dev_event_log_tags = empty_event_log_tags;
+  }
+  static const char data_event_log_tags_path[] =
+      "/data/misc/logd/event-log-tags";
+  std::string data_event_log_tags;
+  if (android::base::ReadFileToString(data_event_log_tags_path,
+                                      &data_event_log_tags) &&
+      (data_event_log_tags.length() == 0)) {
+    data_event_log_tags = empty_event_log_tags;
+  }
+
+  for (int i = 0; i < iters; ++i) {
+    char buffer[256];
+    memset(buffer, 0, sizeof(buffer));
+    log_time now(CLOCK_MONOTONIC);
+    char name[64];
+    snprintf(name, sizeof(name), "a%" PRIu64, now.nsec());
+    snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"(new|1)\"",
+             name);
+    StartBenchmarkTiming();
+    send_to_control(buffer, sizeof(buffer));
+    StopBenchmarkTiming();
+  }
+
+  // Restore copies (logd still know about them, until crash or reboot)
+  if (dev_event_log_tags.length() &&
+      !android::base::WriteStringToFile(dev_event_log_tags,
+                                        dev_event_log_tags_path)) {
+    fprintf(stderr,
+            "WARNING: "
+            "failed to restore %s\n",
+            dev_event_log_tags_path);
+  }
+  if (data_event_log_tags.length() &&
+      !android::base::WriteStringToFile(data_event_log_tags,
+                                        data_event_log_tags_path)) {
+    fprintf(stderr,
+            "WARNING: "
+            "failed to restore %s\n",
+            data_event_log_tags_path);
+  }
+  fprintf(stderr,
+          "WARNING: "
+          "Restarting logd to make it forget what we just did\n");
+  system("stop logd ; start logd");
+}
+BENCHMARK(BM_lookupEventTagNum_logd_new);
+
+static void BM_lookupEventTagNum_logd_existing(int iters) {
+  prechargeEventMap();
+
+  std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+  for (int i = 0; i < iters; ++i) {
+    size_t len;
+    const char* name = android_lookupEventTag_len(map, &len, (*it));
+    std::string Name(name, len);
+    const char* format = android_lookupEventFormat_len(map, &len, (*it));
+    std::string Format(format, len);
+
+    char buffer[256];
+    snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"%s\"",
+             Name.c_str(), Format.c_str());
+
+    StartBenchmarkTiming();
+    send_to_control(buffer, sizeof(buffer));
+    StopBenchmarkTiming();
+    ++it;
+    if (it == set.end()) it = set.begin();
+  }
+}
+BENCHMARK(BM_lookupEventTagNum_logd_existing);
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index f0acdf8..71f74ab 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -14,470 +14,618 @@
  * limitations under the License.
  */
 
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <pthread.h>
 #include <semaphore.h>
 #include <signal.h>
+#include <stdio.h>
 #include <string.h>
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#ifdef __ANDROID__  // includes sys/properties.h which does not exist outside
 #include <cutils/properties.h>
+#endif
 #include <gtest/gtest.h>
-#include <log/log.h>
-#include <log/logger.h>
-#include <log/log_read.h>
+#include <log/log_event_list.h>
+#include <log/log_properties.h>
+#include <log/log_transport.h>
 #include <log/logprint.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
+#ifndef TEST_PREFIX
+#ifdef TEST_LOGGER
+#define TEST_PREFIX android_set_log_transport(TEST_LOGGER);
+// make sure we always run code despite overrides if compiled for android
+#elif defined(__ANDROID__)
+#define TEST_PREFIX
+#endif
+#endif
+
+#if (!defined(USING_LOGGER_DEFAULT) || !defined(USING_LOGGER_LOCAL) || \
+     !defined(USING_LOGGER_STDERR))
+#ifdef liblog  // a binary clue that we are overriding the test names
+// Does not support log reading blocking feature yet
+// Does not support LOG_ID_SECURITY (unless we set LOGGER_LOCAL | LOGGER_LOGD)
+// Assume some common aspects are tested by USING_LOGGER_DEFAULT:
+// Does not need to _retest_ pmsg functionality
+// Does not need to _retest_ property handling as it is a higher function
+// Does not need to _retest_ event mapping functionality
+// Does not need to _retest_ ratelimit
+// Does not need to _retest_ logprint
+#define USING_LOGGER_LOCAL
+#else
+#define USING_LOGGER_DEFAULT
+#endif
+#endif
+#ifdef USING_LOGGER_STDERR
+#define SUPPORTS_END_TO_END 0
+#else
+#define SUPPORTS_END_TO_END 1
+#endif
+
 // 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
 // than try a usleep.
-#define LOG_FAILURE_RETRY(exp) ({  \
-    typeof (exp) _rc;              \
-    do {                           \
-        _rc = (exp);               \
-    } while (((_rc == -1)          \
-           && ((errno == EINTR)    \
-            || (errno == EAGAIN))) \
-          || (_rc == -EINTR)       \
-          || (_rc == -EAGAIN));    \
-    _rc; })
-
-TEST(liblog, __android_log_buf_print) {
-    EXPECT_LT(0, __android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_print",
-                                         "radio"));
-    usleep(1000);
-    EXPECT_LT(0, __android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_print",
-                                         "system"));
-    usleep(1000);
-    EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_print",
-                                         "main"));
-    usleep(1000);
-}
-
-TEST(liblog, __android_log_buf_write) {
-    EXPECT_LT(0, __android_log_buf_write(LOG_ID_RADIO, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_write",
-                                         "radio"));
-    usleep(1000);
-    EXPECT_LT(0, __android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_write",
-                                         "system"));
-    usleep(1000);
-    EXPECT_LT(0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO,
-                                         "TEST__android_log_buf_write",
-                                         "main"));
-    usleep(1000);
-}
+#define LOG_FAILURE_RETRY(exp)                                           \
+  ({                                                                     \
+    typeof(exp) _rc;                                                     \
+    do {                                                                 \
+      _rc = (exp);                                                       \
+    } while (((_rc == -1) && ((errno == EINTR) || (errno == EAGAIN))) || \
+             (_rc == -EINTR) || (_rc == -EAGAIN));                       \
+    _rc;                                                                 \
+  })
 
 TEST(liblog, __android_log_btwrite) {
-    int intBuf = 0xDEADBEEF;
-    EXPECT_LT(0, __android_log_btwrite(0,
-                                      EVENT_TYPE_INT,
-                                      &intBuf, sizeof(intBuf)));
-    long long longBuf = 0xDEADBEEFA55A5AA5;
-    EXPECT_LT(0, __android_log_btwrite(0,
-                                      EVENT_TYPE_LONG,
-                                      &longBuf, sizeof(longBuf)));
-    usleep(1000);
-    char Buf[] = "\20\0\0\0DeAdBeEfA55a5aA5";
-    EXPECT_LT(0, __android_log_btwrite(0,
-                                      EVENT_TYPE_STRING,
-                                      Buf, sizeof(Buf) - 1));
-    usleep(1000);
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+#endif
+  int intBuf = 0xDEADBEEF;
+  EXPECT_LT(0,
+            __android_log_btwrite(0, EVENT_TYPE_INT, &intBuf, sizeof(intBuf)));
+  long long longBuf = 0xDEADBEEFA55A5AA5;
+  EXPECT_LT(
+      0, __android_log_btwrite(0, EVENT_TYPE_LONG, &longBuf, sizeof(longBuf)));
+  usleep(1000);
+  char Buf[] = "\20\0\0\0DeAdBeEfA55a5aA5";
+  EXPECT_LT(0,
+            __android_log_btwrite(0, EVENT_TYPE_STRING, Buf, sizeof(Buf) - 1));
+  usleep(1000);
 }
 
-static void* ConcurrentPrintFn(void *arg) {
-    int ret = __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
-                                  "TEST__android_log_print", "Concurrent %" PRIuPTR,
-                                  reinterpret_cast<uintptr_t>(arg));
-    return reinterpret_cast<void*>(ret);
+#if (defined(__ANDROID__) && defined(USING_LOGGER_DEFAULT))
+static std::string popenToString(std::string command) {
+  std::string ret;
+
+  FILE* fp = popen(command.c_str(), "r");
+  if (fp) {
+    if (!android::base::ReadFdToString(fileno(fp), &ret)) ret = "";
+    pclose(fp);
+  }
+  return ret;
 }
 
-#define NUM_CONCURRENT 64
-#define _concurrent_name(a,n) a##__concurrent##n
-#define concurrent_name(a,n) _concurrent_name(a,n)
+static bool isPmsgActive() {
+  pid_t pid = getpid();
 
-TEST(liblog, concurrent_name(__android_log_buf_print, NUM_CONCURRENT)) {
-    pthread_t t[NUM_CONCURRENT];
-    int i;
-    for (i=0; i < NUM_CONCURRENT; i++) {
-        ASSERT_EQ(0, pthread_create(&t[i], NULL,
-                                    ConcurrentPrintFn,
-                                    reinterpret_cast<void *>(i)));
-    }
-    int ret = 0;
-    for (i=0; i < NUM_CONCURRENT; i++) {
-        void* result;
-        ASSERT_EQ(0, pthread_join(t[i], &result));
-        int this_result = reinterpret_cast<uintptr_t>(result);
-        if ((0 == ret) && (0 != this_result)) {
-            ret = this_result;
-        }
-    }
-    ASSERT_LT(0, ret);
+  std::string myPidFds =
+      popenToString(android::base::StringPrintf("ls -l /proc/%d/fd", pid));
+  if (myPidFds.length() == 0) return true;  // guess it is?
+
+  return std::string::npos != myPidFds.find(" -> /dev/pmsg0");
 }
 
+static bool isLogdwActive() {
+  std::string logdwSignature =
+      popenToString("grep /dev/socket/logdw /proc/net/unix");
+  size_t beginning = logdwSignature.find(" ");
+  if (beginning == std::string::npos) return true;
+  beginning = logdwSignature.find(" ", beginning + 1);
+  if (beginning == std::string::npos) return true;
+  size_t end = logdwSignature.find(" ", beginning + 1);
+  if (end == std::string::npos) return true;
+  end = logdwSignature.find(" ", end + 1);
+  if (end == std::string::npos) return true;
+  end = logdwSignature.find(" ", end + 1);
+  if (end == std::string::npos) return true;
+  end = logdwSignature.find(" ", end + 1);
+  if (end == std::string::npos) return true;
+  std::string allLogdwEndpoints = popenToString(
+      "grep ' 00000002" + logdwSignature.substr(beginning, end - beginning) +
+      " ' /proc/net/unix | " +
+      "sed -n 's/.* \\([0-9][0-9]*\\)$/ -> socket:[\\1]/p'");
+  if (allLogdwEndpoints.length() == 0) return true;
+
+  // NB: allLogdwEndpoints has some false positives in it, but those
+  // strangers do not overlap with the simplistic activities inside this
+  // test suite.
+
+  pid_t pid = getpid();
+
+  std::string myPidFds =
+      popenToString(android::base::StringPrintf("ls -l /proc/%d/fd", pid));
+  if (myPidFds.length() == 0) return true;
+
+  // NB: fgrep with multiple strings is broken in Android
+  for (beginning = 0;
+       (end = allLogdwEndpoints.find("\n", beginning)) != std::string::npos;
+       beginning = end + 1) {
+    if (myPidFds.find(allLogdwEndpoints.substr(beginning, end - beginning)) !=
+        std::string::npos)
+      return true;
+  }
+  return false;
+}
+
+static bool tested__android_log_close;
+#endif
+
 TEST(liblog, __android_log_btwrite__android_logger_list_read) {
-    struct logger_list *logger_list;
+#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+#endif
+  struct logger_list* logger_list;
 
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
 
-    // Check that we can close and reopen the logger
-    log_time ts(CLOCK_MONOTONIC);
-    ASSERT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
-    __android_log_close();
+  log_time ts(CLOCK_MONOTONIC);
+  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+#ifdef USING_LOGGER_DEFAULT
+  // Check that we can close and reopen the logger
+  bool pmsgActiveAfter__android_log_btwrite;
+  bool logdwActiveAfter__android_log_btwrite;
+  if (getuid() == AID_ROOT) {
+    tested__android_log_close = true;
+    pmsgActiveAfter__android_log_btwrite = isPmsgActive();
+    logdwActiveAfter__android_log_btwrite = isLogdwActive();
+    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
+    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
+  } else if (!tested__android_log_close) {
+    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
+  }
+  __android_log_close();
+  if (getuid() == AID_ROOT) {
+    bool pmsgActiveAfter__android_log_close = isPmsgActive();
+    bool logdwActiveAfter__android_log_close = isLogdwActive();
+    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
+    EXPECT_FALSE(logdwActiveAfter__android_log_close);
+  }
+#endif
 
-    log_time ts1(CLOCK_MONOTONIC);
-    ASSERT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
-    usleep(1000000);
+  log_time ts1(CLOCK_MONOTONIC);
+  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
+#ifdef USING_LOGGER_DEFAULT
+  if (getuid() == AID_ROOT) {
+    pmsgActiveAfter__android_log_btwrite = isPmsgActive();
+    logdwActiveAfter__android_log_btwrite = isLogdwActive();
+    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
+    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
+  }
+#endif
+  usleep(1000000);
 
-    int count = 0;
-    int second_count = 0;
+  int count = 0;
+  int second_count = 0;
 
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.len != (4 + 1 + 8))
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        if (eventData[4] != EVENT_TYPE_LONG) {
-            continue;
-        }
-
-        log_time tx(eventData + 4 + 1);
-        if (ts == tx) {
-            ++count;
-        } else if (ts1 == tx) {
-            ++second_count;
-        }
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    EXPECT_EQ(1, count);
-    EXPECT_EQ(1, second_count);
+    EXPECT_EQ(log_msg.entry.pid, pid);
 
-    android_logger_list_close(logger_list);
-}
-
-static inline int32_t get4LE(const char* src)
-{
-    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
-}
-
-TEST(liblog, __android_log_bswrite) {
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    static const char buffer[] = "Hello World";
-    log_time ts(android_log_clockid());
-
-    ASSERT_LT(0, __android_log_bswrite(0, buffer));
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.sec < (ts.tv_sec - 1))
-         || ((ts.tv_sec + 1) < log_msg.entry.sec)
-         || (log_msg.entry.len != (4 + 1 + 4 + sizeof(buffer) - 1))
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        if (eventData[4] != EVENT_TYPE_STRING) {
-            continue;
-        }
-
-        int len = get4LE(eventData + 4 + 1);
-        if (len == (sizeof(buffer) - 1)) {
-            ++count;
-
-            AndroidLogFormat *logformat = android_log_format_new();
-            EXPECT_TRUE(NULL != logformat);
-            AndroidLogEntry entry;
-            char msgBuf[1024];
-            EXPECT_EQ(0, android_log_processBinaryLogBuffer(&log_msg.entry_v1,
-                                                            &entry,
-                                                            NULL,
-                                                            msgBuf,
-                                                            sizeof(msgBuf)));
-            fflush(stderr);
-            EXPECT_EQ(31, android_log_printLogLine(logformat, fileno(stderr), &entry));
-            android_log_format_free(logformat);
-        }
+    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
     }
 
-    EXPECT_EQ(1, count);
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
 
-    android_logger_list_close(logger_list);
-}
-
-TEST(liblog, __android_log_bswrite__empty_string) {
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    static const char buffer[] = "";
-    log_time ts(android_log_clockid());
-
-    ASSERT_LT(0, __android_log_bswrite(0, buffer));
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.sec < (ts.tv_sec - 1))
-         || ((ts.tv_sec + 1) < log_msg.entry.sec)
-         || (log_msg.entry.len != (4 + 1 + 4))
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        if (eventData[4] != EVENT_TYPE_STRING) {
-            continue;
-        }
-
-        int len = get4LE(eventData + 4 + 1);
-        if (len == 0) {
-            ++count;
-
-            AndroidLogFormat *logformat = android_log_format_new();
-            EXPECT_TRUE(NULL != logformat);
-            AndroidLogEntry entry;
-            char msgBuf[1024];
-            EXPECT_EQ(0, android_log_processBinaryLogBuffer(&log_msg.entry_v1,
-                                                            &entry,
-                                                            NULL,
-                                                            msgBuf,
-                                                            sizeof(msgBuf)));
-            fflush(stderr);
-            EXPECT_EQ(20, android_log_printLogLine(logformat, fileno(stderr), &entry));
-            android_log_format_free(logformat);
-        }
+    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
+      continue;
     }
 
-    EXPECT_EQ(1, count);
+    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
+    if (ts == tx) {
+      ++count;
+    } else if (ts1 == tx) {
+      ++second_count;
+    }
+  }
 
-    android_logger_list_close(logger_list);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+  EXPECT_EQ(SUPPORTS_END_TO_END, second_count);
+
+  android_logger_list_close(logger_list);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-TEST(liblog, __security) {
-    static const char persist_key[] = "persist.logd.security";
-    static const char readonly_key[] = "ro.device_owner";
-    static const char nothing_val[] = "_NOTHING_TO_SEE_HERE_";
-    char persist[PROP_VALUE_MAX];
-    char readonly[PROP_VALUE_MAX];
+#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
+static void print_transport(const char* prefix, int logger) {
+  static const char orstr[] = " | ";
 
-    property_get(persist_key, persist, "");
-    property_get(readonly_key, readonly, nothing_val);
+  if (!prefix) {
+    prefix = "";
+  }
+  if (logger < 0) {
+    fprintf(stderr, "%s%s\n", prefix, strerror(-logger));
+    return;
+  }
 
-    if (!strcmp(readonly, nothing_val)) {
-        EXPECT_FALSE(__android_log_security());
-        fprintf(stderr, "Warning, setting ro.device_owner to a domain\n");
-        property_set(readonly_key, "com.google.android.SecOps.DeviceOwner");
-    } else if (!strcasecmp(readonly, "false") || !readonly[0]) {
-        EXPECT_FALSE(__android_log_security());
-        return;
+  if (logger == LOGGER_DEFAULT) {
+    fprintf(stderr, "%sLOGGER_DEFAULT", prefix);
+    prefix = orstr;
+  }
+  if (logger & LOGGER_LOGD) {
+    fprintf(stderr, "%sLOGGER_LOGD", prefix);
+    prefix = orstr;
+  }
+  if (logger & LOGGER_KERNEL) {
+    fprintf(stderr, "%sLOGGER_KERNEL", prefix);
+    prefix = orstr;
+  }
+  if (logger & LOGGER_NULL) {
+    fprintf(stderr, "%sLOGGER_NULL", prefix);
+    prefix = orstr;
+  }
+  if (logger & LOGGER_LOCAL) {
+    fprintf(stderr, "%sLOGGER_LOCAL", prefix);
+    prefix = orstr;
+  }
+  if (logger & LOGGER_STDERR) {
+    fprintf(stderr, "%sLOGGER_STDERR", prefix);
+    prefix = orstr;
+  }
+  logger &= ~(LOGGER_LOGD | LOGGER_KERNEL | LOGGER_NULL | LOGGER_LOCAL |
+              LOGGER_STDERR);
+  if (logger) {
+    fprintf(stderr, "%s0x%x", prefix, logger);
+    prefix = orstr;
+  }
+  if (prefix == orstr) {
+    fprintf(stderr, "\n");
+  }
+}
+#endif
+
+// This test makes little sense standalone, and requires the tests ahead
+// and behind us, to make us whole.  We could incorporate a prefix and
+// suffix test to make this standalone, but opted to not complicate this.
+TEST(liblog, android_set_log_transport) {
+#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+#endif
+
+  int logger = android_get_log_transport();
+  print_transport("android_get_log_transport = ", logger);
+  EXPECT_NE(LOGGER_NULL, logger);
+
+  int ret;
+  EXPECT_EQ(LOGGER_NULL, ret = android_set_log_transport(LOGGER_NULL));
+  print_transport("android_set_log_transport = ", ret);
+  EXPECT_EQ(LOGGER_NULL, ret = android_get_log_transport());
+  print_transport("android_get_log_transport = ", ret);
+
+  pid_t pid = getpid();
+
+  struct logger_list* logger_list;
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
+
+  log_time ts(CLOCK_MONOTONIC);
+  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+
+  usleep(1000000);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    if (!strcasecmp(persist, "true")) {
-        EXPECT_TRUE(__android_log_security());
+    EXPECT_EQ(log_msg.entry.pid, pid);
+
+    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
+    }
+
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
+
+    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
+      continue;
+    }
+
+    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
+    if (ts == tx) {
+      ++count;
+    }
+  }
+
+  android_logger_list_close(logger_list);
+
+  EXPECT_EQ(logger, ret = android_set_log_transport(logger));
+  print_transport("android_set_log_transport = ", ret);
+  EXPECT_EQ(logger, ret = android_get_log_transport());
+  print_transport("android_get_log_transport = ", ret);
+
+  // False negative if liblog.__android_log_btwrite__android_logger_list_read
+  // fails above, so we will likely succeed. But we will have so many
+  // failures elsewhere that it is probably not worthwhile for us to
+  // highlight yet another disappointment.
+  //
+  // We also expect failures in the following tests if the set does not
+  // react in an appropriate manner internally, yet passes, so we depend
+  // on this test being in the middle of a series of tests performed in
+  // the same process.
+  EXPECT_EQ(0, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+#ifdef TEST_PREFIX
+static inline uint32_t get4LE(const uint8_t* src) {
+  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+}
+
+static inline uint32_t get4LE(const char* src) {
+  return get4LE(reinterpret_cast<const uint8_t*>(src));
+}
+#endif
+
+static void bswrite_test(const char* message) {
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  struct logger_list* logger_list;
+
+  pid_t pid = getpid();
+
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
+
+#ifdef __ANDROID__
+  log_time ts(android_log_clockid());
+#else
+  log_time ts(CLOCK_REALTIME);
+#endif
+
+  EXPECT_LT(0, __android_log_bswrite(0, message));
+  size_t num_lines = 1, size = 0, length = 0, total = 0;
+  const char* cp = message;
+  while (*cp) {
+    if (*cp == '\n') {
+      if (cp[1]) {
+        ++num_lines;
+      }
     } else {
-        EXPECT_FALSE(__android_log_security());
+      ++size;
     }
-    property_set(persist_key, "TRUE");
-    EXPECT_TRUE(__android_log_security());
-    property_set(persist_key, "FALSE");
-    EXPECT_FALSE(__android_log_security());
-    property_set(persist_key, "true");
-    EXPECT_TRUE(__android_log_security());
-    property_set(persist_key, "false");
-    EXPECT_FALSE(__android_log_security());
-    property_set(persist_key, "");
-    EXPECT_FALSE(__android_log_security());
-    property_set(persist_key, persist);
+    ++cp;
+    ++total;
+    ++length;
+    if ((LOGGER_ENTRY_MAX_PAYLOAD - 4 - 1 - 4) <= length) {
+      break;
+    }
+  }
+  while (*cp) {
+    ++cp;
+    ++total;
+  }
+  usleep(1000000);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
+    EXPECT_EQ(log_msg.entry.pid, pid);
+
+    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
+        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
+        ((size_t)log_msg.entry.len !=
+         (sizeof(android_log_event_string_t) + length)) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
+    }
+
+    android_log_event_string_t* eventData;
+    eventData = reinterpret_cast<android_log_event_string_t*>(log_msg.msg());
+
+    if (!eventData || (eventData->type != EVENT_TYPE_STRING)) {
+      continue;
+    }
+
+    size_t len = get4LE(reinterpret_cast<char*>(&eventData->length));
+    if (len == total) {
+      ++count;
+
+      AndroidLogFormat* logformat = android_log_format_new();
+      EXPECT_TRUE(NULL != logformat);
+      AndroidLogEntry entry;
+      char msgBuf[1024];
+      if (length != total) {
+        fprintf(stderr, "Expect \"Binary log entry conversion failed\"\n");
+      }
+      int processBinaryLogBuffer = android_log_processBinaryLogBuffer(
+          &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
+      EXPECT_EQ((length == total) ? 0 : -1, processBinaryLogBuffer);
+      if ((processBinaryLogBuffer == 0) || entry.message) {
+        size_t line_overhead = 20;
+        if (pid > 99999) ++line_overhead;
+        if (pid > 999999) ++line_overhead;
+        fflush(stderr);
+        if (processBinaryLogBuffer) {
+          EXPECT_GT((int)((line_overhead * num_lines) + size),
+                    android_log_printLogLine(logformat, fileno(stderr), &entry));
+        } else {
+          EXPECT_EQ((int)((line_overhead * num_lines) + size),
+                    android_log_printLogLine(logformat, fileno(stderr), &entry));
+        }
+      }
+      android_log_format_free(logformat);
+    }
+  }
+
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+
+  android_logger_list_close(logger_list);
+#else
+  message = NULL;
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-TEST(liblog, __security_buffer) {
-    struct logger_list *logger_list;
-    android_event_long_t buffer;
+TEST(liblog, __android_log_bswrite_and_print) {
+  bswrite_test("Hello World");
+}
 
-    static const char persist_key[] = "persist.logd.security";
-    char persist[PROP_VALUE_MAX];
-    bool set_persist = false;
-    bool allow_security = false;
+TEST(liblog, __android_log_bswrite_and_print__empty_string) {
+  bswrite_test("");
+}
 
-    if (__android_log_security()) {
-        allow_security = true;
+TEST(liblog, __android_log_bswrite_and_print__newline_prefix) {
+  bswrite_test("\nHello World\n");
+}
+
+TEST(liblog, __android_log_bswrite_and_print__newline_space_prefix) {
+  bswrite_test("\n Hello World \n");
+}
+
+TEST(liblog, __android_log_bswrite_and_print__multiple_newline) {
+  bswrite_test("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten");
+}
+
+static void buf_write_test(const char* message) {
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  struct logger_list* logger_list;
+
+  pid_t pid = getpid();
+
+  ASSERT_TRUE(
+      NULL !=
+      (logger_list = android_logger_list_open(
+           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+
+  static const char tag[] = "TEST__android_log_buf_write";
+#ifdef __ANDROID__
+  log_time ts(android_log_clockid());
+#else
+  log_time ts(CLOCK_REALTIME);
+#endif
+
+  EXPECT_LT(
+      0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO, tag, message));
+  size_t num_lines = 1, size = 0, length = 0;
+  const char* cp = message;
+  while (*cp) {
+    if (*cp == '\n') {
+      if (cp[1]) {
+        ++num_lines;
+      }
     } else {
-        property_get(persist_key, persist, "");
-        if (strcasecmp(persist, "true")) {
-            property_set(persist_key, "TRUE");
-            if (__android_log_security()) {
-                allow_security = true;
-                set_persist = true;
-            } else {
-                property_set(persist_key, persist);
-            }
-        }
+      ++size;
+    }
+    ++length;
+    if ((LOGGER_ENTRY_MAX_PAYLOAD - 2 - sizeof(tag)) <= length) {
+      break;
+    }
+    ++cp;
+  }
+  usleep(1000000);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    if (!allow_security) {
-        fprintf(stderr, "WARNING: "
-                "security buffer disabled, bypassing end-to-end test\n");
+    ASSERT_EQ(log_msg.entry.pid, pid);
 
-        log_time ts(CLOCK_MONOTONIC);
-
-        buffer.type = EVENT_TYPE_LONG;
-        buffer.data = *(static_cast<uint64_t *>((void *)&ts));
-
-        // expect failure!
-        ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
-
-        return;
+    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
+        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
+        ((size_t)log_msg.entry.len != (sizeof(tag) + length + 2)) ||
+        (log_msg.id() != LOG_ID_MAIN)) {
+      continue;
     }
 
-    /* Matches clientHasLogCredentials() in logd */
-    uid_t uid = getuid();
-    gid_t gid = getgid();
-    bool clientHasLogCredentials = true;
-    if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)
-     && (gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
-        uid_t euid = geteuid();
-        if ((euid != AID_SYSTEM) && (euid != AID_ROOT) && (euid != AID_LOG)) {
-            gid_t egid = getegid();
-            if ((egid != AID_SYSTEM) && (egid != AID_ROOT) && (egid != AID_LOG)) {
-                int num_groups = getgroups(0, NULL);
-                if (num_groups > 0) {
-                    gid_t groups[num_groups];
-                    num_groups = getgroups(num_groups, groups);
-                    while (num_groups > 0) {
-                        if (groups[num_groups - 1] == AID_LOG) {
-                            break;
-                        }
-                        --num_groups;
-                    }
-                }
-                if (num_groups <= 0) {
-                    clientHasLogCredentials = false;
-                }
-            }
-        }
+    ++count;
+
+    AndroidLogFormat* logformat = android_log_format_new();
+    EXPECT_TRUE(NULL != logformat);
+    AndroidLogEntry entry;
+    int processLogBuffer =
+        android_log_processLogBuffer(&log_msg.entry_v1, &entry);
+    EXPECT_EQ(0, processLogBuffer);
+    if (processLogBuffer == 0) {
+      size_t line_overhead = 11;
+      if (pid > 99999) ++line_overhead;
+      if (pid > 999999) ++line_overhead;
+      fflush(stderr);
+      EXPECT_EQ((int)(((line_overhead + sizeof(tag)) * num_lines) + size),
+                android_log_printLogLine(logformat, fileno(stderr), &entry));
     }
-    if (!clientHasLogCredentials) {
-        fprintf(stderr, "WARNING: "
-                "not in system context, bypassing end-to-end test\n");
+    android_log_format_free(logformat);
+  }
 
-        log_time ts(CLOCK_MONOTONIC);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
 
-        buffer.type = EVENT_TYPE_LONG;
-        buffer.data = *(static_cast<uint64_t *>((void *)&ts));
-
-        // expect failure!
-        ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
-
-        return;
-    }
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_SECURITY, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-        1000, pid)));
-
-    log_time ts(CLOCK_MONOTONIC);
-
-    buffer.type = EVENT_TYPE_LONG;
-    buffer.data = *(static_cast<uint64_t *>((void *)&ts));
-
-    ASSERT_LT(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.len != (4 + 1 + 8))
-         || (log_msg.id() != LOG_ID_SECURITY)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        if (eventData[4] != EVENT_TYPE_LONG) {
-            continue;
-        }
-
-        log_time tx(eventData + 4 + 1);
-        if (ts == tx) {
-            ++count;
-        }
-    }
-
-    if (set_persist) {
-        property_set(persist_key, persist);
-    }
-
-    android_logger_list_close(logger_list);
-
-    bool clientHasSecurityCredentials = (uid == AID_SYSTEM) || (gid == AID_SYSTEM);
-    if (!clientHasSecurityCredentials) {
-        fprintf(stderr, "WARNING: "
-                "not system, content submitted but can not check end-to-end\n");
-    }
-    EXPECT_EQ(clientHasSecurityCredentials ? 1 : 0, count);
-
+  android_logger_list_close(logger_list);
+#else
+  message = NULL;
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+TEST(liblog, __android_log_buf_write_and_print__empty) {
+  buf_write_test("");
+}
+
+TEST(liblog, __android_log_buf_write_and_print__newline_prefix) {
+  buf_write_test("\nHello World\n");
+}
+
+TEST(liblog, __android_log_buf_write_and_print__newline_space_prefix) {
+  buf_write_test("\n Hello World \n");
+}
+
+#ifndef USING_LOGGER_LOCAL  // requires blocking reader functionality
+#ifdef TEST_PREFIX
 static unsigned signaled;
 static log_time signal_time;
 
@@ -487,143 +635,151 @@
  * should catch any regressions in that effort. The odds of a logged message
  * in a signal handler causing a lockup problem should be _very_ small.
  */
-static void caught_blocking_signal(int /*signum*/)
-{
-    unsigned long long v = 0xDEADBEEFA55A0000ULL;
+static void caught_blocking_signal(int /*signum*/) {
+  unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
-    v += getpid() & 0xFFFF;
+  v += getpid() & 0xFFFF;
 
-    ++signaled;
-    if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
-        signal_time = log_time(CLOCK_MONOTONIC);
-        signal_time.tv_sec += 2;
-    }
+  ++signaled;
+  if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
+    signal_time = log_time(CLOCK_MONOTONIC);
+    signal_time.tv_sec += 2;
+  }
 
-    LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 }
 
 // Fill in current process user and system time in 10ms increments
-static void get_ticks(unsigned long long *uticks, unsigned long long *sticks)
-{
+static void get_ticks(unsigned long long* uticks, unsigned long long* sticks) {
+  *uticks = *sticks = 0;
+
+  pid_t pid = getpid();
+
+  char buffer[512];
+  snprintf(buffer, sizeof(buffer), "/proc/%u/stat", pid);
+
+  FILE* fp = fopen(buffer, "r");
+  if (!fp) {
+    return;
+  }
+
+  char* cp = fgets(buffer, sizeof(buffer), fp);
+  fclose(fp);
+  if (!cp) {
+    return;
+  }
+
+  pid_t d;
+  char s[sizeof(buffer)];
+  char c;
+  long long ll;
+  unsigned long long ull;
+
+  if (15 != sscanf(buffer,
+                   "%d %s %c %lld %lld %lld %lld %lld %llu %llu %llu %llu %llu "
+                   "%llu %llu ",
+                   &d, s, &c, &ll, &ll, &ll, &ll, &ll, &ull, &ull, &ull, &ull,
+                   &ull, uticks, sticks)) {
     *uticks = *sticks = 0;
-
-    pid_t pid = getpid();
-
-    char buffer[512];
-    snprintf(buffer, sizeof(buffer), "/proc/%u/stat", pid);
-
-    FILE *fp = fopen(buffer, "r");
-    if (!fp) {
-        return;
-    }
-
-    char *cp = fgets(buffer, sizeof(buffer), fp);
-    fclose(fp);
-    if (!cp) {
-        return;
-    }
-
-    pid_t d;
-    char s[sizeof(buffer)];
-    char c;
-    long long ll;
-    unsigned long long ull;
-
-    if (15 != sscanf(buffer,
-      "%d %s %c %lld %lld %lld %lld %lld %llu %llu %llu %llu %llu %llu %llu ",
-      &d, s, &c, &ll, &ll, &ll, &ll, &ll, &ull, &ull, &ull, &ull, &ull,
-      uticks, sticks)) {
-        *uticks = *sticks = 0;
-    }
+  }
 }
+#endif
 
 TEST(liblog, android_logger_list_read__cpu_signal) {
-    struct logger_list *logger_list;
-    unsigned long long v = 0xDEADBEEFA55A0000ULL;
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  struct logger_list* logger_list;
+  unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    v += pid & 0xFFFF;
+  v += pid & 0xFFFF;
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));
+  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
+                           LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));
 
-    int count = 0;
+  int count = 0;
 
-    int signals = 0;
+  int signals = 0;
 
-    unsigned long long uticks_start;
-    unsigned long long sticks_start;
-    get_ticks(&uticks_start, &sticks_start);
+  unsigned long long uticks_start;
+  unsigned long long sticks_start;
+  get_ticks(&uticks_start, &sticks_start);
 
-    const unsigned alarm_time = 10;
+  const unsigned alarm_time = 10;
 
-    memset(&signal_time, 0, sizeof(signal_time));
+  memset(&signal_time, 0, sizeof(signal_time));
 
-    signal(SIGALRM, caught_blocking_signal);
+  signal(SIGALRM, caught_blocking_signal);
+  alarm(alarm_time);
+
+  signaled = 0;
+
+  do {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
     alarm(alarm_time);
 
-    signaled = 0;
+    ++count;
 
-    do {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
+    ASSERT_EQ(log_msg.entry.pid, pid);
 
-        alarm(alarm_time);
+    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
+    }
 
-        ++count;
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
 
-        ASSERT_EQ(log_msg.entry.pid, pid);
+    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
+      continue;
+    }
 
-        if ((log_msg.entry.len != (4 + 1 + 8))
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
+    char* cp = reinterpret_cast<char*>(&eventData->payload.data);
+    unsigned long long l = cp[0] & 0xFF;
+    l |= (unsigned long long)(cp[1] & 0xFF) << 8;
+    l |= (unsigned long long)(cp[2] & 0xFF) << 16;
+    l |= (unsigned long long)(cp[3] & 0xFF) << 24;
+    l |= (unsigned long long)(cp[4] & 0xFF) << 32;
+    l |= (unsigned long long)(cp[5] & 0xFF) << 40;
+    l |= (unsigned long long)(cp[6] & 0xFF) << 48;
+    l |= (unsigned long long)(cp[7] & 0xFF) << 56;
 
-        char *eventData = log_msg.msg();
+    if (l == v) {
+      ++signals;
+      break;
+    }
+  } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
+  alarm(0);
+  signal(SIGALRM, SIG_DFL);
 
-        if (eventData[4] != EVENT_TYPE_LONG) {
-            continue;
-        }
+  EXPECT_LE(1, count);
 
-        unsigned long long l = eventData[4 + 1 + 0] & 0xFF;
-        l |= (unsigned long long) (eventData[4 + 1 + 1] & 0xFF) << 8;
-        l |= (unsigned long long) (eventData[4 + 1 + 2] & 0xFF) << 16;
-        l |= (unsigned long long) (eventData[4 + 1 + 3] & 0xFF) << 24;
-        l |= (unsigned long long) (eventData[4 + 1 + 4] & 0xFF) << 32;
-        l |= (unsigned long long) (eventData[4 + 1 + 5] & 0xFF) << 40;
-        l |= (unsigned long long) (eventData[4 + 1 + 6] & 0xFF) << 48;
-        l |= (unsigned long long) (eventData[4 + 1 + 7] & 0xFF) << 56;
+  EXPECT_EQ(1, signals);
 
-        if (l == v) {
-            ++signals;
-            break;
-        }
-    } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
-    alarm(0);
-    signal(SIGALRM, SIG_DFL);
+  android_logger_list_close(logger_list);
 
-    EXPECT_LE(1, count);
+  unsigned long long uticks_end;
+  unsigned long long sticks_end;
+  get_ticks(&uticks_end, &sticks_end);
 
-    EXPECT_EQ(1, signals);
-
-    android_logger_list_close(logger_list);
-
-    unsigned long long uticks_end;
-    unsigned long long sticks_end;
-    get_ticks(&uticks_end, &sticks_end);
-
-    // Less than 1% in either user or system time, or both
-    const unsigned long long one_percent_ticks = alarm_time;
-    unsigned long long user_ticks = uticks_end - uticks_start;
-    unsigned long long system_ticks = sticks_end - sticks_start;
-    EXPECT_GT(one_percent_ticks, user_ticks);
-    EXPECT_GT(one_percent_ticks, system_ticks);
-    EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+  // Less than 1% in either user or system time, or both
+  const unsigned long long one_percent_ticks = alarm_time;
+  unsigned long long user_ticks = uticks_end - uticks_start;
+  unsigned long long system_ticks = sticks_end - sticks_start;
+  EXPECT_GT(one_percent_ticks, user_ticks);
+  EXPECT_GT(one_percent_ticks, system_ticks);
+  EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef TEST_PREFIX
 /*
  *  Strictly, we are not allowed to log messages in a signal context, the
  * correct way to handle this is to ensure the messages are constructed in
@@ -631,154 +787,164 @@
  */
 static sem_t thread_trigger;
 
-static void caught_blocking_thread(int /*signum*/)
-{
-    sem_post(&thread_trigger);
+static void caught_blocking_thread(int /*signum*/) {
+  sem_post(&thread_trigger);
 }
 
-static void *running_thread(void *) {
-    unsigned long long v = 0xDEADBEAFA55A0000ULL;
+static void* running_thread(void*) {
+  unsigned long long v = 0xDEADBEAFA55A0000ULL;
 
-    v += getpid() & 0xFFFF;
+  v += getpid() & 0xFFFF;
 
-    struct timespec timeout;
-    clock_gettime(CLOCK_REALTIME, &timeout);
-    timeout.tv_sec += 55;
-    sem_timedwait(&thread_trigger, &timeout);
+  struct timespec timeout;
+  clock_gettime(CLOCK_REALTIME, &timeout);
+  timeout.tv_sec += 55;
+  sem_timedwait(&thread_trigger, &timeout);
 
-    ++signaled;
-    if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
-        signal_time = log_time(CLOCK_MONOTONIC);
-        signal_time.tv_sec += 2;
-    }
+  ++signaled;
+  if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
+    signal_time = log_time(CLOCK_MONOTONIC);
+    signal_time.tv_sec += 2;
+  }
 
-    LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 
-    return NULL;
+  return NULL;
 }
 
-int start_thread()
-{
-    sem_init(&thread_trigger, 0, 0);
+static int start_thread() {
+  sem_init(&thread_trigger, 0, 0);
 
-    pthread_attr_t attr;
-    if (pthread_attr_init(&attr)) {
-        return -1;
-    }
+  pthread_attr_t attr;
+  if (pthread_attr_init(&attr)) {
+    return -1;
+  }
 
-    struct sched_param param;
+  struct sched_param param;
 
-    memset(&param, 0, sizeof(param));
-    pthread_attr_setschedparam(&attr, &param);
-    pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
+  memset(&param, 0, sizeof(param));
+  pthread_attr_setschedparam(&attr, &param);
+  pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
 
-    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
-        pthread_attr_destroy(&attr);
-        return -1;
-    }
-
-    pthread_t thread;
-    if (pthread_create(&thread, &attr, running_thread, NULL)) {
-        pthread_attr_destroy(&attr);
-        return -1;
-    }
-
+  if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
     pthread_attr_destroy(&attr);
-    return 0;
+    return -1;
+  }
+
+  pthread_t thread;
+  if (pthread_create(&thread, &attr, running_thread, NULL)) {
+    pthread_attr_destroy(&attr);
+    return -1;
+  }
+
+  pthread_attr_destroy(&attr);
+  return 0;
 }
+#endif
 
 TEST(liblog, android_logger_list_read__cpu_thread) {
-    struct logger_list *logger_list;
-    unsigned long long v = 0xDEADBEAFA55A0000ULL;
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  struct logger_list* logger_list;
+  unsigned long long v = 0xDEADBEAFA55A0000ULL;
 
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    v += pid & 0xFFFF;
+  v += pid & 0xFFFF;
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));
+  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
+                           LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));
 
-    int count = 0;
+  int count = 0;
 
-    int signals = 0;
+  int signals = 0;
 
-    unsigned long long uticks_start;
-    unsigned long long sticks_start;
-    get_ticks(&uticks_start, &sticks_start);
+  unsigned long long uticks_start;
+  unsigned long long sticks_start;
+  get_ticks(&uticks_start, &sticks_start);
 
-    const unsigned alarm_time = 10;
+  const unsigned alarm_time = 10;
 
-    memset(&signal_time, 0, sizeof(signal_time));
+  memset(&signal_time, 0, sizeof(signal_time));
 
-    signaled = 0;
-    EXPECT_EQ(0, start_thread());
+  signaled = 0;
+  EXPECT_EQ(0, start_thread());
 
-    signal(SIGALRM, caught_blocking_thread);
+  signal(SIGALRM, caught_blocking_thread);
+  alarm(alarm_time);
+
+  do {
+    log_msg log_msg;
+    if (LOG_FAILURE_RETRY(android_logger_list_read(logger_list, &log_msg)) <= 0) {
+      break;
+    }
+
     alarm(alarm_time);
 
-    do {
-        log_msg log_msg;
-        if (LOG_FAILURE_RETRY(android_logger_list_read(logger_list, &log_msg)) <= 0) {
-            break;
-        }
+    ++count;
 
-        alarm(alarm_time);
+    ASSERT_EQ(log_msg.entry.pid, pid);
 
-        ++count;
+    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
+    }
 
-        ASSERT_EQ(log_msg.entry.pid, pid);
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
 
-        if ((log_msg.entry.len != (4 + 1 + 8))
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
+    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
+      continue;
+    }
 
-        char *eventData = log_msg.msg();
+    char* cp = reinterpret_cast<char*>(&eventData->payload.data);
+    unsigned long long l = cp[0] & 0xFF;
+    l |= (unsigned long long)(cp[1] & 0xFF) << 8;
+    l |= (unsigned long long)(cp[2] & 0xFF) << 16;
+    l |= (unsigned long long)(cp[3] & 0xFF) << 24;
+    l |= (unsigned long long)(cp[4] & 0xFF) << 32;
+    l |= (unsigned long long)(cp[5] & 0xFF) << 40;
+    l |= (unsigned long long)(cp[6] & 0xFF) << 48;
+    l |= (unsigned long long)(cp[7] & 0xFF) << 56;
 
-        if (eventData[4] != EVENT_TYPE_LONG) {
-            continue;
-        }
+    if (l == v) {
+      ++signals;
+      break;
+    }
+  } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
+  alarm(0);
+  signal(SIGALRM, SIG_DFL);
 
-        unsigned long long l = eventData[4 + 1 + 0] & 0xFF;
-        l |= (unsigned long long) (eventData[4 + 1 + 1] & 0xFF) << 8;
-        l |= (unsigned long long) (eventData[4 + 1 + 2] & 0xFF) << 16;
-        l |= (unsigned long long) (eventData[4 + 1 + 3] & 0xFF) << 24;
-        l |= (unsigned long long) (eventData[4 + 1 + 4] & 0xFF) << 32;
-        l |= (unsigned long long) (eventData[4 + 1 + 5] & 0xFF) << 40;
-        l |= (unsigned long long) (eventData[4 + 1 + 6] & 0xFF) << 48;
-        l |= (unsigned long long) (eventData[4 + 1 + 7] & 0xFF) << 56;
+  EXPECT_LE(1, count);
 
-        if (l == v) {
-            ++signals;
-            break;
-        }
-    } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
-    alarm(0);
-    signal(SIGALRM, SIG_DFL);
+  EXPECT_EQ(1, signals);
 
-    EXPECT_LE(1, count);
+  android_logger_list_close(logger_list);
 
-    EXPECT_EQ(1, signals);
+  unsigned long long uticks_end;
+  unsigned long long sticks_end;
+  get_ticks(&uticks_end, &sticks_end);
 
-    android_logger_list_close(logger_list);
-
-    unsigned long long uticks_end;
-    unsigned long long sticks_end;
-    get_ticks(&uticks_end, &sticks_end);
-
-    // Less than 1% in either user or system time, or both
-    const unsigned long long one_percent_ticks = alarm_time;
-    unsigned long long user_ticks = uticks_end - uticks_start;
-    unsigned long long system_ticks = sticks_end - sticks_start;
-    EXPECT_GT(one_percent_ticks, user_ticks);
-    EXPECT_GT(one_percent_ticks, system_ticks);
-    EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+  // Less than 1% in either user or system time, or both
+  const unsigned long long one_percent_ticks = alarm_time;
+  unsigned long long user_ticks = uticks_end - uticks_start;
+  unsigned long long system_ticks = sticks_end - sticks_start;
+  EXPECT_GT(one_percent_ticks, user_ticks);
+  EXPECT_GT(one_percent_ticks, system_ticks);
+  EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
+#endif  // !USING_LOGGER_LOCAL
 
-static const char max_payload_tag[] = "TEST_max_payload_XXXX";
-#define SIZEOF_MAX_PAYLOAD_BUF (LOGGER_ENTRY_MAX_PAYLOAD - \
-                                sizeof(max_payload_tag) - 1)
-static const char max_payload_buf[] = "LEONATO\n\
+#ifdef TEST_PREFIX
+static const char max_payload_tag[] = "TEST_max_payload_and_longish_tag_XXXX";
+#define SIZEOF_MAX_PAYLOAD_BUF \
+  (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(max_payload_tag) - 1)
+#endif
+static const char max_payload_buf[] =
+    "LEONATO\n\
 I learn in this letter that Don Peter of Arragon\n\
 comes this night to Messina\n\
 MESSENGER\n\
@@ -910,316 +1076,343 @@
 takes his leave.";
 
 TEST(liblog, max_payload) {
-    pid_t pid = getpid();
-    char tag[sizeof(max_payload_tag)];
-    memcpy(tag, max_payload_tag, sizeof(tag));
-    snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  pid_t pid = getpid();
+  char tag[sizeof(max_payload_tag)];
+  memcpy(tag, max_payload_tag, sizeof(tag));
+  snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
 
-    LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
-                                              tag, max_payload_buf));
-    sleep(2);
+  LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
+                                            tag, max_payload_buf));
+  sleep(2);
 
-    struct logger_list *logger_list;
+  struct logger_list* logger_list;
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_SYSTEM, ANDROID_LOG_RDONLY, 100, 0)));
+  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
+                           LOG_ID_SYSTEM, ANDROID_LOG_RDONLY, 100, 0)));
 
-    bool matches = false;
-    ssize_t max_len = 0;
+  bool matches = false;
+  ssize_t max_len = 0;
 
-    for(;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
-            continue;
-        }
-
-        char *data = log_msg.msg() + 1;
-
-        if (strcmp(data, tag)) {
-            continue;
-        }
-
-        data += strlen(data) + 1;
-
-        const char *left = data;
-        const char *right = max_payload_buf;
-        while (*left && *right && (*left == *right)) {
-            ++left;
-            ++right;
-        }
-
-        if (max_len <= (left - data)) {
-            max_len = left - data + 1;
-        }
-
-        if (max_len > 512) {
-            matches = true;
-            break;
-        }
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    android_logger_list_close(logger_list);
+    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
+      continue;
+    }
 
-    EXPECT_EQ(true, matches);
+    char* data = log_msg.msg();
 
-    EXPECT_LE(SIZEOF_MAX_PAYLOAD_BUF, static_cast<size_t>(max_len));
+    if (!data || strcmp(++data, tag)) {
+      continue;
+    }
+
+    data += strlen(data) + 1;
+
+    const char* left = data;
+    const char* right = max_payload_buf;
+    while (*left && *right && (*left == *right)) {
+      ++left;
+      ++right;
+    }
+
+    if (max_len <= (left - data)) {
+      max_len = left - data + 1;
+    }
+
+    if (max_len > 512) {
+      matches = true;
+      break;
+    }
+  }
+
+  android_logger_list_close(logger_list);
+
+#if SUPPORTS_END_TO_END
+  EXPECT_EQ(true, matches);
+
+  EXPECT_LE(SIZEOF_MAX_PAYLOAD_BUF, static_cast<size_t>(max_len));
+#else
+  EXPECT_EQ(false, matches);
+#endif
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_buf_print__maxtag) {
-    struct logger_list *logger_list;
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  struct logger_list* logger_list;
 
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+  ASSERT_TRUE(
+      NULL !=
+      (logger_list = android_logger_list_open(
+           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
 
-    log_time ts(android_log_clockid());
+#ifdef __ANDROID__
+  log_time ts(android_log_clockid());
+#else
+  log_time ts(CLOCK_REALTIME);
+#endif
 
-    EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
-                                         max_payload_buf, max_payload_buf));
-    usleep(1000000);
+  EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
+                                       max_payload_buf, max_payload_buf));
+  usleep(1000000);
 
-    int count = 0;
+  int count = 0;
 
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.sec < (ts.tv_sec - 1))
-         || ((ts.tv_sec + 1) < log_msg.entry.sec)
-         || ((size_t)log_msg.entry.len < LOGGER_ENTRY_MAX_PAYLOAD)
-         || (log_msg.id() != LOG_ID_MAIN)) {
-            continue;
-        }
-
-        ++count;
-
-        AndroidLogFormat *logformat = android_log_format_new();
-        EXPECT_TRUE(NULL != logformat);
-        AndroidLogEntry entry;
-        int processLogBuffer = android_log_processLogBuffer(&log_msg.entry_v1,
-                                                            &entry);
-        EXPECT_EQ(0, processLogBuffer);
-        if (processLogBuffer == 0) {
-            fflush(stderr);
-            int printLogLine =
-                    android_log_printLogLine(logformat, fileno(stderr), &entry);
-            // Legacy tag truncation
-            EXPECT_LE(128, printLogLine);
-            // Measured maximum if we try to print part of the tag as message
-            EXPECT_GT(LOGGER_ENTRY_MAX_PAYLOAD * 13 / 8, printLogLine);
-        }
-        android_log_format_free(logformat);
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    EXPECT_EQ(1, count);
+    ASSERT_EQ(log_msg.entry.pid, pid);
 
-    android_logger_list_close(logger_list);
+    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
+        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
+        ((size_t)log_msg.entry.len < LOGGER_ENTRY_MAX_PAYLOAD) ||
+        (log_msg.id() != LOG_ID_MAIN)) {
+      continue;
+    }
+
+    ++count;
+
+    AndroidLogFormat* logformat = android_log_format_new();
+    EXPECT_TRUE(NULL != logformat);
+    AndroidLogEntry entry;
+    int processLogBuffer =
+        android_log_processLogBuffer(&log_msg.entry_v1, &entry);
+    EXPECT_EQ(0, processLogBuffer);
+    if (processLogBuffer == 0) {
+      fflush(stderr);
+      int printLogLine =
+          android_log_printLogLine(logformat, fileno(stderr), &entry);
+      // Legacy tag truncation
+      EXPECT_LE(128, printLogLine);
+      // Measured maximum if we try to print part of the tag as message
+      EXPECT_GT(LOGGER_ENTRY_MAX_PAYLOAD * 13 / 8, printLogLine);
+    }
+    android_log_format_free(logformat);
+  }
+
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+
+  android_logger_list_close(logger_list);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, too_big_payload) {
-    pid_t pid = getpid();
-    static const char big_payload_tag[] = "TEST_big_payload_XXXX";
-    char tag[sizeof(big_payload_tag)];
-    memcpy(tag, big_payload_tag, sizeof(tag));
-    snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  pid_t pid = getpid();
+  static const char big_payload_tag[] = "TEST_big_payload_XXXX";
+  char tag[sizeof(big_payload_tag)];
+  memcpy(tag, big_payload_tag, sizeof(tag));
+  snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
 
-    std::string longString(3266519, 'x');
+  std::string longString(3266519, 'x');
 
-    ssize_t ret = LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_SYSTEM,
-                                    ANDROID_LOG_INFO, tag, longString.c_str()));
+  ssize_t ret = LOG_FAILURE_RETRY(__android_log_buf_write(
+      LOG_ID_SYSTEM, ANDROID_LOG_INFO, tag, longString.c_str()));
 
-    struct logger_list *logger_list;
+  struct logger_list* logger_list;
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_SYSTEM, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 100, 0)));
+  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
+                           LOG_ID_SYSTEM,
+                           ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 100, 0)));
 
-    ssize_t max_len = 0;
+  ssize_t max_len = 0;
 
-    for(;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
-            continue;
-        }
-
-        char *data = log_msg.msg() + 1;
-
-        if (strcmp(data, tag)) {
-            continue;
-        }
-
-        data += strlen(data) + 1;
-
-        const char *left = data;
-        const char *right = longString.c_str();
-        while (*left && *right && (*left == *right)) {
-            ++left;
-            ++right;
-        }
-
-        if (max_len <= (left - data)) {
-            max_len = left - data + 1;
-        }
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
     }
 
-    android_logger_list_close(logger_list);
+    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
+      continue;
+    }
 
-    EXPECT_LE(LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag),
-              static_cast<size_t>(max_len));
+    char* data = log_msg.msg();
 
-    EXPECT_EQ(ret, max_len + static_cast<ssize_t>(sizeof(big_payload_tag)));
+    if (!data || strcmp(++data, tag)) {
+      continue;
+    }
+
+    data += strlen(data) + 1;
+
+    const char* left = data;
+    const char* right = longString.c_str();
+    while (*left && *right && (*left == *right)) {
+      ++left;
+      ++right;
+    }
+
+    if (max_len <= (left - data)) {
+      max_len = left - data + 1;
+    }
+  }
+
+  android_logger_list_close(logger_list);
+
+#if !SUPPORTS_END_TO_END
+  max_len =
+      max_len ? max_len : LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag);
+#endif
+  EXPECT_LE(LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag),
+            static_cast<size_t>(max_len));
+
+  // SLOP: Allow the underlying interface to optionally place a
+  // terminating nul at the LOGGER_ENTRY_MAX_PAYLOAD's last byte
+  // or not.
+  if (ret == (max_len + static_cast<ssize_t>(sizeof(big_payload_tag)) - 1)) {
+    --max_len;
+  }
+  EXPECT_EQ(ret, max_len + static_cast<ssize_t>(sizeof(big_payload_tag)));
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, dual_reader) {
-    struct logger_list *logger_list1;
+#ifdef TEST_PREFIX
+  TEST_PREFIX
 
-    // >25 messages due to liblog.__android_log_buf_print__concurrentXX above.
-    ASSERT_TRUE(NULL != (logger_list1 = android_logger_list_open(
-        LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 25, 0)));
+  static const int num = 25;
 
-    struct logger_list *logger_list2;
+  for (int i = 25; i > 0; --i) {
+    static const char fmt[] = "dual_reader %02d";
+    char buffer[sizeof(fmt) + 8];
+    snprintf(buffer, sizeof(buffer), fmt, i);
+    LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO,
+                                              "liblog", buffer));
+  }
+  usleep(1000000);
 
-    if (NULL == (logger_list2 = android_logger_list_open(
-            LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 15, 0))) {
-        android_logger_list_close(logger_list1);
-        ASSERT_TRUE(NULL != logger_list2);
-    }
+  struct logger_list* logger_list1;
+  ASSERT_TRUE(NULL != (logger_list1 = android_logger_list_open(
+                           LOG_ID_MAIN,
+                           ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, num, 0)));
 
-    int count1 = 0;
-    bool done1 = false;
-    int count2 = 0;
-    bool done2 = false;
+  struct logger_list* logger_list2;
 
-    do {
-        log_msg log_msg;
-
-        if (!done1) {
-            if (android_logger_list_read(logger_list1, &log_msg) <= 0) {
-                done1 = true;
-            } else {
-                ++count1;
-            }
-        }
-
-        if (!done2) {
-            if (android_logger_list_read(logger_list2, &log_msg) <= 0) {
-                done2 = true;
-            } else {
-                ++count2;
-            }
-        }
-    } while ((!done1) || (!done2));
-
+  if (NULL == (logger_list2 = android_logger_list_open(
+                   LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   num - 10, 0))) {
     android_logger_list_close(logger_list1);
-    android_logger_list_close(logger_list2);
+    ASSERT_TRUE(NULL != logger_list2);
+  }
 
-    EXPECT_EQ(25, count1);
-    EXPECT_EQ(15, count2);
-}
+  int count1 = 0;
+  bool done1 = false;
+  int count2 = 0;
+  bool done2 = false;
 
-TEST(liblog, android_logger_get_) {
-    struct logger_list * logger_list = android_logger_list_alloc(ANDROID_LOG_WRONLY, 0, 0);
+  do {
+    log_msg log_msg;
 
-    for(int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
-        log_id_t id = static_cast<log_id_t>(i);
-        const char *name = android_log_id_to_name(id);
-        if (id != android_name_to_log_id(name)) {
-            continue;
-        }
-        fprintf(stderr, "log buffer %s\r", name);
-        struct logger * logger;
-        EXPECT_TRUE(NULL != (logger = android_logger_open(logger_list, id)));
-        EXPECT_EQ(id, android_logger_get_id(logger));
-        ssize_t get_log_size = android_logger_get_log_size(logger);
-        /* security buffer is allowed to be denied */
-        if (strcmp("security", name)) {
-            EXPECT_LT(0, get_log_size);
-            /* crash buffer is allowed to be empty, that is actually healthy! */
-            EXPECT_LE((strcmp("crash", name)) != 0,
-                      android_logger_get_log_readable_size(logger));
-        } else {
-            EXPECT_NE(0, get_log_size);
-            if (get_log_size < 0) {
-                EXPECT_GT(0, android_logger_get_log_readable_size(logger));
-            } else {
-                EXPECT_LE(0, android_logger_get_log_readable_size(logger));
-            }
-        }
-        EXPECT_LT(0, android_logger_get_log_version(logger));
+    if (!done1) {
+      if (android_logger_list_read(logger_list1, &log_msg) <= 0) {
+        done1 = true;
+      } else {
+        ++count1;
+      }
     }
 
-    android_logger_list_close(logger_list);
+    if (!done2) {
+      if (android_logger_list_read(logger_list2, &log_msg) <= 0) {
+        done2 = true;
+      } else {
+        ++count2;
+      }
+    }
+  } while ((!done1) || (!done2));
+
+  android_logger_list_close(logger_list1);
+  android_logger_list_close(logger_list2);
+
+  EXPECT_EQ(num * SUPPORTS_END_TO_END, count1);
+  EXPECT_EQ((num - 10) * SUPPORTS_END_TO_END, count2);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-static bool checkPriForTag(AndroidLogFormat *p_format, const char *tag, android_LogPriority pri) {
-    return android_log_shouldPrintLine(p_format, tag, pri)
-        && !android_log_shouldPrintLine(p_format, tag, (android_LogPriority)(pri - 1));
+#ifdef USING_LOGGER_DEFAULT  // Do not retest logprint
+static bool checkPriForTag(AndroidLogFormat* p_format, const char* tag,
+                           android_LogPriority pri) {
+  return android_log_shouldPrintLine(p_format, tag, pri) &&
+         !android_log_shouldPrintLine(p_format, tag,
+                                      (android_LogPriority)(pri - 1));
 }
 
 TEST(liblog, filterRule) {
-    static const char tag[] = "random";
+  static const char tag[] = "random";
 
-    AndroidLogFormat *p_format = android_log_format_new();
+  AndroidLogFormat* p_format = android_log_format_new();
 
-    android_log_addFilterRule(p_format,"*:i");
+  android_log_addFilterRule(p_format, "*:i");
 
-    EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
-    android_log_addFilterRule(p_format, "*");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
-    android_log_addFilterRule(p_format, "*:v");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
-    android_log_addFilterRule(p_format, "*:i");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
+              0);
+  android_log_addFilterRule(p_format, "*");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
+  android_log_addFilterRule(p_format, "*:v");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
+  android_log_addFilterRule(p_format, "*:i");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
+              0);
 
-    android_log_addFilterRule(p_format, tag);
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
-    android_log_addFilterRule(p_format, "random:v");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
-    android_log_addFilterRule(p_format, "random:d");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
-    android_log_addFilterRule(p_format, "random:w");
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
+  android_log_addFilterRule(p_format, tag);
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
+  android_log_addFilterRule(p_format, "random:v");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
+  android_log_addFilterRule(p_format, "random:d");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
+  android_log_addFilterRule(p_format, "random:w");
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
+              0);
 
-    android_log_addFilterRule(p_format, "crap:*");
-    EXPECT_TRUE (checkPriForTag(p_format, "crap", ANDROID_LOG_VERBOSE));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);
+  android_log_addFilterRule(p_format, "crap:*");
+  EXPECT_TRUE(checkPriForTag(p_format, "crap", ANDROID_LOG_VERBOSE));
+  EXPECT_TRUE(
+      android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);
 
-    // invalid expression
-    EXPECT_TRUE (android_log_addFilterRule(p_format, "random:z") < 0);
-    EXPECT_TRUE (checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
-    EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) == 0);
+  // invalid expression
+  EXPECT_TRUE(android_log_addFilterRule(p_format, "random:z") < 0);
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
+  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
+              0);
 
-    // Issue #550946
-    EXPECT_TRUE(android_log_addFilterString(p_format, " ") == 0);
-    EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
+  // Issue #550946
+  EXPECT_TRUE(android_log_addFilterString(p_format, " ") == 0);
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
 
-    // note trailing space
-    EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:d ") == 0);
-    EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
+  // note trailing space
+  EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:d ") == 0);
+  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
 
-    EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:z") < 0);
+  EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:z") < 0);
 
-#if 0 // bitrot, seek update
+#if 0  // bitrot, seek update
     char defaultBuffer[512];
 
     android_log_formatLogLine(p_format,
@@ -1229,1291 +1422,1900 @@
     fprintf(stderr, "%s\n", defaultBuffer);
 #endif
 
-    android_log_format_free(p_format);
+  android_log_format_free(p_format);
 }
+#endif  // USING_LOGGER_DEFAULT
 
+#ifdef USING_LOGGER_DEFAULT  // Do not retest property handling
 TEST(liblog, is_loggable) {
-    static const char tag[] = "is_loggable";
-    static const char log_namespace[] = "persist.log.tag.";
-    static const size_t base_offset = 8; /* skip "persist." */
-    // sizeof("string") = strlen("string") + 1
-    char key[sizeof(log_namespace) + sizeof(tag) - 1];
-    char hold[4][PROP_VALUE_MAX];
-    static const struct {
-        int level;
-        char type;
-    } levels[] = {
-        { ANDROID_LOG_VERBOSE, 'v' },
-        { ANDROID_LOG_DEBUG  , 'd' },
-        { ANDROID_LOG_INFO   , 'i' },
-        { ANDROID_LOG_WARN   , 'w' },
-        { ANDROID_LOG_ERROR  , 'e' },
-        { ANDROID_LOG_FATAL  , 'a' },
-        { -1                 , 's' },
-        { -2                 , 'g' }, // Illegal value, resort to default
-    };
+#ifdef __ANDROID__
+  static const char tag[] = "is_loggable";
+  static const char log_namespace[] = "persist.log.tag.";
+  static const size_t base_offset = 8; /* skip "persist." */
+  // sizeof("string") = strlen("string") + 1
+  char key[sizeof(log_namespace) + sizeof(tag) - 1];
+  char hold[4][PROP_VALUE_MAX];
+  static const struct {
+    int level;
+    char type;
+  } levels[] = {
+    { ANDROID_LOG_VERBOSE, 'v' },
+    { ANDROID_LOG_DEBUG, 'd' },
+    { ANDROID_LOG_INFO, 'i' },
+    { ANDROID_LOG_WARN, 'w' },
+    { ANDROID_LOG_ERROR, 'e' },
+    { ANDROID_LOG_FATAL, 'a' },
+    { -1, 's' },
+    { -2, 'g' },  // Illegal value, resort to default
+  };
 
-    // Set up initial test condition
-    memset(hold, 0, sizeof(hold));
-    snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
-    property_get(key, hold[0], "");
-    property_set(key, "");
-    property_get(key + base_offset, hold[1], "");
-    property_set(key + base_offset, "");
-    strcpy(key, log_namespace);
-    key[sizeof(log_namespace) - 2] = '\0';
-    property_get(key, hold[2], "");
-    property_set(key, "");
-    property_get(key, hold[3], "");
-    property_set(key + base_offset, "");
+  // Set up initial test condition
+  memset(hold, 0, sizeof(hold));
+  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
+  property_get(key, hold[0], "");
+  property_set(key, "");
+  property_get(key + base_offset, hold[1], "");
+  property_set(key + base_offset, "");
+  strcpy(key, log_namespace);
+  key[sizeof(log_namespace) - 2] = '\0';
+  property_get(key, hold[2], "");
+  property_set(key, "");
+  property_get(key, hold[3], "");
+  property_set(key + base_offset, "");
 
-    // All combinations of level and defaults
-    for(size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
-        if (levels[i].level == -2) {
-            continue;
-        }
-        for(size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
-            if (levels[j].level == -2) {
-                continue;
-            }
-            fprintf(stderr, "i=%zu j=%zu\r", i, j);
-            bool android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, levels[j].level);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, levels[j].level));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, levels[j].level));
-                }
-            }
-        }
+  // All combinations of level and defaults
+  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
+    if (levels[i].level == -2) {
+      continue;
     }
-
-    // All combinations of level and tag and global properties
-    for(size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
-        if (levels[i].level == -2) {
-            continue;
+    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
+      if (levels[j].level == -2) {
+        continue;
+      }
+      fprintf(stderr, "i=%zu j=%zu\r", i, j);
+      bool android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), levels[j].level);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1)) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
         }
-        for(size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
-            char buf[2];
-            buf[0] = levels[j].type;
-            buf[1] = '\0';
-
-            snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key, buf);
-            property_set(key, buf);
-            bool android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_DEBUG)
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key, "");
-
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key + base_offset, buf);
-            property_set(key + base_offset, buf);
-            android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_DEBUG)
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key + base_offset, "");
-
-            strcpy(key, log_namespace);
-            key[sizeof(log_namespace) - 2] = '\0';
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key, buf);
-            property_set(key, buf);
-            android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_DEBUG)
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key, "");
-
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key + base_offset, buf);
-            property_set(key + base_offset, buf);
-            android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_DEBUG)
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key + base_offset, "");
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), levels[j].level));
         }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), levels[j].level));
+        }
+      }
     }
+  }
 
-    // All combinations of level and tag properties, but with global set to INFO
-    strcpy(key, log_namespace);
-    key[sizeof(log_namespace) - 2] = '\0';
-    property_set(key, "I");
-    snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
-    for(size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
-        if (levels[i].level == -2) {
-            continue;
-        }
-        for(size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
-            char buf[2];
-            buf[0] = levels[j].type;
-            buf[1] = '\0';
-
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key, buf);
-            property_set(key, buf);
-            bool android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_INFO) // Yes INFO
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key, "");
-
-            fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r",
-                    i, j, key + base_offset, buf);
-            property_set(key + base_offset, buf);
-            android_log_is_loggable = __android_log_is_loggable(
-                levels[i].level, tag, ANDROID_LOG_DEBUG);
-            if ((levels[i].level < levels[j].level)
-                    || (levels[j].level == -1)
-                    || ((levels[i].level < ANDROID_LOG_INFO) // Yes INFO
-                        && (levels[j].level == -2))) {
-                if (android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_FALSE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_FALSE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            } else {
-                if (!android_log_is_loggable) {
-                    fprintf(stderr, "\n");
-                }
-                EXPECT_TRUE(android_log_is_loggable);
-                for(size_t k = 10; k; --k) {
-                    EXPECT_TRUE(__android_log_is_loggable(
-                        levels[i].level, tag, ANDROID_LOG_DEBUG));
-                }
-            }
-            property_set(key + base_offset, "");
-        }
+  // All combinations of level and tag and global properties
+  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
+    if (levels[i].level == -2) {
+      continue;
     }
+    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
+      char buf[2];
+      buf[0] = levels[j].type;
+      buf[1] = '\0';
 
-    // reset parms
-    snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
-    property_set(key, hold[0]);
-    property_set(key + base_offset, hold[1]);
-    strcpy(key, log_namespace);
-    key[sizeof(log_namespace) - 2] = '\0';
-    property_set(key, hold[2]);
-    property_set(key + base_offset, hold[3]);
+      snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
+              buf);
+      usleep(20000);
+      property_set(key, buf);
+      bool android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key, "");
+
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
+              key + base_offset, buf);
+      property_set(key + base_offset, buf);
+      android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key + base_offset, "");
+
+      strcpy(key, log_namespace);
+      key[sizeof(log_namespace) - 2] = '\0';
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
+              buf);
+      property_set(key, buf);
+      android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key, "");
+
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
+              key + base_offset, buf);
+      property_set(key + base_offset, buf);
+      android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key + base_offset, "");
+    }
+  }
+
+  // All combinations of level and tag properties, but with global set to INFO
+  strcpy(key, log_namespace);
+  key[sizeof(log_namespace) - 2] = '\0';
+  usleep(20000);
+  property_set(key, "I");
+  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
+  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
+    if (levels[i].level == -2) {
+      continue;
+    }
+    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
+      char buf[2];
+      buf[0] = levels[j].type;
+      buf[1] = '\0';
+
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
+              buf);
+      usleep(20000);
+      property_set(key, buf);
+      bool android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_INFO)  // Yes INFO
+           && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key, "");
+
+      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
+              key + base_offset, buf);
+      property_set(key + base_offset, buf);
+      android_log_is_loggable = __android_log_is_loggable_len(
+          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
+      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
+          ((levels[i].level < ANDROID_LOG_INFO)  // Yes INFO
+           && (levels[j].level == -2))) {
+        if (android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_FALSE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_FALSE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      } else {
+        if (!android_log_is_loggable) {
+          fprintf(stderr, "\n");
+        }
+        EXPECT_TRUE(android_log_is_loggable);
+        for (size_t k = 10; k; --k) {
+          EXPECT_TRUE(__android_log_is_loggable_len(
+              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
+        }
+      }
+      usleep(20000);
+      property_set(key + base_offset, "");
+    }
+  }
+
+  // reset parms
+  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
+  usleep(20000);
+  property_set(key, hold[0]);
+  property_set(key + base_offset, hold[1]);
+  strcpy(key, log_namespace);
+  key[sizeof(log_namespace) - 2] = '\0';
+  property_set(key, hold[2]);
+  property_set(key + base_offset, hold[3]);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
+#endif  // USING_LOGGER_DEFAULT
+
+// Following tests the specific issues surrounding error handling wrt logd.
+// Kills logd and toss all collected data, equivalent to logcat -b all -c,
+// except we also return errors to the logging callers.
+#ifdef USING_LOGGER_DEFAULT
+#ifdef TEST_PREFIX
+// helper to liblog.enoent to count end-to-end matching logging messages.
+static int count_matching_ts(log_time ts) {
+  usleep(1000000);
+
+  pid_t pid = getpid();
+
+  struct logger_list* logger_list = android_logger_list_open(
+      LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid);
+
+  int count = 0;
+  if (logger_list == NULL) return count;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
+
+    if (log_msg.entry.len != sizeof(android_log_event_long_t)) continue;
+    if (log_msg.id() != LOG_ID_EVENTS) continue;
+
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
+    if (!eventData) continue;
+    if (eventData->payload.type != EVENT_TYPE_LONG) continue;
+
+    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
+    if (ts != tx) continue;
+
+    // found event message with matching timestamp signature in payload
+    ++count;
+  }
+  android_logger_list_close(logger_list);
+
+  return count;
+}
+
+// meant to be handed to ASSERT_TRUE / EXPECT_TRUE only to expand the message
+static testing::AssertionResult IsOk(bool ok, std::string& message) {
+  return ok ? testing::AssertionSuccess()
+            : (testing::AssertionFailure() << message);
+}
+#endif  // TEST_PREFIX
+
+TEST(liblog, enoent) {
+#ifdef TEST_PREFIX
+  TEST_PREFIX
+  log_time ts(CLOCK_MONOTONIC);
+  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+  EXPECT_EQ(SUPPORTS_END_TO_END, count_matching_ts(ts));
+
+  // This call will fail if we are setuid(AID_SYSTEM), beware of any
+  // test prior to this one playing with setuid and causing interference.
+  // We need to run before these tests so that they do not interfere with
+  // this test.
+  //
+  // Stopping the logger can affect some other test's expectations as they
+  // count on the log buffers filled with existing content, and this
+  // effectively does a logcat -c emptying it.  So we want this test to be
+  // as near as possible to the bottom of the file.  For example
+  // liblog.android_logger_get_ is one of those tests that has no recourse
+  // and that would be adversely affected by emptying the log if it was run
+  // right after this test.
+  if (getuid() != AID_ROOT) {
+    fprintf(
+        stderr,
+        "WARNING: test conditions request being run as root and not AID=%d\n",
+        getuid());
+    if (!__android_log_is_debuggable()) {
+      fprintf(
+          stderr,
+          "WARNING: can not run test on a \"user\" build, bypassing test\n");
+      return;
+    }
+  }
+
+  system((getuid() == AID_ROOT) ? "stop logd" : "su 0 stop logd");
+  usleep(1000000);
+
+  // A clean stop like we are testing returns -ENOENT, but in the _real_
+  // world we could get -ENOTCONN or -ECONNREFUSED depending on timing.
+  // Alas we can not test these other return values; accept that they
+  // are treated equally within the open-retry logic in liblog.
+  ts = log_time(CLOCK_MONOTONIC);
+  int ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
+  std::string content = android::base::StringPrintf(
+      "__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
+      ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
+  EXPECT_TRUE(
+      IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
+           content));
+  ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
+  content = android::base::StringPrintf(
+      "__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
+      ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
+  EXPECT_TRUE(
+      IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
+           content));
+  EXPECT_EQ(0, count_matching_ts(ts));
+
+  system((getuid() == AID_ROOT) ? "start logd" : "su 0 start logd");
+  usleep(1000000);
+
+  EXPECT_EQ(0, count_matching_ts(ts));
+
+  ts = log_time(CLOCK_MONOTONIC);
+  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+  EXPECT_EQ(SUPPORTS_END_TO_END, count_matching_ts(ts));
+
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+#endif  // USING_LOCAL_LOGD
+
+// Below this point we run risks of setuid(AID_SYSTEM) which may affect others.
+
+// Do not retest properties, and cannot log into LOG_ID_SECURITY
+#ifdef USING_LOGGER_DEFAULT
+TEST(liblog, __security) {
+#ifdef __ANDROID__
+  static const char persist_key[] = "persist.logd.security";
+  static const char readonly_key[] = "ro.device_owner";
+  // A silly default value that can never be in readonly_key so
+  // 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
+  // permissions. If we do not have them, we can not override them, so we
+  // 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";
+    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;
+  }
+
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
+  property_set(persist_key, "TRUE");
+  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");
+  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");
+  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");
+  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, "");
+  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
+}
+
+TEST(liblog, __security_buffer) {
+#ifdef __ANDROID__
+  struct logger_list* logger_list;
+  android_event_long_t buffer;
+
+  static const char persist_key[] = "persist.logd.security";
+  char persist[PROP_VALUE_MAX];
+  bool set_persist = false;
+  bool allow_security = false;
+
+  if (__android_log_security()) {
+    allow_security = true;
+  } else {
+    property_get(persist_key, persist, "");
+    if (strcasecmp(persist, "true")) {
+      property_set(persist_key, "TRUE");
+      if (__android_log_security()) {
+        allow_security = true;
+        set_persist = true;
+      } else {
+        property_set(persist_key, persist);
+      }
+    }
+  }
+
+  if (!allow_security) {
+    fprintf(stderr,
+            "WARNING: "
+            "security buffer disabled, bypassing end-to-end test\n");
+
+    log_time ts(CLOCK_MONOTONIC);
+
+    buffer.type = EVENT_TYPE_LONG;
+    buffer.data = *(static_cast<uint64_t*>((void*)&ts));
+
+    // expect failure!
+    ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
+
+    return;
+  }
+
+  /* Matches clientHasLogCredentials() in logd */
+  uid_t uid = getuid();
+  gid_t gid = getgid();
+  bool clientHasLogCredentials = true;
+  if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG) &&
+      (gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
+    uid_t euid = geteuid();
+    if ((euid != AID_SYSTEM) && (euid != AID_ROOT) && (euid != AID_LOG)) {
+      gid_t egid = getegid();
+      if ((egid != AID_SYSTEM) && (egid != AID_ROOT) && (egid != AID_LOG)) {
+        int num_groups = getgroups(0, NULL);
+        if (num_groups > 0) {
+          gid_t groups[num_groups];
+          num_groups = getgroups(num_groups, groups);
+          while (num_groups > 0) {
+            if (groups[num_groups - 1] == AID_LOG) {
+              break;
+            }
+            --num_groups;
+          }
+        }
+        if (num_groups <= 0) {
+          clientHasLogCredentials = false;
+        }
+      }
+    }
+  }
+  if (!clientHasLogCredentials) {
+    fprintf(stderr,
+            "WARNING: "
+            "not in system context, bypassing end-to-end test\n");
+
+    log_time ts(CLOCK_MONOTONIC);
+
+    buffer.type = EVENT_TYPE_LONG;
+    buffer.data = *(static_cast<uint64_t*>((void*)&ts));
+
+    // expect failure!
+    ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
+
+    return;
+  }
+
+  EXPECT_EQ(0, setuid(AID_SYSTEM));  // only one that can read security buffer
+
+  uid = getuid();
+  gid = getgid();
+  pid_t pid = getpid();
+
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_SECURITY, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
+
+  log_time ts(CLOCK_MONOTONIC);
+
+  buffer.type = EVENT_TYPE_LONG;
+  buffer.data = *(static_cast<uint64_t*>((void*)&ts));
+
+  ASSERT_LT(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
+  usleep(1000000);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
+    ASSERT_EQ(log_msg.entry.pid, pid);
+
+    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
+        (log_msg.id() != LOG_ID_SECURITY)) {
+      continue;
+    }
+
+    android_log_event_long_t* eventData;
+    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
+
+    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
+      continue;
+    }
+
+    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
+    if (ts == tx) {
+      ++count;
+    }
+  }
+
+  if (set_persist) {
+    property_set(persist_key, persist);
+  }
+
+  android_logger_list_close(logger_list);
+
+  bool clientHasSecurityCredentials = (uid == AID_SYSTEM) || (gid == AID_SYSTEM);
+  if (!clientHasSecurityCredentials) {
+    fprintf(stderr,
+            "WARNING: "
+            "not system, content submitted but can not check end-to-end\n");
+  }
+  EXPECT_EQ(clientHasSecurityCredentials ? 1 : 0, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+#endif  // USING_LOGGER_DEFAULT
+
+#ifdef TEST_PREFIX
+static void android_errorWriteWithInfoLog_helper(int TAG, const char* SUBTAG,
+                                                 int UID, const char* payload,
+                                                 int DATA_LEN, int& count) {
+  TEST_PREFIX
+  struct logger_list* logger_list;
+
+  pid_t pid = getpid();
+
+  count = 0;
+
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
+
+  int retval_android_errorWriteWithinInfoLog =
+      android_errorWriteWithInfoLog(TAG, SUBTAG, UID, payload, DATA_LEN);
+  if (payload) {
+    ASSERT_LT(0, retval_android_errorWriteWithinInfoLog);
+  } else {
+    ASSERT_GT(0, retval_android_errorWriteWithinInfoLog);
+  }
+
+  sleep(2);
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
+    char* eventData = log_msg.msg();
+    if (!eventData) {
+      continue;
+    }
+
+    char* original = eventData;
+
+    // Tag
+    int tag = get4LE(eventData);
+    eventData += 4;
+
+    if (tag != TAG) {
+      continue;
+    }
+
+    if (!payload) {
+      // This tag should not have been written because the data was null
+      ++count;
+      break;
+    }
+
+    // List type
+    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
+    eventData++;
+
+    // Number of elements in list
+    ASSERT_EQ(3, eventData[0]);
+    eventData++;
+
+    // Element #1: string type for subtag
+    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
+    eventData++;
+
+    unsigned subtag_len = strlen(SUBTAG);
+    if (subtag_len > 32) subtag_len = 32;
+    ASSERT_EQ(subtag_len, get4LE(eventData));
+    eventData += 4;
+
+    if (memcmp(SUBTAG, eventData, subtag_len)) {
+      continue;
+    }
+    eventData += subtag_len;
+
+    // Element #2: int type for uid
+    ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
+    eventData++;
+
+    ASSERT_EQ(UID, (int)get4LE(eventData));
+    eventData += 4;
+
+    // Element #3: string type for data
+    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
+    eventData++;
+
+    size_t dataLen = get4LE(eventData);
+    eventData += 4;
+    if (DATA_LEN < 512) ASSERT_EQ(DATA_LEN, (int)dataLen);
+
+    if (memcmp(payload, eventData, dataLen)) {
+      continue;
+    }
+
+    if (DATA_LEN >= 512) {
+      eventData += dataLen;
+      // 4 bytes for the tag, and max_payload_buf should be truncated.
+      ASSERT_LE(4 + 512, eventData - original);       // worst expectations
+      ASSERT_GT(4 + DATA_LEN, eventData - original);  // must be truncated
+    }
+
+    ++count;
+  }
+
+  android_logger_list_close(logger_list);
+}
+#endif
+
+// Make multiple tests and re-tests orthogonal to prevent falsing.
+#ifdef TEST_LOGGER
+#define UNIQUE_TAG(X) \
+  (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + TEST_LOGGER)
+#else
+#define UNIQUE_TAG(X) \
+  (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + 0xBA)
+#endif
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
-    const int TAG = 123456781;
-    const char SUBTAG[] = "test-subtag";
-    const int UID = -1;
-    const int DATA_LEN = 200;
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    ASSERT_LT(0, android_errorWriteWithInfoLog(
-            TAG, SUBTAG, UID, max_payload_buf, DATA_LEN));
-
-    sleep(2);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        char *eventData = log_msg.msg();
-
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
-
-        if (tag != TAG) {
-            continue;
-        }
-
-        // List type
-        ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-        eventData++;
-
-        // Number of elements in list
-        ASSERT_EQ(3, eventData[0]);
-        eventData++;
-
-        // Element #1: string type for subtag
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ((int) strlen(SUBTAG), get4LE(eventData));
-        eventData +=4;
-
-        if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
-            continue;
-        }
-        eventData += strlen(SUBTAG);
-
-        // Element #2: int type for uid
-        ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ(UID, get4LE(eventData));
-        eventData += 4;
-
-        // Element #3: string type for data
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ(DATA_LEN, get4LE(eventData));
-        eventData += 4;
-
-        if (memcmp(max_payload_buf, eventData, DATA_LEN)) {
-            continue;
-        }
-
-        ++count;
-    }
-
-    EXPECT_EQ(1, count);
-
-    android_logger_list_close(logger_list);
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(1), "test-subtag", -1,
+                                       max_payload_buf, 200, count);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
-    const int TAG = 123456782;
-    const char SUBTAG[] = "test-subtag";
-    const int UID = -1;
-    const int DATA_LEN = sizeof(max_payload_buf);
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    ASSERT_LT(0, android_errorWriteWithInfoLog(
-            TAG, SUBTAG, UID, max_payload_buf, DATA_LEN));
-
-    sleep(2);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        char *eventData = log_msg.msg();
-        char *original = eventData;
-
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
-
-        if (tag != TAG) {
-            continue;
-        }
-
-        // List type
-        ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-        eventData++;
-
-        // Number of elements in list
-        ASSERT_EQ(3, eventData[0]);
-        eventData++;
-
-        // Element #1: string type for subtag
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ((int) strlen(SUBTAG), get4LE(eventData));
-        eventData +=4;
-
-        if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
-            continue;
-        }
-        eventData += strlen(SUBTAG);
-
-        // Element #2: int type for uid
-        ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ(UID, get4LE(eventData));
-        eventData += 4;
-
-        // Element #3: string type for data
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        size_t dataLen = get4LE(eventData);
-        eventData += 4;
-
-        if (memcmp(max_payload_buf, eventData, dataLen)) {
-            continue;
-        }
-        eventData += dataLen;
-
-        // 4 bytes for the tag, and max_payload_buf should be truncated.
-        ASSERT_LE(4 + 512, eventData - original);      // worst expectations
-        ASSERT_GT(4 + DATA_LEN, eventData - original); // must be truncated
-
-        ++count;
-    }
-
-    EXPECT_EQ(1, count);
-
-    android_logger_list_close(logger_list);
+TEST(liblog,
+     android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(2), "test-subtag", -1,
+                                       max_payload_buf, sizeof(max_payload_buf),
+                                       count);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
-    const int TAG = 123456783;
-    const char SUBTAG[] = "test-subtag";
-    const int UID = -1;
-    const int DATA_LEN = 200;
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    ASSERT_GT(0, android_errorWriteWithInfoLog(
-            TAG, SUBTAG, UID, NULL, DATA_LEN));
-
-    sleep(2);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        char *eventData = log_msg.msg();
-
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
-
-        if (tag == TAG) {
-            // This tag should not have been written because the data was null
-            count++;
-            break;
-        }
-    }
-
-    EXPECT_EQ(0, count);
-
-    android_logger_list_close(logger_list);
+TEST(liblog,
+     android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(3), "test-subtag", -1, NULL,
+                                       200, count);
+  EXPECT_EQ(0, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
-    const int TAG = 123456784;
-    const char SUBTAG[] = "abcdefghijklmnopqrstuvwxyz now i know my abc";
-    const int UID = -1;
-    const int DATA_LEN = 200;
-    struct logger_list *logger_list;
+TEST(liblog,
+     android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteWithInfoLog_helper(
+      UNIQUE_TAG(4), "abcdefghijklmnopqrstuvwxyz now i know my abc", -1,
+      max_payload_buf, 200, count);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
 
-    pid_t pid = getpid();
+TEST(liblog, __android_log_bswrite_and_print___max) {
+  bswrite_test(max_payload_buf);
+}
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+TEST(liblog, __android_log_buf_write_and_print__max) {
+  buf_write_test(max_payload_buf);
+}
 
-    ASSERT_LT(0, android_errorWriteWithInfoLog(
-            TAG, SUBTAG, UID, max_payload_buf, DATA_LEN));
+#ifdef TEST_PREFIX
+static void android_errorWriteLog_helper(int TAG, const char* SUBTAG,
+                                         int& count) {
+  TEST_PREFIX
+  struct logger_list* logger_list;
 
-    sleep(2);
+  pid_t pid = getpid();
 
-    int count = 0;
+  count = 0;
 
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
+  // Do a Before and After on the count to measure the effect. Decrement
+  // what we find in Before to set the stage.
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
 
-        char *eventData = log_msg.msg();
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
 
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
+    char* eventData = log_msg.msg();
+    if (!eventData) continue;
 
-        if (tag != TAG) {
-            continue;
-        }
+    // Tag
+    int tag = get4LE(eventData);
+    eventData += 4;
 
-        // List type
-        ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-        eventData++;
+    if (tag != TAG) continue;
 
-        // Number of elements in list
-        ASSERT_EQ(3, eventData[0]);
-        eventData++;
-
-        // Element #1: string type for subtag
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        // The subtag is longer than 32 and should be truncated to that.
-        ASSERT_EQ(32, get4LE(eventData));
-        eventData +=4;
-
-        if (memcmp(SUBTAG, eventData, 32)) {
-            continue;
-        }
-        eventData += 32;
-
-        // Element #2: int type for uid
-        ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ(UID, get4LE(eventData));
-        eventData += 4;
-
-        // Element #3: string type for data
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ(DATA_LEN, get4LE(eventData));
-        eventData += 4;
-
-        if (memcmp(max_payload_buf, eventData, DATA_LEN)) {
-            continue;
-        }
-
-        ++count;
+    if (!SUBTAG) {
+      // This tag should not have been written because the data was null
+      --count;
+      break;
     }
 
-    EXPECT_EQ(1, count);
+    // List type
+    eventData++;
+    // Number of elements in list
+    eventData++;
+    // Element #1: string type for subtag
+    eventData++;
 
-    android_logger_list_close(logger_list);
+    eventData += 4;
+
+    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) continue;
+    --count;
+  }
+
+  android_logger_list_close(logger_list);
+
+  // Do an After on the count to measure the effect.
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
+
+  int retval_android_errorWriteLog = android_errorWriteLog(TAG, SUBTAG);
+  if (SUBTAG) {
+    ASSERT_LT(0, retval_android_errorWriteLog);
+  } else {
+    ASSERT_GT(0, retval_android_errorWriteLog);
+  }
+
+  sleep(2);
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
+    char* eventData = log_msg.msg();
+    if (!eventData) {
+      continue;
+    }
+
+    // Tag
+    int tag = get4LE(eventData);
+    eventData += 4;
+
+    if (tag != TAG) {
+      continue;
+    }
+
+    if (!SUBTAG) {
+      // This tag should not have been written because the data was null
+      ++count;
+      break;
+    }
+
+    // List type
+    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
+    eventData++;
+
+    // Number of elements in list
+    ASSERT_EQ(3, eventData[0]);
+    eventData++;
+
+    // Element #1: string type for subtag
+    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
+    eventData++;
+
+    ASSERT_EQ(strlen(SUBTAG), get4LE(eventData));
+    eventData += 4;
+
+    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
+      continue;
+    }
+    ++count;
+  }
+
+  android_logger_list_close(logger_list);
 }
+#endif
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
-    const int TAG = 123456785;
-    const char SUBTAG[] = "test-subtag";
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    ASSERT_LT(0, android_errorWriteLog(TAG, SUBTAG));
-
-    sleep(2);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        char *eventData = log_msg.msg();
-
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
-
-        if (tag != TAG) {
-            continue;
-        }
-
-        // List type
-        ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-        eventData++;
-
-        // Number of elements in list
-        ASSERT_EQ(3, eventData[0]);
-        eventData++;
-
-        // Element #1: string type for subtag
-        ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-        eventData++;
-
-        ASSERT_EQ((int) strlen(SUBTAG), get4LE(eventData));
-        eventData +=4;
-
-        if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
-            continue;
-        }
-        ++count;
-    }
-
-    EXPECT_EQ(1, count);
-
-    android_logger_list_close(logger_list);
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteLog_helper(UNIQUE_TAG(5), "test-subtag", count);
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
-    const int TAG = 123456786;
-    struct logger_list *logger_list;
-
-    pid_t pid = getpid();
-
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-    ASSERT_GT(0, android_errorWriteLog(TAG, NULL));
-
-    sleep(2);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        char *eventData = log_msg.msg();
-
-        // Tag
-        int tag = get4LE(eventData);
-        eventData += 4;
-
-        if (tag == TAG) {
-            // This tag should not have been written because the data was null
-            count++;
-            break;
-        }
-    }
-
-    EXPECT_EQ(0, count);
-
-    android_logger_list_close(logger_list);
+#ifdef TEST_PREFIX
+  int count;
+  android_errorWriteLog_helper(UNIQUE_TAG(6), NULL, count);
+  EXPECT_EQ(0, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+// Do not retest logger list handling
+#if (defined(TEST_PREFIX) || !defined(USING_LOGGER_LOCAL))
 static int is_real_element(int type) {
-    return ((type == EVENT_TYPE_INT) ||
-            (type == EVENT_TYPE_LONG) ||
-            (type == EVENT_TYPE_STRING) ||
-            (type == EVENT_TYPE_FLOAT));
+  return ((type == EVENT_TYPE_INT) || (type == EVENT_TYPE_LONG) ||
+          (type == EVENT_TYPE_STRING) || (type == EVENT_TYPE_FLOAT));
 }
 
-int android_log_buffer_to_string(const char *msg, size_t len,
-                                 char *strOut, size_t strOutLen) {
-    android_log_context context = create_android_log_parser(msg, len);
-    android_log_list_element elem;
-    bool overflow = false;
-    /* Reserve 1 byte for null terminator. */
-    size_t origStrOutLen = strOutLen--;
+static int android_log_buffer_to_string(const char* msg, size_t len,
+                                        char* strOut, size_t strOutLen) {
+  android_log_context context = create_android_log_parser(msg, len);
+  android_log_list_element elem;
+  bool overflow = false;
+  /* Reserve 1 byte for null terminator. */
+  size_t origStrOutLen = strOutLen--;
 
-    if (!context) {
-        return -EBADF;
-    }
+  if (!context) {
+    return -EBADF;
+  }
 
-    memset(&elem, 0, sizeof(elem));
+  memset(&elem, 0, sizeof(elem));
 
-    size_t outCount;
+  size_t outCount;
 
-    do {
-        elem = android_log_read_next(context);
-        switch ((int)elem.type) {
-        case EVENT_TYPE_LIST:
-            if (strOutLen == 0) {
-                overflow = true;
-            } else {
-                *strOut++ = '[';
-                strOutLen--;
-            }
-            break;
+  do {
+    elem = android_log_read_next(context);
+    switch ((int)elem.type) {
+      case EVENT_TYPE_LIST:
+        if (strOutLen == 0) {
+          overflow = true;
+        } else {
+          *strOut++ = '[';
+          strOutLen--;
+        }
+        break;
 
-        case EVENT_TYPE_LIST_STOP:
-            if (strOutLen == 0) {
-                overflow = true;
-            } else {
-                *strOut++ = ']';
-                strOutLen--;
-            }
-            break;
+      case EVENT_TYPE_LIST_STOP:
+        if (strOutLen == 0) {
+          overflow = true;
+        } else {
+          *strOut++ = ']';
+          strOutLen--;
+        }
+        break;
 
-        case EVENT_TYPE_INT:
-            /*
-             * snprintf also requires room for the null terminator, which
-             * we don't care about  but we have allocated enough room for
-             * that
-             */
-            outCount = snprintf(strOut, strOutLen + 1,
-                                "%" PRId32, elem.data.int32);
-            if (outCount <= strOutLen) {
-                strOut += outCount;
-                strOutLen -= outCount;
-            } else {
-                overflow = true;
-            }
-            break;
+      case EVENT_TYPE_INT:
+        /*
+         * snprintf also requires room for the null terminator, which
+         * we don't care about  but we have allocated enough room for
+         * that
+         */
+        outCount = snprintf(strOut, strOutLen + 1, "%" PRId32, elem.data.int32);
+        if (outCount <= strOutLen) {
+          strOut += outCount;
+          strOutLen -= outCount;
+        } else {
+          overflow = true;
+        }
+        break;
 
-        case EVENT_TYPE_LONG:
-            /*
-             * snprintf also requires room for the null terminator, which
-             * we don't care about but we have allocated enough room for
-             * that
-             */
-            outCount = snprintf(strOut, strOutLen + 1,
-                                "%" PRId64, elem.data.int64);
-            if (outCount <= strOutLen) {
-                strOut += outCount;
-                strOutLen -= outCount;
-            } else {
-                overflow = true;
-            }
-            break;
+      case EVENT_TYPE_LONG:
+        /*
+         * snprintf also requires room for the null terminator, which
+         * we don't care about but we have allocated enough room for
+         * that
+         */
+        outCount = snprintf(strOut, strOutLen + 1, "%" PRId64, elem.data.int64);
+        if (outCount <= strOutLen) {
+          strOut += outCount;
+          strOutLen -= outCount;
+        } else {
+          overflow = true;
+        }
+        break;
 
-        case EVENT_TYPE_FLOAT:
-            /*
-             * snprintf also requires room for the null terminator, which
-             * we don't care about but we have allocated enough room for
-             * that
-             */
-            outCount = snprintf(strOut, strOutLen + 1, "%f", elem.data.float32);
-            if (outCount <= strOutLen) {
-                strOut += outCount;
-                strOutLen -= outCount;
-            } else {
-                overflow = true;
-            }
-            break;
+      case EVENT_TYPE_FLOAT:
+        /*
+         * snprintf also requires room for the null terminator, which
+         * we don't care about but we have allocated enough room for
+         * that
+         */
+        outCount = snprintf(strOut, strOutLen + 1, "%f", elem.data.float32);
+        if (outCount <= strOutLen) {
+          strOut += outCount;
+          strOutLen -= outCount;
+        } else {
+          overflow = true;
+        }
+        break;
 
-        default:
-            elem.complete = true;
-            break;
+      default:
+        elem.complete = true;
+        break;
 
-        case EVENT_TYPE_UNKNOWN:
-#if 0 // Ideal purity in the test, we want to complain about UNKNOWN showing up
+      case EVENT_TYPE_UNKNOWN:
+#if 0  // Ideal purity in the test, we want to complain about UNKNOWN showing up
             if (elem.complete) {
                 break;
             }
 #endif
-            elem.data.string = const_cast<char *>("<unknown>");
-            elem.len = strlen(elem.data.string);
-            /* FALLTHRU */
-        case EVENT_TYPE_STRING:
-            if (elem.len <= strOutLen) {
-                memcpy(strOut, elem.data.string, elem.len);
-                strOut += elem.len;
-                strOutLen -= elem.len;
-            } else if (strOutLen > 0) {
-                /* copy what we can */
-                memcpy(strOut, elem.data.string, strOutLen);
-                strOut += strOutLen;
-                strOutLen = 0;
-                overflow = true;
-            }
-            break;
+        elem.data.string = const_cast<char*>("<unknown>");
+        elem.len = strlen(elem.data.string);
+      /* FALLTHRU */
+      case EVENT_TYPE_STRING:
+        if (elem.len <= strOutLen) {
+          memcpy(strOut, elem.data.string, elem.len);
+          strOut += elem.len;
+          strOutLen -= elem.len;
+        } else if (strOutLen > 0) {
+          /* copy what we can */
+          memcpy(strOut, elem.data.string, strOutLen);
+          strOut += strOutLen;
+          strOutLen = 0;
+          overflow = true;
         }
+        break;
+    }
 
-        if (elem.complete) {
-            break;
-        }
-        /* Determine whether to put a comma or not. */
-        if (!overflow && (is_real_element(elem.type) ||
-                (elem.type == EVENT_TYPE_LIST_STOP))) {
-            android_log_list_element next = android_log_peek_next(context);
-            if (!next.complete && (is_real_element(next.type) ||
-                    (next.type == EVENT_TYPE_LIST))) {
-                if (strOutLen == 0) {
-                    overflow = true;
-                } else {
-                    *strOut++ = ',';
-                    strOutLen--;
-                }
-            }
-        }
-    } while ((elem.type != EVENT_TYPE_UNKNOWN) && !overflow && !elem.complete);
-
-    android_log_destroy(&context);
-
-    if (overflow) {
-        if (strOutLen < origStrOutLen) {
-            /* leave an indicator */
-            *(strOut-1) = '!';
+    if (elem.complete) {
+      break;
+    }
+    /* Determine whether to put a comma or not. */
+    if (!overflow &&
+        (is_real_element(elem.type) || (elem.type == EVENT_TYPE_LIST_STOP))) {
+      android_log_list_element next = android_log_peek_next(context);
+      if (!next.complete &&
+          (is_real_element(next.type) || (next.type == EVENT_TYPE_LIST))) {
+        if (strOutLen == 0) {
+          overflow = true;
         } else {
-            /* nothing was written at all */
-            *strOut++ = '!';
+          *strOut++ = ',';
+          strOutLen--;
         }
+      }
     }
-    *strOut++ = '\0';
+  } while ((elem.type != EVENT_TYPE_UNKNOWN) && !overflow && !elem.complete);
 
-    if ((elem.type == EVENT_TYPE_UNKNOWN) && !elem.complete) {
-        fprintf(stderr, "Binary log entry conversion failed\n");
-        return -EINVAL;
+  android_log_destroy(&context);
+
+  if (overflow) {
+    if (strOutLen < origStrOutLen) {
+      /* leave an indicator */
+      *(strOut - 1) = '!';
+    } else {
+      /* nothing was written at all */
+      *strOut++ = '!';
     }
+  }
+  *strOut++ = '\0';
 
-    return 0;
+  if ((elem.type == EVENT_TYPE_UNKNOWN) && !elem.complete) {
+    fprintf(stderr, "Binary log entry conversion failed\n");
+    return -EINVAL;
+  }
+
+  return 0;
+}
+#endif  // TEST_PREFIX || !USING_LOGGER_LOCAL
+
+#ifdef TEST_PREFIX
+static const char* event_test_int32(uint32_t tag, size_t& expected_len) {
+  android_log_context ctx;
+
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
+
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t);
+
+  return "1076895760";
 }
 
-static const char *event_test_int32(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_int64(uint32_t tag, size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint32_t);
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint64_t);
 
-    return "1076895760";
+  return "-9191740941672636400";
 }
 
-static const char *event_test_int64(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_list_int64(uint32_t tag, size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint64_t);
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint8_t) + sizeof(uint64_t);
 
-    return "-9191740941672636400";
+  return "[-9191740941672636400]";
 }
 
-static const char *event_test_list_int64(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_simple_automagic_list(uint32_t tag,
+                                                    size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  // The convenience API where we allow a simple list to be
+  // created without explicit begin or end calls.
+  EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
+  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint8_t) +
-                       sizeof(uint8_t) + sizeof(uint64_t);
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
+                 sizeof(uint64_t);
 
-    return "[-9191740941672636400]";
+  return "[1076895760,-9191740941672636400]";
 }
 
-static const char *event_test_simple_automagic_list(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_list_empty(uint32_t tag, size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    // The convenience API where we allow a simple list to be
-    // created without explicit begin or end calls.
-    EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
-    EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint8_t) +
-                       sizeof(uint8_t) + sizeof(uint32_t) +
-                       sizeof(uint8_t) + sizeof(uint64_t);
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t);
 
-    return "[1076895760,-9191740941672636400]";
+  return "[]";
 }
 
-static const char *event_test_list_empty(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_complex_nested_list(uint32_t tag,
+                                                  size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
 
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint8_t);
+  EXPECT_LE(0, android_log_write_list_begin(ctx));  // [
+  EXPECT_LE(0, android_log_write_int32(ctx, 0x01020304));
+  EXPECT_LE(0, android_log_write_int64(ctx, 0x0102030405060708));
+  EXPECT_LE(0, android_log_write_string8(ctx, "Hello World"));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));  // [
+  EXPECT_LE(0, android_log_write_int32(ctx, 1));
+  EXPECT_LE(0, android_log_write_int32(ctx, 2));
+  EXPECT_LE(0, android_log_write_int32(ctx, 3));
+  EXPECT_LE(0, android_log_write_int32(ctx, 4));
+  EXPECT_LE(0, android_log_write_list_end(ctx));  // ]
+  EXPECT_LE(0, android_log_write_float32(ctx, 1.0102030405060708));
+  EXPECT_LE(0, android_log_write_list_end(ctx));  // ]
 
-    return "[]";
+  //
+  // This one checks for the automagic list creation because a list
+  // begin and end was missing for it! This is actually an <oops> corner
+  // case, and not the behavior we morally support. The automagic API is to
+  // allow for a simple case of a series of objects in a single list. e.g.
+  //   int32,int32,int32,string -> [int32,int32,int32,string]
+  //
+  EXPECT_LE(0, android_log_write_string8(ctx, "dlroW olleH"));
+
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
+
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint64_t) +
+                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
+                 1 + sizeof(uint8_t) + sizeof(uint8_t) +
+                 4 * (sizeof(uint8_t) + sizeof(uint32_t)) + sizeof(uint8_t) +
+                 sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t) +
+                 sizeof("dlroW olleH") - 1;
+
+  return "[[16909060,72623859790382856,Hello World,[1,2,3,4],1.010203],dlroW "
+         "olleH]";
 }
 
-static const char *event_test_complex_nested_list(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_7_level_prefix(uint32_t tag,
+                                             size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 1));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 2));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 3));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 4));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 5));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 6));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 7));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    EXPECT_LE(0, android_log_write_list_begin(ctx)); // [
-    EXPECT_LE(0, android_log_write_int32(ctx, 0x01020304));
-    EXPECT_LE(0, android_log_write_int64(ctx, 0x0102030405060708));
-    EXPECT_LE(0, android_log_write_string8(ctx, "Hello World"));
-    EXPECT_LE(0, android_log_write_list_begin(ctx)); // [
-    EXPECT_LE(0, android_log_write_int32(ctx, 1));
-    EXPECT_LE(0, android_log_write_int32(ctx, 2));
-    EXPECT_LE(0, android_log_write_int32(ctx, 3));
-    EXPECT_LE(0, android_log_write_int32(ctx, 4));
-    EXPECT_LE(0, android_log_write_list_end(ctx));   // ]
-    EXPECT_LE(0, android_log_write_float32(ctx, 1.0102030405060708));
-    EXPECT_LE(0, android_log_write_list_end(ctx));   // ]
+  expected_len = sizeof(uint32_t) + 7 * (sizeof(uint8_t) + sizeof(uint8_t) +
+                                         sizeof(uint8_t) + sizeof(uint32_t));
 
-    //
-    // This one checks for the automagic list creation because a list
-    // begin and end was missing for it! This is actually an <oops> corner
-    // case, and not the behavior we morally support. The automagic API is to
-    // allow for a simple case of a series of objects in a single list. e.g.
-    //   int32,int32,int32,string -> [int32,int32,int32,string]
-    //
-    EXPECT_LE(0, android_log_write_string8(ctx, "dlroW olleH"));
-
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
-
-    expected_len = sizeof(uint32_t) +
-                   sizeof(uint8_t) + sizeof(uint8_t) +
-                       sizeof(uint8_t) + sizeof(uint8_t) +
-                           sizeof(uint8_t) + sizeof(uint32_t) +
-                           sizeof(uint8_t) + sizeof(uint64_t) +
-                           sizeof(uint8_t) + sizeof(uint32_t) +
-                                             sizeof("Hello World") - 1 +
-                           sizeof(uint8_t) + sizeof(uint8_t) +
-                               4 * (sizeof(uint8_t) + sizeof(uint32_t)) +
-                           sizeof(uint8_t) + sizeof(uint32_t) +
-                       sizeof(uint8_t) + sizeof(uint32_t) +
-                                         sizeof("dlroW olleH") - 1;
-
-    return "[[16909060,72623859790382856,Hello World,[1,2,3,4],1.010203],dlroW olleH]";
+  return "[[[[[[[1],2],3],4],5],6],7]";
 }
 
-static const char *event_test_7_level_prefix(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_7_level_suffix(uint32_t tag,
+                                             size_t& expected_len) {
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 1));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 2));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 3));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 4));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 5));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 6));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 7));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
+  if (!ctx) {
+    return NULL;
+  }
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 1));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 2));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 3));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 4));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 5));
+  EXPECT_LE(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_write_int32(ctx, 6));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list_end(ctx));
+  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  EXPECT_TRUE(NULL == ctx);
 
-    expected_len = sizeof(uint32_t) + 7 *
-      (sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint32_t));
+  expected_len = sizeof(uint32_t) + 6 * (sizeof(uint8_t) + sizeof(uint8_t) +
+                                         sizeof(uint8_t) + sizeof(uint32_t));
 
-    return "[[[[[[[1],2],3],4],5],6],7]";
+  return "[1,[2,[3,[4,[5,[6]]]]]]";
 }
 
-static const char *event_test_7_level_suffix(uint32_t tag, size_t &expected_len) {
-    android_log_context ctx;
+static const char* event_test_android_log_error_write(uint32_t tag,
+                                                      size_t& expected_len) {
+  EXPECT_LE(
+      0, __android_log_error_write(tag, "Hello World", 42, "dlroW olleH", 11));
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
-    if (!ctx) {
-        return NULL;
-    }
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 1));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 2));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 3));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 4));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 5));
-    EXPECT_LE(0, android_log_write_list_begin(ctx));
-    EXPECT_LE(0, android_log_write_int32(ctx, 6));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list_end(ctx));
-    EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
-    EXPECT_LE(0, android_log_destroy(&ctx));
-    EXPECT_TRUE(NULL == ctx);
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
+                 1 + sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
+                 sizeof(uint32_t) + sizeof("dlroW olleH") - 1;
 
-    expected_len = sizeof(uint32_t) + 6 *
-      (sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint32_t));
-
-    return "[1,[2,[3,[4,[5,[6]]]]]]";
+  return "[Hello World,42,dlroW olleH]";
 }
 
-static const char *event_test_android_log_error_write(uint32_t tag, size_t &expected_len) {
-    EXPECT_LE(0, __android_log_error_write(tag, "Hello World", 42, "dlroW olleH", 11));
+static const char* event_test_android_log_error_write_null(uint32_t tag,
+                                                           size_t& expected_len) {
+  EXPECT_LE(0, __android_log_error_write(tag, "Hello World", 42, NULL, 0));
 
-    expected_len = sizeof(uint32_t) +
-      sizeof(uint8_t) + sizeof(uint8_t) +
-          sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") - 1 +
-          sizeof(uint8_t) + sizeof(uint32_t) +
-          sizeof(uint8_t) + sizeof(uint32_t) + sizeof("dlroW olleH") - 1;
+  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
+                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
+                 1 + sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
+                 sizeof(uint32_t) + sizeof("") - 1;
 
-    return "[Hello World,42,dlroW olleH]";
-}
-
-static const char *event_test_android_log_error_write_null(uint32_t tag, size_t &expected_len) {
-    EXPECT_LE(0, __android_log_error_write(tag, "Hello World", 42, NULL, 0));
-
-    expected_len = sizeof(uint32_t) +
-      sizeof(uint8_t) + sizeof(uint8_t) +
-          sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") - 1 +
-          sizeof(uint8_t) + sizeof(uint32_t) +
-          sizeof(uint8_t) + sizeof(uint32_t) + sizeof("") - 1;
-
-    return "[Hello World,42,]";
+  return "[Hello World,42,]";
 }
 
 // make sure all user buffers are flushed
 static void print_barrier() {
-    std::cout.flush();
-    fflush(stdout);
-    std::cerr.flush();
-    fflush(stderr); // everything else is paranoia ...
+  std::cout.flush();
+  fflush(stdout);
+  std::cerr.flush();
+  fflush(stderr);  // everything else is paranoia ...
 }
 
-static void create_android_logger(const char *(*fn)(uint32_t tag, size_t &expected_len)) {
-    struct logger_list *logger_list;
+static void create_android_logger(const char* (*fn)(uint32_t tag,
+                                                    size_t& expected_len)) {
+  TEST_PREFIX
+  struct logger_list* logger_list;
 
-    pid_t pid = getpid();
+  pid_t pid = getpid();
 
-    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-        LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+  ASSERT_TRUE(NULL !=
+              (logger_list = android_logger_list_open(
+                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                   1000, pid)));
 
-    log_time ts(android_log_clockid());
+#ifdef __ANDROID__
+  log_time ts(android_log_clockid());
+#else
+  log_time ts(CLOCK_REALTIME);
+#endif
 
-    size_t expected_len;
-    const char *expected_string = (*fn)(1005, expected_len);
+  size_t expected_len;
+  const char* expected_string = (*fn)(1005, expected_len);
 
-    if (!expected_string) {
-        android_logger_list_close(logger_list);
-        return;
-    }
-
-    usleep(1000000);
-
-    int count = 0;
-
-    for (;;) {
-        log_msg log_msg;
-        if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-            break;
-        }
-
-        ASSERT_EQ(log_msg.entry.pid, pid);
-
-        if ((log_msg.entry.sec < (ts.tv_sec - 1))
-         || ((ts.tv_sec + 1) < log_msg.entry.sec)
-         || ((size_t)log_msg.entry.len != expected_len)
-         || (log_msg.id() != LOG_ID_EVENTS)) {
-            continue;
-        }
-
-        char *eventData = log_msg.msg();
-
-        ++count;
-
-        AndroidLogFormat *logformat = android_log_format_new();
-        EXPECT_TRUE(NULL != logformat);
-        AndroidLogEntry entry;
-        char msgBuf[1024];
-        int processBinaryLogBuffer = android_log_processBinaryLogBuffer(
-            &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
-        EXPECT_EQ(0, processBinaryLogBuffer);
-        if (processBinaryLogBuffer == 0) {
-            print_barrier();
-            int printLogLine = android_log_printLogLine(
-                logformat, fileno(stderr), &entry);
-            print_barrier();
-            EXPECT_EQ(20 + (int)strlen(expected_string), printLogLine);
-        }
-        android_log_format_free(logformat);
-
-        // test buffer reading API
-        snprintf(msgBuf, sizeof(msgBuf), "I/[%d]", get4LE(eventData));
-        print_barrier();
-        fprintf(stderr, "%-10s(%5u): ", msgBuf, pid);
-        memset(msgBuf, 0, sizeof(msgBuf));
-        int buffer_to_string = android_log_buffer_to_string(
-            eventData + sizeof(uint32_t),
-            log_msg.entry.len - sizeof(uint32_t),
-            msgBuf, sizeof(msgBuf));
-        fprintf(stderr, "%s\n", msgBuf);
-        print_barrier();
-        EXPECT_EQ(0, buffer_to_string);
-        EXPECT_EQ(strlen(expected_string), strlen(msgBuf));
-        EXPECT_EQ(0, strcmp(expected_string, msgBuf));
-    }
-
-    EXPECT_EQ(1, count);
-
+  if (!expected_string) {
     android_logger_list_close(logger_list);
+    return;
+  }
+
+  usleep(1000000);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
+      break;
+    }
+
+    ASSERT_EQ(log_msg.entry.pid, pid);
+
+    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
+        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
+        ((size_t)log_msg.entry.len != expected_len) ||
+        (log_msg.id() != LOG_ID_EVENTS)) {
+      continue;
+    }
+
+    char* eventData = log_msg.msg();
+
+    ++count;
+
+    AndroidLogFormat* logformat = android_log_format_new();
+    EXPECT_TRUE(NULL != logformat);
+    AndroidLogEntry entry;
+    char msgBuf[1024];
+    int processBinaryLogBuffer = android_log_processBinaryLogBuffer(
+        &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
+    EXPECT_EQ(0, processBinaryLogBuffer);
+    if (processBinaryLogBuffer == 0) {
+      int line_overhead = 20;
+      if (pid > 99999) ++line_overhead;
+      if (pid > 999999) ++line_overhead;
+      print_barrier();
+      int printLogLine =
+          android_log_printLogLine(logformat, fileno(stderr), &entry);
+      print_barrier();
+      EXPECT_EQ(line_overhead + (int)strlen(expected_string), printLogLine);
+    }
+    android_log_format_free(logformat);
+
+    // test buffer reading API
+    int buffer_to_string = -1;
+    if (eventData) {
+      snprintf(msgBuf, sizeof(msgBuf), "I/[%" PRIu32 "]", get4LE(eventData));
+      print_barrier();
+      fprintf(stderr, "%-10s(%5u): ", msgBuf, pid);
+      memset(msgBuf, 0, sizeof(msgBuf));
+      buffer_to_string = android_log_buffer_to_string(
+          eventData + sizeof(uint32_t), log_msg.entry.len - sizeof(uint32_t),
+          msgBuf, sizeof(msgBuf));
+      fprintf(stderr, "%s\n", msgBuf);
+      print_barrier();
+    }
+    EXPECT_EQ(0, buffer_to_string);
+    EXPECT_EQ(strlen(expected_string), strlen(msgBuf));
+    EXPECT_EQ(0, strcmp(expected_string, msgBuf));
+  }
+
+  EXPECT_EQ(SUPPORTS_END_TO_END, count);
+
+  android_logger_list_close(logger_list);
 }
+#endif
 
 TEST(liblog, create_android_logger_int32) {
-    create_android_logger(event_test_int32);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_int32);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_int64) {
-    create_android_logger(event_test_int64);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_int64);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_list_int64) {
-    create_android_logger(event_test_list_int64);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_list_int64);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_simple_automagic_list) {
-    create_android_logger(event_test_simple_automagic_list);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_simple_automagic_list);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_list_empty) {
-    create_android_logger(event_test_list_empty);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_list_empty);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_complex_nested_list) {
-    create_android_logger(event_test_complex_nested_list);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_complex_nested_list);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_7_level_prefix) {
-    create_android_logger(event_test_7_level_prefix);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_7_level_prefix);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_7_level_suffix) {
-    create_android_logger(event_test_7_level_suffix);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_7_level_suffix);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_android_log_error_write) {
-    create_android_logger(event_test_android_log_error_write);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_android_log_error_write);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_android_log_error_write_null) {
-    create_android_logger(event_test_android_log_error_write_null);
+#ifdef TEST_PREFIX
+  create_android_logger(event_test_android_log_error_write_null);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef USING_LOGGER_DEFAULT  // Do not retest logger list handling
 TEST(liblog, create_android_logger_overflow) {
-    android_log_context ctx;
+  android_log_context ctx;
 
-    EXPECT_TRUE(NULL != (ctx = create_android_logger(1005)));
-    if (ctx) {
-        for (size_t i = 0; i < ANDROID_MAX_LIST_NEST_DEPTH; ++i) {
-            EXPECT_LE(0, android_log_write_list_begin(ctx));
-        }
-        EXPECT_GT(0, android_log_write_list_begin(ctx));
-        /* One more for good measure, must be permanently unhappy */
-        EXPECT_GT(0, android_log_write_list_begin(ctx));
-        EXPECT_LE(0, android_log_destroy(&ctx));
-        EXPECT_TRUE(NULL == ctx);
-    }
-
-    ASSERT_TRUE(NULL != (ctx = create_android_logger(1005)));
+  EXPECT_TRUE(NULL != (ctx = create_android_logger(1005)));
+  if (ctx) {
     for (size_t i = 0; i < ANDROID_MAX_LIST_NEST_DEPTH; ++i) {
-        EXPECT_LE(0, android_log_write_list_begin(ctx));
-        EXPECT_LE(0, android_log_write_int32(ctx, i));
+      EXPECT_LE(0, android_log_write_list_begin(ctx));
     }
     EXPECT_GT(0, android_log_write_list_begin(ctx));
     /* One more for good measure, must be permanently unhappy */
     EXPECT_GT(0, android_log_write_list_begin(ctx));
     EXPECT_LE(0, android_log_destroy(&ctx));
-    ASSERT_TRUE(NULL == ctx);
+    EXPECT_TRUE(NULL == ctx);
+  }
+
+  ASSERT_TRUE(NULL != (ctx = create_android_logger(1005)));
+  for (size_t i = 0; i < ANDROID_MAX_LIST_NEST_DEPTH; ++i) {
+    EXPECT_LE(0, android_log_write_list_begin(ctx));
+    EXPECT_LE(0, android_log_write_int32(ctx, i));
+  }
+  EXPECT_GT(0, android_log_write_list_begin(ctx));
+  /* One more for good measure, must be permanently unhappy */
+  EXPECT_GT(0, android_log_write_list_begin(ctx));
+  EXPECT_LE(0, android_log_destroy(&ctx));
+  ASSERT_TRUE(NULL == ctx);
 }
 
+TEST(liblog, android_log_write_list_buffer) {
+  __android_log_event_list ctx(1005);
+  ctx << 1005 << "tag_def"
+      << "(tag|1),(name|3),(format|3)";
+  std::string buffer(ctx);
+  ctx.close();
+
+  char msgBuf[1024];
+  memset(msgBuf, 0, sizeof(msgBuf));
+  EXPECT_EQ(android_log_buffer_to_string(buffer.data(), buffer.length(), msgBuf,
+                                         sizeof(msgBuf)),
+            0);
+  EXPECT_STREQ(msgBuf, "[1005,tag_def,(tag|1),(name|3),(format|3)]");
+}
+#endif  // USING_LOGGER_DEFAULT
+
+#ifdef USING_LOGGER_DEFAULT  // Do not retest pmsg functionality
+#ifdef __ANDROID__
 static const char __pmsg_file[] =
-        "/data/william-shakespeare/MuchAdoAboutNothing.txt";
+    "/data/william-shakespeare/MuchAdoAboutNothing.txt";
+#endif
 
 TEST(liblog, __android_log_pmsg_file_write) {
-    EXPECT_LT(0, __android_log_pmsg_file_write(
-            LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
-            __pmsg_file, max_payload_buf, sizeof(max_payload_buf)));
-    fprintf(stderr, "Reboot, ensure file %s matches\n"
-                    "with liblog.__android_log_msg_file_read test\n",
-                    __pmsg_file);
+#ifdef __ANDROID__
+  __android_log_close();
+  if (getuid() == AID_ROOT) {
+    tested__android_log_close = true;
+    bool pmsgActiveAfter__android_log_close = isPmsgActive();
+    bool logdwActiveAfter__android_log_close = isLogdwActive();
+    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
+    EXPECT_FALSE(logdwActiveAfter__android_log_close);
+  } else if (!tested__android_log_close) {
+    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
+  }
+  int return__android_log_pmsg_file_write = __android_log_pmsg_file_write(
+      LOG_ID_CRASH, ANDROID_LOG_VERBOSE, __pmsg_file, max_payload_buf,
+      sizeof(max_payload_buf));
+  EXPECT_LT(0, return__android_log_pmsg_file_write);
+  if (return__android_log_pmsg_file_write == -ENOMEM) {
+    fprintf(stderr,
+            "Kernel does not have space allocated to pmsg pstore driver "
+            "configured\n");
+  } else if (!return__android_log_pmsg_file_write) {
+    fprintf(stderr,
+            "Reboot, ensure file %s matches\n"
+            "with liblog.__android_log_msg_file_read test\n",
+            __pmsg_file);
+  }
+  bool pmsgActiveAfter__android_pmsg_file_write;
+  bool logdwActiveAfter__android_pmsg_file_write;
+  if (getuid() == AID_ROOT) {
+    pmsgActiveAfter__android_pmsg_file_write = isPmsgActive();
+    logdwActiveAfter__android_pmsg_file_write = isLogdwActive();
+    EXPECT_FALSE(pmsgActiveAfter__android_pmsg_file_write);
+    EXPECT_FALSE(logdwActiveAfter__android_pmsg_file_write);
+  }
+  EXPECT_LT(
+      0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
+                                 "TEST__android_log_pmsg_file_write", "main"));
+  if (getuid() == AID_ROOT) {
+    bool pmsgActiveAfter__android_log_buf_print = isPmsgActive();
+    bool logdwActiveAfter__android_log_buf_print = isLogdwActive();
+    EXPECT_TRUE(pmsgActiveAfter__android_log_buf_print);
+    EXPECT_TRUE(logdwActiveAfter__android_log_buf_print);
+  }
+  EXPECT_LT(0, __android_log_pmsg_file_write(LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
+                                             __pmsg_file, max_payload_buf,
+                                             sizeof(max_payload_buf)));
+  if (getuid() == AID_ROOT) {
+    pmsgActiveAfter__android_pmsg_file_write = isPmsgActive();
+    logdwActiveAfter__android_pmsg_file_write = isLogdwActive();
+    EXPECT_TRUE(pmsgActiveAfter__android_pmsg_file_write);
+    EXPECT_TRUE(logdwActiveAfter__android_pmsg_file_write);
+  }
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
-ssize_t __pmsg_fn(log_id_t logId, char prio, const char *filename,
-                  const char *buf, size_t len, void *arg) {
-    EXPECT_TRUE(NULL == arg);
-    EXPECT_EQ(LOG_ID_CRASH, logId);
-    EXPECT_EQ(ANDROID_LOG_VERBOSE, prio);
-    EXPECT_FALSE(NULL == strstr(__pmsg_file, filename));
-    EXPECT_EQ(len, sizeof(max_payload_buf));
-    EXPECT_EQ(0, strcmp(max_payload_buf, buf));
+#ifdef __ANDROID__
+static ssize_t __pmsg_fn(log_id_t logId, char prio, const char* filename,
+                         const char* buf, size_t len, void* arg) {
+  EXPECT_TRUE(NULL == arg);
+  EXPECT_EQ(LOG_ID_CRASH, logId);
+  EXPECT_EQ(ANDROID_LOG_VERBOSE, prio);
+  EXPECT_FALSE(NULL == strstr(__pmsg_file, filename));
+  EXPECT_EQ(len, sizeof(max_payload_buf));
+  EXPECT_EQ(0, strcmp(max_payload_buf, buf));
 
-    ++signaled;
-    if ((len != sizeof(max_payload_buf)) ||
-            strcmp(max_payload_buf, buf)) {
-        fprintf(stderr, "comparison fails on content \"%s\"\n", buf);
-    }
-    return !arg ||
-           (LOG_ID_CRASH != logId) ||
-           (ANDROID_LOG_VERBOSE != prio) ||
-           !strstr(__pmsg_file, filename) ||
-           (len != sizeof(max_payload_buf)) ||
-           !!strcmp(max_payload_buf, buf) ? -ENOEXEC : 1;
+  ++signaled;
+  if ((len != sizeof(max_payload_buf)) || strcmp(max_payload_buf, buf)) {
+    fprintf(stderr, "comparison fails on content \"%s\"\n", buf);
+  }
+  return arg || (LOG_ID_CRASH != logId) || (ANDROID_LOG_VERBOSE != prio) ||
+                 !strstr(__pmsg_file, filename) ||
+                 (len != sizeof(max_payload_buf)) ||
+                 !!strcmp(max_payload_buf, buf)
+             ? -ENOEXEC
+             : 1;
 }
+#endif
 
 TEST(liblog, __android_log_pmsg_file_read) {
-    signaled = 0;
+#ifdef __ANDROID__
+  signaled = 0;
 
-    ssize_t ret = __android_log_pmsg_file_read(
-            LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
-            __pmsg_file, __pmsg_fn, NULL);
+  __android_log_close();
+  if (getuid() == AID_ROOT) {
+    tested__android_log_close = true;
+    bool pmsgActiveAfter__android_log_close = isPmsgActive();
+    bool logdwActiveAfter__android_log_close = isLogdwActive();
+    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
+    EXPECT_FALSE(logdwActiveAfter__android_log_close);
+  } else if (!tested__android_log_close) {
+    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
+  }
 
-    if (ret == -ENOENT) {
-        fprintf(stderr,
+  ssize_t ret = __android_log_pmsg_file_read(LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
+                                             __pmsg_file, __pmsg_fn, NULL);
+
+  if (getuid() == AID_ROOT) {
+    bool pmsgActiveAfter__android_log_pmsg_file_read = isPmsgActive();
+    bool logdwActiveAfter__android_log_pmsg_file_read = isLogdwActive();
+    EXPECT_FALSE(pmsgActiveAfter__android_log_pmsg_file_read);
+    EXPECT_FALSE(logdwActiveAfter__android_log_pmsg_file_read);
+  }
+
+  if (ret == -ENOENT) {
+    fprintf(stderr,
             "No pre-boot results of liblog.__android_log_mesg_file_write to "
             "compare with,\n"
             "false positive test result.\n");
-        return;
+    return;
+  }
+
+  EXPECT_LT(0, ret);
+  EXPECT_EQ(1U, signaled);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+#endif  // USING_LOGGER_DEFAULT
+
+#ifdef USING_LOGGER_DEFAULT  // Do not retest event mapping functionality
+#ifdef __ANDROID__
+// must be: '<needle:> 0 kB'
+static bool isZero(const std::string& content, std::string::size_type pos,
+                   const char* needle) {
+  std::string::size_type offset = content.find(needle, pos);
+  return (offset != std::string::npos) &&
+         ((offset = content.find_first_not_of(" \t", offset + strlen(needle))) !=
+          std::string::npos) &&
+         (content.find_first_not_of("0", offset) != offset);
+}
+
+// must not be: '<needle:> 0 kB'
+static bool isNotZero(const std::string& content, std::string::size_type pos,
+                      const char* needle) {
+  std::string::size_type offset = content.find(needle, pos);
+  return (offset != std::string::npos) &&
+         ((offset = content.find_first_not_of(" \t", offset + strlen(needle))) !=
+          std::string::npos) &&
+         (content.find_first_not_of("123456789", offset) != offset);
+}
+
+static void event_log_tags_test_smap(pid_t pid) {
+  std::string filename = android::base::StringPrintf("/proc/%d/smaps", pid);
+
+  std::string content;
+  if (!android::base::ReadFileToString(filename, &content)) return;
+
+  bool shared_ok = false;
+  bool private_ok = false;
+  bool anonymous_ok = false;
+  bool pass_ok = false;
+
+  static const char event_log_tags[] = "event-log-tags";
+  std::string::size_type pos = 0;
+  while ((pos = content.find(event_log_tags, pos)) != std::string::npos) {
+    pos += strlen(event_log_tags);
+
+    // must not be: 'Shared_Clean: 0 kB'
+    bool ok =
+        isNotZero(content, pos, "Shared_Clean:") ||
+        // If not /etc/event-log-tags, thus r/w, then half points
+        // back for not 'Shared_Dirty: 0 kB'
+        ((content.substr(pos - 5 - strlen(event_log_tags), 5) != "/etc/") &&
+         isNotZero(content, pos, "Shared_Dirty:"));
+    if (ok && !pass_ok) {
+      shared_ok = true;
+    } else if (!ok) {
+      shared_ok = false;
     }
 
-    EXPECT_LT(0, ret);
-    EXPECT_EQ(1U, signaled);
+    // must be: 'Private_Dirty: 0 kB' and 'Private_Clean: 0 kB'
+    ok = isZero(content, pos, "Private_Dirty:") ||
+         isZero(content, pos, "Private_Clean:");
+    if (ok && !pass_ok) {
+      private_ok = true;
+    } else if (!ok) {
+      private_ok = false;
+    }
+
+    // must be: 'Anonymous: 0 kB'
+    ok = isZero(content, pos, "Anonymous:");
+    if (ok && !pass_ok) {
+      anonymous_ok = true;
+    } else if (!ok) {
+      anonymous_ok = false;
+    }
+
+    pass_ok = true;
+  }
+  content = "";
+
+  if (!pass_ok) return;
+  if (shared_ok && anonymous_ok && private_ok) return;
+
+  filename = android::base::StringPrintf("/proc/%d/comm", pid);
+  android::base::ReadFileToString(filename, &content);
+  content = android::base::StringPrintf(
+      "%d:%s", pid, content.substr(0, content.find("\n")).c_str());
+
+  EXPECT_TRUE(IsOk(shared_ok, content));
+  EXPECT_TRUE(IsOk(private_ok, content));
+  EXPECT_TRUE(IsOk(anonymous_ok, content));
 }
+#endif  // __ANDROID__
+
+TEST(liblog, event_log_tags) {
+#ifdef __ANDROID__
+  std::unique_ptr<DIR, int (*)(DIR*)> proc_dir(opendir("/proc"), closedir);
+  ASSERT_FALSE(!proc_dir);
+
+  dirent* e;
+  while ((e = readdir(proc_dir.get()))) {
+    if (e->d_type != DT_DIR) continue;
+    if (!isdigit(e->d_name[0])) continue;
+    long long id = atoll(e->d_name);
+    if (id <= 0) continue;
+    pid_t pid = id;
+    if (id != pid) continue;
+    event_log_tags_test_smap(pid);
+  }
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+#endif  // USING_LOGGER_DEFAULT
+
+#ifdef USING_LOGGER_DEFAULT  // Do not retest ratelimit
+TEST(liblog, __android_log_ratelimit) {
+  time_t state = 0;
+
+  errno = 42;
+  // Prime
+  __android_log_ratelimit(3, &state);
+  EXPECT_EQ(errno, 42);
+  // Check
+  EXPECT_FALSE(__android_log_ratelimit(3, &state));
+  sleep(1);
+  EXPECT_FALSE(__android_log_ratelimit(3, &state));
+  sleep(4);
+  EXPECT_TRUE(__android_log_ratelimit(3, &state));
+  sleep(5);
+  EXPECT_TRUE(__android_log_ratelimit(3, &state));
+
+  // API checks
+  IF_ALOG_RATELIMIT_LOCAL(3, &state) {
+    EXPECT_FALSE(0 != "IF_ALOG_RATELIMIT_LOCAL(3, &state)");
+  }
+
+  IF_ALOG_RATELIMIT() {
+    ;
+  }
+  else {
+    EXPECT_TRUE(0 == "IF_ALOG_RATELIMIT()");
+  }
+  IF_ALOG_RATELIMIT() {
+    EXPECT_FALSE(0 != "IF_ALOG_RATELIMIT()");
+  }
+  // Do not test default seconds, to allow liblog to tune freely
+}
+#endif  // USING_LOGGER_DEFAULT
+
+#ifdef USING_LOGGER_DEFAULT  // Do not retest event mapping functionality
+TEST(liblog, android_lookupEventTagNum) {
+#ifdef __ANDROID__
+  EventTagMap* map = android_openEventTagMap(NULL);
+  EXPECT_TRUE(NULL != map);
+  std::string Name = android::base::StringPrintf("a%d", getpid());
+  int tag = android_lookupEventTagNum(map, Name.c_str(), "(new|1)",
+                                      ANDROID_LOG_UNKNOWN);
+  android_closeEventTagMap(map);
+  if (tag == -1) system("tail -3 /dev/event-log-tags >&2");
+  EXPECT_NE(-1, tag);
+  EXPECT_NE(0, tag);
+  EXPECT_GT(UINT32_MAX, (unsigned)tag);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+#endif  // USING_LOGGER_DEFAULT
diff --git a/liblog/tests/liblog_test_default.cpp b/liblog/tests/liblog_test_default.cpp
new file mode 100644
index 0000000..9fc443c
--- /dev/null
+++ b/liblog/tests/liblog_test_default.cpp
@@ -0,0 +1,5 @@
+#ifdef __ANDROID__
+#include <log/log_transport.h>
+#define TEST_LOGGER LOGGER_DEFAULT
+#endif
+#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_local.cpp b/liblog/tests/liblog_test_local.cpp
new file mode 100644
index 0000000..451beca
--- /dev/null
+++ b/liblog/tests/liblog_test_local.cpp
@@ -0,0 +1,4 @@
+#include <log/log_transport.h>
+#define liblog liblog_local
+#define TEST_LOGGER LOGGER_LOCAL
+#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_stderr.cpp b/liblog/tests/liblog_test_stderr.cpp
new file mode 100644
index 0000000..abc1b9c
--- /dev/null
+++ b/liblog/tests/liblog_test_stderr.cpp
@@ -0,0 +1,5 @@
+#include <log/log_transport.h>
+#define liblog liblog_stderr
+#define TEST_LOGGER LOGGER_STDERR
+#define USING_LOGGER_STDERR
+#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_stderr_local.cpp b/liblog/tests/liblog_test_stderr_local.cpp
new file mode 100644
index 0000000..bb5c7ae
--- /dev/null
+++ b/liblog/tests/liblog_test_stderr_local.cpp
@@ -0,0 +1,4 @@
+#include <log/log_transport.h>
+#define liblog liblog_stderr_local
+#define TEST_LOGGER (LOGGER_LOCAL | LOGGER_STDERR)
+#include "liblog_test.cpp"
diff --git a/liblog/tests/log_id_test.cpp b/liblog/tests/log_id_test.cpp
new file mode 100644
index 0000000..c56fa8b
--- /dev/null
+++ b/liblog/tests/log_id_test.cpp
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2013-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 <inttypes.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <gtest/gtest.h>
+// Test the APIs in this standalone include file
+#include <log/log_id.h>
+
+// We do not want to include <android/log.h> to acquire ANDROID_LOG_INFO for
+// include file API purity.  We do however want to allow the _option_ that
+// log/log_id.h could include this file, or related content, in the future.
+#ifndef __android_LogPriority_defined
+#define ANDROID_LOG_INFO 4
+#endif
+
+TEST(liblog, log_id) {
+  int count = 0;
+
+  for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
+    log_id_t id = static_cast<log_id_t>(i);
+    const char* name = android_log_id_to_name(id);
+    if (id != android_name_to_log_id(name)) {
+      continue;
+    }
+    ++count;
+    fprintf(stderr, "log buffer %s\r", name);
+  }
+  ASSERT_EQ(LOG_ID_MAX, count);
+}
+
+TEST(liblog, __android_log_buf_print) {
+  EXPECT_LT(0, __android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO,
+                                       "TEST__android_log_buf_print", "radio"));
+  usleep(1000);
+  EXPECT_LT(0,
+            __android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
+                                    "TEST__android_log_buf_print", "system"));
+  usleep(1000);
+  EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
+                                       "TEST__android_log_buf_print", "main"));
+  usleep(1000);
+}
+
+TEST(liblog, __android_log_buf_write) {
+  EXPECT_LT(0, __android_log_buf_write(LOG_ID_RADIO, ANDROID_LOG_INFO,
+                                       "TEST__android_log_buf_write", "radio"));
+  usleep(1000);
+  EXPECT_LT(0,
+            __android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
+                                    "TEST__android_log_buf_write", "system"));
+  usleep(1000);
+  EXPECT_LT(0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO,
+                                       "TEST__android_log_buf_write", "main"));
+  usleep(1000);
+}
+
+static void* ConcurrentPrintFn(void* arg) {
+  int ret = __android_log_buf_print(
+      LOG_ID_MAIN, ANDROID_LOG_INFO, "TEST__android_log_print",
+      "Concurrent %" PRIuPTR, reinterpret_cast<uintptr_t>(arg));
+  return reinterpret_cast<void*>(ret);
+}
+
+#define NUM_CONCURRENT 64
+#define _concurrent_name(a, n) a##__concurrent##n
+#define concurrent_name(a, n) _concurrent_name(a, n)
+
+TEST(liblog, concurrent_name(__android_log_buf_print, NUM_CONCURRENT)) {
+  pthread_t t[NUM_CONCURRENT];
+  int i;
+  for (i = 0; i < NUM_CONCURRENT; i++) {
+    ASSERT_EQ(0, pthread_create(&t[i], NULL, ConcurrentPrintFn,
+                                reinterpret_cast<void*>(i)));
+  }
+  int ret = 0;
+  for (i = 0; i < NUM_CONCURRENT; i++) {
+    void* result;
+    ASSERT_EQ(0, pthread_join(t[i], &result));
+    int this_result = reinterpret_cast<uintptr_t>(result);
+    if ((0 == ret) && (0 != this_result)) {
+      ret = this_result;
+    }
+  }
+  ASSERT_LT(0, ret);
+}
diff --git a/liblog/tests/log_radio_test.cpp b/liblog/tests/log_radio_test.cpp
new file mode 100644
index 0000000..f202c67
--- /dev/null
+++ b/liblog/tests/log_radio_test.cpp
@@ -0,0 +1,119 @@
+/*
+ * 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 <stdio.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <gtest/gtest.h>
+// Test the APIs in this standalone include file
+#include <log/log_radio.h>
+
+TEST(liblog, RLOG) {
+  static const char content[] = "log_radio.h";
+  static const char content_false[] = "log_radio.h false";
+
+// ratelimit content to 10/s to keep away from spam filters
+// do not send identical content together to keep away from spam filters
+
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGV"
+  RLOGV(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGD"
+  RLOGD(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGI"
+  RLOGI(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGW"
+  RLOGW(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGE"
+  RLOGE(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGV"
+  RLOGV_IF(true, content);
+  usleep(100000);
+  RLOGV_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGD"
+  RLOGD_IF(true, content);
+  usleep(100000);
+  RLOGD_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGI"
+  RLOGI_IF(true, content);
+  usleep(100000);
+  RLOGI_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGW"
+  RLOGW_IF(true, content);
+  usleep(100000);
+  RLOGW_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__RLOGE"
+  RLOGE_IF(true, content);
+  usleep(100000);
+  RLOGE_IF(false, content_false);
+
+#ifdef __ANDROID__
+  // give time for content to long-path through logger
+  sleep(1);
+
+  std::string buf = android::base::StringPrintf(
+      "logcat -b radio --pid=%u -d -s"
+      " TEST__RLOGV TEST__RLOGD TEST__RLOGI TEST__RLOGW TEST__RLOGE",
+      (unsigned)getpid());
+  FILE* fp = popen(buf.c_str(), "r");
+  int count = 0;
+  int count_false = 0;
+  if (fp) {
+    if (!android::base::ReadFdToString(fileno(fp), &buf)) buf = "";
+    pclose(fp);
+    for (size_t pos = 0; (pos = buf.find(content, pos)) != std::string::npos;
+         ++pos) {
+      ++count;
+    }
+    for (size_t pos = 0;
+         (pos = buf.find(content_false, pos)) != std::string::npos; ++pos) {
+      ++count_false;
+    }
+  }
+  EXPECT_EQ(0, count_false);
+#if LOG_NDEBUG
+  ASSERT_EQ(8, count);
+#else
+  ASSERT_EQ(10, count);
+#endif
+
+#else
+  GTEST_LOG_(INFO) << "This test does not test end-to-end.\n";
+#endif
+}
diff --git a/liblog/tests/log_read_test.cpp b/liblog/tests/log_read_test.cpp
new file mode 100644
index 0000000..6ed568a
--- /dev/null
+++ b/liblog/tests/log_read_test.cpp
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2013-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 <time.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <android/log.h>  // minimal logging API
+#include <gtest/gtest.h>
+#include <log/log_properties.h>
+// Test the APIs in this standalone include file
+#include <log/log_read.h>
+// Do not use anything in log/log_time.h despite side effects of the above.
+
+TEST(liblog, __android_log_write__android_logger_list_read) {
+#ifdef __ANDROID__
+  pid_t pid = getpid();
+
+  struct logger_list* logger_list;
+  ASSERT_TRUE(
+      NULL !=
+      (logger_list = android_logger_list_open(
+           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
+
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  std::string buf = android::base::StringPrintf("pid=%u ts=%ld.%09ld", pid,
+                                                ts.tv_sec, ts.tv_nsec);
+  static const char tag[] =
+      "liblog.__android_log_write__android_logger_list_read";
+  static const char prio = ANDROID_LOG_DEBUG;
+  ASSERT_LT(0, __android_log_write(prio, tag, buf.c_str()));
+  usleep(1000000);
+
+  buf = std::string(&prio, sizeof(prio)) + tag + std::string("", 1) + buf +
+        std::string("", 1);
+
+  int count = 0;
+
+  for (;;) {
+    log_msg log_msg;
+    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
+
+    EXPECT_EQ(log_msg.entry.pid, pid);
+    // There may be a future where we leak "liblog" tagged LOG_ID_EVENT
+    // binary messages through so that logger losses can be correlated?
+    EXPECT_EQ(log_msg.id(), LOG_ID_MAIN);
+
+    if (log_msg.entry.len != buf.length()) continue;
+
+    if (buf != std::string(log_msg.msg(), log_msg.entry.len)) continue;
+
+    ++count;
+  }
+  android_logger_list_close(logger_list);
+
+  EXPECT_EQ(1, count);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(liblog, android_logger_get_) {
+#ifdef __ANDROID__
+  // This test assumes the log buffers are filled with noise from
+  // normal operations. It will fail if done immediately after a
+  // logcat -c.
+  struct logger_list* logger_list =
+      android_logger_list_alloc(ANDROID_LOG_WRONLY, 0, 0);
+
+  for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
+    log_id_t id = static_cast<log_id_t>(i);
+    const char* name = android_log_id_to_name(id);
+    if (id != android_name_to_log_id(name)) {
+      continue;
+    }
+    fprintf(stderr, "log buffer %s\r", name);
+    struct logger* logger;
+    EXPECT_TRUE(NULL != (logger = android_logger_open(logger_list, id)));
+    EXPECT_EQ(id, android_logger_get_id(logger));
+    ssize_t get_log_size = android_logger_get_log_size(logger);
+    /* security buffer is allowed to be denied */
+    if (strcmp("security", name)) {
+      EXPECT_LT(0, get_log_size);
+      // crash buffer is allowed to be empty, that is actually healthy!
+      // kernel buffer is allowed to be empty on "user" builds
+      EXPECT_LE(  // boolean 1 or 0 depending on expected content or empty
+          !!((strcmp("crash", name) != 0) &&
+             ((strcmp("kernel", name) != 0) || __android_log_is_debuggable())),
+          android_logger_get_log_readable_size(logger));
+    } else {
+      EXPECT_NE(0, get_log_size);
+      if (get_log_size < 0) {
+        EXPECT_GT(0, android_logger_get_log_readable_size(logger));
+      } else {
+        EXPECT_LE(0, android_logger_get_log_readable_size(logger));
+      }
+    }
+    EXPECT_LT(0, android_logger_get_log_version(logger));
+  }
+
+  android_logger_list_close(logger_list);
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
diff --git a/liblog/tests/log_system_test.cpp b/liblog/tests/log_system_test.cpp
new file mode 100644
index 0000000..0656c0b
--- /dev/null
+++ b/liblog/tests/log_system_test.cpp
@@ -0,0 +1,119 @@
+/*
+ * 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 <stdio.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <gtest/gtest.h>
+// Test the APIs in this standalone include file
+#include <log/log_system.h>
+
+TEST(liblog, SLOG) {
+  static const char content[] = "log_system.h";
+  static const char content_false[] = "log_system.h false";
+
+// ratelimit content to 10/s to keep away from spam filters
+// do not send identical content together to keep away from spam filters
+
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGV"
+  SLOGV(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGD"
+  SLOGD(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGI"
+  SLOGI(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGW"
+  SLOGW(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGE"
+  SLOGE(content);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGV"
+  SLOGV_IF(true, content);
+  usleep(100000);
+  SLOGV_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGD"
+  SLOGD_IF(true, content);
+  usleep(100000);
+  SLOGD_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGI"
+  SLOGI_IF(true, content);
+  usleep(100000);
+  SLOGI_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGW"
+  SLOGW_IF(true, content);
+  usleep(100000);
+  SLOGW_IF(false, content_false);
+  usleep(100000);
+#undef LOG_TAG
+#define LOG_TAG "TEST__SLOGE"
+  SLOGE_IF(true, content);
+  usleep(100000);
+  SLOGE_IF(false, content_false);
+
+#ifdef __ANDROID__
+  // give time for content to long-path through logger
+  sleep(1);
+
+  std::string buf = android::base::StringPrintf(
+      "logcat -b system --pid=%u -d -s"
+      " TEST__SLOGV TEST__SLOGD TEST__SLOGI TEST__SLOGW TEST__SLOGE",
+      (unsigned)getpid());
+  FILE* fp = popen(buf.c_str(), "r");
+  int count = 0;
+  int count_false = 0;
+  if (fp) {
+    if (!android::base::ReadFdToString(fileno(fp), &buf)) buf = "";
+    pclose(fp);
+    for (size_t pos = 0; (pos = buf.find(content, pos)) != std::string::npos;
+         ++pos) {
+      ++count;
+    }
+    for (size_t pos = 0;
+         (pos = buf.find(content_false, pos)) != std::string::npos; ++pos) {
+      ++count_false;
+    }
+  }
+  EXPECT_EQ(0, count_false);
+#if LOG_NDEBUG
+  ASSERT_EQ(8, count);
+#else
+  ASSERT_EQ(10, count);
+#endif
+
+#else
+  GTEST_LOG_(INFO) << "This test does not test end-to-end.\n";
+#endif
+}
diff --git a/liblog/tests/log_time_test.cpp b/liblog/tests/log_time_test.cpp
new file mode 100644
index 0000000..0ae1d18
--- /dev/null
+++ b/liblog/tests/log_time_test.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 <time.h>
+
+#include <gtest/gtest.h>
+// Test the APIs in this standalone include file
+#include <log/log_time.h>
+
+TEST(liblog, log_time) {
+#ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
+  log_time(CLOCK_MONOTONIC);
+
+  EXPECT_EQ(log_time, log_time::EPOCH);
+#endif
+
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  log_time tl(ts);
+
+  EXPECT_EQ(tl, ts);
+  EXPECT_GE(tl, ts);
+  EXPECT_LE(tl, ts);
+}
diff --git a/liblog/uio.c b/liblog/uio.c
index ac0558f..e127202 100644
--- a/liblog/uio.c
+++ b/liblog/uio.c
@@ -22,58 +22,52 @@
 
 #include "log_portability.h"
 
-LIBLOG_ABI_PUBLIC int readv(int fd, struct iovec *vecs, int count)
-{
-    int   total = 0;
+LIBLOG_ABI_PUBLIC int readv(int fd, struct iovec* vecs, int count) {
+  int total = 0;
 
-    for ( ; count > 0; count--, vecs++ ) {
-        char*  buf = vecs->iov_base;
-        int    len = vecs->iov_len;
+  for (; count > 0; count--, vecs++) {
+    char* buf = vecs->iov_base;
+    int len = vecs->iov_len;
 
-        while (len > 0) {
-            int  ret = read( fd, buf, len );
-            if (ret < 0) {
-                if (total == 0)
-                    total = -1;
-                goto Exit;
-            }
-            if (ret == 0)
-                goto Exit;
+    while (len > 0) {
+      int ret = read(fd, buf, len);
+      if (ret < 0) {
+        if (total == 0) total = -1;
+        goto Exit;
+      }
+      if (ret == 0) goto Exit;
 
-            total += ret;
-            buf   += ret;
-            len   -= ret;
-        }
+      total += ret;
+      buf += ret;
+      len -= ret;
     }
+  }
 Exit:
-    return total;
+  return total;
 }
 
-LIBLOG_ABI_PUBLIC int writev(int fd, const struct iovec *vecs, int count)
-{
-    int   total = 0;
+LIBLOG_ABI_PUBLIC int writev(int fd, const struct iovec* vecs, int count) {
+  int total = 0;
 
-    for ( ; count > 0; count--, vecs++ ) {
-        const char*  buf = vecs->iov_base;
-        int          len = vecs->iov_len;
+  for (; count > 0; count--, vecs++) {
+    const char* buf = vecs->iov_base;
+    int len = vecs->iov_len;
 
-        while (len > 0) {
-            int  ret = write( fd, buf, len );
-            if (ret < 0) {
-                if (total == 0)
-                    total = -1;
-                goto Exit;
-            }
-            if (ret == 0)
-                goto Exit;
+    while (len > 0) {
+      int ret = write(fd, buf, len);
+      if (ret < 0) {
+        if (total == 0) total = -1;
+        goto Exit;
+      }
+      if (ret == 0) goto Exit;
 
-            total += ret;
-            buf   += ret;
-            len   -= ret;
-        }
+      total += ret;
+      buf += ret;
+      len -= ret;
     }
+  }
 Exit:
-    return total;
+  return total;
 }
 
 #endif
diff --git a/libmemtrack/Android.bp b/libmemtrack/Android.bp
new file mode 100644
index 0000000..68c580a
--- /dev/null
+++ b/libmemtrack/Android.bp
@@ -0,0 +1,36 @@
+// Copyright 2013 The Android Open Source Project
+
+cc_library_shared {
+    name: "libmemtrack",
+    srcs: ["memtrack.cpp"],
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+    include_dirs: ["hardware/libhardware/include"],
+    shared_libs: [
+        "libhardware",
+        "liblog",
+        "libbase",
+        "libhidlbase",
+        "libhidltransport",
+        "libhwbinder",
+        "libutils",
+        "android.hardware.memtrack@1.0",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
+
+cc_binary {
+    name: "memtrack_test",
+    srcs: ["memtrack_test.c"],
+    shared_libs: [
+        "libmemtrack",
+        "libpagemap",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
diff --git a/libmemtrack/Android.mk b/libmemtrack/Android.mk
deleted file mode 100644
index 7b170f5..0000000
--- a/libmemtrack/Android.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2013 The Android Open Source Project
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := memtrack.c
-LOCAL_MODULE := libmemtrack
-LOCAL_C_INCLUDES += hardware/libhardware/include
-LOCAL_SHARED_LIBRARIES := libhardware liblog
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := memtrack_test.c
-LOCAL_MODULE := memtrack_test
-LOCAL_SHARED_LIBRARIES := libmemtrack libpagemap
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_EXECUTABLE)
diff --git a/libmemtrack/include/memtrack/memtrack.h b/libmemtrack/include/memtrack/memtrack.h
new file mode 100644
index 0000000..2134a6f
--- /dev/null
+++ b/libmemtrack/include/memtrack/memtrack.h
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBMEMTRACK_MEMTRACK_H_
+#define _LIBMEMTRACK_MEMTRACK_H_
+
+#include <sys/types.h>
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * struct memtrack_proc
+ *
+ * an opaque handle to the memory stats on a process.
+ * Created with memtrack_proc_new, destroyed by
+ * memtrack_proc_destroy.  Can be reused multiple times with
+ * memtrack_proc_get.
+ */
+struct memtrack_proc;
+
+/**
+ * memtrack_proc_new
+ *
+ * Return a new handle to hold process memory stats.
+ *
+ * Returns NULL on error.
+ */
+struct memtrack_proc *memtrack_proc_new(void);
+
+/**
+ * memtrack_proc_destroy
+ *
+ * Free all memory associated with a process memory stats handle.
+ */
+void memtrack_proc_destroy(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_get
+ *
+ * Fill a process memory stats handle with data about the given pid.  Can be
+ * called on a handle that was just allocated with memtrack_proc_new,
+ * or on a handle that has been previously passed to memtrack_proc_get
+ * to replace the data with new data on the same or another process.  It is
+ * expected that the second call on the same handle should not require
+ * allocating any new memory.
+ *
+ * Returns 0 on success, -errno on error.
+ */
+int memtrack_proc_get(struct memtrack_proc *p, pid_t pid);
+
+/**
+ * memtrack_proc_graphics_total
+ *
+ * Return total amount of memory that has been allocated for use as window
+ * buffers.  Does not differentiate between memory that has already been
+ * accounted for by reading /proc/pid/smaps and memory that has not been
+ * accounted for.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_graphics_total(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_graphics_pss
+ *
+ * Return total amount of memory that has been allocated for use as window
+ * buffers, but has not already been accounted for by reading /proc/pid/smaps.
+ * Memory that is shared across processes may already be divided by the
+ * number of processes that share it (preferred), or may be charged in full to
+ * every process that shares it, depending on the capabilities of the driver.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_graphics_pss(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_gl_total
+ *
+ * Same as memtrack_proc_graphics_total, but counts GL memory (which
+ * should not overlap with graphics memory) instead of graphics memory.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_gl_total(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_gl_pss
+ *
+ * Same as memtrack_proc_graphics_total, but counts GL memory (which
+ * should not overlap with graphics memory) instead of graphics memory.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_gl_pss(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_other_total
+ *
+ * Same as memtrack_proc_graphics_total, but counts miscellaneous memory
+ * not tracked by gl or graphics calls above.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_other_total(struct memtrack_proc *p);
+
+/**
+ * memtrack_proc_other_pss
+ *
+ * Same as memtrack_proc_graphics_total, but counts miscellaneous memory
+ * not tracked by gl or graphics calls above.
+ *
+ * Returns non-negative size in bytes on success, -errno on error.
+ */
+ssize_t memtrack_proc_other_pss(struct memtrack_proc *p);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libmemtrack/memtrack.c b/libmemtrack/memtrack.c
deleted file mode 100644
index 21d9ebd..0000000
--- a/libmemtrack/memtrack.c
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <memtrack/memtrack.h>
-
-#define LOG_TAG "memtrack"
-
-#include <log/log.h>
-
-#include <errno.h>
-#include <malloc.h>
-#include <string.h>
-
-#include <hardware/memtrack.h>
-
-#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
-
-static const memtrack_module_t *module;
-
-struct memtrack_proc {
-    pid_t pid;
-    struct memtrack_proc_type {
-        enum memtrack_type type;
-        size_t num_records;
-        size_t allocated_records;
-        struct memtrack_record *records;
-    } types[MEMTRACK_NUM_TYPES];
-};
-
-int memtrack_init(void)
-{
-    int err;
-
-    if (module) {
-        return 0;
-    }
-
-    err = hw_get_module(MEMTRACK_HARDWARE_MODULE_ID,
-            (hw_module_t const**)&module);
-    if (err) {
-        ALOGE("Couldn't load %s module (%s)", MEMTRACK_HARDWARE_MODULE_ID,
-                strerror(-err));
-        return err;
-    }
-
-    return module->init(module);
-}
-
-struct memtrack_proc *memtrack_proc_new(void)
-{
-    if (!module) {
-        return NULL;
-    }
-
-    return calloc(sizeof(struct memtrack_proc), 1);
-}
-
-void memtrack_proc_destroy(struct memtrack_proc *p)
-{
-    enum memtrack_type i;
-
-    if (p) {
-        for (i = 0; i < MEMTRACK_NUM_TYPES; i++) {
-            free(p->types[i].records);
-        }
-    }
-    free(p);
-}
-
-static int memtrack_proc_get_type(struct memtrack_proc_type *t,
-            pid_t pid, enum memtrack_type type)
-{
-    size_t num_records = t->num_records;
-    int ret;
-
-retry:
-    ret = module->getMemory(module, pid, type, t->records, &num_records);
-    if (ret) {
-        t->num_records = 0;
-        return ret;
-    }
-    if (num_records > t->allocated_records) {
-        /* Need more records than allocated */
-        free(t->records);
-        t->records = calloc(sizeof(*t->records), num_records);
-        if (!t->records) {
-            return -ENOMEM;
-        }
-        t->allocated_records = num_records;
-        goto retry;
-    }
-    t->num_records = num_records;
-
-    return 0;
-}
-
-/* TODO: sanity checks on return values from HALs:
- *   make sure no records have invalid flags set
- *    - unknown flags
- *    - too many flags of a single category
- *    - missing ACCOUNTED/UNACCOUNTED
- *   make sure there are not overlapping SHARED and SHARED_PSS records
- */
-static int memtrack_proc_sanity_check(struct memtrack_proc *p)
-{
-    (void)p;
-    return 0;
-}
-
-int memtrack_proc_get(struct memtrack_proc *p, pid_t pid)
-{
-    enum memtrack_type i;
-
-    if (!module) {
-        return -EINVAL;
-    }
-
-    if (!p) {
-        return -EINVAL;
-    }
-
-    p->pid = pid;
-    for (i = 0; i < MEMTRACK_NUM_TYPES; i++) {
-        memtrack_proc_get_type(&p->types[i], pid, i);
-    }
-
-    return memtrack_proc_sanity_check(p);
-}
-
-static ssize_t memtrack_proc_sum(struct memtrack_proc *p,
-            enum memtrack_type types[], size_t num_types,
-            unsigned int flags)
-{
-    ssize_t sum = 0;
-    size_t i;
-    size_t j;
-
-    for (i = 0; i < num_types; i++) {
-        enum memtrack_type type = types[i];
-        for (j = 0; j < p->types[type].num_records; j++) {
-            if ((p->types[type].records[j].flags & flags) == flags) {
-                sum += p->types[type].records[j].size_in_bytes;
-            }
-        }
-    }
-
-    return sum;
-}
-
-ssize_t memtrack_proc_graphics_total(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_GRAPHICS };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types), 0);
-}
-
-ssize_t memtrack_proc_graphics_pss(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_GRAPHICS };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types),
-                MEMTRACK_FLAG_SMAPS_UNACCOUNTED);
-}
-
-ssize_t memtrack_proc_gl_total(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_GL };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types), 0);
-}
-
-ssize_t memtrack_proc_gl_pss(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_GL };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types),
-                MEMTRACK_FLAG_SMAPS_UNACCOUNTED);
-}
-
-ssize_t memtrack_proc_other_total(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_MULTIMEDIA,
-                                        MEMTRACK_TYPE_CAMERA,
-                                        MEMTRACK_TYPE_OTHER };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types), 0);
-}
-
-ssize_t memtrack_proc_other_pss(struct memtrack_proc *p)
-{
-    enum memtrack_type types[] = { MEMTRACK_TYPE_MULTIMEDIA,
-                                        MEMTRACK_TYPE_CAMERA,
-                                        MEMTRACK_TYPE_OTHER };
-    return memtrack_proc_sum(p, types, ARRAY_SIZE(types),
-                MEMTRACK_FLAG_SMAPS_UNACCOUNTED);
-}
diff --git a/libmemtrack/memtrack.cpp b/libmemtrack/memtrack.cpp
new file mode 100644
index 0000000..c5e74c1
--- /dev/null
+++ b/libmemtrack/memtrack.cpp
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "memtrack"
+#include <android/hardware/memtrack/1.0/IMemtrack.h>
+#include <memtrack/memtrack.h>
+
+#include <errno.h>
+#include <malloc.h>
+#include <vector>
+#include <string.h>
+#include <mutex>
+
+#include <log/log.h>
+
+using android::hardware::memtrack::V1_0::IMemtrack;
+using android::hardware::memtrack::V1_0::MemtrackType;
+using android::hardware::memtrack::V1_0::MemtrackRecord;
+using android::hardware::memtrack::V1_0::MemtrackFlag;
+using android::hardware::memtrack::V1_0::MemtrackStatus;
+using android::hardware::hidl_vec;
+using android::hardware::Return;
+
+struct memtrack_proc_type {
+    MemtrackType type;
+    std::vector<MemtrackRecord> records;
+};
+
+struct memtrack_proc {
+    pid_t pid;
+    memtrack_proc_type types[static_cast<int>(MemtrackType::NUM_TYPES)];
+};
+
+//TODO(b/31632518)
+static android::sp<IMemtrack> get_instance() {
+    static android::sp<IMemtrack> module = IMemtrack::getService();
+    if (module == nullptr) {
+        ALOGE("Couldn't load memtrack module");
+    }
+    return module;
+}
+
+memtrack_proc *memtrack_proc_new(void)
+{
+    return new memtrack_proc();
+}
+
+void memtrack_proc_destroy(memtrack_proc *p)
+{
+    delete(p);
+}
+
+static int memtrack_proc_get_type(memtrack_proc_type *t,
+        pid_t pid, MemtrackType type)
+{
+    int err = 0;
+    android::sp<IMemtrack> memtrack = get_instance();
+    if (memtrack == nullptr)
+        return -1;
+
+    Return<void> ret = memtrack->getMemory(pid, type,
+        [&t, &err](MemtrackStatus status, hidl_vec<MemtrackRecord> records) {
+            if (status != MemtrackStatus::SUCCESS) {
+                err = -1;
+                t->records.resize(0);
+            }
+            t->records.resize(records.size());
+            for (size_t i = 0; i < records.size(); i++) {
+                t->records[i].sizeInBytes = records[i].sizeInBytes;
+                t->records[i].flags = records[i].flags;
+            }
+    });
+    return ret.isOk() ? err : -1;
+}
+
+/* TODO: sanity checks on return values from HALs:
+ *   make sure no records have invalid flags set
+ *    - unknown flags
+ *    - too many flags of a single category
+ *    - missing ACCOUNTED/UNACCOUNTED
+ *   make sure there are not overlapping SHARED and SHARED_PSS records
+ */
+static int memtrack_proc_sanity_check(memtrack_proc* /*p*/)
+{
+    return 0;
+}
+
+int memtrack_proc_get(memtrack_proc *p, pid_t pid)
+{
+    if (!p) {
+        return -EINVAL;
+    }
+
+    p->pid = pid;
+    for (uint32_t i = 0; i < (uint32_t)MemtrackType::NUM_TYPES; i++) {
+        int ret = memtrack_proc_get_type(&p->types[i], pid, (MemtrackType)i);
+        if (ret != 0)
+           return ret;
+    }
+
+    return memtrack_proc_sanity_check(p);
+}
+
+static ssize_t memtrack_proc_sum(memtrack_proc *p,
+        const std::vector<MemtrackType>& types, uint32_t flags)
+{
+    ssize_t sum = 0;
+
+    for (size_t i = 0; i < types.size(); i++) {
+        memtrack_proc_type type = p->types[static_cast<int>(types[i])];
+        std::vector<MemtrackRecord> records = type.records;
+        for (size_t j = 0; j < records.size(); j++) {
+            if ((records[j].flags & flags) == flags) {
+                sum += records[j].sizeInBytes;
+            }
+        }
+    }
+
+    return sum;
+}
+
+ssize_t memtrack_proc_graphics_total(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = {MemtrackType::GRAPHICS};
+    return memtrack_proc_sum(p, types, 0);
+}
+
+ssize_t memtrack_proc_graphics_pss(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = { MemtrackType::GRAPHICS };
+    return memtrack_proc_sum(p, types,
+            (uint32_t)MemtrackFlag::SMAPS_UNACCOUNTED);
+}
+
+ssize_t memtrack_proc_gl_total(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = { MemtrackType::GL };
+    return memtrack_proc_sum(p, types, 0);
+}
+
+ssize_t memtrack_proc_gl_pss(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = { MemtrackType::GL };
+    return memtrack_proc_sum(p, types,
+            (uint32_t)MemtrackFlag::SMAPS_UNACCOUNTED);
+}
+
+ssize_t memtrack_proc_other_total(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = { MemtrackType::MULTIMEDIA,
+            MemtrackType::CAMERA, MemtrackType::OTHER };
+    return memtrack_proc_sum(p, types, 0);
+}
+
+ssize_t memtrack_proc_other_pss(memtrack_proc *p)
+{
+    std::vector<MemtrackType> types = { MemtrackType::MULTIMEDIA,
+            MemtrackType::CAMERA, MemtrackType::OTHER };
+    return memtrack_proc_sum(p, types,
+            (uint32_t)MemtrackFlag::SMAPS_UNACCOUNTED);
+}
diff --git a/libmemtrack/memtrack_test.c b/libmemtrack/memtrack_test.c
index eaadfa7..77c935e 100644
--- a/libmemtrack/memtrack_test.c
+++ b/libmemtrack/memtrack_test.c
@@ -82,12 +82,6 @@
     (void)argc;
     (void)argv;
 
-    ret = memtrack_init();
-    if (ret < 0) {
-        fprintf(stderr, "failed to initialize HAL: %s (%d)\n", strerror(-ret), ret);
-        exit(EXIT_FAILURE);
-    }
-
     ret = pm_kernel_create(&ker);
     if (ret) {
         fprintf(stderr, "Error creating kernel interface -- "
diff --git a/libmemunreachable/Allocator.cpp b/libmemunreachable/Allocator.cpp
index 68f654c..6fe67a4 100644
--- a/libmemunreachable/Allocator.cpp
+++ b/libmemunreachable/Allocator.cpp
@@ -52,8 +52,6 @@
   return (x + y - 1) / y;
 }
 
-#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
-
 static constexpr size_t kPageSize = 4096;
 static constexpr size_t kChunkSize = 256 * 1024;
 static constexpr size_t kUsableChunkSize = kChunkSize - kPageSize;
@@ -258,7 +256,7 @@
   unsigned int i = first_free_bitmap_;
   while (free_bitmap_[i] == 0)
     i++;
-  assert(i < ARRAY_SIZE(free_bitmap_));
+  assert(i < arraysize(free_bitmap_));
   unsigned int bit = __builtin_ffs(free_bitmap_[i]) - 1;
   assert(free_bitmap_[i] & (1U << bit));
   free_bitmap_[i] &= ~(1U << bit);
@@ -266,7 +264,7 @@
   assert(n < max_allocations_);
 
   unsigned int page = n * allocation_size_ / kPageSize;
-  assert(page / 32 < ARRAY_SIZE(dirty_pages_));
+  assert(page / 32 < arraysize(dirty_pages_));
   dirty_pages_[page / 32] |= 1U << (page % 32);
 
   free_count_--;
@@ -285,7 +283,7 @@
   unsigned int i = n / 32;
   unsigned int bit = n % 32;
 
-  assert(i < ARRAY_SIZE(free_bitmap_));
+  assert(i < arraysize(free_bitmap_));
   assert(!(free_bitmap_[i] & (1U << bit)));
   free_bitmap_[i] |= 1U << bit;
   free_count_++;
diff --git a/libmemunreachable/Allocator.h b/libmemunreachable/Allocator.h
index a8f579e..5390739 100644
--- a/libmemunreachable/Allocator.h
+++ b/libmemunreachable/Allocator.h
@@ -109,13 +109,13 @@
   }
 
   // Construct an STLAllocator on top of a Heap
-  STLAllocator(const Heap& heap) :
+  STLAllocator(const Heap& heap) :  // NOLINT, implicit
       heap_(heap) {
   }
 
   // Rebind an STLAllocator from an another STLAllocator
   template<typename U>
-  STLAllocator(const STLAllocator<U>& other) :
+  STLAllocator(const STLAllocator<U>& other) :  // NOLINT, implicit
       heap_(other.heap_) {
   }
 
@@ -155,12 +155,12 @@
  public:
   ~Allocator() {}
 
-  Allocator(const Heap& other) :
+  Allocator(const Heap& other) : // NOLINT, implicit
       STLAllocator<T>(other) {
   }
 
   template<typename U>
-  Allocator(const STLAllocator<U>& other) :
+  Allocator(const STLAllocator<U>& other) :  // NOLINT, implicit
       STLAllocator<T>(other) {
   }
 
diff --git a/libmemunreachable/Android.bp b/libmemunreachable/Android.bp
new file mode 100644
index 0000000..1b8830a
--- /dev/null
+++ b/libmemunreachable/Android.bp
@@ -0,0 +1,80 @@
+cc_defaults {
+    name: "libmemunreachable_defaults",
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+    clang: true,
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+}
+
+cc_library_shared {
+    name: "libmemunreachable",
+    vendor_available: true,
+    defaults: ["libmemunreachable_defaults"],
+    srcs: [
+        "Allocator.cpp",
+        "HeapWalker.cpp",
+        "LeakFolding.cpp",
+        "LeakPipe.cpp",
+        "LineBuffer.cpp",
+        "MemUnreachable.cpp",
+        "ProcessMappings.cpp",
+        "PtracerThread.cpp",
+        "ThreadCapture.cpp",
+    ],
+
+    static_libs: [
+        "libc_malloc_debug_backtrace",
+        "libc_logging",
+    ],
+    // Only need this for arm since libc++ uses its own unwind code that
+    // doesn't mix with the other default unwind code.
+    arch: {
+        arm: {
+            static_libs: ["libunwind_llvm"],
+        },
+    },
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+}
+
+cc_test {
+    name: "memunreachable_test",
+    defaults: ["libmemunreachable_defaults"],
+    host_supported: true,
+    srcs: [
+        "tests/Allocator_test.cpp",
+        "tests/HeapWalker_test.cpp",
+        "tests/LeakFolding_test.cpp",
+    ],
+
+    target: {
+        android: {
+            srcs: [
+                "tests/DisableMalloc_test.cpp",
+                "tests/MemUnreachable_test.cpp",
+                "tests/ThreadCapture_test.cpp",
+            ],
+            shared_libs: [
+                "libmemunreachable",
+            ],
+        },
+        host: {
+            srcs: [
+                "Allocator.cpp",
+                "HeapWalker.cpp",
+                "LeakFolding.cpp",
+                "tests/HostMallocStub.cpp",
+            ],
+        },
+        darwin: {
+            enabled: false,
+        },
+    },
+}
diff --git a/libmemunreachable/Android.mk b/libmemunreachable/Android.mk
deleted file mode 100644
index 7b66d44..0000000
--- a/libmemunreachable/Android.mk
+++ /dev/null
@@ -1,65 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-memunreachable_srcs := \
-   Allocator.cpp \
-   HeapWalker.cpp \
-   LeakFolding.cpp \
-   LeakPipe.cpp \
-   LineBuffer.cpp \
-   MemUnreachable.cpp \
-   ProcessMappings.cpp \
-   PtracerThread.cpp \
-   ThreadCapture.cpp \
-
-memunreachable_test_srcs := \
-   tests/Allocator_test.cpp \
-   tests/DisableMalloc_test.cpp \
-   tests/HeapWalker_test.cpp \
-   tests/LeakFolding_test.cpp \
-   tests/MemUnreachable_test.cpp \
-   tests/ThreadCapture_test.cpp \
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libmemunreachable
-LOCAL_SRC_FILES := $(memunreachable_srcs)
-LOCAL_CFLAGS := -std=c++14 -Wall -Wextra -Werror
-LOCAL_SHARED_LIBRARIES := libbase liblog
-LOCAL_STATIC_LIBRARIES := libc_malloc_debug_backtrace libc_logging
-# Only need this for arm since libc++ uses its own unwind code that
-# doesn't mix with the other default unwind code.
-LOCAL_STATIC_LIBRARIES_arm := libunwind_llvm
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CLANG := true
-
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := memunreachable_test
-LOCAL_SRC_FILES := $(memunreachable_test_srcs)
-LOCAL_CFLAGS := -std=c++14 -Wall -Wextra -Werror
-LOCAL_CLANG := true
-LOCAL_SHARED_LIBRARIES := libmemunreachable libbase liblog
-
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := memunreachable_test
-LOCAL_SRC_FILES := \
-   Allocator.cpp \
-   HeapWalker.cpp  \
-   LeakFolding.cpp \
-   tests/Allocator_test.cpp \
-   tests/HeapWalker_test.cpp \
-   tests/HostMallocStub.cpp \
-   tests/LeakFolding_test.cpp \
-
-LOCAL_CFLAGS := -std=c++14 -Wall -Wextra -Werror
-LOCAL_CLANG := true
-LOCAL_SHARED_LIBRARIES := libbase liblog
-LOCAL_MODULE_HOST_OS := linux
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libmemunreachable/HeapWalker.h b/libmemunreachable/HeapWalker.h
index 3c1b513..b25696f 100644
--- a/libmemunreachable/HeapWalker.h
+++ b/libmemunreachable/HeapWalker.h
@@ -48,7 +48,7 @@
 
 class HeapWalker {
  public:
-  HeapWalker(Allocator<HeapWalker> allocator) : allocator_(allocator),
+  explicit HeapWalker(Allocator<HeapWalker> allocator) : allocator_(allocator),
     allocations_(allocator), allocation_bytes_(0),
 	roots_(allocator), root_vals_(allocator),
 	segv_handler_(allocator), walking_ptr_(0) {
diff --git a/libmemunreachable/LeakFolding.h b/libmemunreachable/LeakFolding.h
index 732d3f2..9c6a525 100644
--- a/libmemunreachable/LeakFolding.h
+++ b/libmemunreachable/LeakFolding.h
@@ -54,7 +54,7 @@
     bool dominator;
     SCCInfo* accumulator;
 
-    SCCInfo(Allocator<SCCInfo> allocator) : node(this, allocator),
+    explicit SCCInfo(Allocator<SCCInfo> allocator) : node(this, allocator),
         count(0), size(0), cuumulative_count(0), cuumulative_size(0),
         dominator(false), accumulator(nullptr) {}
    private:
diff --git a/libmemunreachable/LinkedList.h b/libmemunreachable/LinkedList.h
index 3e44035..132842d 100644
--- a/libmemunreachable/LinkedList.h
+++ b/libmemunreachable/LinkedList.h
@@ -21,7 +21,7 @@
 class LinkedList {
 public:
     LinkedList() : next_(this), prev_(this), data_() {}
-    LinkedList(T data) : LinkedList() {
+    explicit LinkedList(T data) : LinkedList() {
         data_ = data;
     }
     ~LinkedList() {}
diff --git a/libmemunreachable/PtracerThread.cpp b/libmemunreachable/PtracerThread.cpp
index aa5b344..4e3c41e 100644
--- a/libmemunreachable/PtracerThread.cpp
+++ b/libmemunreachable/PtracerThread.cpp
@@ -37,7 +37,7 @@
 
 class Stack {
  public:
-  Stack(size_t size) : size_(size) {
+  explicit Stack(size_t size) : size_(size) {
     int prot = PROT_READ | PROT_WRITE;
     int flags = MAP_PRIVATE | MAP_ANONYMOUS;
     page_size_ = sysconf(_SC_PAGE_SIZE);
diff --git a/libmemunreachable/PtracerThread.h b/libmemunreachable/PtracerThread.h
index 4d6ca9a..f88b599 100644
--- a/libmemunreachable/PtracerThread.h
+++ b/libmemunreachable/PtracerThread.h
@@ -32,7 +32,7 @@
 // the parent.
 class PtracerThread {
  public:
-  PtracerThread(const std::function<int()>& func);
+  explicit PtracerThread(const std::function<int()>& func);
   ~PtracerThread();
   bool Start();
   int Join();
diff --git a/libmemunreachable/ScopedDisableMalloc.h b/libmemunreachable/ScopedDisableMalloc.h
index 4f96376..758d317 100644
--- a/libmemunreachable/ScopedDisableMalloc.h
+++ b/libmemunreachable/ScopedDisableMalloc.h
@@ -74,7 +74,7 @@
 
 class ScopedDisableMallocTimeout {
  public:
-  ScopedDisableMallocTimeout(std::chrono::milliseconds timeout = std::chrono::milliseconds(2000)) :
+  explicit ScopedDisableMallocTimeout(std::chrono::milliseconds timeout = std::chrono::milliseconds(2000)) :
     timeout_(timeout), timed_out_(false), disable_malloc_() {
     Disable();
   }
diff --git a/libmemunreachable/ScopedSignalHandler.h b/libmemunreachable/ScopedSignalHandler.h
index e006d43..1fd9d4d 100644
--- a/libmemunreachable/ScopedSignalHandler.h
+++ b/libmemunreachable/ScopedSignalHandler.h
@@ -30,7 +30,7 @@
  public:
   using Fn = std::function<void(ScopedSignalHandler&, int, siginfo_t*, void*)>;
 
-  ScopedSignalHandler(Allocator<Fn> allocator) : allocator_(allocator), signal_(-1) {}
+  explicit ScopedSignalHandler(Allocator<Fn> allocator) : allocator_(allocator), signal_(-1) {}
   ~ScopedSignalHandler() {
     reset();
   }
diff --git a/libmemunreachable/Semaphore.h b/libmemunreachable/Semaphore.h
index 45e8c81..6bcf4ea 100644
--- a/libmemunreachable/Semaphore.h
+++ b/libmemunreachable/Semaphore.h
@@ -24,7 +24,7 @@
 
 class Semaphore {
  public:
-  Semaphore(int count = 0) : count_(count) {}
+  explicit Semaphore(int count = 0) : count_(count) {}
   ~Semaphore() = default;
 
   void Wait(std::chrono::milliseconds ms) {
diff --git a/libmemunreachable/Tarjan.h b/libmemunreachable/Tarjan.h
index d7ecdb9..2546341 100644
--- a/libmemunreachable/Tarjan.h
+++ b/libmemunreachable/Tarjan.h
@@ -19,6 +19,7 @@
 #ifndef LIBMEMUNREACHABLE_TARJAN_H_
 #define LIBMEMUNREACHABLE_TARJAN_H_
 
+#include <assert.h>
 #include <algorithm>
 
 #include "Allocator.h"
@@ -62,7 +63,7 @@
 template<class T>
 class TarjanAlgorithm {
  public:
-  TarjanAlgorithm(Allocator<void> allocator) : index_(0),
+  explicit TarjanAlgorithm(Allocator<void> allocator) : index_(0),
     stack_(allocator), components_(allocator) {}
 
   void Execute(Graph<T>& graph, SCCList<T>& out);
diff --git a/libmemunreachable/tests/Allocator_test.cpp b/libmemunreachable/tests/Allocator_test.cpp
index fa76ae0..21c8218 100644
--- a/libmemunreachable/tests/Allocator_test.cpp
+++ b/libmemunreachable/tests/Allocator_test.cpp
@@ -160,7 +160,7 @@
 
   Allocator<int>::shared_ptr ptr = allocator.make_shared(0);
   {
-    auto ptr2 = ptr;
+    auto ptr2 = ptr;  // NOLINT, test copy of ptr
   }
   ASSERT_NE(ptr, nullptr);
 }
diff --git a/libmemunreachable/tests/LeakFolding_test.cpp b/libmemunreachable/tests/LeakFolding_test.cpp
index 879a3a0..e85df5f 100644
--- a/libmemunreachable/tests/LeakFolding_test.cpp
+++ b/libmemunreachable/tests/LeakFolding_test.cpp
@@ -37,10 +37,10 @@
   Heap heap_;
 };
 
-#define buffer_begin(buffer) reinterpret_cast<uintptr_t>(&buffer[0])
-#define buffer_end(buffer) (reinterpret_cast<uintptr_t>(&buffer[0]) + sizeof(buffer))
+#define buffer_begin(buffer) reinterpret_cast<uintptr_t>(&(buffer)[0])
+#define buffer_end(buffer) (reinterpret_cast<uintptr_t>(&(buffer)[0]) + sizeof(buffer))
 #define ALLOCATION(heap_walker, buffer) \
-  ASSERT_EQ(true, heap_walker.Allocation(buffer_begin(buffer), buffer_end(buffer)))
+  ASSERT_EQ(true, (heap_walker).Allocation(buffer_begin(buffer), buffer_end(buffer)))
 
 TEST_F(LeakFoldingTest, one) {
   void* buffer1[1] = {nullptr};
diff --git a/libmemunreachable/tests/MemUnreachable_test.cpp b/libmemunreachable/tests/MemUnreachable_test.cpp
index 0747b12..2ae3db8 100644
--- a/libmemunreachable/tests/MemUnreachable_test.cpp
+++ b/libmemunreachable/tests/MemUnreachable_test.cpp
@@ -27,7 +27,7 @@
 
 class HiddenPointer {
  public:
-  HiddenPointer(size_t size = 256) {
+  explicit HiddenPointer(size_t size = 256) {
     Set(malloc(size));
   }
   ~HiddenPointer() {
diff --git a/libmetricslogger/Android.bp b/libmetricslogger/Android.bp
new file mode 100644
index 0000000..79d6c3f
--- /dev/null
+++ b/libmetricslogger/Android.bp
@@ -0,0 +1,65 @@
+// Copyright 2017 The Android Open Source Project
+
+metricslogger_lib_src_files = [
+    "metrics_logger.cpp",
+]
+
+cc_defaults {
+    name: "metricslogger_defaults",
+
+    clang: true,
+    host_supported: true,
+
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+    shared_libs: ["liblog"],
+    whole_static_libs: ["libgtest_prod"],
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+
+        // 524291 corresponds to sysui_histogram, from
+        // frameworks/base/core/java/com/android/internal/logging/EventLogTags.logtags
+        "-DHISTOGRAM_LOG_TAG=524292",
+    ],
+}
+
+// metricslogger shared library
+// -----------------------------------------------------------------------------
+cc_library_shared {
+    name: "libmetricslogger",
+    vendor_available: true,
+    srcs: metricslogger_lib_src_files,
+    defaults: ["metricslogger_defaults"],
+}
+
+// metricslogger shared library, debug
+// -----------------------------------------------------------------------------
+cc_library_shared {
+    name: "libmetricslogger_debug",
+    srcs: metricslogger_lib_src_files,
+    defaults: ["metricslogger_defaults"],
+
+    target: {
+        host: {
+            cflags: ["-UNDEBUG"],
+        },
+    },
+}
+
+// Native tests
+// -----------------------------------------------------------------------------
+cc_test {
+    name: "metricslogger_tests",
+    defaults: ["metricslogger_defaults"],
+    shared_libs: [
+        "libbase",
+        "libmetricslogger_debug",
+    ],
+    static_libs: ["libBionicGtestMain"],
+    srcs: [
+        "metrics_logger_test.cpp",
+    ],
+}
diff --git a/libmetricslogger/include/metricslogger/metrics_logger.h b/libmetricslogger/include/metricslogger/metrics_logger.h
new file mode 100644
index 0000000..26aa189
--- /dev/null
+++ b/libmetricslogger/include/metricslogger/metrics_logger.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.
+ */
+
+#include <cstdint>
+#include <string>
+
+namespace android {
+namespace metricslogger {
+
+// Logs a Tron histogram metric named |event| containing |data| to the Tron log
+// buffer.
+void LogHistogram(const std::string& event, int32_t data);
+
+// TODO: replace these with the metric_logger.proto definitions
+enum {
+  LOGBUILDER_CATEGORY = 757,
+  LOGBUILDER_NAME = 799,
+  LOGBUILDER_BUCKET = 801,
+  LOGBUILDER_VALUE = 802,
+  LOGBUILDER_HISTOGRAM = 804,
+};
+
+}  // namespace metricslogger
+}  // namespace android
diff --git a/libmetricslogger/metrics_logger.cpp b/libmetricslogger/metrics_logger.cpp
new file mode 100644
index 0000000..0d08f5c
--- /dev/null
+++ b/libmetricslogger/metrics_logger.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 "metricslogger/metrics_logger.h"
+
+#include <cstdlib>
+
+#include <log/log_event_list.h>
+
+namespace android {
+namespace metricslogger {
+
+// Mirror com.android.internal.logging.MetricsLogger#histogram().
+void LogHistogram(const std::string& event, int32_t data) {
+  android_log_event_list log(HISTOGRAM_LOG_TAG);
+  log << LOGBUILDER_CATEGORY << LOGBUILDER_HISTOGRAM
+      << LOGBUILDER_NAME << event
+      << LOGBUILDER_BUCKET << data
+      << LOGBUILDER_VALUE << 1
+      << LOG_ID_EVENTS;
+}
+
+}  // namespace metricslogger
+}  // namespace android
diff --git a/libmetricslogger/metrics_logger_test.cpp b/libmetricslogger/metrics_logger_test.cpp
new file mode 100644
index 0000000..5a30ad7
--- /dev/null
+++ b/libmetricslogger/metrics_logger_test.cpp
@@ -0,0 +1,24 @@
+/*
+ * 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 "metricslogger/metrics_logger.h"
+
+#include <gtest/gtest.h>
+
+TEST(MetricsLoggerTest, AddSingleBootEvent) {
+  android::metricslogger::LogHistogram("test_event", 42);
+  // TODO(jhawkins): Verify the EventLog is updated.
+}
diff --git a/libmincrypt/Android.mk b/libmincrypt/Android.mk
deleted file mode 100644
index 7906986..0000000
--- a/libmincrypt/Android.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2008 The Android Open Source Project
-#
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libmincrypt
-LOCAL_SRC_FILES := dsa_sig.c p256.c p256_ec.c p256_ecdsa.c rsa.c sha.c sha256.c
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libmincrypt
-LOCAL_SRC_FILES := dsa_sig.c p256.c p256_ec.c p256_ecdsa.c rsa.c sha.c sha256.c
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(LOCAL_PATH)/tools/Android.mk \
-        $(LOCAL_PATH)/test/Android.mk
diff --git a/libmincrypt/NOTICE b/libmincrypt/NOTICE
deleted file mode 100644
index 430d3d6..0000000
--- a/libmincrypt/NOTICE
+++ /dev/null
@@ -1,23 +0,0 @@
- Copyright 2008, The Android Open Source Project
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-     * Redistributions of source code must retain the above copyright
-       notice, this list of conditions and the following disclaimer.
-     * Redistributions in binary form must reproduce the above copyright
-       notice, this list of conditions and the following disclaimer in the
-       documentation and/or other materials provided with the distribution.
-     * Neither the name of Google Inc. nor the names of its contributors may
-       be used to endorse or promote products derived from this software
-       without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR 
- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 
- EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
- OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
- WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/libmincrypt/dsa_sig.c b/libmincrypt/dsa_sig.c
deleted file mode 100644
index 101314b..0000000
--- a/libmincrypt/dsa_sig.c
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string.h>
-
-#include "mincrypt/dsa_sig.h"
-#include "mincrypt/p256.h"
-
-/**
- * Trims off the leading zero bytes and copy it to a buffer aligning it to the end.
- */
-static inline int trim_to_p256_bytes(unsigned char dst[P256_NBYTES], unsigned char *src,
-        int src_len) {
-    int dst_offset;
-    while (*src == '\0' && src_len > 0) {
-        src++;
-        src_len--;
-    }
-    if (src_len > P256_NBYTES || src_len < 1) {
-        return 0;
-    }
-    dst_offset = P256_NBYTES - src_len;
-    memset(dst, 0, dst_offset);
-    memcpy(dst + dst_offset, src, src_len);
-    return 1;
-}
-
-/**
- * Unpacks the ASN.1 DSA signature sequence.
- */
-int dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int) {
-    /*
-     * Structure is:
-     *   0x30 0xNN  SEQUENCE + s_length
-     *     0x02 0xNN  INTEGER + r_length
-     *       0xAA 0xBB ..   r_length bytes of "r" (offset 4)
-     *     0x02 0xNN  INTEGER + s_length
-     *       0xMM 0xNN ..   s_length bytes of "s" (offset 6 + r_len)
-     */
-    int seq_len;
-    unsigned char r_bytes[P256_NBYTES];
-    unsigned char s_bytes[P256_NBYTES];
-    int r_len;
-    int s_len;
-
-    memset(r_bytes, 0, sizeof(r_bytes));
-    memset(s_bytes, 0, sizeof(s_bytes));
-
-    /*
-     * Must have at least:
-     * 2 bytes sequence header and length
-     * 2 bytes R integer header and length
-     * 1 byte of R
-     * 2 bytes S integer header and length
-     * 1 byte of S
-     *
-     * 8 bytes total
-     */
-    if (sig_len < 8 || sig[0] != 0x30 || sig[2] != 0x02) {
-        return 0;
-    }
-
-    seq_len = sig[1];
-    if ((seq_len <= 0) || (seq_len + 2 != sig_len)) {
-        return 0;
-    }
-
-    r_len = sig[3];
-    /*
-     * Must have at least:
-     * 2 bytes for R header and length
-     * 2 bytes S integer header and length
-     * 1 byte of S
-     */
-    if ((r_len < 1) || (r_len > seq_len - 5) || (sig[4 + r_len] != 0x02)) {
-        return 0;
-    }
-    s_len = sig[5 + r_len];
-
-    /**
-     * Must have:
-     * 2 bytes for R header and length
-     * r_len bytes for R
-     * 2 bytes S integer header and length
-     */
-    if ((s_len < 1) || (s_len != seq_len - 4 - r_len)) {
-        return 0;
-    }
-
-    /*
-     * ASN.1 encoded integers are zero-padded for positive integers. Make sure we have
-     * a correctly-sized buffer and that the resulting integer isn't too large.
-     */
-    if (!trim_to_p256_bytes(r_bytes, &sig[4], r_len)
-            || !trim_to_p256_bytes(s_bytes, &sig[6 + r_len], s_len)) {
-        return 0;
-    }
-
-    p256_from_bin(r_bytes, r_int);
-    p256_from_bin(s_bytes, s_int);
-
-    return 1;
-}
diff --git a/libmincrypt/p256.c b/libmincrypt/p256.c
deleted file mode 100644
index 555a07a..0000000
--- a/libmincrypt/p256.c
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This is an implementation of the P256 elliptic curve group. It's written to
-// be portable 32-bit, although it's still constant-time.
-//
-// WARNING: Implementing these functions in a constant-time manner is far from
-//          obvious. Be careful when touching this code.
-//
-// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.
-
-#include <assert.h>
-#include <stdint.h>
-#include <string.h>
-#include <stdio.h>
-
-#include "mincrypt/p256.h"
-
-const p256_int SECP256r1_n =  // curve order
-  {{0xfc632551, 0xf3b9cac2, 0xa7179e84, 0xbce6faad, -1, -1, 0, -1}};
-
-const p256_int SECP256r1_p =  // curve field size
-  {{-1, -1, -1, 0, 0, 0, 1, -1 }};
-
-const p256_int SECP256r1_b =  // curve b
-  {{0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,
-    0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8}};
-
-void p256_init(p256_int* a) {
-  memset(a, 0, sizeof(*a));
-}
-
-void p256_clear(p256_int* a) { p256_init(a); }
-
-int p256_get_bit(const p256_int* scalar, int bit) {
-  return (P256_DIGIT(scalar, bit / P256_BITSPERDIGIT)
-              >> (bit & (P256_BITSPERDIGIT - 1))) & 1;
-}
-
-int p256_is_zero(const p256_int* a) {
-  int i, result = 0;
-  for (i = 0; i < P256_NDIGITS; ++i) result |= P256_DIGIT(a, i);
-  return !result;
-}
-
-// top, c[] += a[] * b
-// Returns new top
-static p256_digit mulAdd(const p256_int* a,
-                         p256_digit b,
-                         p256_digit top,
-                         p256_digit* c) {
-  int i;
-  p256_ddigit carry = 0;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    carry += *c;
-    carry += (p256_ddigit)P256_DIGIT(a, i) * b;
-    *c++ = (p256_digit)carry;
-    carry >>= P256_BITSPERDIGIT;
-  }
-  return top + (p256_digit)carry;
-}
-
-// top, c[] -= top_a, a[]
-static p256_digit subTop(p256_digit top_a,
-                         const p256_digit* a,
-                         p256_digit top_c,
-                         p256_digit* c) {
-  int i;
-  p256_sddigit borrow = 0;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    borrow += *c;
-    borrow -= *a++;
-    *c++ = (p256_digit)borrow;
-    borrow >>= P256_BITSPERDIGIT;
-  }
-  borrow += top_c;
-  borrow -= top_a;
-  top_c = (p256_digit)borrow;
-  assert((borrow >> P256_BITSPERDIGIT) == 0);
-  return top_c;
-}
-
-// top, c[] -= MOD[] & mask (0 or -1)
-// returns new top.
-static p256_digit subM(const p256_int* MOD,
-                       p256_digit top,
-                       p256_digit* c,
-                       p256_digit mask) {
-  int i;
-  p256_sddigit borrow = 0;
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    borrow += *c;
-    borrow -= P256_DIGIT(MOD, i) & mask;
-    *c++ = (p256_digit)borrow;
-    borrow >>= P256_BITSPERDIGIT;
-  }
-  return top + (p256_digit)borrow;
-}
-
-// top, c[] += MOD[] & mask (0 or -1)
-// returns new top.
-static p256_digit addM(const p256_int* MOD,
-                       p256_digit top,
-                       p256_digit* c,
-                       p256_digit mask) {
-  int i;
-  p256_ddigit carry = 0;
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    carry += *c;
-    carry += P256_DIGIT(MOD, i) & mask;
-    *c++ = (p256_digit)carry;
-    carry >>= P256_BITSPERDIGIT;
-  }
-  return top + (p256_digit)carry;
-}
-
-// c = a * b mod MOD. c can be a and/or b.
-void p256_modmul(const p256_int* MOD,
-                 const p256_int* a,
-                 const p256_digit top_b,
-                 const p256_int* b,
-                 p256_int* c) {
-  p256_digit tmp[P256_NDIGITS * 2 + 1] = { 0 };
-  p256_digit top = 0;
-  int i;
-
-  // Multiply/add into tmp.
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    if (i) tmp[i + P256_NDIGITS - 1] = top;
-    top = mulAdd(a, P256_DIGIT(b, i), 0, tmp + i);
-  }
-
-  // Multiply/add top digit
-  tmp[i + P256_NDIGITS - 1] = top;
-  top = mulAdd(a, top_b, 0, tmp + i);
-
-  // Reduce tmp, digit by digit.
-  for (; i >= 0; --i) {
-    p256_digit reducer[P256_NDIGITS] = { 0 };
-    p256_digit top_reducer;
-
-    // top can be any value at this point.
-    // Guestimate reducer as top * MOD, since msw of MOD is -1.
-    top_reducer = mulAdd(MOD, top, 0, reducer);
-
-    // Subtract reducer from top | tmp.
-    top = subTop(top_reducer, reducer, top, tmp + i);
-
-    // top is now either 0 or 1. Make it 0, fixed-timing.
-    assert(top <= 1);
-
-    top = subM(MOD, top, tmp + i, ~(top - 1));
-
-    assert(top == 0);
-
-    // We have now reduced the top digit off tmp. Fetch new top digit.
-    top = tmp[i + P256_NDIGITS - 1];
-  }
-
-  // tmp might still be larger than MOD, yet same bit length.
-  // Make sure it is less, fixed-timing.
-  addM(MOD, 0, tmp, subM(MOD, 0, tmp, -1));
-
-  memcpy(c, tmp, P256_NBYTES);
-}
-int p256_is_odd(const p256_int* a) { return P256_DIGIT(a, 0) & 1; }
-int p256_is_even(const p256_int* a) { return !(P256_DIGIT(a, 0) & 1); }
-
-p256_digit p256_shl(const p256_int* a, int n, p256_int* b) {
-  int i;
-  p256_digit top = P256_DIGIT(a, P256_NDIGITS - 1);
-
-  n %= P256_BITSPERDIGIT;
-  for (i = P256_NDIGITS - 1; i > 0; --i) {
-    p256_digit accu = (P256_DIGIT(a, i) << n);
-    accu |= (P256_DIGIT(a, i - 1) >> (P256_BITSPERDIGIT - n));
-    P256_DIGIT(b, i) = accu;
-  }
-  P256_DIGIT(b, i) = (P256_DIGIT(a, i) << n);
-
-  top = (p256_digit)((((p256_ddigit)top) << n) >> P256_BITSPERDIGIT);
-
-  return top;
-}
-
-void p256_shr(const p256_int* a, int n, p256_int* b) {
-  int i;
-
-  n %= P256_BITSPERDIGIT;
-  for (i = 0; i < P256_NDIGITS - 1; ++i) {
-    p256_digit accu = (P256_DIGIT(a, i) >> n);
-    accu |= (P256_DIGIT(a, i + 1) << (P256_BITSPERDIGIT - n));
-    P256_DIGIT(b, i) = accu;
-  }
-  P256_DIGIT(b, i) = (P256_DIGIT(a, i) >> n);
-}
-
-static void p256_shr1(const p256_int* a, int highbit, p256_int* b) {
-  int i;
-
-  for (i = 0; i < P256_NDIGITS - 1; ++i) {
-    p256_digit accu = (P256_DIGIT(a, i) >> 1);
-    accu |= (P256_DIGIT(a, i + 1) << (P256_BITSPERDIGIT - 1));
-    P256_DIGIT(b, i) = accu;
-  }
-  P256_DIGIT(b, i) = (P256_DIGIT(a, i) >> 1) |
-      (highbit << (P256_BITSPERDIGIT - 1));
-}
-
-// Return -1, 0, 1 for a < b, a == b or a > b respectively.
-int p256_cmp(const p256_int* a, const p256_int* b) {
-  int i;
-  p256_sddigit borrow = 0;
-  p256_digit notzero = 0;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    borrow += (p256_sddigit)P256_DIGIT(a, i) - P256_DIGIT(b, i);
-    // Track whether any result digit is ever not zero.
-    // Relies on !!(non-zero) evaluating to 1, e.g., !!(-1) evaluating to 1.
-    notzero |= !!((p256_digit)borrow);
-    borrow >>= P256_BITSPERDIGIT;
-  }
-  return (int)borrow | notzero;
-}
-
-// c = a - b. Returns borrow: 0 or -1.
-int p256_sub(const p256_int* a, const p256_int* b, p256_int* c) {
-  int i;
-  p256_sddigit borrow = 0;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    borrow += (p256_sddigit)P256_DIGIT(a, i) - P256_DIGIT(b, i);
-    if (c) P256_DIGIT(c, i) = (p256_digit)borrow;
-    borrow >>= P256_BITSPERDIGIT;
-  }
-  return (int)borrow;
-}
-
-// c = a + b. Returns carry: 0 or 1.
-int p256_add(const p256_int* a, const p256_int* b, p256_int* c) {
-  int i;
-  p256_ddigit carry = 0;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    carry += (p256_ddigit)P256_DIGIT(a, i) + P256_DIGIT(b, i);
-    if (c) P256_DIGIT(c, i) = (p256_digit)carry;
-    carry >>= P256_BITSPERDIGIT;
-  }
-  return (int)carry;
-}
-
-// b = a + d. Returns carry, 0 or 1.
-int p256_add_d(const p256_int* a, p256_digit d, p256_int* b) {
-  int i;
-  p256_ddigit carry = d;
-
-  for (i = 0; i < P256_NDIGITS; ++i) {
-    carry += (p256_ddigit)P256_DIGIT(a, i);
-    if (b) P256_DIGIT(b, i) = (p256_digit)carry;
-    carry >>= P256_BITSPERDIGIT;
-  }
-  return (int)carry;
-}
-
-// b = 1/a mod MOD, binary euclid.
-void p256_modinv_vartime(const p256_int* MOD,
-                         const p256_int* a,
-                         p256_int* b) {
-  p256_int R = P256_ZERO;
-  p256_int S = P256_ONE;
-  p256_int U = *MOD;
-  p256_int V = *a;
-
-  for (;;) {
-    if (p256_is_even(&U)) {
-      p256_shr1(&U, 0, &U);
-      if (p256_is_even(&R)) {
-        p256_shr1(&R, 0, &R);
-      } else {
-        // R = (R+MOD)/2
-        p256_shr1(&R, p256_add(&R, MOD, &R), &R);
-      }
-    } else if (p256_is_even(&V)) {
-      p256_shr1(&V, 0, &V);
-      if (p256_is_even(&S)) {
-        p256_shr1(&S, 0, &S);
-      } else {
-        // S = (S+MOD)/2
-        p256_shr1(&S, p256_add(&S, MOD, &S) , &S);
-      }
-    } else {  // U,V both odd.
-      if (!p256_sub(&V, &U, NULL)) {
-        p256_sub(&V, &U, &V);
-        if (p256_sub(&S, &R, &S)) p256_add(&S, MOD, &S);
-        if (p256_is_zero(&V)) break;  // done.
-      } else {
-        p256_sub(&U, &V, &U);
-        if (p256_sub(&R, &S, &R)) p256_add(&R, MOD, &R);
-      }
-    }
-  }
-
-  p256_mod(MOD, &R, b);
-}
-
-void p256_mod(const p256_int* MOD,
-              const p256_int* in,
-              p256_int* out) {
-  if (out != in) *out = *in;
-  addM(MOD, 0, P256_DIGITS(out), subM(MOD, 0, P256_DIGITS(out), -1));
-}
-
-// Verify y^2 == x^3 - 3x + b mod p
-// and 0 < x < p and 0 < y < p
-int p256_is_valid_point(const p256_int* x, const p256_int* y) {
-  p256_int y2, x3;
-
-  if (p256_cmp(&SECP256r1_p, x) <= 0 ||
-      p256_cmp(&SECP256r1_p, y) <= 0 ||
-      p256_is_zero(x) ||
-      p256_is_zero(y)) return 0;
-
-  p256_modmul(&SECP256r1_p, y, 0, y, &y2);  // y^2
-
-  p256_modmul(&SECP256r1_p, x, 0, x, &x3);  // x^2
-  p256_modmul(&SECP256r1_p, x, 0, &x3, &x3);  // x^3
-  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - x
-  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - 2x
-  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - 3x
-  if (p256_add(&x3, &SECP256r1_b, &x3))  // x^3 - 3x + b
-    p256_sub(&x3, &SECP256r1_p, &x3);
-
-  return p256_cmp(&y2, &x3) == 0;
-}
-
-void p256_from_bin(const uint8_t src[P256_NBYTES], p256_int* dst) {
-  int i;
-  const uint8_t* p = &src[0];
-
-  for (i = P256_NDIGITS - 1; i >= 0; --i) {
-    P256_DIGIT(dst, i) =
-        (p[0] << 24) |
-        (p[1] << 16) |
-        (p[2] << 8) |
-        p[3];
-    p += 4;
-  }
-}
diff --git a/libmincrypt/p256_ec.c b/libmincrypt/p256_ec.c
deleted file mode 100644
index 90262cc..0000000
--- a/libmincrypt/p256_ec.c
+++ /dev/null
@@ -1,1279 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This is an implementation of the P256 elliptic curve group. It's written to
-// be portable 32-bit, although it's still constant-time.
-//
-// WARNING: Implementing these functions in a constant-time manner is far from
-//          obvious. Be careful when touching this code.
-//
-// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.
-
-#include <stdint.h>
-#include <stdio.h>
-
-#include <string.h>
-#include <stdlib.h>
-
-#include "mincrypt/p256.h"
-
-typedef uint8_t u8;
-typedef uint32_t u32;
-typedef int32_t s32;
-typedef uint64_t u64;
-
-/* Our field elements are represented as nine 32-bit limbs.
- *
- * The value of an felem (field element) is:
- *   x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)
- *
- * That is, each limb is alternately 29 or 28-bits wide in little-endian
- * order.
- *
- * This means that an felem hits 2**257, rather than 2**256 as we would like. A
- * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems
- * when multiplying as terms end up one bit short of a limb which would require
- * much bit-shifting to correct.
- *
- * Finally, the values stored in an felem are in Montgomery form. So the value
- * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.
- */
-typedef u32 limb;
-#define NLIMBS 9
-typedef limb felem[NLIMBS];
-
-static const limb kBottom28Bits = 0xfffffff;
-static const limb kBottom29Bits = 0x1fffffff;
-
-/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and
- * 28-bit words. */
-static const felem kOne = {
-    2, 0, 0, 0xffff800,
-    0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,
-    0
-};
-static const felem kZero = {0};
-static const felem kP = {
-    0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,
-    0, 0, 0x200000, 0xf000000,
-    0xfffffff
-};
-static const felem k2P = {
-    0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,
-    0, 0, 0x400000, 0xe000000,
-    0x1fffffff
-};
-/* kPrecomputed contains precomputed values to aid the calculation of scalar
- * multiples of the base point, G. It's actually two, equal length, tables
- * concatenated.
- *
- * The first table contains (x,y) felem pairs for 16 multiples of the base
- * point, G.
- *
- *   Index  |  Index (binary) | Value
- *       0  |           0000  | 0G (all zeros, omitted)
- *       1  |           0001  | G
- *       2  |           0010  | 2**64G
- *       3  |           0011  | 2**64G + G
- *       4  |           0100  | 2**128G
- *       5  |           0101  | 2**128G + G
- *       6  |           0110  | 2**128G + 2**64G
- *       7  |           0111  | 2**128G + 2**64G + G
- *       8  |           1000  | 2**192G
- *       9  |           1001  | 2**192G + G
- *      10  |           1010  | 2**192G + 2**64G
- *      11  |           1011  | 2**192G + 2**64G + G
- *      12  |           1100  | 2**192G + 2**128G
- *      13  |           1101  | 2**192G + 2**128G + G
- *      14  |           1110  | 2**192G + 2**128G + 2**64G
- *      15  |           1111  | 2**192G + 2**128G + 2**64G + G
- *
- * The second table follows the same style, but the terms are 2**32G,
- * 2**96G, 2**160G, 2**224G.
- *
- * This is ~2KB of data. */
-static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {
-    0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,
-    0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,
-    0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,
-    0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,
-    0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,
-    0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,
-    0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,
-    0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,
-    0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,
-    0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,
-    0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,
-    0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,
-    0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,
-    0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,
-    0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,
-    0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,
-    0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,
-    0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,
-    0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,
-    0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,
-    0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,
-    0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,
-    0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,
-    0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,
-    0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,
-    0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,
-    0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,
-    0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,
-    0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,
-    0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,
-    0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,
-    0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,
-    0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,
-    0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,
-    0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,
-    0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,
-    0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,
-    0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,
-    0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,
-    0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,
-    0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,
-    0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,
-    0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,
-    0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,
-    0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,
-    0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,
-    0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,
-    0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,
-    0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,
-    0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,
-    0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,
-    0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,
-    0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,
-    0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,
-    0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,
-    0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,
-    0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,
-    0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,
-    0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,
-    0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,
-};
-
-
-/* Field element operations: */
-
-/* NON_ZERO_TO_ALL_ONES returns:
- *   0xffffffff for 0 < x <= 2**31
- *   0 for x == 0 or x > 2**31.
- *
- * x must be a u32 or an equivalent type such as limb. */
-#define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1)
-
-/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,
- * which is a term at 2**257.
- *
- * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.
- * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */
-static void felem_reduce_carry(felem inout, limb carry) {
-  const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry);
-
-  inout[0] += carry << 1;
-  inout[3] += 0x10000000 & carry_mask;
-  /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the
-   * previous line therefore this doesn't underflow. */
-  inout[3] -= carry << 11;
-  inout[4] += (0x20000000 - 1) & carry_mask;
-  inout[5] += (0x10000000 - 1) & carry_mask;
-  inout[6] += (0x20000000 - 1) & carry_mask;
-  inout[6] -= carry << 22;
-  /* This may underflow if carry is non-zero but, if so, we'll fix it in the
-   * next line. */
-  inout[7] -= 1 & carry_mask;
-  inout[7] += carry << 25;
-}
-
-/* felem_sum sets out = in+in2.
- *
- * On entry, in[i]+in2[i] must not overflow a 32-bit word.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */
-static void felem_sum(felem out, const felem in, const felem in2) {
-  limb carry = 0;
-  unsigned i;
-
-  for (i = 0;; i++) {
-    out[i] = in[i] + in2[i];
-    out[i] += carry;
-    carry = out[i] >> 29;
-    out[i] &= kBottom29Bits;
-
-    i++;
-    if (i == NLIMBS)
-      break;
-
-    out[i] = in[i] + in2[i];
-    out[i] += carry;
-    carry = out[i] >> 28;
-    out[i] &= kBottom28Bits;
-  }
-
-  felem_reduce_carry(out, carry);
-}
-
-#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)
-#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)
-#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)
-#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)
-#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)
-#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)
-
-/* zero31 is 0 mod p. */
-static const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 };
-
-/* felem_diff sets out = in-in2.
- *
- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
- *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_diff(felem out, const felem in, const felem in2) {
-  limb carry = 0;
-  unsigned i;
-
-   for (i = 0;; i++) {
-    out[i] = in[i] - in2[i];
-    out[i] += zero31[i];
-    out[i] += carry;
-    carry = out[i] >> 29;
-    out[i] &= kBottom29Bits;
-
-    i++;
-    if (i == NLIMBS)
-      break;
-
-    out[i] = in[i] - in2[i];
-    out[i] += zero31[i];
-    out[i] += carry;
-    carry = out[i] >> 28;
-    out[i] &= kBottom28Bits;
-  }
-
-  felem_reduce_carry(out, carry);
-}
-
-/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words
- * with the same 29,28,... bit positions as an felem.
- *
- * The values in felems are in Montgomery form: x*R mod p where R = 2**257.
- * Since we just multiplied two Montgomery values together, the result is
- * x*y*R*R mod p. We wish to divide by R in order for the result also to be
- * in Montgomery form.
- *
- * On entry: tmp[i] < 2**64
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */
-static void felem_reduce_degree(felem out, u64 tmp[17]) {
-   /* The following table may be helpful when reading this code:
-    *
-    * Limb number:   0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...
-    * Width (bits):  29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29
-    * Start bit:     0 | 29| 57| 86|114|143|171|200|228|257|285
-    *   (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */
-  limb tmp2[18], carry, x, xMask;
-  unsigned i;
-
-  /* tmp contains 64-bit words with the same 29,28,29-bit positions as an
-   * felem. So the top of an element of tmp might overlap with another
-   * element two positions down. The following loop eliminates this
-   * overlap. */
-  tmp2[0] = (limb)(tmp[0] & kBottom29Bits);
-
-  /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try
-   * and hint to the compiler that it can do a single-word shift by selecting
-   * the right register rather than doing a double-word shift and truncating
-   * afterwards. */
-  tmp2[1] = ((limb) tmp[0]) >> 29;
-  tmp2[1] |= (((limb)(tmp[0] >> 32)) << 3) & kBottom28Bits;
-  tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;
-  carry = tmp2[1] >> 28;
-  tmp2[1] &= kBottom28Bits;
-
-  for (i = 2; i < 17; i++) {
-    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;
-    tmp2[i] += ((limb)(tmp[i - 1])) >> 28;
-    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 4) & kBottom29Bits;
-    tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;
-    tmp2[i] += carry;
-    carry = tmp2[i] >> 29;
-    tmp2[i] &= kBottom29Bits;
-
-    i++;
-    if (i == 17)
-      break;
-    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;
-    tmp2[i] += ((limb)(tmp[i - 1])) >> 29;
-    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 3) & kBottom28Bits;
-    tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;
-    tmp2[i] += carry;
-    carry = tmp2[i] >> 28;
-    tmp2[i] &= kBottom28Bits;
-  }
-
-  tmp2[17] = ((limb)(tmp[15] >> 32)) >> 25;
-  tmp2[17] += ((limb)(tmp[16])) >> 29;
-  tmp2[17] += (((limb)(tmp[16] >> 32)) << 3);
-  tmp2[17] += carry;
-
-  /* Montgomery elimination of terms.
-   *
-   * Since R is 2**257, we can divide by R with a bitwise shift if we can
-   * ensure that the right-most 257 bits are all zero. We can make that true by
-   * adding multiplies of p without affecting the value.
-   *
-   * So we eliminate limbs from right to left. Since the bottom 29 bits of p
-   * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.
-   * We can do that for 8 further limbs and then right shift to eliminate the
-   * extra factor of R. */
-  for (i = 0;; i += 2) {
-    tmp2[i + 1] += tmp2[i] >> 29;
-    x = tmp2[i] & kBottom29Bits;
-    xMask = NON_ZERO_TO_ALL_ONES(x);
-    tmp2[i] = 0;
-
-    /* The bounds calculations for this loop are tricky. Each iteration of
-     * the loop eliminates two words by adding values to words to their
-     * right.
-     *
-     * The following table contains the amounts added to each word (as an
-     * offset from the value of i at the top of the loop). The amounts are
-     * accounted for from the first and second half of the loop separately
-     * and are written as, for example, 28 to mean a value <2**28.
-     *
-     * Word:                   3   4   5   6   7   8   9   10
-     * Added in top half:     28  11      29  21  29  28
-     *                                        28  29
-     *                                            29
-     * Added in bottom half:      29  10      28  21  28   28
-     *                                            29
-     *
-     * The value that is currently offset 7 will be offset 5 for the next
-     * iteration and then offset 3 for the iteration after that. Therefore
-     * the total value added will be the values added at 7, 5 and 3.
-     *
-     * The following table accumulates these values. The sums at the bottom
-     * are written as, for example, 29+28, to mean a value < 2**29+2**28.
-     *
-     * Word:                   3   4   5   6   7   8   9  10  11  12  13
-     *                        28  11  10  29  21  29  28  28  28  28  28
-     *                            29  28  11  28  29  28  29  28  29  28
-     *                                    29  28  21  21  29  21  29  21
-     *                                        10  29  28  21  28  21  28
-     *                                        28  29  28  29  28  29  28
-     *                                            11  10  29  10  29  10
-     *                                            29  28  11  28  11
-     *                                                    29      29
-     *                        --------------------------------------------
-     *                                                30+ 31+ 30+ 31+ 30+
-     *                                                28+ 29+ 28+ 29+ 21+
-     *                                                21+ 28+ 21+ 28+ 10
-     *                                                10  21+ 10  21+
-     *                                                    11      11
-     *
-     * So the greatest amount is added to tmp2[10] and tmp2[12]. If
-     * tmp2[10/12] has an initial value of <2**29, then the maximum value
-     * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,
-     * as required. */
-    tmp2[i + 3] += (x << 10) & kBottom28Bits;
-    tmp2[i + 4] += (x >> 18);
-
-    tmp2[i + 6] += (x << 21) & kBottom29Bits;
-    tmp2[i + 7] += x >> 8;
-
-    /* At position 200, which is the starting bit position for word 7, we
-     * have a factor of 0xf000000 = 2**28 - 2**24. */
-    tmp2[i + 7] += 0x10000000 & xMask;
-    /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */
-    tmp2[i + 8] += (x - 1) & xMask;
-    tmp2[i + 7] -= (x << 24) & kBottom28Bits;
-    tmp2[i + 8] -= x >> 4;
-
-    tmp2[i + 8] += 0x20000000 & xMask;
-    tmp2[i + 8] -= x;
-    tmp2[i + 8] += (x << 28) & kBottom29Bits;
-    tmp2[i + 9] += ((x >> 1) - 1) & xMask;
-
-    if (i+1 == NLIMBS)
-      break;
-    tmp2[i + 2] += tmp2[i + 1] >> 28;
-    x = tmp2[i + 1] & kBottom28Bits;
-    xMask = NON_ZERO_TO_ALL_ONES(x);
-    tmp2[i + 1] = 0;
-
-    tmp2[i + 4] += (x << 11) & kBottom29Bits;
-    tmp2[i + 5] += (x >> 18);
-
-    tmp2[i + 7] += (x << 21) & kBottom28Bits;
-    tmp2[i + 8] += x >> 7;
-
-    /* At position 199, which is the starting bit of the 8th word when
-     * dealing with a context starting on an odd word, we have a factor of
-     * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th
-     * word from i+1 is i+8. */
-    tmp2[i + 8] += 0x20000000 & xMask;
-    tmp2[i + 9] += (x - 1) & xMask;
-    tmp2[i + 8] -= (x << 25) & kBottom29Bits;
-    tmp2[i + 9] -= x >> 4;
-
-    tmp2[i + 9] += 0x10000000 & xMask;
-    tmp2[i + 9] -= x;
-    tmp2[i + 10] += (x - 1) & xMask;
-  }
-
-  /* We merge the right shift with a carry chain. The words above 2**257 have
-   * widths of 28,29,... which we need to correct when copying them down.  */
-  carry = 0;
-  for (i = 0; i < 8; i++) {
-    /* The maximum value of tmp2[i + 9] occurs on the first iteration and
-     * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is
-     * therefore safe. */
-    out[i] = tmp2[i + 9];
-    out[i] += carry;
-    out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;
-    carry = out[i] >> 29;
-    out[i] &= kBottom29Bits;
-
-    i++;
-    out[i] = tmp2[i + 9] >> 1;
-    out[i] += carry;
-    carry = out[i] >> 28;
-    out[i] &= kBottom28Bits;
-  }
-
-  out[8] = tmp2[17];
-  out[8] += carry;
-  carry = out[8] >> 29;
-  out[8] &= kBottom29Bits;
-
-  felem_reduce_carry(out, carry);
-}
-
-/* felem_square sets out=in*in.
- *
- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_square(felem out, const felem in) {
-  u64 tmp[17];
-
-  tmp[0] = ((u64) in[0]) * in[0];
-  tmp[1] = ((u64) in[0]) * (in[1] << 1);
-  tmp[2] = ((u64) in[0]) * (in[2] << 1) +
-           ((u64) in[1]) * (in[1] << 1);
-  tmp[3] = ((u64) in[0]) * (in[3] << 1) +
-           ((u64) in[1]) * (in[2] << 1);
-  tmp[4] = ((u64) in[0]) * (in[4] << 1) +
-           ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2];
-  tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) *
-           (in[4] << 1) + ((u64) in[2]) * (in[3] << 1);
-  tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) *
-           (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) +
-           ((u64) in[3]) * (in[3] << 1);
-  tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) *
-           (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) +
-           ((u64) in[3]) * (in[4] << 1);
-  /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,
-   * which is < 2**64 as required. */
-  tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) *
-           (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) +
-           ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4];
-  tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) *
-           (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) +
-           ((u64) in[4]) * (in[5] << 1);
-  tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) *
-            (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) +
-            ((u64) in[5]) * (in[5] << 1);
-  tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) *
-            (in[7] << 1) + ((u64) in[5]) * (in[6] << 1);
-  tmp[12] = ((u64) in[4]) * (in[8] << 1) +
-            ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6];
-  tmp[13] = ((u64) in[5]) * (in[8] << 1) +
-            ((u64) in[6]) * (in[7] << 1);
-  tmp[14] = ((u64) in[6]) * (in[8] << 1) +
-            ((u64) in[7]) * (in[7] << 1);
-  tmp[15] = ((u64) in[7]) * (in[8] << 1);
-  tmp[16] = ((u64) in[8]) * in[8];
-
-  felem_reduce_degree(out, tmp);
-}
-
-/* felem_mul sets out=in*in2.
- *
- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
- *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_mul(felem out, const felem in, const felem in2) {
-  u64 tmp[17];
-
-  tmp[0] = ((u64) in[0]) * in2[0];
-  tmp[1] = ((u64) in[0]) * (in2[1] << 0) +
-           ((u64) in[1]) * (in2[0] << 0);
-  tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) *
-           (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0);
-  tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) *
-           (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) +
-           ((u64) in[3]) * (in2[0] << 0);
-  tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) *
-           (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) +
-           ((u64) in[3]) * (in2[1] << 1) +
-           ((u64) in[4]) * (in2[0] << 0);
-  tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) *
-           (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) +
-           ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) *
-           (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0);
-  tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) *
-           (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) +
-           ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) *
-           (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) +
-           ((u64) in[6]) * (in2[0] << 0);
-  tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) *
-           (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) +
-           ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) *
-           (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) +
-           ((u64) in[6]) * (in2[1] << 0) +
-           ((u64) in[7]) * (in2[0] << 0);
-  /* tmp[8] has the greatest value but doesn't overflow. See logic in
-   * felem_square. */
-  tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) *
-           (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) +
-           ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) *
-           (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) +
-           ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) *
-           (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0);
-  tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) *
-           (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) +
-           ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) *
-           (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) +
-           ((u64) in[7]) * (in2[2] << 0) +
-           ((u64) in[8]) * (in2[1] << 0);
-  tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) *
-            (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) +
-            ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) *
-            (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) +
-            ((u64) in[8]) * (in2[2] << 0);
-  tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) *
-            (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) +
-            ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) *
-            (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0);
-  tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) *
-            (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) +
-            ((u64) in[7]) * (in2[5] << 1) +
-            ((u64) in[8]) * (in2[4] << 0);
-  tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) *
-            (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) +
-            ((u64) in[8]) * (in2[5] << 0);
-  tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) *
-            (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0);
-  tmp[15] = ((u64) in[7]) * (in2[8] << 0) +
-            ((u64) in[8]) * (in2[7] << 0);
-  tmp[16] = ((u64) in[8]) * (in2[8] << 0);
-
-  felem_reduce_degree(out, tmp);
-}
-
-static void felem_assign(felem out, const felem in) {
-  memcpy(out, in, sizeof(felem));
-}
-
-/* felem_inv calculates |out| = |in|^{-1}
- *
- * Based on Fermat's Little Theorem:
- *   a^p = a (mod p)
- *   a^{p-1} = 1 (mod p)
- *   a^{p-2} = a^{-1} (mod p)
- */
-static void felem_inv(felem out, const felem in) {
-  felem ftmp, ftmp2;
-  /* each e_I will hold |in|^{2^I - 1} */
-  felem e2, e4, e8, e16, e32, e64;
-  unsigned i;
-
-  felem_square(ftmp, in); /* 2^1 */
-  felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */
-  felem_assign(e2, ftmp);
-  felem_square(ftmp, ftmp); /* 2^3 - 2^1 */
-  felem_square(ftmp, ftmp); /* 2^4 - 2^2 */
-  felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */
-  felem_assign(e4, ftmp);
-  felem_square(ftmp, ftmp); /* 2^5 - 2^1 */
-  felem_square(ftmp, ftmp); /* 2^6 - 2^2 */
-  felem_square(ftmp, ftmp); /* 2^7 - 2^3 */
-  felem_square(ftmp, ftmp); /* 2^8 - 2^4 */
-  felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */
-  felem_assign(e8, ftmp);
-  for (i = 0; i < 8; i++) {
-    felem_square(ftmp, ftmp);
-  } /* 2^16 - 2^8 */
-  felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */
-  felem_assign(e16, ftmp);
-  for (i = 0; i < 16; i++) {
-    felem_square(ftmp, ftmp);
-  } /* 2^32 - 2^16 */
-  felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */
-  felem_assign(e32, ftmp);
-  for (i = 0; i < 32; i++) {
-    felem_square(ftmp, ftmp);
-  } /* 2^64 - 2^32 */
-  felem_assign(e64, ftmp);
-  felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */
-  for (i = 0; i < 192; i++) {
-    felem_square(ftmp, ftmp);
-  } /* 2^256 - 2^224 + 2^192 */
-
-  felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */
-  for (i = 0; i < 16; i++) {
-    felem_square(ftmp2, ftmp2);
-  } /* 2^80 - 2^16 */
-  felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */
-  for (i = 0; i < 8; i++) {
-    felem_square(ftmp2, ftmp2);
-  } /* 2^88 - 2^8 */
-  felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */
-  for (i = 0; i < 4; i++) {
-    felem_square(ftmp2, ftmp2);
-  } /* 2^92 - 2^4 */
-  felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */
-  felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */
-  felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */
-  felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */
-  felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */
-  felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */
-  felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */
-
-  felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */
-}
-
-/* felem_scalar_3 sets out=3*out.
- *
- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_scalar_3(felem out) {
-  limb carry = 0;
-  unsigned i;
-
-  for (i = 0;; i++) {
-    out[i] *= 3;
-    out[i] += carry;
-    carry = out[i] >> 29;
-    out[i] &= kBottom29Bits;
-
-    i++;
-    if (i == NLIMBS)
-      break;
-
-    out[i] *= 3;
-    out[i] += carry;
-    carry = out[i] >> 28;
-    out[i] &= kBottom28Bits;
-  }
-
-  felem_reduce_carry(out, carry);
-}
-
-/* felem_scalar_4 sets out=4*out.
- *
- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_scalar_4(felem out) {
-  limb carry = 0, next_carry;
-  unsigned i;
-
-  for (i = 0;; i++) {
-    next_carry = out[i] >> 27;
-    out[i] <<= 2;
-    out[i] &= kBottom29Bits;
-    out[i] += carry;
-    carry = next_carry + (out[i] >> 29);
-    out[i] &= kBottom29Bits;
-
-    i++;
-    if (i == NLIMBS)
-      break;
-
-    next_carry = out[i] >> 26;
-    out[i] <<= 2;
-    out[i] &= kBottom28Bits;
-    out[i] += carry;
-    carry = next_carry + (out[i] >> 28);
-    out[i] &= kBottom28Bits;
-  }
-
-  felem_reduce_carry(out, carry);
-}
-
-/* felem_scalar_8 sets out=8*out.
- *
- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */
-static void felem_scalar_8(felem out) {
-  limb carry = 0, next_carry;
-  unsigned i;
-
-  for (i = 0;; i++) {
-    next_carry = out[i] >> 26;
-    out[i] <<= 3;
-    out[i] &= kBottom29Bits;
-    out[i] += carry;
-    carry = next_carry + (out[i] >> 29);
-    out[i] &= kBottom29Bits;
-
-    i++;
-    if (i == NLIMBS)
-      break;
-
-    next_carry = out[i] >> 25;
-    out[i] <<= 3;
-    out[i] &= kBottom28Bits;
-    out[i] += carry;
-    carry = next_carry + (out[i] >> 28);
-    out[i] &= kBottom28Bits;
-  }
-
-  felem_reduce_carry(out, carry);
-}
-
-/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of
- * time depending on the value of |in|. */
-static char felem_is_zero_vartime(const felem in) {
-  limb carry;
-  int i;
-  limb tmp[NLIMBS];
-
-  felem_assign(tmp, in);
-
-  /* First, reduce tmp to a minimal form. */
-  do {
-    carry = 0;
-    for (i = 0;; i++) {
-      tmp[i] += carry;
-      carry = tmp[i] >> 29;
-      tmp[i] &= kBottom29Bits;
-
-      i++;
-      if (i == NLIMBS)
-        break;
-
-      tmp[i] += carry;
-      carry = tmp[i] >> 28;
-      tmp[i] &= kBottom28Bits;
-    }
-
-    felem_reduce_carry(tmp, carry);
-  } while (carry);
-
-  /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */
-  return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||
-         memcmp(tmp, kP, sizeof(tmp)) == 0 ||
-         memcmp(tmp, k2P, sizeof(tmp)) == 0;
-}
-
-
-/* Group operations:
- *
- * Elements of the elliptic curve group are represented in Jacobian
- * coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in
- * Jacobian form. */
-
-/* point_double sets {x_out,y_out,z_out} = 2*{x,y,z}.
- *
- * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l */
-static void point_double(felem x_out, felem y_out, felem z_out, const felem x,
-                         const felem y, const felem z) {
-  felem delta, gamma, alpha, beta, tmp, tmp2;
-
-  felem_square(delta, z);
-  felem_square(gamma, y);
-  felem_mul(beta, x, gamma);
-
-  felem_sum(tmp, x, delta);
-  felem_diff(tmp2, x, delta);
-  felem_mul(alpha, tmp, tmp2);
-  felem_scalar_3(alpha);
-
-  felem_sum(tmp, y, z);
-  felem_square(tmp, tmp);
-  felem_diff(tmp, tmp, gamma);
-  felem_diff(z_out, tmp, delta);
-
-  felem_scalar_4(beta);
-  felem_square(x_out, alpha);
-  felem_diff(x_out, x_out, beta);
-  felem_diff(x_out, x_out, beta);
-
-  felem_diff(tmp, beta, x_out);
-  felem_mul(tmp, alpha, tmp);
-  felem_square(tmp2, gamma);
-  felem_scalar_8(tmp2);
-  felem_diff(y_out, tmp, tmp2);
-}
-
-/* point_add_mixed sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,1}.
- * (i.e. the second point is affine.)
- *
- * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
- *
- * Note that this function does not handle P+P, infinity+P nor P+infinity
- * correctly. */
-static void point_add_mixed(felem x_out, felem y_out, felem z_out,
-                            const felem x1, const felem y1, const felem z1,
-                            const felem x2, const felem y2) {
-  felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp;
-
-  felem_square(z1z1, z1);
-  felem_sum(tmp, z1, z1);
-
-  felem_mul(u2, x2, z1z1);
-  felem_mul(z1z1z1, z1, z1z1);
-  felem_mul(s2, y2, z1z1z1);
-  felem_diff(h, u2, x1);
-  felem_sum(i, h, h);
-  felem_square(i, i);
-  felem_mul(j, h, i);
-  felem_diff(r, s2, y1);
-  felem_sum(r, r, r);
-  felem_mul(v, x1, i);
-
-  felem_mul(z_out, tmp, h);
-  felem_square(rr, r);
-  felem_diff(x_out, rr, j);
-  felem_diff(x_out, x_out, v);
-  felem_diff(x_out, x_out, v);
-
-  felem_diff(tmp, v, x_out);
-  felem_mul(y_out, tmp, r);
-  felem_mul(tmp, y1, j);
-  felem_diff(y_out, y_out, tmp);
-  felem_diff(y_out, y_out, tmp);
-}
-
-/* point_add sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,z2}.
- *
- * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
- *
- * Note that this function does not handle P+P, infinity+P nor P+infinity
- * correctly. */
-static void point_add(felem x_out, felem y_out, felem z_out, const felem x1,
-                      const felem y1, const felem z1, const felem x2,
-                      const felem y2, const felem z2) {
-  felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
-
-  felem_square(z1z1, z1);
-  felem_square(z2z2, z2);
-  felem_mul(u1, x1, z2z2);
-
-  felem_sum(tmp, z1, z2);
-  felem_square(tmp, tmp);
-  felem_diff(tmp, tmp, z1z1);
-  felem_diff(tmp, tmp, z2z2);
-
-  felem_mul(z2z2z2, z2, z2z2);
-  felem_mul(s1, y1, z2z2z2);
-
-  felem_mul(u2, x2, z1z1);
-  felem_mul(z1z1z1, z1, z1z1);
-  felem_mul(s2, y2, z1z1z1);
-  felem_diff(h, u2, u1);
-  felem_sum(i, h, h);
-  felem_square(i, i);
-  felem_mul(j, h, i);
-  felem_diff(r, s2, s1);
-  felem_sum(r, r, r);
-  felem_mul(v, u1, i);
-
-  felem_mul(z_out, tmp, h);
-  felem_square(rr, r);
-  felem_diff(x_out, rr, j);
-  felem_diff(x_out, x_out, v);
-  felem_diff(x_out, x_out, v);
-
-  felem_diff(tmp, v, x_out);
-  felem_mul(y_out, tmp, r);
-  felem_mul(tmp, s1, j);
-  felem_diff(y_out, y_out, tmp);
-  felem_diff(y_out, y_out, tmp);
-}
-
-/* point_add_or_double_vartime sets {x_out,y_out,z_out} = {x1,y1,z1} +
- *                                                        {x2,y2,z2}.
- *
- * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
- *
- * This function handles the case where {x1,y1,z1}={x2,y2,z2}. */
-static void point_add_or_double_vartime(
-    felem x_out, felem y_out, felem z_out, const felem x1, const felem y1,
-    const felem z1, const felem x2, const felem y2, const felem z2) {
-  felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
-  char x_equal, y_equal;
-
-  felem_square(z1z1, z1);
-  felem_square(z2z2, z2);
-  felem_mul(u1, x1, z2z2);
-
-  felem_sum(tmp, z1, z2);
-  felem_square(tmp, tmp);
-  felem_diff(tmp, tmp, z1z1);
-  felem_diff(tmp, tmp, z2z2);
-
-  felem_mul(z2z2z2, z2, z2z2);
-  felem_mul(s1, y1, z2z2z2);
-
-  felem_mul(u2, x2, z1z1);
-  felem_mul(z1z1z1, z1, z1z1);
-  felem_mul(s2, y2, z1z1z1);
-  felem_diff(h, u2, u1);
-  x_equal = felem_is_zero_vartime(h);
-  felem_sum(i, h, h);
-  felem_square(i, i);
-  felem_mul(j, h, i);
-  felem_diff(r, s2, s1);
-  y_equal = felem_is_zero_vartime(r);
-  if (x_equal && y_equal) {
-    point_double(x_out, y_out, z_out, x1, y1, z1);
-    return;
-  }
-  felem_sum(r, r, r);
-  felem_mul(v, u1, i);
-
-  felem_mul(z_out, tmp, h);
-  felem_square(rr, r);
-  felem_diff(x_out, rr, j);
-  felem_diff(x_out, x_out, v);
-  felem_diff(x_out, x_out, v);
-
-  felem_diff(tmp, v, x_out);
-  felem_mul(y_out, tmp, r);
-  felem_mul(tmp, s1, j);
-  felem_diff(y_out, y_out, tmp);
-  felem_diff(y_out, y_out, tmp);
-}
-
-/* copy_conditional sets out=in if mask = 0xffffffff in constant time.
- *
- * On entry: mask is either 0 or 0xffffffff. */
-static void copy_conditional(felem out, const felem in, limb mask) {
-  int i;
-
-  for (i = 0; i < NLIMBS; i++) {
-    const limb tmp = mask & (in[i] ^ out[i]);
-    out[i] ^= tmp;
-  }
-}
-
-/* select_affine_point sets {out_x,out_y} to the index'th entry of table.
- * On entry: index < 16, table[0] must be zero. */
-static void select_affine_point(felem out_x, felem out_y, const limb* table,
-                                limb index) {
-  limb i, j;
-
-  memset(out_x, 0, sizeof(felem));
-  memset(out_y, 0, sizeof(felem));
-
-  for (i = 1; i < 16; i++) {
-    limb mask = i ^ index;
-    mask |= mask >> 2;
-    mask |= mask >> 1;
-    mask &= 1;
-    mask--;
-    for (j = 0; j < NLIMBS; j++, table++) {
-      out_x[j] |= *table & mask;
-    }
-    for (j = 0; j < NLIMBS; j++, table++) {
-      out_y[j] |= *table & mask;
-    }
-  }
-}
-
-/* select_jacobian_point sets {out_x,out_y,out_z} to the index'th entry of
- * table. On entry: index < 16, table[0] must be zero. */
-static void select_jacobian_point(felem out_x, felem out_y, felem out_z,
-                                  const limb* table, limb index) {
-  limb i, j;
-
-  memset(out_x, 0, sizeof(felem));
-  memset(out_y, 0, sizeof(felem));
-  memset(out_z, 0, sizeof(felem));
-
-  /* The implicit value at index 0 is all zero. We don't need to perform that
-   * iteration of the loop because we already set out_* to zero. */
-  table += 3 * NLIMBS;
-
-  // Hit all entries to obscure cache profiling.
-  for (i = 1; i < 16; i++) {
-    limb mask = i ^ index;
-    mask |= mask >> 2;
-    mask |= mask >> 1;
-    mask &= 1;
-    mask--;
-    for (j = 0; j < NLIMBS; j++, table++) {
-      out_x[j] |= *table & mask;
-    }
-    for (j = 0; j < NLIMBS; j++, table++) {
-      out_y[j] |= *table & mask;
-    }
-    for (j = 0; j < NLIMBS; j++, table++) {
-      out_z[j] |= *table & mask;
-    }
-  }
-}
-
-/* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian
- * number. Note that the value of scalar must be less than the order of the
- * group. */
-static void scalar_base_mult(felem nx, felem ny, felem nz,
-                             const p256_int* scalar) {
-  int i, j;
-  limb n_is_infinity_mask = -1, p_is_noninfinite_mask, mask;
-  u32 table_offset;
-
-  felem px, py;
-  felem tx, ty, tz;
-
-  memset(nx, 0, sizeof(felem));
-  memset(ny, 0, sizeof(felem));
-  memset(nz, 0, sizeof(felem));
-
-  /* The loop adds bits at positions 0, 64, 128 and 192, followed by
-   * positions 32,96,160 and 224 and does this 32 times. */
-  for (i = 0; i < 32; i++) {
-    if (i) {
-      point_double(nx, ny, nz, nx, ny, nz);
-    }
-    table_offset = 0;
-    for (j = 0; j <= 32; j += 32) {
-      char bit0 = p256_get_bit(scalar, 31 - i + j);
-      char bit1 = p256_get_bit(scalar, 95 - i + j);
-      char bit2 = p256_get_bit(scalar, 159 - i + j);
-      char bit3 = p256_get_bit(scalar, 223 - i + j);
-      limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3);
-
-      select_affine_point(px, py, kPrecomputed + table_offset, index);
-      table_offset += 30 * NLIMBS;
-
-      /* Since scalar is less than the order of the group, we know that
-       * {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle
-       * below. */
-      point_add_mixed(tx, ty, tz, nx, ny, nz, px, py);
-      /* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero
-       * (a.k.a.  the point at infinity). We handle that situation by
-       * copying the point from the table. */
-      copy_conditional(nx, px, n_is_infinity_mask);
-      copy_conditional(ny, py, n_is_infinity_mask);
-      copy_conditional(nz, kOne, n_is_infinity_mask);
-
-      /* Equally, the result is also wrong if the point from the table is
-       * zero, which happens when the index is zero. We handle that by
-       * only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0. */
-      p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);
-      mask = p_is_noninfinite_mask & ~n_is_infinity_mask;
-      copy_conditional(nx, tx, mask);
-      copy_conditional(ny, ty, mask);
-      copy_conditional(nz, tz, mask);
-      /* If p was not zero, then n is now non-zero. */
-      n_is_infinity_mask &= ~p_is_noninfinite_mask;
-    }
-  }
-}
-
-/* point_to_affine converts a Jacobian point to an affine point. If the input
- * is the point at infinity then it returns (0, 0) in constant time. */
-static void point_to_affine(felem x_out, felem y_out, const felem nx,
-                            const felem ny, const felem nz) {
-  felem z_inv, z_inv_sq;
-  felem_inv(z_inv, nz);
-  felem_square(z_inv_sq, z_inv);
-  felem_mul(x_out, nx, z_inv_sq);
-  felem_mul(z_inv, z_inv, z_inv_sq);
-  felem_mul(y_out, ny, z_inv);
-}
-
-/* scalar_base_mult sets {nx,ny,nz} = scalar*{x,y}. */
-static void scalar_mult(felem nx, felem ny, felem nz, const felem x,
-                        const felem y, const p256_int* scalar) {
-  int i;
-  felem px, py, pz, tx, ty, tz;
-  felem precomp[16][3];
-  limb n_is_infinity_mask, index, p_is_noninfinite_mask, mask;
-
-  /* We precompute 0,1,2,... times {x,y}. */
-  memset(precomp, 0, sizeof(felem) * 3);
-  memcpy(&precomp[1][0], x, sizeof(felem));
-  memcpy(&precomp[1][1], y, sizeof(felem));
-  memcpy(&precomp[1][2], kOne, sizeof(felem));
-
-  for (i = 2; i < 16; i += 2) {
-    point_double(precomp[i][0], precomp[i][1], precomp[i][2],
-                 precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]);
-
-    point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2],
-                    precomp[i][0], precomp[i][1], precomp[i][2], x, y);
-  }
-
-  memset(nx, 0, sizeof(felem));
-  memset(ny, 0, sizeof(felem));
-  memset(nz, 0, sizeof(felem));
-  n_is_infinity_mask = -1;
-
-  /* We add in a window of four bits each iteration and do this 64 times. */
-  for (i = 0; i < 256; i += 4) {
-    if (i) {
-      point_double(nx, ny, nz, nx, ny, nz);
-      point_double(nx, ny, nz, nx, ny, nz);
-      point_double(nx, ny, nz, nx, ny, nz);
-      point_double(nx, ny, nz, nx, ny, nz);
-    }
-
-    index = (p256_get_bit(scalar, 255 - i - 0) << 3) |
-            (p256_get_bit(scalar, 255 - i - 1) << 2) |
-            (p256_get_bit(scalar, 255 - i - 2) << 1) |
-            p256_get_bit(scalar, 255 - i - 3);
-
-    /* See the comments in scalar_base_mult about handling infinities. */
-    select_jacobian_point(px, py, pz, precomp[0][0], index);
-    point_add(tx, ty, tz, nx, ny, nz, px, py, pz);
-    copy_conditional(nx, px, n_is_infinity_mask);
-    copy_conditional(ny, py, n_is_infinity_mask);
-    copy_conditional(nz, pz, n_is_infinity_mask);
-
-    p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);
-    mask = p_is_noninfinite_mask & ~n_is_infinity_mask;
-
-    copy_conditional(nx, tx, mask);
-    copy_conditional(ny, ty, mask);
-    copy_conditional(nz, tz, mask);
-    n_is_infinity_mask &= ~p_is_noninfinite_mask;
-  }
-}
-
-#define kRDigits {2, 0, 0, 0xfffffffe, 0xffffffff, 0xffffffff, 0xfffffffd, 1} // 2^257 mod p256.p
-
-#define kRInvDigits {0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff}  // 1 / 2^257 mod p256.p
-
-static const p256_int kR = { kRDigits };
-static const p256_int kRInv = { kRInvDigits };
-
-/* to_montgomery sets out = R*in. */
-static void to_montgomery(felem out, const p256_int* in) {
-  p256_int in_shifted;
-  int i;
-
-  p256_init(&in_shifted);
-  p256_modmul(&SECP256r1_p, in, 0, &kR, &in_shifted);
-
-  for (i = 0; i < NLIMBS; i++) {
-    if ((i & 1) == 0) {
-      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom29Bits;
-      p256_shr(&in_shifted, 29, &in_shifted);
-    } else {
-      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom28Bits;
-      p256_shr(&in_shifted, 28, &in_shifted);
-    }
-  }
-
-  p256_clear(&in_shifted);
-}
-
-/* from_montgomery sets out=in/R. */
-static void from_montgomery(p256_int* out, const felem in) {
-  p256_int result, tmp;
-  int i, top;
-
-  p256_init(&result);
-  p256_init(&tmp);
-
-  p256_add_d(&tmp, in[NLIMBS - 1], &result);
-  for (i = NLIMBS - 2; i >= 0; i--) {
-    if ((i & 1) == 0) {
-      top = p256_shl(&result, 29, &tmp);
-    } else {
-      top = p256_shl(&result, 28, &tmp);
-    }
-    top |= p256_add_d(&tmp, in[i], &result);
-  }
-
-  p256_modmul(&SECP256r1_p, &kRInv, top, &result, out);
-
-  p256_clear(&result);
-  p256_clear(&tmp);
-}
-
-/* p256_base_point_mul sets {out_x,out_y} = nG, where n is < the
- * order of the group. */
-void p256_base_point_mul(const p256_int* n, p256_int* out_x, p256_int* out_y) {
-  felem x, y, z;
-
-  scalar_base_mult(x, y, z, n);
-
-  {
-    felem x_affine, y_affine;
-
-    point_to_affine(x_affine, y_affine, x, y, z);
-    from_montgomery(out_x, x_affine);
-    from_montgomery(out_y, y_affine);
-  }
-}
-
-/* p256_points_mul_vartime sets {out_x,out_y} = n1*G + n2*{in_x,in_y}, where
- * n1 and n2 are < the order of the group.
- *
- * As indicated by the name, this function operates in variable time. This
- * is safe because it's used for signature validation which doesn't deal
- * with secrets. */
-void p256_points_mul_vartime(
-    const p256_int* n1, const p256_int* n2, const p256_int* in_x,
-    const p256_int* in_y, p256_int* out_x, p256_int* out_y) {
-  felem x1, y1, z1, x2, y2, z2, px, py;
-
-  /* If both scalars are zero, then the result is the point at infinity. */
-  if (p256_is_zero(n1) != 0 && p256_is_zero(n2) != 0) {
-    p256_clear(out_x);
-    p256_clear(out_y);
-    return;
-  }
-
-  to_montgomery(px, in_x);
-  to_montgomery(py, in_y);
-  scalar_base_mult(x1, y1, z1, n1);
-  scalar_mult(x2, y2, z2, px, py, n2);
-
-  if (p256_is_zero(n2) != 0) {
-    /* If n2 == 0, then {x2,y2,z2} is zero and the result is just
-         * {x1,y1,z1}. */
-  } else if (p256_is_zero(n1) != 0) {
-    /* If n1 == 0, then {x1,y1,z1} is zero and the result is just
-         * {x2,y2,z2}. */
-    memcpy(x1, x2, sizeof(x2));
-    memcpy(y1, y2, sizeof(y2));
-    memcpy(z1, z2, sizeof(z2));
-  } else {
-    /* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */
-    point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2);
-  }
-
-  point_to_affine(px, py, x1, y1, z1);
-  from_montgomery(out_x, px);
-  from_montgomery(out_y, py);
-}
diff --git a/libmincrypt/p256_ecdsa.c b/libmincrypt/p256_ecdsa.c
deleted file mode 100644
index f2264b0..0000000
--- a/libmincrypt/p256_ecdsa.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string.h>
-
-#include "mincrypt/p256_ecdsa.h"
-#include "mincrypt/p256.h"
-
-int p256_ecdsa_verify(const p256_int* key_x, const p256_int* key_y,
-                      const p256_int* message,
-                      const p256_int* r, const p256_int* s) {
-  p256_int u, v;
-
-  // Check public key.
-  if (!p256_is_valid_point(key_x, key_y)) return 0;
-
-  // Check r and s are != 0 % n.
-  p256_mod(&SECP256r1_n, r, &u);
-  p256_mod(&SECP256r1_n, s, &v);
-  if (p256_is_zero(&u) || p256_is_zero(&v)) return 0;
-
-  p256_modinv_vartime(&SECP256r1_n, s, &v);
-  p256_modmul(&SECP256r1_n, message, 0, &v, &u);  // message / s % n
-  p256_modmul(&SECP256r1_n, r, 0, &v, &v);  // r / s % n
-
-  p256_points_mul_vartime(&u, &v,
-                          key_x, key_y,
-                          &u, &v);
-
-  p256_mod(&SECP256r1_n, &u, &u);  // (x coord % p) % n
-  return p256_cmp(r, &u) == 0;
-}
-
diff --git a/libmincrypt/rsa.c b/libmincrypt/rsa.c
deleted file mode 100644
index 9061b3a..0000000
--- a/libmincrypt/rsa.c
+++ /dev/null
@@ -1,308 +0,0 @@
-/* rsa.c
-**
-** Copyright 2012, The Android Open Source Project
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**     * Redistributions of source code must retain the above copyright
-**       notice, this list of conditions and the following disclaimer.
-**     * Redistributions in binary form must reproduce the above copyright
-**       notice, this list of conditions and the following disclaimer in the
-**       documentation and/or other materials provided with the distribution.
-**     * Neither the name of Google Inc. nor the names of its contributors may
-**       be used to endorse or promote products derived from this software
-**       without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
-** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-#include "mincrypt/sha256.h"
-
-// a[] -= mod
-static void subM(const RSAPublicKey* key,
-                 uint32_t* a) {
-    int64_t A = 0;
-    int i;
-    for (i = 0; i < key->len; ++i) {
-        A += (uint64_t)a[i] - key->n[i];
-        a[i] = (uint32_t)A;
-        A >>= 32;
-    }
-}
-
-// return a[] >= mod
-static int geM(const RSAPublicKey* key,
-               const uint32_t* a) {
-    int i;
-    for (i = key->len; i;) {
-        --i;
-        if (a[i] < key->n[i]) return 0;
-        if (a[i] > key->n[i]) return 1;
-    }
-    return 1;  // equal
-}
-
-// montgomery c[] += a * b[] / R % mod
-static void montMulAdd(const RSAPublicKey* key,
-                       uint32_t* c,
-                       const uint32_t a,
-                       const uint32_t* b) {
-    uint64_t A = (uint64_t)a * b[0] + c[0];
-    uint32_t d0 = (uint32_t)A * key->n0inv;
-    uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A;
-    int i;
-
-    for (i = 1; i < key->len; ++i) {
-        A = (A >> 32) + (uint64_t)a * b[i] + c[i];
-        B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A;
-        c[i - 1] = (uint32_t)B;
-    }
-
-    A = (A >> 32) + (B >> 32);
-
-    c[i - 1] = (uint32_t)A;
-
-    if (A >> 32) {
-        subM(key, c);
-    }
-}
-
-// montgomery c[] = a[] * b[] / R % mod
-static void montMul(const RSAPublicKey* key,
-                    uint32_t* c,
-                    const uint32_t* a,
-                    const uint32_t* b) {
-    int i;
-    for (i = 0; i < key->len; ++i) {
-        c[i] = 0;
-    }
-    for (i = 0; i < key->len; ++i) {
-        montMulAdd(key, c, a[i], b);
-    }
-}
-
-// In-place public exponentiation.
-// Input and output big-endian byte array in inout.
-static void modpow(const RSAPublicKey* key,
-                   uint8_t* inout) {
-    uint32_t a[RSANUMWORDS];
-    uint32_t aR[RSANUMWORDS];
-    uint32_t aaR[RSANUMWORDS];
-    uint32_t* aaa = 0;
-    int i;
-
-    // Convert from big endian byte array to little endian word array.
-    for (i = 0; i < key->len; ++i) {
-        uint32_t tmp =
-            (inout[((key->len - 1 - i) * 4) + 0] << 24) |
-            (inout[((key->len - 1 - i) * 4) + 1] << 16) |
-            (inout[((key->len - 1 - i) * 4) + 2] << 8) |
-            (inout[((key->len - 1 - i) * 4) + 3] << 0);
-        a[i] = tmp;
-    }
-
-    if (key->exponent == 65537) {
-        aaa = aaR;  // Re-use location.
-        montMul(key, aR, a, key->rr);  // aR = a * RR / R mod M
-        for (i = 0; i < 16; i += 2) {
-            montMul(key, aaR, aR, aR);  // aaR = aR * aR / R mod M
-            montMul(key, aR, aaR, aaR);  // aR = aaR * aaR / R mod M
-        }
-        montMul(key, aaa, aR, a);  // aaa = aR * a / R mod M
-    } else if (key->exponent == 3) {
-        aaa = aR;  // Re-use location.
-        montMul(key, aR, a, key->rr);  /* aR = a * RR / R mod M   */
-        montMul(key, aaR, aR, aR);     /* aaR = aR * aR / R mod M */
-        montMul(key, aaa, aaR, a);     /* aaa = aaR * a / R mod M */
-    }
-
-    // Make sure aaa < mod; aaa is at most 1x mod too large.
-    if (geM(key, aaa)) {
-        subM(key, aaa);
-    }
-
-    // Convert to bigendian byte array
-    for (i = key->len - 1; i >= 0; --i) {
-        uint32_t tmp = aaa[i];
-        *inout++ = tmp >> 24;
-        *inout++ = tmp >> 16;
-        *inout++ = tmp >> 8;
-        *inout++ = tmp >> 0;
-    }
-}
-
-// Expected PKCS1.5 signature padding bytes, for a keytool RSA signature.
-// Has the 0-length optional parameter encoded in the ASN1 (as opposed to the
-// other flavor which omits the optional parameter entirely). This code does not
-// accept signatures without the optional parameter.
-
-/*
-static const uint8_t sha_padding[RSANUMBYTES] = {
-    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x21, 0x30,
-    0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a,
-    0x05, 0x00, 0x04, 0x14,
-
-    // 20 bytes of hash go here.
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
-};
-*/
-
-// SHA-1 of PKCS1.5 signature sha_padding for 2048 bit, as above.
-// At the location of the bytes of the hash all 00 are hashed.
-static const uint8_t kExpectedPadShaRsa2048[SHA_DIGEST_SIZE] = {
-    0xdc, 0xbd, 0xbe, 0x42, 0xd5, 0xf5, 0xa7, 0x2e,
-    0x6e, 0xfc, 0xf5, 0x5d, 0xaf, 0x9d, 0xea, 0x68,
-    0x7c, 0xfb, 0xf1, 0x67
-};
-
-/*
-static const uint8_t sha256_padding[RSANUMBYTES] = {
-    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x31, 0x30,
-    0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
-    0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,
-
-    // 32 bytes of hash go here.
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-};
-*/
-
-// SHA-256 of PKCS1.5 signature sha256_padding for 2048 bit, as above.
-// At the location of the bytes of the hash all 00 are hashed.
-static const uint8_t kExpectedPadSha256Rsa2048[SHA256_DIGEST_SIZE] = {
-    0xab, 0x28, 0x8d, 0x8a, 0xd7, 0xd9, 0x59, 0x92,
-    0xba, 0xcc, 0xf8, 0x67, 0x20, 0xe1, 0x15, 0x2e,
-    0x39, 0x8d, 0x80, 0x36, 0xd6, 0x6f, 0xf0, 0xfd,
-    0x90, 0xe8, 0x7d, 0x8b, 0xe1, 0x7c, 0x87, 0x59,
-};
-
-// Verify a 2048-bit RSA PKCS1.5 signature against an expected hash.
-// Both e=3 and e=65537 are supported.  hash_len may be
-// SHA_DIGEST_SIZE (== 20) to indicate a SHA-1 hash, or
-// SHA256_DIGEST_SIZE (== 32) to indicate a SHA-256 hash.  No other
-// values are supported.
-//
-// Returns 1 on successful verification, 0 on failure.
-int RSA_verify(const RSAPublicKey *key,
-               const uint8_t *signature,
-               const int len,
-               const uint8_t *hash,
-               const int hash_len) {
-    uint8_t buf[RSANUMBYTES];
-    int i;
-    const uint8_t* padding_hash;
-
-    if (key->len != RSANUMWORDS) {
-        return 0;  // Wrong key passed in.
-    }
-
-    if (len != sizeof(buf)) {
-        return 0;  // Wrong input length.
-    }
-
-    if (hash_len != SHA_DIGEST_SIZE &&
-        hash_len != SHA256_DIGEST_SIZE) {
-        return 0;  // Unsupported hash.
-    }
-
-    if (key->exponent != 3 && key->exponent != 65537) {
-        return 0;  // Unsupported exponent.
-    }
-
-    for (i = 0; i < len; ++i) {  // Copy input to local workspace.
-        buf[i] = signature[i];
-    }
-
-    modpow(key, buf);  // In-place exponentiation.
-
-    // Xor sha portion, so it all becomes 00 iff equal.
-    for (i = len - hash_len; i < len; ++i) {
-        buf[i] ^= *hash++;
-    }
-
-    // Hash resulting buf, in-place.
-    switch (hash_len) {
-        case SHA_DIGEST_SIZE:
-            padding_hash = kExpectedPadShaRsa2048;
-            SHA_hash(buf, len, buf);
-            break;
-        case SHA256_DIGEST_SIZE:
-            padding_hash = kExpectedPadSha256Rsa2048;
-            SHA256_hash(buf, len, buf);
-            break;
-        default:
-            return 0;
-    }
-
-    // Compare against expected hash value.
-    for (i = 0; i < hash_len; ++i) {
-        if (buf[i] != padding_hash[i]) {
-            return 0;
-        }
-    }
-
-    return 1;  // All checked out OK.
-}
diff --git a/libmincrypt/sha.c b/libmincrypt/sha.c
deleted file mode 100644
index 5bef32e..0000000
--- a/libmincrypt/sha.c
+++ /dev/null
@@ -1,155 +0,0 @@
-/* sha.c
-**
-** Copyright 2013, The Android Open Source Project
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**     * Redistributions of source code must retain the above copyright
-**       notice, this list of conditions and the following disclaimer.
-**     * Redistributions in binary form must reproduce the above copyright
-**       notice, this list of conditions and the following disclaimer in the
-**       documentation and/or other materials provided with the distribution.
-**     * Neither the name of Google Inc. nor the names of its contributors may
-**       be used to endorse or promote products derived from this software
-**       without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
-** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-// Optimized for minimal code size.
-
-#include "mincrypt/sha.h"
-
-#include <stdio.h>
-#include <string.h>
-#include <stdint.h>
-
-#define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-static void SHA1_Transform(SHA_CTX* ctx) {
-    uint32_t W[80];
-    uint32_t A, B, C, D, E;
-    uint8_t* p = ctx->buf;
-    int t;
-
-    for(t = 0; t < 16; ++t) {
-        uint32_t tmp =  *p++ << 24;
-        tmp |= *p++ << 16;
-        tmp |= *p++ << 8;
-        tmp |= *p++;
-        W[t] = tmp;
-    }
-
-    for(; t < 80; t++) {
-        W[t] = rol(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
-    }
-
-    A = ctx->state[0];
-    B = ctx->state[1];
-    C = ctx->state[2];
-    D = ctx->state[3];
-    E = ctx->state[4];
-
-    for(t = 0; t < 80; t++) {
-        uint32_t tmp = rol(5,A) + E + W[t];
-
-        if (t < 20)
-            tmp += (D^(B&(C^D))) + 0x5A827999;
-        else if ( t < 40)
-            tmp += (B^C^D) + 0x6ED9EBA1;
-        else if ( t < 60)
-            tmp += ((B&C)|(D&(B|C))) + 0x8F1BBCDC;
-        else
-            tmp += (B^C^D) + 0xCA62C1D6;
-
-        E = D;
-        D = C;
-        C = rol(30,B);
-        B = A;
-        A = tmp;
-    }
-
-    ctx->state[0] += A;
-    ctx->state[1] += B;
-    ctx->state[2] += C;
-    ctx->state[3] += D;
-    ctx->state[4] += E;
-}
-
-static const HASH_VTAB SHA_VTAB = {
-    SHA_init,
-    SHA_update,
-    SHA_final,
-    SHA_hash,
-    SHA_DIGEST_SIZE
-};
-
-void SHA_init(SHA_CTX* ctx) {
-    ctx->f = &SHA_VTAB;
-    ctx->state[0] = 0x67452301;
-    ctx->state[1] = 0xEFCDAB89;
-    ctx->state[2] = 0x98BADCFE;
-    ctx->state[3] = 0x10325476;
-    ctx->state[4] = 0xC3D2E1F0;
-    ctx->count = 0;
-}
-
-
-void SHA_update(SHA_CTX* ctx, const void* data, int len) {
-    int i = (int) (ctx->count & 63);
-    const uint8_t* p = (const uint8_t*)data;
-
-    ctx->count += len;
-
-    while (len--) {
-        ctx->buf[i++] = *p++;
-        if (i == 64) {
-            SHA1_Transform(ctx);
-            i = 0;
-        }
-    }
-}
-
-
-const uint8_t* SHA_final(SHA_CTX* ctx) {
-    uint8_t *p = ctx->buf;
-    uint64_t cnt = ctx->count * 8;
-    int i;
-
-    SHA_update(ctx, (uint8_t*)"\x80", 1);
-    while ((ctx->count & 63) != 56) {
-        SHA_update(ctx, (uint8_t*)"\0", 1);
-    }
-    for (i = 0; i < 8; ++i) {
-        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));
-        SHA_update(ctx, &tmp, 1);
-    }
-
-    for (i = 0; i < 5; i++) {
-        uint32_t tmp = ctx->state[i];
-        *p++ = tmp >> 24;
-        *p++ = tmp >> 16;
-        *p++ = tmp >> 8;
-        *p++ = tmp >> 0;
-    }
-
-    return ctx->buf;
-}
-
-/* Convenience function */
-const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest) {
-    SHA_CTX ctx;
-    SHA_init(&ctx);
-    SHA_update(&ctx, data, len);
-    memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE);
-    return digest;
-}
diff --git a/libmincrypt/sha256.c b/libmincrypt/sha256.c
deleted file mode 100644
index eb6e308..0000000
--- a/libmincrypt/sha256.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/* sha256.c
-**
-** Copyright 2013, The Android Open Source Project
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**     * Redistributions of source code must retain the above copyright
-**       notice, this list of conditions and the following disclaimer.
-**     * Redistributions in binary form must reproduce the above copyright
-**       notice, this list of conditions and the following disclaimer in the
-**       documentation and/or other materials provided with the distribution.
-**     * Neither the name of Google Inc. nor the names of its contributors may
-**       be used to endorse or promote products derived from this software
-**       without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
-** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-// Optimized for minimal code size.
-
-#include "mincrypt/sha256.h"
-
-#include <stdio.h>
-#include <string.h>
-#include <stdint.h>
-
-#define ror(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits))))
-#define shr(value, bits) ((value) >> (bits))
-
-static const uint32_t K[64] = {
-    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
-    0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
-    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
-    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
-    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
-    0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
-    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
-    0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
-    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
-    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
-    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
-    0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
-    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
-    0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
-    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
-    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
-
-static void SHA256_Transform(SHA256_CTX* ctx) {
-    uint32_t W[64];
-    uint32_t A, B, C, D, E, F, G, H;
-    uint8_t* p = ctx->buf;
-    int t;
-
-    for(t = 0; t < 16; ++t) {
-        uint32_t tmp =  *p++ << 24;
-        tmp |= *p++ << 16;
-        tmp |= *p++ << 8;
-        tmp |= *p++;
-        W[t] = tmp;
-    }
-
-    for(; t < 64; t++) {
-        uint32_t s0 = ror(W[t-15], 7) ^ ror(W[t-15], 18) ^ shr(W[t-15], 3);
-        uint32_t s1 = ror(W[t-2], 17) ^ ror(W[t-2], 19) ^ shr(W[t-2], 10);
-        W[t] = W[t-16] + s0 + W[t-7] + s1;
-    }
-
-    A = ctx->state[0];
-    B = ctx->state[1];
-    C = ctx->state[2];
-    D = ctx->state[3];
-    E = ctx->state[4];
-    F = ctx->state[5];
-    G = ctx->state[6];
-    H = ctx->state[7];
-
-    for(t = 0; t < 64; t++) {
-        uint32_t s0 = ror(A, 2) ^ ror(A, 13) ^ ror(A, 22);
-        uint32_t maj = (A & B) ^ (A & C) ^ (B & C);
-        uint32_t t2 = s0 + maj;
-        uint32_t s1 = ror(E, 6) ^ ror(E, 11) ^ ror(E, 25);
-        uint32_t ch = (E & F) ^ ((~E) & G);
-        uint32_t t1 = H + s1 + ch + K[t] + W[t];
-
-        H = G;
-        G = F;
-        F = E;
-        E = D + t1;
-        D = C;
-        C = B;
-        B = A;
-        A = t1 + t2;
-    }
-
-    ctx->state[0] += A;
-    ctx->state[1] += B;
-    ctx->state[2] += C;
-    ctx->state[3] += D;
-    ctx->state[4] += E;
-    ctx->state[5] += F;
-    ctx->state[6] += G;
-    ctx->state[7] += H;
-}
-
-static const HASH_VTAB SHA256_VTAB = {
-    SHA256_init,
-    SHA256_update,
-    SHA256_final,
-    SHA256_hash,
-    SHA256_DIGEST_SIZE
-};
-
-void SHA256_init(SHA256_CTX* ctx) {
-    ctx->f = &SHA256_VTAB;
-    ctx->state[0] = 0x6a09e667;
-    ctx->state[1] = 0xbb67ae85;
-    ctx->state[2] = 0x3c6ef372;
-    ctx->state[3] = 0xa54ff53a;
-    ctx->state[4] = 0x510e527f;
-    ctx->state[5] = 0x9b05688c;
-    ctx->state[6] = 0x1f83d9ab;
-    ctx->state[7] = 0x5be0cd19;
-    ctx->count = 0;
-}
-
-
-void SHA256_update(SHA256_CTX* ctx, const void* data, int len) {
-    int i = (int) (ctx->count & 63);
-    const uint8_t* p = (const uint8_t*)data;
-
-    ctx->count += len;
-
-    while (len--) {
-        ctx->buf[i++] = *p++;
-        if (i == 64) {
-            SHA256_Transform(ctx);
-            i = 0;
-        }
-    }
-}
-
-
-const uint8_t* SHA256_final(SHA256_CTX* ctx) {
-    uint8_t *p = ctx->buf;
-    uint64_t cnt = ctx->count * 8;
-    int i;
-
-    SHA256_update(ctx, (uint8_t*)"\x80", 1);
-    while ((ctx->count & 63) != 56) {
-        SHA256_update(ctx, (uint8_t*)"\0", 1);
-    }
-    for (i = 0; i < 8; ++i) {
-        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));
-        SHA256_update(ctx, &tmp, 1);
-    }
-
-    for (i = 0; i < 8; i++) {
-        uint32_t tmp = ctx->state[i];
-        *p++ = tmp >> 24;
-        *p++ = tmp >> 16;
-        *p++ = tmp >> 8;
-        *p++ = tmp >> 0;
-    }
-
-    return ctx->buf;
-}
-
-/* Convenience function */
-const uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest) {
-    SHA256_CTX ctx;
-    SHA256_init(&ctx);
-    SHA256_update(&ctx, data, len);
-    memcpy(digest, SHA256_final(&ctx), SHA256_DIGEST_SIZE);
-    return digest;
-}
diff --git a/libmincrypt/test/Android.mk b/libmincrypt/test/Android.mk
deleted file mode 100644
index 73ff7d0..0000000
--- a/libmincrypt/test/Android.mk
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2013 The Android Open Source Project
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rsa_test
-LOCAL_SRC_FILES := rsa_test.c
-LOCAL_STATIC_LIBRARIES := libmincrypt
-include $(BUILD_HOST_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := ecdsa_test
-LOCAL_SRC_FILES := ecdsa_test.c
-LOCAL_STATIC_LIBRARIES := libmincrypt
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libmincrypt/test/ecdsa_test.c b/libmincrypt/test/ecdsa_test.c
deleted file mode 100644
index 24ec013..0000000
--- a/libmincrypt/test/ecdsa_test.c
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Google Inc. nor the names of its contributors may
- *       be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/cdefs.h>
-
-#include "mincrypt/dsa_sig.h"
-#include "mincrypt/p256.h"
-#include "mincrypt/p256_ecdsa.h"
-#include "mincrypt/sha256.h"
-
-#ifndef __unused
-#define __unused __attribute__((__unused__))
-#endif
-
-/**
- * Messages signed using:
- *
------BEGIN EC PRIVATE KEY-----
-MHcCAQEEIDw6UiziVMbjlfSpOAIpA2tcL+v1OlznZLnpadO8BGi1oAoGCCqGSM49
-AwEHoUQDQgAEZw7VAOjAXYRFuhZWYBgjahdOvkwcAnjGkxQWytZW+iS1hI3ZGE24
-6XmNka9IGxAgj2n/ip+MuZJMFoJ9DRea3g==
------END EC PRIVATE KEY-----
- */
-
-p256_int key_x = {
-    .a = {0xd656fa24u, 0x931416cau, 0x1c0278c6u, 0x174ebe4cu,
-          0x6018236au, 0x45ba1656u, 0xe8c05d84u, 0x670ed500u}
-};
-p256_int key_y = {
-    .a = {0x0d179adeu, 0x4c16827du, 0x9f8cb992u, 0x8f69ff8au,
-          0x481b1020u, 0x798d91afu, 0x184db8e9u, 0xb5848dd9u}
-};
-
-char* message_1 =
-    "f4 5d 55 f3 55 51 e9 75 d6 a8 dc 7e a9 f4 88 59"
-    "39 40 cc 75 69 4a 27 8f 27 e5 78 a1 63 d8 39 b3"
-    "40 40 84 18 08 cf 9c 58 c9 b8 72 8b f5 f9 ce 8e"
-    "e8 11 ea 91 71 4f 47 ba b9 2d 0f 6d 5a 26 fc fe"
-    "ea 6c d9 3b 91 0c 0a 2c 96 3e 64 eb 18 23 f1 02"
-    "75 3d 41 f0 33 59 10 ad 3a 97 71 04 f1 aa f6 c3"
-    "74 27 16 a9 75 5d 11 b8 ee d6 90 47 7f 44 5c 5d"
-    "27 20 8b 2e 28 43 30 fa 3d 30 14 23 fa 7f 2d 08"
-    "6e 0a d0 b8 92 b9 db 54 4e 45 6d 3f 0d ab 85 d9"
-    "53 c1 2d 34 0a a8 73 ed a7 27 c8 a6 49 db 7f a6"
-    "37 40 e2 5e 9a f1 53 3b 30 7e 61 32 99 93 11 0e"
-    "95 19 4e 03 93 99 c3 82 4d 24 c5 1f 22 b2 6b de"
-    "10 24 cd 39 59 58 a2 df eb 48 16 a6 e8 ad ed b5"
-    "0b 1f 6b 56 d0 b3 06 0f f0 f1 c4 cb 0d 0e 00 1d"
-    "d5 9d 73 be 12";
-
-char* signature_1 =
-    "30 44 02 20 43 18 fc eb 3b a8 3a a8 a3 cf 41 b7"
-    "81 4a f9 01 e1 8b 6e 95 c1 3a 83 25 9e a5 2e 66"
-    "7c 98 25 d9 02 20 54 f3 7f 5a e9 36 9c a2 f0 51"
-    "e0 6e 78 48 60 a3 f9 8a d5 2c 37 5a 0a 29 c9 f7"
-    "ea 57 7e 88 46 12";
-
-// Same as signature 1, but with leading zeroes.
-char* message_2 =
-    "f4 5d 55 f3 55 51 e9 75 d6 a8 dc 7e a9 f4 88 59"
-    "39 40 cc 75 69 4a 27 8f 27 e5 78 a1 63 d8 39 b3"
-    "40 40 84 18 08 cf 9c 58 c9 b8 72 8b f5 f9 ce 8e"
-    "e8 11 ea 91 71 4f 47 ba b9 2d 0f 6d 5a 26 fc fe"
-    "ea 6c d9 3b 91 0c 0a 2c 96 3e 64 eb 18 23 f1 02"
-    "75 3d 41 f0 33 59 10 ad 3a 97 71 04 f1 aa f6 c3"
-    "74 27 16 a9 75 5d 11 b8 ee d6 90 47 7f 44 5c 5d"
-    "27 20 8b 2e 28 43 30 fa 3d 30 14 23 fa 7f 2d 08"
-    "6e 0a d0 b8 92 b9 db 54 4e 45 6d 3f 0d ab 85 d9"
-    "53 c1 2d 34 0a a8 73 ed a7 27 c8 a6 49 db 7f a6"
-    "37 40 e2 5e 9a f1 53 3b 30 7e 61 32 99 93 11 0e"
-    "95 19 4e 03 93 99 c3 82 4d 24 c5 1f 22 b2 6b de"
-    "10 24 cd 39 59 58 a2 df eb 48 16 a6 e8 ad ed b5"
-    "0b 1f 6b 56 d0 b3 06 0f f0 f1 c4 cb 0d 0e 00 1d"
-    "d5 9d 73 be 12";
-
-char* signature_2 =
-    "30 46 02 21 00 43 18 fc eb 3b a8 3a a8 a3 cf 41 b7"
-    "81 4a f9 01 e1 8b 6e 95 c1 3a 83 25 9e a5 2e 66"
-    "7c 98 25 d9 02 21 00 54 f3 7f 5a e9 36 9c a2 f0 51"
-    "e0 6e 78 48 60 a3 f9 8a d5 2c 37 5a 0a 29 c9 f7"
-    "ea 57 7e 88 46 12";
-
-// Excessive zeroes on the signature
-char* message_3 =
-    "f4 5d 55 f3 55 51 e9 75 d6 a8 dc 7e a9 f4 88 59"
-    "39 40 cc 75 69 4a 27 8f 27 e5 78 a1 63 d8 39 b3"
-    "40 40 84 18 08 cf 9c 58 c9 b8 72 8b f5 f9 ce 8e"
-    "e8 11 ea 91 71 4f 47 ba b9 2d 0f 6d 5a 26 fc fe"
-    "ea 6c d9 3b 91 0c 0a 2c 96 3e 64 eb 18 23 f1 02"
-    "75 3d 41 f0 33 59 10 ad 3a 97 71 04 f1 aa f6 c3"
-    "74 27 16 a9 75 5d 11 b8 ee d6 90 47 7f 44 5c 5d"
-    "27 20 8b 2e 28 43 30 fa 3d 30 14 23 fa 7f 2d 08"
-    "6e 0a d0 b8 92 b9 db 54 4e 45 6d 3f 0d ab 85 d9"
-    "53 c1 2d 34 0a a8 73 ed a7 27 c8 a6 49 db 7f a6"
-    "37 40 e2 5e 9a f1 53 3b 30 7e 61 32 99 93 11 0e"
-    "95 19 4e 03 93 99 c3 82 4d 24 c5 1f 22 b2 6b de"
-    "10 24 cd 39 59 58 a2 df eb 48 16 a6 e8 ad ed b5"
-    "0b 1f 6b 56 d0 b3 06 0f f0 f1 c4 cb 0d 0e 00 1d"
-    "d5 9d 73 be 12";
-
-char* signature_3 =
-    "30 4c 02 24 00 00 00 00 43 18 fc eb 3b a8 3a a8 a3 cf 41 b7"
-    "81 4a f9 01 e1 8b 6e 95 c1 3a 83 25 9e a5 2e 66"
-    "7c 98 25 d9 02 24 00 00 00 00 54 f3 7f 5a e9 36 9c a2 f0 51"
-    "e0 6e 78 48 60 a3 f9 8a d5 2c 37 5a 0a 29 c9 f7"
-    "ea 57 7e 88 46 12";
-
-
-char* good_dsa_signature_1 =
-    "30 0D 02 01 01 02 08 00 A5 55 5A 01 FF A5 01";
-p256_int good_dsa_signature_1_r = {
-    .a = {0x00000001U, 0x00000000U, 0x00000000U, 0x00000000U,
-          0x00000000U, 0x00000000U, 0x00000000U, 0x00000000U}
-};
-p256_int good_dsa_signature_1_s = {
-    .a = {0x01FFA501U, 0x00A5555AU, 0x00000000U, 0x00000000U,
-          0x00000000U, 0x00000000U, 0x00000000U, 0x00000000U}
-};
-
-
-char* bad_dsa_signature_1 =
-     "a0 06 02 01 01 02 01 01";
-
-char* bad_dsa_signature_2 =
-     "30 07 02 01 01 02 01 01";
-
-char* bad_dsa_signature_3 =
-     "30 06 82 01 01 02 01 01";
-
-char* bad_dsa_signature_4 =
-     "30 06 02 00 01 02 01 01";
-
-char* bad_dsa_signature_5 =
-     "30 06 02 01 01 82 01 01";
-
-char* bad_dsa_signature_6 =
-     "30 05 02 01 01 02 00";
-
-char* bad_dsa_signature_7 =
-     "30 06 02 01 01 02 00 01";
-
-unsigned char* parsehex(char* str, int* len) {
-    // result can't be longer than input
-    unsigned char* result = malloc(strlen(str));
-
-    unsigned char* p = result;
-    *len = 0;
-
-    while (*str) {
-        int b;
-
-        while (isspace(*str)) str++;
-
-        switch (*str) {
-            case '0': case '1': case '2': case '3': case '4':
-            case '5': case '6': case '7': case '8': case '9':
-                b = (*str - '0') << 4; break;
-            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
-                b = (*str - 'a' + 10) << 4; break;
-            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
-                b = (*str - 'A' + 10) << 4; break;
-            case '\0':
-                return result;
-            default:
-                return NULL;
-        }
-        str++;
-
-        while (isspace(*str)) str++;
-
-        switch (*str) {
-            case '0': case '1': case '2': case '3': case '4':
-            case '5': case '6': case '7': case '8': case '9':
-                b |= *str - '0'; break;
-            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
-                b |= *str - 'a' + 10; break;
-            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
-                b |= *str - 'A' + 10; break;
-            default:
-                return NULL;
-        }
-        str++;
-
-        *p++ = b;
-        ++*len;
-    }
-
-    return result;
-}
-
-int main(int arg __unused, char** argv __unused) {
-
-    unsigned char hash_buf[SHA256_DIGEST_SIZE];
-
-    unsigned char* message;
-    int mlen;
-    unsigned char* signature;
-    int slen;
-
-    p256_int hash;
-    p256_int r;
-    p256_int s;
-
-    int success = 1;
-
-#define CHECK_DSA_SIG(sig, good) do {\
-    message = parsehex(sig, &mlen); \
-    int result = dsa_sig_unpack(message, mlen, &r, &s); \
-    printf(#sig ": %s\n", result ? "good" : "bad"); \
-    success = success && !(good ^ result); \
-    free(message); \
-    } while(0)
-#define CHECK_GOOD_DSA_SIG(n) do {\
-    CHECK_DSA_SIG(good_dsa_signature_##n, 1); \
-    int result = !memcmp(P256_DIGITS(&good_dsa_signature_##n##_r), P256_DIGITS(&r), \
-                         P256_NBYTES); \
-    success = success && result; \
-    printf("    R value %s\n", result ? "good" : "bad"); \
-    result = !memcmp(P256_DIGITS(&good_dsa_signature_##n##_s), P256_DIGITS(&s), \
-                    P256_NBYTES); \
-    success = success && result; \
-    printf("    S value %s\n", result ? "good" : "bad"); \
-    } while (0)
-#define CHECK_BAD_DSA_SIG(n) \
-    CHECK_DSA_SIG(bad_dsa_signature_##n, 0)
-
-    CHECK_GOOD_DSA_SIG(1);
-
-    CHECK_BAD_DSA_SIG(1);
-    CHECK_BAD_DSA_SIG(2);
-    CHECK_BAD_DSA_SIG(3);
-    CHECK_BAD_DSA_SIG(4);
-    CHECK_BAD_DSA_SIG(5);
-    CHECK_BAD_DSA_SIG(6);
-    CHECK_BAD_DSA_SIG(7);
-
-
-#define TEST_MESSAGE(n) do {\
-    message = parsehex(message_##n, &mlen); \
-    SHA256_hash(message, mlen, hash_buf); \
-    p256_from_bin(hash_buf, &hash); \
-    signature = parsehex(signature_##n, &slen); \
-    int result = dsa_sig_unpack(signature, slen, &r, &s); \
-    if (result) { result = p256_ecdsa_verify(&key_x, &key_y, &hash, &r, &s); } \
-    printf("message %d: %s\n", n, result ? "verified" : "not verified"); \
-    success = success && result; \
-    free(signature); \
-    } while(0)
-
-    TEST_MESSAGE(1);
-    TEST_MESSAGE(2);
-    TEST_MESSAGE(3);
-
-    printf("\n%s\n\n", success ? "PASS" : "FAIL");
-
-    return !success;
-}
diff --git a/libmincrypt/test/rsa_test.c b/libmincrypt/test/rsa_test.c
deleted file mode 100644
index 055138f..0000000
--- a/libmincrypt/test/rsa_test.c
+++ /dev/null
@@ -1,842 +0,0 @@
-/*
-** Copyright 2013, The Android Open Source Project
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**     * Redistributions of source code must retain the above copyright
-**       notice, this list of conditions and the following disclaimer.
-**     * Redistributions in binary form must reproduce the above copyright
-**       notice, this list of conditions and the following disclaimer in the
-**       documentation and/or other materials provided with the distribution.
-**     * Neither the name of Google Inc. nor the names of its contributors may
-**       be used to endorse or promote products derived from this software
-**       without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR
-** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/cdefs.h>
-
-#include "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-
-#ifndef __unused
-#define __unused __attribute__((unused))
-#endif
-
-// RSA test data taken from:
-//
-//   ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
-
-// This is the result (reformatted) of running DumpPublicKey on:
-//
-//   # Example 15: A 2048-bit RSA key pair
-//   # -----------------------------------
-//
-//
-//   # Public key
-//   # ----------
-//
-//   # Modulus:
-//   df 27 1f d2 5f 86 44 49 6b 0c 81 be 4b d5 02 97
-//   ef 09 9b 00 2a 6f d6 77 27 eb 44 9c ea 56 6e d6
-//   a3 98 1a 71 31 2a 14 1c ab c9 81 5c 12 09 e3 20
-//   a2 5b 32 46 4e 99 99 f1 8c a1 3a 9f d3 89 25 58
-//   f9 e0 ad ef dd 36 50 dd 23 a3 f0 36 d6 0f e3 98
-//   84 37 06 a4 0b 0b 84 62 c8 be e3 bc e1 2f 1f 28
-//   60 c2 44 4c dc 6a 44 47 6a 75 ff 4a a2 42 73 cc
-//   be 3b f8 02 48 46 5f 8f f8 c3 a7 f3 36 7d fc 0d
-//   f5 b6 50 9a 4f 82 81 1c ed d8 1c da aa 73 c4 91
-//   da 41 21 70 d5 44 d4 ba 96 b9 7f 0a fc 80 65 49
-//   8d 3a 49 fd 91 09 92 a1 f0 72 5b e2 4f 46 5c fe
-//   7e 0e ab f6 78 99 6c 50 bc 5e 75 24 ab f7 3f 15
-//   e5 be f7 d5 18 39 4e 31 38 ce 49 44 50 6a aa af
-//   3f 9b 23 6d ca b8 fc 00 f8 7a f5 96 fd c3 d9 d6
-//   c7 5c d5 08 36 2f ae 2c be dd cc 4c 74 50 b1 7b
-//   77 6c 07 9e cc a1 f2 56 35 1a 43 b9 7d be 21 53
-//
-//   # Exponent:
-//   01 00 01
-
-RSAPublicKey key_15 = {
-    .len = 64,
-    .n0inv = 0xf0053525,
-    .n = {2109612371u,890913721u,3433165398u,2003568542u,
-          1951445371u,3202206796u,909094444u,3344749832u,
-          4257470934u,4168807830u,3401120768u,1067131757u,
-          1349167791u,953043268u,406408753u,3854497749u,
-          2885107477u,3160306980u,2023320656u,2114890742u,
-          1330011390u,4034026466u,2433323681u,2369407485u,
-          4236272969u,2528739082u,3578057914u,3661701488u,
-          2859713681u,3990363354u,1333952796u,4122366106u,
-          914226189u,4173572083u,1212571535u,3191601154u,
-          2722264012u,1786117962u,3697951815u,1623344204u,
-          3777961768u,3367953340u,185304162u,2218198692u,
-          3591365528u,597946422u,3711324381u,4192251375u,
-          3548980568u,2359376543u,1318689265u,2723885638u,
-          302637856u,2882109788u,824841244u,2744654449u,
-          3931533014u,669729948u,711972471u,4010384128u,
-          1272251031u,1795981758u,1602634825u,3743883218u},
-    .rr = {820482522u,2494434288u,1082168230u,731376296u,
-           1306039452u,3139792975u,2575869288u,3874938710u,
-           3198185181u,153506080u,1236489694u,1061859740u,
-           1174461268u,115279508u,1782749185u,238124145u,
-           3587596076u,2259236093u,1112265915u,4048059865u,
-           3890381098u,999426242u,794481771u,3804065613u,
-           2786019148u,461403875u,3072256692u,4079652654u,
-           3056719901u,1871565394u,212974856u,3359008174u,
-           1397773937u,3796256698u,914342841u,1097174457u,
-           3322220191u,3170814748u,2439215020u,618719336u,
-           3629353460u,496817177u,317052742u,380264245u,
-           1976007217u,2697736152u,312540864u,4291855337u,
-           697006561u,4234182488u,3904590917u,2609582216u,
-           451424084u,1805773827u,776344974u,1064489733u,
-           2633377036u,1954826648u,3202815814u,2240368662u,
-           2618582484u,2211196815u,4107362845u,3640258615u},
-    .exponent = 65537,
-};
-
-// PKCS#1 v1.5 Signature Example 15.1
-
-char* message_1 =
-    "f4 5d 55 f3 55 51 e9 75 d6 a8 dc 7e a9 f4 88 59"
-    "39 40 cc 75 69 4a 27 8f 27 e5 78 a1 63 d8 39 b3"
-    "40 40 84 18 08 cf 9c 58 c9 b8 72 8b f5 f9 ce 8e"
-    "e8 11 ea 91 71 4f 47 ba b9 2d 0f 6d 5a 26 fc fe"
-    "ea 6c d9 3b 91 0c 0a 2c 96 3e 64 eb 18 23 f1 02"
-    "75 3d 41 f0 33 59 10 ad 3a 97 71 04 f1 aa f6 c3"
-    "74 27 16 a9 75 5d 11 b8 ee d6 90 47 7f 44 5c 5d"
-    "27 20 8b 2e 28 43 30 fa 3d 30 14 23 fa 7f 2d 08"
-    "6e 0a d0 b8 92 b9 db 54 4e 45 6d 3f 0d ab 85 d9"
-    "53 c1 2d 34 0a a8 73 ed a7 27 c8 a6 49 db 7f a6"
-    "37 40 e2 5e 9a f1 53 3b 30 7e 61 32 99 93 11 0e"
-    "95 19 4e 03 93 99 c3 82 4d 24 c5 1f 22 b2 6b de"
-    "10 24 cd 39 59 58 a2 df eb 48 16 a6 e8 ad ed b5"
-    "0b 1f 6b 56 d0 b3 06 0f f0 f1 c4 cb 0d 0e 00 1d"
-    "d5 9d 73 be 12";
-
-char* signature_1 =
-    "b7 5a 54 66 b6 5d 0f 30 0e f5 38 33 f2 17 5c 8a"
-    "34 7a 38 04 fc 63 45 1d c9 02 f0 b7 1f 90 83 45"
-    "9e d3 7a 51 79 a3 b7 23 a5 3f 10 51 64 2d 77 37"
-    "4c 4c 6c 8d bb 1c a2 05 25 f5 c9 f3 2d b7 76 95"
-    "35 56 da 31 29 0e 22 19 74 82 ce b6 99 06 c4 6a"
-    "75 8f b0 e7 40 9b a8 01 07 7d 2a 0a 20 ea e7 d1"
-    "d6 d3 92 ab 49 57 e8 6b 76 f0 65 2d 68 b8 39 88"
-    "a7 8f 26 e1 11 72 ea 60 9b f8 49 fb bd 78 ad 7e"
-    "dc e2 1d e6 62 a0 81 36 8c 04 06 07 ce e2 9d b0"
-    "62 72 27 f4 49 63 ad 17 1d 22 93 b6 33 a3 92 e3"
-    "31 dc a5 4f e3 08 27 52 f4 3f 63 c1 61 b4 47 a4"
-    "c6 5a 68 75 67 0d 5f 66 00 fc c8 60 a1 ca eb 0a"
-    "88 f8 fd ec 4e 56 43 98 a5 c4 6c 87 f6 8c e0 70"
-    "01 f6 21 3a be 0a b5 62 5f 87 d1 90 25 f0 8d 81"
-    "da c7 bd 45 86 bc 93 82 19 1f 6d 28 80 f6 22 7e"
-    "5d f3 ee d2 1e 77 92 d2 49 48 04 87 f3 65 52 61";
-
-// PKCS#1 v1.5 Signature Example 15.2
-
-char *message_2 =
-    "c1 4b 4c 60 75 b2 f9 aa d6 61 de f4 ec fd 3c b9 "
-    "33 c6 23 f4 e6 3b f5 34 10 d2 f0 16 d1 ab 98 e2 "
-    "72 9e cc f8 00 6c d8 e0 80 50 73 7d 95 fd bf 29 "
-    "6b 66 f5 b9 79 2a 90 29 36 c4 f7 ac 69 f5 14 53 "
-    "ce 43 69 45 2d c2 2d 96 f0 37 74 81 14 66 20 00 "
-    "dd 9c d3 a5 e1 79 f4 e0 f8 1f a6 a0 31 1c a1 ae "
-    "e6 51 9a 0f 63 ce c7 8d 27 bb 72 63 93 fb 7f 1f "
-    "88 cd e7 c9 7f 8a 66 cd 66 30 12 81 da c3 f3 a4 "
-    "33 24 8c 75 d6 c2 dc d7 08 b6 a9 7b 0a 3f 32 5e "
-    "0b 29 64 f8 a5 81 9e 47 9b ";
-
-char* signature_2 =
-    "af a7 34 34 62 be a1 22 cc 14 9f ca 70 ab da e7"
-    "94 46 67 7d b5 37 36 66 af 7d c3 13 01 5f 4d e7"
-    "86 e6 e3 94 94 6f ad 3c c0 e2 b0 2b ed ba 50 47"
-    "fe 9e 2d 7d 09 97 05 e4 a3 9f 28 68 32 79 cf 0a"
-    "c8 5c 15 30 41 22 42 c0 e9 18 95 3b e0 00 e9 39"
-    "cf 3b f1 82 52 5e 19 93 70 fa 79 07 eb a6 9d 5d"
-    "b4 63 10 17 c0 e3 6d f7 03 79 b5 db 8d 4c 69 5a"
-    "97 9a 8e 61 73 22 40 65 d7 dc 15 13 2e f2 8c d8"
-    "22 79 51 63 06 3b 54 c6 51 14 1b e8 6d 36 e3 67"
-    "35 bc 61 f3 1f ca 57 4e 53 09 f3 a3 bb df 91 ef"
-    "f1 2b 99 e9 cc 17 44 f1 ee 9a 1b d2 2c 5b ad 96"
-    "ad 48 19 29 25 1f 03 43 fd 36 bc f0 ac de 7f 11"
-    "e5 ad 60 97 77 21 20 27 96 fe 06 1f 9a da 1f c4"
-    "c8 e0 0d 60 22 a8 35 75 85 ff e9 fd d5 93 31 a2"
-    "8c 4a a3 12 15 88 fb 6c f6 83 96 d8 ac 05 46 59"
-    "95 00 c9 70 85 00 a5 97 2b d5 4f 72 cf 8d b0 c8";
-
-// PKCS#1 v1.5 Signature Example 15.3
-
-char* message_3 =
-    "d0 23 71 ad 7e e4 8b bf db 27 63 de 7a 84 3b 94 "
-    "08 ce 5e b5 ab f8 47 ca 3d 73 59 86 df 84 e9 06 "
-    "0b db cd d3 a5 5b a5 5d de 20 d4 76 1e 1a 21 d2 "
-    "25 c1 a1 86 f4 ac 4b 30 19 d3 ad f7 8f e6 33 46 "
-    "67 f5 6f 70 c9 01 a0 a2 70 0c 6f 0d 56 ad d7 19 "
-    "59 2d c8 8f 6d 23 06 c7 00 9f 6e 7a 63 5b 4c b3 "
-    "a5 02 df e6 8d dc 58 d0 3b e1 0a 11 70 00 4f e7 "
-    "4d d3 e4 6b 82 59 1f f7 54 14 f0 c4 a0 3e 60 5e "
-    "20 52 4f 24 16 f1 2e ca 58 9f 11 1b 75 d6 39 c6 "
-    "1b aa 80 ca fd 05 cf 35 00 24 4a 21 9e d9 ce d9 "
-    "f0 b1 02 97 18 2b 65 3b 52 6f 40 0f 29 53 ba 21 "
-    "4d 5b cd 47 88 41 32 87 2a e9 0d 4d 6b 1f 42 15 "
-    "39 f9 f3 46 62 a5 6d c0 e7 b4 b9 23 b6 23 1e 30 "
-    "d2 67 67 97 81 7f 7c 33 7b 5a c8 24 ba 93 14 3b "
-    "33 81 fa 3d ce 0e 6a eb d3 8e 67 73 51 87 b1 eb "
-    "d9 5c 02 ";
-
-char* signature_3 =
-    "3b ac 63 f8 6e 3b 70 27 12 03 10 6b 9c 79 aa bd"
-    "9f 47 7c 56 e4 ee 58 a4 fc e5 ba f2 ca b4 96 0f"
-    "88 39 1c 9c 23 69 8b e7 5c 99 ae df 9e 1a bf 17"
-    "05 be 1d ac 33 14 0a db 48 eb 31 f4 50 bb 9e fe"
-    "83 b7 b9 0d b7 f1 57 6d 33 f4 0c 1c ba 4b 8d 6b"
-    "1d 33 23 56 4b 0f 17 74 11 4f a7 c0 8e 6d 1e 20"
-    "dd 8f bb a9 b6 ac 7a d4 1e 26 b4 56 8f 4a 8a ac"
-    "bf d1 78 a8 f8 d2 c9 d5 f5 b8 81 12 93 5a 8b c9"
-    "ae 32 cd a4 0b 8d 20 37 55 10 73 50 96 53 68 18"
-    "ce 2b 2d b7 1a 97 72 c9 b0 dd a0 9a e1 01 52 fa"
-    "11 46 62 18 d0 91 b5 3d 92 54 30 61 b7 29 4a 55"
-    "be 82 ff 35 d5 c3 2f a2 33 f0 5a aa c7 58 50 30"
-    "7e cf 81 38 3c 11 16 74 39 7b 1a 1b 9d 3b f7 61"
-    "2c cb e5 ba cd 2b 38 f0 a9 83 97 b2 4c 83 65 8f"
-    "b6 c0 b4 14 0e f1 19 70 c4 63 0d 44 34 4e 76 ea"
-    "ed 74 dc be e8 11 db f6 57 59 41 f0 8a 65 23 b8";
-
-// PKCS#1 v1.5 Signature Example 15.4
-
-char* message_4 =
-    "29 03 55 84 ab 7e 02 26 a9 ec 4b 02 e8 dc f1 27 "
-    "2d c9 a4 1d 73 e2 82 00 07 b0 f6 e2 1f ec cd 5b "
-    "d9 db b9 ef 88 cd 67 58 76 9e e1 f9 56 da 7a d1 "
-    "84 41 de 6f ab 83 86 db c6 93 ";
-
-char* signature_4 =
-    "28 d8 e3 fc d5 dd db 21 ff bd 8d f1 63 0d 73 77"
-    "aa 26 51 e1 4c ad 1c 0e 43 cc c5 2f 90 7f 94 6d"
-    "66 de 72 54 e2 7a 6c 19 0e b0 22 ee 89 ec f6 22"
-    "4b 09 7b 71 06 8c d6 07 28 a1 ae d6 4b 80 e5 45"
-    "7b d3 10 6d d9 17 06 c9 37 c9 79 5f 2b 36 36 7f"
-    "f1 53 dc 25 19 a8 db 9b df 2c 80 74 30 c4 51 de"
-    "17 bb cd 0c e7 82 b3 e8 f1 02 4d 90 62 4d ea 7f"
-    "1e ed c7 42 0b 7e 7c aa 65 77 ce f4 31 41 a7 26"
-    "42 06 58 0e 44 a1 67 df 5e 41 ee a0 e6 9a 80 54"
-    "54 c4 0e ef c1 3f 48 e4 23 d7 a3 2d 02 ed 42 c0"
-    "ab 03 d0 a7 cf 70 c5 86 0a c9 2e 03 ee 00 5b 60"
-    "ff 35 03 42 4b 98 cc 89 45 68 c7 c5 6a 02 33 55"
-    "1c eb e5 88 cf 8b 01 67 b7 df 13 ad ca d8 28 67"
-    "68 10 49 9c 70 4d a7 ae 23 41 4d 69 e3 c0 d2 db"
-    "5d cb c2 61 3b c1 20 42 1f 9e 36 53 c5 a8 76 72"
-    "97 64 3c 7e 07 40 de 01 63 55 45 3d 6c 95 ae 72";
-
-// PKCS#1 v1.5 Signature Example 15.5
-
-char* message_5 =
-    "bd a3 a1 c7 90 59 ea e5 98 30 8d 3d f6 09 ";
-
-char* signature_5 =
-    "a1 56 17 6c b9 67 77 c7 fb 96 10 5d bd 91 3b c4"
-    "f7 40 54 f6 80 7c 60 08 a1 a9 56 ea 92 c1 f8 1c"
-    "b8 97 dc 4b 92 ef 9f 4e 40 66 8d c7 c5 56 90 1a"
-    "cb 6c f2 69 fe 61 5b 0f b7 2b 30 a5 13 38 69 23"
-    "14 b0 e5 87 8a 88 c2 c7 77 4b d1 69 39 b5 ab d8"
-    "2b 44 29 d6 7b d7 ac 8e 5e a7 fe 92 4e 20 a6 ec"
-    "66 22 91 f2 54 8d 73 4f 66 34 86 8b 03 9a a5 f9"
-    "d4 d9 06 b2 d0 cb 85 85 bf 42 85 47 af c9 1c 6e"
-    "20 52 dd cd 00 1c 3e f8 c8 ee fc 3b 6b 2a 82 b6"
-    "f9 c8 8c 56 f2 e2 c3 cb 0b e4 b8 0d a9 5e ba 37"
-    "1d 8b 5f 60 f9 25 38 74 3d db b5 da 29 72 c7 1f"
-    "e7 b9 f1 b7 90 26 8a 0e 77 0f c5 eb 4d 5d d8 52"
-    "47 d4 8a e2 ec 3f 26 25 5a 39 85 52 02 06 a1 f2"
-    "68 e4 83 e9 db b1 d5 ca b1 90 91 76 06 de 31 e7"
-    "c5 18 2d 8f 15 1b f4 1d fe cc ae d7 cd e6 90 b2"
-    "16 47 10 6b 49 0c 72 9d 54 a8 fe 28 02 a6 d1 26";
-
-// PKCS#1 v1.5 Signature Example 15.6
-
-char* message_6 =
-    "c1 87 91 5e 4e 87 da 81 c0 8e d4 35 6a 0c ce ac "
-    "1c 4f b5 c0 46 b4 52 81 b3 87 ec 28 f1 ab fd 56 "
-    "7e 54 6b 23 6b 37 d0 1a e7 1d 3b 28 34 36 5d 3d "
-    "f3 80 b7 50 61 b7 36 b0 13 0b 07 0b e5 8a e8 a4 "
-    "6d 12 16 63 61 b6 13 db c4 7d fa eb 4c a7 46 45 "
-    "6c 2e 88 83 85 52 5c ca 9d d1 c3 c7 a9 ad a7 6d "
-    "6c ";;
-
-char* signature_6 =
-    "9c ab 74 16 36 08 66 9f 75 55 a3 33 cf 19 6f e3"
-    "a0 e9 e5 eb 1a 32 d3 4b b5 c8 5f f6 89 aa ab 0e"
-    "3e 65 66 8e d3 b1 15 3f 94 eb 3d 8b e3 79 b8 ee"
-    "f0 07 c4 a0 2c 70 71 ce 30 d8 bb 34 1e 58 c6 20"
-    "f7 3d 37 b4 ec bf 48 be 29 4f 6c 9e 0e cb 5e 63"
-    "fe c4 1f 12 0e 55 53 df a0 eb eb bb 72 64 0a 95"
-    "37 ba dc b4 51 33 02 29 d9 f7 10 f6 2e 3e d8 ec"
-    "78 4e 50 ee 1d 92 62 b4 26 71 34 00 11 d7 d0 98"
-    "c6 f2 55 7b 21 31 fa 9b d0 25 46 36 59 7e 88 ec"
-    "b3 5a 24 0e f0 fd 85 95 71 24 df 80 80 fe e1 e1"
-    "49 af 93 99 89 e8 6b 26 c8 5a 58 81 fa e8 67 3d"
-    "9f d4 08 00 dd 13 4e b9 bd b6 41 0f 42 0b 0a a9"
-    "7b 20 ef cf 2e b0 c8 07 fa eb 83 a3 cc d9 b5 1d"
-    "45 53 e4 1d fc 0d f6 ca 80 a1 e8 1d c2 34 bb 83"
-    "89 dd 19 5a 38 b4 2d e4 ed c4 9d 34 64 78 b9 f1"
-    "1f 05 57 20 5f 5b 0b d7 ff e9 c8 50 f3 96 d7 c4";;
-
-// PKCS#1 v1.5 Signature Example 15.7
-
-char* message_7 =
-    "ab fa 2e cb 7d 29 bd 5b cb 99 31 ce 2b ad 2f 74 "
-    "38 3e 95 68 3c ee 11 02 2f 08 e8 e7 d0 b8 fa 05 "
-    "8b f9 eb 7e b5 f9 88 68 b5 bb 1f b5 c3 1c ed a3 "
-    "a6 4f 1a 12 cd f2 0f cd 0e 5a 24 6d 7a 17 73 d8 "
-    "db a0 e3 b2 77 54 5b ab e5 8f 2b 96 e3 f4 ed c1 "
-    "8e ab f5 cd 2a 56 0f ca 75 fe 96 e0 7d 85 9d ef "
-    "b2 56 4f 3a 34 f1 6f 11 e9 1b 3a 71 7b 41 af 53 "
-    "f6 60 53 23 00 1a a4 06 c6 ";
-
-char* signature_7 =
-    "c4 b4 37 bc f7 03 f3 52 e1 fa f7 4e b9 62 20 39"
-    "42 6b 56 72 ca f2 a7 b3 81 c6 c4 f0 19 1e 7e 4a"
-    "98 f0 ee bc d6 f4 17 84 c2 53 7f f0 f9 9e 74 98"
-    "2c 87 20 1b fb c6 5e ae 83 2d b7 1d 16 da ca db"
-    "09 77 e5 c5 04 67 9e 40 be 0f 9d b0 6f fd 84 8d"
-    "d2 e5 c3 8a 7e c0 21 e7 f6 8c 47 df d3 8c c3 54"
-    "49 3d 53 39 b4 59 5a 5b f3 1e 3f 8f 13 81 68 07"
-    "37 3d f6 ad 0d c7 e7 31 e5 1a d1 9e b4 75 4b 13"
-    "44 85 84 2f e7 09 d3 78 44 4d 8e 36 b1 72 4a 4f"
-    "da 21 ca fe e6 53 ab 80 74 7f 79 52 ee 80 4d ea"
-    "b1 03 9d 84 13 99 45 bb f4 be 82 00 87 53 f3 c5"
-    "4c 78 21 a1 d2 41 f4 21 79 c7 94 ef 70 42 bb f9"
-    "95 56 56 22 2e 45 c3 43 69 a3 84 69 7b 6a e7 42"
-    "e1 8f a5 ca 7a ba d2 7d 9f e7 10 52 e3 31 0d 0f"
-    "52 c8 d1 2e a3 3b f0 53 a3 00 f4 af c4 f0 98 df"
-    "4e 6d 88 67 79 d6 45 94 d3 69 15 8f db c1 f6 94";
-
-// PKCS#1 v1.5 Signature Example 15.8
-
-char* message_8 =
-    "df 40 44 a8 9a 83 e9 fc bf 12 62 54 0a e3 03 8b "
-    "bc 90 f2 b2 62 8b f2 a4 46 7a c6 77 22 d8 54 6b "
-    "3a 71 cb 0e a4 16 69 d5 b4 d6 18 59 c1 b4 e4 7c "
-    "ec c5 93 3f 75 7e c8 6d b0 64 4e 31 18 12 d0 0f "
-    "b8 02 f0 34 00 63 9c 0e 36 4d ae 5a eb c5 79 1b "
-    "c6 55 76 23 61 bc 43 c5 3d 3c 78 86 76 8f 79 68 "
-    "c1 c5 44 c6 f7 9f 7b e8 20 c7 e2 bd 2f 9d 73 e6 "
-    "2d ed 6d 2e 93 7e 6a 6d ae f9 0e e3 7a 1a 52 a5 "
-    "4f 00 e3 1a dd d6 48 94 cf 4c 02 e1 60 99 e2 9f "
-    "9e b7 f1 a7 bb 7f 84 c4 7a 2b 59 48 13 be 02 a1 "
-    "7b 7f c4 3b 34 c2 2c 91 92 52 64 12 6c 89 f8 6b "
-    "b4 d8 7f 3e f1 31 29 6c 53 a3 08 e0 33 1d ac 8b "
-    "af 3b 63 42 22 66 ec ef 2b 90 78 15 35 db da 41 "
-    "cb d0 cf 22 a8 cb fb 53 2e c6 8f c6 af b2 ac 06 ";
-
-char* signature_8 =
-    "14 14 b3 85 67 ae 6d 97 3e de 4a 06 84 2d cc 0e"
-    "05 59 b1 9e 65 a4 88 9b db ab d0 fd 02 80 68 29"
-    "13 ba cd 5d c2 f0 1b 30 bb 19 eb 81 0b 7d 9d ed"
-    "32 b2 84 f1 47 bb e7 71 c9 30 c6 05 2a a7 34 13"
-    "90 a8 49 f8 1d a9 cd 11 e5 ec cf 24 6d ba e9 5f"
-    "a9 58 28 e9 ae 0c a3 55 03 25 32 6d ee f9 f4 95"
-    "30 ba 44 1b ed 4a c2 9c 02 9c 9a 27 36 b1 a4 19"
-    "0b 85 08 4a d1 50 42 6b 46 d7 f8 5b d7 02 f4 8d"
-    "ac 5f 71 33 0b c4 23 a7 66 c6 5c c1 dc ab 20 d3"
-    "d3 bb a7 2b 63 b3 ef 82 44 d4 2f 15 7c b7 e3 a8"
-    "ba 5c 05 27 2c 64 cc 1a d2 1a 13 49 3c 39 11 f6"
-    "0b 4e 9f 4e cc 99 00 eb 05 6e e5 9d 6f e4 b8 ff"
-    "6e 80 48 cc c0 f3 8f 28 36 fd 3d fe 91 bf 4a 38"
-    "6e 1e cc 2c 32 83 9f 0c a4 d1 b2 7a 56 8f a9 40"
-    "dd 64 ad 16 bd 01 25 d0 34 8e 38 30 85 f0 88 94"
-    "86 1c a1 89 87 22 7d 37 b4 2b 58 4a 83 57 cb 04";
-
-// PKCS#1 v1.5 Signature Example 15.9
-
-char* message_9 =
-    "ea 94 1f f0 6f 86 c2 26 92 7f cf 0e 3b 11 b0 87 "
-    "26 76 17 0c 1b fc 33 bd a8 e2 65 c7 77 71 f9 d0 "
-    "85 01 64 a5 ee cb cc 5c e8 27 fb fa 07 c8 52 14 "
-    "79 6d 81 27 e8 ca a8 18 94 ea 61 ce b1 44 9e 72 "
-    "fe a0 a4 c9 43 b2 da 6d 9b 10 5f e0 53 b9 03 9a "
-    "9c c5 3d 42 0b 75 39 fa b2 23 9c 6b 51 d1 7e 69 "
-    "4c 95 7d 4b 0f 09 84 46 18 79 a0 75 9c 44 01 be "
-    "ec d4 c6 06 a0 af bd 7a 07 6f 50 a2 df c2 80 7f "
-    "24 f1 91 9b aa 77 46 d3 a6 4e 26 8e d3 f5 f8 e6 "
-    "da 83 a2 a5 c9 15 2f 83 7c b0 78 12 bd 5b a7 d3 "
-    "a0 79 85 de 88 11 3c 17 96 e9 b4 66 ec 29 9c 5a "
-    "c1 05 9e 27 f0 94 15 ";
-
-char* signature_9 =
-    "ce eb 84 cc b4 e9 09 92 65 65 07 21 ee a0 e8 ec"
-    "89 ca 25 bd 35 4d 4f 64 56 49 67 be 9d 4b 08 b3"
-    "f1 c0 18 53 9c 9d 37 1c f8 96 1f 22 91 fb e0 dc"
-    "2f 2f 95 fe a4 7b 63 9f 1e 12 f4 bc 38 1c ef 0c"
-    "2b 7a 7b 95 c3 ad f2 76 05 b7 f6 39 98 c3 cb ad"
-    "54 28 08 c3 82 2e 06 4d 4a d1 40 93 67 9e 6e 01"
-    "41 8a 6d 5c 05 96 84 cd 56 e3 4e d6 5a b6 05 b8"
-    "de 4f cf a6 40 47 4a 54 a8 25 1b bb 73 26 a4 2d"
-    "08 58 5c fc fc 95 67 69 b1 5b 6d 7f df 7d a8 4f"
-    "81 97 6e aa 41 d6 92 38 0f f1 0e ae cf e0 a5 79"
-    "68 29 09 b5 52 1f ad e8 54 d7 97 b8 a0 34 5b 9a"
-    "86 4e 05 88 f6 ca dd bf 65 f1 77 99 8e 18 0d 1f"
-    "10 24 43 e6 dc a5 3a 94 82 3c aa 9c 3b 35 f3 22"
-    "58 3c 70 3a f6 74 76 15 9e c7 ec 93 d1 76 9b 30"
-    "0a f0 e7 15 7d c2 98 c6 cd 2d ee 22 62 f8 cd dc"
-    "10 f1 1e 01 74 14 71 bb fd 65 18 a1 75 73 45 75";
-
-// PKCS#1 v1.5 Signature Example 15.10
-
-char* message_10 =
-    "d8 b8 16 45 c1 3c d7 ec f5 d0 0e d2 c9 1b 9a cd "
-    "46 c1 55 68 e5 30 3c 4a 97 75 ed e7 6b 48 40 3d "
-    "6b e5 6c 05 b6 b1 cf 77 c6 e7 5d e0 96 c5 cb 35 "
-    "51 cb 6f a9 64 f3 c8 79 cf 58 9d 28 e1 da 2f 9d "
-    "ec ";
-
-char* signature_10 =
-    "27 45 07 4c a9 71 75 d9 92 e2 b4 47 91 c3 23 c5"
-    "71 67 16 5c dd 8d a5 79 cd ef 46 86 b9 bb 40 4b"
-    "d3 6a 56 50 4e b1 fd 77 0f 60 bf a1 88 a7 b2 4b"
-    "0c 91 e8 81 c2 4e 35 b0 4d c4 dd 4c e3 85 66 bc"
-    "c9 ce 54 f4 9a 17 5f c9 d0 b2 25 22 d9 57 90 47"
-    "f9 ed 42 ec a8 3f 76 4a 10 16 39 97 94 7e 7d 2b"
-    "52 ff 08 98 0e 7e 7c 22 57 93 7b 23 f3 d2 79 d4"
-    "cd 17 d6 f4 95 54 63 73 d9 83 d5 36 ef d7 d1 b6"
-    "71 81 ca 2c b5 0a c6 16 c5 c7 ab fb b9 26 0b 91"
-    "b1 a3 8e 47 24 20 01 ff 45 2f 8d e1 0c a6 ea ea"
-    "dc af 9e dc 28 95 6f 28 a7 11 29 1f c9 a8 08 78"
-    "b8 ba 4c fe 25 b8 28 1c b8 0b c9 cd 6d 2b d1 82"
-    "52 46 ee be 25 2d 99 57 ef 93 70 73 52 08 4e 6d"
-    "36 d4 23 55 1b f2 66 a8 53 40 fb 4a 6a f3 70 88"
-    "0a ab 07 15 3d 01 f4 8d 08 6d f0 bf be c0 5e 7b"
-    "44 3b 97 e7 17 18 97 0e 2f 4b f6 20 23 e9 5b 67";
-
-// PKCS#1 v1.5 Signature Example 15.11
-
-char* message_11 =
-    "e5 73 9b 6c 14 c9 2d 51 0d 95 b8 26 93 33 37 ff "
-    "0d 24 ef 72 1a c4 ef 64 c2 ba d2 64 be 8b 44 ef "
-    "a1 51 6e 08 a2 7e b6 b6 11 d3 30 1d f0 06 2d ae "
-    "fc 73 a8 c0 d9 2e 2c 52 1f ac bc 7b 26 47 38 76 "
-    "7e a6 fc 97 d5 88 a0 ba f6 ce 50 ad f7 9e 60 0b "
-    "d2 9e 34 5f cb 1d ba 71 ac 5c 02 89 02 3f e4 a8 "
-    "2b 46 a5 40 77 19 19 7d 2e 95 8e 35 31 fd 54 ae "
-    "f9 03 aa bb 43 55 f8 83 18 99 4e d3 c3 dd 62 f4 "
-    "20 a7 ";
-
-char* signature_11 =
-    "be 40 a5 fb 94 f1 13 e1 b3 ef f6 b6 a3 39 86 f2"
-    "02 e3 63 f0 74 83 b7 92 e6 8d fa 55 54 df 04 66"
-    "cc 32 15 09 50 78 3b 4d 96 8b 63 9a 04 fd 2f b9"
-    "7f 6e b9 67 02 1f 5a dc cb 9f ca 95 ac c8 f2 cd"
-    "88 5a 38 0b 0a 4e 82 bc 76 07 64 db ab 88 c1 e6"
-    "c0 25 5c aa 94 f2 32 19 9d 6f 59 7c c9 14 5b 00"
-    "e3 d4 ba 34 6b 55 9a 88 33 ad 15 16 ad 51 63 f0"
-    "16 af 6a 59 83 1c 82 ea 13 c8 22 4d 84 d0 76 5a"
-    "9d 12 38 4d a4 60 a8 53 1b 4c 40 7e 04 f4 f3 50"
-    "70 9e b9 f0 8f 5b 22 0f fb 45 ab f6 b7 5d 15 79"
-    "fd 3f 1e b5 5f c7 5b 00 af 8b a3 b0 87 82 7f e9"
-    "ae 9f b4 f6 c5 fa 63 03 1f e5 82 85 2f e2 83 4f"
-    "9c 89 bf f5 3e 25 52 21 6b c7 c1 d4 a3 d5 dc 2b"
-    "a6 95 5c d9 b1 7d 13 63 e7 fe e8 ed 76 29 75 3f"
-    "f3 12 5e dd 48 52 1a e3 b9 b0 32 17 f4 49 6d 0d"
-    "8e de 57 ac bc 5b d4 de ae 74 a5 6f 86 67 1d e2";
-
-// PKCS#1 v1.5 Signature Example 15.12
-
-char* message_12 =
-    "7a f4 28 35 91 7a 88 d6 b3 c6 71 6b a2 f5 b0 d5 "
-    "b2 0b d4 e2 e6 e5 74 e0 6a f1 ee f7 c8 11 31 be "
-    "22 bf 81 28 b9 cb c6 ec 00 27 5b a8 02 94 a5 d1 "
-    "17 2d 08 24 a7 9e 8f dd 83 01 83 e4 c0 0b 96 78 "
-    "28 67 b1 22 7f ea 24 9a ad 32 ff c5 fe 00 7b c5 "
-    "1f 21 79 2f 72 8d ed a8 b5 70 8a a9 9c ab ab 20 "
-    "a4 aa 78 3e d8 6f 0f 27 b5 d5 63 f4 2e 07 15 8c "
-    "ea 72 d0 97 aa 68 87 ec 41 1d d0 12 91 2a 5e 03 "
-    "2b bf a6 78 50 71 44 bc c9 5f 39 b5 8b e7 bf d1 "
-    "75 9a db 9a 91 fa 1d 6d 82 26 a8 34 3a 8b 84 9d "
-    "ae 76 f7 b9 82 24 d5 9e 28 f7 81 f1 3e ce 60 5f "
-    "84 f6 c9 0b ae 5f 8c f3 78 81 6f 40 20 a7 dd a1 "
-    "be d9 0c 92 a2 36 34 d2 03 fa c3 fc d8 6d 68 d3 "
-    "18 2a 7d 9c ca be 7b 07 95 f5 c6 55 e9 ac c4 e3 "
-    "ec 18 51 40 d1 0c ef 05 34 64 ab 17 5c 83 bd 83 "
-    "93 5e 3d ab af 34 62 ee be 63 d1 5f 57 3d 26 9a ";
-
-char* signature_12 =
-    "4e 78 c5 90 2b 80 79 14 d1 2f a5 37 ae 68 71 c8"
-    "6d b8 02 1e 55 d1 ad b8 eb 0c cf 1b 8f 36 ab 7d"
-    "ad 1f 68 2e 94 7a 62 70 72 f0 3e 62 73 71 78 1d"
-    "33 22 1d 17 4a be 46 0d bd 88 56 0c 22 f6 90 11"
-    "6e 2f bb e6 e9 64 36 3a 3e 52 83 bb 5d 94 6e f1"
-    "c0 04 7e ba 03 8c 75 6c 40 be 79 23 05 58 09 b0"
-    "e9 f3 4a 03 a5 88 15 eb dd e7 67 93 1f 01 8f 6f"
-    "18 78 f2 ef 4f 47 dd 37 40 51 dd 48 68 5d ed 6e"
-    "fb 3e a8 02 1f 44 be 1d 7d 14 93 98 f9 8e a9 c0"
-    "8d 62 88 8e bb 56 19 2d 17 74 7b 6b 8e 17 09 54"
-    "31 f1 25 a8 a8 e9 96 2a a3 1c 28 52 64 e0 8f b2"
-    "1a ac 33 6c e6 c3 8a a3 75 e4 2b c9 2a b0 ab 91"
-    "03 84 31 e1 f9 2c 39 d2 af 5d ed 7e 43 bc 15 1e"
-    "6e be a4 c3 e2 58 3a f3 43 7e 82 c4 3c 5e 3b 5b"
-    "07 cf 03 59 68 3d 22 98 e3 59 48 ed 80 6c 06 3c"
-    "60 6e a1 78 15 0b 1e fc 15 85 69 34 c7 25 5c fe";
-
-// PKCS#1 v1.5 Signature Example 15.13
-
-char* message_13 =
-    "eb ae f3 f9 f2 3b df e5 fa 6b 8a f4 c2 08 c1 89 "
-    "f2 25 1b f3 2f 5f 13 7b 9d e4 40 63 78 68 6b 3f "
-    "07 21 f6 2d 24 cb 86 88 d6 fc 41 a2 7c ba e2 1d "
-    "30 e4 29 fe ac c7 11 19 41 c2 77 ";
-
-char* signature_13 =
-    "c4 8d be f5 07 11 4f 03 c9 5f af be b4 df 1b fa"
-    "88 e0 18 4a 33 cc 4f 8a 9a 10 35 ff 7f 82 2a 5e"
-    "38 cd a1 87 23 91 5f f0 78 24 44 29 e0 f6 08 1c"
-    "14 fd 83 33 1f a6 5c 6b a7 bb 9a 12 db f6 62 23"
-    "74 cd 0c a5 7d e3 77 4e 2b d7 ae 82 36 77 d0 61"
-    "d5 3a e9 c4 04 0d 2d a7 ef 70 14 f3 bb dc 95 a3"
-    "61 a4 38 55 c8 ce 9b 97 ec ab ce 17 4d 92 62 85"
-    "14 2b 53 4a 30 87 f9 f4 ef 74 51 1e c7 42 b0 d5"
-    "68 56 03 fa f4 03 b5 07 2b 98 5d f4 6a df 2d 25"
-    "29 a0 2d 40 71 1e 21 90 91 70 52 37 1b 79 b7 49"
-    "b8 3a bf 0a e2 94 86 c3 f2 f6 24 77 b2 bd 36 2b"
-    "03 9c 01 3c 0c 50 76 ef 52 0d bb 40 5f 42 ce e9"
-    "54 25 c3 73 a9 75 e1 cd d0 32 c4 96 22 c8 50 79"
-    "b0 9e 88 da b2 b1 39 69 ef 7a 72 39 73 78 10 40"
-    "45 9f 57 d5 01 36 38 48 3d e2 d9 1c b3 c4 90 da"
-    "81 c4 6d e6 cd 76 ea 8a 0c 8f 6f e3 31 71 2d 24";
-
-// PKCS#1 v1.5 Signature Example 15.14
-
-char* message_14 =
-    "c5 a2 71 12 78 76 1d fc dd 4f 0c 99 e6 f5 61 9d "
-    "6c 48 b5 d4 c1 a8 09 82 fa a6 b4 cf 1c f7 a6 0f "
-    "f3 27 ab ef 93 c8 01 42 9e fd e0 86 40 85 81 46 "
-    "10 56 ac c3 3f 3d 04 f5 ad a2 12 16 ca cd 5f d1 "
-    "f9 ed 83 20 3e 0e 2f e6 13 8e 3e ae 84 24 e5 91 "
-    "5a 08 3f 3f 7a b7 60 52 c8 be 55 ae 88 2d 6e c1 "
-    "48 2b 1e 45 c5 da e9 f4 10 15 40 53 27 02 2e c3 "
-    "2f 0e a2 42 97 63 b2 55 04 3b 19 58 ee 3c f6 d6 "
-    "39 83 59 6e b3 85 84 4f 85 28 cc 9a 98 65 83 5d "
-    "c5 11 3c 02 b8 0d 0f ca 68 aa 25 e7 2b ca ae b3 "
-    "cf 9d 79 d8 4f 98 4f d4 17 ";
-
-char* signature_14 =
-    "6b d5 25 7a a0 66 11 fb 46 60 08 7c b4 bc 4a 9e"
-    "44 91 59 d3 16 52 bd 98 08 44 da f3 b1 c7 b3 53"
-    "f8 e5 61 42 f7 ea 98 57 43 3b 18 57 3b 4d ee de"
-    "81 8a 93 b0 29 02 97 78 3f 1a 2f 23 cb c7 27 97"
-    "a6 72 53 7f 01 f6 24 84 cd 41 62 c3 21 4b 9a c6"
-    "28 22 4c 5d e0 1f 32 bb 9b 76 b2 73 54 f2 b1 51"
-    "d0 e8 c4 21 3e 46 15 ad 0b c7 1f 51 5e 30 0d 6a"
-    "64 c6 74 34 11 ff fd e8 e5 ff 19 0e 54 92 30 43"
-    "12 6e cf c4 c4 53 90 22 66 8f b6 75 f2 5c 07 e2"
-    "00 99 ee 31 5b 98 d6 af ec 4b 1a 9a 93 dc 33 49"
-    "6a 15 bd 6f de 16 63 a7 d4 9b 9f 1e 63 9d 38 66"
-    "4b 37 a0 10 b1 f3 5e 65 86 82 d9 cd 63 e5 7d e0"
-    "f1 5e 8b dd 09 65 58 f0 7e c0 ca a2 18 a8 c0 6f"
-    "47 88 45 39 40 28 7c 9d 34 b6 d4 0a 3f 09 bf 77"
-    "99 fe 98 ae 4e b4 9f 3f f4 1c 50 40 a5 0c ef c9"
-    "bd f2 39 4b 74 9c f1 64 48 0d f1 ab 68 80 27 3b";
-
-// PKCS#1 v1.5 Signature Example 15.15
-
-char* message_15 =
-    "9b f8 aa 25 3b 87 2e a7 7a 7e 23 47 6b e2 6b 23 "
-    "29 57 8c f6 ac 9e a2 80 5b 35 7f 6f c3 ad 13 0d "
-    "ba eb 3d 86 9a 13 cc e7 a8 08 bb bb c9 69 85 7e "
-    "03 94 5c 7b b6 1d f1 b5 c2 58 9b 8e 04 6c 2a 5d "
-    "7e 40 57 b1 a7 4f 24 c7 11 21 63 64 28 85 29 ec "
-    "95 70 f2 51 97 21 3b e1 f5 c2 e5 96 f8 bf 8b 2c "
-    "f3 cb 38 aa 56 ff e5 e3 1d f7 39 58 20 e9 4e cf "
-    "3b 11 89 a9 65 dc f9 a9 cb 42 98 d3 c8 8b 29 23 "
-    "c1 9f c6 bc 34 aa ce ca d4 e0 93 1a 7c 4e 5d 73 "
-    "dc 86 df a7 98 a8 47 6d 82 46 3e ef aa 90 a8 a9 "
-    "19 2a b0 8b 23 08 8d d5 8e 12 80 f7 d7 2e 45 48 "
-    "39 6b aa c1 12 25 2d d5 c5 34 6a db 20 04 a2 f7 "
-    "10 1c cc 89 9c c7 fa fa e8 bb e2 95 73 88 96 a5 "
-    "b2 01 22 85 01 4e f6 ";
-
-char* signature_15 =
-    "27 f7 f4 da 9b d6 10 10 6e f5 7d 32 38 3a 44 8a"
-    "8a 62 45 c8 3d c1 30 9c 6d 77 0d 35 7b a8 9e 73"
-    "f2 ad 08 32 06 2e b0 fe 0a c9 15 57 5b cd 6b 8b"
-    "ca db 4e 2b a6 fa 9d a7 3a 59 17 51 52 b2 d4 fe"
-    "72 b0 70 c9 b7 37 9e 50 00 0e 55 e6 c2 69 f6 65"
-    "8c 93 79 72 79 7d 3a dd 69 f1 30 e3 4b 85 bd ec"
-    "9f 3a 9b 39 22 02 d6 f3 e4 30 d0 9c ac a8 22 77"
-    "59 ab 82 5f 70 12 d2 ff 4b 5b 62 c8 50 4d ba d8"
-    "55 c0 5e dd 5c ab 5a 4c cc dc 67 f0 1d d6 51 7c"
-    "7d 41 c4 3e 2a 49 57 af f1 9d b6 f1 8b 17 85 9a"
-    "f0 bc 84 ab 67 14 6e c1 a4 a6 0a 17 d7 e0 5f 8b"
-    "4f 9c ed 6a d1 09 08 d8 d7 8f 7f c8 8b 76 ad c8"
-    "29 0f 87 da f2 a7 be 10 ae 40 85 21 39 5d 54 ed"
-    "25 56 fb 76 61 85 4a 73 0c e3 d8 2c 71 a8 d4 93"
-    "ec 49 a3 78 ac 8a 3c 74 43 9f 7c c5 55 ba 13 f8"
-    "59 07 08 90 ee 18 ff 65 8f a4 d7 41 96 9d 70 a5";
-
-// PKCS#1 v1.5 Signature Example 15.16
-
-char* message_16 =
-    "32 47 48 30 e2 20 37 54 c8 bf 06 81 dc 4f 84 2a "
-    "fe 36 09 30 37 86 16 c1 08 e8 33 65 6e 56 40 c8 "
-    "68 56 88 5b b0 5d 1e b9 43 8e fe de 67 92 63 de "
-    "07 cb 39 55 3f 6a 25 e0 06 b0 a5 23 11 a0 63 ca "
-    "08 82 66 d2 56 4f f6 49 0c 46 b5 60 98 18 54 8f "
-    "88 76 4d ad 34 a2 5e 3a 85 d5 75 02 3f 0b 9e 66 "
-    "50 48 a0 3c 35 05 79 a9 d3 24 46 c7 bb 96 cc 92 "
-    "e0 65 ab 94 d3 c8 95 2e 8d f6 8e f0 d9 fa 45 6b "
-    "3a 06 bb 80 e3 bb c4 b2 8e 6a 94 b6 d0 ff 76 96 "
-    "a6 4e fe 05 e7 35 fe a0 25 d7 bd bc 41 39 f3 a3 "
-    "b5 46 07 5c ba 7e fa 94 73 74 d3 f0 ac 80 a6 8d "
-    "76 5f 5d f6 21 0b ca 06 9a 2d 88 64 7a f7 ea 04 "
-    "2d ac 69 0c b5 73 78 ec 07 77 61 4f b8 b6 5f f4 "
-    "53 ca 6b 7d ce 60 98 45 1a 2f 8c 0d a9 bf ec f1 "
-    "fd f3 91 bb aa 4e 2a 91 ca 18 a1 12 1a 75 23 a2 "
-    "ab d4 25 14 f4 89 e8 ";
-
-char* signature_16 =
-    "69 17 43 72 57 c2 2c cb 54 03 29 0c 3d ee 82 d9"
-    "cf 75 50 b3 1b d3 1c 51 bd 57 bf d3 5d 45 2a b4"
-    "db 7c 4b e6 b2 e2 5a c9 a5 9a 1d 2a 7f eb 62 7f"
-    "0a fd 49 76 b3 00 3c c9 cf fd 88 96 50 5e c3 82"
-    "f2 65 10 4d 4c f8 c9 32 fa 9f e8 6e 00 87 07 95"
-    "99 12 38 9d a4 b2 d6 b3 69 b3 6a 5e 72 e2 9d 24"
-    "c9 a9 8c 9d 31 a3 ab 44 e6 43 e6 94 12 66 a4 7a"
-    "45 e3 44 6c e8 77 6a be 24 1a 8f 5f c6 42 3b 24"
-    "b1 ff 25 0d c2 c3 a8 17 23 53 56 10 77 e8 50 a7"
-    "69 b2 5f 03 25 da c8 89 65 a3 b9 b4 72 c4 94 e9"
-    "5f 71 9b 4e ac 33 2c aa 7a 65 c7 df e4 6d 9a a7"
-    "e6 e0 0f 52 5f 30 3d d6 3a b7 91 92 18 90 18 68"
-    "f9 33 7f 8c d2 6a af e6 f3 3b 7f b2 c9 88 10 af"
-    "19 f7 fc b2 82 ba 15 77 91 2c 1d 36 89 75 fd 5d"
-    "44 0b 86 e1 0c 19 97 15 fa 0b 6f 42 50 b5 33 73"
-    "2d 0b ef e1 54 51 50 fc 47 b8 76 de 09 b0 0a 94";
-
-// PKCS#1 v1.5 Signature Example 15.17
-
-char* message_17 =
-    "00 8e 59 50 5e af b5 50 aa e5 e8 45 58 4c eb b0 "
-    "0b 6d e1 73 3e 9f 95 d4 2c 88 2a 5b be b5 ce 1c "
-    "57 e1 19 e7 c0 d4 da ca 9f 1f f7 87 02 17 f7 cf "
-    "d8 a6 b3 73 97 7c ac 9c ab 8e 71 e4 20 ";
-
-char* signature_17 =
-    "92 25 03 b6 73 ee 5f 3e 69 1e 1c a8 5e 9f f4 17"
-    "3c f7 2b 05 ac 2c 13 1d a5 60 35 93 e3 bc 25 9c"
-    "94 c1 f7 d3 a0 6a 5b 98 91 bf 11 3f a3 9e 59 ff"
-    "7c 1e d6 46 5e 90 80 49 cb 89 e4 e1 25 cd 37 d2"
-    "ff d9 22 7a 41 b4 a0 a1 9c 0a 44 fb bf 3d e5 5b"
-    "ab 80 20 87 a3 bb 8d 4f f6 68 ee 6b bb 8a d8 9e"
-    "68 57 a7 9a 9c 72 78 19 90 df cf 92 cd 51 94 04"
-    "c9 50 f1 3d 11 43 c3 18 4f 1d 25 0c 90 e1 7a c6"
-    "ce 36 16 3b 98 95 62 7a d6 ff ec 14 22 44 1f 55"
-    "e4 49 9d ba 9b e8 95 46 ae 8b c6 3c ca 01 dd 08"
-    "46 3a e7 f1 fc e3 d8 93 99 69 38 77 8c 18 12 e6"
-    "74 ad 9c 30 9c 5a cc a3 fd e4 4e 7d d8 69 59 93"
-    "e9 c1 fa 87 ac da 99 ec e5 c8 49 9e 46 89 57 ad"
-    "66 35 9b f1 2a 51 ad be 78 d3 a2 13 b4 49 bf 0b"
-    "5f 8d 4d 49 6a cf 03 d3 03 3b 7c cd 19 6b c2 2f"
-    "68 fb 7b ef 4f 69 7c 5e a2 b3 50 62 f4 8a 36 dd";
-
-// PKCS#1 v1.5 Signature Example 15.18
-
-char* message_18 =
-    "6a bc 54 cf 8d 1d ff 1f 53 b1 7d 81 60 36 88 78 "
-    "a8 78 8c c6 d2 2f a5 c2 25 8c 88 e6 60 b0 9a 89 "
-    "33 f9 f2 c0 50 4d da dc 21 f6 e7 5e 0b 83 3b eb "
-    "55 52 29 de e6 56 b9 04 7b 92 f6 2e 76 b8 ff cc "
-    "60 da b0 6b 80 ";
-
-char* signature_18 =
-    "0b 6d af 42 f7 a8 62 14 7e 41 74 93 c2 c4 01 ef"
-    "ae 32 63 6a b4 cb d4 41 92 bb f5 f1 95 b5 0a e0"
-    "96 a4 75 a1 61 4f 0a 9f a8 f7 a0 26 cb 46 c6 50"
-    "6e 51 8e 33 d8 3e 56 47 7a 87 5a ca 8c 7e 71 4c"
-    "e1 bd bd 61 ef 5d 53 52 39 b3 3f 2b fd d6 17 71"
-    "ba b6 27 76 d7 81 71 a1 42 3c ea 87 31 f8 2e 60"
-    "76 6d 64 54 26 56 20 b1 5f 5c 5a 58 4f 55 f9 5b"
-    "80 2f e7 8c 57 4e d5 da cf c8 31 f3 cf 2b 05 02"
-    "c0 b2 98 f2 5c cf 11 f9 73 b3 1f 85 e4 74 42 19"
-    "85 f3 cf f7 02 df 39 46 ef 0a 66 05 68 21 11 b2"
-    "f5 5b 1f 8a b0 d2 ea 3a 68 3c 69 98 5e ad 93 ed"
-    "44 9e a4 8f 03 58 dd f7 08 02 cb 41 de 2f d8 3f"
-    "3c 80 80 82 d8 49 36 94 8e 0c 84 a1 31 b4 92 78"
-    "27 46 05 27 bb 5c d2 4b fa b7 b4 8e 07 1b 24 17"
-    "19 30 f9 97 63 27 2f 97 97 bc b7 6f 1d 24 81 57"
-    "55 58 fc f2 60 b1 f0 e5 54 eb b3 df 3c fc b9 58";
-
-// PKCS#1 v1.5 Signature Example 15.19
-
-char* message_19 =
-    "af 2d 78 15 2c f1 0e fe 01 d2 74 f2 17 b1 77 f6 "
-    "b0 1b 5e 74 9f 15 67 71 5d a3 24 85 9c d3 dd 88 "
-    "db 84 8e c7 9f 48 db ba 7b 6f 1d 33 11 1e f3 1b "
-    "64 89 9e 73 91 c2 bf fd 69 f4 90 25 cf 20 1f c5 "
-    "85 db d1 54 2c 1c 77 8a 2c e7 a7 ee 10 8a 30 9f "
-    "ec a2 6d 13 3a 5f fe dc 4e 86 9d cd 76 56 59 6a "
-    "c8 42 7e a3 ef 6e 3f d7 8f e9 9d 8d dc 71 d8 39 "
-    "f6 78 6e 0d a6 e7 86 bd 62 b3 a4 f1 9b 89 1a 56 "
-    "15 7a 55 4e c2 a2 b3 9e 25 a1 d7 c7 d3 73 21 c7 "
-    "a1 d9 46 cf 4f be 75 8d 92 76 f0 85 63 44 9d 67 "
-    "41 4a 2c 03 0f 42 51 cf e2 21 3d 04 a5 41 06 37 "
-    "87 ";
-
-char* signature_19 =
-    "20 9c 61 15 78 57 38 7b 71 e2 4b f3 dd 56 41 45"
-    "50 50 3b ec 18 0f f5 3b dd 9b ac 06 2a 2d 49 95"
-    "09 bf 99 12 81 b7 95 27 df 91 36 61 5b 7a 6d 9d"
-    "b3 a1 03 b5 35 e0 20 2a 2c ac a1 97 a7 b7 4e 53"
-    "56 f3 dd 59 5b 49 ac fd 9d 30 04 9a 98 ca 88 f6"
-    "25 bc a1 d5 f2 2a 39 2d 8a 74 9e fb 6e ed 9b 78"
-    "21 d3 11 0a c0 d2 44 19 9e cb 4a a3 d7 35 a8 3a"
-    "2e 88 93 c6 bf 85 81 38 3c ca ee 83 46 35 b7 fa"
-    "1f af fa 45 b1 3d 15 c1 da 33 af 71 e8 93 03 d6"
-    "80 90 ff 62 ee 61 5f df 5a 84 d1 20 71 1d a5 3c"
-    "28 89 19 8a b3 83 17 a9 73 4a b2 7d 67 92 4c ea"
-    "74 15 6f f9 9b ef 98 76 bb 5c 33 9e 93 74 52 83"
-    "e1 b3 4e 07 22 26 b8 80 45 e0 17 e9 f0 5b 2a 8c"
-    "41 67 40 25 8e 22 3b 26 90 02 74 91 73 22 73 f3"
-    "22 9d 9e f2 b1 b3 80 7e 32 10 18 92 0a d3 e5 3d"
-    "ae 47 e6 d9 39 5c 18 4b 93 a3 74 c6 71 fa a2 ce";
-
-// PKCS#1 v1.5 Signature Example 15.20
-
-char* message_20 =
-    "40 ee 99 24 58 d6 f6 14 86 d2 56 76 a9 6d d2 cb "
-    "93 a3 7f 04 b1 78 48 2f 2b 18 6c f8 82 15 27 0d "
-    "ba 29 d7 86 d7 74 b0 c5 e7 8c 7f 6e 56 a9 56 e7 "
-    "f7 39 50 a2 b0 c0 c1 0a 08 db cd 67 e5 b2 10 bb "
-    "21 c5 8e 27 67 d4 4f 7d d4 01 4e 39 66 14 3b f7 "
-    "e3 d6 6f f0 c0 9b e4 c5 5f 93 b3 99 94 b8 51 8d "
-    "9c 1d 76 d5 b4 73 74 de a0 8f 15 7d 57 d7 06 34 "
-    "97 8f 38 56 e0 e5 b4 81 af bb db 5a 3a c4 8d 48 "
-    "4b e9 2c 93 de 22 91 78 35 4c 2d e5 26 e9 c6 5a "
-    "31 ed e1 ef 68 cb 63 98 d7 91 16 84 fe c0 ba bc "
-    "3a 78 1a 66 66 07 83 50 69 74 d0 e1 48 25 10 1c "
-    "3b fa ea ";
-
-char* signature_20 =
-    "92 75 02 b8 24 af c4 25 13 ca 65 70 de 33 8b 8a"
-    "64 c3 a8 5e b8 28 d3 19 36 24 f2 7e 8b 10 29 c5"
-    "5c 11 9c 97 33 b1 8f 58 49 b3 50 09 18 bc c0 05"
-    "51 d9 a8 fd f5 3a 97 74 9f a8 dc 48 0d 6f e9 74"
-    "2a 58 71 f9 73 92 65 28 97 2a 1a f4 9e 39 25 b0"
-    "ad f1 4a 84 27 19 b4 a5 a2 d8 9f a9 c0 b6 60 5d"
-    "21 2b ed 1e 67 23 b9 34 06 ad 30 e8 68 29 a5 c7"
-    "19 b8 90 b3 89 30 6d c5 50 64 86 ee 2f 36 a8 df"
-    "e0 a9 6a f6 78 c9 cb d6 af f3 97 ca 20 0e 3e dc"
-    "1e 36 bd 2f 08 b3 1d 54 0c 0c b2 82 a9 55 9e 4a"
-    "dd 4f c9 e6 49 2e ed 0c cb d3 a6 98 2e 5f aa 2d"
-    "dd 17 be 47 41 7c 80 b4 e5 45 2d 31 f7 24 01 a0"
-    "42 32 51 09 54 4d 95 4c 01 93 90 79 d4 09 a5 c3"
-    "78 d7 51 2d fc 2d 2a 71 ef cc 34 32 a7 65 d1 c6"
-    "a5 2c fc e8 99 cd 79 b1 5b 4f c3 72 36 41 ef 6b"
-    "d0 0a cc 10 40 7e 5d f5 8d d1 c3 c5 c5 59 a5 06";
-
-
-unsigned char* parsehex(char* str, int* len) {
-    // result can't be longer than input
-    unsigned char* result = malloc(strlen(str));
-
-    unsigned char* p = result;
-    *len = 0;
-
-    while (*str) {
-        int b;
-
-        while (isspace(*str)) str++;
-
-        switch (*str) {
-            case '0': case '1': case '2': case '3': case '4':
-            case '5': case '6': case '7': case '8': case '9':
-                b = (*str - '0') << 4; break;
-            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
-                b = (*str - 'a' + 10) << 4; break;
-            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
-                b = (*str - 'A' + 10) << 4; break;
-            case '\0':
-                return result;
-            default:
-                return NULL;
-        }
-        str++;
-
-        while (isspace(*str)) str++;
-
-        switch (*str) {
-            case '0': case '1': case '2': case '3': case '4':
-            case '5': case '6': case '7': case '8': case '9':
-                b |= *str - '0'; break;
-            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
-                b |= *str - 'a' + 10; break;
-            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
-                b |= *str - 'A' + 10; break;
-            default:
-                return NULL;
-        }
-        str++;
-
-        *p++ = b;
-        ++*len;
-    }
-
-    return result;
-}
-
-
-int main(int arg __unused, char** argv __unused) {
-
-    unsigned char hash[SHA_DIGEST_SIZE];
-
-    unsigned char* message;
-    int mlen;
-    unsigned char* signature;
-    int slen;
-
-#define TEST_MESSAGE(n) do {\
-    message = parsehex(message_##n, &mlen); \
-    SHA_hash(message, mlen, hash); \
-    signature = parsehex(signature_##n, &slen); \
-    int result = RSA_verify(&key_15, signature, slen, hash, sizeof(hash)); \
-    printf("message %d: %s\n", n, result ? "verified" : "not verified"); \
-    success = success && result; \
-    } while(0)
-
-    int success = 1;
-
-    TEST_MESSAGE(1);
-    TEST_MESSAGE(2);
-    TEST_MESSAGE(3);
-    TEST_MESSAGE(4);
-    TEST_MESSAGE(5);
-    TEST_MESSAGE(6);
-    TEST_MESSAGE(7);
-    TEST_MESSAGE(8);
-    TEST_MESSAGE(9);
-    TEST_MESSAGE(10);
-    TEST_MESSAGE(11);
-    TEST_MESSAGE(12);
-    TEST_MESSAGE(13);
-    TEST_MESSAGE(14);
-    TEST_MESSAGE(15);
-    TEST_MESSAGE(16);
-    TEST_MESSAGE(17);
-    TEST_MESSAGE(18);
-    TEST_MESSAGE(19);
-    TEST_MESSAGE(20);
-
-    printf("\n%s\n\n", success ? "PASS" : "FAIL");
-
-    return !success;
-}
diff --git a/libmincrypt/tools/Android.mk b/libmincrypt/tools/Android.mk
deleted file mode 100644
index 3154914..0000000
--- a/libmincrypt/tools/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-# Copyright (C) 2008 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 := dumpkey
-LOCAL_SRC_FILES := DumpPublicKey.java
-LOCAL_JAR_MANIFEST := DumpPublicKey.mf
-LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-host
-include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/libmincrypt/tools/DumpPublicKey.java b/libmincrypt/tools/DumpPublicKey.java
deleted file mode 100644
index 3eb1398..0000000
--- a/libmincrypt/tools/DumpPublicKey.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-package com.android.dumpkey;
-
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-
-import java.io.FileInputStream;
-import java.math.BigInteger;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.KeyStore;
-import java.security.Key;
-import java.security.PublicKey;
-import java.security.Security;
-import java.security.interfaces.ECPublicKey;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.ECPoint;
-
-/**
- * Command line tool to extract RSA public keys from X.509 certificates
- * and output source code with data initializers for the keys.
- * @hide
- */
-class DumpPublicKey {
-    /**
-     * @param key to perform sanity checks on
-     * @return version number of key.  Supported versions are:
-     *     1: 2048-bit RSA key with e=3 and SHA-1 hash
-     *     2: 2048-bit RSA key with e=65537 and SHA-1 hash
-     *     3: 2048-bit RSA key with e=3 and SHA-256 hash
-     *     4: 2048-bit RSA key with e=65537 and SHA-256 hash
-     * @throws Exception if the key has the wrong size or public exponent
-     */
-    static int checkRSA(RSAPublicKey key, boolean useSHA256) throws Exception {
-        BigInteger pubexp = key.getPublicExponent();
-        BigInteger modulus = key.getModulus();
-        int version;
-
-        if (pubexp.equals(BigInteger.valueOf(3))) {
-            version = useSHA256 ? 3 : 1;
-        } else if (pubexp.equals(BigInteger.valueOf(65537))) {
-            version = useSHA256 ? 4 : 2;
-        } else {
-            throw new Exception("Public exponent should be 3 or 65537 but is " +
-                                pubexp.toString(10) + ".");
-        }
-
-        if (modulus.bitLength() != 2048) {
-             throw new Exception("Modulus should be 2048 bits long but is " +
-                        modulus.bitLength() + " bits.");
-        }
-
-        return version;
-    }
-
-    /**
-     * @param key to perform sanity checks on
-     * @return version number of key.  Supported versions are:
-     *     5: 256-bit EC key with curve NIST P-256
-     * @throws Exception if the key has the wrong size or public exponent
-     */
-    static int checkEC(ECPublicKey key) throws Exception {
-        if (key.getParams().getCurve().getField().getFieldSize() != 256) {
-            throw new Exception("Curve must be NIST P-256");
-        }
-
-        return 5;
-    }
-
-    /**
-     * Perform sanity check on public key.
-     */
-    static int check(PublicKey key, boolean useSHA256) throws Exception {
-        if (key instanceof RSAPublicKey) {
-            return checkRSA((RSAPublicKey) key, useSHA256);
-        } else if (key instanceof ECPublicKey) {
-            if (!useSHA256) {
-                throw new Exception("Must use SHA-256 with EC keys!");
-            }
-            return checkEC((ECPublicKey) key);
-        } else {
-            throw new Exception("Unsupported key class: " + key.getClass().getName());
-        }
-    }
-
-    /**
-     * @param key to output
-     * @return a String representing this public key.  If the key is a
-     *    version 1 key, the string will be a C initializer; this is
-     *    not true for newer key versions.
-     */
-    static String printRSA(RSAPublicKey key, boolean useSHA256) throws Exception {
-        int version = check(key, useSHA256);
-
-        BigInteger N = key.getModulus();
-
-        StringBuilder result = new StringBuilder();
-
-        int nwords = N.bitLength() / 32;    // # of 32 bit integers in modulus
-
-        if (version > 1) {
-            result.append("v");
-            result.append(Integer.toString(version));
-            result.append(" ");
-        }
-
-        result.append("{");
-        result.append(nwords);
-
-        BigInteger B = BigInteger.valueOf(0x100000000L);  // 2^32
-        BigInteger N0inv = B.subtract(N.modInverse(B));   // -1 / N[0] mod 2^32
-
-        result.append(",0x");
-        result.append(N0inv.toString(16));
-
-        BigInteger R = BigInteger.valueOf(2).pow(N.bitLength());
-        BigInteger RR = R.multiply(R).mod(N);    // 2^4096 mod N
-
-        // Write out modulus as little endian array of integers.
-        result.append(",{");
-        for (int i = 0; i < nwords; ++i) {
-            long n = N.mod(B).longValue();
-            result.append(n);
-
-            if (i != nwords - 1) {
-                result.append(",");
-            }
-
-            N = N.divide(B);
-        }
-        result.append("}");
-
-        // Write R^2 as little endian array of integers.
-        result.append(",{");
-        for (int i = 0; i < nwords; ++i) {
-            long rr = RR.mod(B).longValue();
-            result.append(rr);
-
-            if (i != nwords - 1) {
-                result.append(",");
-            }
-
-            RR = RR.divide(B);
-        }
-        result.append("}");
-
-        result.append("}");
-        return result.toString();
-    }
-
-    /**
-     * @param key to output
-     * @return a String representing this public key.  If the key is a
-     *    version 1 key, the string will be a C initializer; this is
-     *    not true for newer key versions.
-     */
-    static String printEC(ECPublicKey key) throws Exception {
-        int version = checkEC(key);
-
-        StringBuilder result = new StringBuilder();
-
-        result.append("v");
-        result.append(Integer.toString(version));
-        result.append(" ");
-
-        BigInteger X = key.getW().getAffineX();
-        BigInteger Y = key.getW().getAffineY();
-        int nbytes = key.getParams().getCurve().getField().getFieldSize() / 8;    // # of 32 bit integers in X coordinate
-
-        result.append("{");
-        result.append(nbytes);
-
-        BigInteger B = BigInteger.valueOf(0x100L);  // 2^8
-
-        // Write out Y coordinate as array of characters.
-        result.append(",{");
-        for (int i = 0; i < nbytes; ++i) {
-            long n = X.mod(B).longValue();
-            result.append(n);
-
-            if (i != nbytes - 1) {
-                result.append(",");
-            }
-
-            X = X.divide(B);
-        }
-        result.append("}");
-
-        // Write out Y coordinate as array of characters.
-        result.append(",{");
-        for (int i = 0; i < nbytes; ++i) {
-            long n = Y.mod(B).longValue();
-            result.append(n);
-
-            if (i != nbytes - 1) {
-                result.append(",");
-            }
-
-            Y = Y.divide(B);
-        }
-        result.append("}");
-
-        result.append("}");
-        return result.toString();
-    }
-
-    static String print(PublicKey key, boolean useSHA256) throws Exception {
-        if (key instanceof RSAPublicKey) {
-            return printRSA((RSAPublicKey) key, useSHA256);
-        } else if (key instanceof ECPublicKey) {
-            return printEC((ECPublicKey) key);
-        } else {
-            throw new Exception("Unsupported key class: " + key.getClass().getName());
-        }
-    }
-
-    public static void main(String[] args) {
-        if (args.length < 1) {
-            System.err.println("Usage: DumpPublicKey certfile ... > source.c");
-            System.exit(1);
-        }
-        Security.addProvider(new BouncyCastleProvider());
-        try {
-            for (int i = 0; i < args.length; i++) {
-                FileInputStream input = new FileInputStream(args[i]);
-                CertificateFactory cf = CertificateFactory.getInstance("X.509");
-                X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
-
-                boolean useSHA256 = false;
-                String sigAlg = cert.getSigAlgName();
-                if ("SHA1withRSA".equals(sigAlg) || "MD5withRSA".equals(sigAlg)) {
-                    // SignApk has historically accepted "MD5withRSA"
-                    // certificates, but treated them as "SHA1withRSA"
-                    // anyway.  Continue to do so for backwards
-                    // compatibility.
-                  useSHA256 = false;
-                } else if ("SHA256withRSA".equals(sigAlg) || "SHA256withECDSA".equals(sigAlg)) {
-                  useSHA256 = true;
-                } else {
-                  System.err.println(args[i] + ": unsupported signature algorithm \"" +
-                                     sigAlg + "\"");
-                  System.exit(1);
-                }
-
-                PublicKey key = cert.getPublicKey();
-                check(key, useSHA256);
-                System.out.print(print(key, useSHA256));
-                System.out.println(i < args.length - 1 ? "," : "");
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-            System.exit(1);
-        }
-        System.exit(0);
-    }
-}
diff --git a/libmincrypt/tools/DumpPublicKey.mf b/libmincrypt/tools/DumpPublicKey.mf
deleted file mode 100644
index 7bb3bc8..0000000
--- a/libmincrypt/tools/DumpPublicKey.mf
+++ /dev/null
@@ -1 +0,0 @@
-Main-Class: com.android.dumpkey.DumpPublicKey
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/Android.bp b/libnativebridge/Android.bp
new file mode 100644
index 0000000..5fb56f2
--- /dev/null
+++ b/libnativebridge/Android.bp
@@ -0,0 +1,24 @@
+
+cc_library {
+    name: "libnativebridge",
+
+    host_supported: true,
+    srcs: ["native_bridge.cc"],
+    shared_libs: ["liblog"],
+    clang: true,
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+    cppflags: [
+        "-fvisibility=protected",
+    ],
+
+    host_ldlibs: ["-ldl"],
+    target: {
+        android: {
+            shared_libs: ["libdl"],
+        },
+    },
+}
diff --git a/libnativebridge/Android.mk b/libnativebridge/Android.mk
index d20d44c..3887b1b 100644
--- a/libnativebridge/Android.mk
+++ b/libnativebridge/Android.mk
@@ -1,58 +1,3 @@
 LOCAL_PATH:= $(call my-dir)
 
-NATIVE_BRIDGE_COMMON_SRC_FILES := \
-  native_bridge.cc
-
-# Shared library for target
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativebridge
-
-LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-
-include $(BUILD_SHARED_LIBRARY)
-
-# Shared library for host
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativebridge
-
-LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Static library for host
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativebridge
-
-LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-
 include $(LOCAL_PATH)/tests/Android.mk
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
index 32a65ea..cc30aaf 100644
--- a/libnativebridge/native_bridge.cc
+++ b/libnativebridge/native_bridge.cc
@@ -14,17 +14,21 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "nativebridge"
+
 #include "nativebridge/native_bridge.h"
 
-#include <cstring>
-#include <cutils/log.h>
 #include <dlfcn.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <stdio.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
+#include <unistd.h>
 
+#include <cstring>
+
+#include <log/log.h>
 
 namespace android {
 
@@ -76,6 +80,21 @@
 // Current state of the native bridge.
 static NativeBridgeState state = NativeBridgeState::kNotSetup;
 
+// The version of NativeBridge implementation.
+// Different Nativebridge interface needs the service of different version of
+// Nativebridge implementation.
+// Used by isCompatibleWith() which is introduced in v2.
+enum NativeBridgeImplementationVersion {
+  // first version, not used.
+  DEFAULT_VERSION = 1,
+  // The version which signal semantic is introduced.
+  SIGNAL_VERSION = 2,
+  // The version which namespace semantic is introduced.
+  NAMESPACE_VERSION = 3,
+  // The version with vendor namespaces
+  VENDOR_NAMESPACE_VERSION = 4,
+};
+
 // Whether we had an error at some point.
 static bool had_error = false;
 
@@ -96,8 +115,6 @@
 // and hard code the directory name again here.
 static constexpr const char* kCodeCacheDir = "code_cache";
 
-static constexpr uint32_t kLibNativeBridgeVersion = 2;
-
 // Characters allowed in a native bridge filename. The first character must
 // be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
 static bool CharacterAllowed(char c, bool first) {
@@ -148,19 +165,18 @@
   }
 }
 
-static bool VersionCheck(const NativeBridgeCallbacks* cb) {
+// The policy of invoking Nativebridge changed in v3 with/without namespace.
+// Suggest Nativebridge implementation not maintain backward-compatible.
+static bool isCompatibleWith(const uint32_t version) {
   // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
   // version.
-  if (cb == nullptr || cb->version == 0) {
+  if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
     return false;
   }
 
   // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
-  if (cb->version >= 2) {
-    if (!callbacks->isCompatibleWith(kLibNativeBridgeVersion)) {
-      // TODO: Scan which version is supported, and fall back to handle it.
-      return false;
-    }
+  if (callbacks->version >= SIGNAL_VERSION) {
+    return callbacks->isCompatibleWith(version);
   }
 
   return true;
@@ -201,7 +217,7 @@
         callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
                                                                    kNativeBridgeInterfaceSymbol));
         if (callbacks != nullptr) {
-          if (VersionCheck(callbacks)) {
+          if (isCompatibleWith(NAMESPACE_VERSION)) {
             // Store the handle for later.
             native_bridge_handle = handle;
           } else {
@@ -231,8 +247,10 @@
 static const char* kRuntimeISA = "arm";
 #elif defined(__aarch64__)
 static const char* kRuntimeISA = "arm64";
-#elif defined(__mips__)
+#elif defined(__mips__) && !defined(__LP64__)
 static const char* kRuntimeISA = "mips";
+#elif defined(__mips__) && defined(__LP64__)
+static const char* kRuntimeISA = "mips64";
 #elif defined(__i386__)
 static const char* kRuntimeISA = "x86";
 #elif defined(__x86_64__)
@@ -514,8 +532,112 @@
 }
 
 NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
-  if (NativeBridgeInitialized() && callbacks->version >= 2) {
-    return callbacks->getSignalHandler(signal);
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(SIGNAL_VERSION)) {
+      return callbacks->getSignalHandler(signal);
+    } else {
+      ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
+    }
+  }
+  return nullptr;
+}
+
+int NativeBridgeUnloadLibrary(void* handle) {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->unloadLibrary(handle);
+    } else {
+      ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
+    }
+  }
+  return -1;
+}
+
+const char* NativeBridgeGetError() {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->getError();
+    } else {
+      return "native bridge implementation is not compatible with version 3, cannot get message";
+    }
+  }
+  return "native bridge is not initialized";
+}
+
+bool NativeBridgeIsPathSupported(const char* path) {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->isPathSupported(path);
+    } else {
+      ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
+    }
+  }
+  return false;
+}
+
+bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path) {
+    if (NativeBridgeInitialized()) {
+        if (isCompatibleWith(NAMESPACE_VERSION)) {
+            return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
+        } else {
+            ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
+        }
+    }
+
+    return false;
+}
+
+native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
+                                                       const char* ld_library_path,
+                                                       const char* default_library_path,
+                                                       uint64_t type,
+                                                       const char* permitted_when_isolated_path,
+                                                       native_bridge_namespace_t* parent_ns) {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->createNamespace(name,
+                                        ld_library_path,
+                                        default_library_path,
+                                        type,
+                                        permitted_when_isolated_path,
+                                        parent_ns);
+    } else {
+      ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
+    }
+  }
+
+  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;
+}
+
+native_bridge_namespace_t* NativeBridgeGetVendorNamespace() {
+  if (!NativeBridgeInitialized() || !isCompatibleWith(VENDOR_NAMESPACE_VERSION)) {
+    return nullptr;
+  }
+
+  return callbacks->getVendorNamespace();
+}
+
+void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->loadLibraryExt(libpath, flag, ns);
+    } else {
+      ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
+    }
   }
   return nullptr;
 }
diff --git a/libnativebridge/tests/Android.mk b/libnativebridge/tests/Android.mk
index 7265939..c9468f0 100644
--- a/libnativebridge/tests/Android.mk
+++ b/libnativebridge/tests/Android.mk
@@ -20,7 +20,13 @@
     PreInitializeNativeBridgeFail2_test.cpp \
     ReSetupNativeBridge_test.cpp \
     UnavailableNativeBridge_test.cpp \
-    ValidNameNativeBridge_test.cpp
+    ValidNameNativeBridge_test.cpp \
+    NativeBridge3UnloadLibrary_test.cpp \
+    NativeBridge3GetError_test.cpp \
+    NativeBridge3IsPathSupported_test.cpp \
+    NativeBridge3InitAnonymousNamespace_test.cpp \
+    NativeBridge3CreateNamespace_test.cpp \
+    NativeBridge3LoadLibraryExt_test.cpp
 
 
 shared_libraries := \
@@ -31,7 +37,6 @@
 $(foreach file,$(test_src_files), \
     $(eval include $(CLEAR_VARS)) \
     $(eval LOCAL_CLANG := true) \
-    $(eval LOCAL_CPPFLAGS := -std=gnu++11) \
     $(eval LOCAL_SHARED_LIBRARIES := $(shared_libraries)) \
     $(eval LOCAL_SRC_FILES := $(file)) \
     $(eval LOCAL_MODULE := $(notdir $(file:%.cpp=%))) \
@@ -41,7 +46,6 @@
 $(foreach file,$(test_src_files), \
     $(eval include $(CLEAR_VARS)) \
     $(eval LOCAL_CLANG := true) \
-    $(eval LOCAL_CPPFLAGS := -std=gnu++11) \
     $(eval LOCAL_SHARED_LIBRARIES := $(shared_libraries)) \
     $(eval LOCAL_SRC_FILES := $(file)) \
     $(eval LOCAL_MODULE := $(notdir $(file:%.cpp=%))) \
diff --git a/libnativebridge/tests/Android.nativebridge-dummy.mk b/libnativebridge/tests/Android.nativebridge-dummy.mk
index 2efc176..2d78be0 100644
--- a/libnativebridge/tests/Android.nativebridge-dummy.mk
+++ b/libnativebridge/tests/Android.nativebridge-dummy.mk
@@ -12,8 +12,8 @@
 LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
+LOCAL_CPPFLAGS := -fvisibility=protected
+LOCAL_SHARED_LIBRARIES := libdl
 LOCAL_MULTILIB := both
 
 include $(BUILD_SHARED_LIBRARY)
@@ -27,7 +27,7 @@
 LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
+LOCAL_CPPFLAGS := -fvisibility=protected
 LOCAL_LDFLAGS := -ldl
 LOCAL_MULTILIB := both
 
@@ -48,8 +48,8 @@
 LOCAL_SRC_FILES:= $(NATIVE_BRIDGE2_COMMON_SRC_FILES)
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
+LOCAL_CPPFLAGS := -fvisibility=protected
+LOCAL_SHARED_LIBRARIES := libdl
 LOCAL_MULTILIB := both
 
 include $(BUILD_SHARED_LIBRARY)
@@ -63,8 +63,46 @@
 LOCAL_SRC_FILES:= $(NATIVE_BRIDGE2_COMMON_SRC_FILES)
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
+LOCAL_CPPFLAGS := -fvisibility=protected
+LOCAL_LDFLAGS := -ldl
+LOCAL_MULTILIB := both
+
+include $(BUILD_HOST_SHARED_LIBRARY)
+
+
+# v3.
+
+NATIVE_BRIDGE3_COMMON_SRC_FILES := \
+  DummyNativeBridge3.cpp
+
+# Shared library for target
+# ========================================================
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= libnativebridge3-dummy
+
+LOCAL_SRC_FILES:= $(NATIVE_BRIDGE3_COMMON_SRC_FILES)
+LOCAL_CLANG := true
+LOCAL_CFLAGS += -Werror -Wall
+LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
+LOCAL_LDFLAGS := -ldl
+LOCAL_MULTILIB := both
+
+include $(BUILD_SHARED_LIBRARY)
+
+# Shared library for host
+# ========================================================
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= libnativebridge3-dummy
+
+LOCAL_SRC_FILES:= $(NATIVE_BRIDGE3_COMMON_SRC_FILES)
+LOCAL_CLANG := true
+LOCAL_CFLAGS += -Werror -Wall
 LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
 LOCAL_LDFLAGS := -ldl
 LOCAL_MULTILIB := both
 
 include $(BUILD_HOST_SHARED_LIBRARY)
+
+
diff --git a/libnativebridge/tests/DummyNativeBridge3.cpp b/libnativebridge/tests/DummyNativeBridge3.cpp
new file mode 100644
index 0000000..b0dd6d0
--- /dev/null
+++ b/libnativebridge/tests/DummyNativeBridge3.cpp
@@ -0,0 +1,124 @@
+/*
+ * 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.
+ */
+
+// A dummy implementation of the native-bridge interface.
+
+#include "nativebridge/native_bridge.h"
+
+#include <signal.h>
+
+// NativeBridgeCallbacks implementations
+extern "C" bool native_bridge3_initialize(
+                      const android::NativeBridgeRuntimeCallbacks* /* art_cbs */,
+                      const char* /* app_code_cache_dir */,
+                      const char* /* isa */) {
+  return true;
+}
+
+extern "C" void* native_bridge3_loadLibrary(const char* /* libpath */, int /* flag */) {
+  return nullptr;
+}
+
+extern "C" void* native_bridge3_getTrampoline(void* /* handle */, const char* /* name */,
+                                             const char* /* shorty */, uint32_t /* len */) {
+  return nullptr;
+}
+
+extern "C" bool native_bridge3_isSupported(const char* /* libpath */) {
+  return false;
+}
+
+extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge3_getAppEnv(
+    const char* /* abi */) {
+  return nullptr;
+}
+
+extern "C" bool native_bridge3_isCompatibleWith(uint32_t version) {
+  // For testing, allow 1-3, but disallow 4+.
+  return version <= 3;
+}
+
+static bool native_bridge3_dummy_signal_handler(int, siginfo_t*, void*) {
+  // TODO: Implement something here. We'd either have to have a death test with a log here, or
+  //       we'd have to be able to resume after the faulting instruction...
+  return true;
+}
+
+extern "C" android::NativeBridgeSignalHandlerFn native_bridge3_getSignalHandler(int signal) {
+  if (signal == SIGSEGV) {
+    return &native_bridge3_dummy_signal_handler;
+  }
+  return nullptr;
+}
+
+extern "C" int native_bridge3_unloadLibrary(void* /* handle */) {
+  return 0;
+}
+
+extern "C" const char* native_bridge3_getError() {
+  return nullptr;
+}
+
+extern "C" bool native_bridge3_isPathSupported(const char* /* path */) {
+  return true;
+}
+
+extern "C" bool native_bridge3_initAnonymousNamespace(const char* /* public_ns_sonames */,
+                                                      const char* /* anon_ns_library_path */) {
+    return true;
+}
+
+extern "C" android::native_bridge_namespace_t*
+native_bridge3_createNamespace(const char* /* name */,
+                               const char* /* ld_library_path */,
+                               const char* /* default_library_path */,
+                               uint64_t /* type */,
+                               const char* /* permitted_when_isolated_path */,
+                               android::native_bridge_namespace_t* /* parent_ns */) {
+  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,
+    .initAnonymousNamespace = &native_bridge3_initAnonymousNamespace,
+    .createNamespace = &native_bridge3_createNamespace,
+    .linkNamespaces = &native_bridge3_linkNamespaces,
+    .loadLibraryExt = &native_bridge3_loadLibraryExt};
diff --git a/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp b/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp
new file mode 100644
index 0000000..668d942
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp
@@ -0,0 +1,40 @@
+/*
+ * 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_CreateNamespace) {
+    // 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(nullptr, NativeBridgeCreateNamespace(nullptr, nullptr, nullptr,
+                                                   0, nullptr, nullptr));
+
+    // Clean-up code_cache
+    ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3GetError_test.cpp b/libnativebridge/tests/NativeBridge3GetError_test.cpp
new file mode 100644
index 0000000..0b9f582
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3GetError_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_GetError) {
+    // 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(nullptr, NativeBridgeGetError());
+
+    // Clean-up code_cache
+    ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp b/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp
new file mode 100644
index 0000000..989a819
--- /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/NativeBridge3IsPathSupported_test.cpp b/libnativebridge/tests/NativeBridge3IsPathSupported_test.cpp
new file mode 100644
index 0000000..325e40b
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3IsPathSupported_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_IsPathSupported) {
+    // 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, NativeBridgeIsPathSupported(nullptr));
+
+    // Clean-up code_cache
+    ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3LoadLibraryExt_test.cpp b/libnativebridge/tests/NativeBridge3LoadLibraryExt_test.cpp
new file mode 100644
index 0000000..4caeb44
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3LoadLibraryExt_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_LoadLibraryExt) {
+    // 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(nullptr, NativeBridgeLoadLibraryExt(nullptr, 0, nullptr));
+
+    // Clean-up code_cache
+    ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3UnloadLibrary_test.cpp b/libnativebridge/tests/NativeBridge3UnloadLibrary_test.cpp
new file mode 100644
index 0000000..93a979c
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3UnloadLibrary_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_UnloadLibrary) {
+    // 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(0, NativeBridgeUnloadLibrary(nullptr));
+
+    // Clean-up code_cache
+    ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridgeTest.h b/libnativebridge/tests/NativeBridgeTest.h
index d489420..0f99816 100644
--- a/libnativebridge/tests/NativeBridgeTest.h
+++ b/libnativebridge/tests/NativeBridgeTest.h
@@ -25,6 +25,8 @@
 constexpr const char* kNativeBridgeLibrary = "libnativebridge-dummy.so";
 constexpr const char* kCodeCache = "./code_cache";
 constexpr const char* kCodeCacheStatFail = "./code_cache/temp";
+constexpr const char* kNativeBridgeLibrary2 = "libnativebridge2-dummy.so";
+constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
 
 namespace android {
 
diff --git a/libnativebridge/tests/NeedsNativeBridge_test.cpp b/libnativebridge/tests/NeedsNativeBridge_test.cpp
index e1c0876..2067ed2 100644
--- a/libnativebridge/tests/NeedsNativeBridge_test.cpp
+++ b/libnativebridge/tests/NeedsNativeBridge_test.cpp
@@ -18,15 +18,17 @@
 
 namespace android {
 
-static const char* kISAs[] = { "arm", "arm64", "mips", "x86", "x86_64", "random", "64arm", "64_x86",
-                               "64_x86_64", "", "reallylongstringabcd", nullptr };
+static const char* kISAs[] = { "arm", "arm64", "mips", "mips64", "x86", "x86_64", "random", "64arm",
+                               "64_x86", "64_x86_64", "", "reallylongstringabcd", nullptr };
 
 #if defined(__arm__)
 static const char* kRuntimeISA = "arm";
 #elif defined(__aarch64__)
 static const char* kRuntimeISA = "arm64";
-#elif defined(__mips__)
+#elif defined(__mips__) && !defined(__LP64__)
 static const char* kRuntimeISA = "mips";
+#elif defined(__mips__) && defined(__LP64__)
+static const char* kRuntimeISA = "mips64";
 #elif defined(__i386__)
 static const char* kRuntimeISA = "x86";
 #elif defined(__x86_64__)
diff --git a/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp b/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp
index 69c30a1..5a2b0a1 100644
--- a/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp
+++ b/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp
@@ -16,9 +16,6 @@
 
 #include "NativeBridgeTest.h"
 
-#include <cstdio>
-#include <cstring>
-#include <cutils/log.h>
 #include <dlfcn.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -26,6 +23,11 @@
 #include <sys/mount.h>
 #include <sys/stat.h>
 
+#include <cstdio>
+#include <cstring>
+
+#include <android/log.h>
+
 namespace android {
 
 TEST_F(NativeBridgeTest, PreInitializeNativeBridgeFail1) {
diff --git a/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp b/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp
index 74e96e0..af976b1 100644
--- a/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp
+++ b/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp
@@ -14,11 +14,6 @@
  * limitations under the License.
  */
 
-#include "NativeBridgeTest.h"
-
-#include <cstdio>
-#include <cstring>
-#include <cutils/log.h>
 #include <dlfcn.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -26,6 +21,13 @@
 #include <sys/mount.h>
 #include <sys/stat.h>
 
+#include <cstdio>
+#include <cstring>
+
+#include <android/log.h>
+
+#include "NativeBridgeTest.h"
+
 namespace android {
 
 TEST_F(NativeBridgeTest, PreInitializeNativeBridgeFail2) {
diff --git a/libnativebridge/tests/PreInitializeNativeBridge_test.cpp b/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
index d3bbebe..f3e5f38 100644
--- a/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
+++ b/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
@@ -14,11 +14,6 @@
  * limitations under the License.
  */
 
-#include "NativeBridgeTest.h"
-
-#include <cstdio>
-#include <cstring>
-#include <cutils/log.h>
 #include <dlfcn.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -26,6 +21,13 @@
 #include <sys/mount.h>
 #include <sys/stat.h>
 
+#include <cstdio>
+#include <cstring>
+
+#include <android/log.h>
+
+#include "NativeBridgeTest.h"
+
 namespace android {
 
 static constexpr const char* kTestData = "PreInitializeNativeBridge test.";
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/Android.bp b/libnativeloader/Android.bp
new file mode 100644
index 0000000..c1133fb
--- /dev/null
+++ b/libnativeloader/Android.bp
@@ -0,0 +1,32 @@
+// Shared library for target
+// ========================================================
+cc_library {
+    name: "libnativeloader",
+    host_supported: true,
+    srcs: ["native_loader.cpp"],
+    shared_libs: [
+        "libnativehelper",
+        "liblog",
+        "libcutils",
+        "libnativebridge",
+        "libbase",
+    ],
+    target: {
+        android: {
+            shared_libs: ["libdl"],
+        },
+        host: {
+            host_ldlibs: ["-ldl"],
+        },
+    },
+    clang: true,
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+    cppflags: [
+        "-fvisibility=hidden",
+    ],
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+}
diff --git a/libnativeloader/Android.mk b/libnativeloader/Android.mk
deleted file mode 100644
index 632c6c8..0000000
--- a/libnativeloader/Android.mk
+++ /dev/null
@@ -1,59 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-native_loader_common_src_files := \
-  native_loader.cpp
-
-native_loader_common_cflags := -Werror -Wall
-
-# Shared library for target
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativeloader
-
-LOCAL_SRC_FILES:= $(native_loader_common_src_files)
-LOCAL_SHARED_LIBRARIES := libnativehelper liblog libcutils
-LOCAL_STATIC_LIBRARIES := libbase
-LOCAL_CLANG := true
-LOCAL_CFLAGS := $(native_loader_common_cflags)
-LOCAL_CPPFLAGS := -std=gnu++14 -fvisibility=hidden
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-include $(BUILD_SHARED_LIBRARY)
-
-# Shared library for host
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativeloader
-
-LOCAL_SRC_FILES:= $(native_loader_common_src_files)
-LOCAL_SHARED_LIBRARIES := libnativehelper liblog libcutils
-LOCAL_STATIC_LIBRARIES := libbase
-LOCAL_CLANG := true
-LOCAL_CFLAGS := $(native_loader_common_cflags)
-LOCAL_CPPFLAGS := -std=gnu++14 -fvisibility=hidden
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Static library for host
-# ========================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE:= libnativeloader
-
-LOCAL_SRC_FILES:= $(native_loader_common_src_files)
-LOCAL_STATIC_LIBRARIES := libnativehelper libcutils liblog libbase
-LOCAL_CLANG := true
-LOCAL_CFLAGS := $(native_loader_common_cflags)
-LOCAL_CPPFLAGS := -std=gnu++14 -fvisibility=hidden
-LOCAL_LDFLAGS := -ldl
-LOCAL_MULTILIB := both
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-include $(BUILD_HOST_STATIC_LIBRARY)
diff --git a/libnativeloader/include/nativeloader/dlext_namespaces.h b/libnativeloader/include/nativeloader/dlext_namespaces.h
index 02e7075..43c9329 100644
--- a/libnativeloader/include/nativeloader/dlext_namespaces.h
+++ b/libnativeloader/include/nativeloader/dlext_namespaces.h
@@ -22,16 +22,15 @@
 __BEGIN_DECLS
 
 /*
- * Initializes public and anonymous namespaces. The public_ns_sonames is the list of sonames
- * to be included into public namespace separated by colon. Example: "libc.so:libm.so:libdl.so".
- * The libraries in this list should be loaded prior to this call.
+ * Initializes anonymous namespaces. The shared_libs_sonames is the list of sonames
+ * to be shared by default namespace separated by colon. Example: "libc.so:libm.so:libdl.so".
  *
- * The anon_ns_library_path is the search path for anonymous namespace. The anonymous namespace
+ * The library_search_path is the search path for anonymous namespace. The anonymous namespace
  * is used in the case when linker cannot identify the caller of dlopen/dlsym. This happens
  * for the code not loaded by dynamic linker; for example calls from the mono-compiled code.
  */
-extern bool android_init_namespaces(const char* public_ns_sonames,
-                                    const char* anon_ns_library_path);
+extern bool android_init_anonymous_namespace(const char* shared_libs_sonames,
+                                             const char* library_search_path);
 
 
 enum {
@@ -56,6 +55,12 @@
    * permitted_path from the caller's namespace.
    */
   ANDROID_NAMESPACE_TYPE_SHARED = 2,
+
+  /* This flag instructs linker to enable grey-list workaround for the namespace.
+   * See http://b/26394120 for details.
+   */
+  ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED = 0x08000000,
+
   ANDROID_NAMESPACE_TYPE_SHARED_ISOLATED = ANDROID_NAMESPACE_TYPE_SHARED |
                                            ANDROID_NAMESPACE_TYPE_ISOLATED,
 };
@@ -87,6 +92,26 @@
                                                             android_namespace_t* parent);
 
 /*
+ * Creates a link between namespaces. Every link has list of sonames of
+ * shared libraries. These are the libraries which are accessible from
+ * namespace 'from' but loaded within namespace 'to' context.
+ * When to namespace is nullptr this function establishes a link between
+ * 'from' namespace and the default namespace.
+ *
+ * The lookup order of the libraries in namespaces with links is following:
+ * 1. Look inside current namespace using 'this' namespace search path.
+ * 2. Look in linked namespaces
+ * 2.1. Perform soname check - if library soname is not in the list of shared
+ *      libraries sonames skip this link, otherwise
+ * 2.2. Search library using linked namespace search path. Note that this
+ *      step will not go deeper into linked namespaces for this library but
+ *      will do so for DT_NEEDED libraries.
+ */
+extern bool android_link_namespaces(android_namespace_t* from,
+                                    android_namespace_t* to,
+                                    const char* shared_libs_sonames);
+
+/*
  * Get the default library search path.
  * The path will be copied into buffer, which must have space for at least
  * buffer_size chars. Elements are separated with ':', and the path will always
@@ -99,6 +124,8 @@
  */
 extern void android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size);
 
+extern android_namespace_t* android_get_exported_namespace(const char* name);
+
 __END_DECLS
 
 #endif /* __ANDROID_DLEXT_NAMESPACES_H__ */
diff --git a/libnativeloader/include/nativeloader/native_loader.h b/libnativeloader/include/nativeloader/native_loader.h
index 2a6aaec..99ae3a7 100644
--- a/libnativeloader/include/nativeloader/native_loader.h
+++ b/libnativeloader/include/nativeloader/native_loader.h
@@ -19,6 +19,7 @@
 
 #include "jni.h"
 #include <stdint.h>
+#include <string>
 #if defined(__ANDROID__)
 #include <android/dlext.h>
 #endif
@@ -41,10 +42,12 @@
                         int32_t target_sdk_version,
                         const char* path,
                         jobject class_loader,
-                        jstring library_path);
+                        jstring library_path,
+                        bool* needs_native_bridge,
+                        std::string* error_msg);
 
 __attribute__((visibility("default")))
-bool CloseNativeLibrary(void* handle);
+bool CloseNativeLibrary(void* handle, const bool needs_native_bridge);
 
 #if defined(__ANDROID__)
 // Look up linker namespace by class_loader. Returns nullptr if
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index 66f2f49..36a2e44 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -19,26 +19,75 @@
 
 #include <dlfcn.h>
 #ifdef __ANDROID__
+#define LOG_TAG "libnativeloader"
 #include "nativeloader/dlext_namespaces.h"
 #include "cutils/properties.h"
-#define LOG_TAG "libnativeloader"
 #include "log/log.h"
 #endif
+#include "nativebridge/native_bridge.h"
 
 #include <algorithm>
 #include <vector>
 #include <string>
 #include <mutex>
 
-#include "android-base/file.h"
-#include "android-base/macros.h"
-#include "android-base/strings.h"
+#include <android-base/file.h>
+#include <android-base/macros.h>
+#include <android-base/strings.h>
+
+#define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
+                                             "%s:%d: %s CHECK '" #predicate "' failed.",\
+                                             __FILE__, __LINE__, __FUNCTION__)
 
 namespace android {
 
 #if defined(__ANDROID__)
-static constexpr const char* kPublicNativeLibrariesSystemConfigPathFromRoot = "/etc/public.libraries.txt";
-static constexpr const char* kPublicNativeLibrariesVendorConfig = "/vendor/etc/public.libraries.txt";
+class NativeLoaderNamespace {
+ public:
+  NativeLoaderNamespace()
+      : android_ns_(nullptr), native_bridge_ns_(nullptr) { }
+
+  explicit NativeLoaderNamespace(android_namespace_t* ns)
+      : android_ns_(ns), native_bridge_ns_(nullptr) { }
+
+  explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
+      : android_ns_(nullptr), native_bridge_ns_(ns) { }
+
+  NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
+  NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;
+
+  NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;
+
+  android_namespace_t* get_android_ns() const {
+    CHECK(native_bridge_ns_ == nullptr);
+    return android_ns_;
+  }
+
+  native_bridge_namespace_t* get_native_bridge_ns() const {
+    CHECK(android_ns_ == nullptr);
+    return native_bridge_ns_;
+  }
+
+  bool is_android_namespace() const {
+    return native_bridge_ns_ == nullptr;
+  }
+
+ private:
+  // Only one of them can be not null
+  android_namespace_t* android_ns_;
+  native_bridge_namespace_t* native_bridge_ns_;
+};
+
+static constexpr const char* kPublicNativeLibrariesSystemConfigPathFromRoot =
+                                  "/etc/public.libraries.txt";
+static constexpr const char* kPublicNativeLibrariesVendorConfig =
+                                  "/vendor/etc/public.libraries.txt";
+
+// The device may be configured to have the vendor libraries loaded to a separate namespace.
+// For historical reasons this namespace was named sphal but effectively it is intended
+// to use to load vendor libraries to separate namespace with controlled interface between
+// vendor and system namespaces.
+static constexpr const char* kVendorNamespaceName = "sphal";
 
 // (http://b/27588281) This is a workaround for apps using custom classloaders and calling
 // System.load() with an absolute path which is outside of the classloader library search path.
@@ -55,11 +104,14 @@
  public:
   LibraryNamespaces() : initialized_(false) { }
 
-  android_namespace_t* Create(JNIEnv* env,
-                              jobject class_loader,
-                              bool is_shared,
-                              jstring java_library_path,
-                              jstring java_permitted_path) {
+  bool Create(JNIEnv* env,
+              uint32_t target_sdk_version,
+              jobject class_loader,
+              bool is_shared,
+              jstring java_library_path,
+              jstring java_permitted_path,
+              NativeLoaderNamespace* ns,
+              std::string* error_msg) {
     std::string library_path; // empty string by default.
 
     if (java_library_path != nullptr) {
@@ -82,13 +134,13 @@
       }
     }
 
-    if (!initialized_ && !InitPublicNamespace(library_path.c_str())) {
-      return nullptr;
+    if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
+      return false;
     }
 
-    android_namespace_t* ns = FindNamespaceByClassLoader(env, class_loader);
+    bool found = FindNamespaceByClassLoader(env, class_loader, nullptr);
 
-    LOG_ALWAYS_FATAL_IF(ns != nullptr,
+    LOG_ALWAYS_FATAL_IF(found,
                         "There is already a namespace associated with this classloader");
 
     uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
@@ -96,31 +148,112 @@
       namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
     }
 
-    android_namespace_t* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
-
-    ns = android_create_namespace("classloader-namespace",
-                                  nullptr,
-                                  library_path.c_str(),
-                                  namespace_type,
-                                  permitted_path.c_str(),
-                                  parent_ns);
-
-    if (ns != nullptr) {
-      namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), ns));
+    if (target_sdk_version < 24) {
+      namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
     }
 
-    return ns;
+    NativeLoaderNamespace parent_ns;
+    bool found_parent_namespace = FindParentNamespaceByClassLoader(env, class_loader, &parent_ns);
+
+    bool is_native_bridge = false;
+
+    if (found_parent_namespace) {
+      is_native_bridge = !parent_ns.is_android_namespace();
+    } else if (!library_path.empty()) {
+      is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
+    }
+
+    NativeLoaderNamespace native_loader_ns;
+    if (!is_native_bridge) {
+      android_namespace_t* ns = android_create_namespace("classloader-namespace",
+                                                         nullptr,
+                                                         library_path.c_str(),
+                                                         namespace_type,
+                                                         permitted_path.c_str(),
+                                                         parent_ns.get_android_ns());
+      if (ns == nullptr) {
+        *error_msg = dlerror();
+        return false;
+      }
+
+      // Note that when vendor_ns is not configured this function will return nullptr
+      // and it will result in linking vendor_public_libraries_ to the default namespace
+      // which is expected behavior in this case.
+      android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
+
+      if (!android_link_namespaces(ns, nullptr, system_public_libraries_.c_str())) {
+        *error_msg = dlerror();
+        return false;
+      }
+
+      if (!vendor_public_libraries_.empty()) {
+        if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
+          *error_msg = dlerror();
+          return false;
+        }
+      }
+
+      native_loader_ns = NativeLoaderNamespace(ns);
+    } else {
+      native_bridge_namespace_t* ns = NativeBridgeCreateNamespace("classloader-namespace",
+                                                                  nullptr,
+                                                                  library_path.c_str(),
+                                                                  namespace_type,
+                                                                  permitted_path.c_str(),
+                                                                  parent_ns.get_native_bridge_ns());
+
+      if (ns == nullptr) {
+        *error_msg = NativeBridgeGetError();
+        return false;
+      }
+
+      native_bridge_namespace_t* vendor_ns = NativeBridgeGetVendorNamespace();
+
+      if (!NativeBridgeLinkNamespaces(ns, nullptr, system_public_libraries_.c_str())) {
+        *error_msg = NativeBridgeGetError();
+        return false;
+      }
+
+      if (!vendor_public_libraries_.empty()) {
+        if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
+          *error_msg = NativeBridgeGetError();
+          return false;
+        }
+      }
+
+      native_loader_ns = NativeLoaderNamespace(ns);
+    }
+
+    namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
+
+    *ns = native_loader_ns;
+    return true;
   }
 
-  android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
+  bool FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader, NativeLoaderNamespace* ns) {
     auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
-                [&](const std::pair<jweak, android_namespace_t*>& value) {
+                [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
                   return env->IsSameObject(value.first, class_loader);
                 });
-    return it != namespaces_.end() ? it->second : nullptr;
+    if (it != namespaces_.end()) {
+      if (ns != nullptr) {
+        *ns = it->second;
+      }
+
+      return true;
+    }
+
+    return false;
   }
 
   void Initialize() {
+    // Once public namespace is initialized there is no
+    // point in running this code - it will have no effect
+    // on the current list of public libraries.
+    if (initialized_) {
+      return;
+    }
+
     std::vector<std::string> sonames;
     const char* android_root_env = getenv("ANDROID_ROOT");
     std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
@@ -144,9 +277,6 @@
       }
     }
 
-    // This file is optional, quietly ignore if the file does not exist.
-    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames);
-
     // android_init_namespaces() expects all the public libraries
     // to be loaded so that they can be found by soname alone.
     //
@@ -156,10 +286,18 @@
     // For now we rely on CTS test to catch things like this but
     // it should probably be addressed in the future.
     for (const auto& soname : sonames) {
-      dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE);
+      LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
+                          "Error preloading public library %s: %s",
+                          soname.c_str(), dlerror());
     }
 
-    public_libraries_ = base::Join(sonames, ':');
+    system_public_libraries_ = base::Join(sonames, ':');
+
+    sonames.clear();
+    // This file is optional, quietly ignore if the file does not exist.
+    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames);
+
+    vendor_public_libraries_ = base::Join(sonames, ':');
   }
 
   void Reset() {
@@ -210,12 +348,29 @@
     return true;
   }
 
-  bool InitPublicNamespace(const char* library_path) {
+  bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
+    // Ask native bride if this apps library path should be handled by it
+    bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
+
     // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
     // code is one example) unknown to linker in which  case linker uses anonymous
     // namespace. The second argument specifies the search path for the anonymous
     // namespace which is the library_path of the classloader.
-    initialized_ = android_init_namespaces(public_libraries_.c_str(), library_path);
+    initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
+                                                    is_native_bridge ? nullptr : library_path);
+    if (!initialized_) {
+      *error_msg = dlerror();
+      return false;
+    }
+
+    // and now initialize native bridge namespaces if necessary.
+    if (NativeBridgeInitialized()) {
+      initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
+                                                        is_native_bridge ? library_path : nullptr);
+      if (!initialized_) {
+        *error_msg = NativeBridgeGetError();
+      }
+    }
 
     return initialized_;
   }
@@ -229,24 +384,26 @@
     return env->CallObjectMethod(class_loader, get_parent);
   }
 
-  android_namespace_t* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
+  bool FindParentNamespaceByClassLoader(JNIEnv* env,
+                                        jobject class_loader,
+                                        NativeLoaderNamespace* ns) {
     jobject parent_class_loader = GetParentClassLoader(env, class_loader);
 
     while (parent_class_loader != nullptr) {
-      android_namespace_t* ns = FindNamespaceByClassLoader(env, parent_class_loader);
-      if (ns != nullptr) {
-        return ns;
+      if (FindNamespaceByClassLoader(env, parent_class_loader, ns)) {
+        return true;
       }
 
       parent_class_loader = GetParentClassLoader(env, parent_class_loader);
     }
-    return nullptr;
+
+    return false;
   }
 
   bool initialized_;
-  std::vector<std::pair<jweak, android_namespace_t*>> namespaces_;
-  std::string public_libraries_;
-
+  std::vector<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
+  std::string system_public_libraries_;
+  std::string vendor_public_libraries_;
 
   DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
 };
@@ -276,15 +433,20 @@
                                    jstring library_path,
                                    jstring permitted_path) {
 #if defined(__ANDROID__)
-  UNUSED(target_sdk_version);
   std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  android_namespace_t* ns = g_namespaces->Create(env,
-                                                 class_loader,
-                                                 is_shared,
-                                                 library_path,
-                                                 permitted_path);
-  if (ns == nullptr) {
-    return env->NewStringUTF(dlerror());
+
+  std::string error_msg;
+  NativeLoaderNamespace ns;
+  bool success = g_namespaces->Create(env,
+                                      target_sdk_version,
+                                      class_loader,
+                                      is_shared,
+                                      library_path,
+                                      permitted_path,
+                                      &ns,
+                                      &error_msg);
+  if (!success) {
+    return env->NewStringUTF(error_msg.c_str());
   }
 #else
   UNUSED(env, target_sdk_version, class_loader, is_shared,
@@ -297,44 +459,90 @@
                         int32_t target_sdk_version,
                         const char* path,
                         jobject class_loader,
-                        jstring library_path) {
+                        jstring library_path,
+                        bool* needs_native_bridge,
+                        std::string* error_msg) {
 #if defined(__ANDROID__)
   UNUSED(target_sdk_version);
   if (class_loader == nullptr) {
+    *needs_native_bridge = false;
     return dlopen(path, RTLD_NOW);
   }
 
   std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  android_namespace_t* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
+  NativeLoaderNamespace ns;
 
-  if (ns == nullptr) {
+  if (!g_namespaces->FindNamespaceByClassLoader(env, class_loader, &ns)) {
     // This is the case where the classloader was not created by ApplicationLoaders
     // In this case we create an isolated not-shared namespace for it.
-    ns = g_namespaces->Create(env, class_loader, false, library_path, nullptr);
-    if (ns == nullptr) {
+    if (!g_namespaces->Create(env,
+                              target_sdk_version,
+                              class_loader,
+                              false,
+                              library_path,
+                              nullptr,
+                              &ns,
+                              error_msg)) {
       return nullptr;
     }
   }
 
-  android_dlextinfo extinfo;
-  extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
-  extinfo.library_namespace = ns;
+  if (ns.is_android_namespace()) {
+    android_dlextinfo extinfo;
+    extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
+    extinfo.library_namespace = ns.get_android_ns();
 
-  return android_dlopen_ext(path, RTLD_NOW, &extinfo);
+    void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
+    if (handle == nullptr) {
+      *error_msg = dlerror();
+    }
+    *needs_native_bridge = false;
+    return handle;
+  } else {
+    void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns.get_native_bridge_ns());
+    if (handle == nullptr) {
+      *error_msg = NativeBridgeGetError();
+    }
+    *needs_native_bridge = true;
+    return handle;
+  }
 #else
   UNUSED(env, target_sdk_version, class_loader, library_path);
-  return dlopen(path, RTLD_NOW);
+  *needs_native_bridge = false;
+  void* handle = dlopen(path, RTLD_NOW);
+  if (handle == nullptr) {
+    if (NativeBridgeIsSupported(path)) {
+      *needs_native_bridge = true;
+      handle = NativeBridgeLoadLibrary(path, RTLD_NOW);
+      if (handle == nullptr) {
+        *error_msg = NativeBridgeGetError();
+      }
+    } else {
+      *needs_native_bridge = false;
+      *error_msg = dlerror();
+    }
+  }
+  return handle;
 #endif
 }
 
-bool CloseNativeLibrary(void* handle) {
-  return dlclose(handle) == 0;
+bool CloseNativeLibrary(void* handle, const bool needs_native_bridge) {
+    return needs_native_bridge ? NativeBridgeUnloadLibrary(handle) :
+                                 dlclose(handle);
 }
 
 #if defined(__ANDROID__)
+// native_bridge_namespaces are not supported for callers of this function.
+// This function will return nullptr in the case when application is running
+// on native bridge.
 android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
   std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
+  NativeLoaderNamespace ns;
+  if (g_namespaces->FindNamespaceByClassLoader(env, class_loader, &ns)) {
+    return ns.is_android_namespace() ? ns.get_android_ns() : nullptr;
+  }
+
+  return nullptr;
 }
 #endif
 
diff --git a/libnetutils/Android.bp b/libnetutils/Android.bp
new file mode 100644
index 0000000..d63d619
--- /dev/null
+++ b/libnetutils/Android.bp
@@ -0,0 +1,20 @@
+cc_library_shared {
+    name: "libnetutils",
+    vendor_available: true,
+
+    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 ff899c0..0000000
--- a/libnetutils/Android.mk
+++ /dev/null
@@ -1,25 +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
-
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := dhcptool.c
-LOCAL_SHARED_LIBRARIES := libnetutils
-LOCAL_MODULE := dhcptool
-LOCAL_MODULE_TAGS := debug
-include $(BUILD_EXECUTABLE)
diff --git a/libnetutils/dhcpclient.c b/libnetutils/dhcpclient.c
index 240a789..11c116a 100644
--- a/libnetutils/dhcpclient.c
+++ b/libnetutils/dhcpclient.c
@@ -14,27 +14,25 @@
  * limitations under the License.
  */
 
-#include <stdio.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
-
-#include <time.h>
-#include <sys/time.h>
-#include <poll.h>
-
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-
-#include <cutils/properties.h>
 #define LOG_TAG "DHCP"
-#include <cutils/log.h>
 
 #include <dirent.h>
+#include <errno.h>
+#include <poll.h>
+#include <netinet/in.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <cutils/properties.h>
+#include <log/log.h>
 
 #include <netutils/ifc.h>
 #include "dhcpmsg.h"
diff --git a/libnetutils/dhcptool.c b/libnetutils/dhcptool.c
deleted file mode 100644
index d23afd3..0000000
--- a/libnetutils/dhcptool.c
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2015, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <err.h>
-#include <errno.h>
-#include <error.h>
-#include <stdbool.h>
-#include <stdlib.h>
-
-#include <netutils/ifc.h>
-
-extern int do_dhcp(char*);
-
-int main(int argc, char* argv[]) {
-  if (argc != 2) {
-    error(EXIT_FAILURE, 0, "usage: %s INTERFACE", argv[0]);
-  }
-
-  char* interface = argv[1];
-  if (ifc_init()) {
-    err(errno, "dhcptool %s: ifc_init failed", interface);
-    ifc_close();
-    return EXIT_FAILURE;
-  }
-
-  int rc = do_dhcp(interface);
-  if (rc) {
-    err(errno, "dhcptool %s: do_dhcp failed", interface);
-  }
-
-  ifc_close();
-
-  return rc ? EXIT_FAILURE : EXIT_SUCCESS;
-}
diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c
index eae32ce..a098d59 100644
--- a/libnetutils/ifc_utils.c
+++ b/libnetutils/ifc_utils.c
@@ -1,34 +1,21 @@
 /*
  * Copyright 2008, 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 
+ * 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 
+ *     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 
+ * 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 <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <pthread.h>
-
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <netinet/in.h>
 #include <arpa/inet.h>
-#include <net/if.h>
-#include <netdb.h>
-
+#include <errno.h>
 #include <linux/if.h>
 #include <linux/if_ether.h>
 #include <linux/if_arp.h>
@@ -37,20 +24,29 @@
 #include <linux/ipv6_route.h>
 #include <linux/rtnetlink.h>
 #include <linux/sockios.h>
-
-#include "netutils/ifc.h"
+#include <net/if.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #ifdef ANDROID
 #define LOG_TAG "NetUtils"
-#include <cutils/log.h>
 #include <cutils/properties.h>
+#include <log/log.h>
 #else
-#include <stdio.h>
-#include <string.h>
 #define ALOGD printf
 #define ALOGW printf
 #endif
 
+#include "netutils/ifc.h"
+
 #if defined(__ANDROID__)
 /* SIOCKILLADDR is an Android extension. */
 #define SIOCKILLADDR 0x8939
diff --git a/include/netutils/ifc.h b/libnetutils/include/netutils/ifc.h
similarity index 100%
rename from include/netutils/ifc.h
rename to libnetutils/include/netutils/ifc.h
diff --git a/libnetutils/packet.c b/libnetutils/packet.c
index cd26d05..e53a4c8 100644
--- a/libnetutils/packet.c
+++ b/libnetutils/packet.c
@@ -1,37 +1,36 @@
 /*
  * Copyright 2008, 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 
+ * 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 
+ *     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 
+ * 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 <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <sys/uio.h>
 #include <sys/socket.h>
+#include <sys/uio.h>
+#include <linux/if_ether.h>
+#include <linux/if_packet.h>
 #include <netinet/in.h>
 #include <netinet/ip.h>
 #include <netinet/udp.h>
-#include <linux/if_packet.h>
-#include <linux/if_ether.h>
-#include <errno.h>
+#include <unistd.h>
 
 #ifdef ANDROID
 #define LOG_TAG "DHCP"
-#include <cutils/log.h>
+#include <log/log.h>
 #else
 #include <stdio.h>
-#include <string.h>
 #define ALOGD printf
 #define ALOGW printf
 #endif
diff --git a/libpackagelistparser/Android.bp b/libpackagelistparser/Android.bp
new file mode 100644
index 0000000..70ff528
--- /dev/null
+++ b/libpackagelistparser/Android.bp
@@ -0,0 +1,13 @@
+cc_library {
+
+    name: "libpackagelistparser",
+    srcs: ["packagelistparser.c"],
+    shared_libs: ["liblog"],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+
+    clang: true,
+    sanitize: {
+        misc_undefined: ["integer"],
+    },
+}
diff --git a/libpackagelistparser/Android.mk b/libpackagelistparser/Android.mk
deleted file mode 100644
index c8be050..0000000
--- a/libpackagelistparser/Android.mk
+++ /dev/null
@@ -1,32 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-#########################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libpackagelistparser
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := packagelistparser.c
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-
-include $(BUILD_SHARED_LIBRARY)
-
-#########################
-include $(CLEAR_VARS)
-
-
-LOCAL_MODULE := libpackagelistparser
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := packagelistparser.c
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/libpackagelistparser/packagelistparser.c b/libpackagelistparser/packagelistparser.c
index 16052e2..3e1a3d1 100644
--- a/libpackagelistparser/packagelistparser.c
+++ b/libpackagelistparser/packagelistparser.c
@@ -18,17 +18,16 @@
  *
  */
 
+#define LOG_TAG "packagelistparser"
+
 #include <errno.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-
 #include <sys/limits.h>
 
-#define LOG_TAG "packagelistparser"
-#include <utils/Log.h>
-
+#include <log/log.h>
 #include <packagelistparser/packagelistparser.h>
 
 #define CLOGE(fmt, ...) \
diff --git a/libpixelflinger/Android.mk b/libpixelflinger/Android.mk
index 9a937f8..55891db 100644
--- a/libpixelflinger/Android.mk
+++ b/libpixelflinger/Android.mk
@@ -74,10 +74,6 @@
 		    external/safe-iop/include
 LOCAL_SHARED_LIBRARIES := libcutils liblog libutils
 
-# Really this should go away entirely or at least not depend on
-# libhardware, but this at least gets us built.
-LOCAL_SHARED_LIBRARIES += libhardware_legacy
-LOCAL_CFLAGS += -DWITH_LIB_HARDWARE
 include $(BUILD_SHARED_LIBRARY)
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libpixelflinger/arch-arm64/col32cb16blend.S b/libpixelflinger/arch-arm64/col32cb16blend.S
index 8d9c7c4..84596f9 100644
--- a/libpixelflinger/arch-arm64/col32cb16blend.S
+++ b/libpixelflinger/arch-arm64/col32cb16blend.S
@@ -26,7 +26,7 @@
  * SUCH DAMAGE.
  */
     .text
-    .align 0
+    .balign 0
 
     .global scanline_col32cb16blend_arm64
 
diff --git a/libpixelflinger/arch-arm64/t32cb16blend.S b/libpixelflinger/arch-arm64/t32cb16blend.S
index 230f47b..b1a950d 100644
--- a/libpixelflinger/arch-arm64/t32cb16blend.S
+++ b/libpixelflinger/arch-arm64/t32cb16blend.S
@@ -26,7 +26,7 @@
  * SUCH DAMAGE.
  */
     .text
-    .align 0
+    .balign 0
 
     .global scanline_t32cb16blend_arm64
 
diff --git a/libpixelflinger/arch-mips/col32cb16blend.S b/libpixelflinger/arch-mips/col32cb16blend.S
index 5d18e55..810294c 100644
--- a/libpixelflinger/arch-mips/col32cb16blend.S
+++ b/libpixelflinger/arch-mips/col32cb16blend.S
@@ -59,7 +59,7 @@
        .endm
 
        .text
-       .align
+       .balign 4
 
        .global scanline_col32cb16blend_mips
        .ent    scanline_col32cb16blend_mips
diff --git a/libpixelflinger/arch-mips/t32cb16blend.S b/libpixelflinger/arch-mips/t32cb16blend.S
index 236a2c9..1d2fb8f 100644
--- a/libpixelflinger/arch-mips/t32cb16blend.S
+++ b/libpixelflinger/arch-mips/t32cb16blend.S
@@ -178,7 +178,7 @@
 #endif
 
     .text
-    .align
+    .balign 4
 
     .global scanline_t32cb16blend_mips
     .ent    scanline_t32cb16blend_mips
diff --git a/libpixelflinger/arch-mips64/col32cb16blend.S b/libpixelflinger/arch-mips64/col32cb16blend.S
index fea4491..5baffb1 100644
--- a/libpixelflinger/arch-mips64/col32cb16blend.S
+++ b/libpixelflinger/arch-mips64/col32cb16blend.S
@@ -53,7 +53,7 @@
     .endm
 
     .text
-    .align
+    .balign 4
 
     .global scanline_col32cb16blend_mips64
     .ent    scanline_col32cb16blend_mips64
diff --git a/libpixelflinger/arch-mips64/t32cb16blend.S b/libpixelflinger/arch-mips64/t32cb16blend.S
index d2f4d49..3cb5f93 100644
--- a/libpixelflinger/arch-mips64/t32cb16blend.S
+++ b/libpixelflinger/arch-mips64/t32cb16blend.S
@@ -75,7 +75,7 @@
     .endm
 
     .text
-    .align
+    .balign 4
 
     .global scanline_t32cb16blend_mips64
     .ent    scanline_t32cb16blend_mips64
diff --git a/libpixelflinger/codeflinger/ARMAssembler.cpp b/libpixelflinger/codeflinger/ARMAssembler.cpp
index 92243da..ac009a9 100644
--- a/libpixelflinger/codeflinger/ARMAssembler.cpp
+++ b/libpixelflinger/codeflinger/ARMAssembler.cpp
@@ -2,16 +2,16 @@
 **
 ** 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -19,13 +19,9 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <cutils/log.h>
+
 #include <cutils/properties.h>
-
-#if defined(WITH_LIB_HARDWARE)
-#include <hardware_legacy/qemu_tracing.h>
-#endif
-
+#include <log/log.h>
 #include <private/pixelflinger/ggl_context.h>
 
 #include "ARMAssembler.h"
@@ -48,9 +44,6 @@
 {
     mBase = mPC = (uint32_t *)assembly->base();
     mDuration = ggl_system_time();
-#if defined(WITH_LIB_HARDWARE)
-    mQemuTracing = true;
-#endif
 }
 
 ARMAssembler::~ARMAssembler()
@@ -184,13 +177,6 @@
     const char * const format = "generated %s (%d ins) at [%p:%p] in %lld ns\n";
     ALOGI(format, name, int(pc()-base()), base(), pc(), duration);
 
-#if defined(WITH_LIB_HARDWARE)
-    if (__builtin_expect(mQemuTracing, 0)) {
-        int err = qemu_add_mapping(uintptr_t(base()), name);
-        mQemuTracing = (err >= 0);
-    }
-#endif
-
     char value[PROPERTY_VALUE_MAX];
     property_get("debug.pf.disasm", value, "0");
     if (atoi(value) != 0) {
diff --git a/libpixelflinger/codeflinger/ARMAssembler.h b/libpixelflinger/codeflinger/ARMAssembler.h
index e0c7646..76acf7e 100644
--- a/libpixelflinger/codeflinger/ARMAssembler.h
+++ b/libpixelflinger/codeflinger/ARMAssembler.h
@@ -35,7 +35,7 @@
 class ARMAssembler : public ARMAssemblerInterface
 {
 public:
-                ARMAssembler(const sp<Assembly>& assembly);
+    explicit    ARMAssembler(const sp<Assembly>& assembly);
     virtual     ~ARMAssembler();
 
     uint32_t*   base() const;
@@ -167,9 +167,6 @@
     uint32_t*       mPC;
     uint32_t*       mPrologPC;
     int64_t         mDuration;
-#if defined(WITH_LIB_HARDWARE)
-    bool            mQemuTracing;
-#endif
     
     struct branch_target_t {
         inline branch_target_t() : label(0), pc(0) { }
diff --git a/libpixelflinger/codeflinger/ARMAssemblerInterface.cpp b/libpixelflinger/codeflinger/ARMAssemblerInterface.cpp
index 5041999..c96cf4b 100644
--- a/libpixelflinger/codeflinger/ARMAssemblerInterface.cpp
+++ b/libpixelflinger/codeflinger/ARMAssemblerInterface.cpp
@@ -2,26 +2,27 @@
 **
 ** 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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
-
+#define LOG_TAG "pixelflinger-code"
 
 #include <errno.h>
-#include <stdlib.h>
 #include <stdint.h>
+#include <stdlib.h>
 #include <sys/types.h>
 
-#include <cutils/log.h>
+#include <log/log.h>
+
 #include "ARMAssemblerInterface.h"
 
 namespace android {
diff --git a/libpixelflinger/codeflinger/ARMAssemblerProxy.h b/libpixelflinger/codeflinger/ARMAssemblerProxy.h
index b852794..10d0390 100644
--- a/libpixelflinger/codeflinger/ARMAssemblerProxy.h
+++ b/libpixelflinger/codeflinger/ARMAssemblerProxy.h
@@ -34,7 +34,7 @@
     // ARMAssemblerProxy take ownership of the target
 
                 ARMAssemblerProxy();
-                ARMAssemblerProxy(ARMAssemblerInterface* target);
+    explicit    ARMAssemblerProxy(ARMAssemblerInterface* target);
     virtual     ~ARMAssemblerProxy();
 
     void setTarget(ARMAssemblerInterface* target);
diff --git a/libpixelflinger/codeflinger/Arm64Assembler.cpp b/libpixelflinger/codeflinger/Arm64Assembler.cpp
index bd11818..bff87bb 100644
--- a/libpixelflinger/codeflinger/Arm64Assembler.cpp
+++ b/libpixelflinger/codeflinger/Arm64Assembler.cpp
@@ -32,14 +32,13 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <cutils/log.h>
 #include <cutils/properties.h>
+#include <log/log.h>
 #include <private/pixelflinger/ggl_context.h>
 
 #include "codeflinger/Arm64Assembler.h"
-#include "codeflinger/CodeCache.h"
 #include "codeflinger/Arm64Disassembler.h"
-
+#include "codeflinger/CodeCache.h"
 
 /*
 ** --------------------------------------------
diff --git a/libpixelflinger/codeflinger/Arm64Assembler.h b/libpixelflinger/codeflinger/Arm64Assembler.h
index c9be116..527c757 100644
--- a/libpixelflinger/codeflinger/Arm64Assembler.h
+++ b/libpixelflinger/codeflinger/Arm64Assembler.h
@@ -47,8 +47,8 @@
 class ArmToArm64Assembler : public ARMAssemblerInterface
 {
 public:
-                ArmToArm64Assembler(const sp<Assembly>& assembly);
-                ArmToArm64Assembler(void *base);
+    explicit    ArmToArm64Assembler(const sp<Assembly>& assembly);
+    explicit    ArmToArm64Assembler(void *base);
     virtual     ~ArmToArm64Assembler();
 
     uint32_t*   base() const;
diff --git a/libpixelflinger/codeflinger/CodeCache.cpp b/libpixelflinger/codeflinger/CodeCache.cpp
index 4b498c1..8516640 100644
--- a/libpixelflinger/codeflinger/CodeCache.cpp
+++ b/libpixelflinger/codeflinger/CodeCache.cpp
@@ -15,18 +15,16 @@
 ** limitations under the License.
 */
 
+#define LOG_TAG "CodeCache"
 
 #include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <unistd.h>
 #include <sys/mman.h>
+#include <unistd.h>
 
 #include <cutils/ashmem.h>
-#include <cutils/atomic.h>
-#define LOG_TAG "CodeCache"
-#include <cutils/log.h>
-
+#include <log/log.h>
 
 #include "CodeCache.h"
 
@@ -101,7 +99,7 @@
 }
 
 Assembly::Assembly(size_t size)
-    : mCount(1), mSize(0)
+    : mCount(0), mSize(0)
 {
     mBase = (uint32_t*)mspace_malloc(getMspace(), size);
     LOG_ALWAYS_FATAL_IF(mBase == NULL,
@@ -117,12 +115,12 @@
 
 void Assembly::incStrong(const void*) const
 {
-    android_atomic_inc(&mCount);
+    mCount.fetch_add(1, std::memory_order_relaxed);
 }
 
 void Assembly::decStrong(const void*) const
 {
-    if (android_atomic_dec(&mCount) == 1) {
+    if (mCount.fetch_sub(1, std::memory_order_acq_rel) == 1) {
         delete this;
     }
 }
diff --git a/libpixelflinger/codeflinger/CodeCache.h b/libpixelflinger/codeflinger/CodeCache.h
index 0fb6fd5..9326453 100644
--- a/libpixelflinger/codeflinger/CodeCache.h
+++ b/libpixelflinger/codeflinger/CodeCache.h
@@ -19,6 +19,7 @@
 #ifndef ANDROID_CODECACHE_H
 #define ANDROID_CODECACHE_H
 
+#include <atomic>
 #include <stdint.h>
 #include <pthread.h>
 #include <sys/types.h>
@@ -42,7 +43,7 @@
 class AssemblyKey : public AssemblyKeyBase
 {
 public:
-    AssemblyKey(const T& rhs) : mKey(rhs) { }
+    explicit AssemblyKey(const T& rhs) : mKey(rhs) { }
     virtual int compare_type(const AssemblyKeyBase& key) const {
         const T& rhs = static_cast<const AssemblyKey&>(key).mKey;
         return android::compare_type(mKey, rhs);
@@ -56,7 +57,7 @@
 class Assembly
 {
 public:
-                Assembly(size_t size);
+    explicit    Assembly(size_t size);
     virtual     ~Assembly();
 
     ssize_t     size() const;
@@ -69,7 +70,7 @@
     typedef void    weakref_type;
 
 private:
-    mutable int32_t     mCount;
+    mutable std::atomic<int32_t>     mCount;
             uint32_t*   mBase;
             size_t      mSize;
 };
@@ -80,13 +81,13 @@
 {
 public:
 // pretty simple cache API...
-                CodeCache(size_t size);
-                ~CodeCache();
-    
-            sp<Assembly>        lookup(const AssemblyKeyBase& key) const;
+    explicit            CodeCache(size_t size);
+                        ~CodeCache();
 
-            int                 cache(  const AssemblyKeyBase& key,
-                                        const sp<Assembly>& assembly);
+    sp<Assembly>        lookup(const AssemblyKeyBase& key) const;
+
+    int                 cache(const AssemblyKeyBase& key,
+                              const sp<Assembly>& assembly);
 
 private:
     // nothing to see here...
@@ -105,7 +106,7 @@
         const AssemblyKeyBase* mKey;
     public:
         key_t() { };
-        key_t(const AssemblyKeyBase& k) : mKey(&k)  { }
+        explicit key_t(const AssemblyKeyBase& k) : mKey(&k)  { }
     };
 
     mutable pthread_mutex_t             mLock;
diff --git a/libpixelflinger/codeflinger/GGLAssembler.cpp b/libpixelflinger/codeflinger/GGLAssembler.cpp
index 346779f..91fbd53 100644
--- a/libpixelflinger/codeflinger/GGLAssembler.cpp
+++ b/libpixelflinger/codeflinger/GGLAssembler.cpp
@@ -2,16 +2,16 @@
 **
 ** 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 
+** 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 
+**     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 
+** 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.
 */
 
@@ -19,10 +19,11 @@
 
 #include <assert.h>
 #include <stdint.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <sys/types.h>
-#include <cutils/log.h>
+
+#include <log/log.h>
 
 #include "GGLAssembler.h"
 
diff --git a/libpixelflinger/codeflinger/GGLAssembler.h b/libpixelflinger/codeflinger/GGLAssembler.h
index 9db20df..47dbf3a 100644
--- a/libpixelflinger/codeflinger/GGLAssembler.h
+++ b/libpixelflinger/codeflinger/GGLAssembler.h
@@ -49,7 +49,7 @@
 public:
     class RegisterFile;
     
-                    RegisterAllocator(int arch);
+                    RegisterAllocator(int arch);  // NOLINT, implicit
     RegisterFile&   registerFile();
     int             reserveReg(int reg);
     int             obtainReg();
@@ -59,7 +59,7 @@
     class RegisterFile
     {
     public:
-                            RegisterFile(int arch);
+                            RegisterFile(int arch);  // NOLINT, implicit
                             RegisterFile(const RegisterFile& rhs, int arch);
                             ~RegisterFile();
 
@@ -101,7 +101,7 @@
     class Scratch
     {
     public:
-            Scratch(RegisterFile& regFile)
+            explicit Scratch(RegisterFile& regFile)
                 : mRegFile(regFile), mScratch(0) { 
             }
             ~Scratch() {
@@ -177,8 +177,8 @@
 {
 public:
 
-                    GGLAssembler(ARMAssemblerInterface* target);
-        virtual     ~GGLAssembler();
+    explicit    GGLAssembler(ARMAssemblerInterface* target);
+    virtual     ~GGLAssembler();
 
     uint32_t*   base() const { return 0; } // XXX
     uint32_t*   pc() const { return 0; } // XXX
@@ -206,7 +206,7 @@
         struct reg_t {
             reg_t() : reg(-1), flags(0) {
             }
-            reg_t(int r, int f=0)
+            reg_t(int r, int f=0)  // NOLINT, implicit
                 : reg(r), flags(f) {
             }
             void setTo(int r, int f=0) {
@@ -219,7 +219,7 @@
         struct integer_t : public reg_t {
             integer_t() : reg_t(), s(0) {
             }
-            integer_t(int r, int sz=32, int f=0)
+            integer_t(int r, int sz=32, int f=0)  // NOLINT, implicit
                 : reg_t(r, f), s(sz) {
             }
             void setTo(int r, int sz=32, int f=0) {
@@ -251,7 +251,7 @@
         struct component_t : public reg_t {
             component_t() : reg_t(), h(0), l(0) {
             }
-            component_t(int r, int f=0)
+            component_t(int r, int f=0)  // NOLINT, implicit
                 : reg_t(r, f), h(0), l(0) {
             }
             component_t(int r, int lo, int hi, int f=0)
@@ -288,6 +288,14 @@
 
 
 private:
+    // GGLAssembler hides RegisterAllocator's and ARMAssemblerProxy's reset
+    // methods by providing a reset method with a different parameter set. The
+    // intent of GGLAssembler's reset method is to wrap the inherited reset
+    // methods, so make these methods private in order to prevent direct calls
+    // to these methods from clients.
+    using RegisterAllocator::reset;
+    using ARMAssemblerProxy::reset;
+
     struct tex_coord_t {
         reg_t       s;
         reg_t       t;
diff --git a/libpixelflinger/codeflinger/MIPS64Assembler.cpp b/libpixelflinger/codeflinger/MIPS64Assembler.cpp
index 672040b..d5e4cea 100644
--- a/libpixelflinger/codeflinger/MIPS64Assembler.cpp
+++ b/libpixelflinger/codeflinger/MIPS64Assembler.cpp
@@ -25,28 +25,21 @@
 **
 */
 
-
 #define LOG_TAG "MIPS64Assembler"
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <cutils/log.h>
+
 #include <cutils/properties.h>
-
-#if defined(WITH_LIB_HARDWARE)
-#include <hardware_legacy/qemu_tracing.h>
-#endif
-
+#include <log/log.h>
 #include <private/pixelflinger/ggl_context.h>
 
 #include "MIPS64Assembler.h"
 #include "CodeCache.h"
 #include "mips64_disassem.h"
 
-
 #define NOT_IMPLEMENTED()  LOG_ALWAYS_FATAL("Arm instruction %s not yet implemented\n", __func__)
 
-
 // ----------------------------------------------------------------------------
 
 namespace android {
diff --git a/libpixelflinger/codeflinger/MIPSAssembler.cpp b/libpixelflinger/codeflinger/MIPSAssembler.cpp
index 5497fae..865a568 100644
--- a/libpixelflinger/codeflinger/MIPSAssembler.cpp
+++ b/libpixelflinger/codeflinger/MIPSAssembler.cpp
@@ -47,22 +47,17 @@
 ** functions in ARMAssemblerInterface.cpp so they could be used as static initializers).
 */
 
-
 #define LOG_TAG "MIPSAssembler"
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <cutils/log.h>
+
 #include <cutils/properties.h>
-
-#if defined(WITH_LIB_HARDWARE)
-#include <hardware_legacy/qemu_tracing.h>
-#endif
-
+#include <log/log.h>
 #include <private/pixelflinger/ggl_context.h>
 
-#include "MIPSAssembler.h"
 #include "CodeCache.h"
+#include "MIPSAssembler.h"
 #include "mips_disassem.h"
 
 // Choose MIPS arch variant following gcc flags
@@ -1411,13 +1406,6 @@
     const char * const format = "generated %s (%d ins) at [%p:%p] in %lld ns\n";
     ALOGI(format, name, int(pc()-base()), base(), pc(), duration);
 
-#if defined(WITH_LIB_HARDWARE)
-    if (__builtin_expect(mQemuTracing, 0)) {
-        int err = qemu_add_mapping(uintptr_t(base()), name);
-        mQemuTracing = (err >= 0);
-    }
-#endif
-
     char value[PROPERTY_VALUE_MAX];
     value[0] = '\0';
 
diff --git a/libpixelflinger/codeflinger/MIPSAssembler.h b/libpixelflinger/codeflinger/MIPSAssembler.h
index b53fefb..c1178b6 100644
--- a/libpixelflinger/codeflinger/MIPSAssembler.h
+++ b/libpixelflinger/codeflinger/MIPSAssembler.h
@@ -410,9 +410,6 @@
     uint32_t*       mPC;
     uint32_t*       mPrologPC;
     int64_t         mDuration;
-#if defined(WITH_LIB_HARDWARE)
-    bool            mQemuTracing;
-#endif
 
     struct branch_target_t {
         inline branch_target_t() : label(0), pc(0) { }
diff --git a/libpixelflinger/codeflinger/blending.cpp b/libpixelflinger/codeflinger/blending.cpp
index b20219c..a55dfe3 100644
--- a/libpixelflinger/codeflinger/blending.cpp
+++ b/libpixelflinger/codeflinger/blending.cpp
@@ -2,30 +2,31 @@
 **
 ** 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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
+#define LOG_TAG "pixelflinger-code"
+
 #include <assert.h>
 #include <stdint.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <sys/types.h>
 
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include "GGLAssembler.h"
 
-
 namespace android {
 
 void GGLAssembler::build_fog(
diff --git a/libpixelflinger/codeflinger/disassem.c b/libpixelflinger/codeflinger/disassem.c
index 39dd614..5cbd63d 100644
--- a/libpixelflinger/codeflinger/disassem.c
+++ b/libpixelflinger/codeflinger/disassem.c
@@ -279,14 +279,14 @@
 	"4.0", "5.0", "0.5", "10.0"
 };
 
-#define insn_condition(x)	arm32_insn_conditions[(x >> 28) & 0x0f]
-#define insn_blktrans(x)	insn_block_transfers[(x >> 23) & 3]
-#define insn_stkblktrans(x)	insn_stack_block_transfers[(3*((x >> 20)&1))^((x >> 23)&3)]
-#define op2_shift(x)		op_shifts[(x >> 5) & 3]
-#define insn_fparnd(x)		insn_fpa_rounding[(x >> 5) & 0x03]
-#define insn_fpaprec(x)		insn_fpa_precision[(((x >> 18) & 2)|(x >> 7)) & 1]
-#define insn_fpaprect(x)	insn_fpa_precision[(((x >> 21) & 2)|(x >> 15)) & 1]
-#define insn_fpaimm(x)		insn_fpaconstants[x & 0x07]
+#define insn_condition(x)	arm32_insn_conditions[((x) >> 28) & 0x0f]
+#define insn_blktrans(x)	insn_block_transfers[((x) >> 23) & 3]
+#define insn_stkblktrans(x)	insn_stack_block_transfers[(3*(((x) >> 20)&1))^(((x) >> 23)&3)]
+#define op2_shift(x)		op_shifts[((x) >> 5) & 3]
+#define insn_fparnd(x)		insn_fpa_rounding[((x) >> 5) & 0x03]
+#define insn_fpaprec(x)		insn_fpa_precision[((((x) >> 18) & 2)|((x) >> 7)) & 1]
+#define insn_fpaprect(x)	insn_fpa_precision[((((x) >> 21) & 2)|((x) >> 15)) & 1]
+#define insn_fpaimm(x)		insn_fpaconstants[(x) & 0x07]
 
 /* Local prototypes */
 static void disasm_register_shift(const disasm_interface_t *di, u_int insn);
diff --git a/libpixelflinger/codeflinger/load_store.cpp b/libpixelflinger/codeflinger/load_store.cpp
index e5a1ae0..da21e1d 100644
--- a/libpixelflinger/codeflinger/load_store.cpp
+++ b/libpixelflinger/codeflinger/load_store.cpp
@@ -2,22 +2,26 @@
 **
 ** 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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
+#define LOG_TAG "pixelflinger-code"
+
 #include <assert.h>
 #include <stdio.h>
-#include <cutils/log.h>
+
+#include <log/log.h>
+
 #include "GGLAssembler.h"
 
 namespace android {
@@ -25,7 +29,7 @@
 // ----------------------------------------------------------------------------
 
 void GGLAssembler::store(const pointer_t& addr, const pixel_t& s, uint32_t flags)
-{    
+{
     const int bits = addr.size;
     const int inc = (flags & WRITE_BACK)?1:0;
     switch (bits) {
@@ -59,8 +63,8 @@
 }
 
 void GGLAssembler::load(const pointer_t& addr, const pixel_t& s, uint32_t flags)
-{    
-    Scratch scratches(registerFile());    
+{
+    Scratch scratches(registerFile());
     int s0;
 
     const int bits = addr.size;
@@ -72,7 +76,7 @@
         break;
     case 24:
         // 24 bits formats are a little special and used only for RGB
-        // R,G,B is packed as 0x00BBGGRR 
+        // R,G,B is packed as 0x00BBGGRR
         s0 = scratches.obtain();
         if (s.reg != addr.reg) {
             LDRB(AL, s.reg, addr.reg, immed12_pre(0));      // R
@@ -90,7 +94,7 @@
         }
         if (inc)
             ADD(AL, 0, addr.reg, addr.reg, imm(3));
-        break;        
+        break;
     case 16:
         if (inc)    LDRH(AL, s.reg, addr.reg, immed8_post(2));
         else        LDRH(AL, s.reg, addr.reg);
@@ -112,7 +116,7 @@
     assert(maskLen<=8);
 #endif
     assert(h);
-    
+
     if (h != bits) {
         const int mask = ((1<<maskLen)-1) << l;
         if (isValidImmediate(mask)) {
@@ -126,12 +130,12 @@
         }
         s = d.reg;
     }
-    
+
     if (l) {
         MOV(AL, 0, d.reg, reg_imm(s, LSR, l));  // component = packed >> l;
         s = d.reg;
     }
-    
+
     if (s != d.reg) {
         MOV(AL, 0, d.reg, s);
     }
@@ -212,12 +216,12 @@
         } while(dbits>0);
         return;
     }
-    
+
     dbits -= sbits;
     do {
         ORR(AL, 0, d, s, reg_imm(s, LSL, sbits));
             // d |= d<<sbits;
-        s = d;        
+        s = d;
         dbits -= sbits;
         if (sbits*2 < dbits) {
             sbits *= 2;
@@ -241,14 +245,14 @@
     int dl = d.format.c[component].l;
     int dbits = dh - dl;
     int dithering = 0;
-    
+
     ALOGE_IF(sbits<dbits, "sbits (%d) < dbits (%d) in downshift", sbits, dbits);
 
     if (sbits>dbits) {
         // see if we need to dither
         dithering = mDithering;
     }
-    
+
     int ireg = d.reg;
     if (!(d.flags & FIRST)) {
         if (s.flags & CORRUPTIBLE)  {
@@ -271,7 +275,7 @@
                 if (isValidImmediate(mask) || isValidImmediate(~mask)) {
                     build_and_immediate(ireg, s.reg, mask, 32);
                     sl = offset;
-                    s.reg = ireg; 
+                    s.reg = ireg;
                     sbits = dbits;
                     maskLoBits = maskHiBits = 0;
                 }
@@ -281,7 +285,7 @@
             const uint32_t mask = ((1<<sbits)-1) << sl;
             if (isValidImmediate(mask) || isValidImmediate(~mask)) {
                 build_and_immediate(ireg, s.reg, mask, 32);
-                s.reg = ireg; 
+                s.reg = ireg;
                 maskLoBits = maskHiBits = 0;
             }
         }
@@ -325,7 +329,7 @@
             MOV(AL, 0, ireg, reg_imm(s.reg, LSR, sl));
             sh -= sl;
             sl = 0;
-            s.reg = ireg; 
+            s.reg = ireg;
         }
         // scaling (V-V>>dbits)
         SUB(AL, 0, ireg, s.reg, reg_imm(s.reg, LSR, dbits));
@@ -333,7 +337,7 @@
         if (shift>0)        ADD(AL, 0, ireg, ireg, reg_imm(dither.reg, LSR, shift));
         else if (shift<0)   ADD(AL, 0, ireg, ireg, reg_imm(dither.reg, LSL,-shift));
         else                ADD(AL, 0, ireg, ireg, dither.reg);
-        s.reg = ireg; 
+        s.reg = ireg;
     }
 
     if ((maskLoBits|dithering) && (sh > dbits)) {
diff --git a/libpixelflinger/codeflinger/mips64_disassem.c b/libpixelflinger/codeflinger/mips64_disassem.c
index 44b7fe7..f28d726 100644
--- a/libpixelflinger/codeflinger/mips64_disassem.c
+++ b/libpixelflinger/codeflinger/mips64_disassem.c
@@ -34,21 +34,20 @@
  *  from: @(#)kadb.c    8.1 (Berkeley) 6/10/93
  */
 
-#include <stdio.h>
-#include <stdint.h>
 #include <stdarg.h>
 #include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
 #include <sys/cdefs.h>
-
 #include <sys/types.h>
-#include "mips_opcode.h"
 
-#include <cutils/log.h>
+#include <android/log.h>
+
+#include "mips_opcode.h"
 
 static char *sprintf_buffer;
 static int sprintf_buf_len;
 
-
 typedef uint64_t db_addr_t;
 static void db_printf(const char* fmt, ...);
 
diff --git a/libpixelflinger/codeflinger/texturing.cpp b/libpixelflinger/codeflinger/texturing.cpp
index 29a3742..4c357af 100644
--- a/libpixelflinger/codeflinger/texturing.cpp
+++ b/libpixelflinger/codeflinger/texturing.cpp
@@ -2,26 +2,28 @@
 **
 ** 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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
+#define LOG_TAG "pixelflinger-code"
+
 #include <assert.h>
 #include <stdint.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <sys/types.h>
 
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include "GGLAssembler.h"
 
diff --git a/libpixelflinger/codeflinger/tinyutils/smartpointer.h b/libpixelflinger/codeflinger/tinyutils/smartpointer.h
index 9d0a16e..23a5f7e 100644
--- a/libpixelflinger/codeflinger/tinyutils/smartpointer.h
+++ b/libpixelflinger/codeflinger/tinyutils/smartpointer.h
@@ -51,10 +51,10 @@
 public:
     inline sp() : m_ptr(0) { }
 
-    sp(T* other);
+    sp(T* other);  // NOLINT, implicit
     sp(const sp<T>& other);
-    template<typename U> sp(U* other);
-    template<typename U> sp(const sp<U>& other);
+    template<typename U> sp(U* other);  // NOLINT, implicit
+    template<typename U> sp(const sp<U>& other);  // NOLINT, implicit
 
     ~sp();
     
diff --git a/libpixelflinger/col32cb16blend.S b/libpixelflinger/col32cb16blend.S
index 1831255..39f94e1 100644
--- a/libpixelflinger/col32cb16blend.S
+++ b/libpixelflinger/col32cb16blend.S
@@ -16,7 +16,7 @@
  */
 
     .text
-    .align
+    .balign 4
 
     .global scanline_col32cb16blend_arm
 
diff --git a/libpixelflinger/col32cb16blend_neon.S b/libpixelflinger/col32cb16blend_neon.S
index cbd54d1..7ad34b0 100644
--- a/libpixelflinger/col32cb16blend_neon.S
+++ b/libpixelflinger/col32cb16blend_neon.S
@@ -17,7 +17,7 @@
 
 
     .text
-    .align
+    .balign 4
 
     .global scanline_col32cb16blend_neon
 
diff --git a/libpixelflinger/include/private/pixelflinger/ggl_context.h b/libpixelflinger/include/private/pixelflinger/ggl_context.h
index d45dabc..563b0f1 100644
--- a/libpixelflinger/include/private/pixelflinger/ggl_context.h
+++ b/libpixelflinger/include/private/pixelflinger/ggl_context.h
@@ -120,7 +120,7 @@
 template<bool> struct CTA;
 template<> struct CTA<true> { };
 
-#define GGL_CONTEXT(con, c)         context_t *con = static_cast<context_t *>(c)
+#define GGL_CONTEXT(con, c)         context_t *(con) = static_cast<context_t *>(c) /* NOLINT */
 #define GGL_OFFSETOF(field)         uintptr_t(&(((context_t*)0)->field))
 #define GGL_INIT_PROC(p, f)         p.f = ggl_ ## f;
 #define GGL_BETWEEN(x, L, H)        (uint32_t((x)-(L)) <= ((H)-(L)))
@@ -136,14 +136,14 @@
 // ----------------------------------------------------------------------------
 
 #define GGL_RESERVE_NEEDS(name, l, s)                               \
-    const uint32_t  GGL_NEEDS_##name##_MASK = (((1LU<<(s))-1)<<l);  \
+    const uint32_t  GGL_NEEDS_##name##_MASK = (((1LU<<(s))-1)<<(l));  \
     const uint32_t  GGL_NEEDS_##name##_SHIFT = (l);
 
 #define GGL_BUILD_NEEDS(val, name)                                  \
     (((val)<<(GGL_NEEDS_##name##_SHIFT)) & GGL_NEEDS_##name##_MASK)
 
 #define GGL_READ_NEEDS(name, n)                                     \
-    (uint32_t(n & GGL_NEEDS_##name##_MASK) >> GGL_NEEDS_##name##_SHIFT)
+    (uint32_t((n) & GGL_NEEDS_##name##_MASK) >> GGL_NEEDS_##name##_SHIFT)
 
 #define GGL_NEED_MASK(name)     (uint32_t(GGL_NEEDS_##name##_MASK))
 #define GGL_NEED(name, val)     GGL_BUILD_NEEDS(val, name)
diff --git a/libpixelflinger/rotate90CW_4x4_16v6.S b/libpixelflinger/rotate90CW_4x4_16v6.S
deleted file mode 100644
index 8e3e142..0000000
--- a/libpixelflinger/rotate90CW_4x4_16v6.S
+++ /dev/null
@@ -1,62 +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.
-*/
-
-
-    .text
-    .align
-    
-    .global rotate90CW_4x4_16v6
-
-// Rotates 90deg CW a 4x4 block of 16bpp pixels using ARMv6
-// src and dst must be 4 pixels-aligned (2-pixels aligned might
-// actually work)
-//
-// The code below is complicated by ARM's little endianness. 
-
-rotate90CW_4x4_16v6:
-    // r0 = dst
-    // r1 = src
-    // r2 = dst stride in pixels
-    // r3 = src stride in pixels
-
-    stmfd   sp!, {r4,r5, r6,r7, r8,r9, r10,r11, lr}
-    add     r14, r3, r3
-    add     r12, r2, r2
-
-    ldrd    r2, r3, [r1], r14
-    ldrd    r4, r5, [r1], r14
-    ldrd    r6, r7, [r1], r14
-    ldrd    r8, r9, [r1]
-
-    pkhbt   r10, r8, r6, lsl #16
-    pkhbt   r11, r4, r2, lsl #16
-    strd    r10, r11, [r0], r12  
-
-    pkhtb   r10, r6, r8, asr #16
-    pkhtb   r11, r2, r4, asr #16
-
-    strd    r10, r11, [r0], r12  
-    pkhbt   r10, r9, r7, lsl #16
-    pkhbt   r11, r5, r3, lsl #16
-
-    strd    r10, r11, [r0], r12  
-
-    pkhtb   r10, r7, r9, asr #16
-    pkhtb   r11, r3, r5, asr #16
-    strd    r10, r11, [r0]
-
-    ldmfd   sp!, {r4,r5, r6,r7, r8,r9, r10,r11, pc}
diff --git a/libpixelflinger/scanline.cpp b/libpixelflinger/scanline.cpp
index a718b02..c6cf5bf 100644
--- a/libpixelflinger/scanline.cpp
+++ b/libpixelflinger/scanline.cpp
@@ -2,33 +2,28 @@
 **
 ** Copyright 2006-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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
-
 #define LOG_TAG "pixelflinger"
 
 #include <assert.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
 
 #include <cutils/memory.h>
-#include <cutils/log.h>
-
-#ifdef __arm__
-#include <machine/cpu-features.h>
-#endif
+#include <log/log.h>
 
 #include "buffer.h"
 #include "scanline.h"
@@ -965,7 +960,7 @@
  * Use only for one-to-one texture mapping.
  */
 struct horz_iterator32 {
-    horz_iterator32(context_t* c) {
+    explicit horz_iterator32(context_t* c) {
         const int x = c->iterators.xl;
         const int y = c->iterators.y;
         texture_t& tx = c->state.texture[0];
@@ -982,7 +977,7 @@
 
 /* A variant for 16-bit source textures. */
 struct horz_iterator16 {
-    horz_iterator16(context_t* c) {
+    explicit horz_iterator16(context_t* c) {
         const int x = c->iterators.xl;
         const int y = c->iterators.y;
         texture_t& tx = c->state.texture[0];
@@ -1002,7 +997,7 @@
  * texture pixel value.
  */
 struct clamp_iterator {
-    clamp_iterator(context_t* c) {
+    explicit clamp_iterator(context_t* c) {
         const int xs = c->iterators.xl;
         texture_t& tx = c->state.texture[0];
         texture_iterators_t& ti = tx.iterators;
@@ -1112,13 +1107,13 @@
 }
 
 struct horz_clamp_iterator16 : horz_clamp_iterator {
-    horz_clamp_iterator16(const context_t* c) {
+    explicit horz_clamp_iterator16(const context_t* c) {
         init(c,1);
     };
 };
 
 struct horz_clamp_iterator32 : horz_clamp_iterator {
-    horz_clamp_iterator32(context_t* c) {
+    explicit horz_clamp_iterator32(context_t* c) {
         init(c,2);
     };
 };
@@ -1126,7 +1121,7 @@
 /* This is used to perform dithering operations.
  */
 struct ditherer {
-    ditherer(const context_t* c) {
+    explicit ditherer(const context_t* c) {
         const int x = c->iterators.xl;
         const int y = c->iterators.y;
         m_line = &c->ditherMatrix[ ((y & GGL_DITHER_MASK)<<GGL_DITHER_ORDER_SHIFT) ];
@@ -1172,7 +1167,7 @@
  *   blender.blend(<32-bit-src-pixel-value>,<ptr-to-16-bit-dest-pixel>)
  */
 struct blender_32to16 {
-    blender_32to16(context_t* /*c*/) { }
+    explicit blender_32to16(context_t* /*c*/) { }
     void write(uint32_t s, uint16_t* dst) {
         if (s == 0)
             return;
@@ -1229,7 +1224,7 @@
  * where dstFactor=srcA*(1-srcA) srcFactor=srcA
  */
 struct blender_32to16_srcA {
-    blender_32to16_srcA(const context_t* /*c*/) { }
+    explicit blender_32to16_srcA(const context_t* /*c*/) { }
     void write(uint32_t s, uint16_t* dst) {
         if (!s) {
             return;
@@ -1271,7 +1266,7 @@
 /* This blender does a normal blend after modulation.
  */
 struct blender_32to16_modulate : blender_modulate {
-    blender_32to16_modulate(const context_t* c) {
+    explicit blender_32to16_modulate(const context_t* c) {
         init(c);
     }
     void write(uint32_t s, uint16_t* dst) {
@@ -1343,7 +1338,7 @@
 
 /* same as 32to16_modulate, except that the input is xRGB, instead of ARGB */
 struct blender_x32to16_modulate : blender_modulate {
-    blender_x32to16_modulate(const context_t* c) {
+    explicit blender_x32to16_modulate(const context_t* c) {
         init(c);
     }
     void write(uint32_t s, uint16_t* dst) {
@@ -1398,7 +1393,7 @@
 
 /* Same as above, but source is 16bit rgb565 */
 struct blender_16to16_modulate : blender_modulate {
-    blender_16to16_modulate(const context_t* c) {
+    explicit blender_16to16_modulate(const context_t* c) {
         init(c);
     }
     void write(uint16_t s16, uint16_t* dst) {
@@ -1434,7 +1429,7 @@
  *   }
  */
 struct dst_iterator16 {
-    dst_iterator16(const context_t* c) {
+    explicit dst_iterator16(const context_t* c) {
         const int x = c->iterators.xl;
         const int width = c->iterators.xr - x;
         const int32_t y = c->iterators.y;
diff --git a/libpixelflinger/t32cb16blend.S b/libpixelflinger/t32cb16blend.S
index 1d40ad4..5e4995a 100644
--- a/libpixelflinger/t32cb16blend.S
+++ b/libpixelflinger/t32cb16blend.S
@@ -18,7 +18,7 @@
 
 	.text
 	.syntax unified
-	.align
+	.balign 4
 	
 	.global scanline_t32cb16blend_arm
 
diff --git a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
index 5f58797..63642c4 100644
--- a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
+++ b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
@@ -34,7 +34,6 @@
 
 #include <sys/mman.h>
 #include <cutils/ashmem.h>
-#include <cutils/atomic.h>
 
 #define __STDC_FORMAT_MACROS
 #include <inttypes.h>
diff --git a/libpixelflinger/tests/arch-arm64/assembler/asm_test_jacket.S b/libpixelflinger/tests/arch-arm64/assembler/asm_test_jacket.S
index f44859f..3f900f8 100644
--- a/libpixelflinger/tests/arch-arm64/assembler/asm_test_jacket.S
+++ b/libpixelflinger/tests/arch-arm64/assembler/asm_test_jacket.S
@@ -27,7 +27,7 @@
  */
 
     .text
-    .align 0
+    .balign 0
 
     .global asm_test_jacket
 
diff --git a/libpixelflinger/tests/arch-mips64/assembler/asm_mips_test_jacket.S b/libpixelflinger/tests/arch-mips64/assembler/asm_mips_test_jacket.S
index 8a7f742..705ee9b 100644
--- a/libpixelflinger/tests/arch-mips64/assembler/asm_mips_test_jacket.S
+++ b/libpixelflinger/tests/arch-mips64/assembler/asm_mips_test_jacket.S
@@ -27,7 +27,7 @@
 #  */
 
     .text
-    .align 8
+    .balign 8
 
     .global asm_mips_test_jacket
 
diff --git a/libpixelflinger/tests/arch-mips64/assembler/mips64_assembler_test.cpp b/libpixelflinger/tests/arch-mips64/assembler/mips64_assembler_test.cpp
index b680b60..9fb0a28 100644
--- a/libpixelflinger/tests/arch-mips64/assembler/mips64_assembler_test.cpp
+++ b/libpixelflinger/tests/arch-mips64/assembler/mips64_assembler_test.cpp
@@ -26,22 +26,21 @@
  * SUCH DAMAGE.
  */
 
+#include <errno.h>
+#define __STDC_FORMAT_MACROS
+#include <inttypes.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <errno.h>
-
 #include <sys/mman.h>
-#include <cutils/ashmem.h>
-#include <cutils/atomic.h>
-#include <cutils/log.h>
+#include <unistd.h>
 
-#define __STDC_FORMAT_MACROS
-#include <inttypes.h>
+#include <android/log.h>
+#include <cutils/ashmem.h>
 
 #include "codeflinger/ARMAssemblerInterface.h"
 #include "codeflinger/MIPS64Assembler.h"
+
 using namespace android;
 
 #define TESTS_DATAOP_ENABLE             1
diff --git a/libpixelflinger/trap.cpp b/libpixelflinger/trap.cpp
index ea53625..234bfdd 100644
--- a/libpixelflinger/trap.cpp
+++ b/libpixelflinger/trap.cpp
@@ -2,29 +2,31 @@
 **
 ** 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 
+** 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 
+**     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 
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
+#define LOG_TAG "pixelflinger-trap"
+
 #include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 
+#include <cutils/memory.h>
+#include <log/log.h>
+
 #include "trap.h"
 #include "picker.h"
 
-#include <cutils/log.h>
-#include <cutils/memory.h>
-
 namespace android {
 
 // ----------------------------------------------------------------------------
diff --git a/libprocessgroup/Android.mk b/libprocessgroup/Android.mk
index 1885fa5..0bfc391 100644
--- a/libprocessgroup/Android.mk
+++ b/libprocessgroup/Android.mk
@@ -3,7 +3,16 @@
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := processgroup.cpp
 LOCAL_MODULE := libprocessgroup
-LOCAL_SHARED_LIBRARIES := liblog libutils
+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
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 1bc1659..1572cb3 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -22,21 +22,24 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
-#include <mutex>
-#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#include <log/log.h>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <thread>
+
+#include <android-base/logging.h>
 #include <private/android_filesystem_config.h>
 
-#include <utils/SystemClock.h>
-
 #include <processgroup/processgroup.h>
 
+using namespace std::chrono_literals;
+
 // Uncomment line below use memory cgroups for keeping track of (forked) PIDs
 // #define USE_MEMCG 1
 
@@ -112,7 +115,7 @@
     int fd = open(path, O_RDONLY);
     if (fd < 0) {
         ret = -errno;
-        SLOGW("failed to open %s: %s", path, strerror(errno));
+        PLOG(WARNING) << "failed to open " << path;
         return ret;
     }
 
@@ -121,7 +124,7 @@
     ctx->buf_len = 0;
     ctx->initialized = true;
 
-    SLOGV("Initialized context for %s", path);
+    LOG(VERBOSE) << "Initialized context for " << path;
 
     return 0;
 }
@@ -141,7 +144,7 @@
 
     ctx->buf_len += ret;
     ctx->buf[ctx->buf_len] = 0;
-    SLOGV("Read %zd to buffer: %s", ret, ctx->buf);
+    LOG(VERBOSE) << "Read " << ret << " to buffer: " << ctx->buf;
 
     assert(ctx->buf_len <= sizeof(ctx->buf));
 
@@ -201,11 +204,10 @@
 
 static void removeUidProcessGroups(const char *uid_path)
 {
-    DIR *uid = opendir(uid_path);
+    std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path), closedir);
     if (uid != NULL) {
-        struct dirent cur;
-        struct dirent *dir;
-        while ((readdir_r(uid, &cur, &dir) == 0) && dir) {
+        dirent* dir;
+        while ((dir = readdir(uid.get())) != nullptr) {
             char path[PROCESSGROUP_MAX_PATH_LEN];
 
             if (dir->d_type != DT_DIR) {
@@ -217,24 +219,22 @@
             }
 
             snprintf(path, sizeof(path), "%s/%s", uid_path, dir->d_name);
-            SLOGV("removing %s\n", path);
-            rmdir(path);
+            LOG(VERBOSE) << "removing " << path;
+            if (rmdir(path) == -1) PLOG(WARNING) << "failed to remove " << path;
         }
-        closedir(uid);
     }
 }
 
 void removeAllProcessGroups()
 {
-    SLOGV("removeAllProcessGroups()");
-    const char *cgroup_root_path = getCgroupRootPath();
-    DIR *root = opendir(cgroup_root_path);
+    LOG(VERBOSE) << "removeAllProcessGroups()";
+    const char* cgroup_root_path = getCgroupRootPath();
+    std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path), closedir);
     if (root == NULL) {
-        SLOGE("failed to open %s: %s", cgroup_root_path, strerror(errno));
+        PLOG(ERROR) << "failed to open " << cgroup_root_path;
     } else {
-        struct dirent cur;
-        struct dirent *dir;
-        while ((readdir_r(root, &cur, &dir) == 0) && dir) {
+        dirent* dir;
+        while ((dir = readdir(root.get())) != nullptr) {
             char path[PROCESSGROUP_MAX_PATH_LEN];
 
             if (dir->d_type != DT_DIR) {
@@ -246,15 +246,13 @@
 
             snprintf(path, sizeof(path), "%s/%s", cgroup_root_path, dir->d_name);
             removeUidProcessGroups(path);
-            SLOGV("removing %s\n", path);
-            rmdir(path);
+            LOG(VERBOSE) << "removing " << path;
+            if (rmdir(path) == -1) PLOG(WARNING) << "failed to remove " << path;
         }
-        closedir(root);
     }
 }
 
-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;
@@ -266,19 +264,13 @@
         if (pid == 0) {
             // Should never happen...  but if it does, trying to kill this
             // will boomerang right back and kill us!  Let's not let that happen.
-            SLOGW("Yikes, we've been told to kill pid 0!  How about we don't do that.");
+            LOG(WARNING) << "Yikes, we've been told to kill pid 0!  How about we don't do that?";
             continue;
         }
-        if (pid != initialPid) {
-            // We want to be noisy about killing processes so we can understand
-            // what is going on in the log; however, don't be noisy about the base
-            // process, since that it something we always kill, and we have already
-            // logged elsewhere about killing it.
-            SLOGI("Killing pid %d in uid %d as part of process group %d", pid, uid, initialPid);
-        }
-        int ret = kill(pid, signal);
-        if (ret == -1) {
-            SLOGW("failed to kill pid %d: %s", pid, strerror(errno));
+        LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid
+                     << " as part of process group " << initialPid;
+        if (kill(pid, signal) == -1) {
+            PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
         }
     }
 
@@ -289,27 +281,27 @@
     return processes;
 }
 
-int killProcessGroup(uid_t uid, int initialPid, int signal)
-{
-    int processes;
-    const int sleep_us = 5 * 1000;  // 5ms
-    int64_t startTime = android::uptimeMillis();
-    int retry = 40;
+static int killProcessGroup(uid_t uid, int initialPid, int signal, int retry) {
+    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
 
-    while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) {
-        SLOGV("killed %d processes for processgroup %d\n", processes, initialPid);
+    int processes;
+    while ((processes = doKillProcessGroupOnce(uid, initialPid, signal)) > 0) {
+        LOG(VERBOSE) << "killed " << processes << " processes for processgroup " << initialPid;
         if (retry > 0) {
-            usleep(sleep_us);
+            std::this_thread::sleep_for(5ms);
             --retry;
         } else {
-            SLOGE("failed to kill %d processes for processgroup %d\n",
-                    processes, initialPid);
+            LOG(ERROR) << "failed to kill " << processes << " processes for processgroup "
+                       << initialPid;
             break;
         }
     }
 
-    SLOGV("Killed process group uid %d pid %d in %" PRId64 "ms, %d procs remain", uid, initialPid,
-            android::uptimeMillis()-startTime, processes);
+    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
+
+    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
+    LOG(VERBOSE) << "Killed process group uid " << uid << " pid " << initialPid << " in "
+                 << static_cast<int>(ms) << "ms, " << processes << " procs remain";
 
     if (processes == 0) {
         return removeProcessGroup(uid, initialPid);
@@ -318,67 +310,66 @@
     }
 }
 
-static int mkdirAndChown(const char *path, mode_t mode, uid_t uid, gid_t gid)
+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)
 {
-    int ret;
-
-    ret = mkdir(path, mode);
-    if (ret < 0 && errno != EEXIST) {
-        return -errno;
+    if (mkdir(path, mode) == -1 && errno != EEXIST) {
+        return false;
     }
 
-    ret = chown(path, uid, gid);
-    if (ret < 0) {
-        ret = -errno;
+    if (chown(path, uid, gid) == -1) {
+        int saved_errno = errno;
         rmdir(path);
-        return ret;
+        errno = saved_errno;
+        return false;
     }
 
-    return 0;
+    return true;
 }
 
 int createProcessGroup(uid_t uid, int initialPid)
 {
     char path[PROCESSGROUP_MAX_PATH_LEN] = {0};
-    int ret;
 
     convertUidToPath(path, sizeof(path), uid);
 
-    ret = mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM);
-    if (ret < 0) {
-        SLOGE("failed to make and chown %s: %s", path, strerror(-ret));
-        return ret;
+    if (!mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM)) {
+        PLOG(ERROR) << "failed to make and chown " << path;
+        return -errno;
     }
 
     convertUidPidToPath(path, sizeof(path), uid, initialPid);
 
-    ret = mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM);
-    if (ret < 0) {
-        SLOGE("failed to make and chown %s: %s", path, strerror(-ret));
-        return ret;
+    if (!mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM)) {
+        PLOG(ERROR) << "failed to make and chown " << path;
+        return -errno;
     }
 
     strlcat(path, PROCESSGROUP_CGROUP_PROCS_FILE, sizeof(path));
 
     int fd = open(path, O_WRONLY);
-    if (fd < 0) {
-        ret = -errno;
-        SLOGE("failed to open %s: %s", path, strerror(errno));
+    if (fd == -1) {
+        int ret = -errno;
+        PLOG(ERROR) << "failed to open " << path;
         return ret;
     }
 
     char pid[PROCESSGROUP_MAX_PID_LEN + 1] = {0};
     int len = snprintf(pid, sizeof(pid), "%d", initialPid);
 
-    ret = write(fd, pid, len);
-    if (ret < 0) {
+    int ret = 0;
+    if (write(fd, pid, len) < 0) {
         ret = -errno;
-        SLOGE("failed to write '%s' to %s: %s", pid, path, strerror(errno));
-    } else {
-        ret = 0;
+        PLOG(ERROR) << "failed to write '" << pid << "' to " << path;
     }
 
     close(fd);
     return ret;
 }
-
diff --git a/libprocinfo/.clang-format b/libprocinfo/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libprocinfo/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libprocinfo/Android.bp b/libprocinfo/Android.bp
new file mode 100644
index 0000000..aedaa38
--- /dev/null
+++ b/libprocinfo/Android.bp
@@ -0,0 +1,77 @@
+//
+// 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.
+//
+
+libprocinfo_cppflags = [
+    "-Wall",
+    "-Wextra",
+    "-Werror",
+]
+
+cc_library {
+    name: "libprocinfo",
+    vendor_available: true,
+    host_supported: true,
+    srcs: [
+        "process.cpp",
+    ],
+    cppflags: libprocinfo_cppflags,
+
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+    shared_libs: ["libbase"],
+    target: {
+        darwin: {
+            enabled: false,
+        },
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: false,
+        },
+    },
+}
+
+// Tests
+// ------------------------------------------------------------------------------
+cc_test {
+    name: "libprocinfo_test",
+    host_supported: true,
+    srcs: [
+        "process_test.cpp",
+    ],
+    target: {
+        darwin: {
+            enabled: false,
+        },
+        windows: {
+            enabled: false,
+        },
+    },
+
+    cppflags: libprocinfo_cppflags,
+    shared_libs: ["libbase", "libprocinfo"],
+
+    compile_multilib: "both",
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
diff --git a/libprocinfo/include/procinfo/process.h b/libprocinfo/include/procinfo/process.h
new file mode 100644
index 0000000..fb140ff
--- /dev/null
+++ b/libprocinfo/include/procinfo/process.h
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <memory>
+#include <string>
+#include <type_traits>
+
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+namespace procinfo {
+
+#if defined(__linux__)
+
+struct ProcessInfo {
+  std::string name;
+  pid_t tid;
+  pid_t pid;
+  pid_t ppid;
+  pid_t tracer;
+  uid_t uid;
+  uid_t gid;
+};
+
+// Parse the contents of /proc/<tid>/status into |process_info|.
+bool GetProcessInfo(pid_t tid, ProcessInfo* process_info);
+
+// Parse the contents of <fd>/status into |process_info|.
+// |fd| should be an fd pointing at a /proc/<pid> directory.
+bool GetProcessInfoFromProcPidFd(int fd, ProcessInfo* process_info);
+
+// Fetch the list of threads from a given process's /proc/<pid> directory.
+// |fd| should be an fd pointing at a /proc/<pid> directory.
+template <typename Collection>
+auto GetProcessTidsFromProcPidFd(int fd, Collection* out) ->
+    typename std::enable_if<sizeof(typename Collection::value_type) >= sizeof(pid_t), bool>::type {
+  out->clear();
+
+  int task_fd = openat(fd, "task", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
+  std::unique_ptr<DIR, int (*)(DIR*)> dir(fdopendir(task_fd), closedir);
+  if (!dir) {
+    PLOG(ERROR) << "failed to open task directory";
+    return false;
+  }
+
+  struct dirent* dent;
+  while ((dent = readdir(dir.get()))) {
+    if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0) {
+      pid_t tid;
+      if (!android::base::ParseInt(dent->d_name, &tid, 1, std::numeric_limits<pid_t>::max())) {
+        LOG(ERROR) << "failed to parse task id: " << dent->d_name;
+        return false;
+      }
+
+      out->insert(out->end(), tid);
+    }
+  }
+
+  return true;
+}
+
+template <typename Collection>
+auto GetProcessTids(pid_t pid, Collection* out) ->
+    typename std::enable_if<sizeof(typename Collection::value_type) >= sizeof(pid_t), bool>::type {
+  char task_path[PATH_MAX];
+  if (snprintf(task_path, PATH_MAX, "/proc/%d", pid) >= PATH_MAX) {
+    LOG(ERROR) << "task path overflow (pid = " << pid << ")";
+    return false;
+  }
+
+  android::base::unique_fd fd(open(task_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
+  if (fd == -1) {
+    PLOG(ERROR) << "failed to open " << task_path;
+    return false;
+  }
+
+  return GetProcessTidsFromProcPidFd(fd.get(), out);
+}
+
+#endif
+
+} /* namespace procinfo */
+} /* namespace android */
diff --git a/libprocinfo/process.cpp b/libprocinfo/process.cpp
new file mode 100644
index 0000000..c513e16
--- /dev/null
+++ b/libprocinfo/process.cpp
@@ -0,0 +1,109 @@
+/*
+ * 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 <procinfo/process.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/unique_fd.h>
+
+using android::base::unique_fd;
+
+namespace android {
+namespace procinfo {
+
+bool GetProcessInfo(pid_t tid, ProcessInfo* process_info) {
+  char path[PATH_MAX];
+  snprintf(path, sizeof(path), "/proc/%d", tid);
+
+  unique_fd dirfd(open(path, O_DIRECTORY | O_RDONLY));
+  if (dirfd == -1) {
+    PLOG(ERROR) << "failed to open " << path;
+    return false;
+  }
+
+  return GetProcessInfoFromProcPidFd(dirfd.get(), process_info);
+}
+
+bool GetProcessInfoFromProcPidFd(int fd, ProcessInfo* process_info) {
+  int status_fd = openat(fd, "status", O_RDONLY | O_CLOEXEC);
+
+  if (status_fd == -1) {
+    PLOG(ERROR) << "failed to open status fd in GetProcessInfoFromProcPidFd";
+    return false;
+  }
+
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fdopen(status_fd, "r"), fclose);
+  if (!fp) {
+    PLOG(ERROR) << "failed to open status file in GetProcessInfoFromProcPidFd";
+    close(status_fd);
+    return false;
+  }
+
+  int field_bitmap = 0;
+  static constexpr int finished_bitmap = 127;
+  char* line = nullptr;
+  size_t len = 0;
+
+  while (getline(&line, &len, fp.get()) != -1 && field_bitmap != finished_bitmap) {
+    char* tab = strchr(line, '\t');
+    if (tab == nullptr) {
+      continue;
+    }
+
+    size_t header_len = tab - line;
+    std::string header = std::string(line, header_len);
+    if (header == "Name:") {
+      std::string name = line + header_len + 1;
+
+      // line includes the trailing newline.
+      name.pop_back();
+      process_info->name = std::move(name);
+
+      field_bitmap |= 1;
+    } else if (header == "Pid:") {
+      process_info->tid = atoi(tab + 1);
+      field_bitmap |= 2;
+    } else if (header == "Tgid:") {
+      process_info->pid = atoi(tab + 1);
+      field_bitmap |= 4;
+    } else if (header == "PPid:") {
+      process_info->ppid = atoi(tab + 1);
+      field_bitmap |= 8;
+    } else if (header == "TracerPid:") {
+      process_info->tracer = atoi(tab + 1);
+      field_bitmap |= 16;
+    } else if (header == "Uid:") {
+      process_info->uid = atoi(tab + 1);
+      field_bitmap |= 32;
+    } else if (header == "Gid:") {
+      process_info->gid = atoi(tab + 1);
+      field_bitmap |= 64;
+    }
+  }
+
+  free(line);
+  return field_bitmap == finished_bitmap;
+}
+
+} /* namespace procinfo */
+} /* namespace android */
diff --git a/libprocinfo/process_test.cpp b/libprocinfo/process_test.cpp
new file mode 100644
index 0000000..5ffd236
--- /dev/null
+++ b/libprocinfo/process_test.cpp
@@ -0,0 +1,84 @@
+/*
+ * 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 <procinfo/process.h>
+
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <set>
+#include <thread>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <android-base/stringprintf.h>
+
+#if !defined(__BIONIC__)
+#include <syscall.h>
+static pid_t gettid() {
+  return syscall(__NR_gettid);
+}
+#endif
+
+TEST(process_info, process_info_smoke) {
+  android::procinfo::ProcessInfo self;
+  ASSERT_TRUE(android::procinfo::GetProcessInfo(gettid(), &self));
+  ASSERT_EQ(gettid(), self.tid);
+  ASSERT_EQ(getpid(), self.pid);
+  ASSERT_EQ(getppid(), self.ppid);
+  ASSERT_EQ(getuid(), self.uid);
+  ASSERT_EQ(getgid(), self.gid);
+}
+
+TEST(process_info, process_info_proc_pid_fd_smoke) {
+  android::procinfo::ProcessInfo self;
+  int fd = open(android::base::StringPrintf("/proc/%d", gettid()).c_str(), O_DIRECTORY | O_RDONLY);
+  ASSERT_NE(-1, fd);
+  ASSERT_TRUE(android::procinfo::GetProcessInfoFromProcPidFd(fd, &self));
+
+  // Process name is capped at 15 bytes.
+  ASSERT_EQ("libprocinfo_tes", self.name);
+  ASSERT_EQ(gettid(), self.tid);
+  ASSERT_EQ(getpid(), self.pid);
+  ASSERT_EQ(getppid(), self.ppid);
+  ASSERT_EQ(getuid(), self.uid);
+  ASSERT_EQ(getgid(), self.gid);
+  close(fd);
+}
+
+TEST(process_info, process_tids_smoke) {
+  pid_t main_tid = gettid();
+  std::thread([main_tid]() {
+    pid_t thread_tid = gettid();
+
+    {
+      std::vector<pid_t> vec;
+      ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &vec));
+      ASSERT_EQ(1, std::count(vec.begin(), vec.end(), main_tid));
+      ASSERT_EQ(1, std::count(vec.begin(), vec.end(), thread_tid));
+    }
+
+    {
+      std::set<pid_t> set;
+      ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &set));
+      ASSERT_EQ(1, std::count(set.begin(), set.end(), main_tid));
+      ASSERT_EQ(1, std::count(set.begin(), set.end(), thread_tid));
+    }
+  }).join();
+}
diff --git a/libsparse/Android.bp b/libsparse/Android.bp
new file mode 100644
index 0000000..dd8b5fd
--- /dev/null
+++ b/libsparse/Android.bp
@@ -0,0 +1,67 @@
+// Copyright 2010 The Android Open Source Project
+
+cc_library {
+    name: "libsparse",
+    host_supported: true,
+    unique_host_soname: true,
+    srcs: [
+        "backed_block.c",
+        "output_file.c",
+        "sparse.c",
+        "sparse_crc32.c",
+        "sparse_err.c",
+        "sparse_read.c",
+    ],
+    cflags: ["-Werror"],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+    target: {
+        host: {
+            shared_libs: ["libz-host"],
+        },
+        android: {
+            shared_libs: ["libz"],
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
+
+cc_binary {
+    name: "simg2img",
+    host_supported: true,
+    srcs: [
+        "simg2img.c",
+        "sparse_crc32.c",
+    ],
+    static_libs: [
+        "libsparse",
+        "libz",
+    ],
+
+    cflags: ["-Werror"],
+}
+
+cc_binary {
+    name: "img2simg",
+    host_supported: true,
+    srcs: ["img2simg.c"],
+    static_libs: [
+        "libsparse",
+        "libz",
+    ],
+
+    cflags: ["-Werror"],
+}
+
+cc_binary_host {
+    name: "append2simg",
+    srcs: ["append2simg.c"],
+    static_libs: [
+        "libsparse",
+        "libz",
+    ],
+
+    cflags: ["-Werror"],
+}
diff --git a/libsparse/Android.mk b/libsparse/Android.mk
index c77eba9..05e68bc 100644
--- a/libsparse/Android.mk
+++ b/libsparse/Android.mk
@@ -2,106 +2,6 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-libsparse_src_files := \
-        backed_block.c \
-        output_file.c \
-        sparse.c \
-        sparse_crc32.c \
-        sparse_err.c \
-        sparse_read.c
-
-
-include $(CLEAR_VARS)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SRC_FILES := $(libsparse_src_files)
-LOCAL_MODULE := libsparse_host
-LOCAL_STATIC_LIBRARIES := libz
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-
-include $(CLEAR_VARS)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SRC_FILES := $(libsparse_src_files)
-LOCAL_MODULE := libsparse
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
-LOCAL_SHARED_LIBRARIES := \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_SHARED_LIBRARY)
-
-
-include $(CLEAR_VARS)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SRC_FILES := $(libsparse_src_files)
-LOCAL_MODULE := libsparse_static
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_STATIC_LIBRARY)
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := simg2img.c \
-	sparse_crc32.c
-LOCAL_MODULE := simg2img_host
-# Need a unique module name, but exe should still be called simg2img
-LOCAL_MODULE_STEM := simg2img
-LOCAL_STATIC_LIBRARIES := \
-    libsparse_host \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_HOST_EXECUTABLE)
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := simg2img.c \
-	sparse_crc32.c
-LOCAL_MODULE := simg2img
-LOCAL_STATIC_LIBRARIES := \
-    libsparse_static \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_EXECUTABLE)
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := img2simg.c
-LOCAL_MODULE := img2simg_host
-# Need a unique module name, but exe should still be called simg2img
-LOCAL_MODULE_STEM := img2simg
-LOCAL_STATIC_LIBRARIES := \
-    libsparse_host \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_HOST_EXECUTABLE)
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := img2simg.c
-LOCAL_MODULE := img2simg
-LOCAL_STATIC_LIBRARIES := \
-    libsparse_static \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_EXECUTABLE)
-
-
-ifneq ($(HOST_OS),windows)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := append2simg.c
-LOCAL_MODULE := append2simg
-LOCAL_STATIC_LIBRARIES := \
-    libsparse_host \
-    libz
-LOCAL_CFLAGS := -Werror
-include $(BUILD_HOST_EXECUTABLE)
-
-endif
-
 include $(CLEAR_VARS)
 LOCAL_MODULE := simg_dump.py
 LOCAL_SRC_FILES := simg_dump.py
diff --git a/libsparse/include/sparse/sparse.h b/libsparse/include/sparse/sparse.h
index 42d4adb..356f65f 100644
--- a/libsparse/include/sparse/sparse.h
+++ b/libsparse/include/sparse/sparse.h
@@ -176,6 +176,13 @@
 int64_t sparse_file_len(struct sparse_file *s, bool sparse, bool crc);
 
 /**
+ * sparse_file_block_size
+ *
+ * @s - sparse file cookie
+ */
+unsigned int sparse_file_block_size(struct sparse_file *s);
+
+/**
  * sparse_file_callback - call a callback for blocks in sparse file
  *
  * @s - sparse file cookie
@@ -197,6 +204,24 @@
 		int (*write)(void *priv, const void *data, int len), void *priv);
 
 /**
+ * sparse_file_foreach_chunk - call a callback for data blocks in sparse file
+ *
+ * @s - sparse file cookie
+ * @sparse - write in the Android sparse file format
+ * @crc - append a crc chunk
+ * @write - function to call for each block
+ * @priv - value that will be passed as the first argument to write
+ *
+ * The function has the same behavior as 'sparse_file_callback', except it only
+ * iterates on blocks that contain data.
+ *
+ * Returns 0 on success, negative errno on error.
+ */
+int sparse_file_foreach_chunk(struct sparse_file *s, bool sparse, bool crc,
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks),
+	void *priv);
+/**
  * sparse_file_read - read a file into a sparse file cookie
  *
  * @s - sparse file cookie
diff --git a/libsparse/output_file.c b/libsparse/output_file.c
index cd30800..2115998 100644
--- a/libsparse/output_file.c
+++ b/libsparse/output_file.c
@@ -34,7 +34,7 @@
 #include "sparse_crc32.h"
 #include "sparse_format.h"
 
-#ifndef USE_MINGW
+#ifndef _WIN32
 #include <sys/mman.h>
 #define O_BINARY 0
 #else
@@ -57,13 +57,13 @@
 #define CHUNK_HEADER_LEN (sizeof(chunk_header_t))
 
 #define container_of(inner, outer_t, elem) \
-	((outer_t *)((char *)inner - offsetof(outer_t, elem)))
+	((outer_t *)((char *)(inner) - offsetof(outer_t, elem)))
 
 struct output_file_ops {
 	int (*open)(struct output_file *, int fd);
 	int (*skip)(struct output_file *, int64_t);
 	int (*pad)(struct output_file *, int64_t);
-	int (*write)(struct output_file *, void *, int);
+	int (*write)(struct output_file *, void *, size_t);
 	void (*close)(struct output_file *);
 };
 
@@ -149,18 +149,23 @@
 	return 0;
 }
 
-static int file_write(struct output_file *out, void *data, int len)
+static int file_write(struct output_file *out, void *data, size_t len)
 {
-	int ret;
+	ssize_t ret;
 	struct output_file_normal *outn = to_output_file_normal(out);
 
-	ret = write(outn->fd, data, len);
-	if (ret < 0) {
-		error_errno("write");
-		return -1;
-	} else if (ret < len) {
-		error("incomplete write");
-		return -1;
+	while (len > 0) {
+		ret = write(outn->fd, data, len);
+		if (ret < 0) {
+			if (errno == EINTR) {
+				continue;
+			}
+			error_errno("write");
+			return -1;
+		}
+
+		data = (char *)data + ret;
+		len -= ret;
 	}
 
 	return 0;
@@ -232,18 +237,20 @@
 	return 0;
 }
 
-static int gz_file_write(struct output_file *out, void *data, int len)
+static int gz_file_write(struct output_file *out, void *data, size_t len)
 {
 	int ret;
 	struct output_file_gz *outgz = to_output_file_gz(out);
 
-	ret = gzwrite(outgz->gz_fd, data, len);
-	if (ret < 0) {
-		error_errno("gzwrite");
-		return -1;
-	} else if (ret < len) {
-		error("incomplete gzwrite");
-		return -1;
+	while (len > 0) {
+		ret = gzwrite(outgz->gz_fd, data,
+			      min(len, (unsigned int)INT_MAX));
+		if (ret == 0) {
+			error("gzwrite %s", gzerror(outgz->gz_fd, NULL));
+			return -1;
+		}
+		len -= ret;
+		data = (char *)data + ret;
 	}
 
 	return 0;
@@ -293,7 +300,7 @@
 	return -1;
 }
 
-static int callback_file_write(struct output_file *out, void *data, int len)
+static int callback_file_write(struct output_file *out, void *data, size_t len)
 {
 	struct output_file_callback *outc = to_output_file_callback(out);
 
@@ -698,14 +705,16 @@
 	int ret;
 	int64_t aligned_offset;
 	int aligned_diff;
-	int buffer_size;
+	uint64_t buffer_size;
 	char *ptr;
 
 	aligned_offset = offset & ~(4096 - 1);
 	aligned_diff = offset - aligned_offset;
-	buffer_size = len + aligned_diff;
+	buffer_size = (uint64_t)len + (uint64_t)aligned_diff;
 
-#ifndef USE_MINGW
+#ifndef _WIN32
+	if (buffer_size > SIZE_MAX)
+		return -E2BIG;
 	char *data = mmap64(NULL, buffer_size, PROT_READ, MAP_SHARED, fd,
 			aligned_offset);
 	if (data == MAP_FAILED) {
@@ -733,7 +742,7 @@
 
 	ret = out->sparse_ops->write_data_chunk(out, len, ptr);
 
-#ifndef USE_MINGW
+#ifndef _WIN32
 	munmap(data, buffer_size);
 #else
 	free(data);
diff --git a/libsparse/simg_dump.py b/libsparse/simg_dump.py
index c70d45f..82a03ad 100755
--- a/libsparse/simg_dump.py
+++ b/libsparse/simg_dump.py
@@ -15,43 +15,64 @@
 # limitations under the License.
 
 from __future__ import print_function
-import getopt, posixpath, signal, struct, sys
+import csv
+import getopt
+import hashlib
+import posixpath
+import signal
+import struct
+import sys
+
 
 def usage(argv0):
   print("""
-Usage: %s [-v] sparse_image_file ...
+Usage: %s [-v] [-s] [-c <filename>] sparse_image_file ...
  -v             verbose output
-""" % ( argv0 ))
+ -s             show sha1sum of data blocks
+ -c <filename>  save .csv file of blocks
+""" % (argv0))
   sys.exit(2)
 
-def main():
 
+def main():
   signal.signal(signal.SIGPIPE, signal.SIG_DFL)
 
   me = posixpath.basename(sys.argv[0])
 
   # Parse the command line
-  verbose = 0			# -v
+  verbose = 0                   # -v
+  showhash = 0                  # -s
+  csvfilename = None            # -c
   try:
     opts, args = getopt.getopt(sys.argv[1:],
-                               "v",
-                               ["verbose"])
+                               "vsc:",
+                               ["verbose", "showhash", "csvfile"])
   except getopt.GetoptError, e:
     print(e)
     usage(me)
   for o, a in opts:
     if o in ("-v", "--verbose"):
       verbose += 1
+    elif o in ("-s", "--showhash"):
+      showhash = True
+    elif o in ("-c", "--csvfile"):
+      csvfilename = a
     else:
       print("Unrecognized option \"%s\"" % (o))
       usage(me)
 
-  if len(args) == 0:
+  if not args:
     print("No sparse_image_file specified")
     usage(me)
 
+  if csvfilename:
+    csvfile = open(csvfilename, "wb")
+    csvwriter = csv.writer(csvfile)
+
+  output = verbose or csvfilename or showhash
+
   for path in args:
-    FH = open(path, 'rb')
+    FH = open(path, "rb")
     header_bin = FH.read(28)
     header = struct.unpack("<I4H4I", header_bin)
 
@@ -88,71 +109,99 @@
     if image_checksum != 0:
       print("checksum=0x%08X" % (image_checksum))
 
-    if not verbose:
+    if not output:
       continue
-    print("            input_bytes      output_blocks")
-    print("chunk    offset     number  offset  number")
+
+    if verbose > 0:
+      print("            input_bytes      output_blocks")
+      print("chunk    offset     number  offset  number")
+
+    if csvfilename:
+      csvwriter.writerow(["chunk", "input offset", "input bytes",
+                          "output offset", "output blocks", "type", "hash"])
+
     offset = 0
-    for i in xrange(1,total_chunks+1):
+    for i in xrange(1, total_chunks + 1):
       header_bin = FH.read(12)
       header = struct.unpack("<2H2I", header_bin)
       chunk_type = header[0]
-      reserved1 = header[1]
       chunk_sz = header[2]
       total_sz = header[3]
       data_sz = total_sz - 12
+      curhash = ""
+      curtype = ""
+      curpos = FH.tell()
 
-      print("%4u %10u %10u %7u %7u" % (i, FH.tell(), data_sz, offset, chunk_sz),
-            end=" ")
+      if verbose > 0:
+        print("%4u %10u %10u %7u %7u" % (i, curpos, data_sz, offset, chunk_sz),
+              end=" ")
 
       if chunk_type == 0xCAC1:
         if data_sz != (chunk_sz * blk_sz):
           print("Raw chunk input size (%u) does not match output size (%u)"
                 % (data_sz, chunk_sz * blk_sz))
-          break;
+          break
         else:
-          print("Raw data", end="")
-          FH.read(data_sz)
+          curtype = "Raw data"
+          data = FH.read(data_sz)
+          if showhash:
+            h = hashlib.sha1()
+            h.update(data)
+            curhash = h.hexdigest()
       elif chunk_type == 0xCAC2:
         if data_sz != 4:
           print("Fill chunk should have 4 bytes of fill, but this has %u"
-                % (data_sz), end="")
-          break;
+                % (data_sz))
+          break
         else:
           fill_bin = FH.read(4)
           fill = struct.unpack("<I", fill_bin)
-          print("Fill with 0x%08X" % (fill))
+          curtype = format("Fill with 0x%08X" % (fill))
+          if showhash:
+            h = hashlib.sha1()
+            data = fill_bin * (blk_sz / 4);
+            for block in xrange(chunk_sz):
+              h.update(data)
+            curhash = h.hexdigest()
       elif chunk_type == 0xCAC3:
         if data_sz != 0:
           print("Don't care chunk input size is non-zero (%u)" % (data_sz))
-          break;
+          break
         else:
-          print("Don't care", end="")
+          curtype = "Don't care"
       elif chunk_type == 0xCAC4:
         if data_sz != 4:
           print("CRC32 chunk should have 4 bytes of CRC, but this has %u"
-                % (data_sz), end="")
-          break;
+                % (data_sz))
+          break
         else:
           crc_bin = FH.read(4)
           crc = struct.unpack("<I", crc_bin)
-          print("Unverified CRC32 0x%08X" % (crc))
+          curtype = format("Unverified CRC32 0x%08X" % (crc))
       else:
-          print("Unknown chunk type 0x%04X" % (chunk_type), end="")
-          break;
+        print("Unknown chunk type 0x%04X" % (chunk_type))
+        break
 
-      if verbose > 1:
-        header = struct.unpack("<12B", header_bin)
-        print(" (%02X%02X %02X%02X %02X%02X%02X%02X %02X%02X%02X%02X)"
-              % (header[0], header[1], header[2], header[3],
-                 header[4], header[5], header[6], header[7],
-                 header[8], header[9], header[10], header[11]))
-      else:
-        print()
+      if verbose > 0:
+        print("%-18s" % (curtype), end=" ")
+
+        if verbose > 1:
+          header = struct.unpack("<12B", header_bin)
+          print(" (%02X%02X %02X%02X %02X%02X%02X%02X %02X%02X%02X%02X)"
+                % (header[0], header[1], header[2], header[3],
+                   header[4], header[5], header[6], header[7],
+                   header[8], header[9], header[10], header[11]), end=" ")
+
+        print(curhash)
+
+      if csvfilename:
+        csvwriter.writerow([i, curpos, data_sz, offset, chunk_sz, curtype,
+                            curhash])
 
       offset += chunk_sz
 
-    print("     %10u            %7u         End" % (FH.tell(), offset))
+    if verbose > 0:
+      print("     %10u            %7u         End" % (FH.tell(), offset))
 
     if total_blks != offset:
       print("The header said we should have %u output blocks, but we saw %u"
@@ -163,6 +212,9 @@
       print("There were %u bytes of extra data at the end of the file."
             % (junk_len))
 
+  if csvfilename:
+    csvfile.close()
+
   sys.exit(0)
 
 if __name__ == "__main__":
diff --git a/libsparse/sparse.c b/libsparse/sparse.c
index 311678a..b175860 100644
--- a/libsparse/sparse.c
+++ b/libsparse/sparse.c
@@ -199,6 +199,57 @@
 	return ret;
 }
 
+struct chunk_data {
+	void		*priv;
+	unsigned int	block;
+	unsigned int	nr_blocks;
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks);
+};
+
+static int foreach_chunk_write(void *priv, const void *data, int len)
+{
+	struct chunk_data *chk = priv;
+
+	return chk->write(chk->priv, data, len, chk->block, chk->nr_blocks);
+}
+
+int sparse_file_foreach_chunk(struct sparse_file *s, bool sparse, bool crc,
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks),
+	void *priv)
+{
+	int ret;
+	int chunks;
+	struct chunk_data chk;
+	struct output_file *out;
+	struct backed_block *bb;
+
+	chk.priv = priv;
+	chk.write = write;
+	chk.block = chk.nr_blocks = 0;
+	chunks = sparse_count_chunks(s);
+	out = output_file_open_callback(foreach_chunk_write, &chk,
+					s->block_size, s->len, false, sparse,
+					chunks, crc);
+
+	if (!out)
+		return -ENOMEM;
+
+	for (bb = backed_block_iter_new(s->backed_block_list); bb;
+			bb = backed_block_iter_next(bb)) {
+		chk.block = backed_block_block(bb);
+		chk.nr_blocks = (backed_block_len(bb) - 1) / s->block_size + 1;
+		ret = sparse_file_write_block(out, bb);
+		if (ret)
+			return ret;
+	}
+
+	output_file_close(out);
+
+	return ret;
+}
+
 static int out_counter_write(void *priv, const void *data __unused, int len)
 {
 	int64_t *count = priv;
@@ -230,6 +281,11 @@
 	return count;
 }
 
+unsigned int sparse_file_block_size(struct sparse_file *s)
+{
+	return s->block_size;
+}
+
 static struct backed_block *move_chunks_up_to_len(struct sparse_file *from,
 		struct sparse_file *to, unsigned int len)
 {
diff --git a/libsparse/sparse_read.c b/libsparse/sparse_read.c
index dbb4dab..a188202 100644
--- a/libsparse/sparse_read.c
+++ b/libsparse/sparse_read.c
@@ -79,7 +79,7 @@
 		s = " at ";
 	}
 	if (verbose) {
-#ifndef USE_MINGW
+#ifndef _WIN32
 		if (err == -EOVERFLOW) {
 			sparse_print_verbose("EOF while reading file%s%s\n", s, at);
 		} else
diff --git a/libsuspend/Android.bp b/libsuspend/Android.bp
new file mode 100644
index 0000000..130800e
--- /dev/null
+++ b/libsuspend/Android.bp
@@ -0,0 +1,21 @@
+// Copyright 2012 The Android Open Source Project
+
+cc_library {
+    name: "libsuspend",
+    vendor_available: true,
+
+    srcs: [
+        "autosuspend.c",
+        "autosuspend_wakeup_count.c",
+    ],
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+    ],
+    cflags: [
+        "-Werror",
+        // "-DLOG_NDEBUG=0",
+    ],
+}
diff --git a/libsuspend/Android.mk b/libsuspend/Android.mk
deleted file mode 100644
index 1ba2f59..0000000
--- a/libsuspend/Android.mk
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright 2012 The Android Open Source Project
-
-LOCAL_PATH:= $(call my-dir)
-
-libsuspend_src_files := \
-	autosuspend.c \
-	autosuspend_autosleep.c \
-	autosuspend_earlysuspend.c \
-	autosuspend_wakeup_count.c \
-
-libsuspend_libraries := \
-	liblog libcutils
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(libsuspend_src_files)
-LOCAL_MODULE := libsuspend
-LOCAL_MODULE_TAGS := optional
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
-LOCAL_SHARED_LIBRARIES := $(libsuspend_libraries)
-LOCAL_CFLAGS := -Werror
-#LOCAL_CFLAGS += -DLOG_NDEBUG=0
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(libsuspend_src_files)
-LOCAL_MODULE := libsuspend
-LOCAL_MODULE_TAGS := optional
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror
-#LOCAL_CFLAGS += -DLOG_NDEBUG=0
-include $(BUILD_STATIC_LIBRARY)
diff --git a/libsuspend/autosuspend.c b/libsuspend/autosuspend.c
index edd1007..96e1c10 100644
--- a/libsuspend/autosuspend.c
+++ b/libsuspend/autosuspend.c
@@ -14,10 +14,11 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "libsuspend"
+
 #include <stdbool.h>
 
-#define LOG_TAG "libsuspend"
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include <suspend/autosuspend.h>
 
@@ -33,19 +34,6 @@
         return 0;
     }
 
-    autosuspend_ops = autosuspend_earlysuspend_init();
-    if (autosuspend_ops) {
-        goto out;
-    }
-
-/* Remove autosleep so userspace can manager suspend/resume and keep stats */
-#if 0
-    autosuspend_ops = autosuspend_autosleep_init();
-    if (autosuspend_ops) {
-        goto out;
-    }
-#endif
-
     autosuspend_ops = autosuspend_wakeup_count_init();
     if (autosuspend_ops) {
         goto out;
diff --git a/libsuspend/autosuspend_autosleep.c b/libsuspend/autosuspend_autosleep.c
deleted file mode 100644
index 7262cc7..0000000
--- a/libsuspend/autosuspend_autosleep.c
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stddef.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#define LOG_TAG "libsuspend"
-#include <cutils/log.h>
-
-#include "autosuspend_ops.h"
-
-#define SYS_POWER_AUTOSLEEP "/sys/power/autosleep"
-
-static int autosleep_fd;
-static const char *sleep_state = "mem";
-static const char *on_state = "off";
-
-static int autosuspend_autosleep_enable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_autosleep_enable\n");
-
-    ret = TEMP_FAILURE_RETRY(write(autosleep_fd, sleep_state, strlen(sleep_state)));
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error writing to %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
-        goto err;
-    }
-
-    ALOGV("autosuspend_autosleep_enable done\n");
-
-    return 0;
-
-err:
-    return ret;
-}
-
-static int autosuspend_autosleep_disable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_autosleep_disable\n");
-
-    ret = TEMP_FAILURE_RETRY(write(autosleep_fd, on_state, strlen(on_state)));
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error writing to %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
-        goto err;
-    }
-
-    ALOGV("autosuspend_autosleep_disable done\n");
-
-    return 0;
-
-err:
-    return ret;
-}
-
-struct autosuspend_ops autosuspend_autosleep_ops = {
-        .enable = autosuspend_autosleep_enable,
-        .disable = autosuspend_autosleep_disable,
-};
-
-struct autosuspend_ops *autosuspend_autosleep_init(void)
-{
-    char buf[80];
-
-    autosleep_fd = TEMP_FAILURE_RETRY(open(SYS_POWER_AUTOSLEEP, O_WRONLY));
-    if (autosleep_fd < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error opening %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
-        return NULL;
-    }
-
-    ALOGI("Selected autosleep\n");
-
-    autosuspend_autosleep_disable();
-
-    return &autosuspend_autosleep_ops;
-}
diff --git a/libsuspend/autosuspend_earlysuspend.c b/libsuspend/autosuspend_earlysuspend.c
deleted file mode 100644
index 3793a69..0000000
--- a/libsuspend/autosuspend_earlysuspend.c
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#define LOG_TAG "libsuspend"
-#include <cutils/log.h>
-
-#include "autosuspend_ops.h"
-
-#define EARLYSUSPEND_SYS_POWER_STATE "/sys/power/state"
-#define EARLYSUSPEND_WAIT_FOR_FB_SLEEP "/sys/power/wait_for_fb_sleep"
-#define EARLYSUSPEND_WAIT_FOR_FB_WAKE "/sys/power/wait_for_fb_wake"
-
-static int sPowerStatefd;
-static const char *pwr_state_mem = "mem";
-static const char *pwr_state_on = "on";
-static pthread_t earlysuspend_thread;
-static pthread_mutex_t earlysuspend_mutex = PTHREAD_MUTEX_INITIALIZER;
-static pthread_cond_t earlysuspend_cond = PTHREAD_COND_INITIALIZER;
-static bool wait_for_earlysuspend;
-static enum {
-    EARLYSUSPEND_ON,
-    EARLYSUSPEND_MEM,
-} earlysuspend_state = EARLYSUSPEND_ON;
-
-int wait_for_fb_wake(void)
-{
-    int err = 0;
-    char buf;
-    int fd = TEMP_FAILURE_RETRY(open(EARLYSUSPEND_WAIT_FOR_FB_WAKE, O_RDONLY, 0));
-    // if the file doesn't exist, the error will be caught in read() below
-    err = TEMP_FAILURE_RETRY(read(fd, &buf, 1));
-    ALOGE_IF(err < 0,
-            "*** ANDROID_WAIT_FOR_FB_WAKE failed (%s)", strerror(errno));
-    close(fd);
-    return err < 0 ? err : 0;
-}
-
-static int wait_for_fb_sleep(void)
-{
-    int err = 0;
-    char buf;
-    int fd = TEMP_FAILURE_RETRY(open(EARLYSUSPEND_WAIT_FOR_FB_SLEEP, O_RDONLY, 0));
-    // if the file doesn't exist, the error will be caught in read() below
-    err = TEMP_FAILURE_RETRY(read(fd, &buf, 1));
-    ALOGE_IF(err < 0,
-            "*** ANDROID_WAIT_FOR_FB_SLEEP failed (%s)", strerror(errno));
-    close(fd);
-    return err < 0 ? err : 0;
-}
-
-static void *earlysuspend_thread_func(void __unused *arg)
-{
-    while (1) {
-        if (wait_for_fb_sleep()) {
-            ALOGE("Failed reading wait_for_fb_sleep, exiting earlysuspend thread\n");
-            return NULL;
-        }
-        pthread_mutex_lock(&earlysuspend_mutex);
-        earlysuspend_state = EARLYSUSPEND_MEM;
-        pthread_cond_signal(&earlysuspend_cond);
-        pthread_mutex_unlock(&earlysuspend_mutex);
-
-        if (wait_for_fb_wake()) {
-            ALOGE("Failed reading wait_for_fb_wake, exiting earlysuspend thread\n");
-            return NULL;
-        }
-        pthread_mutex_lock(&earlysuspend_mutex);
-        earlysuspend_state = EARLYSUSPEND_ON;
-        pthread_cond_signal(&earlysuspend_cond);
-        pthread_mutex_unlock(&earlysuspend_mutex);
-    }
-}
-static int autosuspend_earlysuspend_enable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_earlysuspend_enable\n");
-
-    ret = write(sPowerStatefd, pwr_state_mem, strlen(pwr_state_mem));
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error writing to %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
-        goto err;
-    }
-
-    if (wait_for_earlysuspend) {
-        pthread_mutex_lock(&earlysuspend_mutex);
-        while (earlysuspend_state != EARLYSUSPEND_MEM) {
-            pthread_cond_wait(&earlysuspend_cond, &earlysuspend_mutex);
-        }
-        pthread_mutex_unlock(&earlysuspend_mutex);
-    }
-
-    ALOGV("autosuspend_earlysuspend_enable done\n");
-
-    return 0;
-
-err:
-    return ret;
-}
-
-static int autosuspend_earlysuspend_disable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_earlysuspend_disable\n");
-
-    ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, pwr_state_on, strlen(pwr_state_on)));
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error writing to %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
-        goto err;
-    }
-
-    if (wait_for_earlysuspend) {
-        pthread_mutex_lock(&earlysuspend_mutex);
-        while (earlysuspend_state != EARLYSUSPEND_ON) {
-            pthread_cond_wait(&earlysuspend_cond, &earlysuspend_mutex);
-        }
-        pthread_mutex_unlock(&earlysuspend_mutex);
-    }
-
-    ALOGV("autosuspend_earlysuspend_disable done\n");
-
-    return 0;
-
-err:
-    return ret;
-}
-
-struct autosuspend_ops autosuspend_earlysuspend_ops = {
-        .enable = autosuspend_earlysuspend_enable,
-        .disable = autosuspend_earlysuspend_disable,
-};
-
-void start_earlysuspend_thread(void)
-{
-    char buf[80];
-    int ret;
-
-    ret = access(EARLYSUSPEND_WAIT_FOR_FB_SLEEP, F_OK);
-    if (ret < 0) {
-        return;
-    }
-
-    ret = access(EARLYSUSPEND_WAIT_FOR_FB_WAKE, F_OK);
-    if (ret < 0) {
-        return;
-    }
-
-    wait_for_fb_wake();
-
-    ALOGI("Starting early suspend unblocker thread\n");
-    ret = pthread_create(&earlysuspend_thread, NULL, earlysuspend_thread_func, NULL);
-    if (ret) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error creating thread: %s\n", buf);
-        return;
-    }
-
-    wait_for_earlysuspend = true;
-}
-
-struct autosuspend_ops *autosuspend_earlysuspend_init(void)
-{
-    char buf[80];
-    int ret;
-
-    sPowerStatefd = TEMP_FAILURE_RETRY(open(EARLYSUSPEND_SYS_POWER_STATE, O_RDWR));
-
-    if (sPowerStatefd < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGW("Error opening %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
-        return NULL;
-    }
-
-    ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, "on", 2));
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGW("Error writing 'on' to %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
-        goto err_write;
-    }
-
-    ALOGI("Selected early suspend\n");
-
-    start_earlysuspend_thread();
-
-    return &autosuspend_earlysuspend_ops;
-
-err_write:
-    close(sPowerStatefd);
-    return NULL;
-}
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.c
index 23a0290..4dedf7f 100644
--- a/libsuspend/autosuspend_wakeup_count.c
+++ b/libsuspend/autosuspend_wakeup_count.c
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "libsuspend"
+//#define LOG_NDEBUG 0
+
 #include <errno.h>
 #include <fcntl.h>
 #include <pthread.h>
@@ -25,9 +28,7 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#define LOG_TAG "libsuspend"
-//#define LOG_NDEBUG 0
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include "autosuspend_ops.h"
 
diff --git a/libsync/Android.bp b/libsync/Android.bp
new file mode 100644
index 0000000..257d42d
--- /dev/null
+++ b/libsync/Android.bp
@@ -0,0 +1,56 @@
+ndk_headers {
+    name: "libsync_headers",
+    from: "include/ndk",
+    to: "android",
+    srcs: ["include/ndk/sync.h"],
+    license: "NOTICE",
+}
+
+ndk_library {
+    name: "libsync",
+    symbol_file: "libsync.map.txt",
+    first_version: "26",
+}
+
+cc_defaults {
+    name: "libsync_defaults",
+    srcs: ["sync.c"],
+    local_include_dirs: ["include"],
+    export_include_dirs: ["include"],
+    cflags: ["-Werror"],
+}
+
+cc_library_shared {
+    name: "libsync",
+    vendor_available: true,
+    defaults: ["libsync_defaults"],
+}
+
+// libsync_recovery is only intended for the recovery binary.
+// Future versions of the kernel WILL require an updated libsync, and will break
+// anything statically linked against the current libsync.
+cc_library_static {
+    name: "libsync_recovery",
+    defaults: ["libsync_defaults"],
+}
+
+cc_test {
+    name: "sync_test",
+    defaults: ["libsync_defaults"],
+    gtest: false,
+    srcs: ["sync_test.c"],
+}
+
+cc_test {
+    name: "sync-unit-tests",
+    shared_libs: ["libsync"],
+    srcs: ["tests/sync_test.cpp"],
+    cflags: [
+        "-g",
+        "-Wall",
+        "-Werror",
+        "-Wno-missing-field-initializers",
+        "-Wno-sign-compare",
+    ],
+    clang: true,
+}
diff --git a/libsync/Android.mk b/libsync/Android.mk
deleted file mode 100644
index fd1c88c..0000000
--- a/libsync/Android.mk
+++ /dev/null
@@ -1,20 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := sync.c
-LOCAL_MODULE := libsync
-LOCAL_MODULE_TAGS := optional
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := sync.c sync_test.c
-LOCAL_MODULE := sync_test
-LOCAL_MODULE_TAGS := optional tests
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror
-include $(BUILD_EXECUTABLE)
diff --git a/libsync/NOTICE b/libsync/NOTICE
new file mode 100644
index 0000000..2c8db73
--- /dev/null
+++ b/libsync/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2012-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.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/libsync/include/android/sync.h b/libsync/include/android/sync.h
new file mode 100644
index 0000000..68f74a0
--- /dev/null
+++ b/libsync/include/android/sync.h
@@ -0,0 +1,69 @@
+/*
+ *  sync.h
+ *
+ *   Copyright 2012 Google, Inc
+ *
+ *  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 __SYS_CORE_SYNC_H
+#define __SYS_CORE_SYNC_H
+
+/* This file contains the legacy sync interface used by Android platform and
+ * device code. The direct contents will be removed over time as code
+ * transitions to using the updated interface in ndk/sync.h. When this file is
+ * empty other than the ndk/sync.h include, that file will be renamed to
+ * replace this one.
+ *
+ * New code should continue to include this file (#include <android/sync.h>)
+ * instead of ndk/sync.h so the eventual rename is seamless, but should only
+ * use the things declared in ndk/sync.h.
+ *
+ * This file used to be called sync/sync.h, but we renamed to that both the
+ * platform and NDK call it android/sync.h. A symlink from the old name to this
+ * one exists temporarily to avoid having to change all sync clients
+ * simultaneously. It will be removed when they've been updated, and probably
+ * after this change has been delivered to AOSP so that integrations don't
+ * break builds.
+ */
+
+#include "../ndk/sync.h"
+
+__BEGIN_DECLS
+
+struct sync_fence_info_data {
+ uint32_t len;
+ char name[32];
+ int32_t status;
+ uint8_t pt_info[0];
+};
+
+struct sync_pt_info {
+ uint32_t len;
+ char obj_name[32];
+ char driver_name[32];
+ int32_t status;
+ uint64_t timestamp_ns;
+ uint8_t driver_data[0];
+};
+
+/* timeout in msecs */
+int sync_wait(int fd, int timeout);
+struct sync_fence_info_data *sync_fence_info(int fd);
+struct sync_pt_info *sync_pt_info(struct sync_fence_info_data *info,
+                                  struct sync_pt_info *itr);
+void sync_fence_info_free(struct sync_fence_info_data *info);
+
+__END_DECLS
+
+#endif /* __SYS_CORE_SYNC_H */
diff --git a/libsync/include/ndk/sync.h b/libsync/include/ndk/sync.h
new file mode 100644
index 0000000..3c55783
--- /dev/null
+++ b/libsync/include/ndk/sync.h
@@ -0,0 +1,88 @@
+/*
+ *  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.
+ */
+
+#ifndef ANDROID_SYNC_H
+#define ANDROID_SYNC_H
+
+#include <stdint.h>
+
+#include <linux/sync_file.h>
+
+__BEGIN_DECLS
+
+#if __ANDROID_API__ >= __ANDROID_API_O__
+
+/* Fences indicate the status of an asynchronous task. They are initially
+ * in unsignaled state (0), and make a one-time transition to either signaled
+ * (1) or error (< 0) state. A sync file is a collection of one or more fences;
+ * the sync file's status is error if any of its fences are in error state,
+ * signaled if all of the child fences are signaled, or unsignaled otherwise.
+ *
+ * Sync files are created by various device APIs in response to submitting
+ * tasks to the device. Standard file descriptor lifetime syscalls like dup()
+ * and close() are used to manage sync file lifetime.
+ *
+ * The poll(), ppoll(), or select() syscalls can be used to wait for the sync
+ * file to change status, or (with a timeout of zero) to check its status.
+ *
+ * The functions below provide a few additional sync-specific operations.
+ */
+
+/**
+ * Merge two sync files.
+ *
+ * This produces a new sync file with the given name which has the union of the
+ * two original sync file's fences; redundant fences may be removed.
+ *
+ * If one of the input sync files is signaled or invalid, then this function
+ * may behave like dup(): the new file descriptor refers to the valid/unsignaled
+ * sync file with its original name, rather than a new sync file.
+ *
+ * The original fences remain valid, and the caller is responsible for closing
+ * them.
+ */
+int32_t sync_merge(const char *name, int32_t fd1, int32_t fd2);
+
+/**
+ * Retrieve detailed information about a sync file and its fences.
+ *
+ * The returned sync_file_info must be freed by calling sync_file_info_free().
+ */
+struct sync_file_info *sync_file_info(int32_t fd);
+
+/**
+ * Get the array of fence infos from the sync file's info.
+ *
+ * The returned array is owned by the parent sync file info, and has
+ * info->num_fences entries.
+ */
+static inline struct sync_fence_info* sync_get_fence_info(const struct sync_file_info* info) {
+// This header should compile in C, but some C++ projects enable
+// warnings-as-error for C-style casts.
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+    return (struct sync_fence_info *)(uintptr_t)(info->sync_fence_info);
+#pragma GCC diagnostic pop
+}
+
+/** Free a struct sync_file_info structure */
+void sync_file_info_free(struct sync_file_info *info);
+
+#endif // __ANDROID_API__ >= __ANDROID_API_O__
+
+__END_DECLS
+
+#endif /* ANDROID_SYNC_H */
diff --git a/libsync/include/sync/sync.h b/libsync/include/sync/sync.h
deleted file mode 100644
index 2e5d82f..0000000
--- a/libsync/include/sync/sync.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *  sync.h
- *
- *   Copyright 2012 Google, Inc
- *
- *  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 __SYS_CORE_SYNC_H
-#define __SYS_CORE_SYNC_H
-
-#include <sys/cdefs.h>
-#include <stdint.h>
-
-__BEGIN_DECLS
-
-// XXX: These structs are copied from the header "linux/sync.h".
-struct sync_fence_info_data {
- uint32_t len;
- char name[32];
- int32_t status;
- uint8_t pt_info[0];
-};
-
-struct sync_pt_info {
- uint32_t len;
- char obj_name[32];
- char driver_name[32];
- int32_t status;
- uint64_t timestamp_ns;
- uint8_t driver_data[0];
-};
-
-/* timeout in msecs */
-int sync_wait(int fd, int timeout);
-int sync_merge(const char *name, int fd1, int fd2);
-struct sync_fence_info_data *sync_fence_info(int fd);
-struct sync_pt_info *sync_pt_info(struct sync_fence_info_data *info,
-                                  struct sync_pt_info *itr);
-void sync_fence_info_free(struct sync_fence_info_data *info);
-
-__END_DECLS
-
-#endif /* __SYS_CORE_SYNC_H */
diff --git a/libsync/include/sync/sync.h b/libsync/include/sync/sync.h
new file mode 120000
index 0000000..3b17e48
--- /dev/null
+++ b/libsync/include/sync/sync.h
@@ -0,0 +1 @@
+../android/sync.h
\ No newline at end of file
diff --git a/libsync/libsync.map.txt b/libsync/libsync.map.txt
new file mode 100644
index 0000000..daa28ae
--- /dev/null
+++ b/libsync/libsync.map.txt
@@ -0,0 +1,32 @@
+#
+# 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.
+#
+
+LIBSYNC {
+  global:
+    sync_merge; # introduced=26
+    sync_get_fence_info; # introduced=26
+    sync_free_fence_info; # introduced=26
+  local:
+    *;
+};
+
+LIBSYNC_PLATFORM {
+  global:
+    sync_wait;
+    sync_fence_info;
+    sync_pt_info;
+    sync_fence_info_free;
+} LIBSYNC_PLATFORM;
diff --git a/libsync/sync.c b/libsync/sync.c
index d73bb11..baeccda 100644
--- a/libsync/sync.c
+++ b/libsync/sync.c
@@ -16,51 +16,210 @@
  *  limitations under the License.
  */
 
+#include <errno.h>
 #include <fcntl.h>
 #include <malloc.h>
+#include <poll.h>
+#include <stdatomic.h>
 #include <stdint.h>
 #include <string.h>
 
-#include <linux/sync.h>
-#include <linux/sw_sync.h>
-
 #include <sys/ioctl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 
+#include <android/sync.h>
+
+/* Legacy Sync API */
+
+struct sync_legacy_merge_data {
+ int32_t fd2;
+ char name[32];
+ int32_t fence;
+};
+
+/**
+ * DOC: SYNC_IOC_MERGE - merge two fences
+ *
+ * Takes a struct sync_merge_data.  Creates a new fence containing copies of
+ * the sync_pts in both the calling fd and sync_merge_data.fd2.  Returns the
+ * new fence's fd in sync_merge_data.fence
+ *
+ * This is the legacy version of the Sync API before the de-stage that happened
+ * on Linux kernel 4.7.
+ */
+#define SYNC_IOC_LEGACY_MERGE   _IOWR(SYNC_IOC_MAGIC, 1, \
+    struct sync_legacy_merge_data)
+
+/**
+ * DOC: SYNC_IOC_LEGACY_FENCE_INFO - get detailed information on a fence
+ *
+ * Takes a struct sync_fence_info_data with extra space allocated for pt_info.
+ * Caller should write the size of the buffer into len.  On return, len is
+ * updated to reflect the total size of the sync_fence_info_data including
+ * pt_info.
+ *
+ * pt_info is a buffer containing sync_pt_infos for every sync_pt in the fence.
+ * To iterate over the sync_pt_infos, use the sync_pt_info.len field.
+ *
+ * This is the legacy version of the Sync API before the de-stage that happened
+ * on Linux kernel 4.7.
+ */
+#define SYNC_IOC_LEGACY_FENCE_INFO  _IOWR(SYNC_IOC_MAGIC, 2,\
+    struct sync_fence_info_data)
+
+/* SW Sync API */
+
+struct sw_sync_create_fence_data {
+  __u32 value;
+  char name[32];
+  __s32 fence;
+};
+
+#define SW_SYNC_IOC_MAGIC 'W'
+#define SW_SYNC_IOC_CREATE_FENCE _IOWR(SW_SYNC_IOC_MAGIC, 0, struct sw_sync_create_fence_data)
+#define SW_SYNC_IOC_INC _IOW(SW_SYNC_IOC_MAGIC, 1, __u32)
+
+// ---------------------------------------------------------------------------
+// Support for caching the sync uapi version.
+//
+// This library supports both legacy (android/staging) uapi and modern
+// (mainline) sync uapi. Library calls first try one uapi, and if that fails,
+// try the other. Since any given kernel only supports one uapi version, after
+// the first successful syscall we know what the kernel supports and can skip
+// trying the other.
+
+enum uapi_version {
+    UAPI_UNKNOWN,
+    UAPI_MODERN,
+    UAPI_LEGACY
+};
+static atomic_int g_uapi_version = ATOMIC_VAR_INIT(UAPI_UNKNOWN);
+
+// ---------------------------------------------------------------------------
+
 int sync_wait(int fd, int timeout)
 {
-    __s32 to = timeout;
+    struct pollfd fds;
+    int ret;
 
-    return ioctl(fd, SYNC_IOC_WAIT, &to);
+    if (fd < 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    fds.fd = fd;
+    fds.events = POLLIN;
+
+    do {
+        ret = poll(&fds, 1, timeout);
+        if (ret > 0) {
+            if (fds.revents & (POLLERR | POLLNVAL)) {
+                errno = EINVAL;
+                return -1;
+            }
+            return 0;
+        } else if (ret == 0) {
+            errno = ETIME;
+            return -1;
+        }
+    } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
+
+    return ret;
+}
+
+static int legacy_sync_merge(const char *name, int fd1, int fd2)
+{
+    struct sync_legacy_merge_data data;
+    int ret;
+
+    data.fd2 = fd2;
+    strlcpy(data.name, name, sizeof(data.name));
+    ret = ioctl(fd1, SYNC_IOC_LEGACY_MERGE, &data);
+    if (ret < 0)
+        return ret;
+    return data.fence;
+}
+
+static int modern_sync_merge(const char *name, int fd1, int fd2)
+{
+    struct sync_merge_data data;
+    int ret;
+
+    data.fd2 = fd2;
+    strlcpy(data.name, name, sizeof(data.name));
+    data.flags = 0;
+    data.pad = 0;
+
+    ret = ioctl(fd1, SYNC_IOC_MERGE, &data);
+    if (ret < 0)
+        return ret;
+    return data.fence;
 }
 
 int sync_merge(const char *name, int fd1, int fd2)
 {
-    struct sync_merge_data data;
-    int err;
+    int uapi;
+    int ret;
 
-    data.fd2 = fd2;
-    strlcpy(data.name, name, sizeof(data.name));
+    uapi = atomic_load_explicit(&g_uapi_version, memory_order_acquire);
 
-    err = ioctl(fd1, SYNC_IOC_MERGE, &data);
-    if (err < 0)
-        return err;
+    if (uapi == UAPI_MODERN || uapi == UAPI_UNKNOWN) {
+        ret = modern_sync_merge(name, fd1, fd2);
+        if (ret >= 0 || errno != ENOTTY) {
+            if (ret >= 0 && uapi == UAPI_UNKNOWN) {
+                atomic_store_explicit(&g_uapi_version, UAPI_MODERN,
+                                      memory_order_release);
+            }
+            return ret;
+        }
+    }
 
-    return data.fence;
+    ret = legacy_sync_merge(name, fd1, fd2);
+    if (ret >= 0 && uapi == UAPI_UNKNOWN) {
+        atomic_store_explicit(&g_uapi_version, UAPI_LEGACY,
+                              memory_order_release);
+    }
+    return ret;
 }
 
-struct sync_fence_info_data *sync_fence_info(int fd)
+static struct sync_fence_info_data *legacy_sync_fence_info(int fd)
 {
-    struct sync_fence_info_data *info;
+    struct sync_fence_info_data *legacy_info;
+    struct sync_pt_info *legacy_pt_info;
     int err;
 
-    info = malloc(4096);
-    if (info == NULL)
+    legacy_info = malloc(4096);
+    if (legacy_info == NULL)
         return NULL;
 
-    info->len = 4096;
-    err = ioctl(fd, SYNC_IOC_FENCE_INFO, info);
+    legacy_info->len = 4096;
+    err = ioctl(fd, SYNC_IOC_LEGACY_FENCE_INFO, legacy_info);
+    if (err < 0) {
+        free(legacy_info);
+        return NULL;
+    }
+    return legacy_info;
+}
+
+static struct sync_file_info *modern_sync_file_info(int fd)
+{
+    struct sync_file_info local_info;
+    struct sync_file_info *info;
+    int err;
+
+    memset(&local_info, 0, sizeof(local_info));
+    err = ioctl(fd, SYNC_IOC_FILE_INFO, &local_info);
+    if (err < 0)
+        return NULL;
+
+    info = calloc(1, sizeof(struct sync_file_info) +
+                  local_info.num_fences * sizeof(struct sync_fence_info));
+    if (!info)
+        return NULL;
+    info->sync_fence_info = (__u64)(uintptr_t)(info + 1);
+
+    err = ioctl(fd, SYNC_IOC_FILE_INFO, info);
     if (err < 0) {
         free(info);
         return NULL;
@@ -69,6 +228,138 @@
     return info;
 }
 
+static struct sync_fence_info_data *sync_file_info_to_legacy_fence_info(
+    const struct sync_file_info *info)
+{
+    struct sync_fence_info_data *legacy_info;
+    struct sync_pt_info *legacy_pt_info;
+    const struct sync_fence_info *fence_info = sync_get_fence_info(info);
+    const uint32_t num_fences = info->num_fences;
+
+    legacy_info = malloc(4096);
+    if (legacy_info == NULL)
+        return NULL;
+    legacy_info->len = sizeof(*legacy_info) +
+                        num_fences * sizeof(struct sync_pt_info);
+    strlcpy(legacy_info->name, info->name, sizeof(legacy_info->name));
+    legacy_info->status = info->status;
+
+    legacy_pt_info = (struct sync_pt_info *)legacy_info->pt_info;
+    for (uint32_t i = 0; i < num_fences; i++) {
+        legacy_pt_info[i].len = sizeof(*legacy_pt_info);
+        strlcpy(legacy_pt_info[i].obj_name, fence_info[i].obj_name,
+                sizeof(legacy_pt_info->obj_name));
+        strlcpy(legacy_pt_info[i].driver_name, fence_info[i].driver_name,
+                sizeof(legacy_pt_info->driver_name));
+        legacy_pt_info[i].status = fence_info[i].status;
+        legacy_pt_info[i].timestamp_ns = fence_info[i].timestamp_ns;
+    }
+
+    return legacy_info;
+}
+
+static struct sync_file_info* legacy_fence_info_to_sync_file_info(
+                                    struct sync_fence_info_data *legacy_info)
+{
+    struct sync_file_info *info;
+    struct sync_pt_info *pt;
+    struct sync_fence_info *fence;
+    size_t num_fences;
+    int err;
+
+    pt = NULL;
+    num_fences = 0;
+    while ((pt = sync_pt_info(legacy_info, pt)) != NULL)
+        num_fences++;
+
+    info = calloc(1, sizeof(struct sync_file_info) +
+                     num_fences * sizeof(struct sync_fence_info));
+    if (!info) {
+        free(legacy_info);
+        return NULL;
+    }
+    info->sync_fence_info = (__u64)(uintptr_t)(info + 1);
+
+    strlcpy(info->name, legacy_info->name, sizeof(info->name));
+    info->status = legacy_info->status;
+    info->num_fences = num_fences;
+
+    pt = NULL;
+    fence = sync_get_fence_info(info);
+    while ((pt = sync_pt_info(legacy_info, pt)) != NULL) {
+        strlcpy(fence->obj_name, pt->obj_name, sizeof(fence->obj_name));
+        strlcpy(fence->driver_name, pt->driver_name,
+                sizeof(fence->driver_name));
+        fence->status = pt->status;
+        fence->timestamp_ns = pt->timestamp_ns;
+        fence++;
+    }
+
+    return info;
+}
+
+struct sync_fence_info_data *sync_fence_info(int fd)
+{
+    struct sync_fence_info_data *legacy_info;
+    int uapi;
+
+    uapi = atomic_load_explicit(&g_uapi_version, memory_order_acquire);
+
+    if (uapi == UAPI_LEGACY || uapi == UAPI_UNKNOWN) {
+        legacy_info = legacy_sync_fence_info(fd);
+        if (legacy_info || errno != ENOTTY) {
+            if (legacy_info && uapi == UAPI_UNKNOWN) {
+                atomic_store_explicit(&g_uapi_version, UAPI_LEGACY,
+                                      memory_order_release);
+            }
+            return legacy_info;
+        }
+    }
+
+    struct sync_file_info* file_info;
+    file_info = modern_sync_file_info(fd);
+    if (!file_info)
+        return NULL;
+    if (uapi == UAPI_UNKNOWN) {
+        atomic_store_explicit(&g_uapi_version, UAPI_MODERN,
+                              memory_order_release);
+    }
+    legacy_info = sync_file_info_to_legacy_fence_info(file_info);
+    sync_file_info_free(file_info);
+    return legacy_info;
+}
+
+struct sync_file_info* sync_file_info(int32_t fd)
+{
+    struct sync_file_info *info;
+    int uapi;
+
+    uapi = atomic_load_explicit(&g_uapi_version, memory_order_acquire);
+
+    if (uapi == UAPI_MODERN || uapi == UAPI_UNKNOWN) {
+        info = modern_sync_file_info(fd);
+        if (info || errno != ENOTTY) {
+            if (info && uapi == UAPI_UNKNOWN) {
+                atomic_store_explicit(&g_uapi_version, UAPI_MODERN,
+                                      memory_order_release);
+            }
+            return info;
+        }
+    }
+
+    struct sync_fence_info_data *legacy_info;
+    legacy_info = legacy_sync_fence_info(fd);
+    if (!legacy_info)
+        return NULL;
+    if (uapi == UAPI_UNKNOWN) {
+        atomic_store_explicit(&g_uapi_version, UAPI_LEGACY,
+                              memory_order_release);
+    }
+    info = legacy_fence_info_to_sync_file_info(legacy_info);
+    sync_fence_info_free(legacy_info);
+    return info;
+}
+
 struct sync_pt_info *sync_pt_info(struct sync_fence_info_data *info,
                                   struct sync_pt_info *itr)
 {
@@ -88,10 +379,21 @@
     free(info);
 }
 
+void sync_file_info_free(struct sync_file_info *info)
+{
+    free(info);
+}
+
 
 int sw_sync_timeline_create(void)
 {
-    return open("/dev/sw_sync", O_RDWR);
+    int ret;
+
+    ret = open("/sys/kernel/debug/sync/sw_sync", O_RDWR);
+    if (ret < 0)
+        ret = open("/dev/sw_sync", O_RDWR);
+
+    return ret;
 }
 
 int sw_sync_timeline_inc(int fd, unsigned count)
diff --git a/libsync/sync_test.c b/libsync/sync_test.c
index ee9ea3c..f1ffdcf 100644
--- a/libsync/sync_test.c
+++ b/libsync/sync_test.c
@@ -22,7 +22,7 @@
 #include <string.h>
 #include <unistd.h>
 
-#include <sync/sync.h>
+#include <android/sync.h>
 #include "sw_sync.h"
 
 pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -92,7 +92,7 @@
 
         for (j = 0; j < 2; j++) {
             unsigned val = i + j * 3 + 1;
-            sprintf(str, "test_fence%d-%d", i, j);
+            snprintf(str, sizeof(str), "test_fence%d-%d", i, j);
             int fd = sw_sync_fence_create(sync_timeline_fd, str, val);
             if (fd < 0) {
                 printf("can't create sync pt %d: %s", val, strerror(errno));
@@ -106,7 +106,7 @@
 
     sync_data[3].thread_no = 3;
     for (j = 0; j < 2; j++) {
-        sprintf(str, "merged_fence%d", j);
+        snprintf(str, sizeof(str), "merged_fence%d", j);
         sync_data[3].fd[j] = sync_merge(str, sync_data[0].fd[j], sync_data[1].fd[j]);
         if (sync_data[3].fd[j] < 0) {
             printf("can't merge sync pts %d and %d: %s\n",
diff --git a/libsync/tests/Android.mk b/libsync/tests/Android.mk
deleted file mode 100644
index 8137c7a..0000000
--- a/libsync/tests/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# Copyright 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_CLANG := true
-LOCAL_MODULE := sync-unit-tests
-LOCAL_CFLAGS += -g -Wall -Werror -std=gnu++11 -Wno-missing-field-initializers -Wno-sign-compare
-LOCAL_SHARED_LIBRARIES += libsync
-LOCAL_STATIC_LIBRARIES += libgtest_main
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/../include
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/..
-LOCAL_SRC_FILES := \
-    sync_test.cpp
-include $(BUILD_NATIVE_TEST)
diff --git a/libsync/tests/sync_test.cpp b/libsync/tests/sync_test.cpp
index 2c409dc..f08e97e 100644
--- a/libsync/tests/sync_test.cpp
+++ b/libsync/tests/sync_test.cpp
@@ -1,5 +1,5 @@
 #include <gtest/gtest.h>
-#include <sync/sync.h>
+#include <android/sync.h>
 #include <sw_sync.h>
 #include <fcntl.h>
 #include <vector>
@@ -172,20 +172,20 @@
         return sync_wait(m_fd, timeout);
     }
     vector<SyncPointInfo> getInfo() const {
-        struct sync_pt_info *pointInfo = nullptr;
         vector<SyncPointInfo> fenceInfo;
-        sync_fence_info_data *info = sync_fence_info(getFd());
+        struct sync_file_info *info = sync_file_info(getFd());
         if (!info) {
             return fenceInfo;
         }
-        while ((pointInfo = sync_pt_info(info, pointInfo))) {
+        const auto fences = sync_get_fence_info(info);
+        for (uint32_t i = 0; i < info->num_fences; i++) {
             fenceInfo.push_back(SyncPointInfo{
-                pointInfo->driver_name,
-                pointInfo->obj_name,
-                pointInfo->timestamp_ns,
-                pointInfo->status});
+                fences[i].driver_name,
+                fences[i].obj_name,
+                fences[i].timestamp_ns,
+                fences[i].status});
         }
-        sync_fence_info_free(info);
+        sync_file_info_free(info);
         return fenceInfo;
     }
     int getSize() const {
@@ -212,6 +212,32 @@
     }
 };
 
+static void CheckModernLegacyInfoMatch(const SyncFence& f) {
+    struct sync_file_info* modern = sync_file_info(f.getFd());
+    struct sync_fence_info_data* legacy = sync_fence_info(f.getFd());
+
+    ASSERT_TRUE(modern != NULL);
+    ASSERT_TRUE(legacy != NULL);
+
+    EXPECT_STREQ(modern->name, legacy->name);
+    EXPECT_EQ(modern->status, legacy->status);
+
+    uint32_t fenceIdx = 0;
+    struct sync_pt_info* pt = sync_pt_info(legacy, NULL);
+    const struct sync_fence_info* fences = sync_get_fence_info(modern);
+    while (fenceIdx < modern->num_fences && pt != NULL) {
+        EXPECT_STREQ(fences[fenceIdx].obj_name, pt->obj_name);
+        EXPECT_STREQ(fences[fenceIdx].driver_name, pt->driver_name);
+        EXPECT_EQ(fences[fenceIdx].status, pt->status);
+        EXPECT_EQ(fences[fenceIdx].timestamp_ns, pt->timestamp_ns);
+
+        fenceIdx++;
+        pt = sync_pt_info(legacy, pt);
+    }
+    EXPECT_EQ(fenceIdx, modern->num_fences);
+    EXPECT_EQ(NULL, pt);
+}
+
 int SyncFence::s_fenceCount = 0;
 
 TEST(AllocTest, Timeline) {
@@ -225,6 +251,7 @@
 
     SyncFence fence(timeline, 1);
     ASSERT_TRUE(fence.isValid());
+    CheckModernLegacyInfoMatch(fence);
 }
 
 TEST(AllocTest, FenceNegative) {
@@ -321,15 +348,21 @@
     timeline.inc(1);
     ASSERT_EQ(a.getSignaledCount(), 1);
     ASSERT_EQ(d.getActiveCount(), 1);
+    CheckModernLegacyInfoMatch(a);
+    CheckModernLegacyInfoMatch(d);
 
     timeline.inc(1);
     ASSERT_EQ(b.getSignaledCount(), 1);
     ASSERT_EQ(d.getActiveCount(), 1);
+    CheckModernLegacyInfoMatch(b);
+    CheckModernLegacyInfoMatch(d);
 
     timeline.inc(1);
     ASSERT_EQ(c.getSignaledCount(), 1);
     ASSERT_EQ(d.getActiveCount(), 0);
     ASSERT_EQ(d.getSignaledCount(), 1);
+    CheckModernLegacyInfoMatch(c);
+    CheckModernLegacyInfoMatch(d);
 }
 
 TEST(FenceTest, MergeSameFence) {
@@ -343,36 +376,11 @@
     ASSERT_TRUE(selfMergeFence.isValid());
 
     ASSERT_EQ(selfMergeFence.getSignaledCount(), 0);
+    CheckModernLegacyInfoMatch(selfMergeFence);
 
     timeline.inc(5);
     ASSERT_EQ(selfMergeFence.getSignaledCount(), 1);
-}
-
-TEST(FenceTest, WaitOnDestroyedTimeline) {
-    SyncTimeline timeline;
-    ASSERT_TRUE(timeline.isValid());
-
-    SyncFence fenceSig(timeline, 100);
-    SyncFence fenceKill(timeline, 200);
-
-    // Spawn a thread to wait on a fence when the timeline is killed.
-    thread waitThread{
-        [&]() {
-            ASSERT_EQ(timeline.inc(100), 0);
-
-            ASSERT_EQ(fenceKill.wait(-1), -1);
-            ASSERT_EQ(errno, ENOENT);
-        }
-    };
-
-    // Wait for the thread to spool up.
-    fenceSig.wait();
-
-    // Kill the timeline.
-    timeline.destroy();
-
-    // wait for the thread to clean up.
-    waitThread.join();
+    CheckModernLegacyInfoMatch(selfMergeFence);
 }
 
 TEST(FenceTest, PollOnDestroyedTimeline) {
@@ -391,8 +399,7 @@
             struct pollfd fds;
             fds.fd = fenceKill.getFd();
             fds.events = POLLIN | POLLERR;
-            ASSERT_EQ(poll(&fds, 1, -1), 1);
-            ASSERT_TRUE(fds.revents & POLLERR);
+            ASSERT_EQ(poll(&fds, 1, 0), 0);
         }
     };
 
@@ -425,14 +432,17 @@
     timelineA.inc(5);
     ASSERT_EQ(mergedFence.getActiveCount(), 2);
     ASSERT_EQ(mergedFence.getSignaledCount(), 1);
+    CheckModernLegacyInfoMatch(mergedFence);
 
     timelineB.inc(5);
     ASSERT_EQ(mergedFence.getActiveCount(), 1);
     ASSERT_EQ(mergedFence.getSignaledCount(), 2);
+    CheckModernLegacyInfoMatch(mergedFence);
 
     timelineC.inc(5);
     ASSERT_EQ(mergedFence.getActiveCount(), 0);
     ASSERT_EQ(mergedFence.getSignaledCount(), 3);
+    CheckModernLegacyInfoMatch(mergedFence);
 
     // confirm you can successfully wait.
     ASSERT_EQ(mergedFence.wait(100), 0);
@@ -564,7 +574,7 @@
     ASSERT_TRUE(fence.isValid());
 
     unordered_map<int, int> fenceMap;
-    fenceMap.insert(make_tuple(0, 0));
+    fenceMap.insert(make_pair(0, 0));
 
     // Randomly create syncpoints out of a fixed set of timelines, and merge them together.
     for (int i = 0; i < mergeCount; i++) {
@@ -577,17 +587,18 @@
         // Keep track of the latest syncpoint in each timeline.
         auto itr = fenceMap.find(timelineOffset);
         if (itr == end(fenceMap)) {
-            fenceMap.insert(tie(timelineOffset, syncPoint));
+            fenceMap.insert(make_pair(timelineOffset, syncPoint));
         }
         else {
             int oldSyncPoint = itr->second;
             fenceMap.erase(itr);
-            fenceMap.insert(tie(timelineOffset, max(syncPoint, oldSyncPoint)));
+            fenceMap.insert(make_pair(timelineOffset, max(syncPoint, oldSyncPoint)));
         }
 
         // Merge.
         fence = SyncFence(fence, SyncFence(timeline, syncPoint));
         ASSERT_TRUE(fence.isValid());
+        CheckModernLegacyInfoMatch(fence);
     }
 
     // Confirm our map matches the fence.
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/libsystem/include/system/graphics-base.h b/libsystem/include/system/graphics-base.h
new file mode 100644
index 0000000..2a44faf
--- /dev/null
+++ b/libsystem/include/system/graphics-base.h
@@ -0,0 +1,141 @@
+// This file is autogenerated by hidl-gen. Do not edit manually.
+// Source: android.hardware.graphics.common@1.0
+// Root: android.hardware:hardware/interfaces
+
+#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
+#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    HAL_PIXEL_FORMAT_RGBA_8888 = 1,
+    HAL_PIXEL_FORMAT_RGBX_8888 = 2,
+    HAL_PIXEL_FORMAT_RGB_888 = 3,
+    HAL_PIXEL_FORMAT_RGB_565 = 4,
+    HAL_PIXEL_FORMAT_BGRA_8888 = 5,
+    HAL_PIXEL_FORMAT_RGBA_1010102 = 43, // 0x2B
+    HAL_PIXEL_FORMAT_RGBA_FP16 = 22, // 0x16
+    HAL_PIXEL_FORMAT_YV12 = 842094169, // 0x32315659
+    HAL_PIXEL_FORMAT_Y8 = 538982489, // 0x20203859
+    HAL_PIXEL_FORMAT_Y16 = 540422489, // 0x20363159
+    HAL_PIXEL_FORMAT_RAW16 = 32, // 0x20
+    HAL_PIXEL_FORMAT_RAW10 = 37, // 0x25
+    HAL_PIXEL_FORMAT_RAW12 = 38, // 0x26
+    HAL_PIXEL_FORMAT_RAW_OPAQUE = 36, // 0x24
+    HAL_PIXEL_FORMAT_BLOB = 33, // 0x21
+    HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 34, // 0x22
+    HAL_PIXEL_FORMAT_YCBCR_420_888 = 35, // 0x23
+    HAL_PIXEL_FORMAT_YCBCR_422_888 = 39, // 0x27
+    HAL_PIXEL_FORMAT_YCBCR_444_888 = 40, // 0x28
+    HAL_PIXEL_FORMAT_FLEX_RGB_888 = 41, // 0x29
+    HAL_PIXEL_FORMAT_FLEX_RGBA_8888 = 42, // 0x2A
+    HAL_PIXEL_FORMAT_YCBCR_422_SP = 16, // 0x10
+    HAL_PIXEL_FORMAT_YCRCB_420_SP = 17, // 0x11
+    HAL_PIXEL_FORMAT_YCBCR_422_I = 20, // 0x14
+    HAL_PIXEL_FORMAT_JPEG = 256, // 0x100
+} android_pixel_format_t;
+
+typedef enum {
+    HAL_TRANSFORM_FLIP_H = 1, // 0x01
+    HAL_TRANSFORM_FLIP_V = 2, // 0x02
+    HAL_TRANSFORM_ROT_90 = 4, // 0x04
+    HAL_TRANSFORM_ROT_180 = 3, // 0x03
+    HAL_TRANSFORM_ROT_270 = 7, // 0x07
+} android_transform_t;
+
+typedef enum {
+    HAL_DATASPACE_UNKNOWN = 0, // 0x0
+    HAL_DATASPACE_ARBITRARY = 1, // 0x1
+    HAL_DATASPACE_STANDARD_SHIFT = 16,
+    HAL_DATASPACE_STANDARD_MASK = 4128768, // (63 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_UNSPECIFIED = 0, // (0 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT709 = 65536, // (1 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_625 = 131072, // (2 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED = 196608, // (3 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_525 = 262144, // (4 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED = 327680, // (5 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT2020 = 393216, // (6 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE = 458752, // (7 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT470M = 524288, // (8 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_FILM = 589824, // (9 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_DCI_P3 = 655360, // (10 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_ADOBE_RGB = 720896, // (11 << STANDARD_SHIFT)
+    HAL_DATASPACE_TRANSFER_SHIFT = 22,
+    HAL_DATASPACE_TRANSFER_MASK = 130023424, // (31 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_UNSPECIFIED = 0, // (0 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_LINEAR = 4194304, // (1 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_SRGB = 8388608, // (2 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_SMPTE_170M = 12582912, // (3 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_2 = 16777216, // (4 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_6 = 20971520, // (5 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_8 = 25165824, // (6 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_ST2084 = 29360128, // (7 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_HLG = 33554432, // (8 << TRANSFER_SHIFT)
+    HAL_DATASPACE_RANGE_SHIFT = 27,
+    HAL_DATASPACE_RANGE_MASK = 939524096, // (7 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_UNSPECIFIED = 0, // (0 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_FULL = 134217728, // (1 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_LIMITED = 268435456, // (2 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_EXTENDED = 402653184, // (3 << RANGE_SHIFT)
+    HAL_DATASPACE_SRGB_LINEAR = 512, // 0x200
+    HAL_DATASPACE_V0_SRGB_LINEAR = 138477568, // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_V0_SCRGB_LINEAR = 406913024, // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_EXTENDED)
+    HAL_DATASPACE_SRGB = 513, // 0x201
+    HAL_DATASPACE_V0_SRGB = 142671872, // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_FULL)
+    HAL_DATASPACE_V0_SCRGB = 411107328, // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_EXTENDED)
+    HAL_DATASPACE_JFIF = 257, // 0x101
+    HAL_DATASPACE_V0_JFIF = 146931712, // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_FULL)
+    HAL_DATASPACE_BT601_625 = 258, // 0x102
+    HAL_DATASPACE_V0_BT601_625 = 281149440, // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_BT601_525 = 259, // 0x103
+    HAL_DATASPACE_V0_BT601_525 = 281280512, // ((STANDARD_BT601_525 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_BT709 = 260, // 0x104
+    HAL_DATASPACE_V0_BT709 = 281083904, // ((STANDARD_BT709 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_DCI_P3_LINEAR = 139067392, // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_DCI_P3 = 155844608, // ((STANDARD_DCI_P3 | TRANSFER_GAMMA2_6) | RANGE_FULL)
+    HAL_DATASPACE_DISPLAY_P3_LINEAR = 139067392, // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_DISPLAY_P3 = 143261696, // ((STANDARD_DCI_P3 | TRANSFER_SRGB) | RANGE_FULL)
+    HAL_DATASPACE_ADOBE_RGB = 151715840, // ((STANDARD_ADOBE_RGB | TRANSFER_GAMMA2_2) | RANGE_FULL)
+    HAL_DATASPACE_BT2020_LINEAR = 138805248, // ((STANDARD_BT2020 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_BT2020 = 147193856, // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_FULL)
+    HAL_DATASPACE_BT2020_PQ = 163971072, // ((STANDARD_BT2020 | TRANSFER_ST2084) | RANGE_FULL)
+    HAL_DATASPACE_DEPTH = 4096, // 0x1000
+    HAL_DATASPACE_SENSOR = 4097, // 0x1001
+} android_dataspace_t;
+
+typedef enum {
+    HAL_COLOR_MODE_NATIVE = 0,
+    HAL_COLOR_MODE_STANDARD_BT601_625 = 1,
+    HAL_COLOR_MODE_STANDARD_BT601_625_UNADJUSTED = 2,
+    HAL_COLOR_MODE_STANDARD_BT601_525 = 3,
+    HAL_COLOR_MODE_STANDARD_BT601_525_UNADJUSTED = 4,
+    HAL_COLOR_MODE_STANDARD_BT709 = 5,
+    HAL_COLOR_MODE_DCI_P3 = 6,
+    HAL_COLOR_MODE_SRGB = 7,
+    HAL_COLOR_MODE_ADOBE_RGB = 8,
+    HAL_COLOR_MODE_DISPLAY_P3 = 9,
+} android_color_mode_t;
+
+typedef enum {
+    HAL_COLOR_TRANSFORM_IDENTITY = 0,
+    HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX = 1,
+    HAL_COLOR_TRANSFORM_VALUE_INVERSE = 2,
+    HAL_COLOR_TRANSFORM_GRAYSCALE = 3,
+    HAL_COLOR_TRANSFORM_CORRECT_PROTANOPIA = 4,
+    HAL_COLOR_TRANSFORM_CORRECT_DEUTERANOPIA = 5,
+    HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA = 6,
+} android_color_transform_t;
+
+typedef enum {
+    HAL_HDR_DOLBY_VISION = 1,
+    HAL_HDR_HDR10 = 2,
+    HAL_HDR_HLG = 3,
+} android_hdr_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
diff --git a/libsystem/include/system/graphics.h b/libsystem/include/system/graphics.h
new file mode 100644
index 0000000..1a99187
--- /dev/null
+++ b/libsystem/include/system/graphics.h
@@ -0,0 +1,264 @@
+/*
+ * 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 SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
+#define SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/*
+ * Some of the enums are now defined in HIDL in hardware/interfaces and are
+ * generated.
+ */
+#include "graphics-base.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* for compatibility */
+#define HAL_PIXEL_FORMAT_YCbCr_420_888 HAL_PIXEL_FORMAT_YCBCR_420_888
+#define HAL_PIXEL_FORMAT_YCbCr_422_888 HAL_PIXEL_FORMAT_YCBCR_422_888
+#define HAL_PIXEL_FORMAT_YCbCr_444_888 HAL_PIXEL_FORMAT_YCBCR_444_888
+#define HAL_PIXEL_FORMAT_YCbCr_422_SP HAL_PIXEL_FORMAT_YCBCR_422_SP
+#define HAL_PIXEL_FORMAT_YCrCb_420_SP HAL_PIXEL_FORMAT_YCRCB_420_SP
+#define HAL_PIXEL_FORMAT_YCbCr_422_I HAL_PIXEL_FORMAT_YCBCR_422_I
+typedef android_pixel_format_t android_pixel_format;
+typedef android_transform_t android_transform;
+typedef android_dataspace_t android_dataspace;
+typedef android_color_mode_t android_color_mode;
+typedef android_color_transform_t android_color_transform;
+typedef android_hdr_t android_hdr;
+
+/*
+ * If the HAL needs to create service threads to handle graphics related
+ * tasks, these threads need to run at HAL_PRIORITY_URGENT_DISPLAY priority
+ * if they can block the main rendering thread in any way.
+ *
+ * the priority of the current thread can be set with:
+ *
+ *      #include <sys/resource.h>
+ *      setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
+ *
+ */
+
+#define HAL_PRIORITY_URGENT_DISPLAY     (-8)
+
+/*
+ * Structure for describing YCbCr formats for consumption by applications.
+ * This is used with HAL_PIXEL_FORMAT_YCbCr_*_888.
+ *
+ * Buffer chroma subsampling is defined in the format.
+ * e.g. HAL_PIXEL_FORMAT_YCbCr_420_888 has subsampling 4:2:0.
+ *
+ * Buffers must have a 8 bit depth.
+ *
+ * y, cb, and cr point to the first byte of their respective planes.
+ *
+ * Stride describes the distance in bytes from the first value of one row of
+ * the image to the first value of the next row.  It includes the width of the
+ * image plus padding.
+ * ystride is the stride of the luma plane.
+ * cstride is the stride of the chroma planes.
+ *
+ * chroma_step is the distance in bytes from one chroma pixel value to the
+ * next.  This is 2 bytes for semiplanar (because chroma values are interleaved
+ * and each chroma value is one byte) and 1 for planar.
+ */
+
+struct android_ycbcr {
+    void *y;
+    void *cb;
+    void *cr;
+    size_t ystride;
+    size_t cstride;
+    size_t chroma_step;
+
+    /** reserved for future use, set to 0 by gralloc's (*lock_ycbcr)() */
+    uint32_t reserved[8];
+};
+
+/*
+ * Structures for describing flexible YUVA/RGBA formats for consumption by
+ * applications. Such flexible formats contain a plane for each component (e.g.
+ * red, green, blue), where each plane is laid out in a grid-like pattern
+ * occupying unique byte addresses and with consistent byte offsets between
+ * neighboring pixels.
+ *
+ * The android_flex_layout structure is used with any pixel format that can be
+ * represented by it, such as:
+ *  - HAL_PIXEL_FORMAT_YCbCr_*_888
+ *  - HAL_PIXEL_FORMAT_FLEX_RGB*_888
+ *  - HAL_PIXEL_FORMAT_RGB[AX]_888[8],BGRA_8888,RGB_888
+ *  - HAL_PIXEL_FORMAT_YV12,Y8,Y16,YCbCr_422_SP/I,YCrCb_420_SP
+ *  - even implementation defined formats that can be represented by
+ *    the structures
+ *
+ * Vertical increment (aka. row increment or stride) describes the distance in
+ * bytes from the first pixel of one row to the first pixel of the next row
+ * (below) for the component plane. This can be negative.
+ *
+ * Horizontal increment (aka. column or pixel increment) describes the distance
+ * in bytes from one pixel to the next pixel (to the right) on the same row for
+ * the component plane. This can be negative.
+ *
+ * Each plane can be subsampled either vertically or horizontally by
+ * a power-of-two factor.
+ *
+ * The bit-depth of each component can be arbitrary, as long as the pixels are
+ * laid out on whole bytes, in native byte-order, using the most significant
+ * bits of each unit.
+ */
+
+typedef enum android_flex_component {
+    /* luma */
+    FLEX_COMPONENT_Y = 1 << 0,
+    /* chroma blue */
+    FLEX_COMPONENT_Cb = 1 << 1,
+    /* chroma red */
+    FLEX_COMPONENT_Cr = 1 << 2,
+
+    /* red */
+    FLEX_COMPONENT_R = 1 << 10,
+    /* green */
+    FLEX_COMPONENT_G = 1 << 11,
+    /* blue */
+    FLEX_COMPONENT_B = 1 << 12,
+
+    /* alpha */
+    FLEX_COMPONENT_A = 1 << 30,
+} android_flex_component_t;
+
+typedef struct android_flex_plane {
+    /* pointer to the first byte of the top-left pixel of the plane. */
+    uint8_t *top_left;
+
+    android_flex_component_t component;
+
+    /* bits allocated for the component in each pixel. Must be a positive
+       multiple of 8. */
+    int32_t bits_per_component;
+    /* number of the most significant bits used in the format for this
+       component. Must be between 1 and bits_per_component, inclusive. */
+    int32_t bits_used;
+
+    /* horizontal increment */
+    int32_t h_increment;
+    /* vertical increment */
+    int32_t v_increment;
+    /* horizontal subsampling. Must be a positive power of 2. */
+    int32_t h_subsampling;
+    /* vertical subsampling. Must be a positive power of 2. */
+    int32_t v_subsampling;
+} android_flex_plane_t;
+
+typedef enum android_flex_format {
+    /* not a flexible format */
+    FLEX_FORMAT_INVALID = 0x0,
+    FLEX_FORMAT_Y = FLEX_COMPONENT_Y,
+    FLEX_FORMAT_YCbCr = FLEX_COMPONENT_Y | FLEX_COMPONENT_Cb | FLEX_COMPONENT_Cr,
+    FLEX_FORMAT_YCbCrA = FLEX_FORMAT_YCbCr | FLEX_COMPONENT_A,
+    FLEX_FORMAT_RGB = FLEX_COMPONENT_R | FLEX_COMPONENT_G | FLEX_COMPONENT_B,
+    FLEX_FORMAT_RGBA = FLEX_FORMAT_RGB | FLEX_COMPONENT_A,
+} android_flex_format_t;
+
+typedef struct android_flex_layout {
+    /* the kind of flexible format */
+    android_flex_format_t format;
+
+    /* number of planes; 0 for FLEX_FORMAT_INVALID */
+    uint32_t num_planes;
+    /* a plane for each component; ordered in increasing component value order.
+       E.g. FLEX_FORMAT_RGBA maps 0 -> R, 1 -> G, etc.
+       Can be NULL for FLEX_FORMAT_INVALID */
+    android_flex_plane_t *planes;
+} android_flex_layout_t;
+
+/**
+ * Structure used to define depth point clouds for format HAL_PIXEL_FORMAT_BLOB
+ * with dataSpace value of HAL_DATASPACE_DEPTH.
+ * When locking a native buffer of the above format and dataSpace value,
+ * the vaddr pointer can be cast to this structure.
+ *
+ * A variable-length list of (x,y,z, confidence) 3D points, as floats.  (x, y,
+ * z) represents a measured point's position, with the coordinate system defined
+ * by the data source.  Confidence represents the estimated likelihood that this
+ * measurement is correct. It is between 0.f and 1.f, inclusive, with 1.f ==
+ * 100% confidence.
+ *
+ * num_points is the number of points in the list
+ *
+ * xyz_points is the flexible array of floating-point values.
+ *   It contains (num_points) * 4 floats.
+ *
+ *   For example:
+ *     android_depth_points d = get_depth_buffer();
+ *     struct {
+ *       float x; float y; float z; float confidence;
+ *     } firstPoint, lastPoint;
+ *
+ *     firstPoint.x = d.xyzc_points[0];
+ *     firstPoint.y = d.xyzc_points[1];
+ *     firstPoint.z = d.xyzc_points[2];
+ *     firstPoint.confidence = d.xyzc_points[3];
+ *     lastPoint.x = d.xyzc_points[(d.num_points - 1) * 4 + 0];
+ *     lastPoint.y = d.xyzc_points[(d.num_points - 1) * 4 + 1];
+ *     lastPoint.z = d.xyzc_points[(d.num_points - 1) * 4 + 2];
+ *     lastPoint.confidence = d.xyzc_points[(d.num_points - 1) * 4 + 3];
+ */
+
+struct android_depth_points {
+    uint32_t num_points;
+
+    /** reserved for future use, set to 0 by gralloc's (*lock)() */
+    uint32_t reserved[8];
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wc99-extensions"
+#endif
+    float xyzc_points[];
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+};
+
+/**
+  * These structures are used to define the reference display's
+  * capabilities for HDR content. Display engine can use this
+  * to better tone map content to user's display.
+  * Color is defined in CIE XYZ coordinates
+  */
+struct android_xy_color {
+    float x;
+    float y;
+};
+
+struct android_smpte2086_metadata {
+    struct android_xy_color displayPrimaryRed;
+    struct android_xy_color displayPrimaryGreen;
+    struct android_xy_color displayPrimaryBlue;
+    struct android_xy_color whitePoint;
+    float maxLuminance;
+    float minLuminance;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SYSTEM_CORE_INCLUDE_ANDROID_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/libsystem/include/system/radio.h b/libsystem/include/system/radio.h
new file mode 100644
index 0000000..acf3ea7
--- /dev/null
+++ b/libsystem/include/system/radio.h
@@ -0,0 +1,254 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_RADIO_H
+#define ANDROID_RADIO_H
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+
+#define RADIO_NUM_BANDS_MAX     16
+#define RADIO_NUM_SPACINGS_MAX  16
+#define RADIO_STRING_LEN_MAX    128
+
+/*
+ * Radio hardware module class. A given radio hardware module HAL is of one class
+ * only. The platform can not have more than one hardware module of each class.
+ * Current version of the framework only supports RADIO_CLASS_AM_FM.
+ */
+typedef enum {
+    RADIO_CLASS_AM_FM = 0,  /* FM (including HD radio) and AM */
+    RADIO_CLASS_SAT   = 1,  /* Satellite Radio */
+    RADIO_CLASS_DT    = 2,  /* Digital Radio (DAB) */
+} radio_class_t;
+
+/* value for field "type" of radio band described in struct radio_hal_band_config */
+typedef enum {
+    RADIO_BAND_AM     = 0,  /* Amplitude Modulation band: LW, MW, SW */
+    RADIO_BAND_FM     = 1,  /* Frequency Modulation band: FM */
+    RADIO_BAND_FM_HD  = 2,  /* FM HD Radio / DRM (IBOC) */
+    RADIO_BAND_AM_HD  = 3,  /* AM HD Radio / DRM (IBOC) */
+} radio_band_t;
+
+/* RDS variant implemented. A struct radio_hal_fm_band_config can list none or several. */
+enum {
+    RADIO_RDS_NONE   = 0x0,
+    RADIO_RDS_WORLD  = 0x01,
+    RADIO_RDS_US     = 0x02,
+};
+typedef unsigned int radio_rds_t;
+
+/* FM deemphasis variant implemented. A struct radio_hal_fm_band_config can list one or more. */
+enum {
+    RADIO_DEEMPHASIS_50   = 0x1,
+    RADIO_DEEMPHASIS_75   = 0x2,
+};
+typedef unsigned int radio_deemphasis_t;
+
+/* Region a particular radio band configuration corresponds to. Not used at the HAL.
+ * Derived by the framework when converting the band descriptors retrieved from the HAL to
+ * individual band descriptors for each supported region. */
+typedef enum {
+    RADIO_REGION_NONE  = -1,
+    RADIO_REGION_ITU_1 = 0,
+    RADIO_REGION_ITU_2 = 1,
+    RADIO_REGION_OIRT  = 2,
+    RADIO_REGION_JAPAN = 3,
+    RADIO_REGION_KOREA = 4,
+} radio_region_t;
+
+/* scanning direction for scan() and step() tuner APIs */
+typedef enum {
+    RADIO_DIRECTION_UP,
+    RADIO_DIRECTION_DOWN
+} radio_direction_t;
+
+/* unique handle allocated to a radio module */
+typedef uint32_t radio_handle_t;
+
+/* Opaque meta data structure used by radio meta data API (see system/radio_metadata.h) */
+typedef struct radio_metadata radio_metadata_t;
+
+
+/* Additional attributes for an FM band configuration */
+typedef struct radio_hal_fm_band_config {
+    radio_deemphasis_t  deemphasis; /* deemphasis variant */
+    bool                stereo;     /* stereo supported */
+    radio_rds_t         rds;        /* RDS variants supported */
+    bool                ta;         /* Traffic Announcement supported */
+    bool                af;         /* Alternate Frequency supported */
+    bool                ea;         /* Emergency announcements supported */
+} radio_hal_fm_band_config_t;
+
+/* Additional attributes for an AM band configuration */
+typedef struct radio_hal_am_band_config {
+    bool                stereo;     /* stereo supported */
+} radio_hal_am_band_config_t;
+
+/* Radio band configuration. Describes a given band supported by the radio module.
+ * The HAL can expose only one band per type with the the maximum range supported and all options.
+ * THe framework will derive the actual regions were this module can operate and expose separate
+ * band configurations for applications to chose from. */
+typedef struct radio_hal_band_config {
+    radio_band_t type;
+    bool         antenna_connected;
+    uint32_t     lower_limit;
+    uint32_t     upper_limit;
+    uint32_t     num_spacings;
+    uint32_t     spacings[RADIO_NUM_SPACINGS_MAX];
+    union {
+        radio_hal_fm_band_config_t fm;
+        radio_hal_am_band_config_t am;
+    };
+} radio_hal_band_config_t;
+
+/* Used internally by the framework to represent a band for s specific region */
+typedef struct radio_band_config {
+    radio_region_t  region;
+    radio_hal_band_config_t band;
+} radio_band_config_t;
+
+
+/* Exposes properties of a given hardware radio module.
+ * NOTE: current framework implementation supports only one audio source (num_audio_sources = 1).
+ * The source corresponds to AUDIO_DEVICE_IN_FM_TUNER.
+ * If more than one tuner is supported (num_tuners > 1), only one can be connected to the audio
+ * source. */
+typedef struct radio_hal_properties {
+    radio_class_t   class_id;   /* Class of this module. E.g RADIO_CLASS_AM_FM */
+    char            implementor[RADIO_STRING_LEN_MAX];  /* implementor name */
+    char            product[RADIO_STRING_LEN_MAX];  /* product name */
+    char            version[RADIO_STRING_LEN_MAX];  /* product version */
+    char            serial[RADIO_STRING_LEN_MAX];  /* serial number (for subscription services) */
+    uint32_t        num_tuners;     /* number of tuners controllable independently */
+    uint32_t        num_audio_sources; /* number of audio sources driven simultaneously */
+    bool            supports_capture; /* the hardware supports capture of audio source audio HAL */
+    uint32_t        num_bands;      /* number of band descriptors */
+    radio_hal_band_config_t bands[RADIO_NUM_BANDS_MAX]; /* band descriptors */
+} radio_hal_properties_t;
+
+/* Used internally by the framework. Same information as in struct radio_hal_properties plus a
+ * unique handle and one band configuration per region. */
+typedef struct radio_properties {
+    radio_handle_t      handle;
+    radio_class_t       class_id;
+    char                implementor[RADIO_STRING_LEN_MAX];
+    char                product[RADIO_STRING_LEN_MAX];
+    char                version[RADIO_STRING_LEN_MAX];
+    char                serial[RADIO_STRING_LEN_MAX];
+    uint32_t            num_tuners;
+    uint32_t            num_audio_sources;
+    bool                supports_capture;
+    uint32_t            num_bands;
+    radio_band_config_t bands[RADIO_NUM_BANDS_MAX];
+} radio_properties_t;
+
+/* Radio program information. Returned by the HAL with event RADIO_EVENT_TUNED.
+ * Contains information on currently tuned channel.
+ */
+typedef struct radio_program_info {
+    uint32_t         channel;   /* current channel. (e.g kHz for band type RADIO_BAND_FM) */
+    uint32_t         sub_channel; /* current sub channel. (used for RADIO_BAND_FM_HD) */
+    bool             tuned;     /* tuned to a program or not */
+    bool             stereo;    /* program is stereo or not */
+    bool             digital;   /* digital program or not (e.g HD Radio program) */
+    uint32_t         signal_strength; /* signal strength from 0 to 100 */
+                                /* meta data (e.g PTY, song title ...), must not be NULL */
+    __attribute__((aligned(8))) radio_metadata_t *metadata;
+} radio_program_info_t;
+
+
+/* Events sent to the framework via the HAL callback. An event can notify the completion of an
+ * asynchronous command (configuration, tune, scan ...) or a spontaneous change (antenna connection,
+ * failure, AF switching, meta data reception... */
+enum {
+    RADIO_EVENT_HW_FAILURE  = 0,  /* hardware module failure. Requires reopening the tuner */
+    RADIO_EVENT_CONFIG      = 1,  /* configuration change completed */
+    RADIO_EVENT_ANTENNA     = 2,  /* Antenna connected, disconnected */
+    RADIO_EVENT_TUNED       = 3,  /* tune, step, scan completed */
+    RADIO_EVENT_METADATA    = 4,  /* New meta data received */
+    RADIO_EVENT_TA          = 5,  /* Traffic announcement start or stop */
+    RADIO_EVENT_AF_SWITCH   = 6,  /* Switch to Alternate Frequency */
+    RADIO_EVENT_EA          = 7,  /* Emergency announcement start or stop */
+    // begin framework only events
+    RADIO_EVENT_CONTROL     = 100, /* loss/gain of tuner control */
+    RADIO_EVENT_SERVER_DIED = 101, /* radio service died */
+};
+typedef unsigned int radio_event_type_t;
+
+/* Event passed to the framework by the HAL callback */
+typedef struct radio_hal_event {
+    radio_event_type_t  type;       /* event type */
+    int32_t             status;     /* used by RADIO_EVENT_CONFIG, RADIO_EVENT_TUNED */
+    union {
+        /* RADIO_EVENT_ANTENNA, RADIO_EVENT_TA, RADIO_EVENT_EA */
+        bool                    on;
+        radio_hal_band_config_t config; /* RADIO_EVENT_CONFIG */
+        radio_program_info_t    info;   /* RADIO_EVENT_TUNED, RADIO_EVENT_AF_SWITCH */
+        radio_metadata_t        *metadata; /* RADIO_EVENT_METADATA */
+    };
+} radio_hal_event_t;
+
+/* Used internally by the framework. Same information as in struct radio_hal_event */
+typedef struct radio_event {
+    radio_event_type_t  type;
+    int32_t             status;
+    union {
+        bool                    on;
+        radio_band_config_t     config;
+        radio_program_info_t    info;
+                                /* meta data (e.g PTY, song title ...), must not be NULL */
+        __attribute__((aligned(8))) radio_metadata_t *metadata;
+    };
+} radio_event_t;
+
+
+static inline
+radio_rds_t radio_rds_for_region(bool rds, radio_region_t region) {
+    if (!rds)
+        return RADIO_RDS_NONE;
+    switch(region) {
+        case RADIO_REGION_ITU_1:
+        case RADIO_REGION_OIRT:
+        case RADIO_REGION_JAPAN:
+        case RADIO_REGION_KOREA:
+            return RADIO_RDS_WORLD;
+        case RADIO_REGION_ITU_2:
+            return RADIO_RDS_US;
+        default:
+            return RADIO_REGION_NONE;
+    }
+}
+
+static inline
+radio_deemphasis_t radio_demephasis_for_region(radio_region_t region) {
+    switch(region) {
+        case RADIO_REGION_KOREA:
+        case RADIO_REGION_ITU_2:
+            return RADIO_DEEMPHASIS_75;
+        case RADIO_REGION_ITU_1:
+        case RADIO_REGION_OIRT:
+        case RADIO_REGION_JAPAN:
+        default:
+            return RADIO_DEEMPHASIS_50;
+    }
+}
+
+#endif  // ANDROID_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/libsystem/include/system/window-deprecated.h b/libsystem/include/system/window-deprecated.h
new file mode 100644
index 0000000..e836aea
--- /dev/null
+++ b/libsystem/include/system/window-deprecated.h
@@ -0,0 +1,1114 @@
+/*
+ * 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.
+ */
+
+/**************************************************************************************************
+ **************************************************************************************************
+ ****                                                                                          ****
+ ****  DEPRECATED                                                                              ****
+ ****                                                                                          ****
+ ****  THIS FILE EXISTS ONLY FOR BACKWARD SOURCE COMPATIBILITY.                                ****
+ ****                                                                                          ****
+ ****  DO NOT ADD TO THIS FILE.                                                                ****
+ ****                                                                                          ****
+ ****  Driver implementors (vendors) should use vndk/window.h                                  ****
+ ****  (frameworks/native/libs/nativewindow/include/vndk/window.h)                             ****
+ ****                                                                                          ****
+ ****  Internal definition can be found here:                                                  ****
+ ****  frameworks/native/libs/nativewindow/include/system/window.h                             ****
+ ****                                                                                          ****
+ **************************************************************************************************
+ **************************************************************************************************/
+
+#pragma once
+
+#include <cutils/native_handle.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/cdefs.h>
+#include <system/graphics.h>
+#include <unistd.h>
+#include <stdbool.h>
+
+#ifndef __UNUSED
+#define __UNUSED __attribute__((__unused__))
+#endif
+#ifndef __deprecated
+#define __deprecated __attribute__((__deprecated__))
+#endif
+
+__BEGIN_DECLS
+
+/*****************************************************************************/
+
+#ifdef __cplusplus
+#define ANDROID_NATIVE_UNSIGNED_CAST(x) static_cast<unsigned int>(x)
+#else
+#define ANDROID_NATIVE_UNSIGNED_CAST(x) ((unsigned int)(x))
+#endif
+
+#define ANDROID_NATIVE_MAKE_CONSTANT(a,b,c,d) \
+    ((ANDROID_NATIVE_UNSIGNED_CAST(a) << 24) | \
+     (ANDROID_NATIVE_UNSIGNED_CAST(b) << 16) | \
+     (ANDROID_NATIVE_UNSIGNED_CAST(c) << 8) | \
+     (ANDROID_NATIVE_UNSIGNED_CAST(d)))
+
+#define ANDROID_NATIVE_WINDOW_MAGIC \
+    ANDROID_NATIVE_MAKE_CONSTANT('_','w','n','d')
+
+#define ANDROID_NATIVE_BUFFER_MAGIC \
+    ANDROID_NATIVE_MAKE_CONSTANT('_','b','f','r')
+
+// ---------------------------------------------------------------------------
+
+// This #define may be used to conditionally compile device-specific code to
+// support either the prior ANativeWindow interface, which did not pass libsync
+// fences around, or the new interface that does.  This #define is only present
+// when the ANativeWindow interface does include libsync support.
+#define ANDROID_NATIVE_WINDOW_HAS_SYNC 1
+
+// ---------------------------------------------------------------------------
+
+typedef const native_handle_t* buffer_handle_t;
+
+// ---------------------------------------------------------------------------
+
+typedef struct android_native_rect_t
+{
+    int32_t left;
+    int32_t top;
+    int32_t right;
+    int32_t bottom;
+} android_native_rect_t;
+
+// ---------------------------------------------------------------------------
+
+typedef struct android_native_base_t
+{
+    /* a magic value defined by the actual EGL native type */
+    int magic;
+
+    /* the sizeof() of the actual EGL native type */
+    int version;
+
+    void* reserved[4];
+
+    /* reference-counting interface */
+    void (*incRef)(struct android_native_base_t* base);
+    void (*decRef)(struct android_native_base_t* base);
+} android_native_base_t;
+
+typedef struct ANativeWindowBuffer
+{
+#ifdef __cplusplus
+    ANativeWindowBuffer() {
+        common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
+        common.version = sizeof(ANativeWindowBuffer);
+        memset(common.reserved, 0, sizeof(common.reserved));
+    }
+
+    // Implement the methods that sp<ANativeWindowBuffer> expects so that it
+    // can be used to automatically refcount ANativeWindowBuffer's.
+    void incStrong(const void* /*id*/) const {
+        common.incRef(const_cast<android_native_base_t*>(&common));
+    }
+    void decStrong(const void* /*id*/) const {
+        common.decRef(const_cast<android_native_base_t*>(&common));
+    }
+#endif
+
+    struct android_native_base_t common;
+
+    int width;
+    int height;
+    int stride;
+    int format;
+    int usage;
+    uintptr_t layerCount;
+
+    void* reserved[1];
+
+    buffer_handle_t handle;
+
+    void* reserved_proc[8];
+} ANativeWindowBuffer_t;
+
+// Old typedef for backwards compatibility.
+typedef ANativeWindowBuffer_t android_native_buffer_t;
+
+// ---------------------------------------------------------------------------
+
+/* attributes queriable with query() */
+enum {
+    NATIVE_WINDOW_WIDTH     = 0,
+    NATIVE_WINDOW_HEIGHT    = 1,
+    NATIVE_WINDOW_FORMAT    = 2,
+
+    /* The minimum number of buffers that must remain un-dequeued after a buffer
+     * has been queued.  This value applies only if set_buffer_count was used to
+     * override the number of buffers and if a buffer has since been queued.
+     * Users of the set_buffer_count ANativeWindow method should query this
+     * value before calling set_buffer_count.  If it is necessary to have N
+     * buffers simultaneously dequeued as part of the steady-state operation,
+     * and this query returns M then N+M buffers should be requested via
+     * native_window_set_buffer_count.
+     *
+     * Note that this value does NOT apply until a single buffer has been
+     * queued.  In particular this means that it is possible to:
+     *
+     * 1. Query M = min undequeued buffers
+     * 2. Set the buffer count to N + M
+     * 3. Dequeue all N + M buffers
+     * 4. Cancel M buffers
+     * 5. Queue, dequeue, queue, dequeue, ad infinitum
+     */
+    NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS = 3,
+
+    /* Check whether queueBuffer operations on the ANativeWindow send the buffer
+     * to the window compositor.  The query sets the returned 'value' argument
+     * to 1 if the ANativeWindow DOES send queued buffers directly to the window
+     * compositor and 0 if the buffers do not go directly to the window
+     * compositor.
+     *
+     * This can be used to determine whether protected buffer content should be
+     * sent to the ANativeWindow.  Note, however, that a result of 1 does NOT
+     * indicate that queued buffers will be protected from applications or users
+     * capturing their contents.  If that behavior is desired then some other
+     * mechanism (e.g. the GRALLOC_USAGE_PROTECTED flag) should be used in
+     * conjunction with this query.
+     */
+    NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER = 4,
+
+    /* Get the concrete type of a ANativeWindow.  See below for the list of
+     * possible return values.
+     *
+     * This query should not be used outside the Android framework and will
+     * likely be removed in the near future.
+     */
+    NATIVE_WINDOW_CONCRETE_TYPE = 5,
+
+
+    /*
+     * Default width and height of ANativeWindow buffers, these are the
+     * dimensions of the window buffers irrespective of the
+     * NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS call and match the native window
+     * size unless overridden by NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS.
+     */
+    NATIVE_WINDOW_DEFAULT_WIDTH = 6,
+    NATIVE_WINDOW_DEFAULT_HEIGHT = 7,
+
+    /*
+     * transformation that will most-likely be applied to buffers. This is only
+     * a hint, the actual transformation applied might be different.
+     *
+     * INTENDED USE:
+     *
+     * The transform hint can be used by a producer, for instance the GLES
+     * driver, to pre-rotate the rendering such that the final transformation
+     * in the composer is identity. This can be very useful when used in
+     * conjunction with the h/w composer HAL, in situations where it
+     * cannot handle arbitrary rotations.
+     *
+     * 1. Before dequeuing a buffer, the GL driver (or any other ANW client)
+     *    queries the ANW for NATIVE_WINDOW_TRANSFORM_HINT.
+     *
+     * 2. The GL driver overrides the width and height of the ANW to
+     *    account for NATIVE_WINDOW_TRANSFORM_HINT. This is done by querying
+     *    NATIVE_WINDOW_DEFAULT_{WIDTH | HEIGHT}, swapping the dimensions
+     *    according to NATIVE_WINDOW_TRANSFORM_HINT and calling
+     *    native_window_set_buffers_dimensions().
+     *
+     * 3. The GL driver dequeues a buffer of the new pre-rotated size.
+     *
+     * 4. The GL driver renders to the buffer such that the image is
+     *    already transformed, that is applying NATIVE_WINDOW_TRANSFORM_HINT
+     *    to the rendering.
+     *
+     * 5. The GL driver calls native_window_set_transform to apply
+     *    inverse transformation to the buffer it just rendered.
+     *    In order to do this, the GL driver needs
+     *    to calculate the inverse of NATIVE_WINDOW_TRANSFORM_HINT, this is
+     *    done easily:
+     *
+     *        int hintTransform, inverseTransform;
+     *        query(..., NATIVE_WINDOW_TRANSFORM_HINT, &hintTransform);
+     *        inverseTransform = hintTransform;
+     *        if (hintTransform & HAL_TRANSFORM_ROT_90)
+     *            inverseTransform ^= HAL_TRANSFORM_ROT_180;
+     *
+     *
+     * 6. The GL driver queues the pre-transformed buffer.
+     *
+     * 7. The composer combines the buffer transform with the display
+     *    transform.  If the buffer transform happens to cancel out the
+     *    display transform then no rotation is needed.
+     *
+     */
+    NATIVE_WINDOW_TRANSFORM_HINT = 8,
+
+    /*
+     * Boolean that indicates whether the consumer is running more than
+     * one buffer behind the producer.
+     */
+    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND = 9,
+
+    /*
+     * The consumer gralloc usage bits currently set by the consumer.
+     * The values are defined in hardware/libhardware/include/gralloc.h.
+     */
+    NATIVE_WINDOW_CONSUMER_USAGE_BITS = 10,
+
+    /**
+     * Transformation that will by applied to buffers by the hwcomposer.
+     * This must not be set or checked by producer endpoints, and will
+     * disable the transform hint set in SurfaceFlinger (see
+     * NATIVE_WINDOW_TRANSFORM_HINT).
+     *
+     * INTENDED USE:
+     * Temporary - Please do not use this.  This is intended only to be used
+     * by the camera's LEGACY mode.
+     *
+     * In situations where a SurfaceFlinger client wishes to set a transform
+     * that is not visible to the producer, and will always be applied in the
+     * hardware composer, the client can set this flag with
+     * native_window_set_buffers_sticky_transform.  This can be used to rotate
+     * and flip buffers consumed by hardware composer without actually changing
+     * the aspect ratio of the buffers produced.
+     */
+    NATIVE_WINDOW_STICKY_TRANSFORM = 11,
+
+    /**
+     * The default data space for the buffers as set by the consumer.
+     * The values are defined in graphics.h.
+     */
+    NATIVE_WINDOW_DEFAULT_DATASPACE = 12,
+
+    /*
+     * Returns the age of the contents of the most recently dequeued buffer as
+     * the number of frames that have elapsed since it was last queued. For
+     * example, if the window is double-buffered, the age of any given buffer in
+     * steady state will be 2. If the dequeued buffer has never been queued, its
+     * age will be 0.
+     */
+    NATIVE_WINDOW_BUFFER_AGE = 13,
+
+    /*
+     * Returns the duration of the last dequeueBuffer call in microseconds
+     */
+    NATIVE_WINDOW_LAST_DEQUEUE_DURATION = 14,
+
+    /*
+     * Returns the duration of the last queueBuffer call in microseconds
+     */
+    NATIVE_WINDOW_LAST_QUEUE_DURATION = 15,
+
+    /*
+     * Returns the number of image layers that the ANativeWindow buffer
+     * contains. By default this is 1, unless a buffer is explicitly allocated
+     * to contain multiple layers.
+     */
+    NATIVE_WINDOW_LAYER_COUNT = 16,
+
+    /*
+     * Returns 1 if the native window is valid, 0 otherwise. native window is valid
+     * if it is safe (i.e. no crash will occur) to call any method on it.
+     */
+    NATIVE_WINDOW_IS_VALID = 17,
+
+    /*
+     * Returns 1 if NATIVE_WINDOW_GET_FRAME_TIMESTAMPS will return display
+     * present info, 0 if it won't.
+     */
+    NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT = 18,
+
+    /*
+     * The consumer end is capable of handling protected buffers, i.e. buffer
+     * with GRALLOC_USAGE_PROTECTED usage bits on.
+     */
+    NATIVE_WINDOW_CONSUMER_IS_PROTECTED = 19,
+};
+
+/* Valid operations for the (*perform)() hook.
+ *
+ * Values marked as 'deprecated' are supported, but have been superceded by
+ * other functionality.
+ *
+ * Values marked as 'private' should be considered private to the framework.
+ * HAL implementation code with access to an ANativeWindow should not use these,
+ * as it may not interact properly with the framework's use of the
+ * ANativeWindow.
+ */
+enum {
+// clang-format off
+    NATIVE_WINDOW_SET_USAGE                 =  0,
+    NATIVE_WINDOW_CONNECT                   =  1,   /* deprecated */
+    NATIVE_WINDOW_DISCONNECT                =  2,   /* deprecated */
+    NATIVE_WINDOW_SET_CROP                  =  3,   /* private */
+    NATIVE_WINDOW_SET_BUFFER_COUNT          =  4,
+    NATIVE_WINDOW_SET_BUFFERS_GEOMETRY      =  5,   /* deprecated */
+    NATIVE_WINDOW_SET_BUFFERS_TRANSFORM     =  6,
+    NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP     =  7,
+    NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS    =  8,
+    NATIVE_WINDOW_SET_BUFFERS_FORMAT        =  9,
+    NATIVE_WINDOW_SET_SCALING_MODE          = 10,   /* private */
+    NATIVE_WINDOW_LOCK                      = 11,   /* private */
+    NATIVE_WINDOW_UNLOCK_AND_POST           = 12,   /* private */
+    NATIVE_WINDOW_API_CONNECT               = 13,   /* private */
+    NATIVE_WINDOW_API_DISCONNECT            = 14,   /* private */
+    NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS = 15, /* private */
+    NATIVE_WINDOW_SET_POST_TRANSFORM_CROP   = 16,   /* private */
+    NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM = 17,/* private */
+    NATIVE_WINDOW_SET_SIDEBAND_STREAM       = 18,
+    NATIVE_WINDOW_SET_BUFFERS_DATASPACE     = 19,
+    NATIVE_WINDOW_SET_SURFACE_DAMAGE        = 20,   /* private */
+    NATIVE_WINDOW_SET_SHARED_BUFFER_MODE    = 21,
+    NATIVE_WINDOW_SET_AUTO_REFRESH          = 22,
+    NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION= 23,
+    NATIVE_WINDOW_GET_NEXT_FRAME_ID         = 24,
+    NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS   = 25,
+    NATIVE_WINDOW_GET_COMPOSITOR_TIMING     = 26,
+    NATIVE_WINDOW_GET_FRAME_TIMESTAMPS      = 27,
+    NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT    = 28,
+    NATIVE_WINDOW_GET_HDR_SUPPORT           = 29,
+// clang-format on
+};
+
+/* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
+enum {
+    /* Buffers will be queued by EGL via eglSwapBuffers after being filled using
+     * OpenGL ES.
+     */
+    NATIVE_WINDOW_API_EGL = 1,
+
+    /* Buffers will be queued after being filled using the CPU
+     */
+    NATIVE_WINDOW_API_CPU = 2,
+
+    /* Buffers will be queued by Stagefright after being filled by a video
+     * decoder.  The video decoder can either be a software or hardware decoder.
+     */
+    NATIVE_WINDOW_API_MEDIA = 3,
+
+    /* Buffers will be queued by the the camera HAL.
+     */
+    NATIVE_WINDOW_API_CAMERA = 4,
+};
+
+/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */
+enum {
+    /* flip source image horizontally */
+    NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H ,
+    /* flip source image vertically */
+    NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
+    /* rotate source image 90 degrees clock-wise, and is applied after TRANSFORM_FLIP_{H|V} */
+    NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
+    /* rotate source image 180 degrees */
+    NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
+    /* rotate source image 270 degrees clock-wise */
+    NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
+    /* transforms source by the inverse transform of the screen it is displayed onto. This
+     * transform is applied last */
+    NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY = 0x08
+};
+
+/* parameter for NATIVE_WINDOW_SET_SCALING_MODE
+ * keep in sync with Surface.java in frameworks/base */
+enum {
+    /* the window content is not updated (frozen) until a buffer of
+     * the window size is received (enqueued)
+     */
+    NATIVE_WINDOW_SCALING_MODE_FREEZE           = 0,
+    /* the buffer is scaled in both dimensions to match the window size */
+    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW  = 1,
+    /* the buffer is scaled uniformly such that the smaller dimension
+     * of the buffer matches the window size (cropping in the process)
+     */
+    NATIVE_WINDOW_SCALING_MODE_SCALE_CROP       = 2,
+    /* the window is clipped to the size of the buffer's crop rectangle; pixels
+     * outside the crop rectangle are treated as if they are completely
+     * transparent.
+     */
+    NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP    = 3,
+};
+
+/* values returned by the NATIVE_WINDOW_CONCRETE_TYPE query */
+enum {
+    NATIVE_WINDOW_FRAMEBUFFER               = 0, /* FramebufferNativeWindow */
+    NATIVE_WINDOW_SURFACE                   = 1, /* Surface */
+};
+
+/* parameter for NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP
+ *
+ * Special timestamp value to indicate that timestamps should be auto-generated
+ * by the native window when queueBuffer is called.  This is equal to INT64_MIN,
+ * defined directly to avoid problems with C99/C++ inclusion of stdint.h.
+ */
+static const int64_t NATIVE_WINDOW_TIMESTAMP_AUTO = (-9223372036854775807LL-1);
+
+/* parameter for NATIVE_WINDOW_GET_FRAME_TIMESTAMPS
+ *
+ * Special timestamp value to indicate the timestamps aren't yet known or
+ * that they are invalid.
+ */
+static const int64_t NATIVE_WINDOW_TIMESTAMP_PENDING = -2;
+static const int64_t NATIVE_WINDOW_TIMESTAMP_INVALID = -1;
+
+struct ANativeWindow
+{
+#ifdef __cplusplus
+    ANativeWindow()
+        : flags(0), minSwapInterval(0), maxSwapInterval(0), xdpi(0), ydpi(0)
+    {
+        common.magic = ANDROID_NATIVE_WINDOW_MAGIC;
+        common.version = sizeof(ANativeWindow);
+        memset(common.reserved, 0, sizeof(common.reserved));
+    }
+
+    /* Implement the methods that sp<ANativeWindow> expects so that it
+       can be used to automatically refcount ANativeWindow's. */
+    void incStrong(const void* /*id*/) const {
+        common.incRef(const_cast<android_native_base_t*>(&common));
+    }
+    void decStrong(const void* /*id*/) const {
+        common.decRef(const_cast<android_native_base_t*>(&common));
+    }
+#endif
+
+    struct android_native_base_t common;
+
+    /* flags describing some attributes of this surface or its updater */
+    const uint32_t flags;
+
+    /* min swap interval supported by this updated */
+    const int   minSwapInterval;
+
+    /* max swap interval supported by this updated */
+    const int   maxSwapInterval;
+
+    /* horizontal and vertical resolution in DPI */
+    const float xdpi;
+    const float ydpi;
+
+    /* Some storage reserved for the OEM's driver. */
+    intptr_t    oem[4];
+
+    /*
+     * Set the swap interval for this surface.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*setSwapInterval)(struct ANativeWindow* window,
+                int interval);
+
+    /*
+     * Hook called by EGL to acquire a buffer. After this call, the buffer
+     * is not locked, so its content cannot be modified. This call may block if
+     * no buffers are available.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * Returns 0 on success or -errno on error.
+     *
+     * XXX: This function is deprecated.  It will continue to work for some
+     * time for binary compatibility, but the new dequeueBuffer function that
+     * outputs a fence file descriptor should be used in its place.
+     */
+    int     (*dequeueBuffer_DEPRECATED)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer** buffer);
+
+    /*
+     * hook called by EGL to lock a buffer. This MUST be called before modifying
+     * the content of a buffer. The buffer must have been acquired with
+     * dequeueBuffer first.
+     *
+     * Returns 0 on success or -errno on error.
+     *
+     * XXX: This function is deprecated.  It will continue to work for some
+     * time for binary compatibility, but it is essentially a no-op, and calls
+     * to it should be removed.
+     */
+    int     (*lockBuffer_DEPRECATED)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer* buffer);
+
+    /*
+     * Hook called by EGL when modifications to the render buffer are done.
+     * This unlocks and post the buffer.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * Buffers MUST be queued in the same order than they were dequeued.
+     *
+     * Returns 0 on success or -errno on error.
+     *
+     * XXX: This function is deprecated.  It will continue to work for some
+     * time for binary compatibility, but the new queueBuffer function that
+     * takes a fence file descriptor should be used in its place (pass a value
+     * of -1 for the fence file descriptor if there is no valid one to pass).
+     */
+    int     (*queueBuffer_DEPRECATED)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer* buffer);
+
+    /*
+     * hook used to retrieve information about the native window.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*query)(const struct ANativeWindow* window,
+                int what, int* value);
+
+    /*
+     * hook used to perform various operations on the surface.
+     * (*perform)() is a generic mechanism to add functionality to
+     * ANativeWindow while keeping backward binary compatibility.
+     *
+     * DO NOT CALL THIS HOOK DIRECTLY.  Instead, use the helper functions
+     * defined below.
+     *
+     * (*perform)() returns -ENOENT if the 'what' parameter is not supported
+     * by the surface's implementation.
+     *
+     * See above for a list of valid operations, such as
+     * NATIVE_WINDOW_SET_USAGE or NATIVE_WINDOW_CONNECT
+     */
+    int     (*perform)(struct ANativeWindow* window,
+                int operation, ... );
+
+    /*
+     * Hook used to cancel a buffer that has been dequeued.
+     * No synchronization is performed between dequeue() and cancel(), so
+     * either external synchronization is needed, or these functions must be
+     * called from the same thread.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * XXX: This function is deprecated.  It will continue to work for some
+     * time for binary compatibility, but the new cancelBuffer function that
+     * takes a fence file descriptor should be used in its place (pass a value
+     * of -1 for the fence file descriptor if there is no valid one to pass).
+     */
+    int     (*cancelBuffer_DEPRECATED)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer* buffer);
+
+    /*
+     * Hook called by EGL to acquire a buffer. This call may block if no
+     * buffers are available.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * The libsync fence file descriptor returned in the int pointed to by the
+     * fenceFd argument will refer to the fence that must signal before the
+     * dequeued buffer may be written to.  A value of -1 indicates that the
+     * caller may access the buffer immediately without waiting on a fence.  If
+     * a valid file descriptor is returned (i.e. any value except -1) then the
+     * caller is responsible for closing the file descriptor.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*dequeueBuffer)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer** buffer, int* fenceFd);
+
+    /*
+     * Hook called by EGL when modifications to the render buffer are done.
+     * This unlocks and post the buffer.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * The fenceFd argument specifies a libsync fence file descriptor for a
+     * fence that must signal before the buffer can be accessed.  If the buffer
+     * can be accessed immediately then a value of -1 should be used.  The
+     * caller must not use the file descriptor after it is passed to
+     * queueBuffer, and the ANativeWindow implementation is responsible for
+     * closing it.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*queueBuffer)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer* buffer, int fenceFd);
+
+    /*
+     * Hook used to cancel a buffer that has been dequeued.
+     * No synchronization is performed between dequeue() and cancel(), so
+     * either external synchronization is needed, or these functions must be
+     * called from the same thread.
+     *
+     * The window holds a reference to the buffer between dequeueBuffer and
+     * either queueBuffer or cancelBuffer, so clients only need their own
+     * reference if they might use the buffer after queueing or canceling it.
+     * Holding a reference to a buffer after queueing or canceling it is only
+     * allowed if a specific buffer count has been set.
+     *
+     * The fenceFd argument specifies a libsync fence file decsriptor for a
+     * fence that must signal before the buffer can be accessed.  If the buffer
+     * can be accessed immediately then a value of -1 should be used.
+     *
+     * Note that if the client has not waited on the fence that was returned
+     * from dequeueBuffer, that same fence should be passed to cancelBuffer to
+     * ensure that future uses of the buffer are preceded by a wait on that
+     * fence.  The caller must not use the file descriptor after it is passed
+     * to cancelBuffer, and the ANativeWindow implementation is responsible for
+     * closing it.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int     (*cancelBuffer)(struct ANativeWindow* window,
+                struct ANativeWindowBuffer* buffer, int fenceFd);
+};
+
+ /* Backwards compatibility: use ANativeWindow (struct ANativeWindow in C).
+  * android_native_window_t is deprecated.
+  */
+typedef struct ANativeWindow ANativeWindow;
+typedef struct ANativeWindow android_native_window_t __deprecated;
+
+/*
+ *  native_window_set_usage(..., usage)
+ *  Sets the intended usage flags for the next buffers
+ *  acquired with (*lockBuffer)() and on.
+ *  By default (if this function is never called), a usage of
+ *      GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE
+ *  is assumed.
+ *  Calling this function will usually cause following buffers to be
+ *  reallocated.
+ */
+
+static inline int native_window_set_usage(
+        struct ANativeWindow* window, int usage)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_USAGE, usage);
+}
+
+/* deprecated. Always returns 0. Don't call. */
+static inline int native_window_connect(
+        struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated;
+
+static inline int native_window_connect(
+        struct ANativeWindow* window __UNUSED, int api __UNUSED) {
+    return 0;
+}
+
+/* deprecated. Always returns 0. Don't call. */
+static inline int native_window_disconnect(
+        struct ANativeWindow* window __UNUSED, int api __UNUSED) __deprecated;
+
+static inline int native_window_disconnect(
+        struct ANativeWindow* window __UNUSED, int api __UNUSED) {
+    return 0;
+}
+
+/*
+ * native_window_set_crop(..., crop)
+ * Sets which region of the next queued buffers needs to be considered.
+ * Depending on the scaling mode, a buffer's crop region is scaled and/or
+ * cropped to match the surface's size.  This function sets the crop in
+ * pre-transformed buffer pixel coordinates.
+ *
+ * The specified crop region applies to all buffers queued after it is called.
+ *
+ * If 'crop' is NULL, subsequently queued buffers won't be cropped.
+ *
+ * An error is returned if for instance the crop region is invalid, out of the
+ * buffer's bound or if the window is invalid.
+ */
+static inline int native_window_set_crop(
+        struct ANativeWindow* window,
+        android_native_rect_t const * crop)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_CROP, crop);
+}
+
+/*
+ * native_window_set_post_transform_crop(..., crop)
+ * Sets which region of the next queued buffers needs to be considered.
+ * Depending on the scaling mode, a buffer's crop region is scaled and/or
+ * cropped to match the surface's size.  This function sets the crop in
+ * post-transformed pixel coordinates.
+ *
+ * The specified crop region applies to all buffers queued after it is called.
+ *
+ * If 'crop' is NULL, subsequently queued buffers won't be cropped.
+ *
+ * An error is returned if for instance the crop region is invalid, out of the
+ * buffer's bound or if the window is invalid.
+ */
+static inline int native_window_set_post_transform_crop(
+        struct ANativeWindow* window,
+        android_native_rect_t const * crop)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_POST_TRANSFORM_CROP, crop);
+}
+
+/*
+ * native_window_set_active_rect(..., active_rect)
+ *
+ * This function is deprecated and will be removed soon.  For now it simply
+ * sets the post-transform crop for compatibility while multi-project commits
+ * get checked.
+ */
+static inline int native_window_set_active_rect(
+        struct ANativeWindow* window,
+        android_native_rect_t const * active_rect) __deprecated;
+
+static inline int native_window_set_active_rect(
+        struct ANativeWindow* window,
+        android_native_rect_t const * active_rect)
+{
+    return native_window_set_post_transform_crop(window, active_rect);
+}
+
+/*
+ * native_window_set_buffer_count(..., count)
+ * Sets the number of buffers associated with this native window.
+ */
+static inline int native_window_set_buffer_count(
+        struct ANativeWindow* window,
+        size_t bufferCount)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFER_COUNT, bufferCount);
+}
+
+/*
+ * native_window_set_buffers_geometry(..., int w, int h, int format)
+ * All buffers dequeued after this call will have the dimensions and format
+ * specified.  A successful call to this function has the same effect as calling
+ * native_window_set_buffers_size and native_window_set_buffers_format.
+ *
+ * XXX: This function is deprecated.  The native_window_set_buffers_dimensions
+ * and native_window_set_buffers_format functions should be used instead.
+ */
+static inline int native_window_set_buffers_geometry(
+        struct ANativeWindow* window,
+        int w, int h, int format) __deprecated;
+
+static inline int native_window_set_buffers_geometry(
+        struct ANativeWindow* window,
+        int w, int h, int format)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_GEOMETRY,
+            w, h, format);
+}
+
+/*
+ * native_window_set_buffers_dimensions(..., int w, int h)
+ * All buffers dequeued after this call will have the dimensions specified.
+ * In particular, all buffers will have a fixed-size, independent from the
+ * native-window size. They will be scaled according to the scaling mode
+ * (see native_window_set_scaling_mode) upon window composition.
+ *
+ * If w and h are 0, the normal behavior is restored. That is, dequeued buffers
+ * following this call will be sized to match the window's size.
+ *
+ * Calling this function will reset the window crop to a NULL value, which
+ * disables cropping of the buffers.
+ */
+static inline int native_window_set_buffers_dimensions(
+        struct ANativeWindow* window,
+        int w, int h)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS,
+            w, h);
+}
+
+/*
+ * native_window_set_buffers_user_dimensions(..., int w, int h)
+ *
+ * Sets the user buffer size for the window, which overrides the
+ * window's size.  All buffers dequeued after this call will have the
+ * dimensions specified unless overridden by
+ * native_window_set_buffers_dimensions.  All buffers will have a
+ * fixed-size, independent from the native-window size. They will be
+ * scaled according to the scaling mode (see
+ * native_window_set_scaling_mode) upon window composition.
+ *
+ * If w and h are 0, the normal behavior is restored. That is, the
+ * default buffer size will match the windows's size.
+ *
+ * Calling this function will reset the window crop to a NULL value, which
+ * disables cropping of the buffers.
+ */
+static inline int native_window_set_buffers_user_dimensions(
+        struct ANativeWindow* window,
+        int w, int h)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS,
+            w, h);
+}
+
+/*
+ * native_window_set_buffers_format(..., int format)
+ * All buffers dequeued after this call will have the format specified.
+ *
+ * If the specified format is 0, the default buffer format will be used.
+ */
+static inline int native_window_set_buffers_format(
+        struct ANativeWindow* window,
+        int format)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_FORMAT, format);
+}
+
+/*
+ * native_window_set_buffers_data_space(..., int dataSpace)
+ * All buffers queued after this call will be associated with the dataSpace
+ * parameter specified.
+ *
+ * dataSpace specifies additional information about the buffer that's dependent
+ * on the buffer format and the endpoints. For example, it can be used to convey
+ * the color space of the image data in the buffer, or it can be used to
+ * indicate that the buffers contain depth measurement data instead of color
+ * images.  The default dataSpace is 0, HAL_DATASPACE_UNKNOWN, unless it has been
+ * overridden by the consumer.
+ */
+static inline int native_window_set_buffers_data_space(
+        struct ANativeWindow* window,
+        android_dataspace_t dataSpace)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_DATASPACE,
+            dataSpace);
+}
+
+/*
+ * native_window_set_buffers_transform(..., int transform)
+ * All buffers queued after this call will be displayed transformed according
+ * to the transform parameter specified.
+ */
+static inline int native_window_set_buffers_transform(
+        struct ANativeWindow* window,
+        int transform)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TRANSFORM,
+            transform);
+}
+
+/*
+ * native_window_set_buffers_sticky_transform(..., int transform)
+ * All buffers queued after this call will be displayed transformed according
+ * to the transform parameter specified applied on top of the regular buffer
+ * transform.  Setting this transform will disable the transform hint.
+ *
+ * Temporary - This is only intended to be used by the LEGACY camera mode, do
+ *   not use this for anything else.
+ */
+static inline int native_window_set_buffers_sticky_transform(
+        struct ANativeWindow* window,
+        int transform)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM,
+            transform);
+}
+
+/*
+ * native_window_set_buffers_timestamp(..., int64_t timestamp)
+ * All buffers queued after this call will be associated with the timestamp
+ * parameter specified. If the timestamp is set to NATIVE_WINDOW_TIMESTAMP_AUTO
+ * (the default), timestamps will be generated automatically when queueBuffer is
+ * called. The timestamp is measured in nanoseconds, and is normally monotonically
+ * increasing. The timestamp should be unaffected by time-of-day adjustments,
+ * and for a camera should be strictly monotonic but for a media player may be
+ * reset when the position is set.
+ */
+static inline int native_window_set_buffers_timestamp(
+        struct ANativeWindow* window,
+        int64_t timestamp)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP,
+            timestamp);
+}
+
+/*
+ * native_window_set_scaling_mode(..., int mode)
+ * All buffers queued after this call will be associated with the scaling mode
+ * specified.
+ */
+static inline int native_window_set_scaling_mode(
+        struct ANativeWindow* window,
+        int mode)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_SCALING_MODE,
+            mode);
+}
+
+/*
+ * native_window_api_connect(..., int api)
+ * connects an API to this window. only one API can be connected at a time.
+ * Returns -EINVAL if for some reason the window cannot be connected, which
+ * can happen if it's connected to some other API.
+ */
+static inline int native_window_api_connect(
+        struct ANativeWindow* window, int api)
+{
+    return window->perform(window, NATIVE_WINDOW_API_CONNECT, api);
+}
+
+/*
+ * native_window_api_disconnect(..., int api)
+ * disconnect the API from this window.
+ * An error is returned if for instance the window wasn't connected in the
+ * first place.
+ */
+static inline int native_window_api_disconnect(
+        struct ANativeWindow* window, int api)
+{
+    return window->perform(window, NATIVE_WINDOW_API_DISCONNECT, api);
+}
+
+/*
+ * native_window_dequeue_buffer_and_wait(...)
+ * Dequeue a buffer and wait on the fence associated with that buffer.  The
+ * buffer may safely be accessed immediately upon this function returning.  An
+ * error is returned if either of the dequeue or the wait operations fail.
+ */
+static inline int native_window_dequeue_buffer_and_wait(ANativeWindow *anw,
+        struct ANativeWindowBuffer** anb) {
+    return anw->dequeueBuffer_DEPRECATED(anw, anb);
+}
+
+/*
+ * native_window_set_sideband_stream(..., native_handle_t*)
+ * Attach a sideband buffer stream to a native window.
+ */
+static inline int native_window_set_sideband_stream(
+        struct ANativeWindow* window,
+        native_handle_t* sidebandHandle)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_SIDEBAND_STREAM,
+            sidebandHandle);
+}
+
+/*
+ * native_window_set_surface_damage(..., android_native_rect_t* rects, int numRects)
+ * Set the surface damage (i.e., the region of the surface that has changed
+ * since the previous frame). The damage set by this call will be reset (to the
+ * default of full-surface damage) after calling queue, so this must be called
+ * prior to every frame with damage that does not cover the whole surface if the
+ * caller desires downstream consumers to use this optimization.
+ *
+ * The damage region is specified as an array of rectangles, with the important
+ * caveat that the origin of the surface is considered to be the bottom-left
+ * corner, as in OpenGL ES.
+ *
+ * If numRects is set to 0, rects may be NULL, and the surface damage will be
+ * set to the full surface (the same as if this function had not been called for
+ * this frame).
+ */
+static inline int native_window_set_surface_damage(
+        struct ANativeWindow* window,
+        const android_native_rect_t* rects, size_t numRects)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_SURFACE_DAMAGE,
+            rects, numRects);
+}
+
+/*
+ * native_window_set_shared_buffer_mode(..., bool sharedBufferMode)
+ * Enable/disable shared buffer mode
+ */
+static inline int native_window_set_shared_buffer_mode(
+        struct ANativeWindow* window,
+        bool sharedBufferMode)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_SHARED_BUFFER_MODE,
+            sharedBufferMode);
+}
+
+/*
+ * native_window_set_auto_refresh(..., autoRefresh)
+ * Enable/disable auto refresh when in shared buffer mode
+ */
+static inline int native_window_set_auto_refresh(
+        struct ANativeWindow* window,
+        bool autoRefresh)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_AUTO_REFRESH, autoRefresh);
+}
+
+static inline int native_window_get_refresh_cycle_duration(
+        struct ANativeWindow* window,
+        int64_t* outRefreshDuration)
+{
+    return window->perform(window, NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION,
+            outRefreshDuration);
+}
+
+static inline int native_window_get_next_frame_id(
+        struct ANativeWindow* window, uint64_t* frameId)
+{
+    return window->perform(window, NATIVE_WINDOW_GET_NEXT_FRAME_ID, frameId);
+}
+
+static inline int native_window_enable_frame_timestamps(
+        struct ANativeWindow* window, bool enable)
+{
+    return window->perform(window, NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS,
+            enable);
+}
+
+static inline int native_window_get_compositor_timing(
+        struct ANativeWindow* window,
+        int64_t* compositeDeadline, int64_t* compositeInterval,
+        int64_t* compositeToPresentLatency)
+{
+    return window->perform(window, NATIVE_WINDOW_GET_COMPOSITOR_TIMING,
+            compositeDeadline, compositeInterval, compositeToPresentLatency);
+}
+
+static inline int native_window_get_frame_timestamps(
+        struct ANativeWindow* window, uint64_t frameId,
+        int64_t* outRequestedPresentTime, int64_t* outAcquireTime,
+        int64_t* outLatchTime, int64_t* outFirstRefreshStartTime,
+        int64_t* outLastRefreshStartTime, int64_t* outGpuCompositionDoneTime,
+        int64_t* outDisplayPresentTime, int64_t* outDequeueReadyTime,
+        int64_t* outReleaseTime)
+{
+    return window->perform(window, NATIVE_WINDOW_GET_FRAME_TIMESTAMPS,
+            frameId, outRequestedPresentTime, outAcquireTime, outLatchTime,
+            outFirstRefreshStartTime, outLastRefreshStartTime,
+            outGpuCompositionDoneTime, outDisplayPresentTime,
+            outDequeueReadyTime, outReleaseTime);
+}
+
+static inline int native_window_get_wide_color_support(
+    struct ANativeWindow* window, bool* outSupport) {
+  return window->perform(window, NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT,
+                         outSupport);
+}
+
+static inline int native_window_get_hdr_support(struct ANativeWindow* window,
+                                                bool* outSupport) {
+  return window->perform(window, NATIVE_WINDOW_GET_HDR_SUPPORT, outSupport);
+}
+
+__END_DECLS
diff --git a/libsystem/include/system/window.h b/libsystem/include/system/window.h
new file mode 100644
index 0000000..efa10d6
--- /dev/null
+++ b/libsystem/include/system/window.h
@@ -0,0 +1,22 @@
+/*
+ * 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 SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
+#define SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
+
+#include <system/window-deprecated.h>
+
+#endif /* SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H */
diff --git a/libsysutils/Android.bp b/libsysutils/Android.bp
new file mode 100644
index 0000000..550ef42
--- /dev/null
+++ b/libsysutils/Android.bp
@@ -0,0 +1,27 @@
+cc_library_shared {
+    name: "libsysutils",
+    vendor_available: true,
+
+    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 7bf53e3..0000000
--- a/libsysutils/Android.mk
+++ /dev/null
@@ -1,25 +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 := \
-        libcutils \
-        liblog \
-        libnl
-
-include $(BUILD_SHARED_LIBRARY)
-
diff --git a/include/sysutils/FrameworkClient.h b/libsysutils/include/sysutils/FrameworkClient.h
similarity index 100%
rename from include/sysutils/FrameworkClient.h
rename to libsysutils/include/sysutils/FrameworkClient.h
diff --git a/include/sysutils/FrameworkCommand.h b/libsysutils/include/sysutils/FrameworkCommand.h
similarity index 100%
rename from include/sysutils/FrameworkCommand.h
rename to libsysutils/include/sysutils/FrameworkCommand.h
diff --git a/include/sysutils/FrameworkListener.h b/libsysutils/include/sysutils/FrameworkListener.h
similarity index 100%
rename from include/sysutils/FrameworkListener.h
rename to libsysutils/include/sysutils/FrameworkListener.h
diff --git a/include/sysutils/List.h b/libsysutils/include/sysutils/List.h
similarity index 100%
rename from include/sysutils/List.h
rename to libsysutils/include/sysutils/List.h
diff --git a/include/sysutils/NetlinkEvent.h b/libsysutils/include/sysutils/NetlinkEvent.h
similarity index 100%
rename from include/sysutils/NetlinkEvent.h
rename to libsysutils/include/sysutils/NetlinkEvent.h
diff --git a/include/sysutils/NetlinkListener.h b/libsysutils/include/sysutils/NetlinkListener.h
similarity index 100%
rename from include/sysutils/NetlinkListener.h
rename to libsysutils/include/sysutils/NetlinkListener.h
diff --git a/include/sysutils/ServiceManager.h b/libsysutils/include/sysutils/ServiceManager.h
similarity index 100%
rename from include/sysutils/ServiceManager.h
rename to libsysutils/include/sysutils/ServiceManager.h
diff --git a/include/sysutils/SocketClient.h b/libsysutils/include/sysutils/SocketClient.h
similarity index 100%
rename from include/sysutils/SocketClient.h
rename to libsysutils/include/sysutils/SocketClient.h
diff --git a/include/sysutils/SocketClientCommand.h b/libsysutils/include/sysutils/SocketClientCommand.h
similarity index 100%
rename from include/sysutils/SocketClientCommand.h
rename to libsysutils/include/sysutils/SocketClientCommand.h
diff --git a/include/sysutils/SocketListener.h b/libsysutils/include/sysutils/SocketListener.h
similarity index 100%
rename from include/sysutils/SocketListener.h
rename to libsysutils/include/sysutils/SocketListener.h
diff --git a/libsysutils/src/FrameworkClient.cpp b/libsysutils/src/FrameworkClient.cpp
index 2f37055..72b3d0a 100644
--- a/libsysutils/src/FrameworkClient.cpp
+++ b/libsysutils/src/FrameworkClient.cpp
@@ -1,11 +1,27 @@
-#include <alloca.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <pthread.h>
+/*
+ * Copyright (C) 2009-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.
+ */
 
 #define LOG_TAG "FrameworkClient"
-#include <cutils/log.h>
 
+#include <alloca.h>
+#include <errno.h>
+#include <pthread.h>
+#include <sys/types.h>
+
+#include <android/log.h>
 #include <sysutils/FrameworkClient.h>
 
 FrameworkClient::FrameworkClient(int socket) {
diff --git a/libsysutils/src/FrameworkCommand.cpp b/libsysutils/src/FrameworkCommand.cpp
index 0b95a81..a6c4abc 100644
--- a/libsysutils/src/FrameworkCommand.cpp
+++ b/libsysutils/src/FrameworkCommand.cpp
@@ -13,12 +13,12 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <errno.h>
 
 #define LOG_TAG "FrameworkCommand"
 
-#include <cutils/log.h>
+#include <errno.h>
 
+#include <log/log.h>
 #include <sysutils/FrameworkCommand.h>
 
 #define UNUSED __attribute__((unused))
diff --git a/libsysutils/src/FrameworkListener.cpp b/libsysutils/src/FrameworkListener.cpp
index 579ead9..1b6076f 100644
--- a/libsysutils/src/FrameworkListener.cpp
+++ b/libsysutils/src/FrameworkListener.cpp
@@ -13,16 +13,17 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <errno.h>
-#include <string.h>
-#include <stdlib.h>
 
 #define LOG_TAG "FrameworkListener"
 
-#include <cutils/log.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-#include <sysutils/FrameworkListener.h>
+#include <log/log.h>
 #include <sysutils/FrameworkCommand.h>
+#include <sysutils/FrameworkListener.h>
 #include <sysutils/SocketClient.h>
 
 static const int CMD_BUF_SIZE = 1024;
diff --git a/libsysutils/src/NetlinkEvent.cpp b/libsysutils/src/NetlinkEvent.cpp
index 739fad7..79bc888 100644
--- a/libsysutils/src/NetlinkEvent.cpp
+++ b/libsysutils/src/NetlinkEvent.cpp
@@ -13,39 +13,36 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <stdlib.h>
-#include <string.h>
 
 #define LOG_TAG "NetlinkEvent"
-#include <cutils/log.h>
 
-#include <sysutils/NetlinkEvent.h>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
 #include <arpa/inet.h>
-#include <net/if.h>
-
 #include <linux/if.h>
 #include <linux/if_addr.h>
 #include <linux/if_link.h>
 #include <linux/netfilter/nfnetlink.h>
 #include <linux/netfilter/nfnetlink_log.h>
 #include <linux/netfilter_ipv4/ipt_ULOG.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <netinet/icmp6.h>
+#include <netlink/attr.h>
+#include <netlink/genl/genl.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
 
 /* From kernel's net/netfilter/xt_quota2.c */
 const int LOCAL_QLOG_NL_EVENT = 112;
 const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
 
-#include <linux/netlink.h>
-#include <linux/rtnetlink.h>
-
-#include <netlink/attr.h>
-#include <netlink/genl/genl.h>
-#include <netlink/handlers.h>
-#include <netlink/msg.h>
+#include <log/log.h>
+#include <sysutils/NetlinkEvent.h>
 
 NetlinkEvent::NetlinkEvent() {
     mAction = Action::kUnknown;
@@ -564,10 +561,12 @@
 static const char*
 has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
 {
-    if ((end-str) >= (ptrdiff_t)prefixlen && !memcmp(str, prefix, prefixlen))
+    if ((end - str) >= (ptrdiff_t)prefixlen &&
+        (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
         return str + prefixlen;
-    else
+    } else {
         return NULL;
+    }
 }
 
 /* Same as strlen(x) for constant string literals ONLY */
diff --git a/libsysutils/src/NetlinkListener.cpp b/libsysutils/src/NetlinkListener.cpp
index 637aa1e..896dad3 100644
--- a/libsysutils/src/NetlinkListener.cpp
+++ b/libsysutils/src/NetlinkListener.cpp
@@ -13,17 +13,19 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <errno.h>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <linux/netlink.h>
-#include <string.h>
 
 #define LOG_TAG "NetlinkListener"
-#include <cutils/log.h>
-#include <cutils/uevent.h>
 
+#include <errno.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <linux/netlink.h> /* out of order because must follow sys/socket.h */
+
+#include <cutils/uevent.h>
+#include <log/log.h>
 #include <sysutils/NetlinkEvent.h>
 
 #if 1
diff --git a/libsysutils/src/ServiceManager.cpp b/libsysutils/src/ServiceManager.cpp
index 41ac1dd..c7aa1f7 100644
--- a/libsysutils/src/ServiceManager.cpp
+++ b/libsysutils/src/ServiceManager.cpp
@@ -1,34 +1,41 @@
-#include <errno.h>
-#include <string.h>
-
-#include <sysutils/ServiceManager.h>
+/*
+ * Copyright (C) 2009-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.
+ */
 
 #define LOG_TAG "Service"
-#include <cutils/log.h>
-#include <cutils/properties.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/system_properties.h>
+#include <unistd.h>
+
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <log/log.h>
+#include <sysutils/ServiceManager.h>
 
 ServiceManager::ServiceManager() {
 }
 
-/* The service name should not exceed SERVICE_NAME_MAX to avoid
- * some weird things. This is due to the fact that:
- *
- * - Starting a service is done by writing its name to the "ctl.start"
- *   system property. This triggers the init daemon to actually start
- *   the service for us.
- *
- * - Stopping the service is done by writing its name to "ctl.stop"
- *   in a similar way.
- *
- * - Reading the status of a service is done by reading the property
- *   named "init.svc.<name>"
- *
- * If strlen(<name>) > (PROPERTY_KEY_MAX-1)-9, then you can start/stop
- * the service by writing to ctl.start/stop, but you won't be able to
- * read its state due to the truncation of "init.svc.<name>" into a
- * zero-terminated buffer of PROPERTY_KEY_MAX characters.
- */
-#define SERVICE_NAME_MAX  (PROPERTY_KEY_MAX-10)
+// The length of a service name should not exceed SERVICE_NAME_MAX. Starting
+// a service is done by writing its name to the "ctl.start" system property
+// and stopping a service is done by writing its name to "ctl.stop". If a
+// service name is too long to fit in a property, you won't be able to start
+// or stop it.
+static constexpr size_t SERVICE_NAME_MAX = PROP_VALUE_MAX;
 
 /* The maximum amount of time to wait for a service to start or stop,
  * in micro-seconds (really an approximation) */
@@ -43,13 +50,14 @@
         SLOGE("Service name '%s' is too long", name);
         return 0;
     }
+
     if (isRunning(name)) {
         SLOGW("Service '%s' is already running", name);
         return 0;
     }
 
     SLOGD("Starting service '%s'", name);
-    property_set("ctl.start", name);
+    android::base::SetProperty("ctl.start", name);
 
     int count = SLEEP_MAX_USEC;
     while(count > 0) {
@@ -72,13 +80,14 @@
         SLOGE("Service name '%s' is too long", name);
         return 0;
     }
+
     if (!isRunning(name)) {
         SLOGW("Service '%s' is already stopped", name);
         return 0;
     }
 
     SLOGD("Stopping service '%s'", name);
-    property_set("ctl.stop", name);
+    android::base::SetProperty("ctl.stop", name);
 
     int count = SLEEP_MAX_USEC;
     while(count > 0) {
@@ -98,19 +107,6 @@
 }
 
 bool ServiceManager::isRunning(const char *name) {
-    char propVal[PROPERTY_VALUE_MAX];
-    char propName[PROPERTY_KEY_MAX];
-    int  ret;
-
-    ret = snprintf(propName, sizeof(propName), "init.svc.%s", name);
-    if (ret > (int)sizeof(propName)-1) {
-        SLOGD("Service name '%s' is too long", name);
-        return false;
-    }
-
-    if (property_get(propName, propVal, NULL)) {
-        if (!strcmp(propVal, "running"))
-            return true;
-    }
-    return false;
+    std::string property_name = android::base::StringPrintf("init.svc.%s", name);
+    return (android::base::GetProperty(property_name, "") == "running");
 }
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
index bb9b6a1..971f908 100644
--- a/libsysutils/src/SocketClient.cpp
+++ b/libsysutils/src/SocketClient.cpp
@@ -1,16 +1,33 @@
+/*
+ * Copyright (C) 2009-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.
+ */
+
+#define LOG_TAG "SocketClient"
+
 #include <alloca.h>
+#include <arpa/inet.h>
 #include <errno.h>
 #include <malloc.h>
 #include <pthread.h>
 #include <signal.h>
 #include <string.h>
-#include <arpa/inet.h>
 #include <sys/socket.h>
 #include <sys/types.h>
+#include <unistd.h>
 
-#define LOG_TAG "SocketClient"
-#include <cutils/log.h>
-
+#include <log/log.h>
 #include <sysutils/SocketClient.h>
 
 SocketClient::SocketClient(int socket, bool owned) {
diff --git a/libsysutils/src/SocketListener.cpp b/libsysutils/src/SocketListener.cpp
index 168899c..3f8f3db 100644
--- a/libsysutils/src/SocketListener.cpp
+++ b/libsysutils/src/SocketListener.cpp
@@ -13,19 +13,21 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <stdio.h>
+
+#define LOG_TAG "SocketListener"
+
 #include <errno.h>
+#include <stdio.h>
 #include <stdlib.h>
-#include <sys/socket.h>
 #include <sys/select.h>
+#include <sys/socket.h>
 #include <sys/time.h>
 #include <sys/types.h>
 #include <sys/un.h>
+#include <unistd.h>
 
-#define LOG_TAG "SocketListener"
-#include <cutils/log.h>
 #include <cutils/sockets.h>
-
+#include <log/log.h>
 #include <sysutils/SocketListener.h>
 #include <sysutils/SocketClient.h>
 
@@ -199,22 +201,12 @@
             continue;
         }
         if (mListen && FD_ISSET(mSock, &read_fds)) {
-            sockaddr_storage ss;
-            sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
-            socklen_t alen;
-            int c;
-
-            do {
-                alen = sizeof(ss);
-                c = accept(mSock, addrp, &alen);
-                SLOGV("%s got %d from accept", mSocketName, c);
-            } while (c < 0 && errno == EINTR);
+            int c = TEMP_FAILURE_RETRY(accept4(mSock, nullptr, nullptr, SOCK_CLOEXEC));
             if (c < 0) {
                 SLOGE("accept failed (%s)", strerror(errno));
                 sleep(1);
                 continue;
             }
-            fcntl(c, F_SETFD, FD_CLOEXEC);
             pthread_mutex_lock(&mClientsLock);
             mClients->push_back(new SocketClient(c, true, mUseCmdNum));
             pthread_mutex_unlock(&mClientsLock);
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
new file mode 100644
index 0000000..ece623b
--- /dev/null
+++ b/libunwindstack/Android.bp
@@ -0,0 +1,167 @@
+//
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_defaults {
+    name: "libunwindstack_flags",
+
+    host_supported: true,
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
+
+cc_defaults {
+    name: "libunwindstack_common",
+    defaults: ["libunwindstack_flags"],
+
+    srcs: [
+        "ArmExidx.cpp",
+        "Elf.cpp",
+        "ElfInterface.cpp",
+        "ElfInterfaceArm.cpp",
+        "Log.cpp",
+        "Regs.cpp",
+        "Memory.cpp",
+    ],
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+}
+
+cc_library {
+    name: "libunwindstack",
+    defaults: ["libunwindstack_common"],
+}
+
+cc_library {
+    name: "libunwindstack_debug",
+    defaults: ["libunwindstack_common"],
+
+    cflags: [
+        "-UNDEBUG",
+        "-O0",
+        "-g",
+    ],
+}
+
+//-------------------------------------------------------------------------
+// Unit Tests
+//-------------------------------------------------------------------------
+cc_defaults {
+    name: "libunwindstack_test_common",
+    defaults: ["libunwindstack_flags"],
+
+    srcs: [
+        "tests/ArmExidxDecodeTest.cpp",
+        "tests/ArmExidxExtractTest.cpp",
+        "tests/ElfInterfaceArmTest.cpp",
+        "tests/ElfInterfaceTest.cpp",
+        "tests/ElfTest.cpp",
+        "tests/LogFake.cpp",
+        "tests/MemoryFake.cpp",
+        "tests/MemoryFileTest.cpp",
+        "tests/MemoryLocalTest.cpp",
+        "tests/MemoryRangeTest.cpp",
+        "tests/MemoryRemoteTest.cpp",
+        "tests/RegsTest.cpp",
+    ],
+
+    cflags: [
+        "-O0",
+        "-g",
+    ],
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+
+    target: {
+        linux: {
+            host_ldlibs: [
+                "-lrt",
+            ],
+        },
+    },
+}
+
+// These unit tests run against the shared library.
+cc_test {
+    name: "libunwindstack_test",
+    defaults: ["libunwindstack_test_common"],
+
+    shared_libs: [
+        "libunwindstack",
+    ],
+}
+
+// These unit tests run against the static debug library.
+cc_test {
+    name: "libunwindstack_test_debug",
+    defaults: ["libunwindstack_test_common"],
+
+    static_libs: [
+        "libunwindstack_debug",
+    ],
+}
+
+//-------------------------------------------------------------------------
+// Utility Executables
+//-------------------------------------------------------------------------
+cc_defaults {
+    name: "libunwindstack_executables",
+    defaults: ["libunwindstack_flags"],
+
+    shared_libs: [
+        "libunwindstack",
+        "libbase",
+    ],
+
+    static_libs: [
+        "liblog",
+    ],
+
+    compile_multilib: "both",
+}
+
+cc_binary {
+    name: "unwind_info",
+    defaults: ["libunwindstack_executables"],
+
+    srcs: [
+        "unwind_info.cpp",
+    ],
+}
diff --git a/libunwindstack/ArmExidx.cpp b/libunwindstack/ArmExidx.cpp
new file mode 100644
index 0000000..12adf57
--- /dev/null
+++ b/libunwindstack/ArmExidx.cpp
@@ -0,0 +1,686 @@
+/*
+ * 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 <assert.h>
+#include <stdint.h>
+
+#include <deque>
+#include <string>
+
+#include <android-base/stringprintf.h>
+
+#include "ArmExidx.h"
+#include "Log.h"
+#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
+
+void ArmExidx::LogRawData() {
+  std::string log_str("Raw Data:");
+  for (const uint8_t data : data_) {
+    log_str += android::base::StringPrintf(" 0x%02x", data);
+  }
+  log(log_indent_, log_str.c_str());
+}
+
+bool ArmExidx::ExtractEntryData(uint32_t entry_offset) {
+  data_.clear();
+  status_ = ARM_STATUS_NONE;
+
+  if (entry_offset & 1) {
+    // The offset needs to be at least two byte aligned.
+    status_ = ARM_STATUS_INVALID_ALIGNMENT;
+    return false;
+  }
+
+  // Each entry is a 32 bit prel31 offset followed by 32 bits
+  // of unwind information. If bit 31 of the unwind data is zero,
+  // then this is a prel31 offset to the start of the unwind data.
+  // If the unwind data is 1, then this is a cant unwind entry.
+  // Otherwise, this data is the compact form of the unwind information.
+  uint32_t data;
+  if (!elf_memory_->Read32(entry_offset + 4, &data)) {
+    status_ = ARM_STATUS_READ_FAILED;
+    return false;
+  }
+  if (data == 1) {
+    // This is a CANT UNWIND entry.
+    status_ = ARM_STATUS_NO_UNWIND;
+    if (log_) {
+      log(log_indent_, "Raw Data: 0x00 0x00 0x00 0x01");
+      log(log_indent_, "[cantunwind]");
+    }
+    return false;
+  }
+
+  if (data & (1UL << 31)) {
+    // This is a compact table entry.
+    if ((data >> 24) & 0xf) {
+      // This is a non-zero index, this code doesn't support
+      // other formats.
+      status_ = ARM_STATUS_INVALID_PERSONALITY;
+      return false;
+    }
+    data_.push_back((data >> 16) & 0xff);
+    data_.push_back((data >> 8) & 0xff);
+    uint8_t last_op = data & 0xff;
+    data_.push_back(last_op);
+    if (last_op != ARM_OP_FINISH) {
+      // If this didn't end with a finish op, add one.
+      data_.push_back(ARM_OP_FINISH);
+    }
+    if (log_) {
+      LogRawData();
+    }
+    return true;
+  }
+
+  // Get the address of the ops.
+  // Sign extend the data value if necessary.
+  int32_t signed_data = static_cast<int32_t>(data << 1) >> 1;
+  uint32_t addr = (entry_offset + 4) + signed_data;
+  if (!elf_memory_->Read32(addr, &data)) {
+    status_ = ARM_STATUS_READ_FAILED;
+    return false;
+  }
+
+  size_t num_table_words;
+  if (data & (1UL << 31)) {
+    // Compact model.
+    switch ((data >> 24) & 0xf) {
+    case 0:
+      num_table_words = 0;
+      data_.push_back((data >> 16) & 0xff);
+      break;
+    case 1:
+    case 2:
+      num_table_words = (data >> 16) & 0xff;
+      addr += 4;
+      break;
+    default:
+      // Only a personality of 0, 1, 2 is valid.
+      status_ = ARM_STATUS_INVALID_PERSONALITY;
+      return false;
+    }
+    data_.push_back((data >> 8) & 0xff);
+    data_.push_back(data & 0xff);
+  } else {
+    // Generic model.
+
+    // Skip the personality routine data, it doesn't contain any data
+    // needed to decode the unwind information.
+    addr += 4;
+    if (!elf_memory_->Read32(addr, &data)) {
+      status_ = ARM_STATUS_READ_FAILED;
+      return false;
+    }
+    num_table_words = (data >> 24) & 0xff;
+    data_.push_back((data >> 16) & 0xff);
+    data_.push_back((data >> 8) & 0xff);
+    data_.push_back(data & 0xff);
+    addr += 4;
+  }
+
+  if (num_table_words > 5) {
+    status_ = ARM_STATUS_MALFORMED;
+    return false;
+  }
+
+  for (size_t i = 0; i < num_table_words; i++) {
+    if (!elf_memory_->Read32(addr, &data)) {
+      status_ = ARM_STATUS_READ_FAILED;
+      return false;
+    }
+    data_.push_back((data >> 24) & 0xff);
+    data_.push_back((data >> 16) & 0xff);
+    data_.push_back((data >> 8) & 0xff);
+    data_.push_back(data & 0xff);
+    addr += 4;
+  }
+
+  if (data_.back() != ARM_OP_FINISH) {
+    // If this didn't end with a finish op, add one.
+    data_.push_back(ARM_OP_FINISH);
+  }
+
+  if (log_) {
+    LogRawData();
+  }
+  return true;
+}
+
+inline bool ArmExidx::GetByte(uint8_t* byte) {
+  if (data_.empty()) {
+    status_ = ARM_STATUS_TRUNCATED;
+    return false;
+  }
+  *byte = data_.front();
+  data_.pop_front();
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_00(uint8_t byte) {
+  assert((byte >> 4) == 0x8);
+
+  uint16_t registers = (byte & 0xf) << 8;
+  if (!GetByte(&byte)) {
+    return false;
+  }
+
+  registers |= byte;
+  if (registers == 0) {
+    // 10000000 00000000: Refuse to unwind
+    if (log_) {
+      log(log_indent_, "Refuse to unwind");
+    }
+    status_ = ARM_STATUS_NO_UNWIND;
+    return false;
+  }
+  // 1000iiii iiiiiiii: Pop up to 12 integer registers under masks {r15-r12}, {r11-r4}
+  if (log_) {
+    bool add_comma = false;
+    std::string msg = "pop {";
+    for (size_t i = 0; i < 12; i++) {
+      if (registers & (1 << i)) {
+        if (add_comma) {
+          msg += ", ";
+        }
+        msg += android::base::StringPrintf("r%zu", i + 4);
+        add_comma = true;
+      }
+    }
+    log(log_indent_, "%s}", msg.c_str());
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+
+  registers <<= 4;
+  for (size_t reg = 4; reg < 16; reg++) {
+    if (registers & (1 << reg)) {
+      if (!process_memory_->Read32(cfa_, &(*regs_)[reg])) {
+        status_ = ARM_STATUS_READ_FAILED;
+        return false;
+      }
+      cfa_ += 4;
+    }
+  }
+
+  // If the sp register is modified, change the cfa value.
+  if (registers & (1 << ARM_REG_SP)) {
+    cfa_ = (*regs_)[ARM_REG_SP];
+  }
+
+  // Indicate if the pc register was set.
+  if (registers & (1 << ARM_REG_PC)) {
+    pc_set_ = true;
+  }
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_01(uint8_t byte) {
+  assert((byte >> 4) == 0x9);
+
+  uint8_t bits = byte & 0xf;
+  if (bits == 13 || bits == 15) {
+    // 10011101: Reserved as prefix for ARM register to register moves
+    // 10011111: Reserved as prefix for Intel Wireless MMX register to register moves
+    if (log_) {
+      log(log_indent_, "[Reserved]");
+    }
+    status_ = ARM_STATUS_RESERVED;
+    return false;
+  }
+  // 1001nnnn: Set vsp = r[nnnn] (nnnn != 13, 15)
+  if (log_) {
+    log(log_indent_, "vsp = r%d", bits);
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+  // It is impossible for bits to be larger than the total number of
+  // arm registers, so don't bother checking if bits is a valid register.
+  cfa_ = (*regs_)[bits];
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_10(uint8_t byte) {
+  assert((byte >> 4) == 0xa);
+
+  // 10100nnn: Pop r4-r[4+nnn]
+  // 10101nnn: Pop r4-r[4+nnn], r14
+  if (log_) {
+    std::string msg = "pop {r4";
+    uint8_t end_reg = byte & 0x7;
+    if (end_reg) {
+      msg += android::base::StringPrintf("-r%d", 4 + end_reg);
+    }
+    if (byte & 0x8) {
+      log(log_indent_, "%s, r14}", msg.c_str());
+    } else {
+      log(log_indent_, "%s}", msg.c_str());
+    }
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+
+  for (size_t i = 4; i <= 4 + (byte & 0x7); i++) {
+    if (!process_memory_->Read32(cfa_, &(*regs_)[i])) {
+      status_ = ARM_STATUS_READ_FAILED;
+      return false;
+    }
+    cfa_ += 4;
+  }
+  if (byte & 0x8) {
+    if (!process_memory_->Read32(cfa_, &(*regs_)[ARM_REG_R14])) {
+      status_ = ARM_STATUS_READ_FAILED;
+      return false;
+    }
+    cfa_ += 4;
+  }
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_0000() {
+  // 10110000: Finish
+  if (log_) {
+    log(log_indent_, "finish");
+    if (log_skip_execution_) {
+      status_ = ARM_STATUS_FINISH;
+      return false;
+    }
+  }
+  status_ = ARM_STATUS_FINISH;
+  return false;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_0001() {
+  uint8_t byte;
+  if (!GetByte(&byte)) {
+    return false;
+  }
+
+  if (byte == 0) {
+    // 10110001 00000000: Spare
+    if (log_) {
+      log(log_indent_, "Spare");
+    }
+    status_ = ARM_STATUS_SPARE;
+    return false;
+  }
+  if (byte >> 4) {
+    // 10110001 xxxxyyyy: Spare (xxxx != 0000)
+    if (log_) {
+      log(log_indent_, "Spare");
+    }
+    status_ = ARM_STATUS_SPARE;
+    return false;
+  }
+
+  // 10110001 0000iiii: Pop integer registers under mask {r3, r2, r1, r0}
+  if (log_) {
+    bool add_comma = false;
+    std::string msg = "pop {";
+    for (size_t i = 0; i < 4; i++) {
+      if (byte & (1 << i)) {
+        if (add_comma) {
+          msg += ", ";
+        }
+        msg += android::base::StringPrintf("r%zu", i);
+        add_comma = true;
+      }
+    }
+    log(log_indent_, "%s}", msg.c_str());
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+
+  for (size_t reg = 0; reg < 4; reg++) {
+    if (byte & (1 << reg)) {
+      if (!process_memory_->Read32(cfa_, &(*regs_)[reg])) {
+        status_ = ARM_STATUS_READ_FAILED;
+        return false;
+      }
+      cfa_ += 4;
+    }
+  }
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_0010() {
+  // 10110010 uleb128: vsp = vsp + 0x204 + (uleb128 << 2)
+  uint32_t result = 0;
+  uint32_t shift = 0;
+  uint8_t byte;
+  do {
+    if (!GetByte(&byte)) {
+      return false;
+    }
+
+    result |= (byte & 0x7f) << shift;
+    shift += 7;
+  } while (byte & 0x80);
+  result <<= 2;
+  if (log_) {
+    log(log_indent_, "vsp = vsp + %d", 0x204 + result);
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+  cfa_ += 0x204 + result;
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_0011() {
+  // 10110011 sssscccc: Pop VFP double precision registers D[ssss]-D[ssss+cccc] by FSTMFDX
+  uint8_t byte;
+  if (!GetByte(&byte)) {
+    return false;
+  }
+
+  if (log_) {
+    uint8_t start_reg = byte >> 4;
+    std::string msg = android::base::StringPrintf("pop {d%d", start_reg);
+    uint8_t end_reg = start_reg + (byte & 0xf);
+    if (end_reg) {
+      msg += android::base::StringPrintf("-d%d", end_reg);
+    }
+    log(log_indent_, "%s}", msg.c_str());
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+  cfa_ += (byte & 0xf) * 8 + 12;
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_01nn() {
+  // 101101nn: Spare
+  if (log_) {
+    log(log_indent_, "Spare");
+  }
+  status_ = ARM_STATUS_SPARE;
+  return false;
+}
+
+inline bool ArmExidx::DecodePrefix_10_11_1nnn(uint8_t byte) {
+  assert((byte & ~0x07) == 0xb8);
+
+  // 10111nnn: Pop VFP double-precision registers D[8]-D[8+nnn] by FSTMFDX
+  if (log_) {
+    std::string msg = "pop {d8";
+    uint8_t last_reg = (byte & 0x7);
+    if (last_reg) {
+      msg += android::base::StringPrintf("-d%d", last_reg + 8);
+    }
+    log(log_indent_, "%s}", msg.c_str());
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+  // Only update the cfa.
+  cfa_ += (byte & 0x7) * 8 + 12;
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_10(uint8_t byte) {
+  assert((byte >> 6) == 0x2);
+
+  switch ((byte >> 4) & 0x3) {
+  case 0:
+    return DecodePrefix_10_00(byte);
+  case 1:
+    return DecodePrefix_10_01(byte);
+  case 2:
+    return DecodePrefix_10_10(byte);
+  default:
+    switch (byte & 0xf) {
+    case 0:
+      return DecodePrefix_10_11_0000();
+    case 1:
+      return DecodePrefix_10_11_0001();
+    case 2:
+      return DecodePrefix_10_11_0010();
+    case 3:
+      return DecodePrefix_10_11_0011();
+    default:
+      if (byte & 0x8) {
+        return DecodePrefix_10_11_1nnn(byte);
+      } else {
+        return DecodePrefix_10_11_01nn();
+      }
+    }
+  }
+}
+
+inline bool ArmExidx::DecodePrefix_11_000(uint8_t byte) {
+  assert((byte & ~0x07) == 0xc0);
+
+  uint8_t bits = byte & 0x7;
+  if (bits == 6) {
+    if (!GetByte(&byte)) {
+      return false;
+    }
+
+    // 11000110 sssscccc: Intel Wireless MMX pop wR[ssss]-wR[ssss+cccc]
+    if (log_) {
+      uint8_t start_reg = byte >> 4;
+      std::string msg = android::base::StringPrintf("pop {wR%d", start_reg);
+      uint8_t end_reg = byte & 0xf;
+      if (end_reg) {
+        msg += android::base::StringPrintf("-wR%d", start_reg + end_reg);
+      }
+      log(log_indent_, "%s}", msg.c_str());
+      if (log_skip_execution_) {
+        return true;
+      }
+    }
+    // Only update the cfa.
+    cfa_ += (byte & 0xf) * 8 + 8;
+  } else if (bits == 7) {
+    if (!GetByte(&byte)) {
+      return false;
+    }
+
+    if (byte == 0) {
+      // 11000111 00000000: Spare
+      if (log_) {
+        log(log_indent_, "Spare");
+      }
+      status_ = ARM_STATUS_SPARE;
+      return false;
+    } else if ((byte >> 4) == 0) {
+      // 11000111 0000iiii: Intel Wireless MMX pop wCGR registers {wCGR0,1,2,3}
+      if (log_) {
+        bool add_comma = false;
+        std::string msg = "pop {";
+        for (size_t i = 0; i < 4; i++) {
+          if (byte & (1 << i)) {
+            if (add_comma) {
+              msg += ", ";
+            }
+            msg += android::base::StringPrintf("wCGR%zu", i);
+            add_comma = true;
+          }
+        }
+        log(log_indent_, "%s}", msg.c_str());
+      }
+      // Only update the cfa.
+      cfa_ += __builtin_popcount(byte) * 4;
+    } else {
+      // 11000111 xxxxyyyy: Spare (xxxx != 0000)
+      if (log_) {
+        log(log_indent_, "Spare");
+      }
+      status_ = ARM_STATUS_SPARE;
+      return false;
+    }
+  } else {
+    // 11000nnn: Intel Wireless MMX pop wR[10]-wR[10+nnn] (nnn != 6, 7)
+    if (log_) {
+      std::string msg = "pop {wR10";
+      uint8_t nnn = byte & 0x7;
+      if (nnn) {
+        msg += android::base::StringPrintf("-wR%d", 10 + nnn);
+      }
+      log(log_indent_, "%s}", msg.c_str());
+      if (log_skip_execution_) {
+        return true;
+      }
+    }
+    // Only update the cfa.
+    cfa_ += (byte & 0x7) * 8 + 8;
+  }
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_11_001(uint8_t byte) {
+  assert((byte & ~0x07) == 0xc8);
+
+  uint8_t bits = byte & 0x7;
+  if (bits == 0) {
+    // 11001000 sssscccc: Pop VFP double precision registers D[16+ssss]-D[16+ssss+cccc] by VPUSH
+    if (!GetByte(&byte)) {
+      return false;
+    }
+
+    if (log_) {
+      uint8_t start_reg = byte >> 4;
+      std::string msg = android::base::StringPrintf("pop {d%d", 16 + start_reg);
+      uint8_t end_reg = byte & 0xf;
+      if (end_reg) {
+        msg += android::base::StringPrintf("-d%d", 16 + start_reg + end_reg);
+      }
+      log(log_indent_, "%s}", msg.c_str());
+      if (log_skip_execution_) {
+        return true;
+      }
+    }
+    // Only update the cfa.
+    cfa_ += (byte & 0xf) * 8 + 8;
+  } else if (bits == 1) {
+    // 11001001 sssscccc: Pop VFP double precision registers D[ssss]-D[ssss+cccc] by VPUSH
+    if (!GetByte(&byte)) {
+      return false;
+    }
+
+    if (log_) {
+      uint8_t start_reg = byte >> 4;
+      std::string msg = android::base::StringPrintf("pop {d%d", start_reg);
+      uint8_t end_reg = byte & 0xf;
+      if (end_reg) {
+        msg += android::base::StringPrintf("-d%d", start_reg + end_reg);
+      }
+      log(log_indent_, "%s}", msg.c_str());
+      if (log_skip_execution_) {
+        return true;
+      }
+    }
+    // Only update the cfa.
+    cfa_ += (byte & 0xf) * 8 + 8;
+  } else {
+    // 11001yyy: Spare (yyy != 000, 001)
+    if (log_) {
+      log(log_indent_, "Spare");
+    }
+    status_ = ARM_STATUS_SPARE;
+    return false;
+  }
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_11_010(uint8_t byte) {
+  assert((byte & ~0x07) == 0xd0);
+
+  // 11010nnn: Pop VFP double precision registers D[8]-D[8+nnn] by VPUSH
+  if (log_) {
+    std::string msg = "pop {d8";
+    uint8_t end_reg = byte & 0x7;
+    if (end_reg) {
+      msg += android::base::StringPrintf("-d%d", 8 + end_reg);
+    }
+    log(log_indent_, "%s}", msg.c_str());
+    if (log_skip_execution_) {
+      return true;
+    }
+  }
+  cfa_ += (byte & 0x7) * 8 + 8;
+  return true;
+}
+
+inline bool ArmExidx::DecodePrefix_11(uint8_t byte) {
+  assert((byte >> 6) == 0x3);
+
+  switch ((byte >> 3) & 0x7) {
+  case 0:
+    return DecodePrefix_11_000(byte);
+  case 1:
+    return DecodePrefix_11_001(byte);
+  case 2:
+    return DecodePrefix_11_010(byte);
+  default:
+    // 11xxxyyy: Spare (xxx != 000, 001, 010)
+    if (log_) {
+      log(log_indent_, "Spare");
+    }
+    status_ = ARM_STATUS_SPARE;
+    return false;
+  }
+}
+
+bool ArmExidx::Decode() {
+  status_ = ARM_STATUS_NONE;
+  uint8_t byte;
+  if (!GetByte(&byte)) {
+    return false;
+  }
+
+  switch (byte >> 6) {
+  case 0:
+    // 00xxxxxx: vsp = vsp + (xxxxxxx << 2) + 4
+    if (log_) {
+      log(log_indent_, "vsp = vsp + %d", ((byte & 0x3f) << 2) + 4);
+      if (log_skip_execution_) {
+        break;
+      }
+    }
+    cfa_ += ((byte & 0x3f) << 2) + 4;
+    break;
+  case 1:
+    // 01xxxxxx: vsp = vsp - (xxxxxxx << 2) + 4
+    if (log_) {
+      log(log_indent_, "vsp = vsp - %d", ((byte & 0x3f) << 2) + 4);
+      if (log_skip_execution_) {
+        break;
+      }
+    }
+    cfa_ -= ((byte & 0x3f) << 2) + 4;
+    break;
+  case 2:
+    return DecodePrefix_10(byte);
+  default:
+    return DecodePrefix_11(byte);
+  }
+  return true;
+}
+
+bool ArmExidx::Eval() {
+  pc_set_ = false;
+  while (Decode());
+  return status_ == ARM_STATUS_FINISH;
+}
diff --git a/libunwindstack/ArmExidx.h b/libunwindstack/ArmExidx.h
new file mode 100644
index 0000000..8c7f15a
--- /dev/null
+++ b/libunwindstack/ArmExidx.h
@@ -0,0 +1,108 @@
+/*
+ * 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_ARM_EXIDX_H
+#define _LIBUNWINDSTACK_ARM_EXIDX_H
+
+#include <stdint.h>
+
+#include <deque>
+
+// Forward declarations.
+class Memory;
+class RegsArm;
+
+enum ArmStatus : size_t {
+  ARM_STATUS_NONE = 0,
+  ARM_STATUS_NO_UNWIND,
+  ARM_STATUS_FINISH,
+  ARM_STATUS_RESERVED,
+  ARM_STATUS_SPARE,
+  ARM_STATUS_TRUNCATED,
+  ARM_STATUS_READ_FAILED,
+  ARM_STATUS_MALFORMED,
+  ARM_STATUS_INVALID_ALIGNMENT,
+  ARM_STATUS_INVALID_PERSONALITY,
+};
+
+enum ArmOp : uint8_t {
+  ARM_OP_FINISH = 0xb0,
+};
+
+class ArmExidx {
+ public:
+  ArmExidx(RegsArm* regs, Memory* elf_memory, Memory* process_memory)
+      : regs_(regs), elf_memory_(elf_memory), process_memory_(process_memory) {}
+  virtual ~ArmExidx() {}
+
+  void LogRawData();
+
+  bool ExtractEntryData(uint32_t entry_offset);
+
+  bool Eval();
+
+  bool Decode();
+
+  std::deque<uint8_t>* data() { return &data_; }
+
+  ArmStatus status() { return status_; }
+
+  RegsArm* regs() { return regs_; }
+
+  uint32_t cfa() { return cfa_; }
+  void set_cfa(uint32_t cfa) { cfa_ = cfa; }
+
+  bool pc_set() { return pc_set_; }
+  void set_pc_set(bool pc_set) { pc_set_ = pc_set; }
+
+  void set_log(bool log) { log_ = log; }
+  void set_log_skip_execution(bool skip_execution) { log_skip_execution_ = skip_execution; }
+  void set_log_indent(uint8_t indent) { log_indent_ = indent; }
+
+ private:
+  bool GetByte(uint8_t* byte);
+
+  bool DecodePrefix_10_00(uint8_t byte);
+  bool DecodePrefix_10_01(uint8_t byte);
+  bool DecodePrefix_10_10(uint8_t byte);
+  bool DecodePrefix_10_11_0000();
+  bool DecodePrefix_10_11_0001();
+  bool DecodePrefix_10_11_0010();
+  bool DecodePrefix_10_11_0011();
+  bool DecodePrefix_10_11_01nn();
+  bool DecodePrefix_10_11_1nnn(uint8_t byte);
+  bool DecodePrefix_10(uint8_t byte);
+
+  bool DecodePrefix_11_000(uint8_t byte);
+  bool DecodePrefix_11_001(uint8_t byte);
+  bool DecodePrefix_11_010(uint8_t byte);
+  bool DecodePrefix_11(uint8_t byte);
+
+  RegsArm* regs_ = nullptr;
+  uint32_t cfa_ = 0;
+  std::deque<uint8_t> data_;
+  ArmStatus status_ = ARM_STATUS_NONE;
+
+  Memory* elf_memory_;
+  Memory* process_memory_;
+
+  bool log_ = false;
+  uint8_t log_indent_ = 0;
+  bool log_skip_execution_ = false;
+  bool pc_set_ = false;
+};
+
+#endif  // _LIBUNWINDSTACK_ARM_EXIDX_H
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
new file mode 100644
index 0000000..272b5f0
--- /dev/null
+++ b/libunwindstack/Elf.cpp
@@ -0,0 +1,113 @@
+/*
+ * 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 <string.h>
+
+#include <memory>
+#include <string>
+
+#define LOG_TAG "unwind"
+#include <log/log.h>
+
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
+
+bool Elf::Init() {
+  if (!memory_) {
+    return false;
+  }
+
+  interface_.reset(CreateInterfaceFromMemory(memory_.get()));
+  if (!interface_) {
+    return false;
+  }
+
+  valid_ = interface_->Init();
+  if (valid_) {
+    interface_->InitHeaders();
+  } else {
+    interface_.reset(nullptr);
+  }
+  return valid_;
+}
+
+bool Elf::IsValidElf(Memory* memory) {
+  if (memory == nullptr) {
+    return false;
+  }
+
+  // Verify that this is a valid elf file.
+  uint8_t e_ident[SELFMAG + 1];
+  if (!memory->Read(0, e_ident, SELFMAG)) {
+    return false;
+  }
+
+  if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
+    return false;
+  }
+  return true;
+}
+
+ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
+  if (!IsValidElf(memory)) {
+    return nullptr;
+  }
+
+  std::unique_ptr<ElfInterface> interface;
+  if (!memory->Read(EI_CLASS, &class_type_, 1)) {
+    return nullptr;
+  }
+  if (class_type_ == ELFCLASS32) {
+    Elf32_Half e_machine;
+    if (!memory->Read(EI_NIDENT + sizeof(Elf32_Half), &e_machine, sizeof(e_machine))) {
+      return nullptr;
+    }
+
+    if (e_machine != EM_ARM && e_machine != EM_386) {
+      // Unsupported.
+      ALOGI("32 bit elf that is neither arm nor x86: e_machine = %d\n", e_machine);
+      return nullptr;
+    }
+
+    machine_type_ = e_machine;
+    if (e_machine == EM_ARM) {
+      interface.reset(new ElfInterfaceArm(memory));
+    } else {
+      interface.reset(new ElfInterface32(memory));
+    }
+  } else if (class_type_ == ELFCLASS64) {
+    Elf64_Half e_machine;
+    if (!memory->Read(EI_NIDENT + sizeof(Elf64_Half), &e_machine, sizeof(e_machine))) {
+      return nullptr;
+    }
+
+    if (e_machine != EM_AARCH64 && e_machine != EM_X86_64) {
+      // Unsupported.
+      ALOGI("64 bit elf that is neither aarch64 nor x86_64: e_machine = %d\n", e_machine);
+      return nullptr;
+    }
+
+    machine_type_ = e_machine;
+    interface.reset(new ElfInterface64(memory));
+  }
+
+  return interface.release();
+}
diff --git a/libunwindstack/Elf.h b/libunwindstack/Elf.h
new file mode 100644
index 0000000..7bf45b8
--- /dev/null
+++ b/libunwindstack/Elf.h
@@ -0,0 +1,78 @@
+/*
+ * 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_ELF_H
+#define _LIBUNWINDSTACK_ELF_H
+
+#include <stddef.h>
+
+#include <memory>
+#include <string>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+// Forward declaration.
+class Regs;
+
+class Elf {
+ public:
+  Elf(Memory* memory) : memory_(memory) {}
+  virtual ~Elf() = default;
+
+  bool Init();
+
+  void InitGnuDebugdata();
+
+  bool GetSoname(std::string* name) {
+    return valid_ && interface_->GetSoname(name);
+  }
+
+  bool GetFunctionName(uint64_t, std::string*, uint64_t*) {
+    return false;
+  }
+
+  bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory) {
+    return valid_ && interface_->Step(rel_pc, regs, process_memory);
+  }
+
+  ElfInterface* CreateInterfaceFromMemory(Memory* memory);
+
+  bool valid() { return valid_; }
+
+  uint32_t machine_type() { return machine_type_; }
+
+  uint8_t class_type() { return class_type_; }
+
+  Memory* memory() { return memory_.get(); }
+
+  ElfInterface* interface() { return interface_.get(); }
+
+  static bool IsValidElf(Memory* memory);
+
+ protected:
+  bool valid_ = false;
+  std::unique_ptr<ElfInterface> interface_;
+  std::unique_ptr<Memory> memory_;
+  uint32_t machine_type_;
+  uint8_t class_type_;
+};
+
+#endif  // _LIBUNWINDSTACK_ELF_H
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
new file mode 100644
index 0000000..d59e9d8
--- /dev/null
+++ b/libunwindstack/ElfInterface.cpp
@@ -0,0 +1,223 @@
+/*
+ * 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 <elf.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+#include "Regs.h"
+
+template <typename EhdrType, typename PhdrType, typename ShdrType>
+bool ElfInterface::ReadAllHeaders() {
+  EhdrType ehdr;
+  if (!memory_->Read(0, &ehdr, sizeof(ehdr))) {
+    return false;
+  }
+
+  if (!ReadProgramHeaders<EhdrType, PhdrType>(ehdr)) {
+    return false;
+  }
+  return ReadSectionHeaders<EhdrType, ShdrType>(ehdr);
+}
+
+template <typename EhdrType, typename PhdrType>
+bool ElfInterface::ReadProgramHeaders(const EhdrType& ehdr) {
+  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))) {
+      return false;
+    }
+
+    if (HandleType(offset, phdr.p_type)) {
+      continue;
+    }
+
+    switch (phdr.p_type) {
+    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))) {
+        return false;
+      }
+      if ((phdr.p_flags & PF_X) == 0) {
+        continue;
+      }
+
+      if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+        return false;
+      }
+      if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+        return false;
+      }
+      if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+        return false;
+      }
+      pt_loads_[phdr.p_offset] = LoadInfo{phdr.p_offset, phdr.p_vaddr,
+                                          static_cast<size_t>(phdr.p_memsz)};
+      if (phdr.p_offset == 0) {
+        load_bias_ = phdr.p_vaddr;
+      }
+      break;
+    }
+
+    case PT_GNU_EH_FRAME:
+      if (!memory_->Read(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))) {
+        return false;
+      }
+      eh_frame_size_ = phdr.p_memsz;
+      break;
+
+    case PT_DYNAMIC:
+      if (!memory_->Read(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))) {
+        return false;
+      }
+      dynamic_size_ = phdr.p_memsz;
+      break;
+    }
+  }
+  return true;
+}
+
+template <typename EhdrType, typename ShdrType>
+bool ElfInterface::ReadSectionHeaders(const EhdrType& ehdr) {
+  uint64_t offset = ehdr.e_shoff;
+  uint64_t sec_offset = 0;
+  uint64_t sec_size = 0;
+
+  // Get the location of the section header names.
+  // If something is malformed in the header table data, we aren't going
+  // to terminate, we'll simply ignore this part.
+  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))) {
+      sec_offset = shdr.sh_offset;
+      sec_size = shdr.sh_size;
+    }
+  }
+
+  // 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))) {
+      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))) {
+        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))) {
+              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))) {
+              gnu_debugdata_offset_ = shdr.sh_offset;
+              gnu_debugdata_size_ = shdr.sh_size;
+            }
+          }
+        }
+      }
+    }
+  }
+  return true;
+}
+
+template <typename DynType>
+bool ElfInterface::GetSonameWithTemplate(std::string* soname) {
+  if (soname_type_ == SONAME_INVALID) {
+    return false;
+  }
+  if (soname_type_ == SONAME_VALID) {
+    *soname = soname_;
+    return true;
+  }
+
+  soname_type_ = SONAME_INVALID;
+
+  uint64_t soname_offset = 0;
+  uint64_t strtab_offset = 0;
+  uint64_t strtab_size = 0;
+
+  // Find the soname location from the dynamic headers section.
+  DynType dyn;
+  uint64_t offset = dynamic_offset_;
+  uint64_t max_offset = offset + dynamic_size_;
+  for (uint64_t offset = dynamic_offset_; offset < max_offset; offset += sizeof(DynType)) {
+    if (!memory_->Read(offset, &dyn, sizeof(dyn))) {
+      return false;
+    }
+
+    if (dyn.d_tag == DT_STRTAB) {
+      strtab_offset = dyn.d_un.d_ptr;
+    } else if (dyn.d_tag == DT_STRSZ) {
+      strtab_size = dyn.d_un.d_val;
+    } else if (dyn.d_tag == DT_SONAME) {
+      soname_offset = dyn.d_un.d_val;
+    } else if (dyn.d_tag == DT_NULL) {
+      break;
+    }
+  }
+
+  soname_offset += strtab_offset;
+  if (soname_offset >= strtab_offset + strtab_size) {
+    return false;
+  }
+  if (!memory_->ReadString(soname_offset, &soname_)) {
+    return false;
+  }
+  soname_type_ = SONAME_VALID;
+  *soname = soname_;
+  return true;
+}
+
+bool ElfInterface::Step(uint64_t, Regs*, Memory*) {
+  return false;
+}
+
+// Instantiate all of the needed template functions.
+template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>();
+template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>();
+
+template bool ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&);
+template bool ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&);
+
+template bool ElfInterface::ReadSectionHeaders<Elf32_Ehdr, Elf32_Shdr>(const Elf32_Ehdr&);
+template bool ElfInterface::ReadSectionHeaders<Elf64_Ehdr, Elf64_Shdr>(const Elf64_Ehdr&);
+
+template bool ElfInterface::GetSonameWithTemplate<Elf32_Dyn>(std::string*);
+template bool ElfInterface::GetSonameWithTemplate<Elf64_Dyn>(std::string*);
diff --git a/libunwindstack/ElfInterface.h b/libunwindstack/ElfInterface.h
new file mode 100644
index 0000000..944146c
--- /dev/null
+++ b/libunwindstack/ElfInterface.h
@@ -0,0 +1,152 @@
+/*
+ * 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_ELF_INTERFACE_H
+#define _LIBUNWINDSTACK_ELF_INTERFACE_H
+
+#include <elf.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+// Forward declarations.
+class Memory;
+class Regs;
+
+struct LoadInfo {
+  uint64_t offset;
+  uint64_t table_offset;
+  size_t table_size;
+};
+
+enum : uint8_t {
+  SONAME_UNKNOWN = 0,
+  SONAME_VALID,
+  SONAME_INVALID,
+};
+
+class ElfInterface {
+ public:
+  ElfInterface(Memory* memory) : memory_(memory) {}
+  virtual ~ElfInterface() = default;
+
+  virtual bool Init() = 0;
+
+  virtual void InitHeaders() = 0;
+
+  virtual bool GetSoname(std::string* name) = 0;
+
+  virtual bool GetFunctionName(uint64_t addr, std::string* name, uint64_t* offset) = 0;
+
+  virtual bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory);
+
+  Memory* CreateGnuDebugdataMemory();
+
+  Memory* memory() { return memory_; }
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads() { return pt_loads_; }
+  uint64_t load_bias() { return load_bias_; }
+  void set_load_bias(uint64_t load_bias) { load_bias_ = load_bias; }
+
+  uint64_t dynamic_offset() { return dynamic_offset_; }
+  uint64_t dynamic_size() { return dynamic_size_; }
+  uint64_t eh_frame_offset() { return eh_frame_offset_; }
+  uint64_t eh_frame_size() { return eh_frame_size_; }
+  uint64_t gnu_debugdata_offset() { return gnu_debugdata_offset_; }
+  uint64_t gnu_debugdata_size() { return gnu_debugdata_size_; }
+
+ protected:
+  template <typename EhdrType, typename PhdrType, typename ShdrType>
+  bool ReadAllHeaders();
+
+  template <typename EhdrType, typename PhdrType>
+  bool ReadProgramHeaders(const EhdrType& ehdr);
+
+  template <typename EhdrType, typename ShdrType>
+  bool ReadSectionHeaders(const EhdrType& ehdr);
+
+  template <typename DynType>
+  bool GetSonameWithTemplate(std::string* soname);
+
+  virtual bool HandleType(uint64_t, uint32_t) { return false; }
+
+  Memory* memory_;
+  std::unordered_map<uint64_t, LoadInfo> pt_loads_;
+  uint64_t load_bias_ = 0;
+
+  // Stored elf data.
+  uint64_t dynamic_offset_ = 0;
+  uint64_t dynamic_size_ = 0;
+
+  uint64_t eh_frame_offset_ = 0;
+  uint64_t eh_frame_size_ = 0;
+
+  uint64_t debug_frame_offset_ = 0;
+  uint64_t debug_frame_size_ = 0;
+
+  uint64_t gnu_debugdata_offset_ = 0;
+  uint64_t gnu_debugdata_size_ = 0;
+
+  uint8_t soname_type_ = SONAME_UNKNOWN;
+  std::string soname_;
+};
+
+class ElfInterface32 : public ElfInterface {
+ public:
+  ElfInterface32(Memory* memory) : ElfInterface(memory) {}
+  virtual ~ElfInterface32() = default;
+
+  bool Init() override {
+    return ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>();
+  }
+
+  void InitHeaders() override {
+  }
+
+  bool GetSoname(std::string* soname) override {
+    return ElfInterface::GetSonameWithTemplate<Elf32_Dyn>(soname);
+  }
+
+  bool GetFunctionName(uint64_t, std::string*, uint64_t*) override {
+    return false;
+  }
+};
+
+class ElfInterface64 : public ElfInterface {
+ public:
+  ElfInterface64(Memory* memory) : ElfInterface(memory) {}
+  virtual ~ElfInterface64() = default;
+
+  bool Init() override {
+    return ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>();
+  }
+
+  void InitHeaders() override {
+  }
+
+  bool GetSoname(std::string* soname) override {
+    return ElfInterface::GetSonameWithTemplate<Elf64_Dyn>(soname);
+  }
+
+  bool GetFunctionName(uint64_t, std::string*, uint64_t*) override {
+    return false;
+  }
+};
+
+#endif  // _LIBUNWINDSTACK_ELF_INTERFACE_H
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
new file mode 100644
index 0000000..e157320
--- /dev/null
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -0,0 +1,127 @@
+/*
+ * 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 <stdint.h>
+
+#include "ArmExidx.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
+
+bool ElfInterfaceArm::FindEntry(uint32_t pc, uint64_t* entry_offset) {
+  if (start_offset_ == 0 || total_entries_ == 0) {
+    return false;
+  }
+
+  // Need to subtract the load_bias from the pc.
+  if (pc < load_bias_) {
+    return false;
+  }
+  pc -= load_bias_;
+
+  size_t first = 0;
+  size_t last = total_entries_;
+  while (first < last) {
+    size_t current = (first + last) / 2;
+    uint32_t addr = addrs_[current];
+    if (addr == 0) {
+      if (!GetPrel31Addr(start_offset_ + current * 8, &addr)) {
+        return false;
+      }
+      addrs_[current] = addr;
+    }
+    if (pc == addr) {
+      *entry_offset = start_offset_ + current * 8;
+      return true;
+    }
+    if (pc < addr) {
+      last = current;
+    } else {
+      first = current + 1;
+    }
+  }
+  if (last != 0) {
+    *entry_offset = start_offset_ + (last - 1) * 8;
+    return true;
+  }
+  return false;
+}
+
+bool ElfInterfaceArm::GetPrel31Addr(uint32_t offset, uint32_t* addr) {
+  uint32_t data;
+  if (!memory_->Read32(offset, &data)) {
+    return false;
+  }
+
+  // Sign extend the value if necessary.
+  int32_t value = (static_cast<int32_t>(data) << 1) >> 1;
+  *addr = offset + value;
+  return true;
+}
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+bool ElfInterfaceArm::HandleType(uint64_t offset, uint32_t type) {
+  if (type != PT_ARM_EXIDX) {
+    return false;
+  }
+
+  Elf32_Phdr phdr;
+  if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+    return true;
+  }
+  if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+    return true;
+  }
+  // The load_bias_ should always be set by this time.
+  start_offset_ = phdr.p_vaddr - load_bias_;
+  total_entries_ = phdr.p_memsz / 8;
+  return true;
+}
+
+bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
+  return StepExidx(pc, regs, process_memory) ||
+      ElfInterface32::Step(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;
+  }
+  ArmExidx arm(regs_arm, memory_, process_memory);
+  arm.set_cfa(regs_arm->sp());
+  if (arm.ExtractEntryData(entry_offset) && arm.Eval()) {
+    // If the pc was not set, then use the LR registers for the PC.
+    if (!arm.pc_set()) {
+      regs_arm->set_pc((*regs_arm)[ARM_REG_LR]);
+      (*regs_arm)[ARM_REG_PC] = regs_arm->pc();
+    } else {
+      regs_arm->set_pc((*regs_arm)[ARM_REG_PC]);
+    }
+    regs_arm->set_sp(arm.cfa());
+    (*regs_arm)[ARM_REG_SP] = regs_arm->sp();
+    return true;
+  }
+  return false;
+}
diff --git a/libunwindstack/ElfInterfaceArm.h b/libunwindstack/ElfInterfaceArm.h
new file mode 100644
index 0000000..ece694f
--- /dev/null
+++ b/libunwindstack/ElfInterfaceArm.h
@@ -0,0 +1,90 @@
+/*
+ * 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_ELF_INTERFACE_ARM_H
+#define _LIBUNWINDSTACK_ELF_INTERFACE_ARM_H
+
+#include <elf.h>
+#include <stdint.h>
+
+#include <iterator>
+#include <unordered_map>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+
+class ElfInterfaceArm : public ElfInterface32 {
+ public:
+  ElfInterfaceArm(Memory* memory) : ElfInterface32(memory) {}
+  virtual ~ElfInterfaceArm() = default;
+
+  class iterator : public std::iterator<std::bidirectional_iterator_tag, uint32_t> {
+   public:
+    iterator(ElfInterfaceArm* interface, size_t index) : interface_(interface), index_(index) { }
+
+    iterator& operator++() { index_++; return *this; }
+    iterator& operator++(int increment) { index_ += increment; return *this; }
+    iterator& operator--() { index_--; return *this; }
+    iterator& operator--(int decrement) { index_ -= decrement; return *this; }
+
+    bool operator==(const iterator& rhs) { return this->index_ == rhs.index_; }
+    bool operator!=(const iterator& rhs) { return this->index_ != rhs.index_; }
+
+    uint32_t operator*() {
+      uint32_t addr = interface_->addrs_[index_];
+      if (addr == 0) {
+        if (!interface_->GetPrel31Addr(interface_->start_offset_ + index_ * 8, &addr)) {
+          return 0;
+        }
+        interface_->addrs_[index_] = addr;
+      }
+      return addr;
+    }
+
+   private:
+    ElfInterfaceArm* interface_ = nullptr;
+    size_t index_ = 0;
+  };
+
+  iterator begin() { return iterator(this, 0); }
+  iterator end() { return iterator(this, total_entries_); }
+
+  bool GetPrel31Addr(uint32_t offset, uint32_t* addr);
+
+  bool FindEntry(uint32_t pc, uint64_t* entry_offset);
+
+  bool HandleType(uint64_t offset, uint32_t type) override;
+
+  bool Step(uint64_t pc, Regs* regs, Memory* process_memory) override;
+
+  bool StepExidx(uint64_t pc, Regs* regs, Memory* process_memory);
+
+  uint64_t start_offset() { return start_offset_; }
+
+  void set_start_offset(uint64_t start_offset) { start_offset_ = start_offset; }
+
+  size_t total_entries() { return total_entries_; }
+
+  void set_total_entries(size_t total_entries) { total_entries_ = total_entries; }
+
+ private:
+  uint64_t start_offset_ = 0;
+  size_t total_entries_ = 0;
+
+  std::unordered_map<size_t, uint32_t> addrs_;
+};
+
+#endif  // _LIBUNWINDSTACK_ELF_INTERFACE_ARM_H
diff --git a/libunwindstack/Log.cpp b/libunwindstack/Log.cpp
new file mode 100644
index 0000000..faeb66c
--- /dev/null
+++ b/libunwindstack/Log.cpp
@@ -0,0 +1,53 @@
+/*
+ * 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 <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+
+#include <string>
+
+#define LOG_TAG "unwind"
+#include <log/log.h>
+
+#include <android-base/stringprintf.h>
+
+#include "Log.h"
+
+static bool g_print_to_stdout = false;
+
+void log_to_stdout(bool enable) {
+  g_print_to_stdout = enable;
+}
+
+// Send the data to the log.
+void log(uint8_t indent, const char* format, ...) {
+  std::string real_format;
+  if (indent > 0) {
+    real_format = android::base::StringPrintf("%*s%s", 2 * indent, " ", format);
+  } else {
+    real_format = format;
+  }
+  va_list args;
+  va_start(args, format);
+  if (g_print_to_stdout) {
+    real_format += '\n';
+    vprintf(real_format.c_str(), args);
+  } else {
+    LOG_PRI_VA(ANDROID_LOG_INFO, LOG_TAG, real_format.c_str(), args);
+  }
+  va_end(args);
+}
diff --git a/libunwindstack/Log.h b/libunwindstack/Log.h
new file mode 100644
index 0000000..2d01aa8
--- /dev/null
+++ b/libunwindstack/Log.h
@@ -0,0 +1,25 @@
+/*
+ * 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_LOG_H
+#define _LIBUNWINDSTACK_LOG_H
+
+#include <stdint.h>
+
+void log_to_stdout(bool enable);
+void log(uint8_t indent, const char* format, ...);
+
+#endif  // _LIBUNWINDSTACK_LOG_H
diff --git a/libunwindstack/Machine.h b/libunwindstack/Machine.h
new file mode 100644
index 0000000..323ce80
--- /dev/null
+++ b/libunwindstack/Machine.h
@@ -0,0 +1,133 @@
+/*
+ * 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_MACHINE_H
+#define _LIBUNWINDSTACK_MACHINE_H
+
+#include <stdint.h>
+
+enum ArmReg : uint16_t {
+  ARM_REG_R0 = 0,
+  ARM_REG_R1,
+  ARM_REG_R2,
+  ARM_REG_R3,
+  ARM_REG_R4,
+  ARM_REG_R5,
+  ARM_REG_R6,
+  ARM_REG_R7,
+  ARM_REG_R8,
+  ARM_REG_R9,
+  ARM_REG_R10,
+  ARM_REG_R11,
+  ARM_REG_R12,
+  ARM_REG_R13,
+  ARM_REG_R14,
+  ARM_REG_R15,
+  ARM_REG_LAST,
+
+  ARM_REG_SP = ARM_REG_R13,
+  ARM_REG_LR = ARM_REG_R14,
+  ARM_REG_PC = ARM_REG_R15,
+};
+
+enum Arm64Reg : uint16_t {
+  ARM64_REG_R0 = 0,
+  ARM64_REG_R1,
+  ARM64_REG_R2,
+  ARM64_REG_R3,
+  ARM64_REG_R4,
+  ARM64_REG_R5,
+  ARM64_REG_R6,
+  ARM64_REG_R7,
+  ARM64_REG_R8,
+  ARM64_REG_R9,
+  ARM64_REG_R10,
+  ARM64_REG_R11,
+  ARM64_REG_R12,
+  ARM64_REG_R13,
+  ARM64_REG_R14,
+  ARM64_REG_R15,
+  ARM64_REG_R16,
+  ARM64_REG_R17,
+  ARM64_REG_R18,
+  ARM64_REG_R19,
+  ARM64_REG_R20,
+  ARM64_REG_R21,
+  ARM64_REG_R22,
+  ARM64_REG_R23,
+  ARM64_REG_R24,
+  ARM64_REG_R25,
+  ARM64_REG_R26,
+  ARM64_REG_R27,
+  ARM64_REG_R28,
+  ARM64_REG_R29,
+  ARM64_REG_R30,
+  ARM64_REG_R31,
+  ARM64_REG_PC,
+  ARM64_REG_LAST,
+
+  ARM64_REG_SP = ARM64_REG_R31,
+  ARM64_REG_LR = ARM64_REG_R30,
+};
+
+enum X86Reg : uint16_t {
+  X86_REG_EAX = 0,
+  X86_REG_ECX,
+  X86_REG_EDX,
+  X86_REG_EBX,
+  X86_REG_ESP,
+  X86_REG_EBP,
+  X86_REG_ESI,
+  X86_REG_EDI,
+  X86_REG_EIP,
+  X86_REG_EFL,
+  X86_REG_CS,
+  X86_REG_SS,
+  X86_REG_DS,
+  X86_REG_ES,
+  X86_REG_FS,
+  X86_REG_GS,
+  X86_REG_LAST,
+
+  X86_REG_SP = X86_REG_ESP,
+  X86_REG_PC = X86_REG_EIP,
+};
+
+enum X86_64Reg : uint16_t {
+  X86_64_REG_RAX = 0,
+  X86_64_REG_RDX,
+  X86_64_REG_RCX,
+  X86_64_REG_RBX,
+  X86_64_REG_RSI,
+  X86_64_REG_RDI,
+  X86_64_REG_RBP,
+  X86_64_REG_RSP,
+  X86_64_REG_R8,
+  X86_64_REG_R9,
+  X86_64_REG_R10,
+  X86_64_REG_R11,
+  X86_64_REG_R12,
+  X86_64_REG_R13,
+  X86_64_REG_R14,
+  X86_64_REG_R15,
+  X86_64_REG_RIP,
+  X86_64_REG_LAST,
+
+  X86_64_REG_SP = X86_64_REG_RSP,
+  X86_64_REG_PC = X86_64_REG_RIP,
+};
+
+#endif  // _LIBUNWINDSTACK_MACHINE_H
diff --git a/libunwindstack/MapInfo.h b/libunwindstack/MapInfo.h
new file mode 100644
index 0000000..8342904
--- /dev/null
+++ b/libunwindstack/MapInfo.h
@@ -0,0 +1,44 @@
+/*
+ * 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_MAP_INFO_H
+#define _LIBUNWINDSTACK_MAP_INFO_H
+
+#include <stdint.h>
+
+#include <string>
+
+// Forward declarations.
+class Elf;
+class Memory;
+
+struct MapInfo {
+  uint64_t start;
+  uint64_t end;
+  uint64_t offset;
+  uint16_t flags;
+  std::string name;
+  Elf* elf = nullptr;
+  // This value is only non-zero if the offset is non-zero but there is
+  // no elf signature found at that offset. This indicates that the
+  // entire file is represented by the Memory object returned by CreateMemory,
+  // instead of a portion of the file.
+  uint64_t elf_offset;
+
+  Memory* CreateMemory(pid_t pid);
+};
+
+#endif  // _LIBUNWINDSTACK_MAP_INFO_H
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
new file mode 100644
index 0000000..1fcf842
--- /dev/null
+++ b/libunwindstack/Memory.cpp
@@ -0,0 +1,216 @@
+/*
+ * 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 <sys/mman.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <memory>
+
+#include <android-base/unique_fd.h>
+
+#include "Memory.h"
+
+bool Memory::ReadString(uint64_t addr, std::string* string, uint64_t max_read) {
+  string->clear();
+  uint64_t bytes_read = 0;
+  while (bytes_read < max_read) {
+    uint8_t value;
+    if (!Read(addr, &value, sizeof(value))) {
+      return false;
+    }
+    if (value == '\0') {
+      return true;
+    }
+    string->push_back(value);
+    addr++;
+    bytes_read++;
+  }
+  return false;
+}
+
+bool MemoryBuffer::Read(uint64_t addr, void* dst, size_t size) {
+  uint64_t last_read_byte;
+  if (__builtin_add_overflow(size, addr, &last_read_byte)) {
+    return false;
+  }
+  if (last_read_byte > raw_.size()) {
+    return false;
+  }
+  memcpy(dst, &raw_[addr], size);
+  return true;
+}
+
+uint8_t* MemoryBuffer::GetPtr(size_t offset) {
+  if (offset < raw_.size()) {
+    return &raw_[offset];
+  }
+  return nullptr;
+}
+
+MemoryFileAtOffset::~MemoryFileAtOffset() {
+  Clear();
+}
+
+void MemoryFileAtOffset::Clear() {
+  if (data_) {
+    munmap(&data_[-offset_], size_ + offset_);
+    data_ = nullptr;
+  }
+}
+
+bool MemoryFileAtOffset::Init(const std::string& file, uint64_t offset, uint64_t size) {
+  // Clear out any previous data if it exists.
+  Clear();
+
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
+  if (fd == -1) {
+    return false;
+  }
+  struct stat buf;
+  if (fstat(fd, &buf) == -1) {
+    return false;
+  }
+  if (offset >= static_cast<uint64_t>(buf.st_size)) {
+    return false;
+  }
+
+  offset_ = offset & (getpagesize() - 1);
+  uint64_t aligned_offset = offset & ~(getpagesize() - 1);
+  size_ = buf.st_size - aligned_offset;
+  if (size < (UINT64_MAX - offset_) && size + offset_ < size_) {
+    // Truncate the mapped size.
+    size_ = size + offset_;
+  }
+  void* map = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, aligned_offset);
+  if (map == MAP_FAILED) {
+    return false;
+  }
+
+  data_ = &reinterpret_cast<uint8_t*>(map)[offset_];
+  size_ -= offset_;
+
+  return true;
+}
+
+bool MemoryFileAtOffset::Read(uint64_t addr, void* dst, size_t size) {
+  if (addr + size > size_) {
+    return false;
+  }
+  memcpy(dst, &data_[addr], size);
+  return true;
+}
+
+static bool PtraceRead(pid_t pid, uint64_t addr, long* value) {
+#if !defined(__LP64__)
+  // Cannot read an address greater than 32 bits.
+  if (addr > UINT32_MAX) {
+    return false;
+  }
+#endif
+  // 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);
+  if (*value == -1 && errno) {
+    return false;
+  }
+  return true;
+}
+
+bool MemoryRemote::Read(uint64_t addr, void* dst, size_t bytes) {
+  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)) {
+      return false;
+    }
+    size_t copy_bytes = std::min(sizeof(long) - align_bytes, bytes);
+    memcpy(dst, reinterpret_cast<uint8_t*>(&data) + align_bytes, copy_bytes);
+    addr += copy_bytes;
+    dst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(dst) + copy_bytes);
+    bytes -= copy_bytes;
+    bytes_read += copy_bytes;
+  }
+
+  for (size_t i = 0; i < bytes / sizeof(long); i++) {
+    if (!PtraceRead(pid_, addr, &data)) {
+      return false;
+    }
+    memcpy(dst, &data, sizeof(long));
+    dst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(dst) + sizeof(long));
+    addr += sizeof(long);
+    bytes_read += sizeof(long);
+  }
+
+  size_t left_over = bytes & (sizeof(long) - 1);
+  if (left_over) {
+    if (!PtraceRead(pid_, addr, &data)) {
+      return false;
+    }
+    memcpy(dst, &data, left_over);
+    bytes_read += left_over;
+  }
+  return true;
+}
+
+bool MemoryLocal::Read(uint64_t addr, void* dst, size_t size) {
+  // The process_vm_readv call does 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.
+  struct iovec local_io;
+  local_io.iov_base = dst;
+  local_io.iov_len = size;
+
+  struct iovec remote_io;
+  remote_io.iov_base = reinterpret_cast<void*>(static_cast<uintptr_t>(addr));
+  remote_io.iov_len = size;
+
+  ssize_t bytes_read = process_vm_readv(getpid(), &local_io, 1, &remote_io, 1, 0);
+  if (bytes_read == -1) {
+    return false;
+  }
+  return static_cast<size_t>(bytes_read) == size;
+}
+
+bool MemoryOffline::Init(const std::string& file, uint64_t offset) {
+  if (!MemoryFileAtOffset::Init(file, offset)) {
+    return false;
+  }
+  // The first uint64_t value is the start of memory.
+  if (!MemoryFileAtOffset::Read(0, &start_, sizeof(start_))) {
+    return false;
+  }
+  // Subtract the first 64 bit value from the total size.
+  size_ -= sizeof(start_);
+  return true;
+}
+
+bool MemoryOffline::Read(uint64_t addr, void* dst, size_t size) {
+  if (addr < start_ || addr + size > start_ + offset_ + size_) {
+    return false;
+  }
+  memcpy(dst, &data_[addr + offset_ - start_ + sizeof(start_)], size);
+  return true;
+}
diff --git a/libunwindstack/Memory.h b/libunwindstack/Memory.h
new file mode 100644
index 0000000..c5316a1
--- /dev/null
+++ b/libunwindstack/Memory.h
@@ -0,0 +1,137 @@
+/*
+ * 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_MEMORY_H
+#define _LIBUNWINDSTACK_MEMORY_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+class Memory {
+ public:
+  Memory() = default;
+  virtual ~Memory() = default;
+
+  virtual bool ReadString(uint64_t addr, std::string* string, uint64_t max_read = UINT64_MAX);
+
+  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 Read32(uint64_t addr, uint32_t* dst) {
+    return Read(addr, dst, sizeof(uint32_t));
+  }
+
+  inline bool Read64(uint64_t addr, uint64_t* dst) {
+    return Read(addr, dst, sizeof(uint64_t));
+  }
+};
+
+class MemoryBuffer : public Memory {
+ public:
+  MemoryBuffer() = default;
+  virtual ~MemoryBuffer() = default;
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+
+  uint8_t* GetPtr(size_t offset);
+
+  void Resize(size_t size) { raw_.resize(size); }
+
+  uint64_t Size() { return raw_.size(); }
+
+ private:
+  std::vector<uint8_t> raw_;
+};
+
+class MemoryFileAtOffset : public Memory {
+ public:
+  MemoryFileAtOffset() = default;
+  virtual ~MemoryFileAtOffset();
+
+  bool Init(const std::string& file, uint64_t offset, uint64_t size = UINT64_MAX);
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+
+  void Clear();
+
+ protected:
+  size_t size_ = 0;
+  size_t offset_ = 0;
+  uint8_t* data_ = nullptr;
+};
+
+class MemoryOffline : public MemoryFileAtOffset {
+ public:
+  MemoryOffline() = default;
+  virtual ~MemoryOffline() = default;
+
+  bool Init(const std::string& file, uint64_t offset);
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+  uint64_t start_;
+};
+
+class MemoryRemote : public Memory {
+ public:
+  MemoryRemote(pid_t pid) : pid_(pid) {}
+  virtual ~MemoryRemote() = default;
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+
+  pid_t pid() { return pid_; }
+
+ private:
+  pid_t pid_;
+};
+
+class MemoryLocal : public Memory {
+ public:
+  MemoryLocal() = default;
+  virtual ~MemoryLocal() = default;
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+};
+
+class MemoryRange : public Memory {
+ public:
+  MemoryRange(Memory* memory, uint64_t begin, uint64_t end)
+      : memory_(memory), begin_(begin), length_(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;
+  }
+
+ private:
+  Memory* memory_;
+  uint64_t begin_;
+  uint64_t length_;
+};
+
+#endif  // _LIBUNWINDSTACK_MEMORY_H
diff --git a/libunwindstack/Regs.cpp b/libunwindstack/Regs.cpp
new file mode 100644
index 0000000..adb6522
--- /dev/null
+++ b/libunwindstack/Regs.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 <assert.h>
+#include <elf.h>
+#include <stdint.h>
+#include <sys/ptrace.h>
+#include <sys/uio.h>
+
+#include <vector>
+
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "Machine.h"
+#include "MapInfo.h"
+#include "Regs.h"
+#include "User.h"
+
+template <typename AddressType>
+uint64_t RegsTmpl<AddressType>::GetRelPc(Elf* elf, const MapInfo* map_info) {
+  uint64_t load_bias = 0;
+  if (elf->valid()) {
+    load_bias = elf->interface()->load_bias();
+  }
+
+  return pc_ - map_info->start + load_bias + map_info->elf_offset;
+}
+
+template <typename AddressType>
+bool RegsTmpl<AddressType>::GetReturnAddressFromDefault(Memory* memory, uint64_t* value) {
+  switch (return_loc_.type) {
+  case LOCATION_REGISTER:
+    assert(return_loc_.value < total_regs_);
+    *value = regs_[return_loc_.value];
+    return true;
+  case LOCATION_SP_OFFSET:
+    AddressType return_value;
+    if (!memory->Read(sp_ + return_loc_.value, &return_value, sizeof(return_value))) {
+      return false;
+    }
+    *value = return_value;
+    return true;
+  case LOCATION_UNKNOWN:
+  default:
+    return false;
+  }
+}
+
+RegsArm::RegsArm() : RegsTmpl<uint32_t>(ARM_REG_LAST, ARM_REG_SP,
+                                        Location(LOCATION_REGISTER, ARM_REG_LR)) {
+}
+
+uint64_t RegsArm::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+  if (!elf->valid()) {
+    return rel_pc;
+  }
+
+  uint64_t load_bias = elf->interface()->load_bias();
+  if (rel_pc < load_bias) {
+    return rel_pc;
+  }
+  uint64_t adjusted_rel_pc = rel_pc - load_bias;
+
+  if (adjusted_rel_pc < 5) {
+    return rel_pc;
+  }
+
+  if (adjusted_rel_pc & 1) {
+    // This is a thumb instruction, it could be 2 or 4 bytes.
+    uint32_t value;
+    if (rel_pc < 5 || !elf->memory()->Read(adjusted_rel_pc - 5, &value, sizeof(value)) ||
+        (value & 0xe000f000) != 0xe000f000) {
+      return rel_pc - 2;
+    }
+  }
+  return rel_pc - 4;
+}
+
+RegsArm64::RegsArm64() : RegsTmpl<uint64_t>(ARM64_REG_LAST, ARM64_REG_SP,
+                                            Location(LOCATION_REGISTER, ARM64_REG_LR)) {
+}
+
+uint64_t RegsArm64::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+  if (!elf->valid()) {
+    return rel_pc;
+  }
+
+  if (rel_pc < 4) {
+    return rel_pc;
+  }
+  return rel_pc - 4;
+}
+
+RegsX86::RegsX86() : RegsTmpl<uint32_t>(X86_REG_LAST, X86_REG_SP,
+                                        Location(LOCATION_SP_OFFSET, -4)) {
+}
+
+uint64_t RegsX86::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+  if (!elf->valid()) {
+    return rel_pc;
+  }
+
+  if (rel_pc == 0) {
+    return 0;
+  }
+  return rel_pc - 1;
+}
+
+RegsX86_64::RegsX86_64() : RegsTmpl<uint64_t>(X86_64_REG_LAST, X86_64_REG_SP,
+                                              Location(LOCATION_SP_OFFSET, -8)) {
+}
+
+uint64_t RegsX86_64::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+  if (!elf->valid()) {
+    return rel_pc;
+  }
+
+  if (rel_pc == 0) {
+    return 0;
+  }
+
+  return rel_pc - 1;
+}
+
+static Regs* ReadArm(void* remote_data) {
+  arm_user_regs* user = reinterpret_cast<arm_user_regs*>(remote_data);
+
+  RegsArm* regs = new RegsArm();
+  memcpy(regs->RawData(), &user->regs[0], ARM_REG_LAST * sizeof(uint32_t));
+
+  regs->set_pc(user->regs[ARM_REG_PC]);
+  regs->set_sp(user->regs[ARM_REG_SP]);
+
+  return regs;
+}
+
+static Regs* ReadArm64(void* remote_data) {
+  arm64_user_regs* user = reinterpret_cast<arm64_user_regs*>(remote_data);
+
+  RegsArm64* regs = new RegsArm64();
+  memcpy(regs->RawData(), &user->regs[0], (ARM64_REG_R31 + 1) * sizeof(uint64_t));
+  regs->set_pc(user->pc);
+  regs->set_sp(user->sp);
+
+  return regs;
+}
+
+static Regs* ReadX86(void* remote_data) {
+  x86_user_regs* user = reinterpret_cast<x86_user_regs*>(remote_data);
+
+  RegsX86* regs = new RegsX86();
+  (*regs)[X86_REG_EAX] = user->eax;
+  (*regs)[X86_REG_EBX] = user->ebx;
+  (*regs)[X86_REG_ECX] = user->ecx;
+  (*regs)[X86_REG_EDX] = user->edx;
+  (*regs)[X86_REG_EBP] = user->ebp;
+  (*regs)[X86_REG_EDI] = user->edi;
+  (*regs)[X86_REG_ESI] = user->esi;
+  (*regs)[X86_REG_ESP] = user->esp;
+  (*regs)[X86_REG_EIP] = user->eip;
+
+  regs->set_pc(user->eip);
+  regs->set_sp(user->esp);
+
+  return regs;
+}
+
+static Regs* ReadX86_64(void* remote_data) {
+  x86_64_user_regs* user = reinterpret_cast<x86_64_user_regs*>(remote_data);
+
+  RegsX86_64* regs = new RegsX86_64();
+  (*regs)[X86_64_REG_RAX] = user->rax;
+  (*regs)[X86_64_REG_RBX] = user->rbx;
+  (*regs)[X86_64_REG_RCX] = user->rcx;
+  (*regs)[X86_64_REG_RDX] = user->rdx;
+  (*regs)[X86_64_REG_R8] = user->r8;
+  (*regs)[X86_64_REG_R9] = user->r9;
+  (*regs)[X86_64_REG_R10] = user->r10;
+  (*regs)[X86_64_REG_R11] = user->r11;
+  (*regs)[X86_64_REG_R12] = user->r12;
+  (*regs)[X86_64_REG_R13] = user->r13;
+  (*regs)[X86_64_REG_R14] = user->r14;
+  (*regs)[X86_64_REG_R15] = user->r15;
+  (*regs)[X86_64_REG_RDI] = user->rdi;
+  (*regs)[X86_64_REG_RSI] = user->rsi;
+  (*regs)[X86_64_REG_RBP] = user->rbp;
+  (*regs)[X86_64_REG_RSP] = user->rsp;
+  (*regs)[X86_64_REG_RIP] = user->rip;
+
+  regs->set_pc(user->rip);
+  regs->set_sp(user->rsp);
+
+  return regs;
+}
+
+// This function assumes that reg_data is already aligned to a 64 bit value.
+// If not this could crash with an unaligned access.
+Regs* Regs::RemoteGet(pid_t pid, uint32_t* machine_type) {
+  // Make the buffer large enough to contain the largest registers type.
+  std::vector<uint64_t> buffer(MAX_USER_REGS_SIZE / sizeof(uint64_t));
+  struct iovec io;
+  io.iov_base = buffer.data();
+  io.iov_len = buffer.size() * sizeof(uint64_t);
+
+  if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, reinterpret_cast<void*>(&io)) == -1) {
+    return nullptr;
+  }
+
+  switch (io.iov_len) {
+  case sizeof(x86_user_regs):
+    *machine_type = EM_386;
+    return ReadX86(buffer.data());
+  case sizeof(x86_64_user_regs):
+    *machine_type = EM_X86_64;
+    return ReadX86_64(buffer.data());
+  case sizeof(arm_user_regs):
+    *machine_type = EM_ARM;
+    return ReadArm(buffer.data());
+  case sizeof(arm64_user_regs):
+    *machine_type = EM_AARCH64;
+    return ReadArm64(buffer.data());
+  }
+  return nullptr;
+}
diff --git a/libunwindstack/Regs.h b/libunwindstack/Regs.h
new file mode 100644
index 0000000..718fc85
--- /dev/null
+++ b/libunwindstack/Regs.h
@@ -0,0 +1,127 @@
+/*
+ * 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_REGS_H
+#define _LIBUNWINDSTACK_REGS_H
+
+#include <stdint.h>
+
+#include <vector>
+
+// Forward declarations.
+class Elf;
+struct MapInfo;
+
+class Regs {
+ public:
+  enum LocationEnum : uint8_t {
+    LOCATION_UNKNOWN = 0,
+    LOCATION_REGISTER,
+    LOCATION_SP_OFFSET,
+  };
+
+  struct Location {
+    Location(LocationEnum type, int16_t value) : type(type), value(value) {}
+
+    LocationEnum type;
+    int16_t value;
+  };
+
+  Regs(uint16_t total_regs, uint16_t sp_reg, const Location& return_loc)
+      : total_regs_(total_regs), sp_reg_(sp_reg), return_loc_(return_loc) {}
+  virtual ~Regs() = default;
+
+  virtual void* RawData() = 0;
+  virtual uint64_t pc() = 0;
+  virtual uint64_t sp() = 0;
+
+  virtual bool GetReturnAddressFromDefault(Memory* memory, uint64_t* value) = 0;
+
+  virtual uint64_t GetRelPc(Elf* elf, const MapInfo* map_info) = 0;
+
+  virtual uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) = 0;
+
+  uint16_t sp_reg() { return sp_reg_; }
+  uint16_t total_regs() { return total_regs_; }
+
+  static Regs* RemoteGet(pid_t pid, uint32_t* machine_type);
+
+ protected:
+  uint16_t total_regs_;
+  uint16_t sp_reg_;
+  Location return_loc_;
+};
+
+template <typename AddressType>
+class RegsTmpl : public Regs {
+ public:
+  RegsTmpl(uint16_t total_regs, uint16_t sp_reg, Location return_loc)
+      : Regs(total_regs, sp_reg, return_loc), regs_(total_regs) {}
+  virtual ~RegsTmpl() = default;
+
+  uint64_t GetRelPc(Elf* elf, const MapInfo* map_info) override;
+
+  bool GetReturnAddressFromDefault(Memory* memory, uint64_t* value) override;
+
+  uint64_t pc() override { return pc_; }
+  uint64_t sp() override { return sp_; }
+
+  void set_pc(AddressType pc) { pc_ = pc; }
+  void set_sp(AddressType sp) { sp_ = sp; }
+
+  inline AddressType& operator[](size_t reg) { return regs_[reg]; }
+
+  void* RawData() override { return regs_.data(); }
+
+ protected:
+  AddressType pc_;
+  AddressType sp_;
+  std::vector<AddressType> regs_;
+};
+
+class RegsArm : public RegsTmpl<uint32_t> {
+ public:
+  RegsArm();
+  virtual ~RegsArm() = default;
+
+  uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+class RegsArm64 : public RegsTmpl<uint64_t> {
+ public:
+  RegsArm64();
+  virtual ~RegsArm64() = default;
+
+  uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+class RegsX86 : public RegsTmpl<uint32_t> {
+ public:
+  RegsX86();
+  virtual ~RegsX86() = default;
+
+  uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+class RegsX86_64 : public RegsTmpl<uint64_t> {
+ public:
+  RegsX86_64();
+  virtual ~RegsX86_64() = default;
+
+  uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+#endif  // _LIBUNWINDSTACK_REGS_H
diff --git a/libunwindstack/User.h b/libunwindstack/User.h
new file mode 100644
index 0000000..a695467
--- /dev/null
+++ b/libunwindstack/User.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef _LIBUNWINDSTACK_USER_H
+#define _LIBUNWINDSTACK_USER_H
+
+struct x86_user_regs {
+  uint32_t ebx;
+  uint32_t ecx;
+  uint32_t edx;
+  uint32_t esi;
+  uint32_t edi;
+  uint32_t ebp;
+  uint32_t eax;
+  uint32_t xds;
+  uint32_t xes;
+  uint32_t xfs;
+  uint32_t xgs;
+  uint32_t orig_eax;
+  uint32_t eip;
+  uint32_t xcs;
+  uint32_t eflags;
+  uint32_t esp;
+  uint32_t xss;
+};
+
+struct x86_64_user_regs {
+  uint64_t r15;
+  uint64_t r14;
+  uint64_t r13;
+  uint64_t r12;
+  uint64_t rbp;
+  uint64_t rbx;
+  uint64_t r11;
+  uint64_t r10;
+  uint64_t r9;
+  uint64_t r8;
+  uint64_t rax;
+  uint64_t rcx;
+  uint64_t rdx;
+  uint64_t rsi;
+  uint64_t rdi;
+  uint64_t orig_rax;
+  uint64_t rip;
+  uint64_t cs;
+  uint64_t eflags;
+  uint64_t rsp;
+  uint64_t ss;
+  uint64_t fs_base;
+  uint64_t gs_base;
+  uint64_t ds;
+  uint64_t es;
+  uint64_t fs;
+  uint64_t gs;
+};
+
+struct arm_user_regs {
+  uint32_t regs[18];
+};
+
+struct arm64_user_regs {
+  uint64_t regs[31];
+  uint64_t sp;
+  uint64_t pc;
+  uint64_t pstate;
+};
+
+// The largest user structure.
+constexpr size_t MAX_USER_REGS_SIZE = sizeof(arm64_user_regs) + 10;
+
+#endif  // _LIBUNWINDSTACK_USER_H
diff --git a/libunwindstack/tests/ArmExidxDecodeTest.cpp b/libunwindstack/tests/ArmExidxDecodeTest.cpp
new file mode 100644
index 0000000..4fff48e
--- /dev/null
+++ b/libunwindstack/tests/ArmExidxDecodeTest.cpp
@@ -0,0 +1,1094 @@
+/*
+ * 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 <deque>
+#include <ios>
+#include <memory>
+#include <string>
+
+#include <gtest/gtest.h>
+
+#include "ArmExidx.h"
+#include "Regs.h"
+#include "Log.h"
+
+#include "LogFake.h"
+#include "MemoryFake.h"
+
+class ArmExidxDecodeTest : public ::testing::TestWithParam<std::string> {
+ protected:
+  void Init(Memory* process_memory = nullptr) {
+    TearDown();
+
+    if (process_memory == nullptr) {
+      process_memory = &process_memory_;
+    }
+
+    regs_arm_.reset(new RegsArm());
+    for (size_t i = 0; i < regs_arm_->total_regs(); i++) {
+      (*regs_arm_)[i] = 0;
+    }
+    regs_arm_->set_pc(0);
+    regs_arm_->set_sp(0);
+
+    exidx_.reset(new ArmExidx(regs_arm_.get(), &elf_memory_, process_memory));
+    if (log_) {
+      exidx_->set_log(true);
+      exidx_->set_log_indent(0);
+      exidx_->set_log_skip_execution(false);
+    }
+    data_ = exidx_->data();
+    exidx_->set_cfa(0x10000);
+  }
+
+  void SetUp() override {
+    if (GetParam() != "no_logging") {
+      log_ = false;
+    } else {
+      log_ = true;
+    }
+    ResetLogs();
+    elf_memory_.Clear();
+    process_memory_.Clear();
+    Init();
+  }
+
+  std::unique_ptr<ArmExidx> exidx_;
+  std::unique_ptr<RegsArm> regs_arm_;
+  std::deque<uint8_t>* data_;
+
+  MemoryFake elf_memory_;
+  MemoryFake process_memory_;
+  bool log_;
+};
+
+TEST_P(ArmExidxDecodeTest, vsp_incr) {
+  // 00xxxxxx: vsp = vsp + (xxxxxx << 2) + 4
+  data_->push_back(0x00);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 4\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+
+  ResetLogs();
+  data_->clear();
+  data_->push_back(0x01);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 8\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1000cU, exidx_->cfa());
+
+  ResetLogs();
+  data_->clear();
+  data_->push_back(0x3f);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 256\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1010cU, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, vsp_decr) {
+  // 01xxxxxx: vsp = vsp - (xxxxxx << 2) + 4
+  data_->push_back(0x40);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp - 4\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0xfffcU, exidx_->cfa());
+
+  ResetLogs();
+  data_->clear();
+  data_->push_back(0x41);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp - 8\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0xfff4U, exidx_->cfa());
+
+  ResetLogs();
+  data_->clear();
+  data_->push_back(0x7f);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp - 256\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0xfef4U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, refuse_unwind) {
+  // 10000000 00000000: Refuse to unwind
+  data_->push_back(0x80);
+  data_->push_back(0x00);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind Refuse to unwind\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(ARM_STATUS_NO_UNWIND, exidx_->status());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_up_to_12) {
+  // 1000iiii iiiiiiii: Pop up to 12 integer registers
+  data_->push_back(0x88);
+  data_->push_back(0x00);
+  process_memory_.SetData32(0x10000, 0x10);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_TRUE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r15}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+  ASSERT_EQ(0x10U, (*exidx_->regs())[15]);
+
+  ResetLogs();
+  data_->push_back(0x8f);
+  data_->push_back(0xff);
+  for (size_t i = 0; i < 12; i++) {
+    process_memory_.SetData32(0x10004 + i * 4, i + 0x20);
+  }
+  exidx_->set_pc_set(false);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_TRUE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15}\n",
+              GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  // Popping r13 results in a modified cfa.
+  ASSERT_EQ(0x29U, exidx_->cfa());
+
+  ASSERT_EQ(0x20U, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x21U, (*exidx_->regs())[5]);
+  ASSERT_EQ(0x22U, (*exidx_->regs())[6]);
+  ASSERT_EQ(0x23U, (*exidx_->regs())[7]);
+  ASSERT_EQ(0x24U, (*exidx_->regs())[8]);
+  ASSERT_EQ(0x25U, (*exidx_->regs())[9]);
+  ASSERT_EQ(0x26U, (*exidx_->regs())[10]);
+  ASSERT_EQ(0x27U, (*exidx_->regs())[11]);
+  ASSERT_EQ(0x28U, (*exidx_->regs())[12]);
+  ASSERT_EQ(0x29U, (*exidx_->regs())[13]);
+  ASSERT_EQ(0x2aU, (*exidx_->regs())[14]);
+  ASSERT_EQ(0x2bU, (*exidx_->regs())[15]);
+
+  ResetLogs();
+  exidx_->set_cfa(0x10034);
+  data_->push_back(0x81);
+  data_->push_back(0x28);
+  process_memory_.SetData32(0x10034, 0x11);
+  process_memory_.SetData32(0x10038, 0x22);
+  process_memory_.SetData32(0x1003c, 0x33);
+  exidx_->set_pc_set(false);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r7, r9, r12}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10040U, exidx_->cfa());
+  ASSERT_EQ(0x11U, (*exidx_->regs())[7]);
+  ASSERT_EQ(0x22U, (*exidx_->regs())[9]);
+  ASSERT_EQ(0x33U, (*exidx_->regs())[12]);
+}
+
+TEST_P(ArmExidxDecodeTest, set_vsp_from_register) {
+  // 1001nnnn: Set vsp = r[nnnn] (nnnn != 13, 15)
+  exidx_->set_cfa(0x100);
+  for (size_t i = 0; i < 15; i++) {
+    (*regs_arm_)[i] = i + 1;
+  }
+
+  data_->push_back(0x90);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = r0\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(1U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0x93);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = r3\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(4U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0x9e);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = r14\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(15U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, reserved_prefix) {
+  // 10011101: Reserved as prefix for ARM register to register moves
+  data_->push_back(0x9d);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind [Reserved]\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(ARM_STATUS_RESERVED, exidx_->status());
+
+  // 10011111: Reserved as prefix for Intel Wireless MMX register to register moves
+  ResetLogs();
+  data_->push_back(0x9f);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind [Reserved]\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(ARM_STATUS_RESERVED, exidx_->status());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_registers) {
+  // 10100nnn: Pop r4-r[4+nnn]
+  data_->push_back(0xa0);
+  process_memory_.SetData32(0x10000, 0x14);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+  ASSERT_EQ(0x14U, (*exidx_->regs())[4]);
+
+  ResetLogs();
+  data_->push_back(0xa3);
+  process_memory_.SetData32(0x10004, 0x20);
+  process_memory_.SetData32(0x10008, 0x30);
+  process_memory_.SetData32(0x1000c, 0x40);
+  process_memory_.SetData32(0x10010, 0x50);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4-r7}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10014U, exidx_->cfa());
+  ASSERT_EQ(0x20U, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x30U, (*exidx_->regs())[5]);
+  ASSERT_EQ(0x40U, (*exidx_->regs())[6]);
+  ASSERT_EQ(0x50U, (*exidx_->regs())[7]);
+
+  ResetLogs();
+  data_->push_back(0xa7);
+  process_memory_.SetData32(0x10014, 0x41);
+  process_memory_.SetData32(0x10018, 0x51);
+  process_memory_.SetData32(0x1001c, 0x61);
+  process_memory_.SetData32(0x10020, 0x71);
+  process_memory_.SetData32(0x10024, 0x81);
+  process_memory_.SetData32(0x10028, 0x91);
+  process_memory_.SetData32(0x1002c, 0xa1);
+  process_memory_.SetData32(0x10030, 0xb1);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4-r11}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10034U, exidx_->cfa());
+  ASSERT_EQ(0x41U, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x51U, (*exidx_->regs())[5]);
+  ASSERT_EQ(0x61U, (*exidx_->regs())[6]);
+  ASSERT_EQ(0x71U, (*exidx_->regs())[7]);
+  ASSERT_EQ(0x81U, (*exidx_->regs())[8]);
+  ASSERT_EQ(0x91U, (*exidx_->regs())[9]);
+  ASSERT_EQ(0xa1U, (*exidx_->regs())[10]);
+  ASSERT_EQ(0xb1U, (*exidx_->regs())[11]);
+}
+
+TEST_P(ArmExidxDecodeTest, pop_registers_with_r14) {
+  // 10101nnn: Pop r4-r[4+nnn], r14
+  data_->push_back(0xa8);
+  process_memory_.SetData32(0x10000, 0x12);
+  process_memory_.SetData32(0x10004, 0x22);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4, r14}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+  ASSERT_EQ(0x12U, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x22U, (*exidx_->regs())[14]);
+
+  ResetLogs();
+  data_->push_back(0xab);
+  process_memory_.SetData32(0x10008, 0x1);
+  process_memory_.SetData32(0x1000c, 0x2);
+  process_memory_.SetData32(0x10010, 0x3);
+  process_memory_.SetData32(0x10014, 0x4);
+  process_memory_.SetData32(0x10018, 0x5);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4-r7, r14}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1001cU, exidx_->cfa());
+  ASSERT_EQ(0x1U, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x2U, (*exidx_->regs())[5]);
+  ASSERT_EQ(0x3U, (*exidx_->regs())[6]);
+  ASSERT_EQ(0x4U, (*exidx_->regs())[7]);
+  ASSERT_EQ(0x5U, (*exidx_->regs())[14]);
+
+  ResetLogs();
+  data_->push_back(0xaf);
+  process_memory_.SetData32(0x1001c, 0x1a);
+  process_memory_.SetData32(0x10020, 0x2a);
+  process_memory_.SetData32(0x10024, 0x3a);
+  process_memory_.SetData32(0x10028, 0x4a);
+  process_memory_.SetData32(0x1002c, 0x5a);
+  process_memory_.SetData32(0x10030, 0x6a);
+  process_memory_.SetData32(0x10034, 0x7a);
+  process_memory_.SetData32(0x10038, 0x8a);
+  process_memory_.SetData32(0x1003c, 0x9a);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4-r11, r14}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10040U, exidx_->cfa());
+  ASSERT_EQ(0x1aU, (*exidx_->regs())[4]);
+  ASSERT_EQ(0x2aU, (*exidx_->regs())[5]);
+  ASSERT_EQ(0x3aU, (*exidx_->regs())[6]);
+  ASSERT_EQ(0x4aU, (*exidx_->regs())[7]);
+  ASSERT_EQ(0x5aU, (*exidx_->regs())[8]);
+  ASSERT_EQ(0x6aU, (*exidx_->regs())[9]);
+  ASSERT_EQ(0x7aU, (*exidx_->regs())[10]);
+  ASSERT_EQ(0x8aU, (*exidx_->regs())[11]);
+  ASSERT_EQ(0x9aU, (*exidx_->regs())[14]);
+}
+
+TEST_P(ArmExidxDecodeTest, finish) {
+  // 10110000: Finish
+  data_->push_back(0xb0);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind finish\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10000U, exidx_->cfa());
+  ASSERT_EQ(ARM_STATUS_FINISH, exidx_->status());
+}
+
+TEST_P(ArmExidxDecodeTest, spare) {
+  // 10110001 00000000: Spare
+  data_->push_back(0xb1);
+  data_->push_back(0x00);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10000U, exidx_->cfa());
+  ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+
+  // 10110001 xxxxyyyy: Spare (xxxx != 0000)
+  for (size_t x = 1; x < 16; x++) {
+    for (size_t y = 0; y < 16; y++) {
+      ResetLogs();
+      data_->push_back(0xb1);
+      data_->push_back((x << 4) | y);
+      ASSERT_FALSE(exidx_->Decode()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ("", GetFakeLogBuf()) << "x, y = " << x << ", " << y;
+      if (log_) {
+        ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint()) << "x, y = " << x << ", " << y;
+      } else {
+        ASSERT_EQ("", GetFakeLogPrint());
+      }
+      ASSERT_EQ(0x10000U, exidx_->cfa()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+    }
+  }
+
+  // 101101nn: Spare
+  for (size_t n = 0; n < 4; n++) {
+    ResetLogs();
+    data_->push_back(0xb4 | n);
+    ASSERT_FALSE(exidx_->Decode()) << "n = " << n;
+    ASSERT_EQ("", GetFakeLogBuf()) << "n = " << n;
+    if (log_) {
+      ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint()) << "n = " << n;
+    } else {
+      ASSERT_EQ("", GetFakeLogPrint());
+    }
+    ASSERT_EQ(0x10000U, exidx_->cfa()) << "n = " << n;
+    ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+  }
+
+  // 11000111 00000000: Spare
+  ResetLogs();
+  data_->push_back(0xc7);
+  data_->push_back(0x00);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10000U, exidx_->cfa());
+  ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+
+  // 11000111 xxxxyyyy: Spare (xxxx != 0000)
+  for (size_t x = 1; x < 16; x++) {
+    for (size_t y = 0; y < 16; y++) {
+      ResetLogs();
+      data_->push_back(0xc7);
+      data_->push_back(0x10);
+      ASSERT_FALSE(exidx_->Decode()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ("", GetFakeLogBuf()) << "x, y = " << x << ", " << y;
+      if (log_) {
+        ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint()) << "x, y = " << x << ", " << y;
+      } else {
+        ASSERT_EQ("", GetFakeLogPrint());
+      }
+      ASSERT_EQ(0x10000U, exidx_->cfa()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+    }
+  }
+
+  // 11001yyy: Spare (yyy != 000, 001)
+  for (size_t y = 2; y < 8; y++) {
+    ResetLogs();
+    data_->push_back(0xc8 | y);
+    ASSERT_FALSE(exidx_->Decode()) << "y = " << y;
+    ASSERT_EQ("", GetFakeLogBuf()) << "y = " << y;
+    if (log_) {
+      ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint()) << "y = " << y;
+    } else {
+      ASSERT_EQ("", GetFakeLogPrint());
+    }
+    ASSERT_EQ(0x10000U, exidx_->cfa()) << "y = " << y;
+    ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+  }
+
+  // 11xxxyyy: Spare (xxx != 000, 001, 010)
+  for (size_t x = 3; x < 8; x++) {
+    for (size_t y = 0; y < 8; y++) {
+      ResetLogs();
+      data_->push_back(0xc0 | (x << 3) | y);
+      ASSERT_FALSE(exidx_->Decode()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ("", GetFakeLogBuf()) << "x, y = " << x << ", " << y;
+      if (log_) {
+        ASSERT_EQ("4 unwind Spare\n", GetFakeLogPrint()) << "x, y = " << x << ", " << y;
+      } else {
+        ASSERT_EQ("", GetFakeLogPrint());
+      }
+      ASSERT_EQ(0x10000U, exidx_->cfa()) << "x, y = " << x << ", " << y;
+      ASSERT_EQ(ARM_STATUS_SPARE, exidx_->status());
+    }
+  }
+}
+
+TEST_P(ArmExidxDecodeTest, pop_registers_under_mask) {
+  // 10110001 0000iiii: Pop integer registers {r0, r1, r2, r3}
+  data_->push_back(0xb1);
+  data_->push_back(0x01);
+  process_memory_.SetData32(0x10000, 0x45);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r0}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+  ASSERT_EQ(0x45U, (*exidx_->regs())[0]);
+
+  ResetLogs();
+  data_->push_back(0xb1);
+  data_->push_back(0x0a);
+  process_memory_.SetData32(0x10004, 0x23);
+  process_memory_.SetData32(0x10008, 0x24);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r1, r3}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1000cU, exidx_->cfa());
+  ASSERT_EQ(0x23U, (*exidx_->regs())[1]);
+  ASSERT_EQ(0x24U, (*exidx_->regs())[3]);
+
+  ResetLogs();
+  data_->push_back(0xb1);
+  data_->push_back(0x0f);
+  process_memory_.SetData32(0x1000c, 0x65);
+  process_memory_.SetData32(0x10010, 0x54);
+  process_memory_.SetData32(0x10014, 0x43);
+  process_memory_.SetData32(0x10018, 0x32);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r0, r1, r2, r3}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1001cU, exidx_->cfa());
+  ASSERT_EQ(0x65U, (*exidx_->regs())[0]);
+  ASSERT_EQ(0x54U, (*exidx_->regs())[1]);
+  ASSERT_EQ(0x43U, (*exidx_->regs())[2]);
+  ASSERT_EQ(0x32U, (*exidx_->regs())[3]);
+}
+
+TEST_P(ArmExidxDecodeTest, vsp_large_incr) {
+  // 10110010 uleb128: vsp = vsp + 0x204 + (uleb128 << 2)
+  data_->push_back(0xb2);
+  data_->push_back(0x7f);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 1024\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10400U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xb2);
+  data_->push_back(0xff);
+  data_->push_back(0x02);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 2048\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10c00U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xb2);
+  data_->push_back(0xff);
+  data_->push_back(0x82);
+  data_->push_back(0x30);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 3147776\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x311400U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_vfp_fstmfdx) {
+  // 10110011 sssscccc: Pop VFP double precision registers D[ssss]-D[ssss+cccc] by FSTMFDX
+  data_->push_back(0xb3);
+  data_->push_back(0x00);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d0}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1000cU, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xb3);
+  data_->push_back(0x48);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d4-d12}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10058U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_vfp8_fstmfdx) {
+  // 10111nnn: Pop VFP double precision registers D[8]-D[8+nnn] by FSTMFDX
+  data_->push_back(0xb8);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1000cU, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xbb);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8-d11}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10030U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xbf);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8-d15}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10074U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_mmx_wr10) {
+  // 11000nnn: Intel Wireless MMX pop wR[10]-wR[10+nnn] (nnn != 6, 7)
+  data_->push_back(0xc0);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR10}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc2);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR10-wR12}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10020U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc5);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR10-wR15}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10050U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_mmx_wr) {
+  // 11000110 sssscccc: Intel Wireless MMX pop wR[ssss]-wR[ssss+cccc]
+  data_->push_back(0xc6);
+  data_->push_back(0x00);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR0}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc6);
+  data_->push_back(0x25);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR2-wR7}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10038U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc6);
+  data_->push_back(0xff);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wR15-wR30}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x100b8U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_mmx_wcgr) {
+  // 11000111 0000iiii: Intel Wireless MMX pop wCGR registes {wCGR0,1,2,3}
+  data_->push_back(0xc7);
+  data_->push_back(0x01);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wCGR0}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc7);
+  data_->push_back(0x0a);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wCGR1, wCGR3}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1000cU, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc7);
+  data_->push_back(0x0f);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {wCGR0, wCGR1, wCGR2, wCGR3}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x1001cU, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_vfp16_vpush) {
+  // 11001000 sssscccc: Pop VFP double precision registers d[16+ssss]-D[16+ssss+cccc] by VPUSH
+  data_->push_back(0xc8);
+  data_->push_back(0x00);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d16}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc8);
+  data_->push_back(0x14);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d17-d21}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10030U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc8);
+  data_->push_back(0xff);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d31-d46}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x100b0U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_vfp_vpush) {
+  // 11001001 sssscccc: Pop VFP double precision registers d[ssss]-D[ssss+cccc] by VPUSH
+  data_->push_back(0xc9);
+  data_->push_back(0x00);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d0}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc9);
+  data_->push_back(0x23);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d2-d5}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10028U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xc9);
+  data_->push_back(0xff);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d15-d30}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x100a8U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, pop_vfp8_vpush) {
+  // 11010nnn: Pop VFP double precision registers D[8]-D[8+nnn] by VPUSH
+  data_->push_back(0xd0);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10008U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xd2);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8-d10}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10020U, exidx_->cfa());
+
+  ResetLogs();
+  data_->push_back(0xd7);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_FALSE(exidx_->pc_set());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {d8-d15}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10060U, exidx_->cfa());
+}
+
+TEST_P(ArmExidxDecodeTest, expect_truncated) {
+  // This test verifies that any op that requires extra ops will
+  // fail if the data is not present.
+  data_->push_back(0x80);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xb1);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xb2);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xb3);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xc6);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xc7);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xc8);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+
+  data_->clear();
+  data_->push_back(0xc9);
+  ASSERT_FALSE(exidx_->Decode());
+  ASSERT_EQ(ARM_STATUS_TRUNCATED, exidx_->status());
+}
+
+TEST_P(ArmExidxDecodeTest, verify_no_truncated) {
+  // This test verifies that no pattern results in a crash or truncation.
+  MemoryFakeAlwaysReadZero memory_zero;
+  Init(&memory_zero);
+
+  for (size_t x = 0; x < 256; x++) {
+    if (x == 0xb2) {
+      // This opcode is followed by an uleb128, so just skip this one.
+      continue;
+    }
+    for (size_t y = 0; y < 256; y++) {
+      data_->clear();
+      data_->push_back(x);
+      data_->push_back(y);
+      if (!exidx_->Decode()) {
+        ASSERT_NE(ARM_STATUS_TRUNCATED, exidx_->status())
+            << "x y = 0x" << std::hex << x << " 0x" << y;
+        ASSERT_NE(ARM_STATUS_READ_FAILED, exidx_->status())
+            << "x y = 0x" << std::hex << x << " 0x" << y;
+      }
+    }
+  }
+}
+
+TEST_P(ArmExidxDecodeTest, eval_multiple_decodes) {
+  // vsp = vsp + 4
+  data_->push_back(0x00);
+  // vsp = vsp + 8
+  data_->push_back(0x02);
+  // Finish
+  data_->push_back(0xb0);
+
+  ASSERT_TRUE(exidx_->Eval());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 4\n"
+              "4 unwind vsp = vsp + 12\n"
+              "4 unwind finish\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10010U, exidx_->cfa());
+  ASSERT_FALSE(exidx_->pc_set());
+}
+
+TEST_P(ArmExidxDecodeTest, eval_pc_set) {
+  // vsp = vsp + 4
+  data_->push_back(0x00);
+  // vsp = vsp + 8
+  data_->push_back(0x02);
+  // Pop {r15}
+  data_->push_back(0x88);
+  data_->push_back(0x00);
+  // vsp = vsp + 8
+  data_->push_back(0x02);
+  // Finish
+  data_->push_back(0xb0);
+
+  process_memory_.SetData32(0x10010, 0x10);
+
+  ASSERT_TRUE(exidx_->Eval());
+  if (log_) {
+    ASSERT_EQ("4 unwind vsp = vsp + 4\n"
+              "4 unwind vsp = vsp + 12\n"
+              "4 unwind pop {r15}\n"
+              "4 unwind vsp = vsp + 12\n"
+              "4 unwind finish\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10020U, exidx_->cfa());
+  ASSERT_TRUE(exidx_->pc_set());
+  ASSERT_EQ(0x10U, (*exidx_->regs())[15]);
+}
+
+INSTANTIATE_TEST_CASE_P(, ArmExidxDecodeTest, ::testing::Values("logging", "no_logging"));
diff --git a/libunwindstack/tests/ArmExidxExtractTest.cpp b/libunwindstack/tests/ArmExidxExtractTest.cpp
new file mode 100644
index 0000000..aed75bf
--- /dev/null
+++ b/libunwindstack/tests/ArmExidxExtractTest.cpp
@@ -0,0 +1,331 @@
+/*
+ * 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 <deque>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "ArmExidx.h"
+#include "Log.h"
+
+#include "LogFake.h"
+#include "MemoryFake.h"
+
+class ArmExidxExtractTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    elf_memory_.Clear();
+    exidx_ = new ArmExidx(nullptr, &elf_memory_, nullptr);
+    data_ = exidx_->data();
+    data_->clear();
+  }
+
+  void TearDown() override {
+    delete exidx_;
+  }
+
+  ArmExidx* exidx_ = nullptr;
+  std::deque<uint8_t>* data_;
+  MemoryFake elf_memory_;
+};
+
+TEST_F(ArmExidxExtractTest, bad_alignment) {
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x1001));
+  ASSERT_EQ(ARM_STATUS_INVALID_ALIGNMENT, exidx_->status());
+  ASSERT_TRUE(data_->empty());
+}
+
+TEST_F(ArmExidxExtractTest, cant_unwind) {
+  elf_memory_.SetData32(0x1000, 0x7fff2340);
+  elf_memory_.SetData32(0x1004, 1);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x1000));
+  ASSERT_EQ(ARM_STATUS_NO_UNWIND, exidx_->status());
+  ASSERT_TRUE(data_->empty());
+}
+
+TEST_F(ArmExidxExtractTest, compact) {
+  elf_memory_.SetData32(0x4000, 0x7ffa3000);
+  elf_memory_.SetData32(0x4004, 0x80a8b0b0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x4000));
+  ASSERT_EQ(3U, data_->size());
+  ASSERT_EQ(0xa8, data_->at(0));
+  ASSERT_EQ(0xb0, data_->at(1));
+  ASSERT_EQ(0xb0, data_->at(2));
+
+  // Missing finish gets added.
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x534, 0x7ffa3000);
+  elf_memory_.SetData32(0x538, 0x80a1a2a3);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x534));
+  ASSERT_EQ(4U, data_->size());
+  ASSERT_EQ(0xa1, data_->at(0));
+  ASSERT_EQ(0xa2, data_->at(1));
+  ASSERT_EQ(0xa3, data_->at(2));
+  ASSERT_EQ(0xb0, data_->at(3));
+}
+
+TEST_F(ArmExidxExtractTest, compact_non_zero_personality) {
+  elf_memory_.SetData32(0x4000, 0x7ffa3000);
+
+  uint32_t compact_value = 0x80a8b0b0;
+  for (size_t i = 1; i < 16; i++) {
+    elf_memory_.SetData32(0x4004, compact_value | (i << 24));
+    ASSERT_FALSE(exidx_->ExtractEntryData(0x4000));
+    ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+  }
+}
+
+TEST_F(ArmExidxExtractTest, second_read_compact_personality_1_2) {
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x8100f3b0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(2U, data_->size());
+  ASSERT_EQ(0xf3, data_->at(0));
+  ASSERT_EQ(0xb0, data_->at(1));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x8200f3f4);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(3U, data_->size());
+  ASSERT_EQ(0xf3, data_->at(0));
+  ASSERT_EQ(0xf4, data_->at(1));
+  ASSERT_EQ(0xb0, data_->at(2));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x8201f3f4);
+  elf_memory_.SetData32(0x6238, 0x102030b0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(6U, data_->size());
+  ASSERT_EQ(0xf3, data_->at(0));
+  ASSERT_EQ(0xf4, data_->at(1));
+  ASSERT_EQ(0x10, data_->at(2));
+  ASSERT_EQ(0x20, data_->at(3));
+  ASSERT_EQ(0x30, data_->at(4));
+  ASSERT_EQ(0xb0, data_->at(5));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x8103f3f4);
+  elf_memory_.SetData32(0x6238, 0x10203040);
+  elf_memory_.SetData32(0x623c, 0x50607080);
+  elf_memory_.SetData32(0x6240, 0x90a0c0d0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(15U, data_->size());
+  ASSERT_EQ(0xf3, data_->at(0));
+  ASSERT_EQ(0xf4, data_->at(1));
+  ASSERT_EQ(0x10, data_->at(2));
+  ASSERT_EQ(0x20, data_->at(3));
+  ASSERT_EQ(0x30, data_->at(4));
+  ASSERT_EQ(0x40, data_->at(5));
+  ASSERT_EQ(0x50, data_->at(6));
+  ASSERT_EQ(0x60, data_->at(7));
+  ASSERT_EQ(0x70, data_->at(8));
+  ASSERT_EQ(0x80, data_->at(9));
+  ASSERT_EQ(0x90, data_->at(10));
+  ASSERT_EQ(0xa0, data_->at(11));
+  ASSERT_EQ(0xc0, data_->at(12));
+  ASSERT_EQ(0xd0, data_->at(13));
+  ASSERT_EQ(0xb0, data_->at(14));
+}
+
+TEST_F(ArmExidxExtractTest, second_read_compact_personality_illegal) {
+  elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData32(0x5004, 0x1230);
+  elf_memory_.SetData32(0x6234, 0x832132b0);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData32(0x5004, 0x1230);
+  elf_memory_.SetData32(0x6234, 0x842132b0);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, second_read_offset_is_negative) {
+  elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData32(0x5004, 0x7fffb1e0);
+  elf_memory_.SetData32(0x1e4, 0x842132b0);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, second_read_not_compact) {
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x1);
+  elf_memory_.SetData32(0x6238, 0x001122b0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(3U, data_->size());
+  ASSERT_EQ(0x11, data_->at(0));
+  ASSERT_EQ(0x22, data_->at(1));
+  ASSERT_EQ(0xb0, data_->at(2));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x2);
+  elf_memory_.SetData32(0x6238, 0x00112233);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(4U, data_->size());
+  ASSERT_EQ(0x11, data_->at(0));
+  ASSERT_EQ(0x22, data_->at(1));
+  ASSERT_EQ(0x33, data_->at(2));
+  ASSERT_EQ(0xb0, data_->at(3));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x3);
+  elf_memory_.SetData32(0x6238, 0x01112233);
+  elf_memory_.SetData32(0x623c, 0x445566b0);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(7U, data_->size());
+  ASSERT_EQ(0x11, data_->at(0));
+  ASSERT_EQ(0x22, data_->at(1));
+  ASSERT_EQ(0x33, data_->at(2));
+  ASSERT_EQ(0x44, data_->at(3));
+  ASSERT_EQ(0x55, data_->at(4));
+  ASSERT_EQ(0x66, data_->at(5));
+  ASSERT_EQ(0xb0, data_->at(6));
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x3);
+  elf_memory_.SetData32(0x6238, 0x05112233);
+  elf_memory_.SetData32(0x623c, 0x01020304);
+  elf_memory_.SetData32(0x6240, 0x05060708);
+  elf_memory_.SetData32(0x6244, 0x090a0b0c);
+  elf_memory_.SetData32(0x6248, 0x0d0e0f10);
+  elf_memory_.SetData32(0x624c, 0x11121314);
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(24U, data_->size());
+  ASSERT_EQ(0x11, data_->at(0));
+  ASSERT_EQ(0x22, data_->at(1));
+  ASSERT_EQ(0x33, data_->at(2));
+  ASSERT_EQ(0x01, data_->at(3));
+  ASSERT_EQ(0x02, data_->at(4));
+  ASSERT_EQ(0x03, data_->at(5));
+  ASSERT_EQ(0x04, data_->at(6));
+  ASSERT_EQ(0x05, data_->at(7));
+  ASSERT_EQ(0x06, data_->at(8));
+  ASSERT_EQ(0x07, data_->at(9));
+  ASSERT_EQ(0x08, data_->at(10));
+  ASSERT_EQ(0x09, data_->at(11));
+  ASSERT_EQ(0x0a, data_->at(12));
+  ASSERT_EQ(0x0b, data_->at(13));
+  ASSERT_EQ(0x0c, data_->at(14));
+  ASSERT_EQ(0x0d, data_->at(15));
+  ASSERT_EQ(0x0e, data_->at(16));
+  ASSERT_EQ(0x0f, data_->at(17));
+  ASSERT_EQ(0x10, data_->at(18));
+  ASSERT_EQ(0x11, data_->at(19));
+  ASSERT_EQ(0x12, data_->at(20));
+  ASSERT_EQ(0x13, data_->at(21));
+  ASSERT_EQ(0x14, data_->at(22));
+  ASSERT_EQ(0xb0, data_->at(23));
+}
+
+TEST_F(ArmExidxExtractTest, read_failures) {
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData32(0x5000, 0x100);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData32(0x5004, 0x100);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData32(0x5104, 0x1);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData32(0x5108, 0x01010203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, malformed) {
+  elf_memory_.SetData32(0x5000, 0x100);
+  elf_memory_.SetData32(0x5004, 0x100);
+  elf_memory_.SetData32(0x5104, 0x1);
+  elf_memory_.SetData32(0x5108, 0x06010203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
+
+  elf_memory_.Clear();
+  elf_memory_.SetData32(0x5000, 0x100);
+  elf_memory_.SetData32(0x5004, 0x100);
+  elf_memory_.SetData32(0x5104, 0x1);
+  elf_memory_.SetData32(0x5108, 0x81060203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, cant_unwind_log) {
+  elf_memory_.SetData32(0x1000, 0x7fff2340);
+  elf_memory_.SetData32(0x1004, 1);
+
+  exidx_->set_log(true);
+  exidx_->set_log_indent(0);
+  exidx_->set_log_skip_execution(false);
+
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x1000));
+  ASSERT_EQ(ARM_STATUS_NO_UNWIND, exidx_->status());
+
+  ASSERT_EQ("4 unwind Raw Data: 0x00 0x00 0x00 0x01\n"
+            "4 unwind [cantunwind]\n", GetFakeLogPrint());
+}
+
+TEST_F(ArmExidxExtractTest, raw_data_compact) {
+  elf_memory_.SetData32(0x4000, 0x7ffa3000);
+  elf_memory_.SetData32(0x4004, 0x80a8b0b0);
+
+  exidx_->set_log(true);
+  exidx_->set_log_indent(0);
+  exidx_->set_log_skip_execution(false);
+
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x4000));
+  ASSERT_EQ("4 unwind Raw Data: 0xa8 0xb0 0xb0\n", GetFakeLogPrint());
+}
+
+TEST_F(ArmExidxExtractTest, raw_data_non_compact) {
+  elf_memory_.SetData32(0x5000, 0x1234);
+  elf_memory_.SetData32(0x5004, 0x00001230);
+  elf_memory_.SetData32(0x6234, 0x2);
+  elf_memory_.SetData32(0x6238, 0x00112233);
+
+  exidx_->set_log(true);
+  exidx_->set_log_indent(0);
+  exidx_->set_log_skip_execution(false);
+
+  ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ("4 unwind Raw Data: 0x11 0x22 0x33 0xb0\n", GetFakeLogPrint());
+}
diff --git a/libunwindstack/tests/ElfInterfaceArmTest.cpp b/libunwindstack/tests/ElfInterfaceArmTest.cpp
new file mode 100644
index 0000000..67c9a6b
--- /dev/null
+++ b/libunwindstack/tests/ElfInterfaceArmTest.cpp
@@ -0,0 +1,372 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include <vector>
+
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Regs.h"
+
+#include "MemoryFake.h"
+
+class ElfInterfaceArmTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_.Clear();
+    process_memory_.Clear();
+  }
+
+  MemoryFake memory_;
+  MemoryFake process_memory_;
+};
+
+TEST_F(ElfInterfaceArmTest, GetPrel32Addr) {
+  ElfInterfaceArm interface(&memory_);
+  memory_.SetData32(0x1000, 0x230000);
+
+  uint32_t value;
+  ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+  ASSERT_EQ(0x231000U, value);
+
+  memory_.SetData32(0x1000, 0x80001000);
+  ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+  ASSERT_EQ(0x2000U, value);
+
+  memory_.SetData32(0x1000, 0x70001000);
+  ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+  ASSERT_EQ(0xf0002000U, value);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_start_zero) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0);
+  interface.set_total_entries(10);
+
+  uint64_t entry_offset;
+  ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_no_entries) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x100);
+  interface.set_total_entries(0);
+
+  uint64_t entry_offset;
+  ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_no_valid_memory) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x100);
+  interface.set_total_entries(2);
+
+  uint64_t entry_offset;
+  ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_ip_before_first) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(1);
+  memory_.SetData32(0x1000, 0x6000);
+
+  uint64_t entry_offset;
+  ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_single_entry_negative_value) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x8000);
+  interface.set_total_entries(1);
+  memory_.SetData32(0x8000, 0x7fffff00);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x7ff0, &entry_offset));
+  ASSERT_EQ(0x8000U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_two_entries) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(2);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1008, 0x7000);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x7000, &entry_offset));
+  ASSERT_EQ(0x1000U, entry_offset);
+}
+
+
+TEST_F(ElfInterfaceArmTest, FindEntry_last_check_single_entry) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(1);
+  memory_.SetData32(0x1000, 0x6000);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x7000, &entry_offset));
+  ASSERT_EQ(0x1000U, entry_offset);
+
+  // To guarantee that we are using the cache on the second run,
+  // set the memory to a different value.
+  memory_.SetData32(0x1000, 0x8000);
+  ASSERT_TRUE(interface.FindEntry(0x7004, &entry_offset));
+  ASSERT_EQ(0x1000U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_last_check_multiple_entries) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(2);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1008, 0x8000);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x9008, &entry_offset));
+  ASSERT_EQ(0x1008U, entry_offset);
+
+  // To guarantee that we are using the cache on the second run,
+  // set the memory to a different value.
+  memory_.SetData32(0x1000, 0x16000);
+  memory_.SetData32(0x1008, 0x18000);
+  ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+  ASSERT_EQ(0x1008U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_multiple_entries_even) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(4);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1008, 0x7000);
+  memory_.SetData32(0x1010, 0x8000);
+  memory_.SetData32(0x1018, 0x9000);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+  ASSERT_EQ(0x1010U, entry_offset);
+
+  // To guarantee that we are using the cache on the second run,
+  // set the memory to a different value.
+  memory_.SetData32(0x1000, 0x16000);
+  memory_.SetData32(0x1008, 0x17000);
+  memory_.SetData32(0x1010, 0x18000);
+  memory_.SetData32(0x1018, 0x19000);
+  ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+  ASSERT_EQ(0x1010U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_multiple_entries_odd) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(5);
+  memory_.SetData32(0x1000, 0x5000);
+  memory_.SetData32(0x1008, 0x6000);
+  memory_.SetData32(0x1010, 0x7000);
+  memory_.SetData32(0x1018, 0x8000);
+  memory_.SetData32(0x1020, 0x9000);
+
+  uint64_t entry_offset;
+  ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
+  ASSERT_EQ(0x1010U, entry_offset);
+
+  // To guarantee that we are using the cache on the second run,
+  // set the memory to a different value.
+  memory_.SetData32(0x1000, 0x15000);
+  memory_.SetData32(0x1008, 0x16000);
+  memory_.SetData32(0x1010, 0x17000);
+  memory_.SetData32(0x1018, 0x18000);
+  memory_.SetData32(0x1020, 0x19000);
+  ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
+  ASSERT_EQ(0x1010U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, iterate) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(5);
+  memory_.SetData32(0x1000, 0x5000);
+  memory_.SetData32(0x1008, 0x6000);
+  memory_.SetData32(0x1010, 0x7000);
+  memory_.SetData32(0x1018, 0x8000);
+  memory_.SetData32(0x1020, 0x9000);
+
+  std::vector<uint32_t> entries;
+  for (auto addr : interface) {
+    entries.push_back(addr);
+  }
+  ASSERT_EQ(5U, entries.size());
+  ASSERT_EQ(0x6000U, entries[0]);
+  ASSERT_EQ(0x7008U, entries[1]);
+  ASSERT_EQ(0x8010U, entries[2]);
+  ASSERT_EQ(0x9018U, entries[3]);
+  ASSERT_EQ(0xa020U, entries[4]);
+
+  // Make sure the iterate cached the entries.
+  memory_.SetData32(0x1000, 0x11000);
+  memory_.SetData32(0x1008, 0x12000);
+  memory_.SetData32(0x1010, 0x13000);
+  memory_.SetData32(0x1018, 0x14000);
+  memory_.SetData32(0x1020, 0x15000);
+
+  entries.clear();
+  for (auto addr : interface) {
+    entries.push_back(addr);
+  }
+  ASSERT_EQ(5U, entries.size());
+  ASSERT_EQ(0x6000U, entries[0]);
+  ASSERT_EQ(0x7008U, entries[1]);
+  ASSERT_EQ(0x8010U, entries[2]);
+  ASSERT_EQ(0x9018U, entries[3]);
+  ASSERT_EQ(0xa020U, entries[4]);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_load_bias) {
+  ElfInterfaceArm interface(&memory_);
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(2);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1008, 0x8000);
+
+  uint64_t entry_offset;
+  interface.set_load_bias(0x2000);
+  ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+  ASSERT_FALSE(interface.FindEntry(0x8000, &entry_offset));
+  ASSERT_FALSE(interface.FindEntry(0x8fff, &entry_offset));
+  ASSERT_TRUE(interface.FindEntry(0x9000, &entry_offset));
+  ASSERT_EQ(0x1000U, entry_offset);
+  ASSERT_TRUE(interface.FindEntry(0xb007, &entry_offset));
+  ASSERT_EQ(0x1000U, entry_offset);
+  ASSERT_TRUE(interface.FindEntry(0xb008, &entry_offset));
+  ASSERT_EQ(0x1008U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, HandleType_not_arm_exidx) {
+  ElfInterfaceArm interface(&memory_);
+
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_NULL));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_LOAD));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_DYNAMIC));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_INTERP));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_NOTE));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_SHLIB));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_PHDR));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_TLS));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_LOOS));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_HIOS));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_LOPROC));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_HIPROC));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_GNU_EH_FRAME));
+  ASSERT_FALSE(interface.HandleType(0x1000, PT_GNU_STACK));
+}
+
+TEST_F(ElfInterfaceArmTest, HandleType_arm_exidx) {
+  ElfInterfaceArm interface(&memory_);
+
+  Elf32_Phdr phdr;
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(100);
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0xa00;
+
+  // Verify that if reads fail, we don't set the values but still get true.
+  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+  ASSERT_EQ(0x1000U, interface.start_offset());
+  ASSERT_EQ(100U, interface.total_entries());
+
+  // Verify that if the second read fails, we still don't set the values.
+  memory_.SetData32(
+      0x1000 + reinterpret_cast<uint64_t>(&phdr.p_vaddr) - reinterpret_cast<uint64_t>(&phdr),
+      phdr.p_vaddr);
+  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+  ASSERT_EQ(0x1000U, interface.start_offset());
+  ASSERT_EQ(100U, interface.total_entries());
+
+  // Everything is correct and present.
+  memory_.SetData32(
+      0x1000 + reinterpret_cast<uint64_t>(&phdr.p_memsz) - reinterpret_cast<uint64_t>(&phdr),
+      phdr.p_memsz);
+  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+  ASSERT_EQ(0x2000U, interface.start_offset());
+  ASSERT_EQ(320U, interface.total_entries());
+
+  // Non-zero load bias.
+  interface.set_load_bias(0x1000);
+  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+  ASSERT_EQ(0x1000U, interface.start_offset());
+  ASSERT_EQ(320U, interface.total_entries());
+}
+
+TEST_F(ElfInterfaceArmTest, StepExidx) {
+  ElfInterfaceArm interface(&memory_);
+
+  // FindEntry fails.
+  ASSERT_FALSE(interface.StepExidx(0x7000, nullptr, nullptr));
+
+  // ExtractEntry should fail.
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(2);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1008, 0x8000);
+
+  RegsArm regs;
+  regs[ARM_REG_SP] = 0x1000;
+  regs[ARM_REG_LR] = 0x20000;
+  regs.set_sp(regs[ARM_REG_SP]);
+  regs.set_pc(0x1234);
+  ASSERT_FALSE(interface.StepExidx(0x7000, &regs, &process_memory_));
+
+  // Eval should fail.
+  memory_.SetData32(0x1004, 0x81000000);
+  ASSERT_FALSE(interface.StepExidx(0x7000, &regs, &process_memory_));
+
+  // Everything should pass.
+  memory_.SetData32(0x1004, 0x80b0b0b0);
+  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_));
+  ASSERT_EQ(0x1000U, regs.sp());
+  ASSERT_EQ(0x1000U, regs[ARM_REG_SP]);
+  ASSERT_EQ(0x20000U, regs.pc());
+  ASSERT_EQ(0x20000U, regs[ARM_REG_PC]);
+}
+
+TEST_F(ElfInterfaceArmTest, StepExidx_pc_set) {
+  ElfInterfaceArm interface(&memory_);
+
+  interface.set_start_offset(0x1000);
+  interface.set_total_entries(2);
+  memory_.SetData32(0x1000, 0x6000);
+  memory_.SetData32(0x1004, 0x808800b0);
+  memory_.SetData32(0x1008, 0x8000);
+  process_memory_.SetData32(0x10000, 0x10);
+
+  RegsArm regs;
+  regs[ARM_REG_SP] = 0x10000;
+  regs[ARM_REG_LR] = 0x20000;
+  regs.set_sp(regs[ARM_REG_SP]);
+  regs.set_pc(0x1234);
+
+  // Everything should pass.
+  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_));
+  ASSERT_EQ(0x10004U, regs.sp());
+  ASSERT_EQ(0x10004U, regs[ARM_REG_SP]);
+  ASSERT_EQ(0x10U, regs.pc());
+  ASSERT_EQ(0x10U, regs[ARM_REG_PC]);
+}
diff --git a/libunwindstack/tests/ElfInterfaceTest.cpp b/libunwindstack/tests/ElfInterfaceTest.cpp
new file mode 100644
index 0000000..c31903d
--- /dev/null
+++ b/libunwindstack/tests/ElfInterfaceTest.cpp
@@ -0,0 +1,573 @@
+/*
+ * 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 <memory>
+
+#include <gtest/gtest.h>
+
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+
+#include "MemoryFake.h"
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+class ElfInterfaceTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_.Clear();
+  }
+
+  void SetStringMemory(uint64_t offset, const char* string) {
+    memory_.SetMemory(offset, string, strlen(string) + 1);
+  }
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void SinglePtLoad();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void MultipleExecutablePtLoads();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void NonExecutablePtLoads();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void ManyPhdrs();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void Soname();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void SonameAfterDtNull();
+
+  template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+  void SonameSize();
+
+  MemoryFake memory_;
+};
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SinglePtLoad() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  ASSERT_TRUE(elf->Init());
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+  ASSERT_EQ(1U, pt_loads.size());
+  LoadInfo load_data = pt_loads.at(0);
+  ASSERT_EQ(0U, load_data.offset);
+  ASSERT_EQ(0x2000U, load_data.table_offset);
+  ASSERT_EQ(0x10000U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_single_pt_load) {
+  SinglePtLoad<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_single_pt_load) {
+  SinglePtLoad<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::MultipleExecutablePtLoads() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 3;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x1000;
+  phdr.p_vaddr = 0x2001;
+  phdr.p_memsz = 0x10001;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1001;
+  memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x2000;
+  phdr.p_vaddr = 0x2002;
+  phdr.p_memsz = 0x10002;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1002;
+  memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
+
+  ASSERT_TRUE(elf->Init());
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+  ASSERT_EQ(3U, pt_loads.size());
+
+  LoadInfo load_data = pt_loads.at(0);
+  ASSERT_EQ(0U, load_data.offset);
+  ASSERT_EQ(0x2000U, load_data.table_offset);
+  ASSERT_EQ(0x10000U, load_data.table_size);
+
+  load_data = pt_loads.at(0x1000);
+  ASSERT_EQ(0x1000U, load_data.offset);
+  ASSERT_EQ(0x2001U, load_data.table_offset);
+  ASSERT_EQ(0x10001U, load_data.table_size);
+
+  load_data = pt_loads.at(0x2000);
+  ASSERT_EQ(0x2000U, load_data.offset);
+  ASSERT_EQ(0x2002U, load_data.table_offset);
+  ASSERT_EQ(0x10002U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads) {
+  MultipleExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads) {
+  MultipleExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 3;
+  ehdr.e_phentsize = sizeof(Phdr) + 100;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x1000;
+  phdr.p_vaddr = 0x2001;
+  phdr.p_memsz = 0x10001;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1001;
+  memory_.SetMemory(0x100 + sizeof(phdr) + 100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x2000;
+  phdr.p_vaddr = 0x2002;
+  phdr.p_memsz = 0x10002;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1002;
+  memory_.SetMemory(0x100 + 2 * (sizeof(phdr) + 100), &phdr, sizeof(phdr));
+
+  ASSERT_TRUE(elf->Init());
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+  ASSERT_EQ(3U, pt_loads.size());
+
+  LoadInfo load_data = pt_loads.at(0);
+  ASSERT_EQ(0U, load_data.offset);
+  ASSERT_EQ(0x2000U, load_data.table_offset);
+  ASSERT_EQ(0x10000U, load_data.table_size);
+
+  load_data = pt_loads.at(0x1000);
+  ASSERT_EQ(0x1000U, load_data.offset);
+  ASSERT_EQ(0x2001U, load_data.table_offset);
+  ASSERT_EQ(0x10001U, load_data.table_size);
+
+  load_data = pt_loads.at(0x2000);
+  ASSERT_EQ(0x2000U, load_data.offset);
+  ASSERT_EQ(0x2002U, load_data.table_offset);
+  ASSERT_EQ(0x10002U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+  MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn,
+                                                   ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+  MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn,
+                                                   ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::NonExecutablePtLoads() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 3;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x1000;
+  phdr.p_vaddr = 0x2001;
+  phdr.p_memsz = 0x10001;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1001;
+  memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x2000;
+  phdr.p_vaddr = 0x2002;
+  phdr.p_memsz = 0x10002;
+  phdr.p_flags = PF_R;
+  phdr.p_align = 0x1002;
+  memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
+
+  ASSERT_TRUE(elf->Init());
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+  ASSERT_EQ(1U, pt_loads.size());
+
+  LoadInfo load_data = pt_loads.at(0x1000);
+  ASSERT_EQ(0x1000U, load_data.offset);
+  ASSERT_EQ(0x2001U, load_data.table_offset);
+  ASSERT_EQ(0x10001U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_non_executable_pt_loads) {
+  NonExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_non_executable_pt_loads) {
+  NonExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::ManyPhdrs() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 7;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  uint64_t phdr_offset = 0x100;
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_GNU_EH_FRAME;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_DYNAMIC;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_INTERP;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_NOTE;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_SHLIB;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_GNU_EH_FRAME;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  ASSERT_TRUE(elf->Init());
+
+  const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+  ASSERT_EQ(1U, pt_loads.size());
+
+  LoadInfo load_data = pt_loads.at(0);
+  ASSERT_EQ(0U, load_data.offset);
+  ASSERT_EQ(0x2000U, load_data.table_offset);
+  ASSERT_EQ(0x10000U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_many_phdrs) {
+  ElfInterfaceTest::ManyPhdrs<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_many_phdrs) {
+  ElfInterfaceTest::ManyPhdrs<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+TEST_F(ElfInterfaceTest, elf32_arm) {
+  ElfInterfaceArm elf_arm(&memory_);
+
+  Elf32_Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Elf32_Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Elf32_Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_ARM_EXIDX;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 16;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  // Add arm exidx entries.
+  memory_.SetData32(0x2000, 0x1000);
+  memory_.SetData32(0x2008, 0x1000);
+
+  ASSERT_TRUE(elf_arm.Init());
+
+  std::vector<uint32_t> entries;
+  for (auto addr : elf_arm) {
+    entries.push_back(addr);
+  }
+  ASSERT_EQ(2U, entries.size());
+  ASSERT_EQ(0x3000U, entries[0]);
+  ASSERT_EQ(0x3008U, entries[1]);
+
+  ASSERT_EQ(0x2000U, elf_arm.start_offset());
+  ASSERT_EQ(2U, elf_arm.total_entries());
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::Soname() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_DYNAMIC;
+  phdr.p_offset = 0x2000;
+  phdr.p_memsz = sizeof(Dyn) * 3;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  uint64_t offset = 0x2000;
+  Dyn dyn;
+
+  dyn.d_tag = DT_STRTAB;
+  dyn.d_un.d_ptr = 0x10000;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_STRSZ;
+  dyn.d_un.d_val = 0x1000;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_SONAME;
+  dyn.d_un.d_val = 0x10;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_NULL;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+
+  SetStringMemory(0x10010, "fake_soname.so");
+
+  ASSERT_TRUE(elf->Init());
+  std::string name;
+  ASSERT_TRUE(elf->GetSoname(&name));
+  ASSERT_STREQ("fake_soname.so", name.c_str());
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname) {
+  Soname<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname) {
+  Soname<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SonameAfterDtNull() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_DYNAMIC;
+  phdr.p_offset = 0x2000;
+  phdr.p_memsz = sizeof(Dyn) * 3;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  Dyn dyn;
+  uint64_t offset = 0x2000;
+
+  dyn.d_tag = DT_STRTAB;
+  dyn.d_un.d_ptr = 0x10000;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_STRSZ;
+  dyn.d_un.d_val = 0x1000;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_NULL;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_SONAME;
+  dyn.d_un.d_val = 0x10;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  SetStringMemory(0x10010, "fake_soname.so");
+
+  ASSERT_TRUE(elf->Init());
+  std::string name;
+  ASSERT_FALSE(elf->GetSoname(&name));
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname_after_dt_null) {
+  SonameAfterDtNull<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname_after_dt_null) {
+  SonameAfterDtNull<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SonameSize() {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_DYNAMIC;
+  phdr.p_offset = 0x2000;
+  phdr.p_memsz = sizeof(Dyn);
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  Dyn dyn;
+  uint64_t offset = 0x2000;
+
+  dyn.d_tag = DT_STRTAB;
+  dyn.d_un.d_ptr = 0x10000;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_STRSZ;
+  dyn.d_un.d_val = 0x10;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_SONAME;
+  dyn.d_un.d_val = 0x10;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+  offset += sizeof(dyn);
+
+  dyn.d_tag = DT_NULL;
+  memory_.SetMemory(offset, &dyn, sizeof(dyn));
+
+  SetStringMemory(0x10010, "fake_soname.so");
+
+  ASSERT_TRUE(elf->Init());
+  std::string name;
+  ASSERT_FALSE(elf->GetSoname(&name));
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname_size) {
+  SonameSize<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname_size) {
+  SonameSize<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
new file mode 100644
index 0000000..25fec8e
--- /dev/null
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -0,0 +1,210 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include "Elf.h"
+
+#include "MemoryFake.h"
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+class ElfTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_ = new MemoryFake;
+  }
+
+  template <typename Ehdr>
+  void InitEhdr(Ehdr* ehdr) {
+    memset(ehdr, 0, sizeof(Ehdr));
+    memcpy(&ehdr->e_ident[0], ELFMAG, SELFMAG);
+    ehdr->e_ident[EI_DATA] = ELFDATA2LSB;
+    ehdr->e_ident[EI_VERSION] = EV_CURRENT;
+    ehdr->e_ident[EI_OSABI] = ELFOSABI_SYSV;
+  }
+
+  void InitElf32(uint32_t type) {
+    Elf32_Ehdr ehdr;
+
+    InitEhdr<Elf32_Ehdr>(&ehdr);
+    ehdr.e_ident[EI_CLASS] = ELFCLASS32;
+
+    ehdr.e_type = ET_DYN;
+    ehdr.e_machine = type;
+    ehdr.e_version = EV_CURRENT;
+    ehdr.e_entry = 0;
+    ehdr.e_phoff = 0x100;
+    ehdr.e_shoff = 0;
+    ehdr.e_flags = 0;
+    ehdr.e_ehsize = sizeof(ehdr);
+    ehdr.e_phentsize = sizeof(Elf32_Phdr);
+    ehdr.e_phnum = 1;
+    ehdr.e_shentsize = sizeof(Elf32_Shdr);
+    ehdr.e_shnum = 0;
+    ehdr.e_shstrndx = 0;
+    if (type == EM_ARM) {
+      ehdr.e_flags = 0x5000200;
+      ehdr.e_phnum = 2;
+    }
+    memory_->SetMemory(0, &ehdr, sizeof(ehdr));
+
+    Elf32_Phdr phdr;
+    memset(&phdr, 0, sizeof(phdr));
+    phdr.p_type = PT_LOAD;
+    phdr.p_offset = 0;
+    phdr.p_vaddr = 0;
+    phdr.p_paddr = 0;
+    phdr.p_filesz = 0x10000;
+    phdr.p_memsz = 0x10000;
+    phdr.p_flags = PF_R | PF_X;
+    phdr.p_align = 0x1000;
+    memory_->SetMemory(0x100, &phdr, sizeof(phdr));
+
+    if (type == EM_ARM) {
+      memset(&phdr, 0, sizeof(phdr));
+      phdr.p_type = PT_ARM_EXIDX;
+      phdr.p_offset = 0x30000;
+      phdr.p_vaddr = 0x30000;
+      phdr.p_paddr = 0x30000;
+      phdr.p_filesz = 16;
+      phdr.p_memsz = 16;
+      phdr.p_flags = PF_R;
+      phdr.p_align = 0x4;
+      memory_->SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+    }
+  }
+
+  void InitElf64(uint32_t type) {
+    Elf64_Ehdr ehdr;
+
+    InitEhdr<Elf64_Ehdr>(&ehdr);
+    ehdr.e_ident[EI_CLASS] = ELFCLASS64;
+
+    ehdr.e_type = ET_DYN;
+    ehdr.e_machine = type;
+    ehdr.e_version = EV_CURRENT;
+    ehdr.e_entry = 0;
+    ehdr.e_phoff = 0x100;
+    ehdr.e_shoff = 0;
+    ehdr.e_flags = 0x5000200;
+    ehdr.e_ehsize = sizeof(ehdr);
+    ehdr.e_phentsize = sizeof(Elf64_Phdr);
+    ehdr.e_phnum = 1;
+    ehdr.e_shentsize = sizeof(Elf64_Shdr);
+    ehdr.e_shnum = 0;
+    ehdr.e_shstrndx = 0;
+    memory_->SetMemory(0, &ehdr, sizeof(ehdr));
+
+    Elf64_Phdr phdr;
+    memset(&phdr, 0, sizeof(phdr));
+    phdr.p_type = PT_LOAD;
+    phdr.p_offset = 0;
+    phdr.p_vaddr = 0;
+    phdr.p_paddr = 0;
+    phdr.p_filesz = 0x10000;
+    phdr.p_memsz = 0x10000;
+    phdr.p_flags = PF_R | PF_X;
+    phdr.p_align = 0x1000;
+    memory_->SetMemory(0x100, &phdr, sizeof(phdr));
+  }
+
+  MemoryFake* memory_;
+};
+
+TEST_F(ElfTest, invalid_memory) {
+  Elf elf(memory_);
+
+  ASSERT_FALSE(elf.Init());
+  ASSERT_FALSE(elf.valid());
+}
+
+TEST_F(ElfTest, elf_invalid) {
+  Elf elf(memory_);
+
+  InitElf32(EM_386);
+
+  // Corrupt the ELF signature.
+  memory_->SetData32(0, 0x7f000000);
+
+  ASSERT_FALSE(elf.Init());
+  ASSERT_FALSE(elf.valid());
+  ASSERT_TRUE(elf.interface() == nullptr);
+
+  std::string name;
+  ASSERT_FALSE(elf.GetSoname(&name));
+
+  uint64_t func_offset;
+  ASSERT_FALSE(elf.GetFunctionName(0, &name, &func_offset));
+
+  ASSERT_FALSE(elf.Step(0, nullptr, nullptr));
+}
+
+TEST_F(ElfTest, elf_arm) {
+  Elf elf(memory_);
+
+  InitElf32(EM_ARM);
+
+  ASSERT_TRUE(elf.Init());
+  ASSERT_TRUE(elf.valid());
+  ASSERT_EQ(static_cast<uint32_t>(EM_ARM), elf.machine_type());
+  ASSERT_EQ(ELFCLASS32, elf.class_type());
+  ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_x86) {
+  Elf elf(memory_);
+
+  InitElf32(EM_386);
+
+  ASSERT_TRUE(elf.Init());
+  ASSERT_TRUE(elf.valid());
+  ASSERT_EQ(static_cast<uint32_t>(EM_386), elf.machine_type());
+  ASSERT_EQ(ELFCLASS32, elf.class_type());
+  ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_arm64) {
+  Elf elf(memory_);
+
+  InitElf64(EM_AARCH64);
+
+  ASSERT_TRUE(elf.Init());
+  ASSERT_TRUE(elf.valid());
+  ASSERT_EQ(static_cast<uint32_t>(EM_AARCH64), elf.machine_type());
+  ASSERT_EQ(ELFCLASS64, elf.class_type());
+  ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_x86_64) {
+  Elf elf(memory_);
+
+  InitElf64(EM_X86_64);
+
+  ASSERT_TRUE(elf.Init());
+  ASSERT_TRUE(elf.valid());
+  ASSERT_EQ(static_cast<uint32_t>(EM_X86_64), elf.machine_type());
+  ASSERT_EQ(ELFCLASS64, elf.class_type());
+  ASSERT_TRUE(elf.interface() != nullptr);
+}
diff --git a/libunwindstack/tests/LogFake.cpp b/libunwindstack/tests/LogFake.cpp
new file mode 100644
index 0000000..411594a
--- /dev/null
+++ b/libunwindstack/tests/LogFake.cpp
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <stdarg.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+#include <log/log.h>
+
+#include "LogFake.h"
+
+// Forward declarations.
+class Backtrace;
+struct EventTagMap;
+struct AndroidLogEntry;
+
+std::string g_fake_log_buf;
+
+std::string g_fake_log_print;
+
+void ResetLogs() {
+  g_fake_log_buf = "";
+  g_fake_log_print = "";
+}
+
+std::string GetFakeLogBuf() {
+  return g_fake_log_buf;
+}
+
+std::string GetFakeLogPrint() {
+  return g_fake_log_print;
+}
+
+extern "C" int __android_log_buf_write(int bufId, int prio, const char* tag, const char* msg) {
+  g_fake_log_buf += std::to_string(bufId) + ' ' + std::to_string(prio) + ' ';
+  g_fake_log_buf += tag;
+  g_fake_log_buf += ' ';
+  g_fake_log_buf += msg;
+  return 1;
+}
+
+extern "C" int __android_log_print(int prio, const char* tag, const char* fmt, ...) {
+  va_list ap;
+  va_start(ap, fmt);
+  int val = __android_log_vprint(prio, tag, fmt, ap);
+  va_end(ap);
+
+  return val;
+}
+
+extern "C" int __android_log_vprint(int prio, const char* tag, const char* fmt, va_list ap) {
+  g_fake_log_print += std::to_string(prio) + ' ';
+  g_fake_log_print += tag;
+  g_fake_log_print += ' ';
+
+  android::base::StringAppendV(&g_fake_log_print, fmt, ap);
+
+  g_fake_log_print += '\n';
+
+  return 1;
+}
+
+extern "C" log_id_t android_name_to_log_id(const char*) {
+  return LOG_ID_SYSTEM;
+}
+
+extern "C" struct logger_list* android_logger_list_open(log_id_t, int, unsigned int, pid_t) {
+  errno = EACCES;
+  return nullptr;
+}
+
+extern "C" int android_logger_list_read(struct logger_list*, struct log_msg*) {
+  return 0;
+}
+
+extern "C" EventTagMap* android_openEventTagMap(const char*) {
+  return nullptr;
+}
+
+extern "C" int android_log_processBinaryLogBuffer(
+    struct logger_entry*,
+    AndroidLogEntry*, const EventTagMap*, char*, int) {
+  return 0;
+}
+
+extern "C" void android_logger_list_free(struct logger_list*) {
+}
diff --git a/libunwindstack/tests/LogFake.h b/libunwindstack/tests/LogFake.h
new file mode 100644
index 0000000..006d393
--- /dev/null
+++ b/libunwindstack/tests/LogFake.h
@@ -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.
+ */
+
+#ifndef _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
+#define _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
+
+#include <string>
+
+void ResetLogs();
+std::string GetFakeLogBuf();
+std::string GetFakeLogPrint();
+
+#endif  // _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
diff --git a/libunwindstack/tests/MemoryFake.cpp b/libunwindstack/tests/MemoryFake.cpp
new file mode 100644
index 0000000..afb1029
--- /dev/null
+++ b/libunwindstack/tests/MemoryFake.cpp
@@ -0,0 +1,46 @@
+/*
+ * 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 <stdio.h>
+#include <stdlib.h>
+
+#include "MemoryFake.h"
+
+void MemoryFake::SetMemory(uint64_t addr, const void* memory, size_t length) {
+  const uint8_t* src = reinterpret_cast<const uint8_t*>(memory);
+  for (size_t i = 0; i < length; i++, addr++) {
+    auto value = data_.find(addr);
+    if (value != data_.end()) {
+      value->second = src[i];
+    } else {
+      data_.insert({ addr, src[i] });
+    }
+  }
+}
+
+bool MemoryFake::Read(uint64_t addr, void* memory, size_t size) {
+  uint8_t* dst = reinterpret_cast<uint8_t*>(memory);
+  for (size_t i = 0; i < size; i++, addr++) {
+    auto value = data_.find(addr);
+    if (value == data_.end()) {
+      return false;
+    }
+    dst[i] = value->second;
+  }
+  return true;
+}
diff --git a/libunwindstack/tests/MemoryFake.h b/libunwindstack/tests/MemoryFake.h
new file mode 100644
index 0000000..e05736b
--- /dev/null
+++ b/libunwindstack/tests/MemoryFake.h
@@ -0,0 +1,78 @@
+/*
+ * 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_TESTS_MEMORY_FAKE_H
+#define _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+#include <unordered_map>
+
+#include "Memory.h"
+
+class MemoryFake : public Memory {
+ public:
+  MemoryFake() = default;
+  virtual ~MemoryFake() = default;
+
+  bool Read(uint64_t addr, void* buffer, size_t size) override;
+
+  void SetMemory(uint64_t addr, const void* memory, size_t length);
+
+  void SetData8(uint64_t addr, uint8_t value) {
+    SetMemory(addr, &value, sizeof(value));
+  }
+
+  void SetData16(uint64_t addr, uint16_t value) {
+    SetMemory(addr, &value, sizeof(value));
+  }
+
+  void SetData32(uint64_t addr, uint32_t value) {
+    SetMemory(addr, &value, sizeof(value));
+  }
+
+  void SetData64(uint64_t addr, uint64_t value) {
+    SetMemory(addr, &value, sizeof(value));
+  }
+
+  void SetMemory(uint64_t addr, std::vector<uint8_t> values) {
+    SetMemory(addr, values.data(), values.size());
+  }
+
+  void SetMemory(uint64_t addr, std::string string) {
+    SetMemory(addr, string.c_str(), string.size() + 1);
+  }
+
+  void Clear() { data_.clear(); }
+
+ private:
+  std::unordered_map<uint64_t, uint8_t> data_;
+};
+
+class MemoryFakeAlwaysReadZero : public Memory {
+ public:
+  MemoryFakeAlwaysReadZero() = default;
+  virtual ~MemoryFakeAlwaysReadZero() = default;
+
+  bool Read(uint64_t, void* buffer, size_t size) override {
+    memset(buffer, 0, size);
+    return true;
+  }
+};
+
+#endif  // _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
diff --git a/libunwindstack/tests/MemoryFileTest.cpp b/libunwindstack/tests/MemoryFileTest.cpp
new file mode 100644
index 0000000..870ca19
--- /dev/null
+++ b/libunwindstack/tests/MemoryFileTest.cpp
@@ -0,0 +1,274 @@
+/*
+ * 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 <android-base/test_utils.h>
+#include <android-base/file.h>
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+class MemoryFileTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    tf_ = new TemporaryFile;
+  }
+
+  void TearDown() override {
+    delete tf_;
+  }
+
+  void WriteTestData() {
+    ASSERT_TRUE(android::base::WriteStringToFd("0123456789abcdefghijklmnopqrstuvxyz", tf_->fd));
+  }
+
+  MemoryFileAtOffset memory_;
+
+  TemporaryFile* tf_ = nullptr;
+};
+
+TEST_F(MemoryFileTest, offset_0) {
+  WriteTestData();
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 0));
+  std::vector<char> buffer(11);
+  ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
+  buffer[10] = '\0';
+  ASSERT_STREQ("0123456789", buffer.data());
+}
+
+TEST_F(MemoryFileTest, offset_non_zero) {
+  WriteTestData();
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 10));
+  std::vector<char> buffer(11);
+  ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
+  buffer[10] = '\0';
+  ASSERT_STREQ("abcdefghij", buffer.data());
+}
+
+TEST_F(MemoryFileTest, offset_non_zero_larger_than_pagesize) {
+  size_t pagesize = getpagesize();
+  std::string large_string;
+  for (size_t i = 0; i < pagesize; i++) {
+    large_string += '1';
+  }
+  large_string += "012345678901234abcdefgh";
+  ASSERT_TRUE(android::base::WriteStringToFd(large_string, tf_->fd));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, pagesize + 15));
+  std::vector<char> buffer(9);
+  ASSERT_TRUE(memory_.Read(0, buffer.data(), 8));
+  buffer[8] = '\0';
+  ASSERT_STREQ("abcdefgh", buffer.data());
+}
+
+TEST_F(MemoryFileTest, offset_pagesize_aligned) {
+  size_t pagesize = getpagesize();
+  std::string data;
+  for (size_t i = 0; i < 2 * pagesize; i++) {
+    data += static_cast<char>((i / pagesize) + '0');
+    data += static_cast<char>((i % 10) + '0');
+  }
+  ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 2 * pagesize));
+  std::vector<char> buffer(11);
+  ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
+  buffer[10] = '\0';
+  std::string expected_str;
+  for (size_t i = 0; i < 5; i++) {
+    expected_str += '1';
+    expected_str += static_cast<char>(((i + pagesize) % 10) + '0');
+  }
+  ASSERT_STREQ(expected_str.c_str(), buffer.data());
+}
+
+TEST_F(MemoryFileTest, offset_pagesize_aligned_plus_extra) {
+  size_t pagesize = getpagesize();
+  std::string data;
+  for (size_t i = 0; i < 2 * pagesize; i++) {
+    data += static_cast<char>((i / pagesize) + '0');
+    data += static_cast<char>((i % 10) + '0');
+  }
+  ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 2 * pagesize + 10));
+  std::vector<char> buffer(11);
+  ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
+  buffer[10] = '\0';
+  std::string expected_str;
+  for (size_t i = 0; i < 5; i++) {
+    expected_str += '1';
+    expected_str += static_cast<char>(((i + pagesize + 5) % 10) + '0');
+  }
+  ASSERT_STREQ(expected_str.c_str(), buffer.data());
+}
+
+TEST_F(MemoryFileTest, read_error) {
+  std::string data;
+  for (size_t i = 0; i < 5000; i++) {
+    data += static_cast<char>((i % 10) + '0');
+  }
+  ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
+  std::vector<char> buffer(100);
+
+  // Read before init.
+  ASSERT_FALSE(memory_.Read(0, buffer.data(), 10));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 0));
+
+  ASSERT_FALSE(memory_.Read(10000, buffer.data(), 10));
+  ASSERT_FALSE(memory_.Read(5000, buffer.data(), 10));
+  ASSERT_FALSE(memory_.Read(4990, buffer.data(), 11));
+  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));
+}
+
+TEST_F(MemoryFileTest, read_past_file_within_mapping) {
+  size_t pagesize = getpagesize();
+
+  ASSERT_TRUE(pagesize > 100);
+  std::vector<uint8_t> buffer(pagesize - 100);
+  for (size_t i = 0; i < pagesize - 100; i++) {
+    buffer[i] = static_cast<uint8_t>((i % 0x5e) + 0x20);
+  }
+  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 0));
+
+  for (size_t i = 0; i < 100; i++) {
+    uint8_t value;
+    ASSERT_FALSE(memory_.Read(buffer.size() + i, &value, 1)) << "Should have failed at value " << i;
+  }
+}
+
+TEST_F(MemoryFileTest, map_partial_offset_aligned) {
+  size_t pagesize = getpagesize();
+  std::vector<uint8_t> buffer(pagesize * 10);
+  for (size_t i = 0; i < pagesize * 10; i++) {
+    buffer[i] = i / pagesize + 1;
+  }
+  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+  // Map in only two pages of the data, and after the first page.
+  ASSERT_TRUE(memory_.Init(tf_->path, pagesize, pagesize * 2));
+
+  std::vector<uint8_t> read_buffer(pagesize * 2);
+  // Make sure that reading after mapped data is a failure.
+  ASSERT_FALSE(memory_.Read(pagesize * 2, read_buffer.data(), 1));
+  ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 2));
+  for (size_t i = 0; i < pagesize; i++) {
+    ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+  }
+  for (size_t i = pagesize; i < pagesize * 2; i++) {
+    ASSERT_EQ(3, read_buffer[i]) << "Failed at byte " << i;
+  }
+}
+
+TEST_F(MemoryFileTest, map_partial_offset_unaligned) {
+  size_t pagesize = getpagesize();
+  ASSERT_TRUE(pagesize > 0x100);
+  std::vector<uint8_t> buffer(pagesize * 10);
+  for (size_t i = 0; i < buffer.size(); i++) {
+    buffer[i] = i / pagesize + 1;
+  }
+  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+  // Map in only two pages of the data, and after the first page.
+  ASSERT_TRUE(memory_.Init(tf_->path, pagesize + 0x100, pagesize * 2));
+
+  std::vector<uint8_t> read_buffer(pagesize * 2);
+  // Make sure that reading after mapped data is a failure.
+  ASSERT_FALSE(memory_.Read(pagesize * 2, read_buffer.data(), 1));
+  ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 2));
+  for (size_t i = 0; i < pagesize - 0x100; i++) {
+    ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+  }
+  for (size_t i = pagesize - 0x100; i < 2 * pagesize - 0x100; i++) {
+    ASSERT_EQ(3, read_buffer[i]) << "Failed at byte " << i;
+  }
+  for (size_t i = 2 * pagesize - 0x100; i < pagesize * 2; i++) {
+    ASSERT_EQ(4, read_buffer[i]) << "Failed at byte " << i;
+  }
+}
+
+TEST_F(MemoryFileTest, map_overflow) {
+  size_t pagesize = getpagesize();
+  ASSERT_TRUE(pagesize > 0x100);
+  std::vector<uint8_t> buffer(pagesize * 10);
+  for (size_t i = 0; i < buffer.size(); i++) {
+    buffer[i] = i / pagesize + 1;
+  }
+  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+  // Map in only two pages of the data, and after the first page.
+  ASSERT_TRUE(memory_.Init(tf_->path, pagesize + 0x100, UINT64_MAX));
+
+  std::vector<uint8_t> read_buffer(pagesize * 10);
+  ASSERT_FALSE(memory_.Read(pagesize * 9 - 0x100 + 1, read_buffer.data(), 1));
+  ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 9 - 0x100));
+}
+
+TEST_F(MemoryFileTest, init_reinit) {
+  size_t pagesize = getpagesize();
+  std::vector<uint8_t> buffer(pagesize * 2);
+  for (size_t i = 0; i < buffer.size(); i++) {
+    buffer[i] = i / pagesize + 1;
+  }
+  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+  ASSERT_TRUE(memory_.Init(tf_->path, 0));
+  std::vector<uint8_t> read_buffer(buffer.size());
+  ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize));
+  for (size_t i = 0; i < pagesize; i++) {
+    ASSERT_EQ(1, read_buffer[i]) << "Failed at byte " << i;
+  }
+
+  // Now reinit.
+  ASSERT_TRUE(memory_.Init(tf_->path, pagesize));
+  ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize));
+  for (size_t i = 0; i < pagesize; i++) {
+    ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+  }
+}
diff --git a/libunwindstack/tests/MemoryLocalTest.cpp b/libunwindstack/tests/MemoryLocalTest.cpp
new file mode 100644
index 0000000..0ba5f1c
--- /dev/null
+++ b/libunwindstack/tests/MemoryLocalTest.cpp
@@ -0,0 +1,75 @@
+/*
+ * 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 <vector>
+
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+TEST(MemoryLocalTest, read) {
+  std::vector<uint8_t> src(1024);
+  memset(src.data(), 0x4c, 1024);
+
+  MemoryLocal local;
+
+  std::vector<uint8_t> dst(1024);
+  ASSERT_TRUE(local.Read(reinterpret_cast<uint64_t>(src.data()), dst.data(), 1024));
+  ASSERT_EQ(0, memcmp(src.data(), dst.data(), 1024));
+  for (size_t i = 0; i < 1024; i++) {
+    ASSERT_EQ(0x4cU, dst[i]);
+  }
+
+  memset(src.data(), 0x23, 512);
+  ASSERT_TRUE(local.Read(reinterpret_cast<uint64_t>(src.data()), dst.data(), 1024));
+  ASSERT_EQ(0, memcmp(src.data(), dst.data(), 1024));
+  for (size_t i = 0; i < 512; i++) {
+    ASSERT_EQ(0x23U, dst[i]);
+  }
+  for (size_t i = 512; i < 1024; i++) {
+    ASSERT_EQ(0x4cU, dst[i]);
+  }
+}
+
+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;
+
+  std::vector<uint8_t> dst(100);
+  ASSERT_FALSE(local.Read(0, dst.data(), 1));
+  ASSERT_FALSE(local.Read(0, dst.data(), 100));
+}
diff --git a/libunwindstack/tests/MemoryRangeTest.cpp b/libunwindstack/tests/MemoryRangeTest.cpp
new file mode 100644
index 0000000..d636ec4
--- /dev/null
+++ b/libunwindstack/tests/MemoryRangeTest.cpp
@@ -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.
+ */
+
+#include <stdint.h>
+#include <string.h>
+
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+#include "MemoryFake.h"
+
+class MemoryRangeTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_ = new MemoryFake;
+  }
+
+  MemoryFake* memory_;
+};
+
+TEST_F(MemoryRangeTest, read) {
+  std::vector<uint8_t> src(1024);
+  memset(src.data(), 0x4c, 1024);
+  memory_->SetMemory(9001, src);
+
+  MemoryRange range(memory_, 9001, 9001 + src.size());
+
+  std::vector<uint8_t> dst(1024);
+  ASSERT_TRUE(range.Read(0, dst.data(), src.size()));
+  for (size_t i = 0; i < 1024; i++) {
+    ASSERT_EQ(0x4cU, dst[i]) << "Failed at byte " << i;
+  }
+}
+
+TEST_F(MemoryRangeTest, read_near_limit) {
+  std::vector<uint8_t> src(4096);
+  memset(src.data(), 0x4c, 4096);
+  memory_->SetMemory(1000, src);
+
+  MemoryRange range(memory_, 1000, 2024);
+
+  std::vector<uint8_t> dst(1024);
+  ASSERT_TRUE(range.Read(1020, dst.data(), 4));
+  for (size_t i = 0; i < 4; i++) {
+    ASSERT_EQ(0x4cU, dst[i]) << "Failed at byte " << i;
+  }
+
+  // Verify that reads outside of the range will fail.
+  ASSERT_FALSE(range.Read(1020, dst.data(), 5));
+  ASSERT_FALSE(range.Read(1024, dst.data(), 1));
+  ASSERT_FALSE(range.Read(1024, dst.data(), 1024));
+}
+
+TEST_F(MemoryRangeTest, read_string_past_end) {
+  std::string name("0123456789");
+  memory_->SetMemory(0, name);
+
+  // 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));
+}
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
new file mode 100644
index 0000000..7664c3e
--- /dev/null
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -0,0 +1,150 @@
+/*
+ * 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 <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/test_utils.h>
+#include <android-base/file.h>
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+class MemoryRemoteTest : public ::testing::Test {
+ protected:
+  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);
+  }
+
+  static bool Attach(pid_t pid) {
+    if (ptrace(PTRACE_ATTACH, pid, 0, 0) == -1) {
+      return false;
+    }
+
+    uint64_t start = NanoTime();
+    siginfo_t si;
+    while (TEMP_FAILURE_RETRY(ptrace(PTRACE_GETSIGINFO, pid, 0, &si)) < 0 && errno == ESRCH) {
+      if ((NanoTime() - start) > 10 * NS_PER_SEC) {
+        printf("%d: Failed to stop after 10 seconds.\n", pid);
+        return false;
+      }
+      usleep(30);
+    }
+    return true;
+  }
+
+  static bool Detach(pid_t pid) {
+    return ptrace(PTRACE_DETACH, pid, 0, 0) == 0;
+  }
+
+  static constexpr size_t NS_PER_SEC = 1000000000ULL;
+};
+
+TEST_F(MemoryRemoteTest, read) {
+  std::vector<uint8_t> src(1024);
+  memset(src.data(), 0x4c, 1024);
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true);
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+
+  ASSERT_TRUE(Attach(pid));
+
+  MemoryRemote remote(pid);
+
+  std::vector<uint8_t> dst(1024);
+  ASSERT_TRUE(remote.Read(reinterpret_cast<uint64_t>(src.data()), dst.data(), 1024));
+  for (size_t i = 0; i < 1024; i++) {
+    ASSERT_EQ(0x4cU, dst[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_TRUE(Detach(pid));
+
+  kill(pid, SIGKILL);
+}
+
+TEST_F(MemoryRemoteTest, read_fail) {
+  int pagesize = getpagesize();
+  void* src = mmap(nullptr, pagesize * 2, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,-1, 0);
+  memset(src, 0x4c, pagesize * 2);
+  ASSERT_NE(MAP_FAILED, src);
+  // Put a hole right after the first page.
+  ASSERT_EQ(0, munmap(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(src) + pagesize),
+                      pagesize));
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true);
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+
+  ASSERT_TRUE(Attach(pid));
+
+  MemoryRemote remote(pid);
+
+  std::vector<uint8_t> dst(pagesize);
+  ASSERT_TRUE(remote.Read(reinterpret_cast<uint64_t>(src), dst.data(), pagesize));
+  for (size_t i = 0; i < 1024; i++) {
+    ASSERT_EQ(0x4cU, dst[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_FALSE(remote.Read(reinterpret_cast<uint64_t>(src) + pagesize, dst.data(), 1));
+  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));
+
+  ASSERT_EQ(0, munmap(src, pagesize));
+
+  ASSERT_TRUE(Detach(pid));
+
+  kill(pid, SIGKILL);
+}
+
+TEST_F(MemoryRemoteTest, read_illegal) {
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true);
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+
+  ASSERT_TRUE(Attach(pid));
+
+  MemoryRemote remote(pid);
+
+  std::vector<uint8_t> dst(100);
+  ASSERT_FALSE(remote.Read(0, dst.data(), 1));
+  ASSERT_FALSE(remote.Read(0, dst.data(), 100));
+
+  ASSERT_TRUE(Detach(pid));
+
+  kill(pid, SIGKILL);
+}
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
new file mode 100644
index 0000000..0dac278
--- /dev/null
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -0,0 +1,266 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "MapInfo.h"
+#include "Regs.h"
+
+#include "MemoryFake.h"
+
+class ElfFake : public Elf {
+ public:
+  ElfFake(Memory* memory) : Elf(memory) { valid_ = true; }
+  virtual ~ElfFake() = default;
+
+  void set_elf_interface(ElfInterface* interface) { interface_.reset(interface); }
+};
+
+class ElfInterfaceFake : public ElfInterface {
+ public:
+  ElfInterfaceFake(Memory* memory) : ElfInterface(memory) {}
+  virtual ~ElfInterfaceFake() = default;
+
+  void set_load_bias(uint64_t load_bias) { load_bias_ = load_bias; }
+
+  bool Init() override { return false; }
+  void InitHeaders() override {}
+  bool GetSoname(std::string*) override { return false; }
+  bool GetFunctionName(uint64_t, std::string*, uint64_t*) override { return false; }
+  bool Step(uint64_t, Regs*, Memory*) override { return false; }
+};
+
+template <typename TypeParam>
+class RegsTestTmpl : public RegsTmpl<TypeParam> {
+ public:
+  RegsTestTmpl(uint16_t total_regs, uint16_t regs_sp)
+      : RegsTmpl<TypeParam>(total_regs, regs_sp, Regs::Location(Regs::LOCATION_UNKNOWN, 0)) {}
+  RegsTestTmpl(uint16_t total_regs, uint16_t regs_sp, Regs::Location return_loc)
+      : RegsTmpl<TypeParam>(total_regs, regs_sp, return_loc) {}
+  virtual ~RegsTestTmpl() = default;
+
+  uint64_t GetAdjustedPc(uint64_t, Elf*) { return 0; }
+};
+
+class RegsTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_ = new MemoryFake;
+    elf_.reset(new ElfFake(memory_));
+    elf_interface_ = new ElfInterfaceFake(elf_->memory());
+    elf_->set_elf_interface(elf_interface_);
+  }
+
+  template <typename AddressType>
+  void regs_rel_pc();
+
+  template <typename AddressType>
+  void regs_return_address_register();
+
+  ElfInterfaceFake* elf_interface_;
+  MemoryFake* memory_;
+  std::unique_ptr<ElfFake> elf_;
+};
+
+TEST_F(RegsTest, regs32) {
+  RegsTestTmpl<uint32_t> regs32(50, 10);
+  ASSERT_EQ(50U, regs32.total_regs());
+  ASSERT_EQ(10U, regs32.sp_reg());
+
+  uint32_t* raw = reinterpret_cast<uint32_t*>(regs32.RawData());
+  for (size_t i = 0; i < 50; i++) {
+    raw[i] = 0xf0000000 + i;
+  }
+  regs32.set_pc(0xf0120340);
+  regs32.set_sp(0xa0ab0cd0);
+
+  for (size_t i = 0; i < 50; i++) {
+    ASSERT_EQ(0xf0000000U + i, regs32[i]) << "Failed comparing register " << i;
+  }
+
+  ASSERT_EQ(0xf0120340U, regs32.pc());
+  ASSERT_EQ(0xa0ab0cd0U, regs32.sp());
+
+  regs32[32] = 10;
+  ASSERT_EQ(10U, regs32[32]);
+}
+
+TEST_F(RegsTest, regs64) {
+  RegsTestTmpl<uint64_t> regs64(30, 12);
+  ASSERT_EQ(30U, regs64.total_regs());
+  ASSERT_EQ(12U, regs64.sp_reg());
+
+  uint64_t* raw = reinterpret_cast<uint64_t*>(regs64.RawData());
+  for (size_t i = 0; i < 30; i++) {
+    raw[i] = 0xf123456780000000UL + i;
+  }
+  regs64.set_pc(0xf123456780102030UL);
+  regs64.set_sp(0xa123456780a0b0c0UL);
+
+  for (size_t i = 0; i < 30; i++) {
+    ASSERT_EQ(0xf123456780000000U + i, regs64[i]) << "Failed reading register " << i;
+  }
+
+  ASSERT_EQ(0xf123456780102030UL, regs64.pc());
+  ASSERT_EQ(0xa123456780a0b0c0UL, regs64.sp());
+
+  regs64[8] = 10;
+  ASSERT_EQ(10U, regs64[8]);
+}
+
+template <typename AddressType>
+void RegsTest::regs_rel_pc() {
+  RegsTestTmpl<AddressType> regs(30, 12);
+
+  elf_interface_->set_load_bias(0);
+  MapInfo map_info{.start = 0x1000, .end = 0x2000};
+  regs.set_pc(0x1101);
+  ASSERT_EQ(0x101U, regs.GetRelPc(elf_.get(), &map_info));
+  elf_interface_->set_load_bias(0x3000);
+  ASSERT_EQ(0x3101U, regs.GetRelPc(elf_.get(), &map_info));
+}
+
+TEST_F(RegsTest, regs32_rel_pc) {
+  regs_rel_pc<uint32_t>();
+}
+
+TEST_F(RegsTest, regs64_rel_pc) {
+  regs_rel_pc<uint64_t>();
+}
+
+template <typename AddressType>
+void RegsTest::regs_return_address_register() {
+  RegsTestTmpl<AddressType> regs(20, 10, Regs::Location(Regs::LOCATION_REGISTER, 5));
+
+  regs[5] = 0x12345;
+  uint64_t value;
+  ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+  ASSERT_EQ(0x12345U, value);
+}
+
+TEST_F(RegsTest, regs32_return_address_register) {
+  regs_return_address_register<uint32_t>();
+}
+
+TEST_F(RegsTest, regs64_return_address_register) {
+  regs_return_address_register<uint64_t>();
+}
+
+TEST_F(RegsTest, regs32_return_address_sp_offset) {
+  RegsTestTmpl<uint32_t> regs(20, 10, Regs::Location(Regs::LOCATION_SP_OFFSET, -2));
+
+  regs.set_sp(0x2002);
+  memory_->SetData32(0x2000, 0x12345678);
+  uint64_t value;
+  ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+  ASSERT_EQ(0x12345678U, value);
+}
+
+TEST_F(RegsTest, regs64_return_address_sp_offset) {
+  RegsTestTmpl<uint64_t> regs(20, 10, Regs::Location(Regs::LOCATION_SP_OFFSET, -8));
+
+  regs.set_sp(0x2008);
+  memory_->SetData64(0x2000, 0x12345678aabbccddULL);
+  uint64_t value;
+  ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+  ASSERT_EQ(0x12345678aabbccddULL, value);
+}
+
+TEST_F(RegsTest, rel_pc) {
+  RegsArm64 arm64;
+  ASSERT_EQ(0xcU, arm64.GetAdjustedPc(0x10, elf_.get()));
+  ASSERT_EQ(0x0U, arm64.GetAdjustedPc(0x4, elf_.get()));
+  ASSERT_EQ(0x3U, arm64.GetAdjustedPc(0x3, elf_.get()));
+  ASSERT_EQ(0x2U, arm64.GetAdjustedPc(0x2, elf_.get()));
+  ASSERT_EQ(0x1U, arm64.GetAdjustedPc(0x1, elf_.get()));
+  ASSERT_EQ(0x0U, arm64.GetAdjustedPc(0x0, elf_.get()));
+
+  RegsX86 x86;
+  ASSERT_EQ(0xffU,  x86.GetAdjustedPc(0x100, elf_.get()));
+  ASSERT_EQ(0x1U,  x86.GetAdjustedPc(0x2, elf_.get()));
+  ASSERT_EQ(0x0U,  x86.GetAdjustedPc(0x1, elf_.get()));
+  ASSERT_EQ(0x0U,  x86.GetAdjustedPc(0x0, elf_.get()));
+
+  RegsX86_64 x86_64;
+  ASSERT_EQ(0xffU,  x86_64.GetAdjustedPc(0x100, elf_.get()));
+  ASSERT_EQ(0x1U,  x86_64.GetAdjustedPc(0x2, elf_.get()));
+  ASSERT_EQ(0x0U,  x86_64.GetAdjustedPc(0x1, elf_.get()));
+  ASSERT_EQ(0x0U,  x86_64.GetAdjustedPc(0x0, elf_.get()));
+}
+
+TEST_F(RegsTest, rel_pc_arm) {
+  RegsArm arm;
+
+  // Check fence posts.
+  elf_interface_->set_load_bias(0);
+  ASSERT_EQ(3U,  arm.GetAdjustedPc(0x5, elf_.get()));
+  ASSERT_EQ(4U,  arm.GetAdjustedPc(0x4, elf_.get()));
+  ASSERT_EQ(3U,  arm.GetAdjustedPc(0x3, elf_.get()));
+  ASSERT_EQ(2U,  arm.GetAdjustedPc(0x2, elf_.get()));
+  ASSERT_EQ(1U,  arm.GetAdjustedPc(0x1, elf_.get()));
+  ASSERT_EQ(0U,  arm.GetAdjustedPc(0x0, elf_.get()));
+
+  elf_interface_->set_load_bias(0x100);
+  ASSERT_EQ(0xffU,  arm.GetAdjustedPc(0xff, elf_.get()));
+  ASSERT_EQ(0x103U,  arm.GetAdjustedPc(0x105, elf_.get()));
+  ASSERT_EQ(0x104U,  arm.GetAdjustedPc(0x104, elf_.get()));
+  ASSERT_EQ(0x103U,  arm.GetAdjustedPc(0x103, elf_.get()));
+  ASSERT_EQ(0x102U,  arm.GetAdjustedPc(0x102, elf_.get()));
+  ASSERT_EQ(0x101U,  arm.GetAdjustedPc(0x101, elf_.get()));
+  ASSERT_EQ(0x100U,  arm.GetAdjustedPc(0x100, elf_.get()));
+
+  // Check thumb instructions handling.
+  elf_interface_->set_load_bias(0);
+  memory_->SetData32(0x2000, 0);
+  ASSERT_EQ(0x2003U,  arm.GetAdjustedPc(0x2005, elf_.get()));
+  memory_->SetData32(0x2000, 0xe000f000);
+  ASSERT_EQ(0x2001U,  arm.GetAdjustedPc(0x2005, elf_.get()));
+
+  elf_interface_->set_load_bias(0x400);
+  memory_->SetData32(0x2100, 0);
+  ASSERT_EQ(0x2503U,  arm.GetAdjustedPc(0x2505, elf_.get()));
+  memory_->SetData32(0x2100, 0xf111f111);
+  ASSERT_EQ(0x2501U,  arm.GetAdjustedPc(0x2505, elf_.get()));
+}
+
+TEST_F(RegsTest, elf_invalid) {
+  Elf invalid_elf(new MemoryFake);
+  RegsArm regs_arm;
+  RegsArm64 regs_arm64;
+  RegsX86 regs_x86;
+  RegsX86_64 regs_x86_64;
+  MapInfo map_info{.start = 0x1000, .end = 0x2000};
+
+  regs_arm.set_pc(0x1500);
+  ASSERT_EQ(0x500U, regs_arm.GetRelPc(&invalid_elf, &map_info));
+  ASSERT_EQ(0x500U, regs_arm.GetAdjustedPc(0x500U, &invalid_elf));
+
+  regs_arm64.set_pc(0x1600);
+  ASSERT_EQ(0x600U, regs_arm64.GetRelPc(&invalid_elf, &map_info));
+  ASSERT_EQ(0x600U, regs_arm64.GetAdjustedPc(0x600U, &invalid_elf));
+
+  regs_x86.set_pc(0x1700);
+  ASSERT_EQ(0x700U, regs_x86.GetRelPc(&invalid_elf, &map_info));
+  ASSERT_EQ(0x700U, regs_x86.GetAdjustedPc(0x700U, &invalid_elf));
+
+  regs_x86_64.set_pc(0x1800);
+  ASSERT_EQ(0x800U, regs_x86_64.GetRelPc(&invalid_elf, &map_info));
+  ASSERT_EQ(0x800U, regs_x86_64.GetAdjustedPc(0x800U, &invalid_elf));
+}
diff --git a/libunwindstack/unwind_info.cpp b/libunwindstack/unwind_info.cpp
new file mode 100644
index 0000000..6f158b0
--- /dev/null
+++ b/libunwindstack/unwind_info.cpp
@@ -0,0 +1,121 @@
+/*
+ * 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 <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "ArmExidx.h"
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Log.h"
+
+void DumpArm(ElfInterfaceArm* interface) {
+  if (interface == nullptr) {
+    printf("No ARM Unwind Information.\n\n");
+    return;
+  }
+
+  printf("ARM Unwind Information:\n");
+  for (const auto& entry : interface->pt_loads()) {
+    uint64_t load_bias = entry.second.table_offset;
+    printf(" PC Range 0x%" PRIx64 " - 0x%" PRIx64 "\n", entry.second.offset + load_bias,
+           entry.second.table_size + load_bias);
+    for (auto addr : *interface) {
+      std::string name;
+      printf("  PC 0x%" PRIx64, addr + load_bias);
+      uint64_t func_offset;
+      if (interface->GetFunctionName(addr + load_bias + 1, &name, &func_offset) && !name.empty()) {
+        printf(" <%s>", name.c_str());
+      }
+      printf("\n");
+      uint64_t entry;
+      if (!interface->FindEntry(addr + load_bias, &entry)) {
+        printf("    Cannot find entry for address.\n");
+        continue;
+      }
+      ArmExidx arm(nullptr, interface->memory(), nullptr);
+      arm.set_log(true);
+      arm.set_log_skip_execution(true);
+      arm.set_log_indent(2);
+      if (!arm.ExtractEntryData(entry)) {
+        if (arm.status() != ARM_STATUS_NO_UNWIND) {
+          printf("    Error trying to extract data.\n");
+        }
+        continue;
+      }
+      if (arm.data()->size() > 0) {
+        if (!arm.Eval() && arm.status() != ARM_STATUS_NO_UNWIND) {
+          printf("      Error trying to evaluate dwarf data.\n");
+        }
+      }
+    }
+  }
+  printf("\n");
+}
+
+int main(int argc, char** argv) {
+  if (argc != 2) {
+    printf("Need to pass the name of an elf file to the program.\n");
+    return 1;
+  }
+
+  struct stat st;
+  if (stat(argv[1], &st) == -1) {
+    printf("Cannot stat %s: %s\n", argv[1], strerror(errno));
+    return 1;
+  }
+  if (!S_ISREG(st.st_mode)) {
+    printf("%s is not a regular file.\n", argv[1]);
+    return 1;
+  }
+  if (S_ISDIR(st.st_mode)) {
+    printf("%s is a directory.\n", argv[1]);
+    return 1;
+  }
+
+  // Send all log messages to stdout.
+  log_to_stdout(true);
+
+  MemoryFileAtOffset* memory = new MemoryFileAtOffset;
+  if (!memory->Init(argv[1], 0)) {
+    // Initializatation failed.
+    printf("Failed to init\n");
+    return 1;
+  }
+
+  Elf elf(memory);
+  if (!elf.Init() || !elf.valid()) {
+    printf("%s is not a valid elf file.\n", argv[1]);
+    return 1;
+  }
+
+  ElfInterface* interface = elf.interface();
+  if (elf.machine_type() == EM_ARM) {
+    DumpArm(reinterpret_cast<ElfInterfaceArm*>(interface));
+    printf("\n");
+  }
+
+  return 0;
+}
diff --git a/libusbhost/Android.mk b/libusbhost/Android.mk
index 5c12f2c..9439846 100644
--- a/libusbhost/Android.mk
+++ b/libusbhost/Android.mk
@@ -22,11 +22,11 @@
 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
@@ -35,24 +35,22 @@
 # ========================================================
 
 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/include/usbhost/usbhost.h b/libusbhost/include/usbhost/usbhost.h
new file mode 100644
index 0000000..a8dd673
--- /dev/null
+++ b/libusbhost/include/usbhost/usbhost.h
@@ -0,0 +1,247 @@
+/*
+ * 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 __USB_HOST_H
+#define __USB_HOST_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+#include <linux/version.h>
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
+#include <linux/usb/ch9.h>
+#else
+#include <linux/usb_ch9.h>
+#endif
+
+struct usb_host_context;
+struct usb_endpoint_descriptor;
+
+struct usb_descriptor_iter {
+    unsigned char*  config;
+    unsigned char*  config_end;
+    unsigned char*  curr_desc;
+};
+
+struct usb_request
+{
+    struct usb_device *dev;
+    void* buffer;
+    int buffer_length;
+    int actual_length;
+    int max_packet_size;
+    void *private_data; /* struct usbdevfs_urb* */
+    int endpoint;
+    void *client_data;  /* free for use by client */
+};
+
+/* Callback for notification when new USB devices are attached.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_device_added_cb)(const char *dev_name, void *client_data);
+
+/* Callback for notification when USB devices are removed.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_device_removed_cb)(const char *dev_name, void *client_data);
+
+/* Callback indicating that initial device discovery is done.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_discovery_done_cb)(void *client_data);
+
+/* Call this to initialize the USB host library. */
+struct usb_host_context *usb_host_init(void);
+
+/* Call this to cleanup the USB host library. */
+void usb_host_cleanup(struct usb_host_context *context);
+
+/* Call this to get the inotify file descriptor. */
+int usb_host_get_fd(struct usb_host_context *context);
+
+/* Call this to initialize the usb host context. */
+int usb_host_load(struct usb_host_context *context,
+                  usb_device_added_cb added_cb,
+                  usb_device_removed_cb removed_cb,
+                  usb_discovery_done_cb discovery_done_cb,
+                  void *client_data);
+
+/* Call this to read and handle occuring usb event. */
+int usb_host_read_event(struct usb_host_context *context);
+
+/* Call this to monitor the USB bus for new and removed devices.
+ * This is intended to be called from a dedicated thread,
+ * as it will not return until one of the callbacks returns true.
+ * added_cb will be called immediately for each existing USB device,
+ * and subsequently each time a new device is added.
+ * removed_cb is called when USB devices are removed from the bus.
+ * discovery_done_cb is called after the initial discovery of already
+ * connected devices is complete.
+ */
+void usb_host_run(struct usb_host_context *context,
+                  usb_device_added_cb added_cb,
+                  usb_device_removed_cb removed_cb,
+                  usb_discovery_done_cb discovery_done_cb,
+                  void *client_data);
+
+/* Creates a usb_device object for a USB device */
+struct usb_device *usb_device_open(const char *dev_name);
+
+/* Releases all resources associated with the USB device */
+void usb_device_close(struct usb_device *device);
+
+/* Creates a usb_device object for already open USB device */
+struct usb_device *usb_device_new(const char *dev_name, int fd);
+
+/* Returns the file descriptor for the usb_device */
+int usb_device_get_fd(struct usb_device *device);
+
+/* Returns the name for the USB device, which is the same as
+ * the dev_name passed to usb_device_open()
+ */
+const char* usb_device_get_name(struct usb_device *device);
+
+/* Returns a unique ID for the device.
+ *Currently this is generated from the dev_name path.
+ */
+int usb_device_get_unique_id(struct usb_device *device);
+
+/* Returns a unique ID for the device name.
+ * Currently this is generated from the device path.
+ */
+int usb_device_get_unique_id_from_name(const char* name);
+
+/* Returns the device name for the unique ID.
+ * Call free() to deallocate the returned string */
+char* usb_device_get_name_from_unique_id(int id);
+
+/* Returns the USB vendor ID from the device descriptor for the USB device */
+uint16_t usb_device_get_vendor_id(struct usb_device *device);
+
+/* Returns the USB product ID from the device descriptor for the USB device */
+uint16_t usb_device_get_product_id(struct usb_device *device);
+
+const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device);
+
+/* Returns a USB descriptor string for the given string ID.
+ * Used to implement usb_device_get_manufacturer_name,
+ * usb_device_get_product_name and usb_device_get_serial.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_string(struct usb_device *device, int id, int timeout);
+
+/* Returns the manufacturer name for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout);
+
+/* Returns the product name for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_product_name(struct usb_device *device, int timeout);
+
+/* Returns the version number for the USB device.
+ */
+int usb_device_get_version(struct usb_device *device);
+
+/* Returns the USB serial number for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_serial(struct usb_device *device, int timeout);
+
+/* Returns true if we have write access to the USB device,
+ * and false if we only have access to the USB device configuration.
+ */
+int usb_device_is_writeable(struct usb_device *device);
+
+/* Initializes a usb_descriptor_iter, which can be used to iterate through all
+ * the USB descriptors for a USB device.
+ */
+void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter);
+
+/* Returns the next USB descriptor for a device, or NULL if we have reached the
+ * end of the list.
+ */
+struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter);
+
+/* Claims the specified interface of a USB device */
+int usb_device_claim_interface(struct usb_device *device, unsigned int interface);
+
+/* Releases the specified interface of a USB device */
+int usb_device_release_interface(struct usb_device *device, unsigned int interface);
+
+/* Requests the kernel to connect or disconnect its driver for the specified interface.
+ * This can be used to ask the kernel to disconnect its driver for a device
+ * so usb_device_claim_interface can claim it instead.
+ */
+int usb_device_connect_kernel_driver(struct usb_device *device,
+        unsigned int interface, int connect);
+
+/* Sets the current configuration for the device to the specified configuration */
+int usb_device_set_configuration(struct usb_device *device, int configuration);
+
+/* Sets the specified interface of a USB device */
+int usb_device_set_interface(struct usb_device *device, unsigned int interface,
+                            unsigned int alt_setting);
+
+/* Sends a control message to the specified device on endpoint zero */
+int usb_device_control_transfer(struct usb_device *device,
+                            int requestType,
+                            int request,
+                            int value,
+                            int index,
+                            void* buffer,
+                            int length,
+                            unsigned int timeout);
+
+/* Reads or writes on a bulk endpoint.
+ * Returns number of bytes transferred, or negative value for error.
+ */
+int usb_device_bulk_transfer(struct usb_device *device,
+                            int endpoint,
+                            void* buffer,
+                            unsigned int length,
+                            unsigned int timeout);
+
+/** Reset USB bus for the device */
+int usb_device_reset(struct usb_device *device);
+
+/* Creates a new usb_request. */
+struct usb_request *usb_request_new(struct usb_device *dev,
+        const struct usb_endpoint_descriptor *ep_desc);
+
+/* Releases all resources associated with the request */
+void usb_request_free(struct usb_request *req);
+
+/* Submits a read or write request on the specified device */
+int usb_request_queue(struct usb_request *req);
+
+ /* Waits for the results of a previous usb_request_queue operation. timeoutMillis == -1 requests
+  * to wait forever.
+  * Returns a usb_request, or NULL for error.
+  */
+struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis);
+
+/* Cancels a pending usb_request_queue() operation. */
+int usb_request_cancel(struct usb_request *req);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __USB_HOST_H */
diff --git a/libusbhost/usbhost.c b/libusbhost/usbhost.c
index 299fdc4..7adb4f2 100644
--- a/libusbhost/usbhost.c
+++ b/libusbhost/usbhost.c
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
 // #define DEBUG 1
 #if DEBUG
 
@@ -43,6 +47,7 @@
 #include <fcntl.h>
 #include <errno.h>
 #include <ctype.h>
+#include <poll.h>
 #include <pthread.h>
 
 #include <linux/usbdevice_fs.h>
@@ -449,7 +454,7 @@
     return (struct usb_device_descriptor*)device->desc;
 }
 
-char* usb_device_get_string(struct usb_device *device, int id)
+char* usb_device_get_string(struct usb_device *device, int id, int timeout)
 {
     char string[256];
     __u16 buffer[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
@@ -465,7 +470,8 @@
     // read list of supported languages
     result = usb_device_control_transfer(device,
             USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
-            (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages), 0);
+            (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
+            timeout);
     if (result > 0)
         languageCount = (result - 2) / 2;
 
@@ -474,7 +480,8 @@
 
         result = usb_device_control_transfer(device,
                 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
-                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer), 0);
+                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer),
+                timeout);
         if (result > 0) {
             int i;
             // skip first word, and copy the rest to the string, changing shorts to bytes.
@@ -489,16 +496,16 @@
     return NULL;
 }
 
-char* usb_device_get_manufacturer_name(struct usb_device *device)
+char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
 {
     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
-    return usb_device_get_string(device, desc->iManufacturer);
+    return usb_device_get_string(device, desc->iManufacturer, timeout);
 }
 
-char* usb_device_get_product_name(struct usb_device *device)
+char* usb_device_get_product_name(struct usb_device *device, int timeout)
 {
     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
-    return usb_device_get_string(device, desc->iProduct);
+    return usb_device_get_string(device, desc->iProduct, timeout);
 }
 
 int usb_device_get_version(struct usb_device *device)
@@ -507,10 +514,10 @@
     return desc->bcdUSB;
 }
 
-char* usb_device_get_serial(struct usb_device *device)
+char* usb_device_get_serial(struct usb_device *device, int timeout)
 {
     struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
-    return usb_device_get_string(device, desc->iSerialNumber);
+    return usb_device_get_string(device, desc->iSerialNumber, timeout);
 }
 
 int usb_device_is_writeable(struct usb_device *device)
@@ -600,7 +607,7 @@
 int usb_device_bulk_transfer(struct usb_device *device,
                             int endpoint,
                             void* buffer,
-                            int length,
+                            unsigned int length,
                             unsigned int timeout)
 {
     struct usbdevfs_bulktransfer  ctrl;
@@ -681,29 +688,38 @@
     return res;
 }
 
-struct usb_request *usb_request_wait(struct usb_device *dev)
+struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
 {
-    struct usbdevfs_urb *urb = NULL;
-    struct usb_request *req = NULL;
+    // Poll until a request becomes available if there is a timeout
+    if (timeoutMillis > 0) {
+        struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
 
-    while (1) {
-        int res = ioctl(dev->fd, USBDEVFS_REAPURB, &urb);
-        D("USBDEVFS_REAPURB returned %d\n", res);
-        if (res < 0) {
-            if(errno == EINTR) {
-                continue;
-            }
-            D("[ reap urb - error ]\n");
+        int res = poll(&p, 1, timeoutMillis);
+
+        if (res != 1 || p.revents != POLLOUT) {
+            D("[ poll - event %d, error %d]\n", p.revents, errno);
             return NULL;
-        } else {
-            D("[ urb @%p status = %d, actual = %d ]\n",
-                urb, urb->status, urb->actual_length);
-            req = (struct usb_request*)urb->usercontext;
-            req->actual_length = urb->actual_length;
         }
-        break;
     }
-    return req;
+
+    // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
+    // two threads are reading usb requests at the same time and only a single request is available.
+    struct usbdevfs_urb *urb = NULL;
+    int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
+                                       USBDEVFS_REAPURBNDELAY, &urb));
+    D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
+
+    if (res < 0) {
+        D("[ reap urb - error %d]\n", errno);
+        return NULL;
+    } else {
+        D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
+
+        struct usb_request *req = (struct usb_request*)urb->usercontext;
+        req->actual_length = urb->actual_length;
+
+        return req;
+    }
 }
 
 int usb_request_cancel(struct usb_request *req)
@@ -711,4 +727,3 @@
     struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
     return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
 }
-
diff --git a/libutils/Android.bp b/libutils/Android.bp
new file mode 100644
index 0000000..5e76279
--- /dev/null
+++ b/libutils/Android.bp
@@ -0,0 +1,153 @@
+// Copyright (C) 2008 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_headers {
+    name: "libutils_headers",
+    vendor_available: true,
+    host_supported: true,
+
+    header_libs: ["libsystem_headers",],
+    export_header_lib_headers: ["libsystem_headers",],
+    export_include_dirs: ["include"],
+
+    target: {
+        android: {
+            header_libs: ["libbacktrace_headers"],
+            export_header_lib_headers: ["libbacktrace_headers"],
+        },
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
+
+cc_library {
+    name: "libutils",
+    vendor_available: true,
+    host_supported: true,
+
+    srcs: [
+        "CallStack.cpp",
+        "FileMap.cpp",
+        "JenkinsHash.cpp",
+        "Log.cpp",
+        "NativeHandle.cpp",
+        "Printer.cpp",
+        "PropertyMap.cpp",
+        "RefBase.cpp",
+        "SharedBuffer.cpp",
+        "Static.cpp",
+        "StopWatch.cpp",
+        "String8.cpp",
+        "String16.cpp",
+        "StrongPointer.cpp",
+        "SystemClock.cpp",
+        "Threads.cpp",
+        "Timers.cpp",
+        "Tokenizer.cpp",
+        "Unicode.cpp",
+        "VectorImpl.cpp",
+        "misc.cpp",
+    ],
+
+    cflags: ["-Werror"],
+    include_dirs: ["external/safe-iop/include"],
+    header_libs: [
+        "libutils_headers",
+    ],
+    export_header_lib_headers: [
+        "libutils_headers",
+    ],
+
+    arch: {
+        mips: {
+            cflags: ["-DALIGN_DOUBLE"],
+        },
+    },
+
+    target: {
+        android: {
+            srcs: [
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+                "Trace.cpp",
+            ],
+
+            cflags: ["-fvisibility=protected"],
+
+            shared_libs: [
+                "libbacktrace",
+                "libcutils",
+                "libdl",
+                "liblog",
+                "libvndksupport",
+            ],
+
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
+        },
+
+        host: {
+            cflags: ["-DLIBUTILS_NATIVE=1"],
+
+            shared: {
+                enabled: false,
+            },
+        },
+
+        linux: {
+            srcs: [
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+            ],
+        },
+        linux_bionic: {
+            enabled: true,
+            srcs: [
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+            ],
+        },
+
+        darwin: {
+            cflags: ["-Wno-unused-parameter"],
+        },
+
+        // Under MinGW, ctype.h doesn't need multi-byte support
+        windows: {
+            cflags: ["-DMB_CUR_MAX=1"],
+
+            enabled: true,
+        },
+    },
+
+    clang: true,
+}
+
+// Include subdirectory makefiles
+// ============================================================
+
+cc_test {
+    name: "SharedBufferTest",
+    host_supported: true,
+    static_libs: ["libutils"],
+    shared_libs: ["liblog"],
+    srcs: ["SharedBufferTest.cpp"],
+}
+
+subdirs = ["tests"]
diff --git a/libutils/Android.mk b/libutils/Android.mk
deleted file mode 100644
index 84bac32..0000000
--- a/libutils/Android.mk
+++ /dev/null
@@ -1,124 +0,0 @@
-# Copyright (C) 2008 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)
-
-commonSources:= \
-	CallStack.cpp \
-	FileMap.cpp \
-	JenkinsHash.cpp \
-	LinearTransform.cpp \
-	Log.cpp \
-	NativeHandle.cpp \
-	Printer.cpp \
-	PropertyMap.cpp \
-	RefBase.cpp \
-	SharedBuffer.cpp \
-	Static.cpp \
-	StopWatch.cpp \
-	String8.cpp \
-	String16.cpp \
-	SystemClock.cpp \
-	Threads.cpp \
-	Timers.cpp \
-	Tokenizer.cpp \
-	Unicode.cpp \
-	VectorImpl.cpp \
-	misc.cpp \
-
-host_commonCflags := -DLIBUTILS_NATIVE=1 $(TOOL_CFLAGS) -Werror
-
-# For the host
-# =====================================================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= $(commonSources)
-LOCAL_SRC_FILES_linux := Looper.cpp ProcessCallStack.cpp
-LOCAL_CFLAGS_darwin := -Wno-unused-parameter
-LOCAL_MODULE:= libutils
-LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS += $(host_commonCflags)
-# Under MinGW, ctype.h doesn't need multi-byte support
-LOCAL_CFLAGS_windows := -DMB_CUR_MAX=1
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_C_INCLUDES += external/safe-iop/include
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-
-# For the device, static
-# =====================================================
-include $(CLEAR_VARS)
-
-
-# we have the common sources, plus some device-specific stuff
-LOCAL_SRC_FILES:= \
-	$(commonSources) \
-	BlobCache.cpp \
-	Looper.cpp \
-	ProcessCallStack.cpp \
-	Trace.cpp
-
-ifeq ($(TARGET_ARCH),mips)
-LOCAL_CFLAGS += -DALIGN_DOUBLE
-endif
-LOCAL_CFLAGS += -Werror -fvisibility=protected
-
-LOCAL_STATIC_LIBRARIES := \
-	libcutils \
-	libc
-
-LOCAL_SHARED_LIBRARIES := \
-        libbacktrace \
-        liblog \
-        libdl
-
-LOCAL_MODULE := libutils
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-LOCAL_C_INCLUDES += external/safe-iop/include
-include $(BUILD_STATIC_LIBRARY)
-
-# For the device, shared
-# =====================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE:= libutils
-LOCAL_WHOLE_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := \
-        libbacktrace \
-        libcutils \
-        libdl \
-        liblog
-LOCAL_CFLAGS := -Werror
-LOCAL_C_INCLUDES += external/safe-iop/include
-
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := SharedBufferTest
-LOCAL_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_SRC_FILES := SharedBufferTest.cpp
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := SharedBufferTest
-LOCAL_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_SRC_FILES := SharedBufferTest.cpp
-include $(BUILD_HOST_NATIVE_TEST)
-
-# Build the tests in the tests/ subdirectory.
-include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/libutils/BlobCache.cpp b/libutils/BlobCache.cpp
deleted file mode 100644
index 126995b..0000000
--- a/libutils/BlobCache.cpp
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- ** Copyright 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.
- */
-
-#define LOG_TAG "BlobCache"
-//#define LOG_NDEBUG 0
-
-#include <inttypes.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <utils/BlobCache.h>
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include <cutils/properties.h>
-
-namespace android {
-
-// BlobCache::Header::mMagicNumber value
-static const uint32_t blobCacheMagic = ('_' << 24) + ('B' << 16) + ('b' << 8) + '$';
-
-// BlobCache::Header::mBlobCacheVersion value
-static const uint32_t blobCacheVersion = 3;
-
-// BlobCache::Header::mDeviceVersion value
-static const uint32_t blobCacheDeviceVersion = 1;
-
-BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize):
-        mMaxKeySize(maxKeySize),
-        mMaxValueSize(maxValueSize),
-        mMaxTotalSize(maxTotalSize),
-        mTotalSize(0) {
-    nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
-#ifdef _WIN32
-    srand(now);
-#else
-    mRandState[0] = (now >> 0) & 0xFFFF;
-    mRandState[1] = (now >> 16) & 0xFFFF;
-    mRandState[2] = (now >> 32) & 0xFFFF;
-#endif
-    ALOGV("initializing random seed using %lld", (unsigned long long)now);
-}
-
-void BlobCache::set(const void* key, size_t keySize, const void* value,
-        size_t valueSize) {
-    if (mMaxKeySize < keySize) {
-        ALOGV("set: not caching because the key is too large: %zu (limit: %zu)",
-                keySize, mMaxKeySize);
-        return;
-    }
-    if (mMaxValueSize < valueSize) {
-        ALOGV("set: not caching because the value is too large: %zu (limit: %zu)",
-                valueSize, mMaxValueSize);
-        return;
-    }
-    if (mMaxTotalSize < keySize + valueSize) {
-        ALOGV("set: not caching because the combined key/value size is too "
-                "large: %zu (limit: %zu)", keySize + valueSize, mMaxTotalSize);
-        return;
-    }
-    if (keySize == 0) {
-        ALOGW("set: not caching because keySize is 0");
-        return;
-    }
-    if (valueSize <= 0) {
-        ALOGW("set: not caching because valueSize is 0");
-        return;
-    }
-
-    sp<Blob> dummyKey(new Blob(key, keySize, false));
-    CacheEntry dummyEntry(dummyKey, NULL);
-
-    while (true) {
-        ssize_t index = mCacheEntries.indexOf(dummyEntry);
-        if (index < 0) {
-            // Create a new cache entry.
-            sp<Blob> keyBlob(new Blob(key, keySize, true));
-            sp<Blob> valueBlob(new Blob(value, valueSize, true));
-            size_t newTotalSize = mTotalSize + keySize + valueSize;
-            if (mMaxTotalSize < newTotalSize) {
-                if (isCleanable()) {
-                    // Clean the cache and try again.
-                    clean();
-                    continue;
-                } else {
-                    ALOGV("set: not caching new key/value pair because the "
-                            "total cache size limit would be exceeded: %zu "
-                            "(limit: %zu)",
-                            keySize + valueSize, mMaxTotalSize);
-                    break;
-                }
-            }
-            mCacheEntries.add(CacheEntry(keyBlob, valueBlob));
-            mTotalSize = newTotalSize;
-            ALOGV("set: created new cache entry with %zu byte key and %zu byte value",
-                    keySize, valueSize);
-        } else {
-            // Update the existing cache entry.
-            sp<Blob> valueBlob(new Blob(value, valueSize, true));
-            sp<Blob> oldValueBlob(mCacheEntries[index].getValue());
-            size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize();
-            if (mMaxTotalSize < newTotalSize) {
-                if (isCleanable()) {
-                    // Clean the cache and try again.
-                    clean();
-                    continue;
-                } else {
-                    ALOGV("set: not caching new value because the total cache "
-                            "size limit would be exceeded: %zu (limit: %zu)",
-                            keySize + valueSize, mMaxTotalSize);
-                    break;
-                }
-            }
-            mCacheEntries.editItemAt(index).setValue(valueBlob);
-            mTotalSize = newTotalSize;
-            ALOGV("set: updated existing cache entry with %zu byte key and %zu byte "
-                    "value", keySize, valueSize);
-        }
-        break;
-    }
-}
-
-size_t BlobCache::get(const void* key, size_t keySize, void* value,
-        size_t valueSize) {
-    if (mMaxKeySize < keySize) {
-        ALOGV("get: not searching because the key is too large: %zu (limit %zu)",
-                keySize, mMaxKeySize);
-        return 0;
-    }
-    sp<Blob> dummyKey(new Blob(key, keySize, false));
-    CacheEntry dummyEntry(dummyKey, NULL);
-    ssize_t index = mCacheEntries.indexOf(dummyEntry);
-    if (index < 0) {
-        ALOGV("get: no cache entry found for key of size %zu", keySize);
-        return 0;
-    }
-
-    // The key was found. Return the value if the caller's buffer is large
-    // enough.
-    sp<Blob> valueBlob(mCacheEntries[index].getValue());
-    size_t valueBlobSize = valueBlob->getSize();
-    if (valueBlobSize <= valueSize) {
-        ALOGV("get: copying %zu bytes to caller's buffer", valueBlobSize);
-        memcpy(value, valueBlob->getData(), valueBlobSize);
-    } else {
-        ALOGV("get: caller's buffer is too small for value: %zu (needs %zu)",
-                valueSize, valueBlobSize);
-    }
-    return valueBlobSize;
-}
-
-static inline size_t align4(size_t size) {
-    return (size + 3) & ~3;
-}
-
-size_t BlobCache::getFlattenedSize() const {
-    size_t size = align4(sizeof(Header) + PROPERTY_VALUE_MAX);
-    for (size_t i = 0; i < mCacheEntries.size(); i++) {
-        const CacheEntry& e(mCacheEntries[i]);
-        sp<Blob> keyBlob = e.getKey();
-        sp<Blob> valueBlob = e.getValue();
-        size += align4(sizeof(EntryHeader) + keyBlob->getSize() +
-                       valueBlob->getSize());
-    }
-    return size;
-}
-
-status_t BlobCache::flatten(void* buffer, size_t size) const {
-    // Write the cache header
-    if (size < sizeof(Header)) {
-        ALOGE("flatten: not enough room for cache header");
-        return BAD_VALUE;
-    }
-    Header* header = reinterpret_cast<Header*>(buffer);
-    header->mMagicNumber = blobCacheMagic;
-    header->mBlobCacheVersion = blobCacheVersion;
-    header->mDeviceVersion = blobCacheDeviceVersion;
-    header->mNumEntries = mCacheEntries.size();
-    char buildId[PROPERTY_VALUE_MAX];
-    header->mBuildIdLength = property_get("ro.build.id", buildId, "");
-    memcpy(header->mBuildId, buildId, header->mBuildIdLength);
-
-    // Write cache entries
-    uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer);
-    off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
-    for (size_t i = 0; i < mCacheEntries.size(); i++) {
-        const CacheEntry& e(mCacheEntries[i]);
-        sp<Blob> keyBlob = e.getKey();
-        sp<Blob> valueBlob = e.getValue();
-        size_t keySize = keyBlob->getSize();
-        size_t valueSize = valueBlob->getSize();
-
-        size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
-        size_t totalSize = align4(entrySize);
-        if (byteOffset + totalSize > size) {
-            ALOGE("flatten: not enough room for cache entries");
-            return BAD_VALUE;
-        }
-
-        EntryHeader* eheader = reinterpret_cast<EntryHeader*>(
-            &byteBuffer[byteOffset]);
-        eheader->mKeySize = keySize;
-        eheader->mValueSize = valueSize;
-
-        memcpy(eheader->mData, keyBlob->getData(), keySize);
-        memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize);
-
-        if (totalSize > entrySize) {
-            // We have padding bytes. Those will get written to storage, and contribute to the CRC,
-            // so make sure we zero-them to have reproducible results.
-            memset(eheader->mData + keySize + valueSize, 0, totalSize - entrySize);
-        }
-
-        byteOffset += totalSize;
-    }
-
-    return OK;
-}
-
-status_t BlobCache::unflatten(void const* buffer, size_t size) {
-    // All errors should result in the BlobCache being in an empty state.
-    mCacheEntries.clear();
-
-    // Read the cache header
-    if (size < sizeof(Header)) {
-        ALOGE("unflatten: not enough room for cache header");
-        return BAD_VALUE;
-    }
-    const Header* header = reinterpret_cast<const Header*>(buffer);
-    if (header->mMagicNumber != blobCacheMagic) {
-        ALOGE("unflatten: bad magic number: %" PRIu32, header->mMagicNumber);
-        return BAD_VALUE;
-    }
-    char buildId[PROPERTY_VALUE_MAX];
-    int len = property_get("ro.build.id", buildId, "");
-    if (header->mBlobCacheVersion != blobCacheVersion ||
-            header->mDeviceVersion != blobCacheDeviceVersion ||
-            len != header->mBuildIdLength ||
-            strncmp(buildId, header->mBuildId, len)) {
-        // We treat version mismatches as an empty cache.
-        return OK;
-    }
-
-    // Read cache entries
-    const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer);
-    off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
-    size_t numEntries = header->mNumEntries;
-    for (size_t i = 0; i < numEntries; i++) {
-        if (byteOffset + sizeof(EntryHeader) > size) {
-            mCacheEntries.clear();
-            ALOGE("unflatten: not enough room for cache entry headers");
-            return BAD_VALUE;
-        }
-
-        const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>(
-                &byteBuffer[byteOffset]);
-        size_t keySize = eheader->mKeySize;
-        size_t valueSize = eheader->mValueSize;
-        size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
-
-        size_t totalSize = align4(entrySize);
-        if (byteOffset + totalSize > size) {
-            mCacheEntries.clear();
-            ALOGE("unflatten: not enough room for cache entry headers");
-            return BAD_VALUE;
-        }
-
-        const uint8_t* data = eheader->mData;
-        set(data, keySize, data + keySize, valueSize);
-
-        byteOffset += totalSize;
-    }
-
-    return OK;
-}
-
-long int BlobCache::blob_random() {
-#ifdef _WIN32
-    return rand();
-#else
-    return nrand48(mRandState);
-#endif
-}
-
-void BlobCache::clean() {
-    // Remove a random cache entry until the total cache size gets below half
-    // the maximum total cache size.
-    while (mTotalSize > mMaxTotalSize / 2) {
-        size_t i = size_t(blob_random() % (mCacheEntries.size()));
-        const CacheEntry& entry(mCacheEntries[i]);
-        mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize();
-        mCacheEntries.removeAt(i);
-    }
-}
-
-bool BlobCache::isCleanable() const {
-    return mTotalSize > mMaxTotalSize / 2;
-}
-
-BlobCache::Blob::Blob(const void* data, size_t size, bool copyData):
-        mData(copyData ? malloc(size) : data),
-        mSize(size),
-        mOwnsData(copyData) {
-    if (data != NULL && copyData) {
-        memcpy(const_cast<void*>(mData), data, size);
-    }
-}
-
-BlobCache::Blob::~Blob() {
-    if (mOwnsData) {
-        free(const_cast<void*>(mData));
-    }
-}
-
-bool BlobCache::Blob::operator<(const Blob& rhs) const {
-    if (mSize == rhs.mSize) {
-        return memcmp(mData, rhs.mData, mSize) < 0;
-    } else {
-        return mSize < rhs.mSize;
-    }
-}
-
-const void* BlobCache::Blob::getData() const {
-    return mData;
-}
-
-size_t BlobCache::Blob::getSize() const {
-    return mSize;
-}
-
-BlobCache::CacheEntry::CacheEntry() {
-}
-
-BlobCache::CacheEntry::CacheEntry(const sp<Blob>& key, const sp<Blob>& value):
-        mKey(key),
-        mValue(value) {
-}
-
-BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce):
-        mKey(ce.mKey),
-        mValue(ce.mValue) {
-}
-
-bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const {
-    return *mKey < *rhs.mKey;
-}
-
-const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) {
-    mKey = rhs.mKey;
-    mValue = rhs.mValue;
-    return *this;
-}
-
-sp<BlobCache::Blob> BlobCache::CacheEntry::getKey() const {
-    return mKey;
-}
-
-sp<BlobCache::Blob> BlobCache::CacheEntry::getValue() const {
-    return mValue;
-}
-
-void BlobCache::CacheEntry::setValue(const sp<Blob>& value) {
-    mValue = value;
-}
-
-} // namespace android
diff --git a/libutils/CallStack.cpp b/libutils/CallStack.cpp
index 699da74..bd6015e 100644
--- a/libutils/CallStack.cpp
+++ b/libutils/CallStack.cpp
@@ -16,9 +16,10 @@
 
 #define LOG_TAG "CallStack"
 
+#include <utils/CallStack.h>
+
 #include <memory>
 
-#include <utils/CallStack.h>
 #include <utils/Printer.h>
 #include <utils/Errors.h>
 #include <utils/Log.h>
diff --git a/libutils/FileMap.cpp b/libutils/FileMap.cpp
index 4f4b889..1afa1ec 100644
--- a/libutils/FileMap.cpp
+++ b/libutils/FileMap.cpp
@@ -98,7 +98,7 @@
     }
 #if defined(__MINGW32__)
     if (mBasePtr && UnmapViewOfFile(mBasePtr) == 0) {
-        ALOGD("UnmapViewOfFile(%p) failed, error = %" PRId32 "\n", mBasePtr,
+        ALOGD("UnmapViewOfFile(%p) failed, error = %lu\n", mBasePtr,
               GetLastError() );
     }
     if (mFileMapping != INVALID_HANDLE_VALUE) {
@@ -138,7 +138,7 @@
     mFileHandle  = (HANDLE) _get_osfhandle(fd);
     mFileMapping = CreateFileMapping( mFileHandle, NULL, protect, 0, 0, NULL);
     if (mFileMapping == NULL) {
-        ALOGE("CreateFileMapping(%p, %" PRIx32 ") failed with error %" PRId32 "\n",
+        ALOGE("CreateFileMapping(%p, %lx) failed with error %lu\n",
               mFileHandle, protect, GetLastError() );
         return false;
     }
@@ -153,7 +153,7 @@
                               (DWORD)(adjOffset),
                               adjLength );
     if (mBasePtr == NULL) {
-        ALOGE("MapViewOfFile(%" PRId64 ", %zu) failed with error %" PRId32 "\n",
+        ALOGE("MapViewOfFile(%" PRId64 ", %zu) failed with error %lu\n",
               adjOffset, adjLength, GetLastError() );
         CloseHandle(mFileMapping);
         mFileMapping = INVALID_HANDLE_VALUE;
diff --git a/libutils/LinearTransform.cpp b/libutils/LinearTransform.cpp
deleted file mode 100644
index 138ce8b..0000000
--- a/libutils/LinearTransform.cpp
+++ /dev/null
@@ -1,282 +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.
- */
-
-#define __STDC_LIMIT_MACROS
-
-#include <assert.h>
-#include <stdint.h>
-
-#include <utils/LinearTransform.h>
-
-// disable sanitize as these functions may intentionally overflow (see comments below).
-// the ifdef can be removed when host builds use clang.
-#if defined(__clang__)
-#define ATTRIBUTE_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer")))
-#else
-#define ATTRIBUTE_NO_SANITIZE_INTEGER
-#endif
-
-namespace android {
-
-// sanitize failure with T = int32_t and x = 0x80000000
-template<class T>
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static inline T ABS(T x) { return (x < 0) ? -x : x; }
-
-// Static math methods involving linear transformations
-// remote sanitize failure on overflow case.
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static bool scale_u64_to_u64(
-        uint64_t val,
-        uint32_t N,
-        uint32_t D,
-        uint64_t* res,
-        bool round_up_not_down) {
-    uint64_t tmp1, tmp2;
-    uint32_t r;
-
-    assert(res);
-    assert(D);
-
-    // Let U32(X) denote a uint32_t containing the upper 32 bits of a 64 bit
-    // integer X.
-    // Let L32(X) denote a uint32_t containing the lower 32 bits of a 64 bit
-    // integer X.
-    // Let X[A, B] with A <= B denote bits A through B of the integer X.
-    // Let (A | B) denote the concatination of two 32 bit ints, A and B.
-    // IOW X = (A | B) => U32(X) == A && L32(X) == B
-    //
-    // compute M = val * N (a 96 bit int)
-    // ---------------------------------
-    // tmp2 = U32(val) * N (a 64 bit int)
-    // tmp1 = L32(val) * N (a 64 bit int)
-    // which means
-    // M = val * N = (tmp2 << 32) + tmp1
-    tmp2 = (val >> 32) * N;
-    tmp1 = (val & UINT32_MAX) * N;
-
-    // compute M[32, 95]
-    // tmp2 = tmp2 + U32(tmp1)
-    //      = (U32(val) * N) + U32(L32(val) * N)
-    //      = M[32, 95]
-    tmp2 += tmp1 >> 32;
-
-    // if M[64, 95] >= D, then M/D has bits > 63 set and we have
-    // an overflow.
-    if ((tmp2 >> 32) >= D) {
-        *res = UINT64_MAX;
-        return false;
-    }
-
-    // Divide.  Going in we know
-    // tmp2 = M[32, 95]
-    // U32(tmp2) < D
-    r = tmp2 % D;
-    tmp2 /= D;
-
-    // At this point
-    // tmp1      = L32(val) * N
-    // tmp2      = M[32, 95] / D
-    //           = (M / D)[32, 95]
-    // r         = M[32, 95] % D
-    // U32(tmp2) = 0
-    //
-    // compute tmp1 = (r | M[0, 31])
-    tmp1 = (tmp1 & UINT32_MAX) | ((uint64_t)r << 32);
-
-    // Divide again.  Keep the remainder around in order to round properly.
-    r = tmp1 % D;
-    tmp1 /= D;
-
-    // At this point
-    // tmp2      = (M / D)[32, 95]
-    // tmp1      = (M / D)[ 0, 31]
-    // r         =  M % D
-    // U32(tmp1) = 0
-    // U32(tmp2) = 0
-
-    // Pack the result and deal with the round-up case (As well as the
-    // remote possiblility over overflow in such a case).
-    *res = (tmp2 << 32) | tmp1;
-    if (r && round_up_not_down) {
-        ++(*res);
-        if (!(*res)) {
-            *res = UINT64_MAX;
-            return false;
-        }
-    }
-
-    return true;
-}
-
-// at least one known sanitize failure (see comment below)
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static bool linear_transform_s64_to_s64(
-        int64_t  val,
-        int64_t  basis1,
-        int32_t  N,
-        uint32_t D,
-        bool     invert_frac,
-        int64_t  basis2,
-        int64_t* out) {
-    uint64_t scaled, res;
-    uint64_t abs_val;
-    bool is_neg;
-
-    if (!out)
-        return false;
-
-    // Compute abs(val - basis_64). Keep track of whether or not this delta
-    // will be negative after the scale opertaion.
-    if (val < basis1) {
-        is_neg = true;
-        abs_val = basis1 - val;
-    } else {
-        is_neg = false;
-        abs_val = val - basis1;
-    }
-
-    if (N < 0)
-        is_neg = !is_neg;
-
-    if (!scale_u64_to_u64(abs_val,
-                          invert_frac ? D : ABS(N),
-                          invert_frac ? ABS(N) : D,
-                          &scaled,
-                          is_neg))
-        return false; // overflow/undeflow
-
-    // if scaled is >= 0x8000<etc>, then we are going to overflow or
-    // underflow unless ABS(basis2) is large enough to pull us back into the
-    // non-overflow/underflow region.
-    if (scaled & INT64_MIN) {
-        if (is_neg && (basis2 < 0))
-            return false; // certain underflow
-
-        if (!is_neg && (basis2 >= 0))
-            return false; // certain overflow
-
-        if (ABS(basis2) <= static_cast<int64_t>(scaled & INT64_MAX))
-            return false; // not enough
-
-        // Looks like we are OK
-        *out = (is_neg ? (-scaled) : scaled) + basis2;
-    } else {
-        // Scaled fits within signed bounds, so we just need to check for
-        // over/underflow for two signed integers.  Basically, if both scaled
-        // and basis2 have the same sign bit, and the result has a different
-        // sign bit, then we have under/overflow.  An easy way to compute this
-        // is
-        // (scaled_signbit XNOR basis_signbit) &&
-        // (scaled_signbit XOR res_signbit)
-        // ==
-        // (scaled_signbit XOR basis_signbit XOR 1) &&
-        // (scaled_signbit XOR res_signbit)
-
-        if (is_neg)
-            scaled = -scaled; // known sanitize failure
-        res = scaled + basis2;
-
-        if ((scaled ^ basis2 ^ INT64_MIN) & (scaled ^ res) & INT64_MIN)
-            return false;
-
-        *out = res;
-    }
-
-    return true;
-}
-
-bool LinearTransform::doForwardTransform(int64_t a_in, int64_t* b_out) const {
-    if (0 == a_to_b_denom)
-        return false;
-
-    return linear_transform_s64_to_s64(a_in,
-                                       a_zero,
-                                       a_to_b_numer,
-                                       a_to_b_denom,
-                                       false,
-                                       b_zero,
-                                       b_out);
-}
-
-bool LinearTransform::doReverseTransform(int64_t b_in, int64_t* a_out) const {
-    if (0 == a_to_b_numer)
-        return false;
-
-    return linear_transform_s64_to_s64(b_in,
-                                       b_zero,
-                                       a_to_b_numer,
-                                       a_to_b_denom,
-                                       true,
-                                       a_zero,
-                                       a_out);
-}
-
-template <class T> void LinearTransform::reduce(T* N, T* D) {
-    T a, b;
-    if (!N || !D || !(*D)) {
-        assert(false);
-        return;
-    }
-
-    a = *N;
-    b = *D;
-
-    if (a == 0) {
-        *D = 1;
-        return;
-    }
-
-    // This implements Euclid's method to find GCD.
-    if (a < b) {
-        T tmp = a;
-        a = b;
-        b = tmp;
-    }
-
-    while (1) {
-        // a is now the greater of the two.
-        const T remainder = a % b;
-        if (remainder == 0) {
-            *N /= b;
-            *D /= b;
-            return;
-        }
-        // by swapping remainder and b, we are guaranteeing that a is
-        // still the greater of the two upon entrance to the loop.
-        a = b;
-        b = remainder;
-    }
-};
-
-template void LinearTransform::reduce<uint64_t>(uint64_t* N, uint64_t* D);
-template void LinearTransform::reduce<uint32_t>(uint32_t* N, uint32_t* D);
-
-// sanitize failure if *N = 0x80000000
-ATTRIBUTE_NO_SANITIZE_INTEGER
-void LinearTransform::reduce(int32_t* N, uint32_t* D) {
-    if (N && D && *D) {
-        if (*N < 0) {
-            *N = -(*N);
-            reduce(reinterpret_cast<uint32_t*>(N), D);
-            *N = -(*N);
-        } else {
-            reduce(reinterpret_cast<uint32_t*>(N), D);
-        }
-    }
-}
-
-}  // namespace android
diff --git a/libutils/Log.cpp b/libutils/Log.cpp
index bffb56e..2c1fb86 100644
--- a/libutils/Log.cpp
+++ b/libutils/Log.cpp
@@ -21,14 +21,14 @@
 
 namespace android {
 
-LogIfSlow::LogIfSlow(const char* tag, android_LogPriority priority,
-        int timeoutMillis, const char* message) :
-        mTag(tag), mPriority(priority), mTimeoutMillis(timeoutMillis), mMessage(message),
-        mStart(systemTime(SYSTEM_TIME_BOOTTIME)) {
+LogIfSlow::LogIfSlow(
+        const char* tag, android_LogPriority priority, int timeoutMillis, const char* message)
+        : mTag(tag), mPriority(priority), mTimeoutMillis(timeoutMillis), mMessage(message),
+          mStart(systemTime(SYSTEM_TIME_BOOTTIME)) {
 }
 
 LogIfSlow::~LogIfSlow() {
-    int durationMillis = nanoseconds_to_milliseconds(systemTime(SYSTEM_TIME_BOOTTIME) - mStart);
+    int durationMillis = (int)nanoseconds_to_milliseconds(systemTime(SYSTEM_TIME_BOOTTIME) - mStart);
     if (durationMillis > mTimeoutMillis) {
         LOG_PRI(mPriority, mTag, "%s: %dms", mMessage, durationMillis);
     }
diff --git a/libutils/Looper.cpp b/libutils/Looper.cpp
index 952c992..6c57b2e 100644
--- a/libutils/Looper.cpp
+++ b/libutils/Looper.cpp
@@ -13,18 +13,8 @@
 // Debugs callback registration and invocation.
 #define DEBUG_CALLBACKS 0
 
-#include <cutils/log.h>
 #include <utils/Looper.h>
-#include <utils/Timers.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <inttypes.h>
-#include <string.h>
 #include <sys/eventfd.h>
-#include <unistd.h>
-
 
 namespace android {
 
@@ -84,6 +74,7 @@
 
 Looper::~Looper() {
     close(mWakeEventFd);
+    mWakeEventFd = -1;
     if (mEpollFd >= 0) {
         close(mEpollFd);
     }
@@ -413,7 +404,8 @@
     ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
     if (nWrite != sizeof(uint64_t)) {
         if (errno != EAGAIN) {
-            ALOGW("Could not write wake signal: %s", strerror(errno));
+            LOG_ALWAYS_FATAL("Could not write wake signal to fd %d: %s",
+                    mWakeEventFd, strerror(errno));
         }
     }
 }
@@ -677,4 +669,8 @@
     eventItem->data.fd = fd;
 }
 
+MessageHandler::~MessageHandler() { }
+
+LooperCallback::~LooperCallback() { }
+
 } // namespace android
diff --git a/libutils/NativeHandle.cpp b/libutils/NativeHandle.cpp
index e4daca7..97d06b8 100644
--- a/libutils/NativeHandle.cpp
+++ b/libutils/NativeHandle.cpp
@@ -19,14 +19,14 @@
 
 namespace android {
 
-sp<NativeHandle> NativeHandle::create(
-        native_handle_t* handle, bool ownsHandle) {
+sp<NativeHandle> NativeHandle::create(native_handle_t* handle, bool ownsHandle) {
     return handle ? new NativeHandle(handle, ownsHandle) : NULL;
 }
 
 NativeHandle::NativeHandle(native_handle_t* handle, bool ownsHandle)
-:   mHandle(handle), mOwnsHandle(ownsHandle)
-{}
+        : mHandle(handle), mOwnsHandle(ownsHandle) {
+
+}
 
 NativeHandle::~NativeHandle() {
     if (mOwnsHandle) {
diff --git a/libutils/Printer.cpp b/libutils/Printer.cpp
index 1dc8632..12f77bb 100644
--- a/libutils/Printer.cpp
+++ b/libutils/Printer.cpp
@@ -21,8 +21,6 @@
 #include <utils/String8.h>
 #include <utils/Log.h>
 
-#include <string.h>
-#include <stdio.h>
 #include <stdlib.h>
 
 namespace android {
@@ -44,7 +42,7 @@
 
     char* formattedString;
 
-#ifndef USE_MINGW
+#ifndef _WIN32
     if (vasprintf(&formattedString, format, arglist) < 0) { // returns -1 on error
         ALOGE("%s: Failed to format string", __FUNCTION__);
         return;
@@ -115,7 +113,7 @@
         return;
     }
 
-#ifndef USE_MINGW
+#ifndef _WIN32
     dprintf(mFd, mFormatString, mPrefix, string);
 #endif
 }
diff --git a/libutils/ProcessCallStack.cpp b/libutils/ProcessCallStack.cpp
index cdb586d..b8fb6dc 100644
--- a/libutils/ProcessCallStack.cpp
+++ b/libutils/ProcessCallStack.cpp
@@ -17,17 +17,14 @@
 #define LOG_TAG "ProcessCallStack"
 // #define LOG_NDEBUG 0
 
-#include <dirent.h>
-#include <errno.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <utils/Log.h>
-#include <utils/Errors.h>
 #include <utils/ProcessCallStack.h>
-#include <utils/Printer.h>
 
-#include <limits.h>
+#include <dirent.h>
+#include <unistd.h>
+
+#include <memory>
+
+#include <utils/Printer.h>
 
 namespace android {
 
@@ -130,11 +127,7 @@
 }
 
 void ProcessCallStack::update() {
-    DIR *dp;
-    struct dirent *ep;
-    struct dirent entry;
-
-    dp = opendir(PATH_SELF_TASK);
+    std::unique_ptr<DIR, decltype(&closedir)> dp(opendir(PATH_SELF_TASK), closedir);
     if (dp == NULL) {
         ALOGE("%s: Failed to update the process's call stacks: %s",
               __FUNCTION__, strerror(errno));
@@ -158,8 +151,8 @@
      * Each tid is a directory inside of /proc/self/task
      * - Read every file in directory => get every tid
      */
-    int code;
-    while ((code = readdir_r(dp, &entry, &ep)) == 0 && ep != NULL) {
+    dirent* ep;
+    while ((ep = readdir(dp.get())) != NULL) {
         pid_t tid = -1;
         sscanf(ep->d_name, "%d", &tid);
 
@@ -194,12 +187,6 @@
         ALOGV("%s: Got call stack for tid %d (size %zu)",
               __FUNCTION__, tid, threadInfo.callStack.size());
     }
-    if (code != 0) { // returns positive error value on error
-        ALOGE("%s: Failed to readdir from %s: %s",
-              __FUNCTION__, PATH_SELF_TASK, strerror(code));
-    }
-
-    closedir(dp);
 }
 
 void ProcessCallStack::log(const char* logtag, android_LogPriority priority,
diff --git a/libutils/PropertyMap.cpp b/libutils/PropertyMap.cpp
index 5520702..4bcdd0f 100644
--- a/libutils/PropertyMap.cpp
+++ b/libutils/PropertyMap.cpp
@@ -16,11 +16,7 @@
 
 #define LOG_TAG "PropertyMap"
 
-#include <stdlib.h>
-#include <string.h>
-
 #include <utils/PropertyMap.h>
-#include <utils/Log.h>
 
 // Enables debug output for the parser.
 #define DEBUG_PARSER 0
diff --git a/libutils/RefBase.cpp b/libutils/RefBase.cpp
index 4ead19c..24737b9 100644
--- a/libutils/RefBase.cpp
+++ b/libutils/RefBase.cpp
@@ -17,19 +17,9 @@
 #define LOG_TAG "RefBase"
 // #define LOG_NDEBUG 0
 
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <typeinfo>
-#include <unistd.h>
-
 #include <utils/RefBase.h>
 
 #include <utils/CallStack.h>
-#include <utils/Log.h>
-#include <utils/threads.h>
 
 #ifndef __unused
 #define __unused __attribute__((__unused__))
@@ -56,37 +46,44 @@
 
 namespace android {
 
-// Usage, invariants, etc:
+// Observations, invariants, etc:
 
-// It is normally OK just to keep weak pointers to an object.  The object will
-// be deallocated by decWeak when the last weak reference disappears.
-// Once a a strong reference has been created, the object will disappear once
-// the last strong reference does (decStrong).
-// AttemptIncStrong will succeed if the object has a strong reference, or if it
-// has a weak reference and has never had a strong reference.
-// AttemptIncWeak really does succeed only if there is already a WEAK
-// reference, and thus may fail when attemptIncStrong would succeed.
+// By default, obects are destroyed when the last strong reference disappears
+// or, if the object never had a strong reference, when the last weak reference
+// disappears.
+//
 // OBJECT_LIFETIME_WEAK changes this behavior to retain the object
 // unconditionally until the last reference of either kind disappears.  The
 // client ensures that the extendObjectLifetime call happens before the dec
 // call that would otherwise have deallocated the object, or before an
 // attemptIncStrong call that might rely on it.  We do not worry about
 // concurrent changes to the object lifetime.
+//
+// AttemptIncStrong will succeed if the object has a strong reference, or if it
+// has a weak reference and has never had a strong reference.
+// AttemptIncWeak really does succeed only if there is already a WEAK
+// reference, and thus may fail when attemptIncStrong would succeed.
+//
 // mStrong is the strong reference count.  mWeak is the weak reference count.
 // Between calls, and ignoring memory ordering effects, mWeak includes strong
 // references, and is thus >= mStrong.
 //
+// A weakref_impl holds all the information, including both reference counts,
+// required to perform wp<> operations.  Thus these can continue to be performed
+// after the RefBase object has been destroyed.
+//
 // A weakref_impl is allocated as the value of mRefs in a RefBase object on
 // construction.
-// In the OBJECT_LIFETIME_STRONG case, it is deallocated in the RefBase
-// destructor iff the strong reference count was never incremented. The
-// destructor can be invoked either from decStrong, or from decWeak if there
-// was never a strong reference. If the reference count had been incremented,
-// it is deallocated directly in decWeak, and hence still lives as long as
-// the last weak reference.
-// In the OBJECT_LIFETIME_WEAK case, it is always deallocated from the RefBase
-// destructor, which is always invoked by decWeak. DecStrong explicitly avoids
-// the deletion in this case.
+// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
+// and hence lives as long as the last weak reference. (It can also be
+// deallocated in the RefBase destructor iff the strong reference count was
+// never incremented and the weak count is zero, e.g.  if the RefBase object is
+// explicitly destroyed without decrementing the strong count.  This should be
+// avoided.) In this case, the RefBase destructor should be invoked from
+// decStrong.
+// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
+// the RefBase destructor, which is always invoked by decWeak. DecStrong
+// explicitly avoids the deletion in this case.
 //
 // Memory ordering:
 // The client must ensure that every inc() call, together with all other
@@ -120,6 +117,19 @@
 
 #define INITIAL_STRONG_VALUE (1<<28)
 
+#define MAX_COUNT 0xfffff
+
+// Test whether the argument is a clearly invalid strong reference count.
+// Used only for error checking on the value before an atomic decrement.
+// Intended to be very cheap.
+// Note that we cannot just check for excess decrements by comparing to zero
+// since the object would be deallocated before that.
+#define BAD_STRONG(c) \
+        ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)
+
+// Same for weak counts.
+#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)
+
 // ---------------------------------------------------------------------------
 
 class RefBase::weakref_impl : public RefBase::weakref_type
@@ -132,7 +142,7 @@
 
 #if !DEBUG_REFS
 
-    weakref_impl(RefBase* base)
+    explicit weakref_impl(RefBase* base)
         : mStrong(INITIAL_STRONG_VALUE)
         , mWeak(0)
         , mBase(base)
@@ -251,17 +261,22 @@
         {
             Mutex::Autolock _l(mMutex);
             char buf[128];
-            sprintf(buf, "Strong references on RefBase %p (weakref_type %p):\n", mBase, this);
+            snprintf(buf, sizeof(buf),
+                     "Strong references on RefBase %p (weakref_type %p):\n",
+                     mBase, this);
             text.append(buf);
             printRefsLocked(&text, mStrongRefs);
-            sprintf(buf, "Weak references on RefBase %p (weakref_type %p):\n", mBase, this);
+            snprintf(buf, sizeof(buf),
+                     "Weak references on RefBase %p (weakref_type %p):\n",
+                     mBase, this);
             text.append(buf);
             printRefsLocked(&text, mWeakRefs);
         }
 
         {
             char name[100];
-            snprintf(name, 100, DEBUG_REFS_CALLSTACK_PATH "/%p.stack", this);
+            snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
+                     this);
             int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
             if (rc >= 0) {
                 write(rc, text.string(), text.length());
@@ -354,8 +369,8 @@
         char buf[128];
         while (refs) {
             char inc = refs->ref >= 0 ? '+' : '-';
-            sprintf(buf, "\t%c ID %p (ref %d):\n", 
-                    inc, refs->id, refs->ref);
+            snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
+                     inc, refs->id, refs->ref);
             out->append(buf);
 #if DEBUG_REFS_CALLSTACK_ENABLED
             out->append(refs->stack.toString("\t\t"));
@@ -410,15 +425,15 @@
 #if PRINT_REFS
     ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
 #endif
-    ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
+    LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
+            refs);
     if (c == 1) {
         std::atomic_thread_fence(std::memory_order_acquire);
         refs->mBase->onLastStrongRef(id);
         int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
         if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
             delete this;
-            // Since mStrong had been incremented, the destructor did not
-            // delete refs.
+            // The destructor does not delete refs in this case.
         }
     }
     // Note that even with only strong reference operations, the thread
@@ -481,7 +496,8 @@
     weakref_impl* const impl = static_cast<weakref_impl*>(this);
     impl->removeWeakRef(id);
     const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
-    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
+    LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
+            this);
     if (c != 1) return;
     atomic_thread_fence(std::memory_order_acquire);
 
@@ -489,13 +505,19 @@
     if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
         // This is the regular lifetime case. The object is destroyed
         // when the last strong reference goes away. Since weakref_impl
-        // outlive the object, it is not destroyed in the dtor, and
+        // outlives the object, it is not destroyed in the dtor, and
         // we'll have to do it here.
         if (impl->mStrong.load(std::memory_order_relaxed)
                 == INITIAL_STRONG_VALUE) {
-            // Special case: we never had a strong reference, so we need to
-            // destroy the object now.
-            delete impl->mBase;
+            // Decrementing a weak count to zero when object never had a strong
+            // reference.  We assume it acquired a weak reference early, e.g.
+            // in the constructor, and will eventually be properly destroyed,
+            // usually via incrementing and decrementing the strong count.
+            // Thus we no longer do anything here.  We log this case, since it
+            // seems to be extremely rare, and should not normally occur. We
+            // used to deallocate mBase here, so this may now indicate a leak.
+            ALOGW("RefBase: Object at %p lost last weak reference "
+                    "before it had a strong reference", impl->mBase);
         } else {
             // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
             delete impl;
@@ -664,24 +686,28 @@
 
 RefBase::~RefBase()
 {
-    if (mRefs->mStrong.load(std::memory_order_relaxed)
-            == INITIAL_STRONG_VALUE) {
-        // we never acquired a strong (and/or weak) reference on this object.
-        delete mRefs;
-    } else {
-        // life-time of this object is extended to WEAK, in
-        // which case weakref_impl doesn't out-live the object and we
-        // can free it now.
-        int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
-        if ((flags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
-            // It's possible that the weak count is not 0 if the object
-            // re-acquired a weak reference in its destructor
-            if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
-                delete mRefs;
-            }
+    int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
+    // Life-time of this object is extended to WEAK, in
+    // which case weakref_impl doesn't out-live the object and we
+    // can free it now.
+    if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
+        // It's possible that the weak count is not 0 if the object
+        // re-acquired a weak reference in its destructor
+        if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
+            delete mRefs;
         }
+    } else if (mRefs->mStrong.load(std::memory_order_relaxed)
+            == INITIAL_STRONG_VALUE) {
+        // We never acquired a strong reference on this object.
+        LOG_ALWAYS_FATAL_IF(mRefs->mWeak.load() != 0,
+                "RefBase: Explicit destruction with non-zero weak "
+                "reference count");
+        // TODO: Always report if we get here. Currently MediaMetadataRetriever
+        // C++ objects are inconsistently managed and sometimes get here.
+        // There may be other cases, but we believe they should all be fixed.
+        delete mRefs;
     }
-    // for debugging purposes, clear this.
+    // For debugging purposes, clear mRefs.  Ineffective against outstanding wp's.
     const_cast<weakref_impl*&>(mRefs) = NULL;
 }
 
diff --git a/libutils/SharedBuffer.cpp b/libutils/SharedBuffer.cpp
index a8a9fb4..bad98b2 100644
--- a/libutils/SharedBuffer.cpp
+++ b/libutils/SharedBuffer.cpp
@@ -14,13 +14,15 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "sharedbuffer"
+
+#include "SharedBuffer.h"
+
 #include <stdlib.h>
 #include <string.h>
 
 #include <log/log.h>
 
-#include "SharedBuffer.h"
-
 // ---------------------------------------------------------------------------
 
 namespace android {
@@ -111,15 +113,26 @@
 
 int32_t SharedBuffer::release(uint32_t flags) const
 {
-    int32_t prev = 1;
-    if (onlyOwner() || ((prev = mRefs.fetch_sub(1, std::memory_order_release) == 1)
-            && (atomic_thread_fence(std::memory_order_acquire), true))) {
+    const bool useDealloc = ((flags & eKeepStorage) == 0);
+    if (onlyOwner()) {
+        // Since we're the only owner, our reference count goes to zero.
         mRefs.store(0, std::memory_order_relaxed);
-        if ((flags & eKeepStorage) == 0) {
-            free(const_cast<SharedBuffer*>(this));
+        if (useDealloc) {
+            dealloc(this);
+        }
+        // As the only owner, our previous reference count was 1.
+        return 1;
+    }
+    // There's multiple owners, we need to use an atomic decrement.
+    int32_t prevRefCount = mRefs.fetch_sub(1, std::memory_order_release);
+    if (prevRefCount == 1) {
+        // We're the last reference, we need the acquire fence.
+        atomic_thread_fence(std::memory_order_acquire);
+        if (useDealloc) {
+            dealloc(this);
         }
     }
-    return prev;
+    return prevRefCount;
 }
 
 
diff --git a/libutils/StopWatch.cpp b/libutils/StopWatch.cpp
index 8c7b596..219c13c 100644
--- a/libutils/StopWatch.cpp
+++ b/libutils/StopWatch.cpp
@@ -16,9 +16,7 @@
 
 #define LOG_TAG "StopWatch"
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
+#include <utils/StopWatch.h>
 
 /* for PRId64 */
 #ifndef __STDC_FORMAT_MACROS
@@ -27,8 +25,6 @@
 #include <inttypes.h>
 
 #include <utils/Log.h>
-#include <utils/Errors.h>
-#include <utils/StopWatch.h>
 
 /*****************************************************************************/
 
diff --git a/libutils/String16.cpp b/libutils/String16.cpp
index 65396ca..ad335c3 100644
--- a/libutils/String16.cpp
+++ b/libutils/String16.cpp
@@ -17,12 +17,7 @@
 #include <utils/String16.h>
 
 #include <utils/Log.h>
-#include <utils/Unicode.h>
-#include <utils/String8.h>
-#include <utils/threads.h>
 
-#include <memory.h>
-#include <stdio.h>
 #include <ctype.h>
 
 #include "SharedBuffer.h"
@@ -72,12 +67,12 @@
         u8cur = (const uint8_t*) u8str;
         char16_t* u16str = (char16_t*)buf->data();
 
-        utf8_to_utf16(u8cur, u8len, u16str);
+        utf8_to_utf16(u8cur, u8len, u16str, ((size_t) u16len) + 1);
 
         //printf("Created UTF-16 string from UTF-8 \"%s\":", in);
         //printHexData(1, str, buf->size(), 16, 1);
         //printf("\n");
-        
+
         return u16str;
     }
 
@@ -127,7 +122,7 @@
         mString = str;
         return;
     }
-    
+
     mString = getEmptyString();
 }
 
@@ -142,7 +137,7 @@
         mString = str;
         return;
     }
-    
+
     mString = getEmptyString();
 }
 
@@ -228,7 +223,7 @@
     } else if (otherLen == 0) {
         return NO_ERROR;
     }
-    
+
     SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
         ->editResize((myLen+otherLen+1)*sizeof(char16_t));
     if (buf) {
@@ -249,7 +244,7 @@
     } else if (otherLen == 0) {
         return NO_ERROR;
     }
-    
+
     SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
         ->editResize((myLen+otherLen+1)*sizeof(char16_t));
     if (buf) {
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index 755e0d1..ad0e72e 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -21,9 +21,7 @@
 
 #include <utils/Compat.h>
 #include <utils/Log.h>
-#include <utils/Unicode.h>
 #include <utils/String16.h>
-#include <utils/threads.h>
 
 #include <ctype.h>
 
@@ -363,7 +361,7 @@
 status_t String8::real_append(const char* other, size_t otherLen)
 {
     const size_t myLen = bytes();
-    
+
     SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
         ->editResize(myLen+otherLen+1);
     if (buf) {
diff --git a/libutils/StrongPointer.cpp b/libutils/StrongPointer.cpp
new file mode 100644
index 0000000..ba52502
--- /dev/null
+++ b/libutils/StrongPointer.cpp
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "sp"
+
+#include <log/log.h>
+
+namespace android {
+
+void sp_report_race() { LOG_ALWAYS_FATAL("sp<> assignment detected data race"); }
+}
diff --git a/libutils/SystemClock.cpp b/libutils/SystemClock.cpp
index 1fca2b2..28fc351 100644
--- a/libutils/SystemClock.cpp
+++ b/libutils/SystemClock.cpp
@@ -19,22 +19,17 @@
  * System clock functions.
  */
 
-#if defined(__ANDROID__)
-#include <linux/ioctl.h>
-#include <linux/rtc.h>
-#include <utils/Atomic.h>
-#include <linux/android_alarm.h>
-#endif
-
-#include <sys/time.h>
-#include <limits.h>
-#include <fcntl.h>
-#include <string.h>
+#define LOG_TAG "SystemClock"
 
 #include <utils/SystemClock.h>
-#include <utils/Timers.h>
 
-#define LOG_TAG "SystemClock"
+#include <sys/time.h>
+#include <string.h>
+#include <errno.h>
+
+#include <cutils/compiler.h>
+
+#include <utils/Timers.h>
 #include <utils/Log.h>
 
 namespace android {
@@ -56,100 +51,21 @@
 	return nanoseconds_to_milliseconds(elapsedRealtimeNano());
 }
 
-#define METHOD_CLOCK_GETTIME    0
-#define METHOD_IOCTL            1
-#define METHOD_SYSTEMTIME       2
-
-/*
- * To debug/verify the timestamps returned by the kernel, change
- * DEBUG_TIMESTAMP to 1 and call the timestamp routine from a single thread
- * in the test program. b/10899829
- */
-#define DEBUG_TIMESTAMP         0
-
-#if DEBUG_TIMESTAMP && defined(__arm__)
-static inline void checkTimeStamps(int64_t timestamp,
-                                   int64_t volatile *prevTimestampPtr,
-                                   int volatile *prevMethodPtr,
-                                   int curMethod)
-{
-    /*
-     * Disable the check for SDK since the prebuilt toolchain doesn't contain
-     * gettid, and int64_t is different on the ARM platform
-     * (ie long vs long long).
-     */
-    int64_t prevTimestamp = *prevTimestampPtr;
-    int prevMethod = *prevMethodPtr;
-
-    if (timestamp < prevTimestamp) {
-        static const char *gettime_method_names[] = {
-            "clock_gettime",
-            "ioctl",
-            "systemTime",
-        };
-
-        ALOGW("time going backwards: prev %lld(%s) vs now %lld(%s), tid=%d",
-              prevTimestamp, gettime_method_names[prevMethod],
-              timestamp, gettime_method_names[curMethod],
-              gettid());
-    }
-    // NOTE - not atomic and may generate spurious warnings if the 64-bit
-    // write is interrupted or not observed as a whole.
-    *prevTimestampPtr = timestamp;
-    *prevMethodPtr = curMethod;
-}
-#else
-#define checkTimeStamps(timestamp, prevTimestampPtr, prevMethodPtr, curMethod)
-#endif
-
 /*
  * native public static long elapsedRealtimeNano();
  */
 int64_t elapsedRealtimeNano()
 {
-#if defined(__ANDROID__)
+#if defined(__linux__)
     struct timespec ts;
-    int result;
-    int64_t timestamp;
-#if DEBUG_TIMESTAMP
-    static volatile int64_t prevTimestamp;
-    static volatile int prevMethod;
-#endif
-
-    static int s_fd = -1;
-
-    if (s_fd == -1) {
-        int fd = open("/dev/alarm", O_RDONLY);
-        if (android_atomic_cmpxchg(-1, fd, &s_fd)) {
-            close(fd);
-        }
+    int err = clock_gettime(CLOCK_BOOTTIME, &ts);
+    if (CC_UNLIKELY(err)) {
+        // This should never happen, but just in case ...
+        ALOGE("clock_gettime(CLOCK_BOOTTIME) failed: %s", strerror(errno));
+        return 0;
     }
 
-    result = ioctl(s_fd,
-            ANDROID_ALARM_GET_TIME(ANDROID_ALARM_ELAPSED_REALTIME), &ts);
-
-    if (result == 0) {
-        timestamp = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
-        checkTimeStamps(timestamp, &prevTimestamp, &prevMethod, METHOD_IOCTL);
-        return timestamp;
-    }
-
-    // /dev/alarm doesn't exist, fallback to CLOCK_BOOTTIME
-    result = clock_gettime(CLOCK_BOOTTIME, &ts);
-    if (result == 0) {
-        timestamp = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
-        checkTimeStamps(timestamp, &prevTimestamp, &prevMethod,
-                        METHOD_CLOCK_GETTIME);
-        return timestamp;
-    }
-
-    // XXX: there was an error, probably because the driver didn't
-    // exist ... this should return
-    // a real error, like an exception!
-    timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
-    checkTimeStamps(timestamp, &prevTimestamp, &prevMethod,
-                    METHOD_SYSTEMTIME);
-    return timestamp;
+    return seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
 #else
     return systemTime(SYSTEM_TIME_MONOTONIC);
 #endif
diff --git a/libutils/Threads.cpp b/libutils/Threads.cpp
index def739f..6317c32 100644
--- a/libutils/Threads.cpp
+++ b/libutils/Threads.cpp
@@ -18,16 +18,10 @@
 #define LOG_TAG "libutils.threads"
 
 #include <assert.h>
-#include <errno.h>
-#include <memory.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
+#include <utils/Thread.h>
+#include <utils/AndroidThreads.h>
 
 #if !defined(_WIN32)
-# include <pthread.h>
-# include <sched.h>
 # include <sys/resource.h>
 #else
 # include <windows.h>
@@ -40,7 +34,6 @@
 #include <sys/prctl.h>
 #endif
 
-#include <utils/threads.h>
 #include <utils/Log.h>
 
 #include <cutils/sched_policy.h>
diff --git a/libutils/Timers.cpp b/libutils/Timers.cpp
index 201bc41..b2df9a5 100644
--- a/libutils/Timers.cpp
+++ b/libutils/Timers.cpp
@@ -20,7 +20,6 @@
 #include <utils/Timers.h>
 
 #include <limits.h>
-#include <sys/time.h>
 #include <time.h>
 
 #if defined(__ANDROID__)
@@ -53,7 +52,7 @@
 
 int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime)
 {
-    int timeoutDelayMillis;
+    nsecs_t timeoutDelayMillis;
     if (timeoutTime > referenceTime) {
         uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime);
         if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) {
@@ -64,5 +63,5 @@
     } else {
         timeoutDelayMillis = 0;
     }
-    return timeoutDelayMillis;
+    return (int)timeoutDelayMillis;
 }
diff --git a/libutils/Tokenizer.cpp b/libutils/Tokenizer.cpp
index 2d0e83d..b68a2cf 100644
--- a/libutils/Tokenizer.cpp
+++ b/libutils/Tokenizer.cpp
@@ -16,14 +16,10 @@
 
 #define LOG_TAG "Tokenizer"
 
-#include <stdlib.h>
-#include <unistd.h>
+#include <utils/Tokenizer.h>
 #include <fcntl.h>
-#include <errno.h>
-#include <sys/types.h>
 #include <sys/stat.h>
 #include <utils/Log.h>
-#include <utils/Tokenizer.h>
 
 // Enables debug output for the tokenizer.
 #define DEBUG_TOKENIZER 0
diff --git a/libutils/Trace.cpp b/libutils/Trace.cpp
index 36fd802..8530fdc 100644
--- a/libutils/Trace.cpp
+++ b/libutils/Trace.cpp
@@ -14,12 +14,11 @@
  * limitations under the License.
  */
 
-#include <utils/misc.h>
 #include <utils/Trace.h>
+#include <utils/misc.h>
 
 static void traceInit() __attribute__((constructor));
 
-static void traceInit()
-{
+static void traceInit() {
     ::android::add_sysprop_change_callback(atrace_update_tags, 0);
 }
diff --git a/libutils/Unicode.cpp b/libutils/Unicode.cpp
index ba084f6..5fd9155 100644
--- a/libutils/Unicode.cpp
+++ b/libutils/Unicode.cpp
@@ -14,10 +14,12 @@
  * limitations under the License.
  */
 
-#include <log/log.h>
-#include <utils/Unicode.h>
+#define LOG_TAG "unicode"
 
-#include <stddef.h>
+#include <utils/Unicode.h>
+#include <limits.h>
+
+#include <log/log.h>
 
 #if defined(_WIN32)
 # undef  nhtol
@@ -542,7 +544,7 @@
     //printf("Char at %p: len=%d, utf-16=%p\n", src, length, (void*)result);
 }
 
-ssize_t utf8_to_utf16_length(const uint8_t* u8str, size_t u8len)
+ssize_t utf8_to_utf16_length(const uint8_t* u8str, size_t u8len, bool overreadIsFatal)
 {
     const uint8_t* const u8end = u8str + u8len;
     const uint8_t* u8cur = u8str;
@@ -552,6 +554,20 @@
     while (u8cur < u8end) {
         u16measuredLen++;
         int u8charLen = utf8_codepoint_len(*u8cur);
+        // Malformed utf8, some characters are beyond the end.
+        // Cases:
+        // If u8charLen == 1, this becomes u8cur >= u8end, which cannot happen as u8cur < u8end,
+        // then this condition fail and we continue, as expected.
+        // If u8charLen == 2, this becomes u8cur + 1 >= u8end, which fails only if
+        // u8cur == u8end - 1, that is, there was only one remaining character to read but we need
+        // 2 of them. This condition holds and we return -1, as expected.
+        if (u8cur + u8charLen - 1 >= u8end) {
+            if (overreadIsFatal) {
+                LOG_ALWAYS_FATAL("Attempt to overread computing length of utf8 string");
+            } else {
+                return -1;
+            }
+        }
         uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8charLen);
         if (codepoint > 0xFFFF) u16measuredLen++; // this will be a surrogate pair in utf16
         u8cur += u8charLen;
@@ -568,38 +584,21 @@
     return u16measuredLen;
 }
 
-char16_t* utf8_to_utf16_no_null_terminator(const uint8_t* u8str, size_t u8len, char16_t* u16str)
-{
-    const uint8_t* const u8end = u8str + u8len;
-    const uint8_t* u8cur = u8str;
-    char16_t* u16cur = u16str;
-
-    while (u8cur < u8end) {
-        size_t u8len = utf8_codepoint_len(*u8cur);
-        uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8len);
-
-        // Convert the UTF32 codepoint to one or more UTF16 codepoints
-        if (codepoint <= 0xFFFF) {
-            // Single UTF16 character
-            *u16cur++ = (char16_t) codepoint;
-        } else {
-            // Multiple UTF16 characters with surrogates
-            codepoint = codepoint - 0x10000;
-            *u16cur++ = (char16_t) ((codepoint >> 10) + 0xD800);
-            *u16cur++ = (char16_t) ((codepoint & 0x3FF) + 0xDC00);
-        }
-
-        u8cur += u8len;
-    }
-    return u16cur;
-}
-
-void utf8_to_utf16(const uint8_t* u8str, size_t u8len, char16_t* u16str) {
-    char16_t* end = utf8_to_utf16_no_null_terminator(u8str, u8len, u16str);
+char16_t* utf8_to_utf16(const uint8_t* u8str, size_t u8len, char16_t* u16str, size_t u16len) {
+    // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
+    LOG_ALWAYS_FATAL_IF(u16len == 0 || u16len > SSIZE_MAX, "u16len is %zu", u16len);
+    char16_t* end = utf8_to_utf16_no_null_terminator(u8str, u8len, u16str, u16len - 1);
     *end = 0;
+    return end;
 }
 
-char16_t* utf8_to_utf16_n(const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen) {
+char16_t* utf8_to_utf16_no_null_terminator(
+        const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen) {
+    if (dstLen == 0) {
+        return dst;
+    }
+    // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
+    LOG_ALWAYS_FATAL_IF(dstLen > SSIZE_MAX, "dstLen is %zu", dstLen);
     const uint8_t* const u8end = src + srcLen;
     const uint8_t* u8cur = src;
     const char16_t* const u16end = dst + dstLen;
diff --git a/libutils/VectorImpl.cpp b/libutils/VectorImpl.cpp
index e8d40ed..ef3277f 100644
--- a/libutils/VectorImpl.cpp
+++ b/libutils/VectorImpl.cpp
@@ -16,16 +16,16 @@
 
 #define LOG_TAG "Vector"
 
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#include <cutils/log.h>
-#include <safe_iop.h>
-
-#include <utils/Errors.h>
 #include <utils/VectorImpl.h>
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <log/log.h>
+
+#include <safe_iop.h>
+
 #include "SharedBuffer.h"
 
 /*****************************************************************************/
diff --git a/include/utils/AndroidThreads.h b/libutils/include/utils/AndroidThreads.h
similarity index 100%
rename from include/utils/AndroidThreads.h
rename to libutils/include/utils/AndroidThreads.h
diff --git a/include/utils/Atomic.h b/libutils/include/utils/Atomic.h
similarity index 100%
rename from include/utils/Atomic.h
rename to libutils/include/utils/Atomic.h
diff --git a/include/utils/BitSet.h b/libutils/include/utils/BitSet.h
similarity index 100%
rename from include/utils/BitSet.h
rename to libutils/include/utils/BitSet.h
diff --git a/include/utils/ByteOrder.h b/libutils/include/utils/ByteOrder.h
similarity index 100%
rename from include/utils/ByteOrder.h
rename to libutils/include/utils/ByteOrder.h
diff --git a/include/utils/CallStack.h b/libutils/include/utils/CallStack.h
similarity index 100%
rename from include/utils/CallStack.h
rename to libutils/include/utils/CallStack.h
diff --git a/libutils/include/utils/Compat.h b/libutils/include/utils/Compat.h
new file mode 100644
index 0000000..dee577e
--- /dev/null
+++ b/libutils/include/utils/Compat.h
@@ -0,0 +1,87 @@
+/*
+ * 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 __LIB_UTILS_COMPAT_H
+#define __LIB_UTILS_COMPAT_H
+
+#include <unistd.h>
+
+#if defined(__APPLE__)
+
+/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */
+
+typedef off_t off64_t;
+
+static inline off64_t lseek64(int fd, off64_t offset, int whence) {
+    return lseek(fd, offset, whence);
+}
+
+static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) {
+    return pread(fd, buf, nbytes, offset);
+}
+
+static inline ssize_t pwrite64(int fd, const void* buf, size_t nbytes, off64_t offset) {
+    return pwrite(fd, buf, nbytes, offset);
+}
+
+static inline int ftruncate64(int fd, off64_t length) {
+    return ftruncate(fd, length);
+}
+
+#endif /* __APPLE__ */
+
+#if defined(_WIN32)
+#define O_CLOEXEC O_NOINHERIT
+#define O_NOFOLLOW 0
+#define DEFFILEMODE 0666
+#endif /* _WIN32 */
+
+#define ZD "%zd"
+#define ZD_TYPE ssize_t
+
+/*
+ * Needed for cases where something should be constexpr if possible, but not
+ * being constexpr is fine if in pre-C++11 code (such as a const static float
+ * member variable).
+ */
+#if __cplusplus >= 201103L
+#define CONSTEXPR constexpr
+#else
+#define CONSTEXPR
+#endif
+
+/*
+ * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
+ * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
+ * not already defined, then define it here.
+ */
+#ifndef TEMP_FAILURE_RETRY
+/* Used to retry syscalls that can return EINTR. */
+#define TEMP_FAILURE_RETRY(exp) ({         \
+    typeof (exp) _rc;                      \
+    do {                                   \
+        _rc = (exp);                       \
+    } while (_rc == -1 && errno == EINTR); \
+    _rc; })
+#endif
+
+#if defined(_WIN32)
+#define OS_PATH_SEPARATOR '\\'
+#else
+#define OS_PATH_SEPARATOR '/'
+#endif
+
+#endif /* __LIB_UTILS_COMPAT_H */
diff --git a/libutils/include/utils/Condition.h b/libutils/include/utils/Condition.h
new file mode 100644
index 0000000..3019a21
--- /dev/null
+++ b/libutils/include/utils/Condition.h
@@ -0,0 +1,163 @@
+/*
+ * 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_UTILS_CONDITION_H
+#define _LIBS_UTILS_CONDITION_H
+
+#include <limits.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <time.h>
+
+#if !defined(_WIN32)
+# include <pthread.h>
+#endif
+
+#include <utils/Errors.h>
+#include <utils/Mutex.h>
+#include <utils/Timers.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+// ---------------------------------------------------------------------------
+
+/*
+ * Condition variable class.  The implementation is system-dependent.
+ *
+ * Condition variables are paired up with mutexes.  Lock the mutex,
+ * call wait(), then either re-wait() if things aren't quite what you want,
+ * or unlock the mutex and continue.  All threads calling wait() must
+ * use the same mutex for a given Condition.
+ *
+ * On Android and Apple platforms, these are implemented as a simple wrapper
+ * around pthread condition variables.  Care must be taken to abide by
+ * the pthreads semantics, in particular, a boolean predicate must
+ * be re-evaluated after a wake-up, as spurious wake-ups may happen.
+ */
+class Condition {
+public:
+    enum {
+        PRIVATE = 0,
+        SHARED = 1
+    };
+
+    enum WakeUpType {
+        WAKE_UP_ONE = 0,
+        WAKE_UP_ALL = 1
+    };
+
+    Condition();
+    explicit Condition(int type);
+    ~Condition();
+    // Wait on the condition variable.  Lock the mutex before calling.
+    // Note that spurious wake-ups may happen.
+    status_t wait(Mutex& mutex);
+    // same with relative timeout
+    status_t waitRelative(Mutex& mutex, nsecs_t reltime);
+    // Signal the condition variable, allowing one thread to continue.
+    void signal();
+    // Signal the condition variable, allowing one or all threads to continue.
+    void signal(WakeUpType type) {
+        if (type == WAKE_UP_ONE) {
+            signal();
+        } else {
+            broadcast();
+        }
+    }
+    // Signal the condition variable, allowing all threads to continue.
+    void broadcast();
+
+private:
+#if !defined(_WIN32)
+    pthread_cond_t mCond;
+#else
+    void*   mState;
+#endif
+};
+
+// ---------------------------------------------------------------------------
+
+#if !defined(_WIN32)
+
+inline Condition::Condition() : Condition(PRIVATE) {
+}
+inline Condition::Condition(int type) {
+    pthread_condattr_t attr;
+    pthread_condattr_init(&attr);
+#if defined(__linux__)
+    pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
+#endif
+
+    if (type == SHARED) {
+        pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
+    }
+
+    pthread_cond_init(&mCond, &attr);
+    pthread_condattr_destroy(&attr);
+
+}
+inline Condition::~Condition() {
+    pthread_cond_destroy(&mCond);
+}
+inline status_t Condition::wait(Mutex& mutex) {
+    return -pthread_cond_wait(&mCond, &mutex.mMutex);
+}
+inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
+    struct timespec ts;
+#if defined(__linux__)
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+#else // __APPLE__
+    // Apple doesn't support POSIX clocks.
+    struct timeval t;
+    gettimeofday(&t, NULL);
+    ts.tv_sec = t.tv_sec;
+    ts.tv_nsec = t.tv_usec*1000;
+#endif
+
+    // On 32-bit devices, tv_sec is 32-bit, but `reltime` is 64-bit.
+    int64_t reltime_sec = reltime/1000000000;
+
+    ts.tv_nsec += static_cast<long>(reltime%1000000000);
+    if (reltime_sec < INT64_MAX && ts.tv_nsec >= 1000000000) {
+        ts.tv_nsec -= 1000000000;
+        ++reltime_sec;
+    }
+
+    int64_t time_sec = ts.tv_sec;
+    if (time_sec > INT64_MAX - reltime_sec) {
+        time_sec = INT64_MAX;
+    } else {
+        time_sec += reltime_sec;
+    }
+
+    ts.tv_sec = (time_sec > LONG_MAX) ? LONG_MAX : static_cast<long>(time_sec);
+
+    return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
+}
+inline void Condition::signal() {
+    pthread_cond_signal(&mCond);
+}
+inline void Condition::broadcast() {
+    pthread_cond_broadcast(&mCond);
+}
+
+#endif // !defined(_WIN32)
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+// ---------------------------------------------------------------------------
+
+#endif // _LIBS_UTILS_CONDITON_H
diff --git a/include/utils/Debug.h b/libutils/include/utils/Debug.h
similarity index 100%
rename from include/utils/Debug.h
rename to libutils/include/utils/Debug.h
diff --git a/include/utils/Endian.h b/libutils/include/utils/Endian.h
similarity index 100%
rename from include/utils/Endian.h
rename to libutils/include/utils/Endian.h
diff --git a/include/utils/Errors.h b/libutils/include/utils/Errors.h
similarity index 100%
rename from include/utils/Errors.h
rename to libutils/include/utils/Errors.h
diff --git a/libutils/include/utils/FastStrcmp.h b/libutils/include/utils/FastStrcmp.h
new file mode 100644
index 0000000..5cadc94
--- /dev/null
+++ b/libutils/include/utils/FastStrcmp.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2014-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 _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
+//
+// Template class fastcmp used to create more time-efficient str*cmp
+// functions by pre-checking the first character before resorting
+// to calling the underlying string function.  Profiled with a
+// measurable speedup when used in hot code.  Usage is of the form:
+//
+//  fastcmp<strncmp>(str1, str2, len)
+//
+// 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) {
+    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, 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 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
+
+#endif // _ANDROID_UTILS_FASTSTRCMP_H__
diff --git a/include/utils/FileMap.h b/libutils/include/utils/FileMap.h
similarity index 100%
rename from include/utils/FileMap.h
rename to libutils/include/utils/FileMap.h
diff --git a/libutils/include/utils/Flattenable.h b/libutils/include/utils/Flattenable.h
new file mode 100644
index 0000000..070c710
--- /dev/null
+++ b/libutils/include/utils/Flattenable.h
@@ -0,0 +1,205 @@
+/*
+ * 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 ANDROID_UTILS_FLATTENABLE_H
+#define ANDROID_UTILS_FLATTENABLE_H
+
+
+#include <stdint.h>
+#include <string.h>
+#include <sys/types.h>
+#include <utils/Errors.h>
+#include <utils/Debug.h>
+
+#include <type_traits>
+
+namespace android {
+
+
+class FlattenableUtils {
+public:
+    template<size_t N>
+    static size_t align(size_t size) {
+        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
+        return (size + (N-1)) & ~(N-1);
+    }
+
+    template<size_t N>
+    static size_t align(void const*& buffer) {
+        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
+        uintptr_t b = uintptr_t(buffer);
+        buffer = reinterpret_cast<void*>((uintptr_t(buffer) + (N-1)) & ~(N-1));
+        return size_t(uintptr_t(buffer) - b);
+    }
+
+    template<size_t N>
+    static size_t align(void*& buffer) {
+        return align<N>( const_cast<void const*&>(buffer) );
+    }
+
+    static void advance(void*& buffer, size_t& size, size_t offset) {
+        buffer = reinterpret_cast<void*>( uintptr_t(buffer) + offset );
+        size -= offset;
+    }
+
+    static void advance(void const*& buffer, size_t& size, size_t offset) {
+        buffer = reinterpret_cast<void const*>( uintptr_t(buffer) + offset );
+        size -= offset;
+    }
+
+    // write a POD structure
+    template<typename T>
+    static void write(void*& buffer, size_t& size, const T& value) {
+        static_assert(std::is_trivially_copyable<T>::value,
+                      "Cannot flatten a non-trivially-copyable type");
+        memcpy(buffer, &value, sizeof(T));
+        advance(buffer, size, sizeof(T));
+    }
+
+    // read a POD structure
+    template<typename T>
+    static void read(void const*& buffer, size_t& size, T& value) {
+        static_assert(std::is_trivially_copyable<T>::value,
+                      "Cannot unflatten a non-trivially-copyable type");
+        memcpy(&value, buffer, sizeof(T));
+        advance(buffer, size, sizeof(T));
+    }
+};
+
+
+/*
+ * The Flattenable protocol allows an object to serialize itself out
+ * to a byte-buffer and an array of file descriptors.
+ * Flattenable objects must implement this protocol.
+ */
+
+template <typename T>
+class Flattenable {
+public:
+    // size in bytes of the flattened object
+    inline size_t getFlattenedSize() const;
+
+    // number of file descriptors to flatten
+    inline size_t getFdCount() const;
+
+    // flattens the object into buffer.
+    // size should be at least of getFlattenedSize()
+    // file descriptors are written in the fds[] array but ownership is
+    // not transfered (ie: they must be dupped by the caller of
+    // flatten() if needed).
+    inline status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+
+    // unflattens the object from buffer.
+    // size should be equal to the value of getFlattenedSize() when the
+    // object was flattened.
+    // unflattened file descriptors are found in the fds[] array and
+    // don't need to be dupped(). ie: the caller of unflatten doesn't
+    // keep ownership. If a fd is not retained by unflatten() it must be
+    // explicitly closed.
+    inline status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
+};
+
+template<typename T>
+inline size_t Flattenable<T>::getFlattenedSize() const {
+    return static_cast<T const*>(this)->T::getFlattenedSize();
+}
+template<typename T>
+inline size_t Flattenable<T>::getFdCount() const {
+    return static_cast<T const*>(this)->T::getFdCount();
+}
+template<typename T>
+inline status_t Flattenable<T>::flatten(
+        void*& buffer, size_t& size, int*& fds, size_t& count) const {
+    return static_cast<T const*>(this)->T::flatten(buffer, size, fds, count);
+}
+template<typename T>
+inline status_t Flattenable<T>::unflatten(
+        void const*& buffer, size_t& size, int const*& fds, size_t& count) {
+    return static_cast<T*>(this)->T::unflatten(buffer, size, fds, count);
+}
+
+/*
+ * LightFlattenable is a protocol allowing object to serialize themselves out
+ * to a byte-buffer. Because it doesn't handle file-descriptors,
+ * LightFlattenable is usually more size efficient than Flattenable.
+ * LightFlattenable objects must implement this protocol.
+ */
+template <typename T>
+class LightFlattenable {
+public:
+    // returns whether this object always flatten into the same size.
+    // for efficiency, this should always be inline.
+    inline bool isFixedSize() const;
+
+    // returns size in bytes of the flattened object. must be a constant.
+    inline size_t getFlattenedSize() const;
+
+    // flattens the object into buffer.
+    inline status_t flatten(void* buffer, size_t size) const;
+
+    // unflattens the object from buffer of given size.
+    inline status_t unflatten(void const* buffer, size_t size);
+};
+
+template <typename T>
+inline bool LightFlattenable<T>::isFixedSize() const {
+    return static_cast<T const*>(this)->T::isFixedSize();
+}
+template <typename T>
+inline size_t LightFlattenable<T>::getFlattenedSize() const {
+    return static_cast<T const*>(this)->T::getFlattenedSize();
+}
+template <typename T>
+inline status_t LightFlattenable<T>::flatten(void* buffer, size_t size) const {
+    return static_cast<T const*>(this)->T::flatten(buffer, size);
+}
+template <typename T>
+inline status_t LightFlattenable<T>::unflatten(void const* buffer, size_t size) {
+    return static_cast<T*>(this)->T::unflatten(buffer, size);
+}
+
+/*
+ * LightFlattenablePod is an implementation of the LightFlattenable protocol
+ * for POD (plain-old-data) objects.
+ * Simply derive from LightFlattenablePod<Foo> to make Foo flattenable; no
+ * need to implement any methods; obviously Foo must be a POD structure.
+ */
+template <typename T>
+class LightFlattenablePod : public LightFlattenable<T> {
+public:
+    inline bool isFixedSize() const {
+        return true;
+    }
+
+    inline size_t getFlattenedSize() const {
+        return sizeof(T);
+    }
+    inline status_t flatten(void* buffer, size_t size) const {
+        if (size < sizeof(T)) return NO_MEMORY;
+        memcpy(buffer, static_cast<T const*>(this), sizeof(T));
+        return NO_ERROR;
+    }
+    inline status_t unflatten(void const* buffer, size_t) {
+        memcpy(static_cast<T*>(this), buffer, sizeof(T));
+        return NO_ERROR;
+    }
+};
+
+
+}; // namespace android
+
+
+#endif /* ANDROID_UTILS_FLATTENABLE_H */
diff --git a/include/utils/Functor.h b/libutils/include/utils/Functor.h
similarity index 100%
rename from include/utils/Functor.h
rename to libutils/include/utils/Functor.h
diff --git a/include/utils/JenkinsHash.h b/libutils/include/utils/JenkinsHash.h
similarity index 100%
rename from include/utils/JenkinsHash.h
rename to libutils/include/utils/JenkinsHash.h
diff --git a/libutils/include/utils/KeyedVector.h b/libutils/include/utils/KeyedVector.h
new file mode 100644
index 0000000..f93ad6e
--- /dev/null
+++ b/libutils/include/utils/KeyedVector.h
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2005 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_KEYED_VECTOR_H
+#define ANDROID_KEYED_VECTOR_H
+
+#include <assert.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <log/log.h>
+#include <utils/Errors.h>
+#include <utils/SortedVector.h>
+#include <utils/TypeHelpers.h>
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+template <typename KEY, typename VALUE>
+class KeyedVector
+{
+public:
+    typedef KEY    key_type;
+    typedef VALUE  value_type;
+
+    inline                  KeyedVector();
+
+    /*
+     * empty the vector
+     */
+
+    inline  void            clear()                     { mVector.clear(); }
+
+    /*! 
+     * vector stats
+     */
+
+    //! returns number of items in the vector
+    inline  size_t          size() const                { return mVector.size(); }
+    //! returns whether or not the vector is empty
+    inline  bool            isEmpty() const             { return mVector.isEmpty(); }
+    //! returns how many items can be stored without reallocating the backing store
+    inline  size_t          capacity() const            { return mVector.capacity(); }
+    //! sets the capacity. capacity can never be reduced less than size()
+    inline ssize_t          setCapacity(size_t size)    { return mVector.setCapacity(size); }
+
+    // returns true if the arguments is known to be identical to this vector
+    inline bool isIdenticalTo(const KeyedVector& rhs) const;
+
+    /*! 
+     * accessors
+     */
+            const VALUE&    valueFor(const KEY& key) const;
+            const VALUE&    valueAt(size_t index) const;
+            const KEY&      keyAt(size_t index) const;
+            ssize_t         indexOfKey(const KEY& key) const;
+            const VALUE&    operator[] (size_t index) const;
+
+    /*!
+     * modifying the array
+     */
+
+            VALUE&          editValueFor(const KEY& key);
+            VALUE&          editValueAt(size_t index);
+
+            /*! 
+             * add/insert/replace items
+             */
+             
+            ssize_t         add(const KEY& key, const VALUE& item);
+            ssize_t         replaceValueFor(const KEY& key, const VALUE& item);
+            ssize_t         replaceValueAt(size_t index, const VALUE& item);
+
+    /*!
+     * remove items
+     */
+
+            ssize_t         removeItem(const KEY& key);
+            ssize_t         removeItemsAt(size_t index, size_t count = 1);
+            
+private:
+            SortedVector< key_value_pair_t<KEY, VALUE> >    mVector;
+};
+
+// ---------------------------------------------------------------------------
+
+/**
+ * Variation of KeyedVector that holds a default value to return when
+ * valueFor() is called with a key that doesn't exist.
+ */
+template <typename KEY, typename VALUE>
+class DefaultKeyedVector : public KeyedVector<KEY, VALUE>
+{
+public:
+    inline                  DefaultKeyedVector(const VALUE& defValue = VALUE());
+            const VALUE&    valueFor(const KEY& key) const;
+
+private:
+            VALUE                                           mDefault;
+};
+
+// ---------------------------------------------------------------------------
+
+template<typename KEY, typename VALUE> inline
+KeyedVector<KEY,VALUE>::KeyedVector()
+{
+}
+
+template<typename KEY, typename VALUE> inline
+bool KeyedVector<KEY,VALUE>::isIdenticalTo(const KeyedVector<KEY,VALUE>& rhs) const {
+    return mVector.array() == rhs.mVector.array();
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY,VALUE>::indexOfKey(const KEY& key) const {
+    return mVector.indexOf( key_value_pair_t<KEY,VALUE>(key) );
+}
+
+template<typename KEY, typename VALUE> inline
+const VALUE& KeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
+    ssize_t i = this->indexOfKey(key);
+    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
+    return mVector.itemAt(i).value;
+}
+
+template<typename KEY, typename VALUE> inline
+const VALUE& KeyedVector<KEY,VALUE>::valueAt(size_t index) const {
+    return mVector.itemAt(index).value;
+}
+
+template<typename KEY, typename VALUE> inline
+const VALUE& KeyedVector<KEY,VALUE>::operator[] (size_t index) const {
+    return valueAt(index);
+}
+
+template<typename KEY, typename VALUE> inline
+const KEY& KeyedVector<KEY,VALUE>::keyAt(size_t index) const {
+    return mVector.itemAt(index).key;
+}
+
+template<typename KEY, typename VALUE> inline
+VALUE& KeyedVector<KEY,VALUE>::editValueFor(const KEY& key) {
+    ssize_t i = this->indexOfKey(key);
+    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
+    return mVector.editItemAt(static_cast<size_t>(i)).value;
+}
+
+template<typename KEY, typename VALUE> inline
+VALUE& KeyedVector<KEY,VALUE>::editValueAt(size_t index) {
+    return mVector.editItemAt(index).value;
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY,VALUE>::add(const KEY& key, const VALUE& value) {
+    return mVector.add( key_value_pair_t<KEY,VALUE>(key, value) );
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY,VALUE>::replaceValueFor(const KEY& key, const VALUE& value) {
+    key_value_pair_t<KEY,VALUE> pair(key, value);
+    mVector.remove(pair);
+    return mVector.add(pair);
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) {
+    if (index<size()) {
+        mVector.editItemAt(index).value = item;
+        return static_cast<ssize_t>(index);
+    }
+    return BAD_INDEX;
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY,VALUE>::removeItem(const KEY& key) {
+    return mVector.remove(key_value_pair_t<KEY,VALUE>(key));
+}
+
+template<typename KEY, typename VALUE> inline
+ssize_t KeyedVector<KEY, VALUE>::removeItemsAt(size_t index, size_t count) {
+    return mVector.removeItemsAt(index, count);
+}
+
+// ---------------------------------------------------------------------------
+
+template<typename KEY, typename VALUE> inline
+DefaultKeyedVector<KEY,VALUE>::DefaultKeyedVector(const VALUE& defValue)
+    : mDefault(defValue)
+{
+}
+
+template<typename KEY, typename VALUE> inline
+const VALUE& DefaultKeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
+    ssize_t i = this->indexOfKey(key);
+    return i >= 0 ? KeyedVector<KEY,VALUE>::valueAt(i) : mDefault;
+}
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_KEYED_VECTOR_H
diff --git a/libutils/include/utils/LightRefBase.h b/libutils/include/utils/LightRefBase.h
new file mode 100644
index 0000000..65257ed
--- /dev/null
+++ b/libutils/include/utils/LightRefBase.h
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/*
+ * See documentation in RefBase.h
+ */
+
+#include <atomic>
+
+#include <sys/types.h>
+
+namespace android {
+
+class ReferenceRenamer;
+
+template <class T>
+class LightRefBase
+{
+public:
+    inline LightRefBase() : mCount(0) { }
+    inline void incStrong(__attribute__((unused)) const void* id) const {
+        mCount.fetch_add(1, std::memory_order_relaxed);
+    }
+    inline void decStrong(__attribute__((unused)) const void* id) const {
+        if (mCount.fetch_sub(1, std::memory_order_release) == 1) {
+            std::atomic_thread_fence(std::memory_order_acquire);
+            delete static_cast<const T*>(this);
+        }
+    }
+    //! DEBUGGING ONLY: Get current strong ref count.
+    inline int32_t getStrongCount() const {
+        return mCount.load(std::memory_order_relaxed);
+    }
+
+    typedef LightRefBase<T> basetype;
+
+protected:
+    inline ~LightRefBase() { }
+
+private:
+    friend class ReferenceMover;
+    inline static void renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
+    inline static void renameRefId(T* /*ref*/, const void* /*old_id*/ , const void* /*new_id*/) { }
+
+private:
+    mutable std::atomic<int32_t> mCount;
+};
+
+
+// This is a wrapper around LightRefBase that simply enforces a virtual
+// destructor to eliminate the template requirement of LightRefBase
+class VirtualLightRefBase : public LightRefBase<VirtualLightRefBase> {
+public:
+    virtual ~VirtualLightRefBase() = default;
+};
+
+}; // namespace android
diff --git a/include/utils/List.h b/libutils/include/utils/List.h
similarity index 100%
rename from include/utils/List.h
rename to libutils/include/utils/List.h
diff --git a/libutils/include/utils/Log.h b/libutils/include/utils/Log.h
new file mode 100644
index 0000000..5276a49
--- /dev/null
+++ b/libutils/include/utils/Log.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2005 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.
+ */
+
+//
+// C/C++ logging functions.  See the logging documentation for API details.
+//
+// We'd like these to be available from C code (in case we import some from
+// somewhere), so this has a C interface.
+//
+// The output will be correct when the log file is shared between multiple
+// threads and/or multiple processes so long as the operating system
+// supports O_APPEND.  These calls have mutex-protected data structures
+// and so are NOT reentrant.  Do not use LOG in a signal handler.
+//
+#ifndef _LIBS_UTILS_LOG_H
+#define _LIBS_UTILS_LOG_H
+
+#include <sys/types.h>
+
+#include <log/log.h>
+
+#ifdef __cplusplus
+
+namespace android {
+
+/*
+ * A very simple utility that yells in the log when an operation takes too long.
+ */
+class LogIfSlow {
+public:
+    LogIfSlow(const char* tag, android_LogPriority priority,
+            int timeoutMillis, const char* message);
+    ~LogIfSlow();
+
+private:
+    const char* const mTag;
+    const android_LogPriority mPriority;
+    const int mTimeoutMillis;
+    const char* const mMessage;
+    const int64_t mStart;
+};
+
+/*
+ * Writes the specified debug log message if this block takes longer than the
+ * specified number of milliseconds to run.  Includes the time actually taken.
+ *
+ * {
+ *     ALOGD_IF_SLOW(50, "Excessive delay doing something.");
+ *     doSomething();
+ * }
+ */
+#define ALOGD_IF_SLOW(timeoutMillis, message) \
+    android::LogIfSlow _logIfSlow(LOG_TAG, ANDROID_LOG_DEBUG, timeoutMillis, message);
+
+} // namespace android
+
+#endif // __cplusplus
+
+#endif // _LIBS_UTILS_LOG_H
diff --git a/libutils/include/utils/Looper.h b/libutils/include/utils/Looper.h
new file mode 100644
index 0000000..a62e67f
--- /dev/null
+++ b/libutils/include/utils/Looper.h
@@ -0,0 +1,487 @@
+/*
+ * 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 UTILS_LOOPER_H
+#define UTILS_LOOPER_H
+
+#include <utils/threads.h>
+#include <utils/RefBase.h>
+#include <utils/KeyedVector.h>
+#include <utils/Timers.h>
+
+#include <sys/epoll.h>
+
+namespace android {
+
+/*
+ * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
+ * enums and the signature of Looper_callbackFunc need to align with
+ * that implementation.
+ */
+
+/**
+ * For callback-based event loops, this is the prototype of the function
+ * that is called when a file descriptor event occurs.
+ * It is given the file descriptor it is associated with,
+ * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
+ * and the data pointer that was originally supplied.
+ *
+ * Implementations should return 1 to continue receiving callbacks, or 0
+ * to have this file descriptor and callback unregistered from the looper.
+ */
+typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
+
+/**
+ * A message that can be posted to a Looper.
+ */
+struct Message {
+    Message() : what(0) { }
+    Message(int w) : what(w) { }
+
+    /* The message type. (interpretation is left up to the handler) */
+    int what;
+};
+
+
+/**
+ * Interface for a Looper message handler.
+ *
+ * The Looper holds a strong reference to the message handler whenever it has
+ * a message to deliver to it.  Make sure to call Looper::removeMessages
+ * to remove any pending messages destined for the handler so that the handler
+ * can be destroyed.
+ */
+class MessageHandler : public virtual RefBase {
+protected:
+    virtual ~MessageHandler();
+
+public:
+    /**
+     * Handles a message.
+     */
+    virtual void handleMessage(const Message& message) = 0;
+};
+
+
+/**
+ * A simple proxy that holds a weak reference to a message handler.
+ */
+class WeakMessageHandler : public MessageHandler {
+protected:
+    virtual ~WeakMessageHandler();
+
+public:
+    WeakMessageHandler(const wp<MessageHandler>& handler);
+    virtual void handleMessage(const Message& message);
+
+private:
+    wp<MessageHandler> mHandler;
+};
+
+
+/**
+ * A looper callback.
+ */
+class LooperCallback : public virtual RefBase {
+protected:
+    virtual ~LooperCallback();
+
+public:
+    /**
+     * Handles a poll event for the given file descriptor.
+     * It is given the file descriptor it is associated with,
+     * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
+     * and the data pointer that was originally supplied.
+     *
+     * Implementations should return 1 to continue receiving callbacks, or 0
+     * to have this file descriptor and callback unregistered from the looper.
+     */
+    virtual int handleEvent(int fd, int events, void* data) = 0;
+};
+
+/**
+ * Wraps a Looper_callbackFunc function pointer.
+ */
+class SimpleLooperCallback : public LooperCallback {
+protected:
+    virtual ~SimpleLooperCallback();
+
+public:
+    SimpleLooperCallback(Looper_callbackFunc callback);
+    virtual int handleEvent(int fd, int events, void* data);
+
+private:
+    Looper_callbackFunc mCallback;
+};
+
+/**
+ * A polling loop that supports monitoring file descriptor events, optionally
+ * using callbacks.  The implementation uses epoll() internally.
+ *
+ * A looper can be associated with a thread although there is no requirement that it must be.
+ */
+class Looper : public RefBase {
+protected:
+    virtual ~Looper();
+
+public:
+    enum {
+        /**
+         * Result from Looper_pollOnce() and Looper_pollAll():
+         * The poll was awoken using wake() before the timeout expired
+         * and no callbacks were executed and no other file descriptors were ready.
+         */
+        POLL_WAKE = -1,
+
+        /**
+         * Result from Looper_pollOnce() and Looper_pollAll():
+         * One or more callbacks were executed.
+         */
+        POLL_CALLBACK = -2,
+
+        /**
+         * Result from Looper_pollOnce() and Looper_pollAll():
+         * The timeout expired.
+         */
+        POLL_TIMEOUT = -3,
+
+        /**
+         * Result from Looper_pollOnce() and Looper_pollAll():
+         * An error occurred.
+         */
+        POLL_ERROR = -4,
+    };
+
+    /**
+     * Flags for file descriptor events that a looper can monitor.
+     *
+     * These flag bits can be combined to monitor multiple events at once.
+     */
+    enum {
+        /**
+         * The file descriptor is available for read operations.
+         */
+        EVENT_INPUT = 1 << 0,
+
+        /**
+         * The file descriptor is available for write operations.
+         */
+        EVENT_OUTPUT = 1 << 1,
+
+        /**
+         * The file descriptor has encountered an error condition.
+         *
+         * The looper always sends notifications about errors; it is not necessary
+         * to specify this event flag in the requested event set.
+         */
+        EVENT_ERROR = 1 << 2,
+
+        /**
+         * The file descriptor was hung up.
+         * For example, indicates that the remote end of a pipe or socket was closed.
+         *
+         * The looper always sends notifications about hangups; it is not necessary
+         * to specify this event flag in the requested event set.
+         */
+        EVENT_HANGUP = 1 << 3,
+
+        /**
+         * The file descriptor is invalid.
+         * For example, the file descriptor was closed prematurely.
+         *
+         * The looper always sends notifications about invalid file descriptors; it is not necessary
+         * to specify this event flag in the requested event set.
+         */
+        EVENT_INVALID = 1 << 4,
+    };
+
+    enum {
+        /**
+         * Option for Looper_prepare: this looper will accept calls to
+         * Looper_addFd() that do not have a callback (that is provide NULL
+         * for the callback).  In this case the caller of Looper_pollOnce()
+         * or Looper_pollAll() MUST check the return from these functions to
+         * discover when data is available on such fds and process it.
+         */
+        PREPARE_ALLOW_NON_CALLBACKS = 1<<0
+    };
+
+    /**
+     * Creates a looper.
+     *
+     * If allowNonCallbaks is true, the looper will allow file descriptors to be
+     * registered without associated callbacks.  This assumes that the caller of
+     * pollOnce() is prepared to handle callback-less events itself.
+     */
+    Looper(bool allowNonCallbacks);
+
+    /**
+     * Returns whether this looper instance allows the registration of file descriptors
+     * using identifiers instead of callbacks.
+     */
+    bool getAllowNonCallbacks() const;
+
+    /**
+     * Waits for events to be available, with optional timeout in milliseconds.
+     * Invokes callbacks for all file descriptors on which an event occurred.
+     *
+     * If the timeout is zero, returns immediately without blocking.
+     * If the timeout is negative, waits indefinitely until an event appears.
+     *
+     * Returns POLL_WAKE if the poll was awoken using wake() before
+     * the timeout expired and no callbacks were invoked and no other file
+     * descriptors were ready.
+     *
+     * Returns POLL_CALLBACK if one or more callbacks were invoked.
+     *
+     * Returns POLL_TIMEOUT if there was no data before the given
+     * timeout expired.
+     *
+     * Returns POLL_ERROR if an error occurred.
+     *
+     * Returns a value >= 0 containing an identifier if its file descriptor has data
+     * and it has no callback function (requiring the caller here to handle it).
+     * In this (and only this) case outFd, outEvents and outData will contain the poll
+     * events and data associated with the fd, otherwise they will be set to NULL.
+     *
+     * This method does not return until it has finished invoking the appropriate callbacks
+     * for all file descriptors that were signalled.
+     */
+    int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
+    inline int pollOnce(int timeoutMillis) {
+        return pollOnce(timeoutMillis, NULL, NULL, NULL);
+    }
+
+    /**
+     * Like pollOnce(), but performs all pending callbacks until all
+     * data has been consumed or a file descriptor is available with no callback.
+     * This function will never return POLL_CALLBACK.
+     */
+    int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
+    inline int pollAll(int timeoutMillis) {
+        return pollAll(timeoutMillis, NULL, NULL, NULL);
+    }
+
+    /**
+     * Wakes the poll asynchronously.
+     *
+     * This method can be called on any thread.
+     * This method returns immediately.
+     */
+    void wake();
+
+    /**
+     * Adds a new file descriptor to be polled by the looper.
+     * If the same file descriptor was previously added, it is replaced.
+     *
+     * "fd" is the file descriptor to be added.
+     * "ident" is an identifier for this event, which is returned from pollOnce().
+     * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
+     * "events" are the poll events to wake up on.  Typically this is EVENT_INPUT.
+     * "callback" is the function to call when there is an event on the file descriptor.
+     * "data" is a private data pointer to supply to the callback.
+     *
+     * There are two main uses of this function:
+     *
+     * (1) If "callback" is non-NULL, then this function will be called when there is
+     * data on the file descriptor.  It should execute any events it has pending,
+     * appropriately reading from the file descriptor.  The 'ident' is ignored in this case.
+     *
+     * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
+     * when its file descriptor has data available, requiring the caller to take
+     * care of processing it.
+     *
+     * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
+     *
+     * This method can be called on any thread.
+     * This method may block briefly if it needs to wake the poll.
+     *
+     * The callback may either be specified as a bare function pointer or as a smart
+     * pointer callback object.  The smart pointer should be preferred because it is
+     * easier to avoid races when the callback is removed from a different thread.
+     * See removeFd() for details.
+     */
+    int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
+    int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
+
+    /**
+     * Removes a previously added file descriptor from the looper.
+     *
+     * When this method returns, it is safe to close the file descriptor since the looper
+     * will no longer have a reference to it.  However, it is possible for the callback to
+     * already be running or for it to run one last time if the file descriptor was already
+     * signalled.  Calling code is responsible for ensuring that this case is safely handled.
+     * For example, if the callback takes care of removing itself during its own execution either
+     * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
+     * again at any later time unless registered anew.
+     *
+     * A simple way to avoid this problem is to use the version of addFd() that takes
+     * a sp<LooperCallback> instead of a bare function pointer.  The LooperCallback will
+     * be released at the appropriate time by the Looper.
+     *
+     * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
+     *
+     * This method can be called on any thread.
+     * This method may block briefly if it needs to wake the poll.
+     */
+    int removeFd(int fd);
+
+    /**
+     * Enqueues a message to be processed by the specified handler.
+     *
+     * The handler must not be null.
+     * This method can be called on any thread.
+     */
+    void sendMessage(const sp<MessageHandler>& handler, const Message& message);
+
+    /**
+     * Enqueues a message to be processed by the specified handler after all pending messages
+     * after the specified delay.
+     *
+     * The time delay is specified in uptime nanoseconds.
+     * The handler must not be null.
+     * This method can be called on any thread.
+     */
+    void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
+            const Message& message);
+
+    /**
+     * Enqueues a message to be processed by the specified handler after all pending messages
+     * at the specified time.
+     *
+     * The time is specified in uptime nanoseconds.
+     * The handler must not be null.
+     * This method can be called on any thread.
+     */
+    void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
+            const Message& message);
+
+    /**
+     * Removes all messages for the specified handler from the queue.
+     *
+     * The handler must not be null.
+     * This method can be called on any thread.
+     */
+    void removeMessages(const sp<MessageHandler>& handler);
+
+    /**
+     * Removes all messages of a particular type for the specified handler from the queue.
+     *
+     * The handler must not be null.
+     * This method can be called on any thread.
+     */
+    void removeMessages(const sp<MessageHandler>& handler, int what);
+
+    /**
+     * Returns whether this looper's thread is currently polling for more work to do.
+     * This is a good signal that the loop is still alive rather than being stuck
+     * handling a callback.  Note that this method is intrinsically racy, since the
+     * state of the loop can change before you get the result back.
+     */
+    bool isPolling() const;
+
+    /**
+     * Prepares a looper associated with the calling thread, and returns it.
+     * If the thread already has a looper, it is returned.  Otherwise, a new
+     * one is created, associated with the thread, and returned.
+     *
+     * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
+     */
+    static sp<Looper> prepare(int opts);
+
+    /**
+     * Sets the given looper to be associated with the calling thread.
+     * If another looper is already associated with the thread, it is replaced.
+     *
+     * If "looper" is NULL, removes the currently associated looper.
+     */
+    static void setForThread(const sp<Looper>& looper);
+
+    /**
+     * Returns the looper associated with the calling thread, or NULL if
+     * there is not one.
+     */
+    static sp<Looper> getForThread();
+
+private:
+    struct Request {
+        int fd;
+        int ident;
+        int events;
+        int seq;
+        sp<LooperCallback> callback;
+        void* data;
+
+        void initEventItem(struct epoll_event* eventItem) const;
+    };
+
+    struct Response {
+        int events;
+        Request request;
+    };
+
+    struct MessageEnvelope {
+        MessageEnvelope() : uptime(0) { }
+
+        MessageEnvelope(nsecs_t u, const sp<MessageHandler> h,
+                const Message& m) : uptime(u), handler(h), message(m) {
+        }
+
+        nsecs_t uptime;
+        sp<MessageHandler> handler;
+        Message message;
+    };
+
+    const bool mAllowNonCallbacks; // immutable
+
+    int mWakeEventFd;  // immutable
+    Mutex mLock;
+
+    Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
+    bool mSendingMessage; // guarded by mLock
+
+    // Whether we are currently waiting for work.  Not protected by a lock,
+    // any use of it is racy anyway.
+    volatile bool mPolling;
+
+    int mEpollFd; // guarded by mLock but only modified on the looper thread
+    bool mEpollRebuildRequired; // guarded by mLock
+
+    // Locked list of file descriptor monitoring requests.
+    KeyedVector<int, Request> mRequests;  // guarded by mLock
+    int mNextRequestSeq;
+
+    // This state is only used privately by pollOnce and does not require a lock since
+    // it runs on a single thread.
+    Vector<Response> mResponses;
+    size_t mResponseIndex;
+    nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
+
+    int pollInner(int timeoutMillis);
+    int removeFd(int fd, int seq);
+    void awoken();
+    void pushResponse(int events, const Request& request);
+    void rebuildEpollLocked();
+    void scheduleEpollRebuildLocked();
+
+    static void initTLSKey();
+    static void threadDestructor(void *st);
+    static void initEpollEvent(struct epoll_event* eventItem);
+};
+
+} // namespace android
+
+#endif // UTILS_LOOPER_H
diff --git a/libutils/include/utils/LruCache.h b/libutils/include/utils/LruCache.h
new file mode 100644
index 0000000..89dccd6
--- /dev/null
+++ b/libutils/include/utils/LruCache.h
@@ -0,0 +1,298 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_UTILS_LRU_CACHE_H
+#define ANDROID_UTILS_LRU_CACHE_H
+
+#include <memory>
+#include <unordered_set>
+
+#include "utils/TypeHelpers.h"  // hash_t
+
+namespace android {
+
+/**
+ * GenerationCache callback used when an item is removed
+ */
+template<typename EntryKey, typename EntryValue>
+class OnEntryRemoved {
+public:
+    virtual ~OnEntryRemoved() { };
+    virtual void operator()(EntryKey& key, EntryValue& value) = 0;
+}; // class OnEntryRemoved
+
+template <typename TKey, typename TValue>
+class LruCache {
+public:
+    explicit LruCache(uint32_t maxCapacity);
+    virtual ~LruCache();
+
+    enum Capacity {
+        kUnlimitedCapacity,
+    };
+
+    void setOnEntryRemovedListener(OnEntryRemoved<TKey, TValue>* listener);
+    size_t size() const;
+    const TValue& get(const TKey& key);
+    bool put(const TKey& key, const TValue& value);
+    bool remove(const TKey& key);
+    bool removeOldest();
+    void clear();
+    const TValue& peekOldestValue();
+
+private:
+    LruCache(const LruCache& that);  // disallow copy constructor
+
+    // Super class so that we can have entries having only a key reference, for searches.
+    class KeyedEntry {
+    public:
+        virtual const TKey& getKey() const = 0;
+        // Make sure the right destructor is executed so that keys and values are deleted.
+        virtual ~KeyedEntry() {}
+    };
+
+    class Entry final : public KeyedEntry {
+    public:
+        TKey key;
+        TValue value;
+        Entry* parent;
+        Entry* child;
+
+        Entry(TKey _key, TValue _value) : key(_key), value(_value), parent(NULL), child(NULL) {
+        }
+        const TKey& getKey() const final { return key; }
+    };
+
+    class EntryForSearch : public KeyedEntry {
+    public:
+        const TKey& key;
+        EntryForSearch(const TKey& key_) : key(key_) {
+        }
+        const TKey& getKey() const final { return key; }
+    };
+
+    struct HashForEntry : public std::unary_function<KeyedEntry*, hash_t> {
+        size_t operator() (const KeyedEntry* entry) const {
+            return hash_type(entry->getKey());
+        };
+    };
+
+    struct EqualityForHashedEntries : public std::unary_function<KeyedEntry*, hash_t> {
+        bool operator() (const KeyedEntry* lhs, const KeyedEntry* rhs) const {
+            return lhs->getKey() == rhs->getKey();
+        };
+    };
+
+    // All entries in the set will be Entry*. Using the weaker KeyedEntry as to allow entries
+    // that have only a key reference, for searching.
+    typedef std::unordered_set<KeyedEntry*, HashForEntry, EqualityForHashedEntries> LruCacheSet;
+
+    void attachToCache(Entry& entry);
+    void detachFromCache(Entry& entry);
+
+    typename LruCacheSet::iterator findByKey(const TKey& key) {
+        EntryForSearch entryForSearch(key);
+        typename LruCacheSet::iterator result = mSet->find(&entryForSearch);
+        return result;
+    }
+
+    std::unique_ptr<LruCacheSet> mSet;
+    OnEntryRemoved<TKey, TValue>* mListener;
+    Entry* mOldest;
+    Entry* mYoungest;
+    uint32_t mMaxCapacity;
+    TValue mNullValue;
+
+public:
+    // To be used like:
+    // while (it.next()) {
+    //   it.value(); it.key();
+    // }
+    class Iterator {
+    public:
+        Iterator(const LruCache<TKey, TValue>& cache):
+                mCache(cache), mIterator(mCache.mSet->begin()), mBeginReturned(false) {
+        }
+
+        bool next() {
+            if (mIterator == mCache.mSet->end()) {
+                return false;
+            }
+            if (!mBeginReturned) {
+                // mIterator has been initialized to the beginning and
+                // hasn't been returned. Do not advance:
+                mBeginReturned = true;
+            } else {
+                std::advance(mIterator, 1);
+            }
+            bool ret = (mIterator != mCache.mSet->end());
+            return ret;
+        }
+
+        const TValue& value() const {
+            // All the elements in the set are of type Entry. See comment in the definition
+            // of LruCacheSet above.
+            return reinterpret_cast<Entry *>(*mIterator)->value;
+        }
+
+        const TKey& key() const {
+            return (*mIterator)->getKey();
+        }
+    private:
+        const LruCache<TKey, TValue>& mCache;
+        typename LruCacheSet::iterator mIterator;
+        bool mBeginReturned;
+    };
+};
+
+// Implementation is here, because it's fully templated
+template <typename TKey, typename TValue>
+LruCache<TKey, TValue>::LruCache(uint32_t maxCapacity)
+    : mSet(new LruCacheSet())
+    , mListener(NULL)
+    , mOldest(NULL)
+    , mYoungest(NULL)
+    , mMaxCapacity(maxCapacity)
+    , mNullValue(0) {
+    mSet->max_load_factor(1.0);
+};
+
+template <typename TKey, typename TValue>
+LruCache<TKey, TValue>::~LruCache() {
+    // Need to delete created entries.
+    clear();
+};
+
+template<typename K, typename V>
+void LruCache<K, V>::setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener) {
+    mListener = listener;
+}
+
+template <typename TKey, typename TValue>
+size_t LruCache<TKey, TValue>::size() const {
+    return mSet->size();
+}
+
+template <typename TKey, typename TValue>
+const TValue& LruCache<TKey, TValue>::get(const TKey& key) {
+    typename LruCacheSet::const_iterator find_result = findByKey(key);
+    if (find_result == mSet->end()) {
+        return mNullValue;
+    }
+    // All the elements in the set are of type Entry. See comment in the definition
+    // of LruCacheSet above.
+    Entry *entry = reinterpret_cast<Entry*>(*find_result);
+    detachFromCache(*entry);
+    attachToCache(*entry);
+    return entry->value;
+}
+
+template <typename TKey, typename TValue>
+bool LruCache<TKey, TValue>::put(const TKey& key, const TValue& value) {
+    if (mMaxCapacity != kUnlimitedCapacity && size() >= mMaxCapacity) {
+        removeOldest();
+    }
+
+    if (findByKey(key) != mSet->end()) {
+        return false;
+    }
+
+    Entry* newEntry = new Entry(key, value);
+    mSet->insert(newEntry);
+    attachToCache(*newEntry);
+    return true;
+}
+
+template <typename TKey, typename TValue>
+bool LruCache<TKey, TValue>::remove(const TKey& key) {
+    typename LruCacheSet::const_iterator find_result = findByKey(key);
+    if (find_result == mSet->end()) {
+        return false;
+    }
+    // All the elements in the set are of type Entry. See comment in the definition
+    // of LruCacheSet above.
+    Entry* entry = reinterpret_cast<Entry*>(*find_result);
+    mSet->erase(entry);
+    if (mListener) {
+        (*mListener)(entry->key, entry->value);
+    }
+    detachFromCache(*entry);
+    delete entry;
+    return true;
+}
+
+template <typename TKey, typename TValue>
+bool LruCache<TKey, TValue>::removeOldest() {
+    if (mOldest != NULL) {
+        return remove(mOldest->key);
+        // TODO: should probably abort if false
+    }
+    return false;
+}
+
+template <typename TKey, typename TValue>
+const TValue& LruCache<TKey, TValue>::peekOldestValue() {
+    if (mOldest) {
+        return mOldest->value;
+    }
+    return mNullValue;
+}
+
+template <typename TKey, typename TValue>
+void LruCache<TKey, TValue>::clear() {
+    if (mListener) {
+        for (Entry* p = mOldest; p != NULL; p = p->child) {
+            (*mListener)(p->key, p->value);
+        }
+    }
+    mYoungest = NULL;
+    mOldest = NULL;
+    for (auto entry : *mSet.get()) {
+        delete entry;
+    }
+    mSet->clear();
+}
+
+template <typename TKey, typename TValue>
+void LruCache<TKey, TValue>::attachToCache(Entry& entry) {
+    if (mYoungest == NULL) {
+        mYoungest = mOldest = &entry;
+    } else {
+        entry.parent = mYoungest;
+        mYoungest->child = &entry;
+        mYoungest = &entry;
+    }
+}
+
+template <typename TKey, typename TValue>
+void LruCache<TKey, TValue>::detachFromCache(Entry& entry) {
+    if (entry.parent != NULL) {
+        entry.parent->child = entry.child;
+    } else {
+        mOldest = entry.child;
+    }
+    if (entry.child != NULL) {
+        entry.child->parent = entry.parent;
+    } else {
+        mYoungest = entry.parent;
+    }
+
+    entry.parent = NULL;
+    entry.child = NULL;
+}
+
+}
+#endif // ANDROID_UTILS_LRU_CACHE_H
diff --git a/libutils/include/utils/Mutex.h b/libutils/include/utils/Mutex.h
new file mode 100644
index 0000000..d106185
--- /dev/null
+++ b/libutils/include/utils/Mutex.h
@@ -0,0 +1,167 @@
+/*
+ * 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_UTILS_MUTEX_H
+#define _LIBS_UTILS_MUTEX_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <time.h>
+
+#if !defined(_WIN32)
+# include <pthread.h>
+#endif
+
+#include <utils/Errors.h>
+#include <utils/Timers.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+// ---------------------------------------------------------------------------
+
+class Condition;
+
+/*
+ * NOTE: This class is for code that builds on Win32.  Its usage is
+ * deprecated for code which doesn't build for Win32.  New code which
+ * doesn't build for Win32 should use std::mutex and std::lock_guard instead.
+ *
+ * Simple mutex class.  The implementation is system-dependent.
+ *
+ * The mutex must be unlocked by the thread that locked it.  They are not
+ * recursive, i.e. the same thread can't lock it multiple times.
+ */
+class Mutex {
+public:
+    enum {
+        PRIVATE = 0,
+        SHARED = 1
+    };
+
+                Mutex();
+    explicit    Mutex(const char* name);
+    explicit    Mutex(int type, const char* name = NULL);
+                ~Mutex();
+
+    // lock or unlock the mutex
+    status_t    lock();
+    void        unlock();
+
+    // lock if possible; returns 0 on success, error otherwise
+    status_t    tryLock();
+
+#if defined(__ANDROID__)
+    // Lock the mutex, but don't wait longer than timeoutNs (relative time).
+    // Returns 0 on success, TIMED_OUT for failure due to timeout expiration.
+    //
+    // OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep
+    // capabilities consistent across host OSes, this method is only available
+    // when building Android binaries.
+    //
+    // FIXME?: pthread_mutex_timedlock is based on CLOCK_REALTIME,
+    // which is subject to NTP adjustments, and includes time during suspend,
+    // so a timeout may occur even though no processes could run.
+    // Not holding a partial wakelock may lead to a system suspend.
+    status_t    timedLock(nsecs_t timeoutNs);
+#endif
+
+    // Manages the mutex automatically. It'll be locked when Autolock is
+    // constructed and released when Autolock goes out of scope.
+    class Autolock {
+    public:
+        inline explicit Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }
+        inline explicit Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }
+        inline ~Autolock() { mLock.unlock(); }
+    private:
+        Mutex& mLock;
+    };
+
+private:
+    friend class Condition;
+
+    // A mutex cannot be copied
+                Mutex(const Mutex&);
+    Mutex&      operator = (const Mutex&);
+
+#if !defined(_WIN32)
+    pthread_mutex_t mMutex;
+#else
+    void    _init();
+    void*   mState;
+#endif
+};
+
+// ---------------------------------------------------------------------------
+
+#if !defined(_WIN32)
+
+inline Mutex::Mutex() {
+    pthread_mutex_init(&mMutex, NULL);
+}
+inline Mutex::Mutex(__attribute__((unused)) const char* name) {
+    pthread_mutex_init(&mMutex, NULL);
+}
+inline Mutex::Mutex(int type, __attribute__((unused)) const char* name) {
+    if (type == SHARED) {
+        pthread_mutexattr_t attr;
+        pthread_mutexattr_init(&attr);
+        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
+        pthread_mutex_init(&mMutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+    } else {
+        pthread_mutex_init(&mMutex, NULL);
+    }
+}
+inline Mutex::~Mutex() {
+    pthread_mutex_destroy(&mMutex);
+}
+inline status_t Mutex::lock() {
+    return -pthread_mutex_lock(&mMutex);
+}
+inline void Mutex::unlock() {
+    pthread_mutex_unlock(&mMutex);
+}
+inline status_t Mutex::tryLock() {
+    return -pthread_mutex_trylock(&mMutex);
+}
+#if defined(__ANDROID__)
+inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
+    timeoutNs += systemTime(SYSTEM_TIME_REALTIME);
+    const struct timespec ts = {
+        /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
+        /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
+    };
+    return -pthread_mutex_timedlock(&mMutex, &ts);
+}
+#endif
+
+#endif // !defined(_WIN32)
+
+// ---------------------------------------------------------------------------
+
+/*
+ * Automatic mutex.  Declare one of these at the top of a function.
+ * When the function returns, it will go out of scope, and release the
+ * mutex.
+ */
+
+typedef Mutex::Autolock AutoMutex;
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+// ---------------------------------------------------------------------------
+
+#endif // _LIBS_UTILS_MUTEX_H
diff --git a/libutils/include/utils/NativeHandle.h b/libutils/include/utils/NativeHandle.h
new file mode 100644
index 0000000..73fe804
--- /dev/null
+++ b/libutils/include/utils/NativeHandle.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_NATIVE_HANDLE_H
+#define ANDROID_NATIVE_HANDLE_H
+
+#include <utils/RefBase.h>
+#include <utils/StrongPointer.h>
+
+typedef struct native_handle native_handle_t;
+
+namespace android {
+
+class NativeHandle : public LightRefBase<NativeHandle> {
+public:
+    // Create a refcounted wrapper around a native_handle_t, and declare
+    // whether the wrapper owns the handle (so that it should clean up the
+    // handle upon destruction) or not.
+    // If handle is NULL, no NativeHandle will be created.
+    static sp<NativeHandle> create(native_handle_t* handle, bool ownsHandle);
+
+    const native_handle_t* handle() const {
+        return mHandle;
+    }
+
+private:
+    // for access to the destructor
+    friend class LightRefBase<NativeHandle>;
+
+    NativeHandle(native_handle_t* handle, bool ownsHandle);
+    ~NativeHandle();
+
+    native_handle_t* mHandle;
+    bool mOwnsHandle;
+
+    // non-copyable
+    NativeHandle(const NativeHandle&);
+    NativeHandle& operator=(const NativeHandle&);
+};
+
+} // namespace android
+
+#endif // ANDROID_NATIVE_HANDLE_H
diff --git a/include/utils/Printer.h b/libutils/include/utils/Printer.h
similarity index 100%
rename from include/utils/Printer.h
rename to libutils/include/utils/Printer.h
diff --git a/include/utils/ProcessCallStack.h b/libutils/include/utils/ProcessCallStack.h
similarity index 100%
rename from include/utils/ProcessCallStack.h
rename to libutils/include/utils/ProcessCallStack.h
diff --git a/include/utils/PropertyMap.h b/libutils/include/utils/PropertyMap.h
similarity index 100%
rename from include/utils/PropertyMap.h
rename to libutils/include/utils/PropertyMap.h
diff --git a/libutils/include/utils/RWLock.h b/libutils/include/utils/RWLock.h
new file mode 100644
index 0000000..d5b81d3
--- /dev/null
+++ b/libutils/include/utils/RWLock.h
@@ -0,0 +1,126 @@
+/*
+ * 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_UTILS_RWLOCK_H
+#define _LIBS_UTILS_RWLOCK_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#if !defined(_WIN32)
+# include <pthread.h>
+#endif
+
+#include <utils/Errors.h>
+#include <utils/ThreadDefs.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+// ---------------------------------------------------------------------------
+
+#if !defined(_WIN32)
+
+/*
+ * Simple mutex class.  The implementation is system-dependent.
+ *
+ * The mutex must be unlocked by the thread that locked it.  They are not
+ * recursive, i.e. the same thread can't lock it multiple times.
+ */
+class RWLock {
+public:
+    enum {
+        PRIVATE = 0,
+        SHARED = 1
+    };
+
+                RWLock();
+    explicit    RWLock(const char* name);
+    explicit    RWLock(int type, const char* name = NULL);
+                ~RWLock();
+
+    status_t    readLock();
+    status_t    tryReadLock();
+    status_t    writeLock();
+    status_t    tryWriteLock();
+    void        unlock();
+
+    class AutoRLock {
+    public:
+        inline explicit AutoRLock(RWLock& rwlock) : mLock(rwlock)  { mLock.readLock(); }
+        inline ~AutoRLock() { mLock.unlock(); }
+    private:
+        RWLock& mLock;
+    };
+
+    class AutoWLock {
+    public:
+        inline explicit AutoWLock(RWLock& rwlock) : mLock(rwlock)  { mLock.writeLock(); }
+        inline ~AutoWLock() { mLock.unlock(); }
+    private:
+        RWLock& mLock;
+    };
+
+private:
+    // A RWLock cannot be copied
+                RWLock(const RWLock&);
+   RWLock&      operator = (const RWLock&);
+
+   pthread_rwlock_t mRWLock;
+};
+
+inline RWLock::RWLock() {
+    pthread_rwlock_init(&mRWLock, NULL);
+}
+inline RWLock::RWLock(__attribute__((unused)) const char* name) {
+    pthread_rwlock_init(&mRWLock, NULL);
+}
+inline RWLock::RWLock(int type, __attribute__((unused)) const char* name) {
+    if (type == SHARED) {
+        pthread_rwlockattr_t attr;
+        pthread_rwlockattr_init(&attr);
+        pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
+        pthread_rwlock_init(&mRWLock, &attr);
+        pthread_rwlockattr_destroy(&attr);
+    } else {
+        pthread_rwlock_init(&mRWLock, NULL);
+    }
+}
+inline RWLock::~RWLock() {
+    pthread_rwlock_destroy(&mRWLock);
+}
+inline status_t RWLock::readLock() {
+    return -pthread_rwlock_rdlock(&mRWLock);
+}
+inline status_t RWLock::tryReadLock() {
+    return -pthread_rwlock_tryrdlock(&mRWLock);
+}
+inline status_t RWLock::writeLock() {
+    return -pthread_rwlock_wrlock(&mRWLock);
+}
+inline status_t RWLock::tryWriteLock() {
+    return -pthread_rwlock_trywrlock(&mRWLock);
+}
+inline void RWLock::unlock() {
+    pthread_rwlock_unlock(&mRWLock);
+}
+
+#endif // !defined(_WIN32)
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+// ---------------------------------------------------------------------------
+
+#endif // _LIBS_UTILS_RWLOCK_H
diff --git a/libutils/include/utils/RefBase.h b/libutils/include/utils/RefBase.h
new file mode 100644
index 0000000..223b666
--- /dev/null
+++ b/libutils/include/utils/RefBase.h
@@ -0,0 +1,690 @@
+/*
+ * 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.
+ */
+
+
+// SOME COMMENTS ABOUT USAGE:
+
+// This provides primarily wp<> weak pointer types and RefBase, which work
+// together with sp<> from <StrongPointer.h>.
+
+// sp<> (and wp<>) are a type of smart pointer that use a well defined protocol
+// to operate. As long as the object they are templated with implements that
+// protocol, these smart pointers work. In several places the platform
+// instantiates sp<> with non-RefBase objects; the two are not tied to each
+// other.
+
+// RefBase is such an implementation and it supports strong pointers, weak
+// pointers and some magic features for the binder.
+
+// So, when using RefBase objects, you have the ability to use strong and weak
+// pointers through sp<> and wp<>.
+
+// Normally, when the last strong pointer goes away, the object is destroyed,
+// i.e. it's destructor is called. HOWEVER, parts of its associated memory is not
+// freed until the last weak pointer is released.
+
+// Weak pointers are essentially "safe" pointers. They are always safe to
+// access through promote(). They may return nullptr if the object was
+// destroyed because it ran out of strong pointers. This makes them good candidates
+// for keys in a cache for instance.
+
+// Weak pointers remain valid for comparison purposes even after the underlying
+// object has been destroyed. Even if object A is destroyed and its memory reused
+// for B, A remaining weak pointer to A will not compare equal to one to B.
+// This again makes them attractive for use as keys.
+
+// How is this supposed / intended to be used?
+
+// Our recommendation is to use strong references (sp<>) when there is an
+// ownership relation. e.g. when an object "owns" another one, use a strong
+// ref. And of course use strong refs as arguments of functions (it's extremely
+// rare that a function will take a wp<>).
+
+// Typically a newly allocated object will immediately be used to initialize
+// a strong pointer, which may then be used to construct or assign to other
+// strong and weak pointers.
+
+// Use weak references when there are no ownership relation. e.g. the keys in a
+// cache (you cannot use plain pointers because there is no safe way to acquire
+// a strong reference from a vanilla pointer).
+
+// This implies that two objects should never (or very rarely) have sp<> on
+// each other, because they can't both own each other.
+
+
+// Caveats with reference counting
+
+// Obviously, circular strong references are a big problem; this creates leaks
+// and it's hard to debug -- except it's in fact really easy because RefBase has
+// tons of debugging code for that. It can basically tell you exactly where the
+// leak is.
+
+// Another problem has to do with destructors with side effects. You must
+// assume that the destructor of reference counted objects can be called AT ANY
+// TIME. For instance code as simple as this:
+
+// void setStuff(const sp<Stuff>& stuff) {
+//   std::lock_guard<std::mutex> lock(mMutex);
+//   mStuff = stuff;
+// }
+
+// is very dangerous. This code WILL deadlock one day or another.
+
+// What isn't obvious is that ~Stuff() can be called as a result of the
+// assignment. And it gets called with the lock held. First of all, the lock is
+// protecting mStuff, not ~Stuff(). Secondly, if ~Stuff() uses its own internal
+// mutex, now you have mutex ordering issues.  Even worse, if ~Stuff() is
+// virtual, now you're calling into "user" code (potentially), by that, I mean,
+// code you didn't even write.
+
+// A correct way to write this code is something like:
+
+// void setStuff(const sp<Stuff>& stuff) {
+//   std::unique_lock<std::mutex> lock(mMutex);
+//   sp<Stuff> hold = mStuff;
+//   mStuff = stuff;
+//   lock.unlock();
+// }
+
+// More importantly, reference counted objects should do as little work as
+// possible in their destructor, or at least be mindful that their destructor
+// could be called from very weird and unintended places.
+
+// Other more specific restrictions for wp<> and sp<>:
+
+// Do not construct a strong pointer to "this" in an object's constructor.
+// The onFirstRef() callback would be made on an incompletely constructed
+// object.
+// Construction of a weak pointer to "this" in an object's constructor is also
+// discouraged. But the implementation was recently changed so that, in the
+// absence of extendObjectLifetime() calls, weak pointers no longer impact
+// object lifetime, and hence this no longer risks premature deallocation,
+// and hence usually works correctly.
+
+// Such strong or weak pointers can be safely created in the RefBase onFirstRef()
+// callback.
+
+// Use of wp::unsafe_get() for any purpose other than debugging is almost
+// always wrong.  Unless you somehow know that there is a longer-lived sp<> to
+// the same object, it may well return a pointer to a deallocated object that
+// has since been reallocated for a different purpose. (And if you know there
+// is a longer-lived sp<>, why not use an sp<> directly?) A wp<> should only be
+// dereferenced by using promote().
+
+// Any object inheriting from RefBase should always be destroyed as the result
+// of a reference count decrement, not via any other means.  Such objects
+// should never be stack allocated, or appear directly as data members in other
+// objects. Objects inheriting from RefBase should have their strong reference
+// count incremented as soon as possible after construction. Usually this
+// will be done via construction of an sp<> to the object, but may instead
+// involve other means of calling RefBase::incStrong().
+// Explicitly deleting or otherwise destroying a RefBase object with outstanding
+// wp<> or sp<> pointers to it will result in an abort or heap corruption.
+
+// It is particularly important not to mix sp<> and direct storage management
+// since the sp from raw pointer constructor is implicit. Thus if a RefBase-
+// -derived object of type T is managed without ever incrementing its strong
+// count, and accidentally passed to f(sp<T>), a strong pointer to the object
+// will be temporarily constructed and destroyed, prematurely deallocating the
+// object, and resulting in heap corruption. None of this would be easily
+// visible in the source.
+
+// Extra Features:
+
+// RefBase::extendObjectLifetime() can be used to prevent destruction of the
+// object while there are still weak references. This is really special purpose
+// functionality to support Binder.
+
+// Wp::promote(), implemented via the attemptIncStrong() member function, is
+// used to try to convert a weak pointer back to a strong pointer.  It's the
+// normal way to try to access the fields of an object referenced only through
+// a wp<>.  Binder code also sometimes uses attemptIncStrong() directly.
+
+// RefBase provides a number of additional callbacks for certain reference count
+// events, as well as some debugging facilities.
+
+// Debugging support can be enabled by turning on DEBUG_REFS in RefBase.cpp.
+// Otherwise little checking is provided.
+
+// Thread safety:
+
+// Like std::shared_ptr, sp<> and wp<> allow concurrent accesses to DIFFERENT
+// sp<> and wp<> instances that happen to refer to the same underlying object.
+// They do NOT support concurrent access (where at least one access is a write)
+// to THE SAME sp<> or wp<>.  In effect, their thread-safety properties are
+// exactly like those of T*, NOT atomic<T*>.
+
+#ifndef ANDROID_REF_BASE_H
+#define ANDROID_REF_BASE_H
+
+#include <atomic>
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <stdlib.h>
+#include <string.h>
+
+// LightRefBase used to be declared in this header, so we have to include it
+#include <utils/LightRefBase.h>
+
+#include <utils/StrongPointer.h>
+#include <utils/TypeHelpers.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+
+class TextOutput;
+TextOutput& printWeakPointer(TextOutput& to, const void* val);
+
+// ---------------------------------------------------------------------------
+
+#define COMPARE_WEAK(_op_)                                      \
+inline bool operator _op_ (const sp<T>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}                                                               \
+inline bool operator _op_ (const T* o) const {                  \
+    return m_ptr _op_ o;                                        \
+}                                                               \
+template<typename U>                                            \
+inline bool operator _op_ (const sp<U>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}                                                               \
+template<typename U>                                            \
+inline bool operator _op_ (const U* o) const {                  \
+    return m_ptr _op_ o;                                        \
+}
+
+// ---------------------------------------------------------------------------
+
+// RefererenceRenamer is pure abstract, there is no virtual method
+// implementation to put in a translation unit in order to silence the
+// weak vtables warning.
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wweak-vtables"
+#endif
+
+class ReferenceRenamer {
+protected:
+    // destructor is purposely not virtual so we avoid code overhead from
+    // subclasses; we have to make it protected to guarantee that it
+    // cannot be called from this base class (and to make strict compilers
+    // happy).
+    ~ReferenceRenamer() { }
+public:
+    virtual void operator()(size_t i) const = 0;
+};
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+// ---------------------------------------------------------------------------
+
+class RefBase
+{
+public:
+            void            incStrong(const void* id) const;
+            void            decStrong(const void* id) const;
+    
+            void            forceIncStrong(const void* id) const;
+
+            //! DEBUGGING ONLY: Get current strong ref count.
+            int32_t         getStrongCount() const;
+
+    class weakref_type
+    {
+    public:
+        RefBase*            refBase() const;
+
+        void                incWeak(const void* id);
+        void                decWeak(const void* id);
+
+        // acquires a strong reference if there is already one.
+        bool                attemptIncStrong(const void* id);
+
+        // acquires a weak reference if there is already one.
+        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
+        // for proper use.
+        bool                attemptIncWeak(const void* id);
+
+        //! DEBUGGING ONLY: Get current weak ref count.
+        int32_t             getWeakCount() const;
+
+        //! DEBUGGING ONLY: Print references held on object.
+        void                printRefs() const;
+
+        //! DEBUGGING ONLY: Enable tracking for this object.
+        // enable -- enable/disable tracking
+        // retain -- when tracking is enable, if true, then we save a stack trace
+        //           for each reference and dereference; when retain == false, we
+        //           match up references and dereferences and keep only the
+        //           outstanding ones.
+
+        void                trackMe(bool enable, bool retain);
+    };
+
+            weakref_type*   createWeak(const void* id) const;
+            
+            weakref_type*   getWeakRefs() const;
+
+            //! DEBUGGING ONLY: Print references held on object.
+    inline  void            printRefs() const { getWeakRefs()->printRefs(); }
+
+            //! DEBUGGING ONLY: Enable tracking of object.
+    inline  void            trackMe(bool enable, bool retain)
+    { 
+        getWeakRefs()->trackMe(enable, retain); 
+    }
+
+    typedef RefBase basetype;
+
+protected:
+                            RefBase();
+    virtual                 ~RefBase();
+    
+    //! Flags for extendObjectLifetime()
+    enum {
+        OBJECT_LIFETIME_STRONG  = 0x0000,
+        OBJECT_LIFETIME_WEAK    = 0x0001,
+        OBJECT_LIFETIME_MASK    = 0x0001
+    };
+    
+            void            extendObjectLifetime(int32_t mode);
+            
+    //! Flags for onIncStrongAttempted()
+    enum {
+        FIRST_INC_STRONG = 0x0001
+    };
+    
+    // Invoked after creation of initial strong pointer/reference.
+    virtual void            onFirstRef();
+    // Invoked when either the last strong reference goes away, or we need to undo
+    // the effect of an unnecessary onIncStrongAttempted.
+    virtual void            onLastStrongRef(const void* id);
+    // Only called in OBJECT_LIFETIME_WEAK case.  Returns true if OK to promote to
+    // strong reference. May have side effects if it returns true.
+    // The first flags argument is always FIRST_INC_STRONG.
+    // TODO: Remove initial flag argument.
+    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
+    // Invoked in the OBJECT_LIFETIME_WEAK case when the last reference of either
+    // kind goes away.  Unused.
+    // TODO: Remove.
+    virtual void            onLastWeakRef(const void* id);
+
+private:
+    friend class weakref_type;
+    class weakref_impl;
+    
+                            RefBase(const RefBase& o);
+            RefBase&        operator=(const RefBase& o);
+
+private:
+    friend class ReferenceMover;
+
+    static void renameRefs(size_t n, const ReferenceRenamer& renamer);
+
+    static void renameRefId(weakref_type* ref,
+            const void* old_id, const void* new_id);
+
+    static void renameRefId(RefBase* ref,
+            const void* old_id, const void* new_id);
+
+        weakref_impl* const mRefs;
+};
+
+// ---------------------------------------------------------------------------
+
+template <typename T>
+class wp
+{
+public:
+    typedef typename RefBase::weakref_type weakref_type;
+
+    inline wp() : m_ptr(0) { }
+
+    wp(T* other);  // NOLINT(implicit)
+    wp(const wp<T>& other);
+    explicit wp(const sp<T>& other);
+    template<typename U> wp(U* other);  // NOLINT(implicit)
+    template<typename U> wp(const sp<U>& other);  // NOLINT(implicit)
+    template<typename U> wp(const wp<U>& other);  // NOLINT(implicit)
+
+    ~wp();
+
+    // Assignment
+
+    wp& operator = (T* other);
+    wp& operator = (const wp<T>& other);
+    wp& operator = (const sp<T>& other);
+
+    template<typename U> wp& operator = (U* other);
+    template<typename U> wp& operator = (const wp<U>& other);
+    template<typename U> wp& operator = (const sp<U>& other);
+
+    void set_object_and_refs(T* other, weakref_type* refs);
+
+    // promotion to sp
+
+    sp<T> promote() const;
+
+    // Reset
+
+    void clear();
+
+    // Accessors
+
+    inline  weakref_type* get_refs() const { return m_refs; }
+
+    inline  T* unsafe_get() const { return m_ptr; }
+
+    // Operators
+
+    COMPARE_WEAK(==)
+    COMPARE_WEAK(!=)
+    COMPARE_WEAK(>)
+    COMPARE_WEAK(<)
+    COMPARE_WEAK(<=)
+    COMPARE_WEAK(>=)
+
+    inline bool operator == (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
+    }
+    template<typename U>
+    inline bool operator == (const wp<U>& o) const {
+        return m_ptr == o.m_ptr;
+    }
+
+    inline bool operator > (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
+    }
+    template<typename U>
+    inline bool operator > (const wp<U>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
+    }
+
+    inline bool operator < (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
+    }
+    template<typename U>
+    inline bool operator < (const wp<U>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
+    }
+                         inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
+    template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
+                         inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
+    template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
+                         inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
+    template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
+
+private:
+    template<typename Y> friend class sp;
+    template<typename Y> friend class wp;
+
+    T*              m_ptr;
+    weakref_type*   m_refs;
+};
+
+template <typename T>
+TextOutput& operator<<(TextOutput& to, const wp<T>& val);
+
+#undef COMPARE_WEAK
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts below here.
+
+template<typename T>
+wp<T>::wp(T* other)
+    : m_ptr(other)
+{
+    if (other) m_refs = other->createWeak(this);
+}
+
+template<typename T>
+wp<T>::wp(const wp<T>& other)
+    : m_ptr(other.m_ptr), m_refs(other.m_refs)
+{
+    if (m_ptr) m_refs->incWeak(this);
+}
+
+template<typename T>
+wp<T>::wp(const sp<T>& other)
+    : m_ptr(other.m_ptr)
+{
+    if (m_ptr) {
+        m_refs = m_ptr->createWeak(this);
+    }
+}
+
+template<typename T> template<typename U>
+wp<T>::wp(U* other)
+    : m_ptr(other)
+{
+    if (other) m_refs = other->createWeak(this);
+}
+
+template<typename T> template<typename U>
+wp<T>::wp(const wp<U>& other)
+    : m_ptr(other.m_ptr)
+{
+    if (m_ptr) {
+        m_refs = other.m_refs;
+        m_refs->incWeak(this);
+    }
+}
+
+template<typename T> template<typename U>
+wp<T>::wp(const sp<U>& other)
+    : m_ptr(other.m_ptr)
+{
+    if (m_ptr) {
+        m_refs = m_ptr->createWeak(this);
+    }
+}
+
+template<typename T>
+wp<T>::~wp()
+{
+    if (m_ptr) m_refs->decWeak(this);
+}
+
+template<typename T>
+wp<T>& wp<T>::operator = (T* other)
+{
+    weakref_type* newRefs =
+        other ? other->createWeak(this) : 0;
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = other;
+    m_refs = newRefs;
+    return *this;
+}
+
+template<typename T>
+wp<T>& wp<T>::operator = (const wp<T>& other)
+{
+    weakref_type* otherRefs(other.m_refs);
+    T* otherPtr(other.m_ptr);
+    if (otherPtr) otherRefs->incWeak(this);
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = otherPtr;
+    m_refs = otherRefs;
+    return *this;
+}
+
+template<typename T>
+wp<T>& wp<T>::operator = (const sp<T>& other)
+{
+    weakref_type* newRefs =
+        other != NULL ? other->createWeak(this) : 0;
+    T* otherPtr(other.m_ptr);
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = otherPtr;
+    m_refs = newRefs;
+    return *this;
+}
+
+template<typename T> template<typename U>
+wp<T>& wp<T>::operator = (U* other)
+{
+    weakref_type* newRefs =
+        other ? other->createWeak(this) : 0;
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = other;
+    m_refs = newRefs;
+    return *this;
+}
+
+template<typename T> template<typename U>
+wp<T>& wp<T>::operator = (const wp<U>& other)
+{
+    weakref_type* otherRefs(other.m_refs);
+    U* otherPtr(other.m_ptr);
+    if (otherPtr) otherRefs->incWeak(this);
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = otherPtr;
+    m_refs = otherRefs;
+    return *this;
+}
+
+template<typename T> template<typename U>
+wp<T>& wp<T>::operator = (const sp<U>& other)
+{
+    weakref_type* newRefs =
+        other != NULL ? other->createWeak(this) : 0;
+    U* otherPtr(other.m_ptr);
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = otherPtr;
+    m_refs = newRefs;
+    return *this;
+}
+
+template<typename T>
+void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
+{
+    if (other) refs->incWeak(this);
+    if (m_ptr) m_refs->decWeak(this);
+    m_ptr = other;
+    m_refs = refs;
+}
+
+template<typename T>
+sp<T> wp<T>::promote() const
+{
+    sp<T> result;
+    if (m_ptr && m_refs->attemptIncStrong(&result)) {
+        result.set_pointer(m_ptr);
+    }
+    return result;
+}
+
+template<typename T>
+void wp<T>::clear()
+{
+    if (m_ptr) {
+        m_refs->decWeak(this);
+        m_ptr = 0;
+    }
+}
+
+template <typename T>
+inline TextOutput& operator<<(TextOutput& to, const wp<T>& val)
+{
+    return printWeakPointer(to, val.unsafe_get());
+}
+
+// ---------------------------------------------------------------------------
+
+// this class just serves as a namespace so TYPE::moveReferences can stay
+// private.
+class ReferenceMover {
+public:
+    // it would be nice if we could make sure no extra code is generated
+    // for sp<TYPE> or wp<TYPE> when TYPE is a descendant of RefBase:
+    // Using a sp<RefBase> override doesn't work; it's a bit like we wanted
+    // a template<typename TYPE inherits RefBase> template...
+
+    template<typename TYPE> static inline
+    void move_references(sp<TYPE>* dest, sp<TYPE> const* src, size_t n) {
+
+        class Renamer : public ReferenceRenamer {
+            sp<TYPE>* d_;
+            sp<TYPE> const* s_;
+            virtual void operator()(size_t i) const {
+                // The id are known to be the sp<>'s this pointer
+                TYPE::renameRefId(d_[i].get(), &s_[i], &d_[i]);
+            }
+        public:
+            Renamer(sp<TYPE>* d, sp<TYPE> const* s) : d_(d), s_(s) { }
+            virtual ~Renamer() { }
+        };
+
+        memmove(dest, src, n*sizeof(sp<TYPE>));
+        TYPE::renameRefs(n, Renamer(dest, src));
+    }
+
+
+    template<typename TYPE> static inline
+    void move_references(wp<TYPE>* dest, wp<TYPE> const* src, size_t n) {
+
+        class Renamer : public ReferenceRenamer {
+            wp<TYPE>* d_;
+            wp<TYPE> const* s_;
+            virtual void operator()(size_t i) const {
+                // The id are known to be the wp<>'s this pointer
+                TYPE::renameRefId(d_[i].get_refs(), &s_[i], &d_[i]);
+            }
+        public:
+            Renamer(wp<TYPE>* rd, wp<TYPE> const* rs) : d_(rd), s_(rs) { }
+            virtual ~Renamer() { }
+        };
+
+        memmove(dest, src, n*sizeof(wp<TYPE>));
+        TYPE::renameRefs(n, Renamer(dest, src));
+    }
+};
+
+// specialization for moving sp<> and wp<> types.
+// these are used by the [Sorted|Keyed]Vector<> implementations
+// sp<> and wp<> need to be handled specially, because they do not
+// have trivial copy operation in the general case (see RefBase.cpp
+// when DEBUG ops are enabled), but can be implemented very
+// efficiently in most cases.
+
+template<typename TYPE> inline
+void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
+    ReferenceMover::move_references(d, s, n);
+}
+
+template<typename TYPE> inline
+void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
+    ReferenceMover::move_references(d, s, n);
+}
+
+template<typename TYPE> inline
+void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
+    ReferenceMover::move_references(d, s, n);
+}
+
+template<typename TYPE> inline
+void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
+    ReferenceMover::move_references(d, s, n);
+}
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_REF_BASE_H
diff --git a/libutils/include/utils/Singleton.h b/libutils/include/utils/Singleton.h
new file mode 100644
index 0000000..bdb2332
--- /dev/null
+++ b/libutils/include/utils/Singleton.h
@@ -0,0 +1,96 @@
+/*
+ * 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 ANDROID_UTILS_SINGLETON_H
+#define ANDROID_UTILS_SINGLETON_H
+
+#include <stdint.h>
+
+// some vendor code assumes they have atoi() after including this file.
+#include <stdlib.h>
+
+#include <sys/types.h>
+#include <utils/Mutex.h>
+#include <cutils/compiler.h>
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+// Singleton<TYPE> may be used in multiple libraries, only one of which should
+// define the static member variables using ANDROID_SINGLETON_STATIC_INSTANCE.
+// Turn off -Wundefined-var-template so other users don't get:
+// instantiation of variable 'android::Singleton<TYPE>::sLock' required here,
+// but no definition is available
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wundefined-var-template"
+#endif
+
+template <typename TYPE>
+class ANDROID_API Singleton
+{
+public:
+    static TYPE& getInstance() {
+        Mutex::Autolock _l(sLock);
+        TYPE* instance = sInstance;
+        if (instance == 0) {
+            instance = new TYPE();
+            sInstance = instance;
+        }
+        return *instance;
+    }
+
+    static bool hasInstance() {
+        Mutex::Autolock _l(sLock);
+        return sInstance != 0;
+    }
+    
+protected:
+    ~Singleton() { }
+    Singleton() { }
+
+private:
+    Singleton(const Singleton&);
+    Singleton& operator = (const Singleton&);
+    static Mutex sLock;
+    static TYPE* sInstance;
+};
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+/*
+ * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file
+ * (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes,
+ * and avoid to have a copy of them in each compilation units Singleton<TYPE>
+ * is used.
+ * NOTE: we use a version of Mutex ctor that takes a parameter, because
+ * for some unknown reason using the default ctor doesn't emit the variable!
+ */
+
+#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE)                 \
+    template<> ::android::Mutex  \
+        (::android::Singleton< TYPE >::sLock)(::android::Mutex::PRIVATE);  \
+    template<> TYPE* ::android::Singleton< TYPE >::sInstance(0);  \
+    template class ::android::Singleton< TYPE >;
+
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_UTILS_SINGLETON_H
+
diff --git a/libutils/include/utils/SortedVector.h b/libutils/include/utils/SortedVector.h
new file mode 100644
index 0000000..5b2a232
--- /dev/null
+++ b/libutils/include/utils/SortedVector.h
@@ -0,0 +1,294 @@
+/*
+ * Copyright (C) 2005 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_SORTED_VECTOR_H
+#define ANDROID_SORTED_VECTOR_H
+
+#include <assert.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <log/log.h>
+#include <utils/TypeHelpers.h>
+#include <utils/Vector.h>
+#include <utils/VectorImpl.h>
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+template <class TYPE>
+class SortedVector : private SortedVectorImpl
+{
+    friend class Vector<TYPE>;
+
+public:
+            typedef TYPE    value_type;
+
+    /*!
+     * Constructors and destructors
+     */
+
+                            SortedVector();
+                            SortedVector(const SortedVector<TYPE>& rhs);
+    virtual                 ~SortedVector();
+
+    /*! copy operator */
+    const SortedVector<TYPE>&   operator = (const SortedVector<TYPE>& rhs) const;
+    SortedVector<TYPE>&         operator = (const SortedVector<TYPE>& rhs);
+
+    /*
+     * empty the vector
+     */
+
+    inline  void            clear()             { VectorImpl::clear(); }
+
+    /*!
+     * vector stats
+     */
+
+    //! returns number of items in the vector
+    inline  size_t          size() const                { return VectorImpl::size(); }
+    //! returns whether or not the vector is empty
+    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
+    //! returns how many items can be stored without reallocating the backing store
+    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
+    //! sets the capacity. capacity can never be reduced less than size()
+    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
+
+    /*!
+     * C-style array access
+     */
+
+    //! read-only C-style access
+    inline  const TYPE*     array() const;
+
+    //! read-write C-style access. BE VERY CAREFUL when modifying the array
+    //! you must keep it sorted! You usually don't use this function.
+            TYPE*           editArray();
+
+            //! finds the index of an item
+            ssize_t         indexOf(const TYPE& item) const;
+
+            //! finds where this item should be inserted
+            size_t          orderOf(const TYPE& item) const;
+
+
+    /*!
+     * accessors
+     */
+
+    //! read-only access to an item at a given index
+    inline  const TYPE&     operator [] (size_t index) const;
+    //! alternate name for operator []
+    inline  const TYPE&     itemAt(size_t index) const;
+    //! stack-usage of the vector. returns the top of the stack (last element)
+            const TYPE&     top() const;
+
+    /*!
+     * modifying the array
+     */
+
+            //! add an item in the right place (and replace the one that is there)
+            ssize_t         add(const TYPE& item);
+
+            //! editItemAt() MUST NOT change the order of this item
+            TYPE&           editItemAt(size_t index) {
+                return *( static_cast<TYPE *>(VectorImpl::editItemLocation(index)) );
+            }
+
+            //! merges a vector into this one
+            ssize_t         merge(const Vector<TYPE>& vector);
+            ssize_t         merge(const SortedVector<TYPE>& vector);
+
+            //! removes an item
+            ssize_t         remove(const TYPE&);
+
+    //! remove several items
+    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
+    //! remove one item
+    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
+
+    /*
+     * these inlines add some level of compatibility with STL.
+     */
+    typedef TYPE* iterator;
+    typedef TYPE const* const_iterator;
+
+    inline iterator begin() { return editArray(); }
+    inline iterator end()   { return editArray() + size(); }
+    inline const_iterator begin() const { return array(); }
+    inline const_iterator end() const   { return array() + size(); }
+    inline void reserve(size_t n) { setCapacity(n); }
+    inline bool empty() const{ return isEmpty(); }
+    inline iterator erase(iterator pos) {
+        ssize_t index = removeItemsAt(pos-array());
+        return begin() + index;
+    }
+
+protected:
+    virtual void    do_construct(void* storage, size_t num) const;
+    virtual void    do_destroy(void* storage, size_t num) const;
+    virtual void    do_copy(void* dest, const void* from, size_t num) const;
+    virtual void    do_splat(void* dest, const void* item, size_t num) const;
+    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
+    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
+    virtual int     do_compare(const void* lhs, const void* rhs) const;
+};
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts from here...
+// ---------------------------------------------------------------------------
+
+template<class TYPE> inline
+SortedVector<TYPE>::SortedVector()
+    : SortedVectorImpl(sizeof(TYPE),
+                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
+                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
+                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
+                )
+{
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>::SortedVector(const SortedVector<TYPE>& rhs)
+    : SortedVectorImpl(rhs) {
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>::~SortedVector() {
+    finish_vector();
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
+    SortedVectorImpl::operator = (rhs);
+    return *this;
+}
+
+template<class TYPE> inline
+const SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
+    SortedVectorImpl::operator = (rhs);
+    return *this;
+}
+
+template<class TYPE> inline
+const TYPE* SortedVector<TYPE>::array() const {
+    return static_cast<const TYPE *>(arrayImpl());
+}
+
+template<class TYPE> inline
+TYPE* SortedVector<TYPE>::editArray() {
+    return static_cast<TYPE *>(editArrayImpl());
+}
+
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::operator[](size_t index) const {
+    LOG_FATAL_IF(index>=size(),
+            "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__,
+            int(index), int(size()));
+    return *(array() + index);
+}
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::itemAt(size_t index) const {
+    return operator[](index);
+}
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::top() const {
+    return *(array() + size() - 1);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::add(const TYPE& item) {
+    return SortedVectorImpl::add(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::indexOf(const TYPE& item) const {
+    return SortedVectorImpl::indexOf(&item);
+}
+
+template<class TYPE> inline
+size_t SortedVector<TYPE>::orderOf(const TYPE& item) const {
+    return SortedVectorImpl::orderOf(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::merge(const Vector<TYPE>& vector) {
+    return SortedVectorImpl::merge(reinterpret_cast<const VectorImpl&>(vector));
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::merge(const SortedVector<TYPE>& vector) {
+    return SortedVectorImpl::merge(reinterpret_cast<const SortedVectorImpl&>(vector));
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::remove(const TYPE& item) {
+    return SortedVectorImpl::remove(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::removeItemsAt(size_t index, size_t count) {
+    return VectorImpl::removeItemsAt(index, count);
+}
+
+// ---------------------------------------------------------------------------
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void SortedVector<TYPE>::do_construct(void* storage, size_t num) const {
+    construct_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_destroy(void* storage, size_t num) const {
+    destroy_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void SortedVector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
+    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void SortedVector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
+    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void SortedVector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
+    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void SortedVector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
+    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+int SortedVector<TYPE>::do_compare(const void* lhs, const void* rhs) const {
+    return compare_type( *reinterpret_cast<const TYPE*>(lhs), *reinterpret_cast<const TYPE*>(rhs) );
+}
+
+}; // namespace android
+
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_SORTED_VECTOR_H
diff --git a/include/utils/StopWatch.h b/libutils/include/utils/StopWatch.h
similarity index 100%
rename from include/utils/StopWatch.h
rename to libutils/include/utils/StopWatch.h
diff --git a/libutils/include/utils/String16.h b/libutils/include/utils/String16.h
new file mode 100644
index 0000000..f6433a8
--- /dev/null
+++ b/libutils/include/utils/String16.h
@@ -0,0 +1,251 @@
+/*
+ * Copyright (C) 2005 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_STRING16_H
+#define ANDROID_STRING16_H
+
+#include <string> // for std::string
+
+#include <utils/Errors.h>
+#include <utils/String8.h>
+#include <utils/TypeHelpers.h>
+
+// ---------------------------------------------------------------------------
+
+extern "C" {
+
+}
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class SharedBuffer;
+class String8;
+class TextOutput;
+
+//! This is a string holding UTF-16 characters.
+class String16
+{
+public:
+    /* use String16(StaticLinkage) if you're statically linking against
+     * libutils and declaring an empty static String16, e.g.:
+     *
+     *   static String16 sAStaticEmptyString(String16::kEmptyString);
+     *   static String16 sAnotherStaticEmptyString(sAStaticEmptyString);
+     */
+    enum StaticLinkage { kEmptyString };
+
+                                String16();
+    explicit                    String16(StaticLinkage);
+                                String16(const String16& o);
+                                String16(const String16& o,
+                                         size_t len,
+                                         size_t begin=0);
+    explicit                    String16(const char16_t* o);
+    explicit                    String16(const char16_t* o, size_t len);
+    explicit                    String16(const String8& o);
+    explicit                    String16(const char* o);
+    explicit                    String16(const char* o, size_t len);
+
+                                ~String16();
+
+    inline  const char16_t*     string() const;
+
+//TODO(b/35363681): remove
+private:
+    static inline std::string   std_string(const String16& str);
+public:
+            size_t              size() const;
+            void                setTo(const String16& other);
+            status_t            setTo(const char16_t* other);
+            status_t            setTo(const char16_t* other, size_t len);
+            status_t            setTo(const String16& other,
+                                      size_t len,
+                                      size_t begin=0);
+
+            status_t            append(const String16& other);
+            status_t            append(const char16_t* other, size_t len);
+
+    inline  String16&           operator=(const String16& other);
+
+    inline  String16&           operator+=(const String16& other);
+    inline  String16            operator+(const String16& other) const;
+
+            status_t            insert(size_t pos, const char16_t* chrs);
+            status_t            insert(size_t pos,
+                                       const char16_t* chrs, size_t len);
+
+            ssize_t             findFirst(char16_t c) const;
+            ssize_t             findLast(char16_t c) const;
+
+            bool                startsWith(const String16& prefix) const;
+            bool                startsWith(const char16_t* prefix) const;
+
+            bool                contains(const char16_t* chrs) const;
+
+            status_t            makeLower();
+
+            status_t            replaceAll(char16_t replaceThis,
+                                           char16_t withThis);
+
+            status_t            remove(size_t len, size_t begin=0);
+
+    inline  int                 compare(const String16& other) const;
+
+    inline  bool                operator<(const String16& other) const;
+    inline  bool                operator<=(const String16& other) const;
+    inline  bool                operator==(const String16& other) const;
+    inline  bool                operator!=(const String16& other) const;
+    inline  bool                operator>=(const String16& other) const;
+    inline  bool                operator>(const String16& other) const;
+
+    inline  bool                operator<(const char16_t* other) const;
+    inline  bool                operator<=(const char16_t* other) const;
+    inline  bool                operator==(const char16_t* other) const;
+    inline  bool                operator!=(const char16_t* other) const;
+    inline  bool                operator>=(const char16_t* other) const;
+    inline  bool                operator>(const char16_t* other) const;
+
+    inline                      operator const char16_t*() const;
+
+private:
+            const char16_t*     mString;
+};
+
+// String16 can be trivially moved using memcpy() because moving does not
+// require any change to the underlying SharedBuffer contents or reference count.
+ANDROID_TRIVIAL_MOVE_TRAIT(String16)
+
+// ---------------------------------------------------------------------------
+// No user servicable parts below.
+
+inline int compare_type(const String16& lhs, const String16& rhs)
+{
+    return lhs.compare(rhs);
+}
+
+inline int strictly_order_type(const String16& lhs, const String16& rhs)
+{
+    return compare_type(lhs, rhs) < 0;
+}
+
+inline const char16_t* String16::string() const
+{
+    return mString;
+}
+
+inline std::string String16::std_string(const String16& str)
+{
+    return std::string(String8(str).string());
+}
+
+inline String16& String16::operator=(const String16& other)
+{
+    setTo(other);
+    return *this;
+}
+
+inline String16& String16::operator+=(const String16& other)
+{
+    append(other);
+    return *this;
+}
+
+inline String16 String16::operator+(const String16& other) const
+{
+    String16 tmp(*this);
+    tmp += other;
+    return tmp;
+}
+
+inline int String16::compare(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size());
+}
+
+inline bool String16::operator<(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) < 0;
+}
+
+inline bool String16::operator<=(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) <= 0;
+}
+
+inline bool String16::operator==(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) == 0;
+}
+
+inline bool String16::operator!=(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) != 0;
+}
+
+inline bool String16::operator>=(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) >= 0;
+}
+
+inline bool String16::operator>(const String16& other) const
+{
+    return strzcmp16(mString, size(), other.mString, other.size()) > 0;
+}
+
+inline bool String16::operator<(const char16_t* other) const
+{
+    return strcmp16(mString, other) < 0;
+}
+
+inline bool String16::operator<=(const char16_t* other) const
+{
+    return strcmp16(mString, other) <= 0;
+}
+
+inline bool String16::operator==(const char16_t* other) const
+{
+    return strcmp16(mString, other) == 0;
+}
+
+inline bool String16::operator!=(const char16_t* other) const
+{
+    return strcmp16(mString, other) != 0;
+}
+
+inline bool String16::operator>=(const char16_t* other) const
+{
+    return strcmp16(mString, other) >= 0;
+}
+
+inline bool String16::operator>(const char16_t* other) const
+{
+    return strcmp16(mString, other) > 0;
+}
+
+inline String16::operator const char16_t*() const
+{
+    return mString;
+}
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_STRING16_H
diff --git a/libutils/include/utils/String8.h b/libutils/include/utils/String8.h
new file mode 100644
index 0000000..f5f9219
--- /dev/null
+++ b/libutils/include/utils/String8.h
@@ -0,0 +1,414 @@
+/*
+ * Copyright (C) 2005 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_STRING8_H
+#define ANDROID_STRING8_H
+
+#include <string> // for std::string
+
+#include <utils/Errors.h>
+#include <utils/Unicode.h>
+#include <utils/TypeHelpers.h>
+
+#include <string.h> // for strcmp
+#include <stdarg.h>
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+class String16;
+class TextOutput;
+
+//! This is a string holding UTF-8 characters. Does not allow the value more
+// than 0x10FFFF, which is not valid unicode codepoint.
+class String8
+{
+public:
+    /* use String8(StaticLinkage) if you're statically linking against
+     * libutils and declaring an empty static String8, e.g.:
+     *
+     *   static String8 sAStaticEmptyString(String8::kEmptyString);
+     *   static String8 sAnotherStaticEmptyString(sAStaticEmptyString);
+     */
+    enum StaticLinkage { kEmptyString };
+
+                                String8();
+    explicit                    String8(StaticLinkage);
+                                String8(const String8& o);
+    explicit                    String8(const char* o);
+    explicit                    String8(const char* o, size_t numChars);
+
+    explicit                    String8(const String16& o);
+    explicit                    String8(const char16_t* o);
+    explicit                    String8(const char16_t* o, size_t numChars);
+    explicit                    String8(const char32_t* o);
+    explicit                    String8(const char32_t* o, size_t numChars);
+                                ~String8();
+
+    static inline const String8 empty();
+
+    static String8              format(const char* fmt, ...) __attribute__((format (printf, 1, 2)));
+    static String8              formatV(const char* fmt, va_list args);
+
+    inline  const char*         c_str() const;
+    inline  const char*         string() const;
+
+// TODO(b/35363681): remove
+private:
+    static inline std::string   std_string(const String8& str);
+public:
+
+    inline  size_t              size() const;
+    inline  size_t              bytes() const;
+    inline  bool                isEmpty() const;
+
+            size_t              length() const;
+
+            void                clear();
+
+            void                setTo(const String8& other);
+            status_t            setTo(const char* other);
+            status_t            setTo(const char* other, size_t numChars);
+            status_t            setTo(const char16_t* other, size_t numChars);
+            status_t            setTo(const char32_t* other,
+                                      size_t length);
+
+            status_t            append(const String8& other);
+            status_t            append(const char* other);
+            status_t            append(const char* other, size_t numChars);
+
+            status_t            appendFormat(const char* fmt, ...)
+                    __attribute__((format (printf, 2, 3)));
+            status_t            appendFormatV(const char* fmt, va_list args);
+
+            // Note that this function takes O(N) time to calculate the value.
+            // No cache value is stored.
+            size_t              getUtf32Length() const;
+            int32_t             getUtf32At(size_t index,
+                                           size_t *next_index) const;
+            void                getUtf32(char32_t* dst) const;
+
+    inline  String8&            operator=(const String8& other);
+    inline  String8&            operator=(const char* other);
+
+    inline  String8&            operator+=(const String8& other);
+    inline  String8             operator+(const String8& other) const;
+
+    inline  String8&            operator+=(const char* other);
+    inline  String8             operator+(const char* other) const;
+
+    inline  int                 compare(const String8& other) const;
+
+    inline  bool                operator<(const String8& other) const;
+    inline  bool                operator<=(const String8& other) const;
+    inline  bool                operator==(const String8& other) const;
+    inline  bool                operator!=(const String8& other) const;
+    inline  bool                operator>=(const String8& other) const;
+    inline  bool                operator>(const String8& other) const;
+
+    inline  bool                operator<(const char* other) const;
+    inline  bool                operator<=(const char* other) const;
+    inline  bool                operator==(const char* other) const;
+    inline  bool                operator!=(const char* other) const;
+    inline  bool                operator>=(const char* other) const;
+    inline  bool                operator>(const char* other) const;
+
+    inline                      operator const char*() const;
+
+            char*               lockBuffer(size_t size);
+            void                unlockBuffer();
+            status_t            unlockBuffer(size_t size);
+
+            // return the index of the first byte of other in this at or after
+            // start, or -1 if not found
+            ssize_t             find(const char* other, size_t start = 0) const;
+
+            // return true if this string contains the specified substring
+    inline  bool                contains(const char* other) const;
+
+            // removes all occurrence of the specified substring
+            // returns true if any were found and removed
+            bool                removeAll(const char* other);
+
+            void                toLower();
+            void                toLower(size_t start, size_t numChars);
+            void                toUpper();
+            void                toUpper(size_t start, size_t numChars);
+
+
+    /*
+     * These methods operate on the string as if it were a path name.
+     */
+
+    /*
+     * Set the filename field to a specific value.
+     *
+     * Normalizes the filename, removing a trailing '/' if present.
+     */
+    void setPathName(const char* name);
+    void setPathName(const char* name, size_t numChars);
+
+    /*
+     * Get just the filename component.
+     *
+     * "/tmp/foo/bar.c" --> "bar.c"
+     */
+    String8 getPathLeaf(void) const;
+
+    /*
+     * Remove the last (file name) component, leaving just the directory
+     * name.
+     *
+     * "/tmp/foo/bar.c" --> "/tmp/foo"
+     * "/tmp" --> "" // ????? shouldn't this be "/" ???? XXX
+     * "bar.c" --> ""
+     */
+    String8 getPathDir(void) const;
+
+    /*
+     * Retrieve the front (root dir) component.  Optionally also return the
+     * remaining components.
+     *
+     * "/tmp/foo/bar.c" --> "tmp" (remain = "foo/bar.c")
+     * "/tmp" --> "tmp" (remain = "")
+     * "bar.c" --> "bar.c" (remain = "")
+     */
+    String8 walkPath(String8* outRemains = NULL) const;
+
+    /*
+     * Return the filename extension.  This is the last '.' and any number
+     * of characters that follow it.  The '.' is included in case we
+     * decide to expand our definition of what constitutes an extension.
+     *
+     * "/tmp/foo/bar.c" --> ".c"
+     * "/tmp" --> ""
+     * "/tmp/foo.bar/baz" --> ""
+     * "foo.jpeg" --> ".jpeg"
+     * "foo." --> ""
+     */
+    String8 getPathExtension(void) const;
+
+    /*
+     * Return the path without the extension.  Rules for what constitutes
+     * an extension are described in the comment for getPathExtension().
+     *
+     * "/tmp/foo/bar.c" --> "/tmp/foo/bar"
+     */
+    String8 getBasePath(void) const;
+
+    /*
+     * Add a component to the pathname.  We guarantee that there is
+     * exactly one path separator between the old path and the new.
+     * If there is no existing name, we just copy the new name in.
+     *
+     * If leaf is a fully qualified path (i.e. starts with '/', it
+     * replaces whatever was there before.
+     */
+    String8& appendPath(const char* leaf);
+    String8& appendPath(const String8& leaf)  { return appendPath(leaf.string()); }
+
+    /*
+     * Like appendPath(), but does not affect this string.  Returns a new one instead.
+     */
+    String8 appendPathCopy(const char* leaf) const
+                                             { String8 p(*this); p.appendPath(leaf); return p; }
+    String8 appendPathCopy(const String8& leaf) const { return appendPathCopy(leaf.string()); }
+
+    /*
+     * Converts all separators in this string to /, the default path separator.
+     *
+     * If the default OS separator is backslash, this converts all
+     * backslashes to slashes, in-place. Otherwise it does nothing.
+     * Returns self.
+     */
+    String8& convertToResPath();
+
+private:
+            status_t            real_append(const char* other, size_t numChars);
+            char*               find_extension(void) const;
+
+            const char* mString;
+};
+
+// String8 can be trivially moved using memcpy() because moving does not
+// require any change to the underlying SharedBuffer contents or reference count.
+ANDROID_TRIVIAL_MOVE_TRAIT(String8)
+
+// ---------------------------------------------------------------------------
+// No user servicable parts below.
+
+inline int compare_type(const String8& lhs, const String8& rhs)
+{
+    return lhs.compare(rhs);
+}
+
+inline int strictly_order_type(const String8& lhs, const String8& rhs)
+{
+    return compare_type(lhs, rhs) < 0;
+}
+
+inline const String8 String8::empty() {
+    return String8();
+}
+
+inline const char* String8::c_str() const
+{
+    return mString;
+}
+inline const char* String8::string() const
+{
+    return mString;
+}
+
+inline std::string String8::std_string(const String8& str)
+{
+    return std::string(str.string());
+}
+
+inline size_t String8::size() const
+{
+    return length();
+}
+
+inline bool String8::isEmpty() const
+{
+    return length() == 0;
+}
+
+inline size_t String8::bytes() const
+{
+    return length();
+}
+
+inline bool String8::contains(const char* other) const
+{
+    return find(other) >= 0;
+}
+
+inline String8& String8::operator=(const String8& other)
+{
+    setTo(other);
+    return *this;
+}
+
+inline String8& String8::operator=(const char* other)
+{
+    setTo(other);
+    return *this;
+}
+
+inline String8& String8::operator+=(const String8& other)
+{
+    append(other);
+    return *this;
+}
+
+inline String8 String8::operator+(const String8& other) const
+{
+    String8 tmp(*this);
+    tmp += other;
+    return tmp;
+}
+
+inline String8& String8::operator+=(const char* other)
+{
+    append(other);
+    return *this;
+}
+
+inline String8 String8::operator+(const char* other) const
+{
+    String8 tmp(*this);
+    tmp += other;
+    return tmp;
+}
+
+inline int String8::compare(const String8& other) const
+{
+    return strcmp(mString, other.mString);
+}
+
+inline bool String8::operator<(const String8& other) const
+{
+    return strcmp(mString, other.mString) < 0;
+}
+
+inline bool String8::operator<=(const String8& other) const
+{
+    return strcmp(mString, other.mString) <= 0;
+}
+
+inline bool String8::operator==(const String8& other) const
+{
+    return strcmp(mString, other.mString) == 0;
+}
+
+inline bool String8::operator!=(const String8& other) const
+{
+    return strcmp(mString, other.mString) != 0;
+}
+
+inline bool String8::operator>=(const String8& other) const
+{
+    return strcmp(mString, other.mString) >= 0;
+}
+
+inline bool String8::operator>(const String8& other) const
+{
+    return strcmp(mString, other.mString) > 0;
+}
+
+inline bool String8::operator<(const char* other) const
+{
+    return strcmp(mString, other) < 0;
+}
+
+inline bool String8::operator<=(const char* other) const
+{
+    return strcmp(mString, other) <= 0;
+}
+
+inline bool String8::operator==(const char* other) const
+{
+    return strcmp(mString, other) == 0;
+}
+
+inline bool String8::operator!=(const char* other) const
+{
+    return strcmp(mString, other) != 0;
+}
+
+inline bool String8::operator>=(const char* other) const
+{
+    return strcmp(mString, other) >= 0;
+}
+
+inline bool String8::operator>(const char* other) const
+{
+    return strcmp(mString, other) > 0;
+}
+
+inline String8::operator const char*() const
+{
+    return mString;
+}
+
+}  // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_STRING8_H
diff --git a/libutils/include/utils/StrongPointer.h b/libutils/include/utils/StrongPointer.h
new file mode 100644
index 0000000..0c20607
--- /dev/null
+++ b/libutils/include/utils/StrongPointer.h
@@ -0,0 +1,245 @@
+/*
+ * Copyright (C) 2005 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_STRONG_POINTER_H
+#define ANDROID_STRONG_POINTER_H
+
+// ---------------------------------------------------------------------------
+namespace android {
+
+template<typename T> class wp;
+
+// ---------------------------------------------------------------------------
+
+#define COMPARE(_op_)                                           \
+inline bool operator _op_ (const sp<T>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}                                                               \
+inline bool operator _op_ (const T* o) const {                  \
+    return m_ptr _op_ o;                                        \
+}                                                               \
+template<typename U>                                            \
+inline bool operator _op_ (const sp<U>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}                                                               \
+template<typename U>                                            \
+inline bool operator _op_ (const U* o) const {                  \
+    return m_ptr _op_ o;                                        \
+}                                                               \
+inline bool operator _op_ (const wp<T>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}                                                               \
+template<typename U>                                            \
+inline bool operator _op_ (const wp<U>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
+}
+
+// ---------------------------------------------------------------------------
+
+template<typename T>
+class sp {
+public:
+    inline sp() : m_ptr(0) { }
+
+    sp(T* other);  // NOLINT(implicit)
+    sp(const sp<T>& other);
+    sp(sp<T>&& other);
+    template<typename U> sp(U* other);  // NOLINT(implicit)
+    template<typename U> sp(const sp<U>& other);  // NOLINT(implicit)
+    template<typename U> sp(sp<U>&& other);  // NOLINT(implicit)
+
+    ~sp();
+
+    // Assignment
+
+    sp& operator = (T* other);
+    sp& operator = (const sp<T>& other);
+    sp& operator = (sp<T>&& other);
+
+    template<typename U> sp& operator = (const sp<U>& other);
+    template<typename U> sp& operator = (sp<U>&& other);
+    template<typename U> sp& operator = (U* other);
+
+    //! Special optimization for use by ProcessState (and nobody else).
+    void force_set(T* other);
+
+    // Reset
+
+    void clear();
+
+    // Accessors
+
+    inline  T&      operator* () const  { return *m_ptr; }
+    inline  T*      operator-> () const { return m_ptr;  }
+    inline  T*      get() const         { return m_ptr; }
+
+    // Operators
+
+    COMPARE(==)
+    COMPARE(!=)
+    COMPARE(>)
+    COMPARE(<)
+    COMPARE(<=)
+    COMPARE(>=)
+
+private:    
+    template<typename Y> friend class sp;
+    template<typename Y> friend class wp;
+    void set_pointer(T* ptr);
+    T* m_ptr;
+};
+
+// For code size reasons, we do not want this inlined or templated.
+void sp_report_race();
+
+#undef COMPARE
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts below here.
+
+template<typename T>
+sp<T>::sp(T* other)
+        : m_ptr(other) {
+    if (other)
+        other->incStrong(this);
+}
+
+template<typename T>
+sp<T>::sp(const sp<T>& other)
+        : m_ptr(other.m_ptr) {
+    if (m_ptr)
+        m_ptr->incStrong(this);
+}
+
+template<typename T>
+sp<T>::sp(sp<T>&& other)
+        : m_ptr(other.m_ptr) {
+    other.m_ptr = nullptr;
+}
+
+template<typename T> template<typename U>
+sp<T>::sp(U* other)
+        : m_ptr(other) {
+    if (other)
+        (static_cast<T*>(other))->incStrong(this);
+}
+
+template<typename T> template<typename U>
+sp<T>::sp(const sp<U>& other)
+        : m_ptr(other.m_ptr) {
+    if (m_ptr)
+        m_ptr->incStrong(this);
+}
+
+template<typename T> template<typename U>
+sp<T>::sp(sp<U>&& other)
+        : m_ptr(other.m_ptr) {
+    other.m_ptr = nullptr;
+}
+
+template<typename T>
+sp<T>::~sp() {
+    if (m_ptr)
+        m_ptr->decStrong(this);
+}
+
+template<typename T>
+sp<T>& sp<T>::operator =(const sp<T>& other) {
+    // Force m_ptr to be read twice, to heuristically check for data races.
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    T* otherPtr(other.m_ptr);
+    if (otherPtr) otherPtr->incStrong(this);
+    if (oldPtr) oldPtr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = otherPtr;
+    return *this;
+}
+
+template<typename T>
+sp<T>& sp<T>::operator =(sp<T>&& other) {
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    if (oldPtr) oldPtr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = other.m_ptr;
+    other.m_ptr = nullptr;
+    return *this;
+}
+
+template<typename T>
+sp<T>& sp<T>::operator =(T* other) {
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    if (other) other->incStrong(this);
+    if (oldPtr) oldPtr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = other;
+    return *this;
+}
+
+template<typename T> template<typename U>
+sp<T>& sp<T>::operator =(const sp<U>& other) {
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    T* otherPtr(other.m_ptr);
+    if (otherPtr) otherPtr->incStrong(this);
+    if (oldPtr) oldPtr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = otherPtr;
+    return *this;
+}
+
+template<typename T> template<typename U>
+sp<T>& sp<T>::operator =(sp<U>&& other) {
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    if (m_ptr) m_ptr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = other.m_ptr;
+    other.m_ptr = nullptr;
+    return *this;
+}
+
+template<typename T> template<typename U>
+sp<T>& sp<T>::operator =(U* other) {
+    T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+    if (other) (static_cast<T*>(other))->incStrong(this);
+    if (oldPtr) oldPtr->decStrong(this);
+    if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
+    m_ptr = other;
+    return *this;
+}
+
+template<typename T>
+void sp<T>::force_set(T* other) {
+    other->forceIncStrong(this);
+    m_ptr = other;
+}
+
+template<typename T>
+void sp<T>::clear() {
+    if (m_ptr) {
+        m_ptr->decStrong(this);
+        m_ptr = 0;
+    }
+}
+
+template<typename T>
+void sp<T>::set_pointer(T* ptr) {
+    m_ptr = ptr;
+}
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_STRONG_POINTER_H
diff --git a/include/utils/SystemClock.h b/libutils/include/utils/SystemClock.h
similarity index 100%
rename from include/utils/SystemClock.h
rename to libutils/include/utils/SystemClock.h
diff --git a/libutils/include/utils/Thread.h b/libutils/include/utils/Thread.h
new file mode 100644
index 0000000..a261fc8
--- /dev/null
+++ b/libutils/include/utils/Thread.h
@@ -0,0 +1,116 @@
+/*
+ * 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_UTILS_THREAD_H
+#define _LIBS_UTILS_THREAD_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <time.h>
+
+#if !defined(_WIN32)
+# include <pthread.h>
+#endif
+
+#include <utils/Condition.h>
+#include <utils/Errors.h>
+#include <utils/Mutex.h>
+#include <utils/RefBase.h>
+#include <utils/Timers.h>
+#include <utils/ThreadDefs.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+// ---------------------------------------------------------------------------
+
+class Thread : virtual public RefBase
+{
+public:
+    // Create a Thread object, but doesn't create or start the associated
+    // thread. See the run() method.
+    explicit            Thread(bool canCallJava = true);
+    virtual             ~Thread();
+
+    // Start the thread in threadLoop() which needs to be implemented.
+    virtual status_t    run(    const char* name,
+                                int32_t priority = PRIORITY_DEFAULT,
+                                size_t stack = 0);
+    
+    // Ask this object's thread to exit. This function is asynchronous, when the
+    // function returns the thread might still be running. Of course, this
+    // function can be called from a different thread.
+    virtual void        requestExit();
+
+    // Good place to do one-time initializations
+    virtual status_t    readyToRun();
+    
+    // Call requestExit() and wait until this object's thread exits.
+    // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call
+    // this function from this object's thread. Will return WOULD_BLOCK in
+    // that case.
+            status_t    requestExitAndWait();
+
+    // Wait until this object's thread exits. Returns immediately if not yet running.
+    // Do not call from this object's thread; will return WOULD_BLOCK in that case.
+            status_t    join();
+
+    // Indicates whether this thread is running or not.
+            bool        isRunning() const;
+
+#if defined(__ANDROID__)
+    // Return the thread's kernel ID, same as the thread itself calling gettid(),
+    // or -1 if the thread is not running.
+            pid_t       getTid() const;
+#endif
+
+protected:
+    // exitPending() returns true if requestExit() has been called.
+            bool        exitPending() const;
+    
+private:
+    // Derived class must implement threadLoop(). The thread starts its life
+    // here. There are two ways of using the Thread object:
+    // 1) loop: if threadLoop() returns true, it will be called again if
+    //          requestExit() wasn't called.
+    // 2) once: if threadLoop() returns false, the thread will exit upon return.
+    virtual bool        threadLoop() = 0;
+
+private:
+    Thread& operator=(const Thread&);
+    static  int             _threadLoop(void* user);
+    const   bool            mCanCallJava;
+    // always hold mLock when reading or writing
+            thread_id_t     mThread;
+    mutable Mutex           mLock;
+            Condition       mThreadExitedCondition;
+            status_t        mStatus;
+    // note that all accesses of mExitPending and mRunning need to hold mLock
+    volatile bool           mExitPending;
+    volatile bool           mRunning;
+            sp<Thread>      mHoldSelf;
+#if defined(__ANDROID__)
+    // legacy for debugging, not used by getTid() as it is set by the child thread
+    // and so is not initialized until the child reaches that point
+            pid_t           mTid;
+#endif
+};
+
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+#endif // _LIBS_UTILS_THREAD_H
+// ---------------------------------------------------------------------------
diff --git a/include/utils/ThreadDefs.h b/libutils/include/utils/ThreadDefs.h
similarity index 100%
rename from include/utils/ThreadDefs.h
rename to libutils/include/utils/ThreadDefs.h
diff --git a/include/utils/Timers.h b/libutils/include/utils/Timers.h
similarity index 100%
rename from include/utils/Timers.h
rename to libutils/include/utils/Timers.h
diff --git a/include/utils/Tokenizer.h b/libutils/include/utils/Tokenizer.h
similarity index 100%
rename from include/utils/Tokenizer.h
rename to libutils/include/utils/Tokenizer.h
diff --git a/libutils/include/utils/Trace.h b/libutils/include/utils/Trace.h
new file mode 100644
index 0000000..5e9229c
--- /dev/null
+++ b/libutils/include/utils/Trace.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_TRACE_H
+#define ANDROID_TRACE_H
+
+#if defined(__ANDROID__)
+
+#include <stdint.h>
+
+#include <cutils/trace.h>
+
+// See <cutils/trace.h> for more ATRACE_* macros.
+
+// ATRACE_NAME traces from its location until the end of its enclosing scope.
+#define _PASTE(x, y) x ## y
+#define PASTE(x, y) _PASTE(x,y)
+#define ATRACE_NAME(name) android::ScopedTrace PASTE(___tracer, __LINE__) (ATRACE_TAG, name)
+
+// ATRACE_CALL is an ATRACE_NAME that uses the current function name.
+#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
+
+namespace android {
+
+class ScopedTrace {
+public:
+    inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) {
+        atrace_begin(mTag, name);
+    }
+
+    inline ~ScopedTrace() {
+        atrace_end(mTag);
+    }
+
+private:
+    uint64_t mTag;
+};
+
+}; // namespace android
+
+#else // !__ANDROID__
+
+#define ATRACE_NAME(...)
+#define ATRACE_CALL()
+
+#endif // __ANDROID__
+
+#endif // ANDROID_TRACE_H
diff --git a/libutils/include/utils/TypeHelpers.h b/libutils/include/utils/TypeHelpers.h
new file mode 100644
index 0000000..28fbca5
--- /dev/null
+++ b/libutils/include/utils/TypeHelpers.h
@@ -0,0 +1,336 @@
+/*
+ * Copyright (C) 2005 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_TYPE_HELPERS_H
+#define ANDROID_TYPE_HELPERS_H
+
+#include <new>
+#include <type_traits>
+
+#include <stdint.h>
+#include <string.h>
+#include <sys/types.h>
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+/*
+ * Types traits
+ */
+
+template <typename T> struct trait_trivial_ctor { enum { value = false }; };
+template <typename T> struct trait_trivial_dtor { enum { value = false }; };
+template <typename T> struct trait_trivial_copy { enum { value = false }; };
+template <typename T> struct trait_trivial_move { enum { value = false }; };
+template <typename T> struct trait_pointer      { enum { value = false }; };
+template <typename T> struct trait_pointer<T*>  { enum { value = true }; };
+
+template <typename TYPE>
+struct traits {
+    enum {
+        // whether this type is a pointer
+        is_pointer          = trait_pointer<TYPE>::value,
+        // whether this type's constructor is a no-op
+        has_trivial_ctor    = is_pointer || trait_trivial_ctor<TYPE>::value,
+        // whether this type's destructor is a no-op
+        has_trivial_dtor    = is_pointer || trait_trivial_dtor<TYPE>::value,
+        // whether this type type can be copy-constructed with memcpy
+        has_trivial_copy    = is_pointer || trait_trivial_copy<TYPE>::value,
+        // whether this type can be moved with memmove
+        has_trivial_move    = is_pointer || trait_trivial_move<TYPE>::value
+    };
+};
+
+template <typename T, typename U>
+struct aggregate_traits {
+    enum {
+        is_pointer          = false,
+        has_trivial_ctor    =
+            traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor,
+        has_trivial_dtor    =
+            traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor,
+        has_trivial_copy    =
+            traits<T>::has_trivial_copy && traits<U>::has_trivial_copy,
+        has_trivial_move    =
+            traits<T>::has_trivial_move && traits<U>::has_trivial_move
+    };
+};
+
+#define ANDROID_TRIVIAL_CTOR_TRAIT( T ) \
+    template<> struct trait_trivial_ctor< T >   { enum { value = true }; };
+
+#define ANDROID_TRIVIAL_DTOR_TRAIT( T ) \
+    template<> struct trait_trivial_dtor< T >   { enum { value = true }; };
+
+#define ANDROID_TRIVIAL_COPY_TRAIT( T ) \
+    template<> struct trait_trivial_copy< T >   { enum { value = true }; };
+
+#define ANDROID_TRIVIAL_MOVE_TRAIT( T ) \
+    template<> struct trait_trivial_move< T >   { enum { value = true }; };
+
+#define ANDROID_BASIC_TYPES_TRAITS( T ) \
+    ANDROID_TRIVIAL_CTOR_TRAIT( T ) \
+    ANDROID_TRIVIAL_DTOR_TRAIT( T ) \
+    ANDROID_TRIVIAL_COPY_TRAIT( T ) \
+    ANDROID_TRIVIAL_MOVE_TRAIT( T )
+
+// ---------------------------------------------------------------------------
+
+/*
+ * basic types traits
+ */
+
+ANDROID_BASIC_TYPES_TRAITS( void )
+ANDROID_BASIC_TYPES_TRAITS( bool )
+ANDROID_BASIC_TYPES_TRAITS( char )
+ANDROID_BASIC_TYPES_TRAITS( unsigned char )
+ANDROID_BASIC_TYPES_TRAITS( short )
+ANDROID_BASIC_TYPES_TRAITS( unsigned short )
+ANDROID_BASIC_TYPES_TRAITS( int )
+ANDROID_BASIC_TYPES_TRAITS( unsigned int )
+ANDROID_BASIC_TYPES_TRAITS( long )
+ANDROID_BASIC_TYPES_TRAITS( unsigned long )
+ANDROID_BASIC_TYPES_TRAITS( long long )
+ANDROID_BASIC_TYPES_TRAITS( unsigned long long )
+ANDROID_BASIC_TYPES_TRAITS( float )
+ANDROID_BASIC_TYPES_TRAITS( double )
+
+// ---------------------------------------------------------------------------
+
+
+/*
+ * compare and order types
+ */
+
+template<typename TYPE> inline
+int strictly_order_type(const TYPE& lhs, const TYPE& rhs) {
+    return (lhs < rhs) ? 1 : 0;
+}
+
+template<typename TYPE> inline
+int compare_type(const TYPE& lhs, const TYPE& rhs) {
+    return strictly_order_type(rhs, lhs) - strictly_order_type(lhs, rhs);
+}
+
+/*
+ * create, destroy, copy and move types...
+ */
+
+template<typename TYPE> inline
+void construct_type(TYPE* p, size_t n) {
+    if (!traits<TYPE>::has_trivial_ctor) {
+        while (n > 0) {
+            n--;
+            new(p++) TYPE;
+        }
+    }
+}
+
+template<typename TYPE> inline
+void destroy_type(TYPE* p, size_t n) {
+    if (!traits<TYPE>::has_trivial_dtor) {
+        while (n > 0) {
+            n--;
+            p->~TYPE();
+            p++;
+        }
+    }
+}
+
+template<typename TYPE>
+typename std::enable_if<traits<TYPE>::has_trivial_copy>::type
+inline
+copy_type(TYPE* d, const TYPE* s, size_t n) {
+    memcpy(d,s,n*sizeof(TYPE));
+}
+
+template<typename TYPE>
+typename std::enable_if<!traits<TYPE>::has_trivial_copy>::type
+inline
+copy_type(TYPE* d, const TYPE* s, size_t n) {
+    while (n > 0) {
+        n--;
+        new(d) TYPE(*s);
+        d++, s++;
+    }
+}
+
+template<typename TYPE> inline
+void splat_type(TYPE* where, const TYPE* what, size_t n) {
+    if (!traits<TYPE>::has_trivial_copy) {
+        while (n > 0) {
+            n--;
+            new(where) TYPE(*what);
+            where++;
+        }
+    } else {
+        while (n > 0) {
+            n--;
+            *where++ = *what;
+        }
+    }
+}
+
+template<typename TYPE>
+struct use_trivial_move : public std::integral_constant<bool,
+    (traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy)
+    || traits<TYPE>::has_trivial_move
+> {};
+
+template<typename TYPE>
+typename std::enable_if<use_trivial_move<TYPE>::value>::type
+inline
+move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) {
+    memmove(d, s, n*sizeof(TYPE));
+}
+
+template<typename TYPE>
+typename std::enable_if<!use_trivial_move<TYPE>::value>::type
+inline
+move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) {
+    d += n;
+    s += n;
+    while (n > 0) {
+        n--;
+        --d, --s;
+        if (!traits<TYPE>::has_trivial_copy) {
+            new(d) TYPE(*s);
+        } else {
+            *d = *s;
+        }
+        if (!traits<TYPE>::has_trivial_dtor) {
+            s->~TYPE();
+        }
+    }
+}
+
+template<typename TYPE>
+typename std::enable_if<use_trivial_move<TYPE>::value>::type
+inline
+move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) {
+    memmove(d, s, n*sizeof(TYPE));
+}
+
+template<typename TYPE>
+typename std::enable_if<!use_trivial_move<TYPE>::value>::type
+inline
+move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) {
+    while (n > 0) {
+        n--;
+        if (!traits<TYPE>::has_trivial_copy) {
+            new(d) TYPE(*s);
+        } else {
+            *d = *s;
+        }
+        if (!traits<TYPE>::has_trivial_dtor) {
+            s->~TYPE();
+        }
+        d++, s++;
+    }
+}
+
+// ---------------------------------------------------------------------------
+
+/*
+ * a key/value pair
+ */
+
+template <typename KEY, typename VALUE>
+struct key_value_pair_t {
+    typedef KEY key_t;
+    typedef VALUE value_t;
+
+    KEY     key;
+    VALUE   value;
+    key_value_pair_t() { }
+    key_value_pair_t(const key_value_pair_t& o) : key(o.key), value(o.value) { }
+    key_value_pair_t& operator=(const key_value_pair_t& o) {
+        key = o.key;
+        value = o.value;
+        return *this;
+    }
+    key_value_pair_t(const KEY& k, const VALUE& v) : key(k), value(v)  { }
+    explicit key_value_pair_t(const KEY& k) : key(k) { }
+    inline bool operator < (const key_value_pair_t& o) const {
+        return strictly_order_type(key, o.key);
+    }
+    inline const KEY& getKey() const {
+        return key;
+    }
+    inline const VALUE& getValue() const {
+        return value;
+    }
+};
+
+template <typename K, typename V>
+struct trait_trivial_ctor< key_value_pair_t<K, V> >
+{ enum { value = aggregate_traits<K,V>::has_trivial_ctor }; };
+template <typename K, typename V>
+struct trait_trivial_dtor< key_value_pair_t<K, V> >
+{ enum { value = aggregate_traits<K,V>::has_trivial_dtor }; };
+template <typename K, typename V>
+struct trait_trivial_copy< key_value_pair_t<K, V> >
+{ enum { value = aggregate_traits<K,V>::has_trivial_copy }; };
+template <typename K, typename V>
+struct trait_trivial_move< key_value_pair_t<K, V> >
+{ enum { value = aggregate_traits<K,V>::has_trivial_move }; };
+
+// ---------------------------------------------------------------------------
+
+/*
+ * Hash codes.
+ */
+typedef uint32_t hash_t;
+
+template <typename TKey>
+hash_t hash_type(const TKey& key);
+
+/* Built-in hash code specializations */
+#define ANDROID_INT32_HASH(T) \
+        template <> inline hash_t hash_type(const T& value) { return hash_t(value); }
+#define ANDROID_INT64_HASH(T) \
+        template <> inline hash_t hash_type(const T& value) { \
+                return hash_t((value >> 32) ^ value); }
+#define ANDROID_REINTERPRET_HASH(T, R) \
+        template <> inline hash_t hash_type(const T& value) { \
+            R newValue; \
+            static_assert(sizeof(newValue) == sizeof(value), "size mismatch"); \
+            memcpy(&newValue, &value, sizeof(newValue)); \
+            return hash_type(newValue); \
+        }
+
+ANDROID_INT32_HASH(bool)
+ANDROID_INT32_HASH(int8_t)
+ANDROID_INT32_HASH(uint8_t)
+ANDROID_INT32_HASH(int16_t)
+ANDROID_INT32_HASH(uint16_t)
+ANDROID_INT32_HASH(int32_t)
+ANDROID_INT32_HASH(uint32_t)
+ANDROID_INT64_HASH(int64_t)
+ANDROID_INT64_HASH(uint64_t)
+ANDROID_REINTERPRET_HASH(float, uint32_t)
+ANDROID_REINTERPRET_HASH(double, uint64_t)
+
+template <typename T> inline hash_t hash_type(T* const & value) {
+    return hash_type(uintptr_t(value));
+}
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_TYPE_HELPERS_H
diff --git a/libutils/include/utils/Unicode.h b/libutils/include/utils/Unicode.h
new file mode 100644
index 0000000..666b70f
--- /dev/null
+++ b/libutils/include/utils/Unicode.h
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2005 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_UNICODE_H
+#define ANDROID_UNICODE_H
+
+#include <sys/types.h>
+#include <stdint.h>
+
+extern "C" {
+
+// Standard string functions on char16_t strings.
+int strcmp16(const char16_t *, const char16_t *);
+int strncmp16(const char16_t *s1, const char16_t *s2, size_t n);
+size_t strlen16(const char16_t *);
+size_t strnlen16(const char16_t *, size_t);
+char16_t *strcpy16(char16_t *, const char16_t *);
+char16_t *strncpy16(char16_t *, const char16_t *, size_t);
+char16_t *strstr16(const char16_t*, const char16_t*);
+
+// Version of comparison that supports embedded NULs.
+// This is different than strncmp() because we don't stop
+// at a nul character and consider the strings to be different
+// if the lengths are different (thus we need to supply the
+// lengths of both strings).  This can also be used when
+// your string is not nul-terminated as it will have the
+// equivalent result as strcmp16 (unlike strncmp16).
+int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2);
+
+// Version of strzcmp16 for comparing strings in different endianness.
+int strzcmp16_h_n(const char16_t *s1H, size_t n1, const char16_t *s2N, size_t n2);
+
+// Standard string functions on char32_t strings.
+size_t strlen32(const char32_t *);
+size_t strnlen32(const char32_t *, size_t);
+
+/**
+ * Measure the length of a UTF-32 string in UTF-8. If the string is invalid
+ * such as containing a surrogate character, -1 will be returned.
+ */
+ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len);
+
+/**
+ * Stores a UTF-8 string converted from "src" in "dst", if "dst_length" is not
+ * large enough to store the string, the part of the "src" string is stored
+ * into "dst" as much as possible. See the examples for more detail.
+ * Returns the size actually used for storing the string.
+ * dst" is not nul-terminated when dst_len is fully used (like strncpy).
+ *
+ * \code
+ * Example 1
+ * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
+ * "src_len" == 2
+ * "dst_len" >= 7
+ * ->
+ * Returned value == 6
+ * "dst" becomes \xE3\x81\x82\xE3\x81\x84\0
+ * (note that "dst" is nul-terminated)
+ *
+ * Example 2
+ * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
+ * "src_len" == 2
+ * "dst_len" == 5
+ * ->
+ * Returned value == 3
+ * "dst" becomes \xE3\x81\x82\0
+ * (note that "dst" is nul-terminated, but \u3044 is not stored in "dst"
+ * since "dst" does not have enough size to store the character)
+ *
+ * Example 3
+ * "src" == \u3042\u3044 (\xE3\x81\x82\xE3\x81\x84)
+ * "src_len" == 2
+ * "dst_len" == 6
+ * ->
+ * Returned value == 6
+ * "dst" becomes \xE3\x81\x82\xE3\x81\x84
+ * (note that "dst" is NOT nul-terminated, like strncpy)
+ * \endcode
+ */
+void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len);
+
+/**
+ * Returns the unicode value at "index".
+ * Returns -1 when the index is invalid (equals to or more than "src_len").
+ * If returned value is positive, it is able to be converted to char32_t, which
+ * is unsigned. Then, if "next_index" is not NULL, the next index to be used is
+ * stored in "next_index". "next_index" can be NULL.
+ */
+int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index);
+
+
+/**
+ * Returns the UTF-8 length of UTF-16 string "src".
+ */
+ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len);
+
+/**
+ * Converts a UTF-16 string to UTF-8. The destination buffer must be large
+ * enough to fit the UTF-16 as measured by utf16_to_utf8_length with an added
+ * NUL terminator.
+ */
+void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len);
+
+/**
+ * Returns the length of "src" when "src" is valid UTF-8 string.
+ * Returns 0 if src is NULL or 0-length string. Returns -1 when the source
+ * is an invalid string.
+ *
+ * This function should be used to determine whether "src" is valid UTF-8
+ * characters with valid unicode codepoints. "src" must be nul-terminated.
+ *
+ * If you are going to use other utf8_to_... functions defined in this header
+ * with string which may not be valid UTF-8 with valid codepoint (form 0 to
+ * 0x10FFFF), you should use this function before calling others, since the
+ * other functions do not check whether the string is valid UTF-8 or not.
+ *
+ * If you do not care whether "src" is valid UTF-8 or not, you should use
+ * strlen() as usual, which should be much faster.
+ */
+ssize_t utf8_length(const char *src);
+
+/**
+ * Measure the length of a UTF-32 string.
+ */
+size_t utf8_to_utf32_length(const char *src, size_t src_len);
+
+/**
+ * Stores a UTF-32 string converted from "src" in "dst". "dst" must be large
+ * enough to store the entire converted string as measured by
+ * utf8_to_utf32_length plus space for a NUL terminator.
+ */
+void utf8_to_utf32(const char* src, size_t src_len, char32_t* dst);
+
+/**
+ * Returns the UTF-16 length of UTF-8 string "src". Returns -1 in case
+ * it's invalid utf8. No buffer over-read occurs because of bound checks. Using overreadIsFatal you
+ * can ask to log a message and fail in case the invalid utf8 could have caused an override if no
+ * bound checks were used (otherwise -1 is returned).
+ */
+ssize_t utf8_to_utf16_length(const uint8_t* src, size_t srcLen, bool overreadIsFatal = false);
+
+/**
+ * Convert UTF-8 to UTF-16 including surrogate pairs.
+ * Returns a pointer to the end of the string (where a NUL terminator might go
+ * if you wanted to add one). At most dstLen characters are written; it won't emit half a surrogate
+ * pair. If dstLen == 0 nothing is written and dst is returned. If dstLen > SSIZE_MAX it aborts
+ * (this being probably a negative number returned as an error and casted to unsigned).
+ */
+char16_t* utf8_to_utf16_no_null_terminator(
+        const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen);
+
+/**
+ * Convert UTF-8 to UTF-16 including surrogate pairs. At most dstLen - 1
+ * characters are written; it won't emit half a surrogate pair; and a NUL terminator is appended
+ * after. dstLen - 1 can be measured beforehand using utf8_to_utf16_length. Aborts if dstLen == 0
+ * (at least one character is needed for the NUL terminator) or dstLen > SSIZE_MAX (the latter
+ * case being likely a negative number returned as an error and casted to unsigned) . Returns a
+ * pointer to the NUL terminator.
+ */
+char16_t *utf8_to_utf16(
+        const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen);
+
+}
+
+#endif
diff --git a/libutils/include/utils/Vector.h b/libutils/include/utils/Vector.h
new file mode 100644
index 0000000..7e00123
--- /dev/null
+++ b/libutils/include/utils/Vector.h
@@ -0,0 +1,431 @@
+/*
+ * Copyright (C) 2005 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_VECTOR_H
+#define ANDROID_VECTOR_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <log/log.h>
+#include <utils/TypeHelpers.h>
+#include <utils/VectorImpl.h>
+
+/*
+ * Used to blacklist some functions from CFI.
+ *
+ */
+#ifndef __has_attribute
+#define __has_attribute(x) 0
+#endif
+
+#if __has_attribute(no_sanitize)
+#define UTILS_VECTOR_NO_CFI __attribute__((no_sanitize("cfi")))
+#else
+#define UTILS_VECTOR_NO_CFI
+#endif
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+template <typename TYPE>
+class SortedVector;
+
+/*!
+ * The main templated vector class ensuring type safety
+ * while making use of VectorImpl.
+ * This is the class users want to use.
+ */
+
+template <class TYPE>
+class Vector : private VectorImpl
+{
+public:
+            typedef TYPE    value_type;
+
+    /*!
+     * Constructors and destructors
+     */
+
+                            Vector();
+                            Vector(const Vector<TYPE>& rhs);
+    explicit                Vector(const SortedVector<TYPE>& rhs);
+    virtual                 ~Vector();
+
+    /*! copy operator */
+            const Vector<TYPE>&     operator = (const Vector<TYPE>& rhs) const;
+            Vector<TYPE>&           operator = (const Vector<TYPE>& rhs);
+
+            const Vector<TYPE>&     operator = (const SortedVector<TYPE>& rhs) const;
+            Vector<TYPE>&           operator = (const SortedVector<TYPE>& rhs);
+
+            /*
+     * empty the vector
+     */
+
+    inline  void            clear()             { VectorImpl::clear(); }
+
+    /*!
+     * vector stats
+     */
+
+    //! returns number of items in the vector
+    inline  size_t          size() const                { return VectorImpl::size(); }
+    //! returns whether or not the vector is empty
+    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
+    //! returns how many items can be stored without reallocating the backing store
+    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
+    //! sets the capacity. capacity can never be reduced less than size()
+    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
+
+    /*!
+     * set the size of the vector. items are appended with the default
+     * constructor, or removed from the end as needed.
+     */
+    inline  ssize_t         resize(size_t size)         { return VectorImpl::resize(size); }
+
+    /*!
+     * C-style array access
+     */
+
+    //! read-only C-style access
+    inline  const TYPE*     array() const;
+    //! read-write C-style access
+            TYPE*           editArray();
+
+    /*!
+     * accessors
+     */
+
+    //! read-only access to an item at a given index
+    inline  const TYPE&     operator [] (size_t index) const;
+    //! alternate name for operator []
+    inline  const TYPE&     itemAt(size_t index) const;
+    //! stack-usage of the vector. returns the top of the stack (last element)
+            const TYPE&     top() const;
+
+    /*!
+     * modifying the array
+     */
+
+    //! copy-on write support, grants write access to an item
+            TYPE&           editItemAt(size_t index);
+    //! grants right access to the top of the stack (last element)
+            TYPE&           editTop();
+
+            /*!
+             * append/insert another vector
+             */
+
+    //! insert another vector at a given index
+            ssize_t         insertVectorAt(const Vector<TYPE>& vector, size_t index);
+
+    //! append another vector at the end of this one
+            ssize_t         appendVector(const Vector<TYPE>& vector);
+
+
+    //! insert an array at a given index
+            ssize_t         insertArrayAt(const TYPE* array, size_t index, size_t length);
+
+    //! append an array at the end of this vector
+            ssize_t         appendArray(const TYPE* array, size_t length);
+
+            /*!
+             * add/insert/replace items
+             */
+
+    //! insert one or several items initialized with their default constructor
+    inline  ssize_t         insertAt(size_t index, size_t numItems = 1);
+    //! insert one or several items initialized from a prototype item
+            ssize_t         insertAt(const TYPE& prototype_item, size_t index, size_t numItems = 1);
+    //! pop the top of the stack (removes the last element). No-op if the stack's empty
+    inline  void            pop();
+    //! pushes an item initialized with its default constructor
+    inline  void            push();
+    //! pushes an item on the top of the stack
+            void            push(const TYPE& item);
+    //! same as push() but returns the index the item was added at (or an error)
+    inline  ssize_t         add();
+    //! same as push() but returns the index the item was added at (or an error)
+            ssize_t         add(const TYPE& item);
+    //! replace an item with a new one initialized with its default constructor
+    inline  ssize_t         replaceAt(size_t index);
+    //! replace an item with a new one
+            ssize_t         replaceAt(const TYPE& item, size_t index);
+
+    /*!
+     * remove items
+     */
+
+    //! remove several items
+    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
+    //! remove one item
+    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
+
+    /*!
+     * sort (stable) the array
+     */
+
+     typedef int (*compar_t)(const TYPE* lhs, const TYPE* rhs);
+     typedef int (*compar_r_t)(const TYPE* lhs, const TYPE* rhs, void* state);
+
+     inline status_t        sort(compar_t cmp);
+     inline status_t        sort(compar_r_t cmp, void* state);
+
+     // for debugging only
+     inline size_t getItemSize() const { return itemSize(); }
+
+
+     /*
+      * these inlines add some level of compatibility with STL. eventually
+      * we should probably turn things around.
+      */
+     typedef TYPE* iterator;
+     typedef TYPE const* const_iterator;
+
+     inline iterator begin() { return editArray(); }
+     inline iterator end()   { return editArray() + size(); }
+     inline const_iterator begin() const { return array(); }
+     inline const_iterator end() const   { return array() + size(); }
+     inline void reserve(size_t n) { setCapacity(n); }
+     inline bool empty() const{ return isEmpty(); }
+     inline void push_back(const TYPE& item)  { insertAt(item, size(), 1); }
+     inline void push_front(const TYPE& item) { insertAt(item, 0, 1); }
+     inline iterator erase(iterator pos) {
+         ssize_t index = removeItemsAt(static_cast<size_t>(pos-array()));
+         return begin() + index;
+     }
+
+protected:
+    virtual void    do_construct(void* storage, size_t num) const;
+    virtual void    do_destroy(void* storage, size_t num) const;
+    virtual void    do_copy(void* dest, const void* from, size_t num) const;
+    virtual void    do_splat(void* dest, const void* item, size_t num) const;
+    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
+    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
+};
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts from here...
+// ---------------------------------------------------------------------------
+
+template<class TYPE> inline
+Vector<TYPE>::Vector()
+    : VectorImpl(sizeof(TYPE),
+                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
+                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
+                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
+                )
+{
+}
+
+template<class TYPE> inline
+Vector<TYPE>::Vector(const Vector<TYPE>& rhs)
+    : VectorImpl(rhs) {
+}
+
+template<class TYPE> inline
+Vector<TYPE>::Vector(const SortedVector<TYPE>& rhs)
+    : VectorImpl(static_cast<const VectorImpl&>(rhs)) {
+}
+
+template<class TYPE> inline
+Vector<TYPE>::~Vector() {
+    finish_vector();
+}
+
+template<class TYPE> inline
+Vector<TYPE>& Vector<TYPE>::operator = (const Vector<TYPE>& rhs) {
+    VectorImpl::operator = (rhs);
+    return *this;
+}
+
+template<class TYPE> inline
+const Vector<TYPE>& Vector<TYPE>::operator = (const Vector<TYPE>& rhs) const {
+    VectorImpl::operator = (static_cast<const VectorImpl&>(rhs));
+    return *this;
+}
+
+template<class TYPE> inline
+Vector<TYPE>& Vector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
+    VectorImpl::operator = (static_cast<const VectorImpl&>(rhs));
+    return *this;
+}
+
+template<class TYPE> inline
+const Vector<TYPE>& Vector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
+    VectorImpl::operator = (rhs);
+    return *this;
+}
+
+template<class TYPE> inline
+const TYPE* Vector<TYPE>::array() const {
+    return static_cast<const TYPE *>(arrayImpl());
+}
+
+template<class TYPE> inline
+TYPE* Vector<TYPE>::editArray() {
+    return static_cast<TYPE *>(editArrayImpl());
+}
+
+
+template<class TYPE> inline
+const TYPE& Vector<TYPE>::operator[](size_t index) const {
+    LOG_FATAL_IF(index>=size(),
+            "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__,
+            int(index), int(size()));
+    return *(array() + index);
+}
+
+template<class TYPE> inline
+const TYPE& Vector<TYPE>::itemAt(size_t index) const {
+    return operator[](index);
+}
+
+template<class TYPE> inline
+const TYPE& Vector<TYPE>::top() const {
+    return *(array() + size() - 1);
+}
+
+template<class TYPE> inline
+TYPE& Vector<TYPE>::editItemAt(size_t index) {
+    return *( static_cast<TYPE *>(editItemLocation(index)) );
+}
+
+template<class TYPE> inline
+TYPE& Vector<TYPE>::editTop() {
+    return *( static_cast<TYPE *>(editItemLocation(size()-1)) );
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::insertVectorAt(const Vector<TYPE>& vector, size_t index) {
+    return VectorImpl::insertVectorAt(reinterpret_cast<const VectorImpl&>(vector), index);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::appendVector(const Vector<TYPE>& vector) {
+    return VectorImpl::appendVector(reinterpret_cast<const VectorImpl&>(vector));
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::insertArrayAt(const TYPE* array, size_t index, size_t length) {
+    return VectorImpl::insertArrayAt(array, index, length);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::appendArray(const TYPE* array, size_t length) {
+    return VectorImpl::appendArray(array, length);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::insertAt(const TYPE& item, size_t index, size_t numItems) {
+    return VectorImpl::insertAt(&item, index, numItems);
+}
+
+template<class TYPE> inline
+void Vector<TYPE>::push(const TYPE& item) {
+    return VectorImpl::push(&item);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::add(const TYPE& item) {
+    return VectorImpl::add(&item);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::replaceAt(const TYPE& item, size_t index) {
+    return VectorImpl::replaceAt(&item, index);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::insertAt(size_t index, size_t numItems) {
+    return VectorImpl::insertAt(index, numItems);
+}
+
+template<class TYPE> inline
+void Vector<TYPE>::pop() {
+    VectorImpl::pop();
+}
+
+template<class TYPE> inline
+void Vector<TYPE>::push() {
+    VectorImpl::push();
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::add() {
+    return VectorImpl::add();
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::replaceAt(size_t index) {
+    return VectorImpl::replaceAt(index);
+}
+
+template<class TYPE> inline
+ssize_t Vector<TYPE>::removeItemsAt(size_t index, size_t count) {
+    return VectorImpl::removeItemsAt(index, count);
+}
+
+template<class TYPE> inline
+status_t Vector<TYPE>::sort(Vector<TYPE>::compar_t cmp) {
+    return VectorImpl::sort(reinterpret_cast<VectorImpl::compar_t>(cmp));
+}
+
+template<class TYPE> inline
+status_t Vector<TYPE>::sort(Vector<TYPE>::compar_r_t cmp, void* state) {
+    return VectorImpl::sort(reinterpret_cast<VectorImpl::compar_r_t>(cmp), state);
+}
+
+// ---------------------------------------------------------------------------
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void Vector<TYPE>::do_construct(void* storage, size_t num) const {
+    construct_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+void Vector<TYPE>::do_destroy(void* storage, size_t num) const {
+    destroy_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void Vector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
+    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void Vector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
+    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void Vector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
+    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+UTILS_VECTOR_NO_CFI void Vector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
+    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+}; // namespace android
+
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_VECTOR_H
diff --git a/libutils/include/utils/VectorImpl.h b/libutils/include/utils/VectorImpl.h
new file mode 100644
index 0000000..4dd91fd
--- /dev/null
+++ b/libutils/include/utils/VectorImpl.h
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2005 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_VECTOR_IMPL_H
+#define ANDROID_VECTOR_IMPL_H
+
+#include <assert.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <utils/Errors.h>
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts in here...
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+/*!
+ * Implementation of the guts of the vector<> class
+ * this ensures backward binary compatibility and
+ * reduces code size.
+ * For performance reasons, we expose mStorage and mCount
+ * so these fields are set in stone.
+ *
+ */
+
+class VectorImpl
+{
+public:
+    enum { // flags passed to the ctor
+        HAS_TRIVIAL_CTOR    = 0x00000001,
+        HAS_TRIVIAL_DTOR    = 0x00000002,
+        HAS_TRIVIAL_COPY    = 0x00000004,
+    };
+
+                            VectorImpl(size_t itemSize, uint32_t flags);
+                            VectorImpl(const VectorImpl& rhs);
+    virtual                 ~VectorImpl();
+
+    /*! must be called from subclasses destructor */
+            void            finish_vector();
+
+            VectorImpl&     operator = (const VectorImpl& rhs);    
+            
+    /*! C-style array access */
+    inline  const void*     arrayImpl() const       { return mStorage; }
+            void*           editArrayImpl();
+            
+    /*! vector stats */
+    inline  size_t          size() const        { return mCount; }
+    inline  bool            isEmpty() const     { return mCount == 0; }
+            size_t          capacity() const;
+            ssize_t         setCapacity(size_t size);
+            ssize_t         resize(size_t size);
+
+            /*! append/insert another vector or array */
+            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
+            ssize_t         appendVector(const VectorImpl& vector);
+            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
+            ssize_t         appendArray(const void* array, size_t length);
+            
+            /*! add/insert/replace items */
+            ssize_t         insertAt(size_t where, size_t numItems = 1);
+            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
+            void            pop();
+            void            push();
+            void            push(const void* item);
+            ssize_t         add();
+            ssize_t         add(const void* item);
+            ssize_t         replaceAt(size_t index);
+            ssize_t         replaceAt(const void* item, size_t index);
+
+            /*! remove items */
+            ssize_t         removeItemsAt(size_t index, size_t count = 1);
+            void            clear();
+
+            const void*     itemLocation(size_t index) const;
+            void*           editItemLocation(size_t index);
+
+            typedef int (*compar_t)(const void* lhs, const void* rhs);
+            typedef int (*compar_r_t)(const void* lhs, const void* rhs, void* state);
+            status_t        sort(compar_t cmp);
+            status_t        sort(compar_r_t cmp, void* state);
+
+protected:
+            size_t          itemSize() const;
+            void            release_storage();
+
+    virtual void            do_construct(void* storage, size_t num) const = 0;
+    virtual void            do_destroy(void* storage, size_t num) const = 0;
+    virtual void            do_copy(void* dest, const void* from, size_t num) const = 0;
+    virtual void            do_splat(void* dest, const void* item, size_t num) const = 0;
+    virtual void            do_move_forward(void* dest, const void* from, size_t num) const = 0;
+    virtual void            do_move_backward(void* dest, const void* from, size_t num) const = 0;
+    
+private:
+        void* _grow(size_t where, size_t amount);
+        void  _shrink(size_t where, size_t amount);
+
+        inline void _do_construct(void* storage, size_t num) const;
+        inline void _do_destroy(void* storage, size_t num) const;
+        inline void _do_copy(void* dest, const void* from, size_t num) const;
+        inline void _do_splat(void* dest, const void* item, size_t num) const;
+        inline void _do_move_forward(void* dest, const void* from, size_t num) const;
+        inline void _do_move_backward(void* dest, const void* from, size_t num) const;
+
+            // These 2 fields are exposed in the inlines below,
+            // so they're set in stone.
+            void *      mStorage;   // base address of the vector
+            size_t      mCount;     // number of items
+
+    const   uint32_t    mFlags;
+    const   size_t      mItemSize;
+};
+
+
+
+class SortedVectorImpl : public VectorImpl
+{
+public:
+                            SortedVectorImpl(size_t itemSize, uint32_t flags);
+    explicit                SortedVectorImpl(const VectorImpl& rhs);
+    virtual                 ~SortedVectorImpl();
+    
+    SortedVectorImpl&     operator = (const SortedVectorImpl& rhs);    
+
+    //! finds the index of an item
+            ssize_t         indexOf(const void* item) const;
+
+    //! finds where this item should be inserted
+            size_t          orderOf(const void* item) const;
+
+    //! add an item in the right place (or replaces it if there is one)
+            ssize_t         add(const void* item);
+
+    //! merges a vector into this one
+            ssize_t         merge(const VectorImpl& vector);
+            ssize_t         merge(const SortedVectorImpl& vector);
+             
+    //! removes an item
+            ssize_t         remove(const void* item);
+        
+protected:
+    virtual int             do_compare(const void* lhs, const void* rhs) const = 0;
+
+private:
+            ssize_t         _indexOrderOf(const void* item, size_t* order = 0) const;
+
+            // these are made private, because they can't be used on a SortedVector
+            // (they don't have an implementation either)
+            ssize_t         add();
+            void            pop();
+            void            push();
+            void            push(const void* item);
+            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
+            ssize_t         appendVector(const VectorImpl& vector);
+            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
+            ssize_t         appendArray(const void* array, size_t length);
+            ssize_t         insertAt(size_t where, size_t numItems = 1);
+            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
+            ssize_t         replaceAt(size_t index);
+            ssize_t         replaceAt(const void* item, size_t index);
+};
+
+}; // namespace android
+
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_VECTOR_IMPL_H
diff --git a/include/utils/misc.h b/libutils/include/utils/misc.h
similarity index 100%
rename from include/utils/misc.h
rename to libutils/include/utils/misc.h
diff --git a/include/utils/threads.h b/libutils/include/utils/threads.h
similarity index 100%
rename from include/utils/threads.h
rename to libutils/include/utils/threads.h
diff --git a/libutils/misc.cpp b/libutils/misc.cpp
index 216dc14..d95fd05 100644
--- a/libutils/misc.cpp
+++ b/libutils/misc.cpp
@@ -16,21 +16,19 @@
 
 #define LOG_TAG "misc"
 
-//
-// Miscellaneous utility functions.
-//
 #include <utils/misc.h>
+
+#include <pthread.h>
+
 #include <utils/Log.h>
+#include <utils/Vector.h>
 
-#include <sys/stat.h>
-#include <string.h>
-#include <stdio.h>
-
-#if !defined(_WIN32)
-# include <pthread.h>
+#if defined(__ANDROID__)
+#include <dlfcn.h>
+#include <vndksupport/linker.h>
 #endif
 
-#include <utils/Vector.h>
+extern "C" void do_report_sysprop_change();
 
 using namespace android;
 
@@ -70,7 +68,36 @@
 #endif
 }
 
+#if defined(__ANDROID__)
+void (*get_report_sysprop_change_func())() {
+    void (*func)() = nullptr;
+    void* handle = android_load_sphal_library("libutils.so", RTLD_NOW);
+    if (handle != nullptr) {
+        func = reinterpret_cast<decltype(func)>(dlsym(handle, "do_report_sysprop_change"));
+    }
+
+    return func;
+}
+#endif
+
 void report_sysprop_change() {
+    do_report_sysprop_change();
+
+#if defined(__ANDROID__)
+    // libutils.so is double loaded; from the default namespace and from the
+    // 'sphal' namespace. Redirect the sysprop change event to the other instance
+    // of libutils.so loaded in the 'sphal' namespace so that listeners attached
+    // to that instance is also notified with this event.
+    static auto func = get_report_sysprop_change_func();
+    if (func != nullptr) {
+        (*func)();
+    }
+#endif
+}
+
+};  // namespace android
+
+void do_report_sysprop_change() {
 #if !defined(_WIN32)
     pthread_mutex_lock(&gSyspropMutex);
     Vector<sysprop_change_callback_info> listeners;
@@ -85,5 +112,3 @@
     }
 #endif
 }
-
-}; // namespace android
diff --git a/libutils/primes.py b/libutils/primes.py
deleted file mode 100755
index e161dd8..0000000
--- a/libutils/primes.py
+++ /dev/null
@@ -1,47 +0,0 @@
-#!/usr/bin/env python2.6
-#
-# 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.
-#
-
-#
-# Generates a table of prime numbers for use in BasicHashtable.cpp.
-#
-# Each prime is chosen such that it is a little more than twice as large as
-# the previous prime in the table.  This makes it easier to choose a new
-# hashtable size when the underlying array is grown by as nominal factor
-# of two each time.
-#
-
-def is_odd_prime(n):
-  limit = (n - 1) / 2
-  d = 3
-  while d <= limit:
-    if n % d == 0:
-      return False
-    d += 2
-  return True
-
-print "static size_t PRIMES[] = {"
-
-n = 5
-max = 2**31 - 1
-while n < max:
-  print "    %d," % (n)
-  n = n * 2 + 1
-  while not is_odd_prime(n):
-    n += 2
-
-print "    0,"
-print "};"
diff --git a/libutils/tests/Android.bp b/libutils/tests/Android.bp
new file mode 100644
index 0000000..7b62c24
--- /dev/null
+++ b/libutils/tests/Android.bp
@@ -0,0 +1,90 @@
+//
+// 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.
+//
+
+// Build the unit tests.
+
+cc_test {
+    name: "libutils_tests",
+    host_supported: true,
+
+    srcs: [
+        "BitSet_test.cpp",
+        "LruCache_test.cpp",
+        "Singleton_test.cpp",
+        "String8_test.cpp",
+        "StrongPointer_test.cpp",
+        "Unicode_test.cpp",
+        "Vector_test.cpp",
+    ],
+
+    target: {
+        android: {
+            srcs: [
+                "Looper_test.cpp",
+                "RefBase_test.cpp",
+                "SystemClock_test.cpp",
+            ],
+            shared_libs: [
+                "libz",
+                "liblog",
+                "libcutils",
+                "libutils",
+                "libbase",
+                "libdl",
+            ],
+        },
+        linux: {
+            srcs: [
+                "Looper_test.cpp",
+                "RefBase_test.cpp",
+            ],
+        },
+        host: {
+            static_libs: [
+                "libutils",
+                "liblog",
+                "libbase",
+            ],
+            host_ldlibs: ["-ldl"],
+        },
+    },
+
+    required: [
+        "libutils_tests_singleton1",
+        "libutils_tests_singleton2",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+}
+
+cc_test_library {
+    name: "libutils_tests_singleton1",
+    host_supported: true,
+    relative_install_path: "libutils_tests",
+    srcs: ["Singleton_test1.cpp"],
+}
+
+cc_test_library {
+    name: "libutils_tests_singleton2",
+    host_supported: true,
+    relative_install_path: "libutils_tests",
+    srcs: ["Singleton_test2.cpp"],
+    shared_libs: ["libutils_tests_singleton1"],
+}
diff --git a/libutils/tests/Android.mk b/libutils/tests/Android.mk
deleted file mode 100644
index 8f07f1a..0000000
--- a/libutils/tests/Android.mk
+++ /dev/null
@@ -1,48 +0,0 @@
-#
-# 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.
-#
-
-# Build the unit tests.
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libutils_tests
-
-LOCAL_SRC_FILES := \
-    BlobCache_test.cpp \
-    BitSet_test.cpp \
-    Looper_test.cpp \
-    LruCache_test.cpp \
-    String8_test.cpp \
-    StrongPointer_test.cpp \
-    Unicode_test.cpp \
-    Vector_test.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-    libz \
-    liblog \
-    libcutils \
-    libutils \
-
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libutils_tests_host
-LOCAL_SRC_FILES := Vector_test.cpp
-LOCAL_STATIC_LIBRARIES := libutils liblog
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libutils/tests/BitSet_test.cpp b/libutils/tests/BitSet_test.cpp
index 59d913e..fbcf025 100644
--- a/libutils/tests/BitSet_test.cpp
+++ b/libutils/tests/BitSet_test.cpp
@@ -16,11 +16,12 @@
 
 #define LOG_TAG "BitSet_test"
 
-#include <utils/BitSet.h>
-#include <cutils/log.h>
-#include <gtest/gtest.h>
 #include <unistd.h>
 
+#include <android/log.h>
+#include <gtest/gtest.h>
+#include <utils/BitSet.h>
+
 namespace android {
 
 class BitSet32Test : public testing::Test {
diff --git a/libutils/tests/BlobCache_test.cpp b/libutils/tests/BlobCache_test.cpp
deleted file mode 100644
index dac4e2c..0000000
--- a/libutils/tests/BlobCache_test.cpp
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- ** Copyright 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 <fcntl.h>
-#include <stdio.h>
-
-#include <gtest/gtest.h>
-
-#include <utils/BlobCache.h>
-#include <utils/Errors.h>
-
-namespace android {
-
-class BlobCacheTest : public ::testing::Test {
-protected:
-    enum {
-        MAX_KEY_SIZE = 6,
-        MAX_VALUE_SIZE = 8,
-        MAX_TOTAL_SIZE = 13,
-    };
-
-    virtual void SetUp() {
-        mBC = new BlobCache(MAX_KEY_SIZE, MAX_VALUE_SIZE, MAX_TOTAL_SIZE);
-    }
-
-    virtual void TearDown() {
-        mBC.clear();
-    }
-
-    sp<BlobCache> mBC;
-};
-
-TEST_F(BlobCacheTest, CacheSingleValueSucceeds) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, buf, 4));
-    ASSERT_EQ('e', buf[0]);
-    ASSERT_EQ('f', buf[1]);
-    ASSERT_EQ('g', buf[2]);
-    ASSERT_EQ('h', buf[3]);
-}
-
-TEST_F(BlobCacheTest, CacheTwoValuesSucceeds) {
-    unsigned char buf[2] = { 0xee, 0xee };
-    mBC->set("ab", 2, "cd", 2);
-    mBC->set("ef", 2, "gh", 2);
-    ASSERT_EQ(size_t(2), mBC->get("ab", 2, buf, 2));
-    ASSERT_EQ('c', buf[0]);
-    ASSERT_EQ('d', buf[1]);
-    ASSERT_EQ(size_t(2), mBC->get("ef", 2, buf, 2));
-    ASSERT_EQ('g', buf[0]);
-    ASSERT_EQ('h', buf[1]);
-}
-
-TEST_F(BlobCacheTest, GetOnlyWritesInsideBounds) {
-    unsigned char buf[6] = { 0xee, 0xee, 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, buf+1, 4));
-    ASSERT_EQ(0xee, buf[0]);
-    ASSERT_EQ('e', buf[1]);
-    ASSERT_EQ('f', buf[2]);
-    ASSERT_EQ('g', buf[3]);
-    ASSERT_EQ('h', buf[4]);
-    ASSERT_EQ(0xee, buf[5]);
-}
-
-TEST_F(BlobCacheTest, GetOnlyWritesIfBufferIsLargeEnough) {
-    unsigned char buf[3] = { 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, buf, 3));
-    ASSERT_EQ(0xee, buf[0]);
-    ASSERT_EQ(0xee, buf[1]);
-    ASSERT_EQ(0xee, buf[2]);
-}
-
-TEST_F(BlobCacheTest, GetDoesntAccessNullBuffer) {
-    mBC->set("abcd", 4, "efgh", 4);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, NULL, 0));
-}
-
-TEST_F(BlobCacheTest, MultipleSetsCacheLatestValue) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    mBC->set("abcd", 4, "ijkl", 4);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, buf, 4));
-    ASSERT_EQ('i', buf[0]);
-    ASSERT_EQ('j', buf[1]);
-    ASSERT_EQ('k', buf[2]);
-    ASSERT_EQ('l', buf[3]);
-}
-
-TEST_F(BlobCacheTest, SecondSetKeepsFirstValueIfTooLarge) {
-    unsigned char buf[MAX_VALUE_SIZE+1] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    mBC->set("abcd", 4, buf, MAX_VALUE_SIZE+1);
-    ASSERT_EQ(size_t(4), mBC->get("abcd", 4, buf, 4));
-    ASSERT_EQ('e', buf[0]);
-    ASSERT_EQ('f', buf[1]);
-    ASSERT_EQ('g', buf[2]);
-    ASSERT_EQ('h', buf[3]);
-}
-
-TEST_F(BlobCacheTest, DoesntCacheIfKeyIsTooBig) {
-    char key[MAX_KEY_SIZE+1];
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    for (int i = 0; i < MAX_KEY_SIZE+1; i++) {
-        key[i] = 'a';
-    }
-    mBC->set(key, MAX_KEY_SIZE+1, "bbbb", 4);
-    ASSERT_EQ(size_t(0), mBC->get(key, MAX_KEY_SIZE+1, buf, 4));
-    ASSERT_EQ(0xee, buf[0]);
-    ASSERT_EQ(0xee, buf[1]);
-    ASSERT_EQ(0xee, buf[2]);
-    ASSERT_EQ(0xee, buf[3]);
-}
-
-TEST_F(BlobCacheTest, DoesntCacheIfValueIsTooBig) {
-    char buf[MAX_VALUE_SIZE+1];
-    for (int i = 0; i < MAX_VALUE_SIZE+1; i++) {
-        buf[i] = 'b';
-    }
-    mBC->set("abcd", 4, buf, MAX_VALUE_SIZE+1);
-    for (int i = 0; i < MAX_VALUE_SIZE+1; i++) {
-        buf[i] = 0xee;
-    }
-    ASSERT_EQ(size_t(0), mBC->get("abcd", 4, buf, MAX_VALUE_SIZE+1));
-    for (int i = 0; i < MAX_VALUE_SIZE+1; i++) {
-        SCOPED_TRACE(i);
-        ASSERT_EQ(0xee, buf[i]);
-    }
-}
-
-TEST_F(BlobCacheTest, DoesntCacheIfKeyValuePairIsTooBig) {
-    // Check a testing assumptions
-    ASSERT_TRUE(MAX_TOTAL_SIZE < MAX_KEY_SIZE + MAX_VALUE_SIZE);
-    ASSERT_TRUE(MAX_KEY_SIZE < MAX_TOTAL_SIZE);
-
-    enum { bufSize = MAX_TOTAL_SIZE - MAX_KEY_SIZE + 1 };
-
-    char key[MAX_KEY_SIZE];
-    char buf[bufSize];
-    for (int i = 0; i < MAX_KEY_SIZE; i++) {
-        key[i] = 'a';
-    }
-    for (int i = 0; i < bufSize; i++) {
-        buf[i] = 'b';
-    }
-
-    mBC->set(key, MAX_KEY_SIZE, buf, MAX_VALUE_SIZE);
-    ASSERT_EQ(size_t(0), mBC->get(key, MAX_KEY_SIZE, NULL, 0));
-}
-
-TEST_F(BlobCacheTest, CacheMaxKeySizeSucceeds) {
-    char key[MAX_KEY_SIZE];
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    for (int i = 0; i < MAX_KEY_SIZE; i++) {
-        key[i] = 'a';
-    }
-    mBC->set(key, MAX_KEY_SIZE, "wxyz", 4);
-    ASSERT_EQ(size_t(4), mBC->get(key, MAX_KEY_SIZE, buf, 4));
-    ASSERT_EQ('w', buf[0]);
-    ASSERT_EQ('x', buf[1]);
-    ASSERT_EQ('y', buf[2]);
-    ASSERT_EQ('z', buf[3]);
-}
-
-TEST_F(BlobCacheTest, CacheMaxValueSizeSucceeds) {
-    char buf[MAX_VALUE_SIZE];
-    for (int i = 0; i < MAX_VALUE_SIZE; i++) {
-        buf[i] = 'b';
-    }
-    mBC->set("abcd", 4, buf, MAX_VALUE_SIZE);
-    for (int i = 0; i < MAX_VALUE_SIZE; i++) {
-        buf[i] = 0xee;
-    }
-    ASSERT_EQ(size_t(MAX_VALUE_SIZE), mBC->get("abcd", 4, buf,
-            MAX_VALUE_SIZE));
-    for (int i = 0; i < MAX_VALUE_SIZE; i++) {
-        SCOPED_TRACE(i);
-        ASSERT_EQ('b', buf[i]);
-    }
-}
-
-TEST_F(BlobCacheTest, CacheMaxKeyValuePairSizeSucceeds) {
-    // Check a testing assumption
-    ASSERT_TRUE(MAX_KEY_SIZE < MAX_TOTAL_SIZE);
-
-    enum { bufSize = MAX_TOTAL_SIZE - MAX_KEY_SIZE };
-
-    char key[MAX_KEY_SIZE];
-    char buf[bufSize];
-    for (int i = 0; i < MAX_KEY_SIZE; i++) {
-        key[i] = 'a';
-    }
-    for (int i = 0; i < bufSize; i++) {
-        buf[i] = 'b';
-    }
-
-    mBC->set(key, MAX_KEY_SIZE, buf, bufSize);
-    ASSERT_EQ(size_t(bufSize), mBC->get(key, MAX_KEY_SIZE, NULL, 0));
-}
-
-TEST_F(BlobCacheTest, CacheMinKeyAndValueSizeSucceeds) {
-    unsigned char buf[1] = { 0xee };
-    mBC->set("x", 1, "y", 1);
-    ASSERT_EQ(size_t(1), mBC->get("x", 1, buf, 1));
-    ASSERT_EQ('y', buf[0]);
-}
-
-TEST_F(BlobCacheTest, CacheSizeDoesntExceedTotalLimit) {
-    for (int i = 0; i < 256; i++) {
-        uint8_t k = i;
-        mBC->set(&k, 1, "x", 1);
-    }
-    int numCached = 0;
-    for (int i = 0; i < 256; i++) {
-        uint8_t k = i;
-        if (mBC->get(&k, 1, NULL, 0) == 1) {
-            numCached++;
-        }
-    }
-    ASSERT_GE(MAX_TOTAL_SIZE / 2, numCached);
-}
-
-TEST_F(BlobCacheTest, ExceedingTotalLimitHalvesCacheSize) {
-    // Fill up the entire cache with 1 char key/value pairs.
-    const int maxEntries = MAX_TOTAL_SIZE / 2;
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        mBC->set(&k, 1, "x", 1);
-    }
-    // Insert one more entry, causing a cache overflow.
-    {
-        uint8_t k = maxEntries;
-        mBC->set(&k, 1, "x", 1);
-    }
-    // Count the number of entries in the cache.
-    int numCached = 0;
-    for (int i = 0; i < maxEntries+1; i++) {
-        uint8_t k = i;
-        if (mBC->get(&k, 1, NULL, 0) == 1) {
-            numCached++;
-        }
-    }
-    ASSERT_EQ(maxEntries/2 + 1, numCached);
-}
-
-class BlobCacheFlattenTest : public BlobCacheTest {
-protected:
-    virtual void SetUp() {
-        BlobCacheTest::SetUp();
-        mBC2 = new BlobCache(MAX_KEY_SIZE, MAX_VALUE_SIZE, MAX_TOTAL_SIZE);
-    }
-
-    virtual void TearDown() {
-        mBC2.clear();
-        BlobCacheTest::TearDown();
-    }
-
-    void roundTrip() {
-        size_t size = mBC->getFlattenedSize();
-        uint8_t* flat = new uint8_t[size];
-        ASSERT_EQ(OK, mBC->flatten(flat, size));
-        ASSERT_EQ(OK, mBC2->unflatten(flat, size));
-        delete[] flat;
-    }
-
-    sp<BlobCache> mBC2;
-};
-
-TEST_F(BlobCacheFlattenTest, FlattenOneValue) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-    roundTrip();
-    ASSERT_EQ(size_t(4), mBC2->get("abcd", 4, buf, 4));
-    ASSERT_EQ('e', buf[0]);
-    ASSERT_EQ('f', buf[1]);
-    ASSERT_EQ('g', buf[2]);
-    ASSERT_EQ('h', buf[3]);
-}
-
-TEST_F(BlobCacheFlattenTest, FlattenFullCache) {
-    // Fill up the entire cache with 1 char key/value pairs.
-    const int maxEntries = MAX_TOTAL_SIZE / 2;
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        mBC->set(&k, 1, &k, 1);
-    }
-
-    roundTrip();
-
-    // Verify the deserialized cache
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        uint8_t v = 0xee;
-        ASSERT_EQ(size_t(1), mBC2->get(&k, 1, &v, 1));
-        ASSERT_EQ(k, v);
-    }
-}
-
-TEST_F(BlobCacheFlattenTest, FlattenDoesntChangeCache) {
-    // Fill up the entire cache with 1 char key/value pairs.
-    const int maxEntries = MAX_TOTAL_SIZE / 2;
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        mBC->set(&k, 1, &k, 1);
-    }
-
-    size_t size = mBC->getFlattenedSize();
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(OK, mBC->flatten(flat, size));
-    delete[] flat;
-
-    // Verify the cache that we just serialized
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        uint8_t v = 0xee;
-        ASSERT_EQ(size_t(1), mBC->get(&k, 1, &v, 1));
-        ASSERT_EQ(k, v);
-    }
-}
-
-TEST_F(BlobCacheFlattenTest, FlattenCatchesBufferTooSmall) {
-    // Fill up the entire cache with 1 char key/value pairs.
-    const int maxEntries = MAX_TOTAL_SIZE / 2;
-    for (int i = 0; i < maxEntries; i++) {
-        uint8_t k = i;
-        mBC->set(&k, 1, &k, 1);
-    }
-
-    size_t size = mBC->getFlattenedSize() - 1;
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(BAD_VALUE, mBC->flatten(flat, size));
-    delete[] flat;
-}
-
-TEST_F(BlobCacheFlattenTest, UnflattenCatchesBadMagic) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-
-    size_t size = mBC->getFlattenedSize();
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(OK, mBC->flatten(flat, size));
-    flat[1] = ~flat[1];
-
-    // Bad magic should cause an error.
-    ASSERT_EQ(BAD_VALUE, mBC2->unflatten(flat, size));
-    delete[] flat;
-
-    // The error should cause the unflatten to result in an empty cache
-    ASSERT_EQ(size_t(0), mBC2->get("abcd", 4, buf, 4));
-}
-
-TEST_F(BlobCacheFlattenTest, UnflattenCatchesBadBlobCacheVersion) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-
-    size_t size = mBC->getFlattenedSize();
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(OK, mBC->flatten(flat, size));
-    flat[5] = ~flat[5];
-
-    // Version mismatches shouldn't cause errors, but should not use the
-    // serialized entries
-    ASSERT_EQ(OK, mBC2->unflatten(flat, size));
-    delete[] flat;
-
-    // The version mismatch should cause the unflatten to result in an empty
-    // cache
-    ASSERT_EQ(size_t(0), mBC2->get("abcd", 4, buf, 4));
-}
-
-TEST_F(BlobCacheFlattenTest, UnflattenCatchesBadBlobCacheDeviceVersion) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-
-    size_t size = mBC->getFlattenedSize();
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(OK, mBC->flatten(flat, size));
-    flat[10] = ~flat[10];
-
-    // Version mismatches shouldn't cause errors, but should not use the
-    // serialized entries
-    ASSERT_EQ(OK, mBC2->unflatten(flat, size));
-    delete[] flat;
-
-    // The version mismatch should cause the unflatten to result in an empty
-    // cache
-    ASSERT_EQ(size_t(0), mBC2->get("abcd", 4, buf, 4));
-}
-
-TEST_F(BlobCacheFlattenTest, UnflattenCatchesBufferTooSmall) {
-    unsigned char buf[4] = { 0xee, 0xee, 0xee, 0xee };
-    mBC->set("abcd", 4, "efgh", 4);
-
-    size_t size = mBC->getFlattenedSize();
-    uint8_t* flat = new uint8_t[size];
-    ASSERT_EQ(OK, mBC->flatten(flat, size));
-
-    // A buffer truncation shouldt cause an error
-    ASSERT_EQ(BAD_VALUE, mBC2->unflatten(flat, size-1));
-    delete[] flat;
-
-    // The error should cause the unflatten to result in an empty cache
-    ASSERT_EQ(size_t(0), mBC2->get("abcd", 4, buf, 4));
-}
-
-} // namespace android
diff --git a/libutils/tests/Looper_test.cpp b/libutils/tests/Looper_test.cpp
index 17319e0..8ebcfaf 100644
--- a/libutils/tests/Looper_test.cpp
+++ b/libutils/tests/Looper_test.cpp
@@ -76,7 +76,7 @@
     int fd;
     int events;
 
-    StubCallbackHandler(int nextResult) : nextResult(nextResult),
+    explicit StubCallbackHandler(int nextResult) : nextResult(nextResult),
             callbackCount(0), fd(-1), events(-1) {
     }
 
diff --git a/libutils/tests/LruCache_test.cpp b/libutils/tests/LruCache_test.cpp
index dd95c57..4e885bb 100644
--- a/libutils/tests/LruCache_test.cpp
+++ b/libutils/tests/LruCache_test.cpp
@@ -15,10 +15,11 @@
  */
 
 #include <stdlib.h>
+
+#include <android/log.h>
+#include <gtest/gtest.h>
 #include <utils/JenkinsHash.h>
 #include <utils/LruCache.h>
-#include <cutils/log.h>
-#include <gtest/gtest.h>
 
 namespace {
 
@@ -80,6 +81,14 @@
     }
 };
 
+struct KeyFailsOnCopy : public ComplexKey {
+    public:
+    KeyFailsOnCopy(const KeyFailsOnCopy& key) : ComplexKey(key) {
+        ADD_FAILURE();
+    }
+    KeyFailsOnCopy(int key) : ComplexKey(key) { }
+};
+
 } // namespace
 
 
@@ -95,6 +104,10 @@
     return hash_type(*value.ptr);
 }
 
+template<> inline android::hash_t hash_type(const KeyFailsOnCopy& value) {
+    return hash_type<ComplexKey>(value);
+}
+
 class EntryRemovedCallback : public OnEntryRemoved<SimpleKey, StringValue> {
 public:
     EntryRemovedCallback() : callbackCount(0), lastKey(-1), lastValue(NULL) { }
@@ -437,4 +450,10 @@
     EXPECT_EQ(std::unordered_set<int>({ 4, 5, 6 }), returnedValues);
 }
 
+TEST_F(LruCacheTest, DontCopyKeyInGet) {
+    LruCache<KeyFailsOnCopy, KeyFailsOnCopy> cache(1);
+    // Check that get doesn't copy the key
+    cache.get(KeyFailsOnCopy(0));
+}
+
 }
diff --git a/libutils/tests/README.txt b/libutils/tests/README.txt
new file mode 100644
index 0000000..ad54e57
--- /dev/null
+++ b/libutils/tests/README.txt
@@ -0,0 +1,8 @@
+Run device tests:
+
+mma -j<whatever>
+(after adb root; adb disable-verity; adb reboot)
+adb root
+adb remount
+adb sync
+adb shell /data/nativetest/libutils_tests/libutils_tests
diff --git a/libutils/tests/RefBase_test.cpp b/libutils/tests/RefBase_test.cpp
new file mode 100644
index 0000000..2e0cf6e
--- /dev/null
+++ b/libutils/tests/RefBase_test.cpp
@@ -0,0 +1,258 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include <utils/StrongPointer.h>
+#include <utils/RefBase.h>
+
+#include <thread>
+#include <atomic>
+#include <sched.h>
+#include <errno.h>
+
+// Enhanced version of StrongPointer_test, but using RefBase underneath.
+
+using namespace android;
+
+static constexpr int NITERS = 1000000;
+
+static constexpr int INITIAL_STRONG_VALUE = 1 << 28;  // Mirroring RefBase definition.
+
+class Foo : public RefBase {
+public:
+    Foo(bool* deleted_check) : mDeleted(deleted_check) {
+        *mDeleted = false;
+    }
+
+    ~Foo() {
+        *mDeleted = true;
+    }
+private:
+    bool* mDeleted;
+};
+
+TEST(RefBase, StrongMoves) {
+    bool isDeleted;
+    Foo* foo = new Foo(&isDeleted);
+    ASSERT_EQ(INITIAL_STRONG_VALUE, foo->getStrongCount());
+    ASSERT_FALSE(isDeleted) << "Already deleted...?";
+    sp<Foo> sp1(foo);
+    wp<Foo> wp1(sp1);
+    ASSERT_EQ(1, foo->getStrongCount());
+    // Weak count includes both strong and weak references.
+    ASSERT_EQ(2, foo->getWeakRefs()->getWeakCount());
+    {
+        sp<Foo> sp2 = std::move(sp1);
+        ASSERT_EQ(1, foo->getStrongCount())
+                << "std::move failed, incremented refcnt";
+        ASSERT_EQ(nullptr, sp1.get()) << "std::move failed, sp1 is still valid";
+        // The strong count isn't increasing, let's double check the old object
+        // is properly reset and doesn't early delete
+        sp1 = std::move(sp2);
+    }
+    ASSERT_FALSE(isDeleted) << "deleted too early! still has a reference!";
+    {
+        // Now let's double check it deletes on time
+        sp<Foo> sp2 = std::move(sp1);
+    }
+    ASSERT_TRUE(isDeleted) << "foo was leaked!";
+    ASSERT_TRUE(wp1.promote().get() == nullptr);
+}
+
+TEST(RefBase, WeakCopies) {
+    bool isDeleted;
+    Foo* foo = new Foo(&isDeleted);
+    EXPECT_EQ(0, foo->getWeakRefs()->getWeakCount());
+    ASSERT_FALSE(isDeleted) << "Foo (weak) already deleted...?";
+    wp<Foo> wp1(foo);
+    EXPECT_EQ(1, foo->getWeakRefs()->getWeakCount());
+    {
+        wp<Foo> wp2 = wp1;
+        ASSERT_EQ(2, foo->getWeakRefs()->getWeakCount());
+    }
+    EXPECT_EQ(1, foo->getWeakRefs()->getWeakCount());
+    ASSERT_FALSE(isDeleted) << "deleted too early! still has a reference!";
+    wp1 = nullptr;
+    ASSERT_FALSE(isDeleted) << "Deletion on wp destruction should no longer occur";
+}
+
+
+// Set up a situation in which we race with visit2AndRremove() to delete
+// 2 strong references.  Bar destructor checks that there are no early
+// deletions and prior updates are visible to destructor.
+class Bar : public RefBase {
+public:
+    Bar(std::atomic<int>* delete_count) : mVisited1(false), mVisited2(false),
+            mDeleteCount(delete_count) {
+    }
+
+    ~Bar() {
+        EXPECT_TRUE(mVisited1);
+        EXPECT_TRUE(mVisited2);
+        (*mDeleteCount)++;
+    }
+    bool mVisited1;
+    bool mVisited2;
+private:
+    std::atomic<int>* mDeleteCount;
+};
+
+static sp<Bar> buffer;
+static std::atomic<bool> bufferFull(false);
+
+// Wait until bufferFull has value val.
+static inline void waitFor(bool val) {
+    while (bufferFull != val) {}
+}
+
+cpu_set_t otherCpus;
+
+// Divide the cpus we're allowed to run on into myCpus and otherCpus.
+// Set origCpus to the processors we were originally allowed to run on.
+// Return false if origCpus doesn't include at least processors 0 and 1.
+static bool setExclusiveCpus(cpu_set_t* origCpus /* out */,
+        cpu_set_t* myCpus /* out */, cpu_set_t* otherCpus) {
+    if (sched_getaffinity(0, sizeof(cpu_set_t), origCpus) != 0) {
+        return false;
+    }
+    if (!CPU_ISSET(0,  origCpus) || !CPU_ISSET(1, origCpus)) {
+        return false;
+    }
+    CPU_ZERO(myCpus);
+    CPU_ZERO(otherCpus);
+    CPU_OR(myCpus, myCpus, origCpus);
+    CPU_OR(otherCpus, otherCpus, origCpus);
+    for (unsigned i = 0; i < CPU_SETSIZE; ++i) {
+        // I get the even cores, the other thread gets the odd ones.
+        if (i & 1) {
+            CPU_CLR(i, myCpus);
+        } else {
+            CPU_CLR(i, otherCpus);
+        }
+    }
+    return true;
+}
+
+static void visit2AndRemove() {
+    if (sched_setaffinity(0, sizeof(cpu_set_t), &otherCpus) != 0) {
+        FAIL() << "setaffinity returned:" << errno;
+    }
+    for (int i = 0; i < NITERS; ++i) {
+        waitFor(true);
+        buffer->mVisited2 = true;
+        buffer = nullptr;
+        bufferFull = false;
+    }
+}
+
+TEST(RefBase, RacingDestructors) {
+    cpu_set_t origCpus;
+    cpu_set_t myCpus;
+    // Restrict us and the helper thread to disjoint cpu sets.
+    // This prevents us from getting scheduled against each other,
+    // which would be atrociously slow.
+    if (setExclusiveCpus(&origCpus, &myCpus, &otherCpus)) {
+        std::thread t(visit2AndRemove);
+        std::atomic<int> deleteCount(0);
+        if (sched_setaffinity(0, sizeof(cpu_set_t), &myCpus) != 0) {
+            FAIL() << "setaffinity returned:" << errno;
+        }
+        for (int i = 0; i < NITERS; ++i) {
+            waitFor(false);
+            Bar* bar = new Bar(&deleteCount);
+            sp<Bar> sp3(bar);
+            buffer = sp3;
+            bufferFull = true;
+            ASSERT_TRUE(bar->getStrongCount() >= 1);
+            // Weak count includes strong count.
+            ASSERT_TRUE(bar->getWeakRefs()->getWeakCount() >= 1);
+            sp3->mVisited1 = true;
+            sp3 = nullptr;
+        }
+        t.join();
+        if (sched_setaffinity(0, sizeof(cpu_set_t), &origCpus) != 0) {
+            FAIL();
+        }
+        ASSERT_EQ(NITERS, deleteCount) << "Deletions missed!";
+    }  // Otherwise this is slow and probably pointless on a uniprocessor.
+}
+
+static wp<Bar> wpBuffer;
+static std::atomic<bool> wpBufferFull(false);
+
+// Wait until wpBufferFull has value val.
+static inline void wpWaitFor(bool val) {
+    while (wpBufferFull != val) {}
+}
+
+static void visit3AndRemove() {
+    if (sched_setaffinity(0, sizeof(cpu_set_t), &otherCpus) != 0) {
+        FAIL() << "setaffinity returned:" << errno;
+    }
+    for (int i = 0; i < NITERS; ++i) {
+        wpWaitFor(true);
+        {
+            sp<Bar> sp1 = wpBuffer.promote();
+            // We implicitly check that sp1 != NULL
+            sp1->mVisited2 = true;
+        }
+        wpBuffer = nullptr;
+        wpBufferFull = false;
+    }
+}
+
+TEST(RefBase, RacingPromotions) {
+    cpu_set_t origCpus;
+    cpu_set_t myCpus;
+    // Restrict us and the helper thread to disjoint cpu sets.
+    // This prevents us from getting scheduled against each other,
+    // which would be atrociously slow.
+    if (setExclusiveCpus(&origCpus, &myCpus, &otherCpus)) {
+        std::thread t(visit3AndRemove);
+        std::atomic<int> deleteCount(0);
+        if (sched_setaffinity(0, sizeof(cpu_set_t), &myCpus) != 0) {
+            FAIL() << "setaffinity returned:" << errno;
+        }
+        for (int i = 0; i < NITERS; ++i) {
+            Bar* bar = new Bar(&deleteCount);
+            wp<Bar> wp1(bar);
+            bar->mVisited1 = true;
+            if (i % (NITERS / 10) == 0) {
+                // Do this rarely, since it generates a log message.
+                wp1 = nullptr;  // No longer destroys the object.
+                wp1 = bar;
+            }
+            wpBuffer = wp1;
+            ASSERT_EQ(bar->getWeakRefs()->getWeakCount(), 2);
+            wpBufferFull = true;
+            // Promotion races with that in visit3AndRemove.
+            // This may or may not succeed, but it shouldn't interfere with
+            // the concurrent one.
+            sp<Bar> sp1 = wp1.promote();
+            wpWaitFor(false);  // Waits for other thread to drop strong pointer.
+            sp1 = nullptr;
+            // No strong pointers here.
+            sp1 = wp1.promote();
+            ASSERT_EQ(sp1.get(), nullptr) << "Dead wp promotion succeeded!";
+        }
+        t.join();
+        if (sched_setaffinity(0, sizeof(cpu_set_t), &origCpus) != 0) {
+            FAIL();
+        }
+        ASSERT_EQ(NITERS, deleteCount) << "Deletions missed!";
+    }  // Otherwise this is slow and probably pointless on a uniprocessor.
+}
diff --git a/libutils/tests/Singleton_test.cpp b/libutils/tests/Singleton_test.cpp
new file mode 100644
index 0000000..9acd3c3
--- /dev/null
+++ b/libutils/tests/Singleton_test.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "Singleton_test"
+
+#include <dlfcn.h>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <utils/Singleton.h>
+
+#include <gtest/gtest.h>
+
+#include "Singleton_test.h"
+
+namespace android {
+
+TEST(SingletonTest, bug35674422) {
+    std::string path = android::base::GetExecutableDirectory();
+    // libutils_tests_singleton1.so contains the ANDROID_SINGLETON_STATIC_INSTANCE
+    // definition of SingletonTestData, load it first.
+    std::string lib = android::base::StringPrintf("%s/libutils_tests_singleton1.so", path.c_str());
+    void* handle1 = dlopen(lib.c_str(), RTLD_NOW);
+    ASSERT_TRUE(handle1 != nullptr) << dlerror();
+
+    // libutils_tests_singleton2.so references SingletonTestData but should not
+    // have a definition
+    lib = android::base::StringPrintf("%s/libutils_tests_singleton2.so", path.c_str());
+    void* handle2 = dlopen(lib.c_str(), RTLD_NOW);
+    ASSERT_TRUE(handle2 != nullptr) << dlerror();
+
+    using has_fn_t = decltype(&singletonHasInstance);
+    using get_fn_t = decltype(&singletonGetInstanceContents);
+    using set_fn_t = decltype(&singletonSetInstanceContents);
+
+    has_fn_t has1 = reinterpret_cast<has_fn_t>(dlsym(handle1, "singletonHasInstance"));
+    ASSERT_TRUE(has1 != nullptr) << dlerror();
+    has_fn_t has2 = reinterpret_cast<has_fn_t>(dlsym(handle2, "singletonHasInstance"));
+    ASSERT_TRUE(has2 != nullptr) << dlerror();
+    get_fn_t get1 = reinterpret_cast<get_fn_t>(dlsym(handle1, "singletonGetInstanceContents"));
+    ASSERT_TRUE(get1 != nullptr) << dlerror();
+    get_fn_t get2 = reinterpret_cast<get_fn_t>(dlsym(handle2, "singletonGetInstanceContents"));
+    ASSERT_TRUE(get2 != nullptr) << dlerror();
+    set_fn_t set1 = reinterpret_cast<set_fn_t>(dlsym(handle2, "singletonSetInstanceContents"));
+    ASSERT_TRUE(set1 != nullptr) << dlerror();
+
+    EXPECT_FALSE(has1());
+    EXPECT_FALSE(has2());
+    set1(12345678U);
+    EXPECT_TRUE(has1());
+    EXPECT_TRUE(has2());
+    EXPECT_EQ(12345678U, get1());
+    EXPECT_EQ(12345678U, get2());
+}
+
+}
diff --git a/libutils/tests/Singleton_test.h b/libutils/tests/Singleton_test.h
new file mode 100644
index 0000000..c77d9ff
--- /dev/null
+++ b/libutils/tests/Singleton_test.h
@@ -0,0 +1,41 @@
+/*
+ * 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_UTILS_SINGLETON_TEST_H
+#define ANDROID_UTILS_SINGLETON_TEST_H
+
+#include <sys/cdefs.h>
+
+#include "Singleton_test.h"
+
+namespace android {
+
+struct SingletonTestData : Singleton<SingletonTestData> {
+    unsigned int contents;
+};
+
+__BEGIN_DECLS
+
+unsigned int singletonGetInstanceContents();
+void singletonSetInstanceContents(unsigned int);
+bool singletonHasInstance();
+
+__END_DECLS
+
+}
+
+#endif // ANDROID_UTILS_SINGLETON_TEST_H
+
diff --git a/libutils/tests/Singleton_test1.cpp b/libutils/tests/Singleton_test1.cpp
new file mode 100644
index 0000000..4a91ec0
--- /dev/null
+++ b/libutils/tests/Singleton_test1.cpp
@@ -0,0 +1,39 @@
+/*
+ * 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 <utils/Singleton.h>
+
+#include "Singleton_test.h"
+
+namespace android {
+
+// Singleton<SingletonTestStruct> is referenced in Singleton_test1.cpp and
+// Singleton_test2.cpp, but only defined in Singleton_test1.cpp.
+ANDROID_SINGLETON_STATIC_INSTANCE(SingletonTestData);
+
+void singletonSetInstanceContents(unsigned int contents) {
+    SingletonTestData::getInstance().contents = contents;
+}
+
+unsigned int singletonGetInstanceContents() {
+    return SingletonTestData::getInstance().contents;
+}
+
+bool singletonHasInstance() {
+    return SingletonTestData::hasInstance();
+}
+
+}
diff --git a/libutils/tests/Singleton_test2.cpp b/libutils/tests/Singleton_test2.cpp
new file mode 100644
index 0000000..eb2a9df
--- /dev/null
+++ b/libutils/tests/Singleton_test2.cpp
@@ -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.
+ */
+
+#include <utils/Singleton.h>
+
+#include "Singleton_test.h"
+
+namespace android {
+
+// Singleton<SingletonTestStruct> is referenced in Singleton_test1.cpp and
+// Singleton_test2.cpp, but only defined in Singleton_test1.cpp.
+
+void singletonSetInstanceContents(unsigned int contents) {
+    SingletonTestData::getInstance().contents = contents;
+}
+
+unsigned int singletonGetInstanceContents() {
+    return SingletonTestData::getInstance().contents;
+}
+
+bool singletonHasInstance() {
+    return SingletonTestData::hasInstance();
+}
+
+}
diff --git a/libutils/tests/StrongPointer_test.cpp b/libutils/tests/StrongPointer_test.cpp
index f46d6d1..153cf96 100644
--- a/libutils/tests/StrongPointer_test.cpp
+++ b/libutils/tests/StrongPointer_test.cpp
@@ -21,13 +21,13 @@
 
 using namespace android;
 
-class Foo : public LightRefBase<Foo> {
+class SPFoo : public LightRefBase<SPFoo> {
 public:
-    Foo(bool* deleted_check) : mDeleted(deleted_check) {
+    explicit SPFoo(bool* deleted_check) : mDeleted(deleted_check) {
         *mDeleted = false;
     }
 
-    ~Foo() {
+    ~SPFoo() {
         *mDeleted = true;
     }
 private:
@@ -36,13 +36,13 @@
 
 TEST(StrongPointer, move) {
     bool isDeleted;
-    Foo* foo = new Foo(&isDeleted);
+    SPFoo* foo = new SPFoo(&isDeleted);
     ASSERT_EQ(0, foo->getStrongCount());
     ASSERT_FALSE(isDeleted) << "Already deleted...?";
-    sp<Foo> sp1(foo);
+    sp<SPFoo> sp1(foo);
     ASSERT_EQ(1, foo->getStrongCount());
     {
-        sp<Foo> sp2 = std::move(sp1);
+        sp<SPFoo> sp2 = std::move(sp1);
         ASSERT_EQ(1, foo->getStrongCount()) << "std::move failed, incremented refcnt";
         ASSERT_EQ(nullptr, sp1.get()) << "std::move failed, sp1 is still valid";
         // The strong count isn't increasing, let's double check the old object
@@ -52,7 +52,7 @@
     ASSERT_FALSE(isDeleted) << "deleted too early! still has a reference!";
     {
         // Now let's double check it deletes on time
-        sp<Foo> sp2 = std::move(sp1);
+        sp<SPFoo> sp2 = std::move(sp1);
     }
     ASSERT_TRUE(isDeleted) << "foo was leaked!";
 }
diff --git a/libutils/tests/SystemClock_test.cpp b/libutils/tests/SystemClock_test.cpp
new file mode 100644
index 0000000..5ad060b
--- /dev/null
+++ b/libutils/tests/SystemClock_test.cpp
@@ -0,0 +1,74 @@
+/*
+ * 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 <unistd.h>
+#include <utils/SystemClock.h>
+
+#include <gtest/gtest.h>
+
+static const auto MS_IN_NS = 1000000;
+
+static const int64_t SLEEP_MS = 500;
+static const int64_t SLEEP_NS = SLEEP_MS * MS_IN_NS;
+// Conservatively assume that we might be descheduled for up to 50 ms
+static const int64_t SLACK_MS = 50;
+static const int64_t SLACK_NS = SLACK_MS * MS_IN_NS;
+
+TEST(SystemClock, SystemClock) {
+    auto startUptimeMs = android::uptimeMillis();
+    auto startRealtimeMs = android::elapsedRealtime();
+    auto startRealtimeNs = android::elapsedRealtimeNano();
+
+    ASSERT_GT(startUptimeMs, 0)
+            << "uptimeMillis() reported an impossible uptime";
+    ASSERT_GE(startRealtimeMs, startUptimeMs)
+            << "elapsedRealtime() thinks we've suspended for negative time";
+    ASSERT_GE(startRealtimeNs, startUptimeMs * MS_IN_NS)
+            << "elapsedRealtimeNano() thinks we've suspended for negative time";
+
+    ASSERT_GE(startRealtimeNs, startRealtimeMs * MS_IN_NS)
+            << "elapsedRealtime() and elapsedRealtimeNano() are inconsistent";
+    ASSERT_LT(startRealtimeNs, (startRealtimeMs + SLACK_MS) * MS_IN_NS)
+            << "elapsedRealtime() and elapsedRealtimeNano() are inconsistent";
+
+    timespec ts;
+    ts.tv_sec = 0;
+    ts.tv_nsec = SLEEP_MS * MS_IN_NS;
+    auto nanosleepErr = TEMP_FAILURE_RETRY(nanosleep(&ts, nullptr));
+    ASSERT_EQ(nanosleepErr, 0) << "nanosleep() failed: " << strerror(errno);
+
+    auto endUptimeMs = android::uptimeMillis();
+    auto endRealtimeMs = android::elapsedRealtime();
+    auto endRealtimeNs = android::elapsedRealtimeNano();
+
+    EXPECT_GE(endUptimeMs - startUptimeMs, SLEEP_MS)
+            << "uptimeMillis() advanced too little after nanosleep()";
+    EXPECT_LT(endUptimeMs - startUptimeMs, SLEEP_MS + SLACK_MS)
+            << "uptimeMillis() advanced too much after nanosleep()";
+    EXPECT_GE(endRealtimeMs - startRealtimeMs, SLEEP_MS)
+            << "elapsedRealtime() advanced too little after nanosleep()";
+    EXPECT_LT(endRealtimeMs - startRealtimeMs, SLEEP_MS + SLACK_MS)
+            << "elapsedRealtime() advanced too much after nanosleep()";
+    EXPECT_GE(endRealtimeNs - startRealtimeNs, SLEEP_NS)
+            << "elapsedRealtimeNano() advanced too little after nanosleep()";
+    EXPECT_LT(endRealtimeNs - startRealtimeNs, SLEEP_NS + SLACK_NS)
+            << "elapsedRealtimeNano() advanced too much after nanosleep()";
+
+    EXPECT_GE(endRealtimeNs, endRealtimeMs * MS_IN_NS)
+            << "elapsedRealtime() and elapsedRealtimeNano() are inconsistent after nanosleep()";
+    EXPECT_LT(endRealtimeNs, (endRealtimeMs + SLACK_MS) * MS_IN_NS)
+            << "elapsedRealtime() and elapsedRealtimeNano() are inconsistent after nanosleep()";
+}
diff --git a/libutils/tests/TestHelpers.h b/libutils/tests/TestHelpers.h
index d8e985e..6801cd7 100644
--- a/libutils/tests/TestHelpers.h
+++ b/libutils/tests/TestHelpers.h
@@ -60,7 +60,7 @@
     int mDelayMillis;
 
 public:
-    DelayedTask(int delayMillis) : mDelayMillis(delayMillis) { }
+    explicit DelayedTask(int delayMillis) : mDelayMillis(delayMillis) { }
 
 protected:
     virtual ~DelayedTask() { }
diff --git a/libutils/tests/Unicode_test.cpp b/libutils/tests/Unicode_test.cpp
index c263f75..d23e43a 100644
--- a/libutils/tests/Unicode_test.cpp
+++ b/libutils/tests/Unicode_test.cpp
@@ -98,7 +98,7 @@
 
     char16_t output[1 + 1 + 1 + 2 + 1]; // Room for NULL
 
-    utf8_to_utf16(str, sizeof(str), output);
+    utf8_to_utf16(str, sizeof(str), output, sizeof(output) / sizeof(output[0]));
 
     EXPECT_EQ(0x0030, output[0])
             << "should be U+0030";
@@ -147,4 +147,15 @@
     EXPECT_EQ(nullptr, result);
 }
 
+// http://b/29267949
+// Test that overreading in utf8_to_utf16_length is detected
+TEST_F(UnicodeTest, InvalidUtf8OverreadDetected) {
+    // An utf8 char starting with \xc4 is two bytes long.
+    // Add extra zeros so no extra memory is read in case the code doesn't
+    // work as expected.
+    static char utf8[] = "\xc4\x00\x00\x00";
+    ASSERT_DEATH(utf8_to_utf16_length((uint8_t *) utf8, strlen(utf8),
+            true /* overreadIsFatal */), "" /* regex for ASSERT_DEATH */);
+}
+
 }
diff --git a/libutils/tests/Vector_test.cpp b/libutils/tests/Vector_test.cpp
index d9b32f9..e074a92 100644
--- a/libutils/tests/Vector_test.cpp
+++ b/libutils/tests/Vector_test.cpp
@@ -18,11 +18,12 @@
 
 #define __STDC_LIMIT_MACROS
 #include <stdint.h>
-#include <utils/Vector.h>
-#include <cutils/log.h>
-#include <gtest/gtest.h>
 #include <unistd.h>
 
+#include <android/log.h>
+#include <gtest/gtest.h>
+#include <utils/Vector.h>
+
 namespace android {
 
 class VectorTest : public testing::Test {
@@ -73,12 +74,9 @@
     EXPECT_EQ(other[3], 5);
 }
 
-// TODO: gtest isn't capable of parsing Abort messages formatted by
-// Android (fails differently on host and target), so we always need to
-// use an empty error message for death tests.
 TEST_F(VectorTest, SetCapacity_Overflow) {
   Vector<int> vector;
-  EXPECT_DEATH(vector.setCapacity(SIZE_MAX / sizeof(int) + 1), "");
+  EXPECT_DEATH(vector.setCapacity(SIZE_MAX / sizeof(int) + 1), "Assertion failed");
 }
 
 TEST_F(VectorTest, SetCapacity_ShrinkBelowSize) {
@@ -89,25 +87,18 @@
   vector.add(4);
 
   vector.setCapacity(8);
-  ASSERT_EQ(8, vector.capacity());
+  ASSERT_EQ(8U, vector.capacity());
   vector.setCapacity(2);
-  ASSERT_EQ(8, vector.capacity());
+  ASSERT_EQ(8U, vector.capacity());
 }
 
-// NOTE: All of the tests below are useless because of the "TODO" above.
-// We have no way of knowing *why* the process crashed. Given that we're
-// inserting a NULL array, we'll fail with a SIGSEGV eventually. We need
-// the ability to make assertions on the abort message to make sure we're
-// failing for the right reasons.
 TEST_F(VectorTest, _grow_OverflowSize) {
   Vector<int> vector;
   vector.add(1);
 
   // Checks that the size calculation (not the capacity calculation) doesn't
   // overflow : the size here will be (1 + SIZE_MAX).
-  //
-  // EXPECT_DEATH(vector.insertArrayAt(NULL, 0, SIZE_MAX), "new_size_overflow");
-  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, SIZE_MAX), "");
+  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, SIZE_MAX), "new_size overflow");
 }
 
 TEST_F(VectorTest, _grow_OverflowCapacityDoubling) {
@@ -115,18 +106,14 @@
 
   // This should fail because the calculated capacity will overflow even though
   // the size of the vector doesn't.
-  //
-  // EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX - 1)), "new_capacity_overflow");
-  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX - 1)), "");
+  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX - 1)), "new_capacity overflow");
 }
 
 TEST_F(VectorTest, _grow_OverflowBufferAlloc) {
   Vector<int> vector;
   // This should fail because the capacity * sizeof(int) overflows, even
   // though the capacity itself doesn't.
-  //
-  // EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX / 2)), "new_alloc_size overflow");
-  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX / 2)), "");
+  EXPECT_DEATH(vector.insertArrayAt(NULL, 0, (SIZE_MAX / 2)), "new_alloc_size overflow");
 }
 
 TEST_F(VectorTest, editArray_Shared) {
diff --git a/libvndksupport/Android.bp b/libvndksupport/Android.bp
new file mode 100644
index 0000000..b624223
--- /dev/null
+++ b/libvndksupport/Android.bp
@@ -0,0 +1,15 @@
+subdirs = ["tests"]
+
+cc_library {
+    name: "libvndksupport",
+    srcs: ["linker.c"],
+    local_include_dirs: ["include/vndksupport"],
+    export_include_dirs: ["include"],
+    shared_libs: ["liblog"],
+}
+
+llndk_library {
+    name: "libvndksupport",
+    symbol_file: "libvndksupport.map.txt",
+    export_include_dirs: ["include"],
+}
diff --git a/libvndksupport/include/vndksupport/linker.h b/libvndksupport/include/vndksupport/linker.h
new file mode 100644
index 0000000..f509564
--- /dev/null
+++ b/libvndksupport/include/vndksupport/linker.h
@@ -0,0 +1,31 @@
+/*
+ * 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 VNDKSUPPORT_LINKER_H_
+#define VNDKSUPPORT_LINKER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void* android_load_sphal_library(const char* name, int flag);
+
+int android_unload_sphal_library(void* handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // VNDKSUPPORT_LINKER_H_
diff --git a/libvndksupport/libvndksupport.map.txt b/libvndksupport/libvndksupport.map.txt
new file mode 100644
index 0000000..16e38da
--- /dev/null
+++ b/libvndksupport/libvndksupport.map.txt
@@ -0,0 +1,7 @@
+LIBVNDKSUPPORT {
+  global:
+    android_load_sphal_library; # vndk
+    android_unload_sphal_library; # vndk
+  local:
+    *;
+};
diff --git a/libvndksupport/linker.c b/libvndksupport/linker.c
new file mode 100644
index 0000000..289f153
--- /dev/null
+++ b/libvndksupport/linker.c
@@ -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 "linker.h"
+
+#include <android/dlext.h>
+#include <dlfcn.h>
+
+#define LOG_TAG "vndksupport"
+#include <log/log.h>
+
+extern struct android_namespace_t* android_get_exported_namespace(const char*);
+
+void* android_load_sphal_library(const char* name, int flag) {
+    struct android_namespace_t* sphal_namespace = android_get_exported_namespace("sphal");
+    if (sphal_namespace != NULL) {
+        const android_dlextinfo dlextinfo = {
+            .flags = ANDROID_DLEXT_USE_NAMESPACE, .library_namespace = sphal_namespace,
+        };
+        void* handle = android_dlopen_ext(name, flag, &dlextinfo);
+        if (!handle) {
+            ALOGE("Could not load %s from sphal namespace: %s.", name, dlerror());
+        }
+        return handle;
+    } else {
+        ALOGI(
+            "sphal namespace is not configured for this process. "
+            "Loading %s from the current namespace instead.",
+            name);
+        return dlopen(name, flag);
+    }
+}
+
+int android_unload_sphal_library(void* handle) { return dlclose(handle); }
diff --git a/libvndksupport/tests/Android.bp b/libvndksupport/tests/Android.bp
new file mode 100644
index 0000000..3587cf8
--- /dev/null
+++ b/libvndksupport/tests/Android.bp
@@ -0,0 +1,26 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_test {
+    name: "libvndksupport-tests",
+    srcs: [
+        "linker_test.cpp",
+    ],
+
+    host_supported: false,
+    shared_libs: [
+        "libvndksupport",
+        "libbase",
+    ]
+}
diff --git a/libvndksupport/tests/linker_test.cpp b/libvndksupport/tests/linker_test.cpp
new file mode 100644
index 0000000..7ce27d4
--- /dev/null
+++ b/libvndksupport/tests/linker_test.cpp
@@ -0,0 +1,60 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include <android-base/strings.h>
+#include <dirent.h>
+#include <dlfcn.h>
+#include <vndksupport/linker.h>
+#include <string>
+
+// Since the test executable will be in /data and ld.config.txt does not
+// configure sphal namespace for executables in /data, the call to
+// android_load_sphal_library will always fallback to the plain dlopen from the
+// default namespace.
+
+// Let's use libEGL_<chipset>.so as a SP-HAL in test
+static std::string find_sphal_lib() {
+    const char* path =
+#if defined(__LP64__)
+        "/vendor/lib64/egl";
+#else
+        "/vendor/lib/egl";
+#endif
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path), closedir);
+
+    dirent* dp;
+    while ((dp = readdir(dir.get())) != nullptr) {
+        std::string name = dp->d_name;
+        if (android::base::StartsWith(name, "libEGL_")) {
+            return std::string(path) + "/" + name;
+        }
+    }
+    return "";
+}
+
+TEST(linker, load_existing_lib) {
+    std::string name = find_sphal_lib();
+    ASSERT_NE("", name);
+    void* handle = android_load_sphal_library(name.c_str(), RTLD_NOW | RTLD_LOCAL);
+    ASSERT_NE(nullptr, handle);
+    android_unload_sphal_library(handle);
+}
+
+TEST(linker, load_nonexisting_lib) {
+    void* handle = android_load_sphal_library("libNeverUseThisName.so", RTLD_NOW | RTLD_LOCAL);
+    ASSERT_EQ(nullptr, handle);
+}
diff --git a/libziparchive/Android.bp b/libziparchive/Android.bp
new file mode 100644
index 0000000..0a4f088
--- /dev/null
+++ b/libziparchive/Android.bp
@@ -0,0 +1,126 @@
+//
+// Copyright (C) 2013 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_defaults {
+    name: "libziparchive_flags",
+    cflags: [
+        // ZLIB_CONST turns on const for input buffers, which is pretty standard.
+        "-DZLIB_CONST",
+        "-Werror",
+        "-Wall",
+        "-D_FILE_OFFSET_BITS=64",
+    ],
+    cppflags: [
+        "-Wold-style-cast",
+        // Incorrectly warns when C++11 empty brace {} initializer is used.
+        // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61489
+        "-Wno-missing-field-initializers",
+    ],
+}
+
+cc_defaults {
+    name: "libziparchive_defaults",
+    srcs: [
+        "zip_archive.cc",
+        "zip_archive_stream_entry.cc",
+        "zip_writer.cc",
+    ],
+
+    target: {
+        windows: {
+            cflags: ["-mno-ms-bitfields"],
+
+            enabled: true,
+        },
+    },
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+}
+
+
+cc_library {
+    name: "libziparchive",
+    host_supported: true,
+    vendor_available:true,
+
+    defaults: ["libziparchive_defaults", "libziparchive_flags"],
+    shared_libs: ["liblog", "libbase"],
+    target: {
+        android: {
+            shared_libs: ["libz", "libutils"],
+        },
+        host: {
+            static_libs: ["libutils"],
+        },
+        linux_bionic: {
+            static_libs: ["libz"],
+            enabled: true,
+        },
+        linux: {
+            shared_libs: ["libz-host"],
+        },
+        darwin: {
+            shared_libs: ["libz-host"],
+        },
+        windows: {
+            shared_libs: ["libz-host"],
+        },
+    },
+}
+
+// Also provide libziparchive-host until everything is switched over to using libziparchive
+cc_library {
+    name: "libziparchive-host",
+    host_supported: true,
+    device_supported: false,
+    defaults: ["libziparchive_defaults", "libziparchive_flags"],
+    shared_libs: ["libz-host"],
+    static_libs: ["libutils"],
+}
+
+// Tests.
+cc_test {
+    name: "ziparchive-tests",
+    host_supported: true,
+    defaults: ["libziparchive_flags"],
+
+    srcs: [
+        "entry_name_utils_test.cc",
+        "zip_archive_test.cc",
+        "zip_writer_test.cc",
+    ],
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libziparchive",
+        "libz",
+        "libutils",
+    ],
+
+    target: {
+        host: {
+            cppflags: ["-Wno-unnamed-type-template-args"],
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk
deleted file mode 100644
index 3cd8b87..0000000
--- a/libziparchive/Android.mk
+++ /dev/null
@@ -1,106 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-libziparchive_source_files := \
-    zip_archive.cc \
-    zip_archive_stream_entry.cc \
-    zip_writer.cc \
-
-libziparchive_test_files := \
-    entry_name_utils_test.cc \
-    zip_archive_test.cc \
-    zip_writer_test.cc \
-
-# ZLIB_CONST turns on const for input buffers, which is pretty standard.
-libziparchive_common_c_flags := \
-    -DZLIB_CONST \
-    -Werror \
-    -Wall \
-
-# Incorrectly warns when C++11 empty brace {} initializer is used.
-# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61489
-libziparchive_common_cpp_flags := \
-    -Wold-style-cast \
-    -Wno-missing-field-initializers \
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libz
-LOCAL_SHARED_LIBRARIES := libutils libbase
-LOCAL_MODULE:= libziparchive
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libz libutils libbase
-LOCAL_MODULE:= libziparchive-host
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CFLAGS_windows := -mno-ms-bitfields
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-
-LOCAL_MULTILIB := both
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_SRC_FILES := $(libziparchive_source_files)
-LOCAL_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := libz-host liblog libbase
-LOCAL_MODULE:= libziparchive-host
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-LOCAL_MULTILIB := both
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Tests.
-include $(CLEAR_VARS)
-LOCAL_MODULE := ziparchive-tests
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := $(libziparchive_common_cpp_flags)
-LOCAL_SRC_FILES := $(libziparchive_test_files)
-LOCAL_SHARED_LIBRARIES := \
-    libbase \
-    liblog \
-
-LOCAL_STATIC_LIBRARIES := \
-    libziparchive \
-    libz \
-    libutils \
-
-include $(BUILD_NATIVE_TEST)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := ziparchive-tests-host
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(libziparchive_common_c_flags)
-LOCAL_CPPFLAGS := -Wno-unnamed-type-template-args $(libziparchive_common_cpp_flags)
-LOCAL_SRC_FILES := $(libziparchive_test_files)
-LOCAL_STATIC_LIBRARIES := \
-    libziparchive-host \
-    libz \
-    libbase \
-    libutils \
-    liblog \
-
-LOCAL_MODULE_HOST_OS := darwin linux windows
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libziparchive/testdata/bad_filename.zip b/libziparchive/testdata/bad_filename.zip
new file mode 100644
index 0000000..294eaf5
--- /dev/null
+++ b/libziparchive/testdata/bad_filename.zip
Binary files differ
diff --git a/libziparchive/testdata/crash.apk b/libziparchive/testdata/crash.apk
new file mode 100644
index 0000000..d6dd52d
--- /dev/null
+++ b/libziparchive/testdata/crash.apk
Binary files differ
diff --git a/libziparchive/testdata/dummy-update.zip b/libziparchive/testdata/dummy-update.zip
new file mode 100644
index 0000000..6976bf1
--- /dev/null
+++ b/libziparchive/testdata/dummy-update.zip
Binary files differ
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 49097ce..78de40a 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -18,6 +18,8 @@
  * Read-only access to Zip archives, with minimal heap allocation.
  */
 
+#define LOG_TAG "ziparchive"
+
 #include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -30,12 +32,13 @@
 #include <memory>
 #include <vector>
 
-#include "android-base/file.h"
-#include "android-base/macros.h"  // TEMP_FAILURE_RETRY may or may not be in unistd
-#include "android-base/memory.h"
-#include "log/log.h"
-#include "utils/Compat.h"
-#include "utils/FileMap.h"
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>  // TEMP_FAILURE_RETRY may or may not be in unistd
+#include <android-base/memory.h>
+#include <log/log.h>
+#include <utils/Compat.h>
+#include <utils/FileMap.h>
 #include "ziparchive/zip_archive.h"
 #include "zlib.h"
 
@@ -214,19 +217,14 @@
   return 0;
 }
 
-static int32_t MapCentralDirectory0(int fd, const char* debug_file_name,
-                                    ZipArchive* archive, off64_t file_length,
-                                    off64_t read_amount, uint8_t* scan_buffer) {
+static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
+                                    off64_t file_length, off64_t read_amount,
+                                    uint8_t* scan_buffer) {
   const off64_t search_start = file_length - read_amount;
 
-  if (lseek64(fd, search_start, SEEK_SET) != search_start) {
-    ALOGW("Zip: seek %" PRId64 " failed: %s", static_cast<int64_t>(search_start),
-          strerror(errno));
-    return kIoError;
-  }
-  if (!android::base::ReadFully(fd, scan_buffer, static_cast<size_t>(read_amount))) {
-    ALOGW("Zip: read %" PRId64 " failed: %s", static_cast<int64_t>(read_amount),
-          strerror(errno));
+  if(!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
+    ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed",
+          static_cast<int64_t>(read_amount), static_cast<int64_t>(search_start));
     return kIoError;
   }
 
@@ -291,9 +289,11 @@
    * It all looks good.  Create a mapping for the CD, and set the fields
    * in archive.
    */
-  if (!archive->directory_map.create(debug_file_name, fd,
-          static_cast<off64_t>(eocd->cd_start_offset),
-          static_cast<size_t>(eocd->cd_size), true /* read only */) ) {
+
+  if (!archive->InitializeCentralDirectory(debug_file_name,
+                                           static_cast<off64_t>(eocd->cd_start_offset),
+                                           static_cast<size_t>(eocd->cd_size))) {
+    ALOGE("Zip: failed to intialize central directory.\n");
     return kMmapFailed;
   }
 
@@ -308,18 +308,16 @@
  *
  * On success, returns 0 after populating fields from the EOCD area:
  *   directory_offset
- *   directory_map
+ *   directory_ptr
  *   num_entries
  */
-static int32_t MapCentralDirectory(int fd, const char* debug_file_name,
-                                   ZipArchive* archive) {
+static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
 
   // Test file length. We use lseek64 to make sure the file
   // is small enough to be a zip file (Its size must be less than
   // 0xffffffff bytes).
-  off64_t file_length = lseek64(fd, 0, SEEK_END);
+  off64_t file_length = archive->mapped_zip.GetFileLength();
   if (file_length == -1) {
-    ALOGV("Zip: lseek on fd %d failed", fd);
     return kInvalidFile;
   }
 
@@ -350,11 +348,9 @@
     read_amount = file_length;
   }
 
-  uint8_t* scan_buffer = reinterpret_cast<uint8_t*>(malloc(read_amount));
-  int32_t result = MapCentralDirectory0(fd, debug_file_name, archive,
-                                        file_length, read_amount, scan_buffer);
-
-  free(scan_buffer);
+  std::vector<uint8_t> scan_buffer(read_amount);
+  int32_t result = MapCentralDirectory0(debug_file_name, archive, file_length, read_amount,
+                                        scan_buffer.data());
   return result;
 }
 
@@ -365,9 +361,8 @@
  * Returns 0 on success.
  */
 static int32_t ParseZipArchive(ZipArchive* archive) {
-  const uint8_t* const cd_ptr =
-      reinterpret_cast<const uint8_t*>(archive->directory_map.getDataPtr());
-  const size_t cd_length = archive->directory_map.getDataLength();
+  const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
+  const size_t cd_length = archive->central_directory.GetMapLength();
   const uint16_t num_entries = archive->num_entries;
 
   /*
@@ -378,6 +373,11 @@
   archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
   archive->hash_table = reinterpret_cast<ZipString*>(calloc(archive->hash_table_size,
       sizeof(ZipString)));
+  if (archive->hash_table == nullptr) {
+    ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
+          archive->hash_table_size, sizeof(ZipString));
+    return -1;
+  }
 
   /*
    * Walk through the central directory, adding entries to the hash
@@ -413,6 +413,11 @@
     const uint16_t comment_length = cdr->comment_length;
     const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
 
+    if (file_name + file_name_length > cd_end) {
+      ALOGW("Zip: file name boundary exceeds the central directory range, file_name_length: "
+            "%" PRIx16 ", cd_length: %zu", file_name_length, cd_length);
+      return -1;
+    }
     /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
     if (!IsValidEntryName(file_name, file_name_length)) {
       return -1;
@@ -444,7 +449,7 @@
 static int32_t OpenArchiveInternal(ZipArchive* archive,
                                    const char* debug_file_name) {
   int32_t result = -1;
-  if ((result = MapCentralDirectory(archive->fd, debug_file_name, archive))) {
+  if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
     return result;
   }
 
@@ -475,6 +480,13 @@
   return OpenArchiveInternal(archive, fileName);
 }
 
+int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
+                              ZipArchiveHandle *handle) {
+  ZipArchive* archive = new ZipArchive(address, length);
+  *handle = archive;
+  return OpenArchiveInternal(archive, debug_file_name);
+}
+
 /*
  * Close a ZipArchive, closing the file and freeing the contents.
  */
@@ -484,10 +496,10 @@
   delete archive;
 }
 
-static int32_t UpdateEntryFromDataDescriptor(int fd,
+static int32_t UpdateEntryFromDataDescriptor(MappedZipFile& mapped_zip,
                                              ZipEntry *entry) {
   uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
-  if (!android::base::ReadFully(fd, ddBuf, sizeof(ddBuf))) {
+  if (!mapped_zip.ReadData(ddBuf, sizeof(ddBuf))) {
     return kIoError;
   }
 
@@ -502,23 +514,6 @@
   return 0;
 }
 
-// Attempts to read |len| bytes into |buf| at offset |off|.
-// On non-Windows platforms, callers are guaranteed that the |fd|
-// offset is unchanged and there is no side effect to this call.
-//
-// On Windows platforms this is not thread-safe.
-static inline bool ReadAtOffset(int fd, uint8_t* buf, size_t len, off64_t off) {
-#if !defined(_WIN32)
-  return TEMP_FAILURE_RETRY(pread64(fd, buf, len, off));
-#else
-  if (lseek64(fd, off, SEEK_SET) != off) {
-    ALOGW("Zip: failed seek to offset %" PRId64, off);
-    return false;
-  }
-  return android::base::ReadFully(fd, buf, len);
-#endif
-}
-
 static int32_t FindEntry(const ZipArchive* archive, const int ent,
                          ZipEntry* data) {
   const uint16_t nameLen = archive->hash_table[ent].name_length;
@@ -532,9 +527,8 @@
   // This is the base of our mmapped region, we have to sanity check that
   // the name that's in the hash table is a pointer to a location within
   // this mapped region.
-  const uint8_t* base_ptr = reinterpret_cast<const uint8_t*>(
-    archive->directory_map.getDataPtr());
-  if (ptr < base_ptr || ptr > base_ptr + archive->directory_map.getDataLength()) {
+  const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
+  if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
     ALOGW("Zip: Invalid entry pointer");
     return kInvalidOffset;
   }
@@ -566,7 +560,7 @@
   }
 
   uint8_t lfh_buf[sizeof(LocalFileHeader)];
-  if (!ReadAtOffset(archive->fd, lfh_buf, sizeof(lfh_buf), local_header_offset)) {
+  if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
     ALOGW("Zip: failed reading lfh name from offset %" PRId64,
         static_cast<int64_t>(local_header_offset));
     return kIoError;
@@ -582,6 +576,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 have the same general purpose bit
+  // flags set.
+  if (lfh->gpb_flags != cdr->gpb_flags) {
+    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
@@ -606,19 +611,16 @@
       return kInvalidOffset;
     }
 
-    uint8_t* name_buf = reinterpret_cast<uint8_t*>(malloc(nameLen));
-    if (!ReadAtOffset(archive->fd, name_buf, nameLen, name_offset)) {
+    std::vector<uint8_t> name_buf(nameLen);
+    if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
       ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
-      free(name_buf);
       return kIoError;
     }
 
-    if (memcmp(archive->hash_table[ent].name, name_buf, nameLen)) {
-      free(name_buf);
+    if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
       return kInconsistentInformation;
     }
 
-    free(name_buf);
   } else {
     ALOGW("Zip: lfh name did not match central directory.");
     return kInconsistentInformation;
@@ -808,7 +810,8 @@
   // Creates a FileWriter for |fd| and prepare to write |entry| to it,
   // guaranteeing that the file descriptor is valid and that there's enough
   // space on the volume to write out the entry completely and that the file
-  // is truncated to the correct length.
+  // is truncated to the correct length (no truncation if |fd| references a
+  // block device).
   //
   // Returns a valid FileWriter on success, |nullptr| if an error occurred.
   static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry* entry) {
@@ -833,20 +836,30 @@
       // disk does not have enough space.
       result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
       if (result == -1 && errno == ENOSPC) {
-        ALOGW("Zip: unable to allocate space for file to %" PRId64 ": %s",
-              static_cast<int64_t>(declared_length + current_offset), strerror(errno));
+        ALOGW("Zip: unable to allocate  %" PRId64 " bytes at offset %" PRId64 " : %s",
+              static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
+              strerror(errno));
         return std::unique_ptr<FileWriter>(nullptr);
       }
     }
 #endif  // __linux__
 
-    result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
-    if (result == -1) {
-      ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
-            static_cast<int64_t>(declared_length + current_offset), strerror(errno));
+    struct stat sb;
+    if (fstat(fd, &sb) == -1) {
+      ALOGW("Zip: unable to fstat file: %s", strerror(errno));
       return std::unique_ptr<FileWriter>(nullptr);
     }
 
+    // Block device doesn't support ftruncate(2).
+    if (!S_ISBLK(sb.st_mode)) {
+      result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
+      if (result == -1) {
+        ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
+              static_cast<int64_t>(declared_length + current_offset), strerror(errno));
+        return std::unique_ptr<FileWriter>(nullptr);
+      }
+    }
+
     return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
   }
 
@@ -887,7 +900,7 @@
 }
 #pragma GCC diagnostic pop
 
-static int32_t InflateEntryToWriter(int fd, const ZipEntry* entry,
+static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
                                     Writer* writer, uint64_t* crc_out) {
   const size_t kBufSize = 32768;
   std::vector<uint8_t> read_buf(kBufSize);
@@ -937,7 +950,7 @@
     /* read as much as we can */
     if (zstream.avail_in == 0) {
       const size_t getSize = (compressed_length > kBufSize) ? kBufSize : compressed_length;
-      if (!android::base::ReadFully(fd, read_buf.data(), getSize)) {
+      if (!mapped_zip.ReadData(read_buf.data(), getSize)) {
         ALOGW("Zip: inflate read failed, getSize = %zu: %s", getSize, strerror(errno));
         return kIoError;
       }
@@ -985,7 +998,7 @@
   return 0;
 }
 
-static int32_t CopyEntryToWriter(int fd, const ZipEntry* entry, Writer* writer,
+static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry, Writer* writer,
                                  uint64_t *crc_out) {
   static const uint32_t kBufSize = 32768;
   std::vector<uint8_t> buf(kBufSize);
@@ -999,7 +1012,7 @@
     // Safe conversion because kBufSize is narrow enough for a 32 bit signed
     // value.
     const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
-    if (!android::base::ReadFully(fd, buf.data(), block_size)) {
+    if (!mapped_zip.ReadData(buf.data(), block_size)) {
       ALOGW("CopyFileToFile: copy read failed, block_size = %zu: %s", block_size, strerror(errno));
       return kIoError;
     }
@@ -1022,7 +1035,7 @@
   const uint16_t method = entry->method;
   off64_t data_offset = entry->offset;
 
-  if (lseek64(archive->fd, data_offset, SEEK_SET) != data_offset) {
+  if (!archive->mapped_zip.SeekToOffset(data_offset)) {
     ALOGW("Zip: lseek to data at %" PRId64 " failed", static_cast<int64_t>(data_offset));
     return kIoError;
   }
@@ -1031,13 +1044,13 @@
   int32_t return_value = -1;
   uint64_t crc = 0;
   if (method == kCompressStored) {
-    return_value = CopyEntryToWriter(archive->fd, entry, writer, &crc);
+    return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
   } else if (method == kCompressDeflated) {
-    return_value = InflateEntryToWriter(archive->fd, entry, writer, &crc);
+    return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
   }
 
   if (!return_value && entry->has_data_descriptor) {
-    return_value = UpdateEntryFromDataDescriptor(archive->fd, entry);
+    return_value = UpdateEntryFromDataDescriptor(archive->mapped_zip, entry);
     if (return_value) {
       return return_value;
     }
@@ -1078,5 +1091,152 @@
 }
 
 int GetFileDescriptor(const ZipArchiveHandle handle) {
-  return reinterpret_cast<ZipArchive*>(handle)->fd;
+  return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
+}
+
+ZipString::ZipString(const char* entry_name)
+    : name(reinterpret_cast<const uint8_t*>(entry_name)) {
+  size_t len = strlen(entry_name);
+  CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
+  name_length = static_cast<uint16_t>(len);
+}
+
+#if !defined(_WIN32)
+class ProcessWriter : public Writer {
+ public:
+  ProcessWriter(ProcessZipEntryFunction func, void* cookie) : Writer(),
+    proc_function_(func),
+    cookie_(cookie) {
+  }
+
+  virtual bool Append(uint8_t* buf, size_t buf_size) override {
+    return proc_function_(buf, buf_size, cookie_);
+  }
+
+ private:
+  ProcessZipEntryFunction proc_function_;
+  void* cookie_;
+};
+
+int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
+                                ProcessZipEntryFunction func, void* cookie) {
+  ProcessWriter writer(func, cookie);
+  return ExtractToWriter(handle, entry, &writer);
+}
+
+#endif //!defined(_WIN32)
+
+int MappedZipFile::GetFileDescriptor() const {
+  if (!has_fd_) {
+    ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
+    return -1;
+  }
+  return fd_;
+}
+
+void* MappedZipFile::GetBasePtr() const {
+  if (has_fd_) {
+    ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
+    return nullptr;
+  }
+  return base_ptr_;
+}
+
+off64_t MappedZipFile::GetFileLength() const {
+  if (has_fd_) {
+    off64_t result = lseek64(fd_, 0, SEEK_END);
+    if (result == -1) {
+      ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
+    }
+    return result;
+  } else {
+    if (base_ptr_ == nullptr) {
+      ALOGE("Zip: invalid file map\n");
+      return -1;
+    }
+    return static_cast<off64_t>(data_length_);
+  }
+}
+
+bool MappedZipFile::SeekToOffset(off64_t offset) {
+  if (has_fd_) {
+    if (lseek64(fd_, offset, SEEK_SET) != offset) {
+      ALOGE("Zip: lseek to %" PRId64 " failed: %s\n", offset, strerror(errno));
+      return false;
+    }
+    return true;
+  } else {
+    if (offset < 0 || offset > static_cast<off64_t>(data_length_)) {
+      ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n" , offset,
+            data_length_);
+      return false;
+    }
+
+    read_pos_ = offset;
+    return true;
+  }
+}
+
+bool MappedZipFile::ReadData(uint8_t* buffer, size_t read_amount) {
+  if (has_fd_) {
+    if(!android::base::ReadFully(fd_, buffer, read_amount)) {
+      ALOGE("Zip: read from %d failed\n", fd_);
+      return false;
+    }
+  } else {
+    memcpy(buffer, static_cast<uint8_t*>(base_ptr_) + read_pos_, read_amount);
+    read_pos_ += read_amount;
+  }
+  return true;
+}
+
+// Attempts to read |len| bytes into |buf| at offset |off|.
+bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) {
+#if !defined(_WIN32)
+  if (has_fd_) {
+    if (static_cast<size_t>(TEMP_FAILURE_RETRY(pread64(fd_, buf, len, off))) != len) {
+      ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
+      return false;
+    }
+    return true;
+  }
+#endif
+  if (!SeekToOffset(off)) {
+    return false;
+  }
+  return ReadData(buf, len);
+
+}
+
+void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
+  base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
+  length_ = cd_size;
+}
+
+bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
+                                            size_t cd_size) {
+  if (mapped_zip.HasFd()) {
+    if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(),
+                               cd_start_offset, cd_size, true /* read only */)) {
+      return false;
+    }
+
+    CHECK_EQ(directory_map->getDataLength(), cd_size);
+    central_directory.Initialize(directory_map->getDataPtr(), 0/*offset*/, cd_size);
+  } else {
+    if (mapped_zip.GetBasePtr() == nullptr) {
+      ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
+      return false;
+    }
+    if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
+        mapped_zip.GetFileLength()) {
+      ALOGE("Zip: Failed to map central directory, offset exceeds mapped memory region ("
+            "start_offset %"  PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
+            static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
+      return false;
+    }
+
+    central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
+  }
+  return true;
 }
diff --git a/libziparchive/zip_archive_private.h b/libziparchive/zip_archive_private.h
index ab52368..971db4f 100644
--- a/libziparchive/zip_archive_private.h
+++ b/libziparchive/zip_archive_private.h
@@ -21,17 +21,83 @@
 #include <stdlib.h>
 #include <unistd.h>
 
+#include <memory>
+#include <vector>
+
 #include <utils/FileMap.h>
 #include <ziparchive/zip_archive.h>
 
+class MappedZipFile {
+ public:
+  explicit MappedZipFile(const int fd) :
+    has_fd_(true),
+    fd_(fd),
+    base_ptr_(nullptr),
+    data_length_(0),
+    read_pos_(0) {}
+
+  explicit MappedZipFile(void* address, size_t length) :
+    has_fd_(false),
+    fd_(-1),
+    base_ptr_(address),
+    data_length_(static_cast<off64_t>(length)),
+    read_pos_(0) {}
+
+  bool HasFd() const {return has_fd_;}
+
+  int GetFileDescriptor() const;
+
+  void* GetBasePtr() const;
+
+  off64_t GetFileLength() const;
+
+  bool SeekToOffset(off64_t offset);
+
+  bool ReadData(uint8_t* buffer, size_t read_amount);
+
+  bool ReadAtOffset(uint8_t* buf, size_t len, off64_t off);
+
+ private:
+  // If has_fd_ is true, fd is valid and we'll read contents of a zip archive
+  // from the file. Otherwise, we're opening the archive from a memory mapped
+  // file. In that case, base_ptr_ points to the start of the memory region and
+  // data_length_ defines the file length.
+  const bool has_fd_;
+
+  const int fd_;
+
+  void* const base_ptr_;
+  const off64_t data_length_;
+  // read_pos_ is the offset to the base_ptr_ where we read data from.
+  size_t read_pos_;
+};
+
+class CentralDirectory {
+ public:
+  CentralDirectory(void) :
+    base_ptr_(nullptr),
+    length_(0) {}
+
+  const uint8_t* GetBasePtr() const {return base_ptr_;}
+
+  size_t GetMapLength() const {return length_;}
+
+  void Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size);
+
+ private:
+  const uint8_t* base_ptr_;
+  size_t length_;
+};
+
 struct ZipArchive {
   // open Zip archive
-  const int fd;
+  mutable MappedZipFile mapped_zip;
   const bool close_file;
 
   // mapped central directory area
   off64_t directory_offset;
-  android::FileMap directory_map;
+  CentralDirectory central_directory;
+  std::unique_ptr<android::FileMap> directory_map;
 
   // number of entries in the Zip archive
   uint16_t num_entries;
@@ -44,20 +110,36 @@
   ZipString* hash_table;
 
   ZipArchive(const int fd, bool assume_ownership) :
-      fd(fd),
-      close_file(assume_ownership),
-      directory_offset(0),
-      num_entries(0),
-      hash_table_size(0),
-      hash_table(NULL) {}
+    mapped_zip(fd),
+    close_file(assume_ownership),
+    directory_offset(0),
+    central_directory(),
+    directory_map(new android::FileMap()),
+    num_entries(0),
+    hash_table_size(0),
+    hash_table(nullptr) {}
+
+  ZipArchive(void* address, size_t length) :
+    mapped_zip(address, length),
+    close_file(false),
+    directory_offset(0),
+    central_directory(),
+    directory_map(new android::FileMap()),
+    num_entries(0),
+    hash_table_size(0),
+    hash_table(nullptr) {}
 
   ~ZipArchive() {
-    if (close_file && fd >= 0) {
-      close(fd);
+    if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
+      close(mapped_zip.GetFileDescriptor());
     }
 
     free(hash_table);
   }
+
+  bool InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
+                                  size_t cd_size);
+
 };
 
 #endif  // LIBZIPARCHIVE_ZIPARCHIVE_PRIVATE_H_
diff --git a/libziparchive/zip_archive_stream_entry.cc b/libziparchive/zip_archive_stream_entry.cc
index f618835..3f336a6 100644
--- a/libziparchive/zip_archive_stream_entry.cc
+++ b/libziparchive/zip_archive_stream_entry.cc
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "ZIPARCHIVE"
+
 // Read-only stream access to Zip Archive entries.
 #include <errno.h>
 #include <inttypes.h>
@@ -24,9 +26,9 @@
 #include <memory>
 #include <vector>
 
-#define LOG_TAG "ZIPARCHIVE"
 #include <android-base/file.h>
 #include <log/log.h>
+
 #include <ziparchive/zip_archive.h>
 #include <ziparchive/zip_archive_stream_entry.h>
 #include <zlib.h>
@@ -38,7 +40,7 @@
 bool ZipArchiveStreamEntry::Init(const ZipEntry& entry) {
   ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle_);
   off64_t data_offset = entry.offset;
-  if (lseek64(archive->fd, data_offset, SEEK_SET) != data_offset) {
+  if (!archive->mapped_zip.SeekToOffset(data_offset)) {
     ALOGW("lseek to data at %" PRId64 " failed: %s", data_offset, strerror(errno));
     return false;
   }
@@ -48,7 +50,8 @@
 
 class ZipArchiveStreamEntryUncompressed : public ZipArchiveStreamEntry {
  public:
-  ZipArchiveStreamEntryUncompressed(ZipArchiveHandle handle) : ZipArchiveStreamEntry(handle) {}
+  explicit ZipArchiveStreamEntryUncompressed(ZipArchiveHandle handle)
+      : ZipArchiveStreamEntry(handle) {}
   virtual ~ZipArchiveStreamEntryUncompressed() {}
 
   const std::vector<uint8_t>* Read() override;
@@ -86,7 +89,7 @@
   size_t bytes = (length_ > data_.size()) ? data_.size() : length_;
   ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle_);
   errno = 0;
-  if (!android::base::ReadFully(archive->fd, data_.data(), bytes)) {
+  if (!archive->mapped_zip.ReadData(data_.data(), bytes)) {
     if (errno != 0) {
       ALOGE("Error reading from archive fd: %s", strerror(errno));
     } else {
@@ -110,7 +113,8 @@
 
 class ZipArchiveStreamEntryCompressed : public ZipArchiveStreamEntry {
  public:
-  ZipArchiveStreamEntryCompressed(ZipArchiveHandle handle) : ZipArchiveStreamEntry(handle) {}
+  explicit ZipArchiveStreamEntryCompressed(ZipArchiveHandle handle)
+      : ZipArchiveStreamEntry(handle) {}
   virtual ~ZipArchiveStreamEntryCompressed();
 
   const std::vector<uint8_t>* Read() override;
@@ -206,7 +210,7 @@
       size_t bytes = (compressed_length_ > in_.size()) ? in_.size() : compressed_length_;
       ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle_);
       errno = 0;
-      if (!android::base::ReadFully(archive->fd, in_.data(), bytes)) {
+      if (!archive->mapped_zip.ReadData(in_.data(), bytes)) {
         if (errno != 0) {
           ALOGE("Error reading from archive fd: %s", strerror(errno));
         } else {
@@ -249,7 +253,7 @@
 
 class ZipArchiveStreamEntryRawCompressed : public ZipArchiveStreamEntryUncompressed {
  public:
-  ZipArchiveStreamEntryRawCompressed(ZipArchiveHandle handle)
+  explicit ZipArchiveStreamEntryRawCompressed(ZipArchiveHandle handle)
       : ZipArchiveStreamEntryUncompressed(handle) {}
   virtual ~ZipArchiveStreamEntryRawCompressed() {}
 
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index 6aee1bb..493a0ce 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -26,7 +26,9 @@
 
 #include <android-base/file.h>
 #include <android-base/test_utils.h>
+#include <android-base/unique_fd.h>
 #include <gtest/gtest.h>
+#include <utils/FileMap.h>
 #include <ziparchive/zip_archive.h>
 #include <ziparchive/zip_archive_stream_entry.h>
 
@@ -36,6 +38,9 @@
 static const std::string kValidZip = "valid.zip";
 static const std::string kLargeZip = "large.zip";
 static const std::string kBadCrcZip = "bad_crc.zip";
+static const std::string kCrashApk = "crash.apk";
+static const std::string kBadFilenameZip = "bad_filename.zip";
+static const std::string kUpdateZip = "dummy-update.zip";
 
 static const std::vector<uint8_t> kATxtContents {
   'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
@@ -80,7 +85,15 @@
 TEST(ziparchive, Open) {
   ZipArchiveHandle handle;
   ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
+  CloseArchive(handle);
 
+  ASSERT_EQ(-1, OpenArchiveWrapper(kBadFilenameZip, &handle));
+  CloseArchive(handle);
+}
+
+TEST(ziparchive, OutOfBound) {
+  ZipArchiveHandle handle;
+  ASSERT_EQ(-8, OpenArchiveWrapper(kCrashApk, &handle));
   CloseArchive(handle);
 }
 
@@ -494,6 +507,32 @@
             lseek64(tmp_file.fd, 0, SEEK_END));
 }
 
+#if !defined(_WIN32)
+TEST(ziparchive, OpenFromMemory) {
+  const std::string zip_path = test_data_dir + "/" + kUpdateZip;
+  android::base::unique_fd fd(open(zip_path.c_str(), O_RDONLY | O_BINARY));
+  ASSERT_NE(-1, fd);
+  struct stat sb;
+  ASSERT_EQ(0, fstat(fd, &sb));
+
+  // Memory map the file first and open the archive from the memory region.
+  android::FileMap file_map;
+  file_map.create(zip_path.c_str(), fd, 0/*offset*/, sb.st_size, true);
+  ZipArchiveHandle handle;
+  ASSERT_EQ(0, OpenArchiveFromMemory(file_map.getDataPtr(), file_map.getDataLength(),
+                                     zip_path.c_str(), &handle));
+
+  // Assert one entry can be found and extracted correctly.
+  std::string BINARY_PATH("META-INF/com/google/android/update-binary");
+  ZipString binary_path(BINARY_PATH.c_str());
+  ZipEntry binary_entry;
+  ASSERT_EQ(0, FindEntry(handle, binary_path, &binary_entry));
+  TemporaryFile tmp_binary;
+  ASSERT_NE(-1, tmp_binary.fd);
+  ASSERT_EQ(0, ExtractEntryToFile(handle, &binary_entry, tmp_binary.fd));
+}
+#endif
+
 static void ZipArchiveStreamTest(
     ZipArchiveHandle& handle, const std::string& entry_name, bool raw,
     bool verified, ZipEntry* entry, std::vector<uint8_t>* read_data) {
diff --git a/libziparchive/zip_writer.cc b/libziparchive/zip_writer.cc
index 1ebed30..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,80 +207,99 @@
     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);
 
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
   int zerr = deflateInit2(z_stream_.get(), Z_BEST_COMPRESSION, Z_DEFLATED, -MAX_WBITS,
                           DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
+#pragma GCC diagnostic pop
+
   if (zerr != Z_OK) {
     if (zerr == Z_VERSION_ERROR) {
       ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
@@ -265,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);
@@ -293,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);
@@ -327,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);
@@ -369,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;
 }
@@ -401,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;
@@ -413,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);
     }
@@ -438,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.mk b/lmkd/Android.mk
index 8c88661..8980d1c 100644
--- a/lmkd/Android.mk
+++ b/lmkd/Android.mk
@@ -2,7 +2,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := lmkd.c
-LOCAL_SHARED_LIBRARIES := liblog libm libc libprocessgroup
+LOCAL_SHARED_LIBRARIES := liblog libm libc libprocessgroup libcutils
 LOCAL_CFLAGS := -Werror
 
 LOCAL_MODULE := lmkd
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index afc81ed..8a6168c 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -18,6 +18,7 @@
 
 #include <arpa/inet.h>
 #include <errno.h>
+#include <sched.h>
 #include <signal.h>
 #include <stdlib.h>
 #include <string.h>
@@ -109,7 +110,7 @@
 static struct proc *pidhash[PIDHASH_SZ];
 #define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
 
-#define ADJTOSLOT(adj) (adj + -OOM_SCORE_ADJ_MIN)
+#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
 static struct adjslot_list procadjslot_list[ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1];
 
 /*
@@ -397,9 +398,6 @@
 }
 
 static void ctrl_connect_handler(uint32_t events __unused) {
-    struct sockaddr_storage ss;
-    struct sockaddr *addrp = (struct sockaddr *)&ss;
-    socklen_t alen;
     struct epoll_event epev;
 
     if (ctrl_dfd >= 0) {
@@ -407,8 +405,7 @@
         ctrl_dfd_reopened = 1;
     }
 
-    alen = sizeof(ss);
-    ctrl_dfd = accept(ctrl_lfd, addrp, &alen);
+    ctrl_dfd = accept(ctrl_lfd, NULL, NULL);
 
     if (ctrl_dfd < 0) {
         ALOGE("lmkd control socket accept failed; errno=%d", errno);
diff --git a/logcat/.clang-format b/logcat/.clang-format
new file mode 100644
index 0000000..393c309
--- /dev/null
+++ b/logcat/.clang-format
@@ -0,0 +1,11 @@
+BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: false
+
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 4
+PointerAlignment: Left
+TabWidth: 4
+PenaltyExcessCharacter: 32
+
+Cpp11BracedListStyle: false
diff --git a/logcat/Android.mk b/logcat/Android.mk
index 1dacbe1..4e11ca9 100644
--- a/logcat/Android.mk
+++ b/logcat/Android.mk
@@ -1,20 +1,41 @@
 # Copyright 2006-2014 The Android Open Source Project
 
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
+
+logcatLibs := liblog libbase libcutils libpcrecpp
+
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= logcat.cpp event.logtags
-
-LOCAL_SHARED_LIBRARIES := liblog libbase libcutils libpcrecpp
-
 LOCAL_MODULE := logcat
-
+LOCAL_SRC_FILES := logcat_main.cpp event.logtags
+LOCAL_SHARED_LIBRARIES := liblogcat $(logcatLibs)
 LOCAL_CFLAGS := -Werror
 
 include $(BUILD_EXECUTABLE)
 
 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)
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_CFLAGS := -Werror
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+
 LOCAL_MODULE := logpersist.start
 LOCAL_MODULE_TAGS := debug
 LOCAL_MODULE_CLASS := EXECUTABLES
diff --git a/logcat/getopt_long.cpp b/logcat/getopt_long.cpp
new file mode 100644
index 0000000..5f8dd66
--- /dev/null
+++ b/logcat/getopt_long.cpp
@@ -0,0 +1,402 @@
+/* $OpenBSD: getopt_long.c,v 1.26 2013/06/08 22:47:56 millert Exp $ */
+/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $       */
+
+/*
+ * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/cdefs.h>
+
+#include <log/getopt.h>
+
+#define PRINT_ERROR ((context->opterr) && (*options != ':'))
+
+#define FLAG_PERMUTE 0x01  // permute non-options to the end of argv
+#define FLAG_ALLARGS 0x02  // treat non-options as args to option "-1"
+
+// return values
+#define BADCH (int)'?'
+#define BADARG ((*options == ':') ? (int)':' : (int)'?')
+#define INORDER (int)1
+
+#define D_PREFIX 0
+#define DD_PREFIX 1
+#define W_PREFIX 2
+
+// Compute the greatest common divisor of a and b.
+static int gcd(int a, int b) {
+    int c = a % b;
+    while (c) {
+        a = b;
+        b = c;
+        c = a % b;
+    }
+    return b;
+}
+
+// Exchange the block from nonopt_start to nonopt_end with the block from
+// nonopt_end to opt_end (keeping the same order of arguments in each block).
+// Returns optind - (nonopt_end - nonopt_start) for convenience.
+static int permute_args(getopt_context* context, char* const* nargv) {
+    // compute lengths of blocks and number and size of cycles
+    int nnonopts = context->nonopt_end - context->nonopt_start;
+    int nopts = context->optind - context->nonopt_end;
+    int ncycle = gcd(nnonopts, nopts);
+    int cyclelen = (context->optind - context->nonopt_start) / ncycle;
+
+    for (int i = 0; i < ncycle; i++) {
+        int cstart = context->nonopt_end + i;
+        int pos = cstart;
+        for (int j = 0; j < cyclelen; j++) {
+            if (pos >= context->nonopt_end) {
+                pos -= nnonopts;
+            } else {
+                pos += nopts;
+            }
+            char* swap = nargv[pos];
+            const_cast<char**>(nargv)[pos] = nargv[cstart];
+            const_cast<char**>(nargv)[cstart] = swap;
+        }
+    }
+    return context->optind - (context->nonopt_end - context->nonopt_start);
+}
+
+// parse_long_options_r --
+//    Parse long options in argc/argv argument vector.
+// Returns -1 if short_too is set and the option does not match long_options.
+static int parse_long_options_r(char* const* nargv, const char* options,
+                                const struct option* long_options, int* idx,
+                                bool short_too, struct getopt_context* context) {
+    const char* current_argv = context->place;
+    const char* current_dash;
+    switch (context->dash_prefix) {
+        case D_PREFIX:
+            current_dash = "-";
+            break;
+        case DD_PREFIX:
+            current_dash = "--";
+            break;
+        case W_PREFIX:
+            current_dash = "-W ";
+            break;
+        default:
+            current_dash = "";
+            break;
+    }
+    context->optind++;
+
+    const char* has_equal;
+    size_t current_argv_len;
+    if (!!(has_equal = strchr(current_argv, '='))) {
+        // argument found (--option=arg)
+        current_argv_len = has_equal - current_argv;
+        has_equal++;
+    } else {
+        current_argv_len = strlen(current_argv);
+    }
+
+    int match = -1;
+    bool exact_match = false;
+    bool second_partial_match = false;
+    for (int i = 0; long_options[i].name; i++) {
+        // find matching long option
+        if (strncmp(current_argv, long_options[i].name, current_argv_len)) {
+            continue;
+        }
+
+        if (strlen(long_options[i].name) == current_argv_len) {
+            // exact match
+            match = i;
+            exact_match = true;
+            break;
+        }
+        // If this is a known short option, don't allow
+        // a partial match of a single character.
+        if (short_too && current_argv_len == 1) continue;
+
+        if (match == -1) {  // first partial match
+            match = i;
+        } else if (long_options[i].has_arg != long_options[match].has_arg ||
+                   long_options[i].flag != long_options[match].flag ||
+                   long_options[i].val != long_options[match].val) {
+            second_partial_match = true;
+        }
+    }
+    if (!exact_match && second_partial_match) {
+        // ambiguous abbreviation
+        if (PRINT_ERROR) {
+            fprintf(context->optstderr ?: stderr,
+                    "option `%s%.*s' is ambiguous", current_dash,
+                    (int)current_argv_len, current_argv);
+        }
+        context->optopt = 0;
+        return BADCH;
+    }
+    if (match != -1) {  // option found
+        if (long_options[match].has_arg == no_argument && has_equal) {
+            if (PRINT_ERROR) {
+                fprintf(context->optstderr ?: stderr,
+                        "option `%s%.*s' doesn't allow an argument",
+                        current_dash, (int)current_argv_len, current_argv);
+            }
+            // XXX: GNU sets optopt to val regardless of flag
+            context->optopt =
+                long_options[match].flag ? 0 : long_options[match].val;
+            return BADCH;
+        }
+        if (long_options[match].has_arg == required_argument ||
+            long_options[match].has_arg == optional_argument) {
+            if (has_equal) {
+                context->optarg = has_equal;
+            } else if (long_options[match].has_arg == required_argument) {
+                // optional argument doesn't use next nargv
+                context->optarg = nargv[context->optind++];
+            }
+        }
+        if ((long_options[match].has_arg == required_argument) &&
+            !context->optarg) {
+            // Missing argument; leading ':' indicates no error
+            // should be generated.
+            if (PRINT_ERROR) {
+                fprintf(context->optstderr ?: stderr,
+                        "option `%s%s' requires an argument", current_dash,
+                        current_argv);
+            }
+            // XXX: GNU sets optopt to val regardless of flag
+            context->optopt =
+                long_options[match].flag ? 0 : long_options[match].val;
+            context->optind--;
+            return BADARG;
+        }
+    } else {  // unknown option
+        if (short_too) {
+            context->optind--;
+            return -1;
+        }
+        if (PRINT_ERROR) {
+            fprintf(context->optstderr ?: stderr, "unrecognized option `%s%s'",
+                    current_dash, current_argv);
+        }
+        context->optopt = 0;
+        return BADCH;
+    }
+    if (idx) *idx = match;
+    if (long_options[match].flag) {
+        *long_options[match].flag = long_options[match].val;
+        return 0;
+    }
+    return long_options[match].val;
+}
+
+// getopt_long_r --
+//    Parse argc/argv argument vector.
+int getopt_long_r(int nargc, char* const* nargv, const char* options,
+                  const struct option* long_options, int* idx,
+                  struct getopt_context* context) {
+    if (!options) return -1;
+
+    // XXX Some GNU programs (like cvs) set optind to 0 instead of
+    // XXX using optreset.  Work around this braindamage.
+    if (!context->optind) context->optind = context->optreset = 1;
+
+    // Disable GNU extensions if options string begins with a '+'.
+    int flags = FLAG_PERMUTE;
+    if (*options == '-') {
+        flags |= FLAG_ALLARGS;
+    } else if (*options == '+') {
+        flags &= ~FLAG_PERMUTE;
+    }
+    if (*options == '+' || *options == '-') options++;
+
+    context->optarg = nullptr;
+    if (context->optreset) context->nonopt_start = context->nonopt_end = -1;
+start:
+    if (context->optreset || !*context->place) {  // update scanning pointer
+        context->optreset = 0;
+        if (context->optind >= nargc) {  // end of argument vector
+            context->place = EMSG;
+            if (context->nonopt_end != -1) {
+                // do permutation, if we have to
+                context->optind = permute_args(context, nargv);
+            } else if (context->nonopt_start != -1) {
+                // If we skipped non-options, set optind to the first of them.
+                context->optind = context->nonopt_start;
+            }
+            context->nonopt_start = context->nonopt_end = -1;
+            return -1;
+        }
+        if (*(context->place = nargv[context->optind]) != '-' ||
+            context->place[1] == '\0') {
+            context->place = EMSG;  // found non-option
+            if (flags & FLAG_ALLARGS) {
+                // GNU extension: return non-option as argument to option 1
+                context->optarg = nargv[context->optind++];
+                return INORDER;
+            }
+            if (!(flags & FLAG_PERMUTE)) {
+                // If no permutation wanted, stop parsing at first non-option.
+                return -1;
+            }
+            // do permutation
+            if (context->nonopt_start == -1) {
+                context->nonopt_start = context->optind;
+            } else if (context->nonopt_end != -1) {
+                context->nonopt_start = permute_args(context, nargv);
+                context->nonopt_end = -1;
+            }
+            context->optind++;
+            // process next argument
+            goto start;
+        }
+        if (context->nonopt_start != -1 && context->nonopt_end == -1) {
+            context->nonopt_end = context->optind;
+        }
+
+        // If we have "-" do nothing, if "--" we are done.
+        if (context->place[1] != '\0' && *++(context->place) == '-' &&
+            context->place[1] == '\0') {
+            context->optind++;
+            context->place = EMSG;
+            // We found an option (--), so if we skipped
+            // non-options, we have to permute.
+            if (context->nonopt_end != -1) {
+                context->optind = permute_args(context, nargv);
+            }
+            context->nonopt_start = context->nonopt_end = -1;
+            return -1;
+        }
+    }
+
+    int optchar;
+    // Check long options if:
+    //  1) we were passed some
+    //  2) the arg is not just "-"
+    //  3) either the arg starts with -- we are getopt_long_only()
+    if (long_options && context->place != nargv[context->optind] &&
+        (*context->place == '-')) {
+        bool short_too = false;
+        context->dash_prefix = D_PREFIX;
+        if (*context->place == '-') {
+            context->place++;  // --foo long option
+            context->dash_prefix = DD_PREFIX;
+        } else if (*context->place != ':' && strchr(options, *context->place)) {
+            short_too = true;  // could be short option too
+        }
+
+        optchar = parse_long_options_r(nargv, options, long_options, idx,
+                                       short_too, context);
+        if (optchar != -1) {
+            context->place = EMSG;
+            return optchar;
+        }
+    }
+
+    const char* oli;  // option letter list index
+    if ((optchar = (int)*(context->place)++) == (int)':' ||
+        (optchar == (int)'-' && *context->place != '\0') ||
+        !(oli = strchr(options, optchar))) {
+        // If the user specified "-" and  '-' isn't listed in
+        // options, return -1 (non-option) as per POSIX.
+        // Otherwise, it is an unknown option character (or ':').
+        if (optchar == (int)'-' && *context->place == '\0') return -1;
+        if (!*context->place) context->optind++;
+        if (PRINT_ERROR) {
+            fprintf(context->optstderr ?: stderr, "invalid option -- %c",
+                    optchar);
+        }
+        context->optopt = optchar;
+        return BADCH;
+    }
+
+    static const char recargchar[] = "option requires an argument -- %c";
+    if (long_options && optchar == 'W' && oli[1] == ';') {
+        // -W long-option
+        if (*context->place) {                      // no space
+            ;                                       // NOTHING
+        } else if (++(context->optind) >= nargc) {  // no arg
+            context->place = EMSG;
+            if (PRINT_ERROR) {
+                fprintf(context->optstderr ?: stderr, recargchar, optchar);
+            }
+            context->optopt = optchar;
+            return BADARG;
+        } else {  // white space
+            context->place = nargv[context->optind];
+        }
+        context->dash_prefix = W_PREFIX;
+        optchar = parse_long_options_r(nargv, options, long_options, idx, false,
+                                       context);
+        context->place = EMSG;
+        return optchar;
+    }
+    if (*++oli != ':') {  // doesn't take argument
+        if (!*context->place) context->optind++;
+    } else {  // takes (optional) argument
+        context->optarg = nullptr;
+        if (*context->place) {  // no white space
+            context->optarg = context->place;
+        } else if (oli[1] != ':') {              // arg not optional
+            if (++(context->optind) >= nargc) {  // no arg
+                context->place = EMSG;
+                if (PRINT_ERROR) {
+                    fprintf(context->optstderr ?: stderr, recargchar, optchar);
+                }
+                context->optopt = optchar;
+                return BADARG;
+            }
+            context->optarg = nargv[context->optind];
+        }
+        context->place = EMSG;
+        context->optind++;
+    }
+    // dump back option letter
+    return optchar;
+}
diff --git a/logcat/include/log/getopt.h b/logcat/include/log/getopt.h
new file mode 100644
index 0000000..0da2b10
--- /dev/null
+++ b/logcat/include/log/getopt.h
@@ -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.
+ */
+
+#ifndef _LOG_GETOPT_H_
+#define _LOG_GETOPT_H_
+
+#ifndef __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 1
+#elif __ANDROID_API__ > 24 /* > Nougat */
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE
+
+#include <getopt.h>
+#include <sys/cdefs.h>
+
+struct getopt_context {
+    int opterr;
+    int optind;
+    int optopt;
+    int optreset;
+    const char* optarg;
+    FILE* optstderr; /* NULL defaults to stderr */
+    /* private */
+    const char* place;
+    int nonopt_start;
+    int nonopt_end;
+    int dash_prefix;
+    /* expansion space */
+    int __extra__;
+    void* __stuff__;
+};
+
+#define EMSG ""
+#define NO_PREFIX (-1)
+
+#define INIT_GETOPT_CONTEXT(context) \
+    context = { 1, 1, '?', 0, NULL, NULL, EMSG, -1, -1, NO_PREFIX, 0, NULL }
+
+__BEGIN_DECLS
+int getopt_long_r(int nargc, char* const* nargv, const char* options,
+                  const struct option* long_options, int* idx,
+                  struct getopt_context* context);
+
+__END_DECLS
+
+#endif /* __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE */
+
+#endif /* !_LOG_GETOPT_H_ */
diff --git a/logcat/include/log/logcat.h b/logcat/include/log/logcat.h
new file mode 100644
index 0000000..009672c
--- /dev/null
+++ b/logcat/include/log/logcat.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2005-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 _LIBS_LOGCAT_H /* header boilerplate */
+#define _LIBS_LOGCAT_H
+
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 1
+#elif __ANDROID_API__ > 24 /* > Nougat */
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE
+
+/* For managing an in-process logcat function, rather than forking/execing
+ *
+ * It also serves as the basis for the logcat command.
+ *
+ * The following C API allows a logcat instance to be created, run
+ * to completion, and then release all the associated resources.
+ */
+
+/*
+ * The opaque context
+ */
+#ifndef __android_logcat_context_defined /* typedef boilerplate */
+#define __android_logcat_context_defined
+typedef struct android_logcat_context_internal* android_logcat_context;
+#endif
+
+/* Creates a context associated with this logcat instance
+ *
+ * Returns a pointer to the context, or a NULL on error.
+ */
+android_logcat_context create_android_logcat();
+
+/* Collects and outputs the logcat data to output and error file descriptors
+ *
+ * Will block, performed in-thread and in-process
+ *
+ * The output file descriptor variable, if greater than or equal to 0, is
+ * where the output (ie: stdout) will be sent. The file descriptor is closed
+ * on android_logcat_destroy which terminates the instance, or when an -f flag
+ * (output redirect to a file) is present in the command.  The error file
+ * descriptor variable, if greater than or equal to 0, is where the error
+ * stream (ie: stderr) will be sent, also closed on android_logcat_destroy.
+ * The error file descriptor can be set to equal to the output file descriptor,
+ * which will mix output and error stream content, and will defer closure of
+ * the file descriptor on -f flag redirection.  Negative values for the file
+ * descriptors will use stdout and stderr FILE references respectively
+ * internally, and will not close the references as noted above.
+ *
+ * Return value is 0 for success, non-zero for errors.
+ */
+int android_logcat_run_command(android_logcat_context ctx, int output, int error,
+                               int argc, char* const* argv, char* const* envp);
+
+/* Will not block, performed in-process
+ *
+ * Starts a thread, opens a pipe, returns reading end fd, saves off argv.
+ * The command supports 2>&1 (mix content) and 2>/dev/null (drop content) for
+ * scripted error (stderr) redirection.
+ */
+int android_logcat_run_command_thread(android_logcat_context ctx, int argc,
+                                      char* const* argv, char* const* envp);
+int android_logcat_run_command_thread_running(android_logcat_context ctx);
+
+/* Finished with context
+ *
+ * Kill the command thread ASAP (if any), and free up all associated resources.
+ *
+ * Return value is the result of the android_logcat_run_command, or
+ * non-zero for any errors.
+ */
+int android_logcat_destroy(android_logcat_context* ctx);
+
+/* derived helpers */
+
+/*
+ * In-process thread that acts like somewhat like libc-like system and popen
+ * respectively.  Can not handle shell scripting, only pure calls to the
+ * logcat operations. The android_logcat_system is a wrapper for the
+ * create_android_logcat, android_logcat_run_command and android_logcat_destroy
+ * API above.  The android_logcat_popen is a wrapper for the
+ * android_logcat_run_command_thread API above.  The android_logcat_pclose is
+ * a wrapper for a reasonable wait until output has subsided for command
+ * completion, fclose on the FILE pointer and the android_logcat_destroy API.
+ */
+int android_logcat_system(const char* command);
+FILE* android_logcat_popen(android_logcat_context* ctx, const char* command);
+int android_logcat_pclose(android_logcat_context* ctx, FILE* output);
+
+#endif /* __ANDROID_USE_LIBLOG_LOGCAT_INTERFACE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOGCAT_H */
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 33f22dd..64d1d2f 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -1,4 +1,18 @@
-// Copyright 2006-2015 The Android Open Source Project
+/*
+ * Copyright (C) 2006-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 <arpa/inet.h>
 #include <assert.h>
@@ -6,10 +20,9 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <getopt.h>
 #include <math.h>
+#include <pthread.h>
 #include <sched.h>
-#include <signal.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -22,35 +35,33 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <atomic>
 #include <memory>
 #include <string>
+#include <vector>
 
 #include <android-base/file.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <cutils/sched_policy.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
-#include <log/log.h>
-#include <log/log_read.h>
-#include <log/logd.h>
-#include <log/logger.h>
+#include <log/getopt.h>
+#include <log/logcat.h>
 #include <log/logprint.h>
-#include <utils/threads.h>
+#include <private/android_logger.h>
+#include <system/thread_defs.h>
 
 #include <pcrecpp.h>
 
 #define DEFAULT_MAX_ROTATED_LOGS 4
 
-static AndroidLogFormat * g_logformat;
-
-/* logd prefixes records with a length field */
-#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
-
 struct log_device_t {
     const char* device;
     bool binary;
-    struct logger *logger;
-    struct logger_list *logger_list;
+    struct logger* logger;
+    struct logger_list* logger_list;
     bool printed;
 
     log_device_t* next;
@@ -58,236 +69,388 @@
     log_device_t(const char* d, bool b) {
         device = d;
         binary = b;
-        next = NULL;
+        next = nullptr;
         printed = false;
-        logger = NULL;
-        logger_list = NULL;
+        logger = nullptr;
+        logger_list = nullptr;
     }
 };
 
+struct android_logcat_context_internal {
+    // status
+    volatile std::atomic_int retval;  // valid if thread_stopped set
+    // Arguments passed in, or copies and storage thereof if a thread.
+    int argc;
+    char* const* argv;
+    char* const* envp;
+    std::vector<std::string> args;
+    std::vector<const char*> argv_hold;
+    std::vector<std::string> envs;
+    std::vector<const char*> envp_hold;
+    int output_fd;  // duplication of fileno(output) (below)
+    int error_fd;   // duplication of fileno(error) (below)
+
+    // library
+    int fds[2];    // From popen call
+    FILE* output;  // everything writes to fileno(output), buffer unused
+    FILE* error;   // unless error == output.
+    pthread_t thr;
+    volatile std::atomic_bool stop;  // quick exit flag
+    volatile std::atomic_bool thread_stopped;
+    bool stderr_null;    // shell "2>/dev/null"
+    bool stderr_stdout;  // shell "2>&1"
+
+    // global variables
+    AndroidLogFormat* logformat;
+    const char* outputFileName;
+    // 0 means "no log rotation"
+    size_t logRotateSizeKBytes;
+    // 0 means "unbounded"
+    size_t maxRotatedLogs;
+    size_t outByteCount;
+    int printBinary;
+    int devCount;  // >1 means multiple
+    pcrecpp::RE* regex;
+    log_device_t* devices;
+    EventTagMap* eventTagMap;
+    // 0 means "infinite"
+    size_t maxCount;
+    size_t printCount;
+
+    bool printItAnyways;
+    bool debug;
+    bool hasOpenedEventTagMap;
+};
+
+// Creates a context associated with this logcat instance
+android_logcat_context create_android_logcat() {
+    android_logcat_context_internal* context;
+
+    context = (android_logcat_context_internal*)calloc(
+        1, sizeof(android_logcat_context_internal));
+    if (!context) return nullptr;
+
+    context->fds[0] = -1;
+    context->fds[1] = -1;
+    context->output_fd = -1;
+    context->error_fd = -1;
+    context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
+
+    context->argv_hold.clear();
+    context->args.clear();
+    context->envp_hold.clear();
+    context->envs.clear();
+
+    return (android_logcat_context)context;
+}
+
+// logd prefixes records with a length field
+#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
+
 namespace android {
 
-/* Global Variables */
-
-static const char * g_outputFileName;
-// 0 means "no log rotation"
-static size_t g_logRotateSizeKBytes;
-// 0 means "unbounded"
-static size_t g_maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
-static int g_outFD = -1;
-static size_t g_outByteCount;
-static int g_printBinary;
-static int g_devCount;                              // >1 means multiple
-static pcrecpp::RE* g_regex;
-// 0 means "infinite"
-static size_t g_maxCount;
-static size_t g_printCount;
-static bool g_printItAnyways;
+enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
 
 // if showHelp is set, newline required in fmt statement to transition to usage
-__noreturn static void logcat_panic(bool showHelp, const char *fmt, ...) __printflike(2,3);
+static void logcat_panic(android_logcat_context_internal* context,
+                         enum helpType showHelp, const char* fmt, ...)
+    __printflike(3, 4);
 
-static int openLogFile (const char *pathname)
-{
+static int openLogFile(const char* pathname) {
     return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
 }
 
-static void rotateLogs()
-{
+static void close_output(android_logcat_context_internal* context) {
+    // split output_from_error
+    if (context->error == context->output) {
+        context->output = nullptr;
+        context->output_fd = -1;
+    }
+    if (context->error && (context->output_fd == fileno(context->error))) {
+        context->output_fd = -1;
+    }
+    if (context->output_fd == context->error_fd) {
+        context->output_fd = -1;
+    }
+    // close output channel
+    if (context->output) {
+        if (context->output != stdout) {
+            if (context->output_fd == fileno(context->output)) {
+                context->output_fd = -1;
+            }
+            if (context->fds[1] == fileno(context->output)) {
+                context->fds[1] = -1;
+            }
+            fclose(context->output);
+        }
+        context->output = nullptr;
+    }
+    if (context->output_fd >= 0) {
+        if (context->output_fd != fileno(stdout)) {
+            if (context->fds[1] == context->output_fd) {
+                context->fds[1] = -1;
+            }
+            close(context->output_fd);
+        }
+        context->output_fd = -1;
+    }
+}
+
+static void close_error(android_logcat_context_internal* context) {
+    // split error_from_output
+    if (context->output == context->error) {
+        context->error = nullptr;
+        context->error_fd = -1;
+    }
+    if (context->output && (context->error_fd == fileno(context->output))) {
+        context->error_fd = -1;
+    }
+    if (context->error_fd == context->output_fd) {
+        context->error_fd = -1;
+    }
+    // close error channel
+    if (context->error) {
+        if ((context->error != stderr) && (context->error != stdout)) {
+            if (context->error_fd == fileno(context->error)) {
+                context->error_fd = -1;
+            }
+            if (context->fds[1] == fileno(context->error)) {
+                context->fds[1] = -1;
+            }
+            fclose(context->error);
+        }
+        context->error = nullptr;
+    }
+    if (context->error_fd >= 0) {
+        if ((context->error_fd != fileno(stdout)) &&
+            (context->error_fd != fileno(stderr))) {
+            if (context->fds[1] == context->error_fd) context->fds[1] = -1;
+            close(context->error_fd);
+        }
+        context->error_fd = -1;
+    }
+}
+
+static void rotateLogs(android_logcat_context_internal* context) {
     int err;
 
     // Can't rotate logs if we're not outputting to a file
-    if (g_outputFileName == NULL) {
-        return;
-    }
+    if (!context->outputFileName) return;
 
-    close(g_outFD);
+    close_output(context);
 
-    // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
-    // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
+    // Compute the maximum number of digits needed to count up to
+    // maxRotatedLogs in decimal.  eg:
+    // maxRotatedLogs == 30
+    //   -> log10(30) == 1.477
+    //   -> maxRotationCountDigits == 2
     int maxRotationCountDigits =
-            (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+        (context->maxRotatedLogs > 0)
+            ? (int)(floor(log10(context->maxRotatedLogs) + 1))
+            : 0;
 
-    for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
-        char *file0, *file1;
+    for (int i = context->maxRotatedLogs; i > 0; i--) {
+        std::string file1 = android::base::StringPrintf(
+            "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
 
-        asprintf(&file1, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
-
-        if (i - 1 == 0) {
-            asprintf(&file0, "%s", g_outputFileName);
+        std::string file0;
+        if (!(i - 1)) {
+            file0 = android::base::StringPrintf("%s", context->outputFileName);
         } else {
-            asprintf(&file0, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
+            file0 =
+                android::base::StringPrintf("%s.%.*d", context->outputFileName,
+                                            maxRotationCountDigits, i - 1);
         }
 
-        if (!file0 || !file1) {
+        if (!file0.length() || !file1.length()) {
             perror("while rotating log files");
             break;
         }
 
-        err = rename(file0, file1);
+        err = rename(file0.c_str(), file1.c_str());
 
         if (err < 0 && errno != ENOENT) {
             perror("while rotating log files");
         }
-
-        free(file1);
-        free(file0);
     }
 
-    g_outFD = openLogFile(g_outputFileName);
+    context->output_fd = openLogFile(context->outputFileName);
 
-    if (g_outFD < 0) {
-        logcat_panic(false, "couldn't open output file");
+    if (context->output_fd < 0) {
+        logcat_panic(context, HELP_FALSE, "couldn't open output file");
+        return;
+    }
+    context->output = fdopen(context->output_fd, "web");
+    if (!context->output) {
+        logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
+        return;
+    }
+    if (context->stderr_stdout) {
+        close_error(context);
+        context->error = context->output;
+        context->error_fd = context->output_fd;
     }
 
-    g_outByteCount = 0;
-
+    context->outByteCount = 0;
 }
 
-void printBinary(struct log_msg *buf)
-{
+void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
     size_t size = buf->len();
 
-    TEMP_FAILURE_RETRY(write(g_outFD, buf, size));
+    TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
 }
 
-static bool regexOk(const AndroidLogEntry& entry)
-{
-    if (!g_regex) {
-        return true;
-    }
+static bool regexOk(android_logcat_context_internal* context,
+                    const AndroidLogEntry& entry) {
+    if (!context->regex) return true;
 
     std::string messageString(entry.message, entry.messageLen);
 
-    return g_regex->PartialMatch(messageString);
+    return context->regex->PartialMatch(messageString);
 }
 
-static void processBuffer(log_device_t* dev, struct log_msg *buf)
-{
+static void processBuffer(android_logcat_context_internal* context,
+                          log_device_t* dev, struct log_msg* buf) {
     int bytesWritten = 0;
     int err;
     AndroidLogEntry entry;
     char binaryMsgBuf[1024];
 
     if (dev->binary) {
-        static bool hasOpenedEventTagMap = false;
-        static EventTagMap *eventTagMap = NULL;
-
-        if (!eventTagMap && !hasOpenedEventTagMap) {
-            eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
-            hasOpenedEventTagMap = true;
+        if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
+            context->eventTagMap = android_openEventTagMap(nullptr);
+            context->hasOpenedEventTagMap = true;
         }
-        err = android_log_processBinaryLogBuffer(&buf->entry_v1, &entry,
-                                                 eventTagMap,
-                                                 binaryMsgBuf,
-                                                 sizeof(binaryMsgBuf));
-        //printf(">>> pri=%d len=%d msg='%s'\n",
+        err = android_log_processBinaryLogBuffer(
+            &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
+            sizeof(binaryMsgBuf));
+        // printf(">>> pri=%d len=%d msg='%s'\n",
         //    entry.priority, entry.messageLen, entry.message);
     } else {
         err = android_log_processLogBuffer(&buf->entry_v1, &entry);
     }
-    if (err < 0) {
-        goto error;
-    }
+    if ((err < 0) && !context->debug) return;
 
-    if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
-        bool match = regexOk(entry);
+    if (android_log_shouldPrintLine(
+            context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
+            entry.priority)) {
+        bool match = regexOk(context, entry);
 
-        g_printCount += match;
-        if (match || g_printItAnyways) {
-            bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
+        context->printCount += match;
+        if (match || context->printItAnyways) {
+            bytesWritten = android_log_printLogLine(context->logformat,
+                                                    context->output_fd, &entry);
 
             if (bytesWritten < 0) {
-                logcat_panic(false, "output error");
+                logcat_panic(context, HELP_FALSE, "output error");
+                return;
             }
         }
     }
 
-    g_outByteCount += bytesWritten;
+    context->outByteCount += bytesWritten;
 
-    if (g_logRotateSizeKBytes > 0
-        && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
-    ) {
-        rotateLogs();
+    if (context->logRotateSizeKBytes > 0 &&
+        (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
+        rotateLogs(context);
     }
-
-error:
-    //fprintf (stderr, "Error processing record\n");
-    return;
 }
 
-static void maybePrintStart(log_device_t* dev, bool printDividers) {
+static void maybePrintStart(android_logcat_context_internal* context,
+                            log_device_t* dev, bool printDividers) {
     if (!dev->printed || printDividers) {
-        if (g_devCount > 1 && !g_printBinary) {
+        if (context->devCount > 1 && !context->printBinary) {
             char buf[1024];
             snprintf(buf, sizeof(buf), "--------- %s %s\n",
-                     dev->printed ? "switch to" : "beginning of",
-                     dev->device);
-            if (write(g_outFD, buf, strlen(buf)) < 0) {
-                logcat_panic(false, "output error");
+                     dev->printed ? "switch to" : "beginning of", dev->device);
+            if (write(context->output_fd, buf, strlen(buf)) < 0) {
+                logcat_panic(context, HELP_FALSE, "output error");
+                return;
             }
         }
         dev->printed = true;
     }
 }
 
-static void setupOutput()
-{
+static void setupOutputAndSchedulingPolicy(
+    android_logcat_context_internal* context, bool blocking) {
+    if (!context->outputFileName) return;
 
-    if (g_outputFileName == NULL) {
-        g_outFD = STDOUT_FILENO;
-
-    } else {
-        if (set_sched_policy(0, SP_BACKGROUND) < 0) {
-            fprintf(stderr, "failed to set background scheduling policy\n");
+    if (blocking) {
+        // Lower priority and set to batch scheduling if we are saving
+        // the logs into files and taking continuous content.
+        if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
+            fprintf(context->error,
+                    "failed to set background scheduling policy\n");
         }
 
         struct sched_param param;
         memset(&param, 0, sizeof(param));
-        if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
+        if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
             fprintf(stderr, "failed to set to batch scheduler\n");
         }
 
-        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
-            fprintf(stderr, "failed set to priority\n");
+        if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
+            context->error) {
+            fprintf(context->error, "failed set to priority\n");
         }
-
-        g_outFD = openLogFile (g_outputFileName);
-
-        if (g_outFD < 0) {
-            logcat_panic(false, "couldn't open output file");
-        }
-
-        struct stat statbuf;
-        if (fstat(g_outFD, &statbuf) == -1) {
-            close(g_outFD);
-            logcat_panic(false, "couldn't get output file stat\n");
-        }
-
-        if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
-            close(g_outFD);
-            logcat_panic(false, "invalid output file stat\n");
-        }
-
-        g_outByteCount = statbuf.st_size;
     }
+
+    close_output(context);
+
+    context->output_fd = openLogFile(context->outputFileName);
+
+    if (context->output_fd < 0) {
+        logcat_panic(context, HELP_FALSE, "couldn't open output file");
+        return;
+    }
+
+    struct stat statbuf;
+    if (fstat(context->output_fd, &statbuf) == -1) {
+        close_output(context);
+        logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
+        return;
+    }
+
+    if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
+        close_output(context);
+        logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
+        return;
+    }
+
+    context->output = fdopen(context->output_fd, "web");
+
+    context->outByteCount = statbuf.st_size;
 }
 
-static void show_help(const char *cmd)
-{
-    fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
+// clang-format off
+static void show_help(android_logcat_context_internal* context) {
+    if (!context->error) return;
 
-    fprintf(stderr, "options include:\n"
+    const char* cmd = strrchr(context->argv[0], '/');
+    cmd = cmd ? cmd + 1 : context->argv[0];
+
+    fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
+
+    fprintf(context->error, "options include:\n"
                     "  -s              Set default filter to silent. Equivalent to filterspec '*:S'\n"
                     "  -f <file>, --file=<file>               Log to file. Default is stdout\n"
                     "  -r <kbytes>, --rotate-kbytes=<kbytes>\n"
                     "                  Rotate log every kbytes. Requires -f option\n"
                     "  -n <count>, --rotate-count=<count>\n"
                     "                  Sets max number of rotated logs to <count>, default 4\n"
+                    "  --id=<id>       If the signature id for logging to file changes, then clear\n"
+                    "                  the fileset and continue\n"
                     "  -v <format>, --format=<format>\n"
-                    "                  Sets the log print format, where <format> is:\n"
-                    "                    brief color epoch long monotonic printable process raw\n"
-                    "                    tag thread threadtime time uid usec UTC year zone\n"
+                    "                  Sets log print format verb and adverbs, where <format> is:\n"
+                    "                    brief help long process raw tag thread threadtime time\n"
+                    "                  and individually flagged modifying adverbs can be added:\n"
+                    "                    color descriptive epoch monotonic printable uid\n"
+                    "                    usec UTC year zone\n"
+                    "                  Multiple -v parameters or comma separated list of format and\n"
+                    "                  format modifiers are allowed.\n"
+                    // private and undocumented nsec, no signal, too much noise
+                    // useful for -T or -t <timestamp> accurate testing though.
                     "  -D, --dividers  Print dividers between each log buffer\n"
                     "  -c, --clear     Clear (flush) the entire log and exit\n"
                     "                  if Log to File specified, clear fileset instead\n"
@@ -311,7 +474,7 @@
                     "  -g, --buffer-size                      Get the size of the ring buffer.\n"
                     "  -G <size>, --buffer-size=<size>\n"
                     "                  Set size of log ring buffer, may suffix with K or M.\n"
-                    "  -L, -last       Dump logs from prior to last reboot\n"
+                    "  -L, --last      Dump logs from prior to last reboot\n"
                     // Leave security (Device Owner only installations) and
                     // kernel (userdebug and eng) buffers undocumented.
                     "  -b <buffer>, --buffer=<buffer>         Request alternate ring buffer, 'main',\n"
@@ -335,7 +498,7 @@
                     "                  comes first. Improves efficiency of polling by providing\n"
                     "                  an about-to-wrap wakeup.\n");
 
-    fprintf(stderr,"\nfilterspecs are a series of \n"
+    fprintf(context->error, "\nfilterspecs are a series of \n"
                    "  <tag>[:priority]\n\n"
                    "where <tag> is a log component tag (or * for all) and priority is:\n"
                    "  V    Verbose (default for <tag>)\n"
@@ -353,138 +516,154 @@
                    "or defaults to \"threadtime\"\n\n");
 }
 
-static int setLogFormat(const char * formatString)
-{
-    static AndroidLogPrintFormat format;
+static void show_format_help(android_logcat_context_internal* context) {
+    if (!context->error) return;
+    fprintf(context->error,
+        "-v <format>, --format=<format> options:\n"
+        "  Sets log print format verb and adverbs, where <format> is:\n"
+        "    brief long process raw tag thread threadtime time\n"
+        "  and individually flagged modifying adverbs can be added:\n"
+        "    color descriptive epoch monotonic printable uid usec UTC year zone\n"
+        "\nSingle format verbs:\n"
+        "  brief      — Display priority/tag and PID of the process issuing the message.\n"
+        "  long       — Display all metadata fields, separate messages with blank lines.\n"
+        "  process    — Display PID only.\n"
+        "  raw        — Display the raw log message, with no other metadata fields.\n"
+        "  tag        — Display the priority/tag only.\n"
+        "  threadtime — Display the date, invocation time, priority, tag, and the PID\n"
+        "               and TID of the thread issuing the message. (the default format).\n"
+        "  time       — Display the date, invocation time, priority/tag, and PID of the\n"
+        "             process issuing the message.\n"
+        "\nAdverb modifiers can be used in combination:\n"
+        "  color       — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
+        "                \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
+        "  descriptive — events logs only, descriptions from event-log-tags database.\n"
+        "  epoch       — Display time as seconds since Jan 1 1970.\n"
+        "  monotonic   — Display time as cpu seconds since last boot.\n"
+        "  printable   — Ensure that any binary logging content is escaped.\n"
+        "  uid         — If permitted, display the UID or Android ID of logged process.\n"
+        "  usec        — Display time down the microsecond precision.\n"
+        "  UTC         — Display time as UTC.\n"
+        "  year        — Add the year to the displayed time.\n"
+        "  zone        — Add the local timezone to the displayed time.\n"
+        "  \"<zone>\"    — Print using this public named timezone (experimental).\n\n"
+    );
+}
+// clang-format on
+
+static int setLogFormat(android_logcat_context_internal* context,
+                        const char* formatString) {
+    AndroidLogPrintFormat format;
 
     format = android_log_formatFromString(formatString);
 
-    if (format == FORMAT_OFF) {
-        // FORMAT_OFF means invalid string
-        return -1;
-    }
+    // invalid string?
+    if (format == FORMAT_OFF) return -1;
 
-    return android_log_setPrintFormat(g_logformat, format);
+    return android_log_setPrintFormat(context->logformat, format);
 }
 
-static const char multipliers[][2] = {
-    { "" },
-    { "K" },
-    { "M" },
-    { "G" }
-};
+static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
 
-static unsigned long value_of_size(unsigned long value)
-{
+static unsigned long value_of_size(unsigned long value) {
     for (unsigned i = 0;
-            (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
-            value /= 1024, ++i) ;
+         (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
+         value /= 1024, ++i)
+        ;
     return value;
 }
 
-static const char *multiplier_of_size(unsigned long value)
-{
+static const char* multiplier_of_size(unsigned long value) {
     unsigned i;
     for (i = 0;
-            (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
-            value /= 1024, ++i) ;
+         (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
+         value /= 1024, ++i)
+        ;
     return multipliers[i];
 }
 
-/*String to unsigned int, returns -1 if it fails*/
-static bool getSizeTArg(char *ptr, size_t *val, size_t min = 0,
-                        size_t max = SIZE_MAX)
-{
-    if (!ptr) {
-        return false;
-    }
+// String to unsigned int, returns -1 if it fails
+static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
+                        size_t max = SIZE_MAX) {
+    if (!ptr) return false;
 
-    char *endp;
+    char* endp;
     errno = 0;
     size_t ret = (size_t)strtoll(ptr, &endp, 0);
 
-    if (endp[0] || errno) {
-        return false;
-    }
+    if (endp[0] || errno) return false;
 
-    if ((ret > max) || (ret < min)) {
-        return false;
-    }
+    if ((ret > max) || (ret < min)) return false;
 
     *val = ret;
     return true;
 }
 
-static void logcat_panic(bool showHelp, const char *fmt, ...)
-{
-    va_list  args;
+static void logcat_panic(android_logcat_context_internal* context,
+                         enum helpType showHelp, const char* fmt, ...) {
+    context->retval = EXIT_FAILURE;
+    if (!context->error) {
+        context->stop = true;
+        return;
+    }
+
+    va_list args;
     va_start(args, fmt);
-    vfprintf(stderr, fmt,  args);
+    vfprintf(context->error, fmt, args);
     va_end(args);
 
-    if (showHelp) {
-       show_help(getprogname());
+    switch (showHelp) {
+        case HELP_TRUE:
+            show_help(context);
+            break;
+        case HELP_FORMAT:
+            show_format_help(context);
+            break;
+        case HELP_FALSE:
+        default:
+            break;
     }
 
-    exit(EXIT_FAILURE);
+    context->stop = true;
 }
 
-static char *parseTime(log_time &t, const char *cp) {
-
-    char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
-    if (ep) {
-        return ep;
-    }
+static char* parseTime(log_time& t, const char* cp) {
+    char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
+    if (ep) return ep;
     ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
-    if (ep) {
-        return ep;
-    }
+    if (ep) return ep;
     return t.strptime(cp, "%s.%q");
 }
 
-// Find last logged line in gestalt of all matching existing output files
-static log_time lastLogTime(char *outputFileName) {
+// Find last logged line in <outputFileName>, or <outputFileName>.1
+static log_time lastLogTime(const char* outputFileName) {
     log_time retval(log_time::EPOCH);
-    if (!outputFileName) {
-        return retval;
-    }
+    if (!outputFileName) return retval;
 
     std::string directory;
-    char *file = strrchr(outputFileName, '/');
+    const char* file = strrchr(outputFileName, '/');
     if (!file) {
         directory = ".";
         file = outputFileName;
     } else {
-        *file = '\0';
-        directory = outputFileName;
-        *file = '/';
+        directory = std::string(outputFileName, file - outputFileName);
         ++file;
     }
 
-    std::unique_ptr<DIR, int(*)(DIR*)>
-            dir(opendir(directory.c_str()), closedir);
-    if (!dir.get()) {
-        return retval;
-    }
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
+                                            closedir);
+    if (!dir.get()) return retval;
 
-    clockid_t clock_type = android_log_clockid();
-    log_time now(clock_type);
-    bool monotonic = clock_type == CLOCK_MONOTONIC;
+    log_time now(android_log_clockid());
 
     size_t len = strlen(file);
     log_time modulo(0, NS_PER_SEC);
-    struct dirent *dp;
+    struct dirent* dp;
 
-    while ((dp = readdir(dir.get())) != NULL) {
-        if ((dp->d_type != DT_REG)
-                // If we are using realtime, check all files that match the
-                // basename for latest time. If we are using monotonic time
-                // then only check the main file because time cycles on
-                // every reboot.
-                || strncmp(dp->d_name, file, len + monotonic)
-                || (dp->d_name[len]
-                    && ((dp->d_name[len] != '.')
-                        || !isdigit(dp->d_name[len+1])))) {
+    while (!!(dp = readdir(dir.get()))) {
+        if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
+            (dp->d_name[len] && ((dp->d_name[len] != '.') ||
+                                 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
             continue;
         }
 
@@ -492,17 +671,13 @@
         file_name += "/";
         file_name += dp->d_name;
         std::string file;
-        if (!android::base::ReadFileToString(file_name, &file)) {
-            continue;
-        }
+        if (!android::base::ReadFileToString(file_name, &file)) continue;
 
         bool found = false;
         for (const auto& line : android::base::Split(file, "\n")) {
             log_time t(log_time::EPOCH);
-            char *ep = parseTime(t, line.c_str());
-            if (!ep || (*ep != ' ')) {
-                continue;
-            }
+            char* ep = parseTime(t, line.c_str());
+            if (!ep || (*ep != ' ')) continue;
             // determine the time precision of the logs (eg: msec or usec)
             for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
                 if (t.tv_nsec % (mod * 10)) {
@@ -520,119 +695,244 @@
             }
         }
         // We count on the basename file to be the definitive end, so stop here.
-        if (!dp->d_name[len] && found) {
-            break;
-        }
+        if (!dp->d_name[len] && found) break;
     }
-    if (retval == log_time::EPOCH) {
-        return retval;
-    }
+    if (retval == log_time::EPOCH) return retval;
     // tail_time prints matching or higher, round up by the modulo to prevent
     // a replay of the last entry we have just checked.
     retval += modulo;
     return retval;
 }
 
-} /* namespace android */
+const char* getenv(android_logcat_context_internal* context, const char* name) {
+    if (!context->envp || !name || !*name) return nullptr;
 
+    for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
+        if (strncmp(context->envp[i], name, len)) continue;
+        if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
+    }
+    return nullptr;
+}
 
-int main(int argc, char **argv)
-{
+}  // namespace android
+
+void reportErrorName(const char** current, const char* name,
+                     bool blockSecurity) {
+    if (*current) return;
+    if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
+        *current = name;
+    }
+}
+
+static int __logcat(android_logcat_context_internal* context) {
     using namespace android;
     int err;
-    int hasSetLogFormat = 0;
-    int clearLog = 0;
-    int getLogSize = 0;
-    unsigned long setLogSize = 0;
-    int getPruneList = 0;
-    char *setPruneList = NULL;
-    int printStatistics = 0;
-    int mode = ANDROID_LOG_RDONLY;
-    const char *forceFilters = NULL;
-    log_device_t* devices = NULL;
-    log_device_t* dev;
+    bool hasSetLogFormat = false;
+    bool clearLog = false;
+    bool allSelected = false;
+    bool getLogSize = false;
+    bool getPruneList = false;
+    bool printStatistics = false;
     bool printDividers = false;
-    struct logger_list *logger_list;
+    unsigned long setLogSize = 0;
+    const char* setPruneList = nullptr;
+    const char* setId = nullptr;
+    int mode = ANDROID_LOG_RDONLY;
+    std::string forceFilters;
+    log_device_t* dev;
+    struct logger_list* logger_list;
     size_t tail_lines = 0;
     log_time tail_time(log_time::EPOCH);
     size_t pid = 0;
     bool got_t = false;
 
-    signal(SIGPIPE, exit);
+    // object instantiations before goto's can happen
+    log_device_t unexpected("unexpected", false);
+    const char* openDeviceFail = nullptr;
+    const char* clearFail = nullptr;
+    const char* setSizeFail = nullptr;
+    const char* getSizeFail = nullptr;
+    int argc = context->argc;
+    char* const* argv = context->argv;
 
-    g_logformat = android_log_format_new();
+    context->output = stdout;
+    context->error = stderr;
 
-    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
-        show_help(argv[0]);
-        return EXIT_SUCCESS;
+    for (int i = 0; i < argc; ++i) {
+        // Simulate shell stderr redirect parsing
+        if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
+
+        // Append to file not implemented, just open file
+        size_t skip = (argv[i][2] == '>') + 2;
+        if (!strcmp(&argv[i][skip], "/dev/null")) {
+            context->stderr_null = true;
+        } else if (!strcmp(&argv[i][skip], "&1")) {
+            context->stderr_stdout = true;
+        } else {
+            // stderr file redirections are not supported
+            fprintf(context->stderr_stdout ? stdout : stderr,
+                    "stderr redirection to file %s unsupported, skipping\n",
+                    &argv[i][skip]);
+        }
+        // Only the first one
+        break;
     }
 
+    const char* filename = nullptr;
+    for (int i = 0; i < argc; ++i) {
+        // Simulate shell stdout redirect parsing
+        if (argv[i][0] != '>') continue;
+
+        // Append to file not implemented, just open file
+        filename = &argv[i][(argv[i][1] == '>') + 1];
+        // Only the first one
+        break;
+    }
+
+    // Deal with setting up file descriptors and FILE pointers
+    if (context->error_fd >= 0) {  // Is an error file descriptor supplied?
+        if (context->error_fd == context->output_fd) {
+            context->stderr_stdout = true;
+        } else if (context->stderr_null) {  // redirection told us to close it
+            close(context->error_fd);
+            context->error_fd = -1;
+        } else {  // All Ok, convert error to a FILE pointer
+            context->error = fdopen(context->error_fd, "web");
+            if (!context->error) {
+                context->retval = -errno;
+                fprintf(context->stderr_stdout ? stdout : stderr,
+                        "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
+                        strerror(errno));
+                goto exit;
+            }
+        }
+    }
+    if (context->output_fd >= 0) {  // Is an output file descriptor supplied?
+        if (filename) {  // redirect to file, close supplied file descriptor.
+            close(context->output_fd);
+            context->output_fd = -1;
+        } else {  // All Ok, convert output to a FILE pointer
+            context->output = fdopen(context->output_fd, "web");
+            if (!context->output) {
+                context->retval = -errno;
+                fprintf(context->stderr_stdout ? stdout : context->error,
+                        "Failed to fdopen(output_fd=%d) %s\n",
+                        context->output_fd, strerror(errno));
+                goto exit;
+            }
+        }
+    }
+    if (filename) {  // We supplied an output file redirected in command line
+        context->output = fopen(filename, "web");
+    }
+    // Deal with 2>&1
+    if (context->stderr_stdout) context->error = context->output;
+    // Deal with 2>/dev/null
+    if (context->stderr_null) {
+        context->error_fd = -1;
+        context->error = nullptr;
+    }
+    // Only happens if output=stdout or output=filename
+    if ((context->output_fd < 0) && context->output) {
+        context->output_fd = fileno(context->output);
+    }
+    // Only happens if error=stdout || error=stderr
+    if ((context->error_fd < 0) && context->error) {
+        context->error_fd = fileno(context->error);
+    }
+
+    context->logformat = android_log_format_new();
+
+    if (argc == 2 && !strcmp(argv[1], "--help")) {
+        show_help(context);
+        context->retval = EXIT_SUCCESS;
+        goto exit;
+    }
+
+    // meant to catch comma-delimited values, but cast a wider
+    // net for stability dealing with possible mistaken inputs.
+    static const char delimiters[] = ",:; \t\n\r\f";
+
+    struct getopt_context optctx;
+    INIT_GETOPT_CONTEXT(optctx);
+    optctx.opterr = !!context->error;
+    optctx.optstderr = context->error;
+
     for (;;) {
         int ret;
 
         int option_index = 0;
         // list of long-argument only strings for later comparison
         static const char pid_str[] = "pid";
+        static const char debug_str[] = "debug";
+        static const char id_str[] = "id";
         static const char wrap_str[] = "wrap";
         static const char print_str[] = "print";
+        // clang-format off
         static const struct option long_options[] = {
-          { "binary",        no_argument,       NULL,   'B' },
-          { "buffer",        required_argument, NULL,   'b' },
-          { "buffer-size",   optional_argument, NULL,   'g' },
-          { "clear",         no_argument,       NULL,   'c' },
-          { "dividers",      no_argument,       NULL,   'D' },
-          { "file",          required_argument, NULL,   'f' },
-          { "format",        required_argument, NULL,   'v' },
+          { "binary",        no_argument,       nullptr, 'B' },
+          { "buffer",        required_argument, nullptr, 'b' },
+          { "buffer-size",   optional_argument, nullptr, 'g' },
+          { "clear",         no_argument,       nullptr, 'c' },
+          { debug_str,       no_argument,       nullptr, 0 },
+          { "dividers",      no_argument,       nullptr, 'D' },
+          { "file",          required_argument, nullptr, 'f' },
+          { "format",        required_argument, nullptr, 'v' },
           // hidden and undocumented reserved alias for --regex
-          { "grep",          required_argument, NULL,   'e' },
+          { "grep",          required_argument, nullptr, 'e' },
           // hidden and undocumented reserved alias for --max-count
-          { "head",          required_argument, NULL,   'm' },
-          { "last",          no_argument,       NULL,   'L' },
-          { "max-count",     required_argument, NULL,   'm' },
-          { pid_str,         required_argument, NULL,   0 },
-          { print_str,       no_argument,       NULL,   0 },
-          { "prune",         optional_argument, NULL,   'p' },
-          { "regex",         required_argument, NULL,   'e' },
-          { "rotate-count",  required_argument, NULL,   'n' },
-          { "rotate-kbytes", required_argument, NULL,   'r' },
-          { "statistics",    no_argument,       NULL,   'S' },
+          { "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' },
+          { pid_str,         required_argument, nullptr, 0 },
+          { print_str,       no_argument,       nullptr, 0 },
+          { "prune",         optional_argument, nullptr, 'p' },
+          { "regex",         required_argument, nullptr, 'e' },
+          { "rotate-count",  required_argument, nullptr, 'n' },
+          { "rotate-kbytes", required_argument, nullptr, 'r' },
+          { "statistics",    no_argument,       nullptr, 'S' },
           // hidden and undocumented reserved alias for -t
-          { "tail",          required_argument, NULL,   't' },
+          { "tail",          required_argument, nullptr, 't' },
           // support, but ignore and do not document, the optional argument
-          { wrap_str,        optional_argument, NULL,   0 },
-          { NULL,            0,                 NULL,   0 }
+          { wrap_str,        optional_argument, nullptr, 0 },
+          { nullptr,         0,                 nullptr, 0 }
         };
+        // clang-format on
 
-        ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
-                          long_options, &option_index);
-
-        if (ret < 0) {
-            break;
-        }
+        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) {
             case 0:
-                // One of the long options
+                // only long options
                 if (long_options[option_index].name == pid_str) {
                     // ToDo: determine runtime PID_MAX?
-                    if (!getSizeTArg(optarg, &pid, 1)) {
-                        logcat_panic(true, "%s %s out of range\n",
-                                     long_options[option_index].name, optarg);
+                    if (!getSizeTArg(optctx.optarg, &pid, 1)) {
+                        logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
+                                     long_options[option_index].name,
+                                     optctx.optarg);
+                        goto exit;
                     }
                     break;
                 }
                 if (long_options[option_index].name == wrap_str) {
-                    mode |= ANDROID_LOG_WRAP |
-                            ANDROID_LOG_RDONLY |
+                    mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
                             ANDROID_LOG_NONBLOCK;
                     // ToDo: implement API that supports setting a wrap timeout
                     size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
-                    if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
-                        logcat_panic(true, "%s %s out of range\n",
-                                     long_options[option_index].name, optarg);
+                    if (optctx.optarg &&
+                        !getSizeTArg(optctx.optarg, &dummy, 1)) {
+                        logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
+                                     long_options[option_index].name,
+                                     optctx.optarg);
+                        goto exit;
                     }
-                    if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
-                        fprintf(stderr,
+                    if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
+                        context->error) {
+                        fprintf(context->error,
                                 "WARNING: %s %u seconds, ignoring %zu\n",
                                 long_options[option_index].name,
                                 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
@@ -640,387 +940,503 @@
                     break;
                 }
                 if (long_options[option_index].name == print_str) {
-                    g_printItAnyways = true;
+                    context->printItAnyways = true;
                     break;
                 }
-            break;
+                if (long_options[option_index].name == debug_str) {
+                    context->debug = true;
+                    break;
+                }
+                if (long_options[option_index].name == id_str) {
+                    setId = (optctx.optarg && optctx.optarg[0]) ? optctx.optarg
+                                                                : nullptr;
+                }
+                break;
 
             case 's':
                 // default to all silent
-                android_log_addFilterRule(g_logformat, "*:s");
-            break;
+                android_log_addFilterRule(context->logformat, "*:s");
+                break;
 
             case 'c':
-                clearLog = 1;
+                clearLog = true;
                 mode |= ANDROID_LOG_WRONLY;
-            break;
+                break;
 
             case 'L':
-                mode |= ANDROID_LOG_PSTORE;
-            break;
+                mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
+                        ANDROID_LOG_NONBLOCK;
+                break;
 
             case 'd':
                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
-            break;
+                break;
 
             case 't':
                 got_t = true;
                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
-                /* FALLTHRU */
+            // FALLTHRU
             case 'T':
-                if (strspn(optarg, "0123456789") != strlen(optarg)) {
-                    char *cp = parseTime(tail_time, optarg);
+                if (strspn(optctx.optarg, "0123456789") !=
+                    strlen(optctx.optarg)) {
+                    char* cp = parseTime(tail_time, optctx.optarg);
                     if (!cp) {
-                        logcat_panic(false, "-%c \"%s\" not in time format\n",
-                                     ret, optarg);
+                        logcat_panic(context, HELP_FALSE,
+                                     "-%c \"%s\" not in time format\n", ret,
+                                     optctx.optarg);
+                        goto exit;
                     }
                     if (*cp) {
                         char c = *cp;
                         *cp = '\0';
-                        fprintf(stderr,
+                        if (context->error) {
+                            fprintf(
+                                context->error,
                                 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
-                                ret, optarg, c, cp + 1);
+                                ret, optctx.optarg, c, cp + 1);
+                        }
                         *cp = c;
                     }
                 } else {
-                    if (!getSizeTArg(optarg, &tail_lines, 1)) {
-                        fprintf(stderr,
-                                "WARNING: -%c %s invalid, setting to 1\n",
-                                ret, optarg);
+                    if (!getSizeTArg(optctx.optarg, &tail_lines, 1)) {
+                        if (context->error) {
+                            fprintf(context->error,
+                                    "WARNING: -%c %s invalid, setting to 1\n",
+                                    ret, optctx.optarg);
+                        }
                         tail_lines = 1;
                     }
                 }
-            break;
+                break;
 
             case 'D':
                 printDividers = true;
-            break;
+                break;
 
             case 'e':
-                g_regex = new pcrecpp::RE(optarg);
-            break;
+                context->regex = new pcrecpp::RE(optctx.optarg);
+                break;
 
             case 'm': {
-                char *end = NULL;
-                if (!getSizeTArg(optarg, &g_maxCount)) {
-                    logcat_panic(false, "-%c \"%s\" isn't an "
-                                 "integer greater than zero\n", ret, optarg);
+                char* end = nullptr;
+                if (!getSizeTArg(optctx.optarg, &context->maxCount)) {
+                    logcat_panic(context, HELP_FALSE,
+                                 "-%c \"%s\" isn't an "
+                                 "integer greater than zero\n",
+                                 ret, optctx.optarg);
+                    goto exit;
                 }
-            }
-            break;
+            } break;
 
             case 'g':
-                if (!optarg) {
-                    getLogSize = 1;
+                if (!optctx.optarg) {
+                    getLogSize = true;
                     break;
                 }
-                // FALLTHRU
+            // FALLTHRU
 
             case 'G': {
-                char *cp;
-                if (strtoll(optarg, &cp, 0) > 0) {
-                    setLogSize = strtoll(optarg, &cp, 0);
+                char* cp;
+                if (strtoll(optctx.optarg, &cp, 0) > 0) {
+                    setLogSize = strtoll(optctx.optarg, &cp, 0);
                 } else {
                     setLogSize = 0;
                 }
 
-                switch(*cp) {
-                case 'g':
-                case 'G':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case 'm':
-                case 'M':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case 'k':
-                case 'K':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case '\0':
-                break;
+                switch (*cp) {
+                    case 'g':
+                    case 'G':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case 'm':
+                    case 'M':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case 'k':
+                    case 'K':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case '\0':
+                        break;
 
-                default:
-                    setLogSize = 0;
+                    default:
+                        setLogSize = 0;
                 }
 
                 if (!setLogSize) {
-                    fprintf(stderr, "ERROR: -G <num><multiplier>\n");
-                    return EXIT_FAILURE;
+                    logcat_panic(context, HELP_FALSE,
+                                 "ERROR: -G <num><multiplier>\n");
+                    goto exit;
                 }
-            }
-            break;
+            } break;
 
             case 'p':
-                if (!optarg) {
-                    getPruneList = 1;
+                if (!optctx.optarg) {
+                    getPruneList = true;
                     break;
                 }
-                // FALLTHRU
+            // FALLTHRU
 
             case 'P':
-                setPruneList = optarg;
-            break;
+                setPruneList = optctx.optarg;
+                break;
 
             case 'b': {
+                std::unique_ptr<char, void (*)(void*)> buffers(
+                    strdup(optctx.optarg), free);
+                char* arg = buffers.get();
                 unsigned idMask = 0;
-                while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
-                    if (strcmp(optarg, "default") == 0) {
-                        idMask |= (1 << LOG_ID_MAIN) |
-                                  (1 << LOG_ID_SYSTEM) |
+                char* sv = nullptr;  // protect against -ENOMEM above
+                while (!!(arg = strtok_r(arg, delimiters, &sv))) {
+                    if (!strcmp(arg, "default")) {
+                        idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
                                   (1 << LOG_ID_CRASH);
-                    } else if (strcmp(optarg, "all") == 0) {
+                    } else if (!strcmp(arg, "all")) {
+                        allSelected = true;
                         idMask = (unsigned)-1;
                     } else {
-                        log_id_t log_id = android_name_to_log_id(optarg);
-                        const char *name = android_log_id_to_name(log_id);
+                        log_id_t log_id = android_name_to_log_id(arg);
+                        const char* name = android_log_id_to_name(log_id);
 
-                        if (strcmp(name, optarg) != 0) {
-                            logcat_panic(true, "unknown buffer %s\n", optarg);
+                        if (!!strcmp(name, arg)) {
+                            logcat_panic(context, HELP_TRUE,
+                                         "unknown buffer %s\n", arg);
+                            goto exit;
                         }
+                        if (log_id == LOG_ID_SECURITY) allSelected = false;
                         idMask |= (1 << log_id);
                     }
-                    optarg = NULL;
+                    arg = nullptr;
                 }
 
                 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
-                    const char *name = android_log_id_to_name((log_id_t)i);
+                    const char* name = android_log_id_to_name((log_id_t)i);
                     log_id_t log_id = android_name_to_log_id(name);
 
-                    if (log_id != (log_id_t)i) {
-                        continue;
-                    }
-                    if ((idMask & (1 << i)) == 0) {
-                        continue;
-                    }
+                    if (log_id != (log_id_t)i) continue;
+                    if (!(idMask & (1 << i))) continue;
 
                     bool found = false;
-                    for (dev = devices; dev; dev = dev->next) {
+                    for (dev = context->devices; dev; dev = dev->next) {
                         if (!strcmp(name, dev->device)) {
                             found = true;
                             break;
                         }
-                        if (!dev->next) {
-                            break;
-                        }
+                        if (!dev->next) break;
                     }
-                    if (found) {
-                        continue;
-                    }
+                    if (found) continue;
 
-                    bool binary = !strcmp(name, "events") ||
-                                  !strcmp(name, "security");
+                    bool binary =
+                        !strcmp(name, "events") || !strcmp(name, "security");
                     log_device_t* d = new log_device_t(name, binary);
 
                     if (dev) {
                         dev->next = d;
                         dev = d;
                     } else {
-                        devices = dev = d;
+                        context->devices = dev = d;
                     }
-                    g_devCount++;
+                    context->devCount++;
                 }
-            }
-            break;
+            } break;
 
             case 'B':
-                g_printBinary = 1;
-            break;
+                context->printBinary = 1;
+                break;
 
             case 'f':
-                if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
-                    tail_time = lastLogTime(optarg);
+                if ((tail_time == log_time::EPOCH) && !tail_lines) {
+                    tail_time = lastLogTime(optctx.optarg);
                 }
                 // redirect output to a file
-                g_outputFileName = optarg;
-            break;
+                context->outputFileName = optctx.optarg;
+                break;
 
             case 'r':
-                if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
-                    logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
+                if (!getSizeTArg(optctx.optarg, &context->logRotateSizeKBytes,
+                                 1)) {
+                    logcat_panic(context, HELP_TRUE,
+                                 "Invalid parameter \"%s\" to -r\n",
+                                 optctx.optarg);
+                    goto exit;
                 }
-            break;
+                break;
 
             case 'n':
-                if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
-                    logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
+                if (!getSizeTArg(optctx.optarg, &context->maxRotatedLogs, 1)) {
+                    logcat_panic(context, HELP_TRUE,
+                                 "Invalid parameter \"%s\" to -n\n",
+                                 optctx.optarg);
+                    goto exit;
                 }
-            break;
+                break;
 
-            case 'v':
-                err = setLogFormat (optarg);
-                if (err < 0) {
-                    logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
+            case 'v': {
+                if (!strcmp(optctx.optarg, "help") ||
+                    !strcmp(optctx.optarg, "--help")) {
+                    show_format_help(context);
+                    context->retval = EXIT_SUCCESS;
+                    goto exit;
                 }
-                hasSetLogFormat |= err;
-            break;
+                std::unique_ptr<char, void (*)(void*)> formats(
+                    strdup(optctx.optarg), free);
+                char* arg = formats.get();
+                unsigned idMask = 0;
+                char* sv = nullptr;  // protect against -ENOMEM above
+                while (!!(arg = strtok_r(arg, delimiters, &sv))) {
+                    err = setLogFormat(context, arg);
+                    if (err < 0) {
+                        logcat_panic(context, HELP_FORMAT,
+                                     "Invalid parameter \"%s\" to -v\n", arg);
+                        goto exit;
+                    }
+                    arg = nullptr;
+                    if (err) hasSetLogFormat = true;
+                }
+            } break;
 
             case 'Q':
-                /* this is a *hidden* option used to start a version of logcat                 */
-                /* in an emulated device only. it basically looks for androidboot.logcat=      */
-                /* on the kernel command line. If something is found, it extracts a log filter */
-                /* and uses it to run the program. If nothing is found, the program should     */
-                /* quit immediately                                                            */
-#define  KERNEL_OPTION  "androidboot.logcat="
-#define  CONSOLE_OPTION "androidboot.console="
+#define LOGCAT_FILTER "androidboot.logcat="
+#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
+#define CONSOLE_OPTION "androidboot.console="
+#define QEMU_PROPERTY "ro.kernel.qemu"
+#define QEMU_CMDLINE "qemu.cmdline"
+                // This is a *hidden* option used to start a version of logcat
+                // in an emulated device only.  It basically looks for
+                // androidboot.logcat= on the kernel command line.  If
+                // something is found, it extracts a log filter and uses it to
+                // run the program. The logcat output will go to consolepipe if
+                // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
+                // it goes to androidboot.console (e.g. tty)
                 {
-                    int          fd;
-                    char*        logcat;
-                    char*        console;
-                    int          force_exit = 1;
-                    static char  cmdline[1024];
+                    // if not in emulator, exit quietly
+                    if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
+                        context->retval = EXIT_SUCCESS;
+                        goto exit;
+                    }
 
-                    fd = open("/proc/cmdline", O_RDONLY);
-                    if (fd >= 0) {
-                        int  n = read(fd, cmdline, sizeof(cmdline)-1 );
-                        if (n < 0) n = 0;
-                        cmdline[n] = 0;
-                        close(fd);
+                    std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
+                    if (cmdline.empty()) {
+                        android::base::ReadFileToString("/proc/cmdline", &cmdline);
+                    }
+
+                    const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
+                    // if nothing found or invalid filters, exit quietly
+                    if (!logcatFilter) {
+                        context->retval = EXIT_SUCCESS;
+                        goto exit;
+                    }
+
+                    const char* p = logcatFilter + strlen(LOGCAT_FILTER);
+                    const char* q = strpbrk(p, " \t\n\r");
+                    if (!q) q = p + strlen(p);
+                    forceFilters = std::string(p, q);
+
+                    // redirect our output to the emulator console pipe or console
+                    const char* consolePipe =
+                        strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
+                    const char* console =
+                        strstr(cmdline.c_str(), CONSOLE_OPTION);
+
+                    if (consolePipe) {
+                        p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
+                    } else if (console) {
+                        p = console + strlen(CONSOLE_OPTION);
                     } else {
-                        cmdline[0] = 0;
+                        context->retval = EXIT_FAILURE;
+                        goto exit;
                     }
 
-                    logcat  = strstr( cmdline, KERNEL_OPTION );
-                    console = strstr( cmdline, CONSOLE_OPTION );
-                    if (logcat != NULL) {
-                        char*  p = logcat + sizeof(KERNEL_OPTION)-1;;
-                        char*  q = strpbrk( p, " \t\n\r" );;
-
-                        if (q != NULL)
-                            *q = 0;
-
-                        forceFilters = p;
-                        force_exit   = 0;
-                    }
-                    /* if nothing found or invalid filters, exit quietly */
-                    if (force_exit) {
-                        return EXIT_SUCCESS;
-                    }
-
-                    /* redirect our output to the emulator console */
-                    if (console) {
-                        char*  p = console + sizeof(CONSOLE_OPTION)-1;
-                        char*  q = strpbrk( p, " \t\n\r" );
-                        char   devname[64];
-                        int    len;
-
-                        if (q != NULL) {
-                            len = q - p;
-                        } else
-                            len = strlen(p);
-
-                        len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
-                        fprintf(stderr, "logcat using %s (%d)\n", devname, len);
-                        if (len < (int)sizeof(devname)) {
-                            fd = open( devname, O_WRONLY );
-                            if (fd >= 0) {
-                                dup2(fd, 1);
-                                dup2(fd, 2);
-                                close(fd);
-                            }
+                    q = strpbrk(p, " \t\n\r");
+                    int len = q ? q - p : strlen(p);
+                    std::string devname = "/dev/" + std::string(p, len);
+                    std::string pipePurpose("pipe:logcat");
+                    if (consolePipe) {
+                        // example: "qemu_pipe,pipe:logcat"
+                        // upon opening of /dev/qemu_pipe, the "pipe:logcat"
+                        // string with trailing '\0' should be written to the fd
+                        size_t pos = devname.find(",");
+                        if (pos != std::string::npos) {
+                            pipePurpose = devname.substr(pos + 1);
+                            devname = devname.substr(0, pos);
                         }
                     }
+                    cmdline.erase();
+
+                    if (context->error) {
+                        fprintf(context->error, "logcat using %s\n",
+                                devname.c_str());
+                    }
+
+                    FILE* fp = fopen(devname.c_str(), "web");
+                    devname.erase();
+                    if (!fp) break;
+
+                    if (consolePipe) {
+                        // need the trailing '\0'
+                        if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
+                                    pipePurpose.size() + 1)) {
+                            fclose(fp);
+                            context->retval = EXIT_FAILURE;
+                            goto exit;
+                        }
+                    }
+
+                    // close output and error channels, replace with console
+                    android::close_output(context);
+                    android::close_error(context);
+                    context->stderr_stdout = true;
+                    context->output = fp;
+                    context->output_fd = fileno(fp);
+                    if (context->stderr_null) break;
+                    context->stderr_stdout = true;
+                    context->error = fp;
+                    context->error_fd = fileno(fp);
                 }
                 break;
 
             case 'S':
-                printStatistics = 1;
+                printStatistics = true;
                 break;
 
             case ':':
-                logcat_panic(true, "Option -%c needs an argument\n", optopt);
-                break;
+                logcat_panic(context, HELP_TRUE,
+                             "Option -%c needs an argument\n", optctx.optopt);
+                goto exit;
+
+            case 'h':
+                show_help(context);
+                show_format_help(context);
+                goto exit;
 
             default:
-                logcat_panic(true, "Unrecognized Option %c\n", optopt);
-                break;
+                logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
+                             optctx.optopt);
+                goto exit;
         }
     }
 
-    if (g_maxCount && got_t) {
-        logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
+    if (context->maxCount && got_t) {
+        logcat_panic(context, HELP_TRUE,
+                     "Cannot use -m (--max-count) and -t together\n");
+        goto exit;
     }
-    if (g_printItAnyways && (!g_regex || !g_maxCount)) {
+    if (context->printItAnyways && (!context->regex || !context->maxCount)) {
         // One day it would be nice if --print -v color and --regex <expr>
         // could play with each other and show regex highlighted content.
-        fprintf(stderr, "WARNING: "
+        // clang-format off
+        if (context->error) {
+            fprintf(context->error, "WARNING: "
                             "--print ignored, to be used in combination with\n"
-                        "         "
+                                "         "
                             "--regex <expr> and --max-count <N>\n");
-        g_printItAnyways = false;
+        }
+        context->printItAnyways = false;
     }
 
-    if (!devices) {
-        dev = devices = new log_device_t("main", false);
-        g_devCount = 1;
+    if (!context->devices) {
+        dev = context->devices = new log_device_t("main", false);
+        context->devCount = 1;
         if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
             dev = dev->next = new log_device_t("system", false);
-            g_devCount++;
+            context->devCount++;
         }
         if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
             dev = dev->next = new log_device_t("crash", false);
-            g_devCount++;
+            context->devCount++;
         }
     }
 
-    if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
-        logcat_panic(true, "-r requires -f as well\n");
+    if (!!context->logRotateSizeKBytes && !context->outputFileName) {
+        logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
+        goto exit;
     }
 
-    setupOutput();
+    if (!!setId) {
+        if (!context->outputFileName) {
+            logcat_panic(context, HELP_TRUE,
+                         "--id='%s' requires -f as well\n", setId);
+            goto exit;
+        }
 
-    if (hasSetLogFormat == 0) {
-        const char* logFormat = getenv("ANDROID_PRINTF_LOG");
+        std::string file_name = android::base::StringPrintf(
+                                        "%s.id", context->outputFileName);
+        std::string file;
+        bool file_ok = android::base::ReadFileToString(file_name, &file);
+        android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
+                                         getuid(), getgid());
+        if (!file_ok || !file.compare(setId)) setId = nullptr;
+    }
 
-        if (logFormat != NULL) {
-            err = setLogFormat(logFormat);
-            if (err < 0) {
-                fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
-                                    logFormat);
+    if (!hasSetLogFormat) {
+        const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
+
+        if (!!logFormat) {
+            std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
+                                                           free);
+            char* sv = nullptr;  // protect against -ENOMEM above
+            char* arg = formats.get();
+            while (!!(arg = strtok_r(arg, delimiters, &sv))) {
+                err = setLogFormat(context, arg);
+                // environment should not cause crash of logcat
+                if ((err < 0) && context->error) {
+                    fprintf(context->error,
+                            "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
+                }
+                arg = nullptr;
+                if (err > 0) hasSetLogFormat = true;
             }
-        } else {
-            setLogFormat("threadtime");
+        }
+        if (!hasSetLogFormat) {
+            setLogFormat(context, "threadtime");
         }
     }
 
-    if (forceFilters) {
-        err = android_log_addFilterString(g_logformat, forceFilters);
+    if (forceFilters.size()) {
+        err = android_log_addFilterString(context->logformat,
+                                          forceFilters.c_str());
         if (err < 0) {
-            logcat_panic(false, "Invalid filter expression in logcat args\n");
+            logcat_panic(context, HELP_FALSE,
+                         "Invalid filter expression in logcat args\n");
+            goto exit;
         }
-    } else if (argc == optind) {
+    } else if (argc == optctx.optind) {
         // Add from environment variable
-        char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
+        const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
 
-        if (env_tags_orig != NULL) {
-            err = android_log_addFilterString(g_logformat, env_tags_orig);
+        if (!!env_tags_orig) {
+            err = android_log_addFilterString(context->logformat,
+                                              env_tags_orig);
 
             if (err < 0) {
-                logcat_panic(true,
+                logcat_panic(context, HELP_TRUE,
                             "Invalid filter expression in ANDROID_LOG_TAGS\n");
+                goto exit;
             }
         }
     } else {
         // Add from commandline
-        for (int i = optind ; i < argc ; i++) {
-            err = android_log_addFilterString(g_logformat, argv[i]);
+        for (int i = optctx.optind ; i < argc ; i++) {
+            // skip stderr redirections of _all_ kinds
+            if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
+            // skip stdout redirections of _all_ kinds
+            if (argv[i][0] == '>') continue;
 
+            err = android_log_addFilterString(context->logformat, argv[i]);
             if (err < 0) {
-                logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
+                logcat_panic(context, HELP_TRUE,
+                             "Invalid filter expression '%s'\n", argv[i]);
+                goto exit;
             }
         }
     }
 
-    dev = devices;
+    dev = context->devices;
     if (tail_time != log_time::EPOCH) {
         logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
     } else {
         logger_list = android_logger_list_alloc(mode, tail_lines, pid);
     }
-    const char *openDeviceFail = NULL;
-    const char *clearFail = NULL;
-    const char *setSizeFail = NULL;
-    const char *getSizeFail = NULL;
     // We have three orthogonal actions below to clear, set log size and
     // get log size. All sharing the same iteration loop.
     while (dev) {
@@ -1028,48 +1444,50 @@
         dev->logger = android_logger_open(logger_list,
                                           android_name_to_log_id(dev->device));
         if (!dev->logger) {
-            openDeviceFail = openDeviceFail ?: dev->device;
+            reportErrorName(&openDeviceFail, dev->device, allSelected);
             dev = dev->next;
             continue;
         }
 
-        if (clearLog) {
-            if (g_outputFileName) {
+        if (clearLog || setId) {
+            if (context->outputFileName) {
                 int maxRotationCountDigits =
-                    (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+                    (context->maxRotatedLogs > 0) ?
+                        (int)(floor(log10(context->maxRotatedLogs) + 1)) :
+                        0;
 
-                for (int i = g_maxRotatedLogs ; i >= 0 ; --i) {
-                    char *file;
+                for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
+                    std::string file;
 
-                    if (i == 0) {
-                        asprintf(&file, "%s", g_outputFileName);
+                    if (!i) {
+                        file = android::base::StringPrintf(
+                            "%s", context->outputFileName);
                     } else {
-                        asprintf(&file, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
+                        file = android::base::StringPrintf("%s.%.*d",
+                            context->outputFileName, maxRotationCountDigits, i);
                     }
 
-                    if (!file) {
+                    if (!file.length()) {
                         perror("while clearing log files");
-                        clearFail = clearFail ?: dev->device;
+                        reportErrorName(&clearFail, dev->device, allSelected);
                         break;
                     }
 
-                    err = unlink(file);
+                    err = unlink(file.c_str());
 
-                    if (err < 0 && errno != ENOENT && clearFail == NULL) {
+                    if (err < 0 && errno != ENOENT && !clearFail) {
                         perror("while clearing log files");
-                        clearFail = dev->device;
+                        reportErrorName(&clearFail, dev->device, allSelected);
                     }
-
-                    free(file);
                 }
             } else if (android_logger_clear(dev->logger)) {
-                clearFail = clearFail ?: dev->device;
+                reportErrorName(&clearFail, dev->device, allSelected);
             }
         }
 
         if (setLogSize) {
             if (android_logger_set_log_size(dev->logger, setLogSize)) {
-                setSizeFail = setSizeFail ?: dev->device;
+                reportErrorName(&setSizeFail, dev->device, allSelected);
             }
         }
 
@@ -1078,66 +1496,82 @@
             long readable = android_logger_get_log_readable_size(dev->logger);
 
             if ((size < 0) || (readable < 0)) {
-                getSizeFail = getSizeFail ?: dev->device;
+                reportErrorName(&getSizeFail, dev->device, allSelected);
             } else {
-                printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
-                       "max entry is %db, max payload is %db\n", dev->device,
+                std::string str = android::base::StringPrintf(
+                       "%s: ring buffer is %ld%sb (%ld%sb consumed),"
+                         " max entry is %db, max payload is %db\n",
+                       dev->device,
                        value_of_size(size), multiplier_of_size(size),
                        value_of_size(readable), multiplier_of_size(readable),
-                       (int) LOGGER_ENTRY_MAX_LEN,
-                       (int) LOGGER_ENTRY_MAX_PAYLOAD);
+                       (int)LOGGER_ENTRY_MAX_LEN,
+                       (int)LOGGER_ENTRY_MAX_PAYLOAD);
+                TEMP_FAILURE_RETRY(write(context->output_fd,
+                                         str.data(), str.length()));
             }
         }
 
         dev = dev->next;
     }
+
+    context->retval = EXIT_SUCCESS;
+
     // report any errors in the above loop and exit
     if (openDeviceFail) {
-        logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
+        logcat_panic(context, HELP_FALSE,
+                     "Unable to open log device '%s'\n", openDeviceFail);
+        goto close;
     }
     if (clearFail) {
-        logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
+        logcat_panic(context, HELP_FALSE,
+                     "failed to clear the '%s' log\n", clearFail);
+        goto close;
     }
     if (setSizeFail) {
-        logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
+        logcat_panic(context, HELP_FALSE,
+                     "failed to set the '%s' log size\n", setSizeFail);
+        goto close;
     }
     if (getSizeFail) {
-        logcat_panic(false, "failed to get the readable '%s' log size",
-                     getSizeFail);
+        logcat_panic(context, HELP_FALSE,
+                     "failed to get the readable '%s' log size", getSizeFail);
+        goto close;
     }
 
     if (setPruneList) {
         size_t len = strlen(setPruneList);
-        /*extra 32 bytes are needed by  android_logger_set_prune_list */
+        // extra 32 bytes are needed by android_logger_set_prune_list
         size_t bLen = len + 32;
-        char *buf = NULL;
+        char* buf = nullptr;
         if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
             buf[len] = '\0';
             if (android_logger_set_prune_list(logger_list, buf, bLen)) {
-                logcat_panic(false, "failed to set the prune list");
+                logcat_panic(context, HELP_FALSE,
+                             "failed to set the prune list");
             }
             free(buf);
         } else {
-            logcat_panic(false, "failed to set the prune list (alloc)");
+            logcat_panic(context, HELP_FALSE,
+                         "failed to set the prune list (alloc)");
         }
+        goto close;
     }
 
     if (printStatistics || getPruneList) {
         size_t len = 8192;
-        char *buf;
+        char* buf;
 
-        for (int retry = 32;
-                (retry >= 0) && ((buf = new char [len]));
-                delete [] buf, buf = NULL, --retry) {
+        for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
+             delete[] buf, buf = nullptr, --retry) {
             if (getPruneList) {
                 android_logger_get_prune_list(logger_list, buf, len);
             } else {
                 android_logger_get_statistics(logger_list, buf, len);
             }
-            buf[len-1] = '\0';
+            buf[len - 1] = '\0';
             if (atol(buf) < 3) {
-                delete [] buf;
-                buf = NULL;
+                delete[] buf;
+                buf = nullptr;
                 break;
             }
             size_t ret = atol(buf) + 1;
@@ -1149,97 +1583,282 @@
         }
 
         if (!buf) {
-            logcat_panic(false, "failed to read data");
+            logcat_panic(context, HELP_FALSE, "failed to read data");
+            goto close;
         }
 
         // remove trailing FF
-        char *cp = buf + len - 1;
+        char* cp = buf + len - 1;
         *cp = '\0';
         bool truncated = *--cp != '\f';
-        if (!truncated) {
-            *cp = '\0';
-        }
+        if (!truncated) *cp = '\0';
 
         // squash out the byte count
         cp = buf;
         if (!truncated) {
-            while (isdigit(*cp)) {
-                ++cp;
-            }
-            if (*cp == '\n') {
-                ++cp;
-            }
+            while (isdigit(*cp)) ++cp;
+            if (*cp == '\n') ++cp;
         }
 
-        printf("%s", cp);
-        delete [] buf;
-        return EXIT_SUCCESS;
+        len = strlen(cp);
+        TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
+        delete[] buf;
+        goto close;
     }
 
+    if (getLogSize || setLogSize || clearLog) goto close;
 
-    if (getLogSize) {
-        return EXIT_SUCCESS;
-    }
-    if (setLogSize || setPruneList) {
-        return EXIT_SUCCESS;
-    }
-    if (clearLog) {
-        return EXIT_SUCCESS;
-    }
+    setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
+    if (context->stop) goto close;
 
-    //LOG_EVENT_INT(10, 12345);
-    //LOG_EVENT_LONG(11, 0x1122334455667788LL);
-    //LOG_EVENT_STRING(0, "whassup, doc?");
+    // LOG_EVENT_INT(10, 12345);
+    // LOG_EVENT_LONG(11, 0x1122334455667788LL);
+    // LOG_EVENT_STRING(0, "whassup, doc?");
 
-    dev = NULL;
-    log_device_t unexpected("unexpected", false);
+    dev = nullptr;
 
-    while (!g_maxCount || (g_printCount < g_maxCount)) {
+    while (!context->stop &&
+           (!context->maxCount || (context->printCount < context->maxCount))) {
         struct log_msg log_msg;
-        log_device_t* d;
         int ret = android_logger_list_read(logger_list, &log_msg);
-
-        if (ret == 0) {
-            logcat_panic(false, "read: unexpected EOF!\n");
+        if (!ret) {
+            logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
+            break;
         }
 
         if (ret < 0) {
-            if (ret == -EAGAIN) {
-                break;
-            }
+            if (ret == -EAGAIN) break;
 
             if (ret == -EIO) {
-                logcat_panic(false, "read: unexpected EOF!\n");
-            }
-            if (ret == -EINVAL) {
-                logcat_panic(false, "read: unexpected length.\n");
-            }
-            logcat_panic(false, "logcat read failure");
-        }
-
-        for (d = devices; d; d = d->next) {
-            if (android_name_to_log_id(d->device) == log_msg.id()) {
+                logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
                 break;
             }
+            if (ret == -EINVAL) {
+                logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
+                break;
+            }
+            logcat_panic(context, HELP_FALSE, "logcat read failure");
+            break;
+        }
+
+        log_device_t* d;
+        for (d = context->devices; d; d = d->next) {
+            if (android_name_to_log_id(d->device) == log_msg.id()) break;
         }
         if (!d) {
-            g_devCount = 2; // set to Multiple
+            context->devCount = 2; // set to Multiple
             d = &unexpected;
             d->binary = log_msg.id() == LOG_ID_EVENTS;
         }
 
         if (dev != d) {
             dev = d;
-            maybePrintStart(dev, printDividers);
+            maybePrintStart(context, dev, printDividers);
+            if (context->stop) break;
         }
-        if (g_printBinary) {
-            printBinary(&log_msg);
+        if (context->printBinary) {
+            printBinary(context, &log_msg);
         } else {
-            processBuffer(dev, &log_msg);
+            processBuffer(context, dev, &log_msg);
         }
     }
 
+close:
+    // Short and sweet. Implemented generic version in android_logcat_destroy.
+    while (!!(dev = context->devices)) {
+        context->devices = dev->next;
+        delete dev;
+    }
     android_logger_list_free(logger_list);
 
-    return EXIT_SUCCESS;
+exit:
+    // close write end of pipe to help things along
+    if (context->output_fd == context->fds[1]) {
+        android::close_output(context);
+    }
+    if (context->error_fd == context->fds[1]) {
+        android::close_error(context);
+    }
+    if (context->fds[1] >= 0) {
+        // NB: should be closed by the above
+        int save_errno = errno;
+        close(context->fds[1]);
+        errno = save_errno;
+        context->fds[1] = -1;
+    }
+    context->thread_stopped = true;
+    return context->retval;
+}
+
+// Can block
+int android_logcat_run_command(android_logcat_context ctx,
+                               int output, int error,
+                               int argc, char* const* argv,
+                               char* const* envp) {
+    android_logcat_context_internal* context = ctx;
+
+    context->output_fd = output;
+    context->error_fd = error;
+    context->argc = argc;
+    context->argv = argv;
+    context->envp = envp;
+    context->stop = false;
+    context->thread_stopped = false;
+    return __logcat(context);
+}
+
+// starts a thread, opens a pipe, returns reading end.
+int android_logcat_run_command_thread(android_logcat_context ctx,
+                                      int argc, char* const* argv,
+                                      char* const* envp) {
+    android_logcat_context_internal* context = ctx;
+
+    int save_errno = EBUSY;
+    if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
+
+    if (pipe(context->fds) < 0) {
+        save_errno = errno;
+        goto exit;
+    }
+
+    pthread_attr_t attr;
+    if (pthread_attr_init(&attr)) {
+        save_errno = errno;
+        goto close_exit;
+    }
+
+    struct sched_param param;
+    memset(&param, 0, sizeof(param));
+    pthread_attr_setschedparam(&attr, &param);
+    pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
+    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
+        int save_errno = errno;
+        goto pthread_attr_exit;
+    }
+
+    context->stop = false;
+    context->thread_stopped = false;
+    context->output_fd = context->fds[1];
+    // save off arguments so they remain while thread is active.
+    for (int i = 0; i < argc; ++i) {
+        context->args.push_back(std::string(argv[i]));
+    }
+    // save off environment so they remain while thread is active.
+    if (envp) for (size_t i = 0; envp[i]; ++i) {
+        context->envs.push_back(std::string(envp[i]));
+    }
+
+    for (auto& str : context->args) {
+        context->argv_hold.push_back(str.c_str());
+    }
+    context->argv_hold.push_back(nullptr);
+    for (auto& str : context->envs) {
+        context->envp_hold.push_back(str.c_str());
+    }
+    context->envp_hold.push_back(nullptr);
+
+    context->argc = context->argv_hold.size() - 1;
+    context->argv = (char* const*)&context->argv_hold[0];
+    context->envp = (char* const*)&context->envp_hold[0];
+
+#ifdef DEBUG
+    fprintf(stderr, "argv[%d] = {", context->argc);
+    for (auto str : context->argv_hold) {
+        fprintf(stderr, " \"%s\"", str ?: "nullptr");
+    }
+    fprintf(stderr, " }\n");
+    fflush(stderr);
+#endif
+    context->retval = EXIT_SUCCESS;
+    if (pthread_create(&context->thr, &attr,
+                       (void*(*)(void*))__logcat, context)) {
+        int save_errno = errno;
+        goto argv_exit;
+    }
+    pthread_attr_destroy(&attr);
+
+    return context->fds[0];
+
+argv_exit:
+    context->argv_hold.clear();
+    context->args.clear();
+    context->envp_hold.clear();
+    context->envs.clear();
+pthread_attr_exit:
+    pthread_attr_destroy(&attr);
+close_exit:
+    close(context->fds[0]);
+    context->fds[0] = -1;
+    close(context->fds[1]);
+    context->fds[1] = -1;
+exit:
+    errno = save_errno;
+    context->stop = true;
+    context->thread_stopped = true;
+    context->retval = EXIT_FAILURE;
+    return -1;
+}
+
+// test if the thread is still doing 'stuff'
+int android_logcat_run_command_thread_running(android_logcat_context ctx) {
+    android_logcat_context_internal* context = ctx;
+
+    return context->thread_stopped == false;
+}
+
+// Finished with context
+int android_logcat_destroy(android_logcat_context* ctx) {
+    android_logcat_context_internal* context = *ctx;
+
+    if (!context) return -EBADF;
+
+    *ctx = nullptr;
+
+    context->stop = true;
+
+    while (context->thread_stopped == false) {
+        // Makes me sad, replace thread_stopped with semaphore.  Short lived.
+        sched_yield();
+    }
+
+    delete context->regex;
+    context->argv_hold.clear();
+    context->args.clear();
+    context->envp_hold.clear();
+    context->envs.clear();
+    if (context->fds[0] >= 0) {
+        close(context->fds[0]);
+        context->fds[0] = -1;
+    }
+    android::close_output(context);
+    android::close_error(context);
+    if (context->fds[1] >= 0) {
+        // NB: could be closed by the above fclose(s), ignore error.
+        int save_errno = errno;
+        close(context->fds[1]);
+        errno = save_errno;
+        context->fds[1] = -1;
+    }
+
+    android_closeEventTagMap(context->eventTagMap);
+
+    // generic cleanup of devices list to handle all possible dirty cases
+    log_device_t* dev;
+    while (!!(dev = context->devices)) {
+        struct logger_list* logger_list = dev->logger_list;
+        if (logger_list) {
+            for (log_device_t* d = dev; d; d = d->next) {
+                if (d->logger_list == logger_list) d->logger_list = nullptr;
+            }
+            android_logger_list_free(logger_list);
+        }
+        context->devices = dev->next;
+        delete dev;
+    }
+
+    int retval = context->retval;
+
+    free(context);
+
+    return retval;
 }
diff --git a/logcat/logcat_main.cpp b/logcat/logcat_main.cpp
new file mode 100644
index 0000000..9477e79
--- /dev/null
+++ b/logcat/logcat_main.cpp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <signal.h>
+#include <stdlib.h>
+
+#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);
+    int retval = android_logcat_run_command(ctx, -1, -1, argc, argv, envp);
+    int ret = android_logcat_destroy(&ctx);
+    if (!ret) ret = retval;
+    return ret;
+}
diff --git a/logcat/logcat_system.cpp b/logcat/logcat_system.cpp
new file mode 100644
index 0000000..ea393bd
--- /dev/null
+++ b/logcat/logcat_system.cpp
@@ -0,0 +1,148 @@
+/*
+ * 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 <ctype.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+#include <log/logcat.h>
+
+static std::string unquote(const char*& cp, const char*& delim) {
+    if ((*cp == '\'') || (*cp == '"')) {
+        // KISS: Simple quotes. Do not handle the case
+        //       of concatenation like "blah"foo'bar'
+        char quote = *cp++;
+        delim = strchr(cp, quote);
+        if (!delim) delim = cp + strlen(cp);
+        std::string str(cp, delim);
+        if (*delim) ++delim;
+        return str;
+    }
+    delim = strpbrk(cp, " \t\f\r\n");
+    if (!delim) delim = cp + strlen(cp);
+    return std::string(cp, delim);
+}
+
+static bool __android_logcat_parse(const char* command,
+                                   std::vector<std::string>& args,
+                                   std::vector<std::string>& envs) {
+    for (const char *delim, *cp = command; cp && *cp; cp = delim) {
+        while (isspace(*cp)) ++cp;
+        if ((args.size() == 0) && (*cp != '=') && !isdigit(*cp)) {
+            const char* env = cp;
+            while (isalnum(*cp) || (*cp == '_')) ++cp;
+            if (cp && (*cp == '=')) {
+                std::string str(env, ++cp);
+                str += unquote(cp, delim);
+                envs.push_back(str);
+                continue;
+            }
+            cp = env;
+        }
+        args.push_back(unquote(cp, delim));
+        if ((args.size() == 1) && (args[0] != "logcat") &&
+            (args[0] != "/system/bin/logcat")) {
+            return false;
+        }
+    }
+    return args.size() != 0;
+}
+
+FILE* android_logcat_popen(android_logcat_context* ctx, const char* command) {
+    *ctx = NULL;
+
+    std::vector<std::string> args;
+    std::vector<std::string> envs;
+    if (!__android_logcat_parse(command, args, envs)) return NULL;
+
+    std::vector<const char*> argv;
+    for (auto& str : args) {
+        argv.push_back(str.c_str());
+    }
+    argv.push_back(NULL);
+
+    std::vector<const char*> envp;
+    for (auto& str : envs) {
+        envp.push_back(str.c_str());
+    }
+    envp.push_back(NULL);
+
+    *ctx = create_android_logcat();
+    if (!*ctx) return NULL;
+
+    int fd = android_logcat_run_command_thread(
+        *ctx, argv.size() - 1, (char* const*)&argv[0], (char* const*)&envp[0]);
+    argv.clear();
+    args.clear();
+    envp.clear();
+    envs.clear();
+    if (fd < 0) {
+        android_logcat_destroy(ctx);
+        return NULL;
+    }
+
+    FILE* retval = fdopen(fd, "reb");
+    if (!retval) android_logcat_destroy(ctx);
+    return retval;
+}
+
+int android_logcat_pclose(android_logcat_context* ctx, FILE* output) {
+    if (*ctx) {
+        static const useconds_t wait_sample = 20000;
+        // Wait two seconds maximum
+        for (size_t retry = ((2 * 1000000) + wait_sample - 1) / wait_sample;
+             android_logcat_run_command_thread_running(*ctx) && retry; --retry) {
+            usleep(wait_sample);
+        }
+    }
+
+    if (output) fclose(output);
+    return android_logcat_destroy(ctx);
+}
+
+int android_logcat_system(const char* command) {
+    std::vector<std::string> args;
+    std::vector<std::string> envs;
+    if (!__android_logcat_parse(command, args, envs)) return -1;
+
+    std::vector<const char*> argv;
+    for (auto& str : args) {
+        argv.push_back(str.c_str());
+    }
+    argv.push_back(NULL);
+
+    std::vector<const char*> envp;
+    for (auto& str : envs) {
+        envp.push_back(str.c_str());
+    }
+    envp.push_back(NULL);
+
+    android_logcat_context ctx = create_android_logcat();
+    if (!ctx) return -1;
+    /* Command return value */
+    int retval = android_logcat_run_command(ctx, -1, -1, argv.size() - 1,
+                                            (char* const*)&argv[0],
+                                            (char* const*)&envp[0]);
+    /* destroy return value */
+    int ret = android_logcat_destroy(&ctx);
+    /* Paranoia merging any discrepancies between the two return values */
+    if (!ret) ret = retval;
+    return ret;
+}
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index 4d5c80c..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}
     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}
+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/logpersist b/logcat/logpersist
index a0e27ce..c09b6b2 100755
--- a/logcat/logpersist
+++ b/logcat/logpersist
@@ -1,8 +1,8 @@
 #! /system/bin/sh
 # logpersist cat, start and stop handlers
 progname="${0##*/}"
-case `getprop ro.build.type` in
-userdebug|eng) ;;
+case `getprop ro.debuggable` in
+1) ;;
 *) echo "${progname} - Permission denied"
    exit 1
    ;;
@@ -17,7 +17,9 @@
    ;;
 esac
 
-data=/data/misc/logd
+log_uid=logd
+log_tag_property=persist.log.tag
+data=/data/misc/logd/logcat
 service=logcatd
 size_default=256
 buffer_default=all
@@ -36,7 +38,7 @@
     -b|--buffer) buffer="${2}" ; shift ;;
     -h|--help|*)
       LEAD_SPACE_="`echo ${progname%.*} | tr '[ -~]' ' '`"
-      echo "${progname%.*}.cat             - dump current ${service%d} logs"
+      echo "${progname%.*}.cat             - dump current ${service} logs"
       echo "${progname%.*}.start [--size=<size_in_kb>] [--buffer=<buffers>] [--clear]"
       echo "${LEAD_SPACE_}                 - start ${service} service"
       echo "${progname%.*}.stop [--clear]  - stop ${service} service"
@@ -65,16 +67,20 @@
   exit 1
 fi
 
+log_tag="`getprop ${log_tag_property}`"
+logd_logpersistd="`getprop ${property}`"
+
 case ${progname} in
 *.cat)
   if [ -n "${size}${buffer}" -o "true" = "${clear}" ]; then
     echo WARNING: Can not use --clear, --size or --buffer with ${progname%.*}.cat >&2
   fi
-  su logd ls "${data}" |
+  su ${log_uid} ls "${data%/*}" |
   tr -d '\r' |
   sort -ru |
-  sed "s#^#${data}/#" |
-  su logd xargs cat
+  sed "s#^#${data%/*}/#" |
+  grep "${data}[.]*[0-9]*\$" |
+  su ${log_uid} xargs cat
   ;;
 *.start)
   current_buffer="`getprop ${property#persist.}.buffer`"
@@ -123,13 +129,19 @@
   while [ "clear" = "`getprop ${property#persist.}`" ]; do
     continue
   done
+  # Tell Settings that we are back on again if we turned logging off
+  tag="${log_tag#Settings}"
+  if [ X"${log_tag}" != X"${tag}" ]; then
+    echo "WARNING: enabling logd service" >&2
+    setprop ${log_tag_property} "${tag#,}"
+  fi
   # ${service}.rc does the heavy lifting with the following trigger
   setprop ${property} ${service}
   # 20ms done, to permit process feedback check
   sleep 1
   getprop ${property#persist.}
-  # also generate an error return code if not found running, bonus
-  ps -t | grep "${data##*/}.*${service%d}"
+  # also generate an error return code if not found running
+  pgrep -u ${log_uid} ${service%d}
   ;;
 *.stop)
   if [ -n "${size}${buffer}" ]; then
@@ -158,3 +170,9 @@
   echo "ERROR: Unexpected command ${0##*/} ${args}" >&2
   exit 1
 esac
+
+if [ X"${log_tag}" != X"`getprop ${log_tag_property}`" ] ||
+   [ X"${logd_logpersistd}" != X"`getprop ${property}`" ]; then
+  echo "WARNING: killing Settings application to pull in new values" >&2
+  am force-stop com.android.settings
+fi
diff --git a/logcat/tests/Android.mk b/logcat/tests/Android.mk
index a28664e..defd3c4 100644
--- a/logcat/tests/Android.mk
+++ b/logcat/tests/Android.mk
@@ -25,14 +25,14 @@
     -Wall -Wextra \
     -Werror \
     -fno-builtin \
-    -std=gnu++11
 
 # -----------------------------------------------------------------------------
-# Benchmarks (actually a gTest where the result code does not matter)
+# Benchmarks
 # ----------------------------------------------------------------------------
 
 benchmark_src_files := \
-    logcat_benchmark.cpp
+    logcat_benchmark.cpp \
+    exec_benchmark.cpp \
 
 # Build benchmarks for the device. Run with:
 #   adb shell /data/nativetest/logcat-benchmarks/logcat-benchmarks
@@ -41,7 +41,8 @@
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
 LOCAL_SRC_FILES := $(benchmark_src_files)
-include $(BUILD_NATIVE_TEST)
+LOCAL_SHARED_LIBRARIES := libbase liblogcat
+include $(BUILD_NATIVE_BENCHMARK)
 
 # -----------------------------------------------------------------------------
 # Unit tests.
@@ -49,6 +50,8 @@
 
 test_src_files := \
     logcat_test.cpp \
+    logcatd_test.cpp \
+    liblogcat_test.cpp \
 
 # Build tests for the device (with .so). Run with:
 #   adb shell /data/nativetest/logcat-unit-tests/logcat-unit-tests
@@ -56,6 +59,6 @@
 LOCAL_MODULE := $(test_module_prefix)unit-tests
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_SHARED_LIBRARIES := liblog libbase liblogcat
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/logcat/tests/exec_benchmark.cpp b/logcat/tests/exec_benchmark.cpp
new file mode 100644
index 0000000..c30a5f5
--- /dev/null
+++ b/logcat/tests/exec_benchmark.cpp
@@ -0,0 +1,96 @@
+/*
+ * 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 <stdio.h>
+
+#include <android-base/file.h>
+#include <benchmark/benchmark.h>
+#include <log/logcat.h>
+
+// Dump the statistics and report results
+
+static void logcat_popen_libc(benchmark::State& state, const char* cmd) {
+    while (state.KeepRunning()) {
+        FILE* fp = popen(cmd, "r");
+        std::string ret;
+        android::base::ReadFdToString(fileno(fp), &ret);
+        pclose(fp);
+    }
+}
+
+static void BM_logcat_stat_popen_libc(benchmark::State& state) {
+    logcat_popen_libc(state, "logcat -b all -S");
+}
+BENCHMARK(BM_logcat_stat_popen_libc);
+
+static void logcat_popen_liblogcat(benchmark::State& state, const char* cmd) {
+    while (state.KeepRunning()) {
+        android_logcat_context ctx;
+        FILE* fp = android_logcat_popen(&ctx, cmd);
+        std::string ret;
+        android::base::ReadFdToString(fileno(fp), &ret);
+        android_logcat_pclose(&ctx, fp);
+    }
+}
+
+static void BM_logcat_stat_popen_liblogcat(benchmark::State& state) {
+    logcat_popen_liblogcat(state, "logcat -b all -S");
+}
+BENCHMARK(BM_logcat_stat_popen_liblogcat);
+
+static void logcat_system_libc(benchmark::State& state, const char* cmd) {
+    while (state.KeepRunning()) {
+        system(cmd);
+    }
+}
+
+static void BM_logcat_stat_system_libc(benchmark::State& state) {
+    logcat_system_libc(state, "logcat -b all -S >/dev/null 2>/dev/null");
+}
+BENCHMARK(BM_logcat_stat_system_libc);
+
+static void logcat_system_liblogcat(benchmark::State& state, const char* cmd) {
+    while (state.KeepRunning()) {
+        android_logcat_system(cmd);
+    }
+}
+
+static void BM_logcat_stat_system_liblogcat(benchmark::State& state) {
+    logcat_system_liblogcat(state, "logcat -b all -S >/dev/null 2>/dev/null");
+}
+BENCHMARK(BM_logcat_stat_system_liblogcat);
+
+// Dump the logs and report results
+
+static void BM_logcat_dump_popen_libc(benchmark::State& state) {
+    logcat_popen_libc(state, "logcat -b all -d");
+}
+BENCHMARK(BM_logcat_dump_popen_libc);
+
+static void BM_logcat_dump_popen_liblogcat(benchmark::State& state) {
+    logcat_popen_liblogcat(state, "logcat -b all -d");
+}
+BENCHMARK(BM_logcat_dump_popen_liblogcat);
+
+static void BM_logcat_dump_system_libc(benchmark::State& state) {
+    logcat_system_libc(state, "logcat -b all -d >/dev/null 2>/dev/null");
+}
+BENCHMARK(BM_logcat_dump_system_libc);
+
+static void BM_logcat_dump_system_liblogcat(benchmark::State& state) {
+    logcat_system_liblogcat(state, "logcat -b all -d >/dev/null 2>/dev/null");
+}
+BENCHMARK(BM_logcat_dump_system_liblogcat);
diff --git a/logcat/tests/liblogcat_test.cpp b/logcat/tests/liblogcat_test.cpp
new file mode 100644
index 0000000..9e9a2c2
--- /dev/null
+++ b/logcat/tests/liblogcat_test.cpp
@@ -0,0 +1,25 @@
+/*
+ * 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 <log/logcat.h>
+
+#define logcat_define(context) android_logcat_context context
+#define logcat_popen(context, command) android_logcat_popen(&context, command)
+#define logcat_pclose(context, fp) android_logcat_pclose(&context, fp)
+#define logcat_system(command) android_logcat_system(command)
+#define logcat liblogcat
+
+#include "logcat_test.cpp"
diff --git a/logcat/tests/logcat_benchmark.cpp b/logcat/tests/logcat_benchmark.cpp
index be815be..8d88628 100644
--- a/logcat/tests/logcat_benchmark.cpp
+++ b/logcat/tests/logcat_benchmark.cpp
@@ -18,19 +18,22 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <gtest/gtest.h>
+#include <benchmark/benchmark.h>
 
 static const char begin[] = "--------- beginning of ";
 
-TEST(logcat, sorted_order) {
-    FILE *fp;
+static void BM_logcat_sorted_order(benchmark::State& state) {
+    FILE* fp;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v time -b radio -b events -b system -b main -d 2>/dev/null",
-      "r")));
+    if (!state.KeepRunning()) return;
+
+    fp = popen(
+        "logcat -v time -b radio -b events -b system -b main -d 2>/dev/null",
+        "r");
+    if (!fp) return;
 
     class timestamp {
-    private:
+       private:
         int month;
         int day;
         int hour;
@@ -39,44 +42,39 @@
         int millisecond;
         bool ok;
 
-    public:
-        void init(const char *buffer)
-        {
+       public:
+        void init(const char* buffer) {
             ok = false;
             if (buffer != NULL) {
-                ok = sscanf(buffer, "%d-%d %d:%d:%d.%d ",
-                    &month, &day, &hour, &minute, &second, &millisecond) == 6;
+                ok = sscanf(buffer, "%d-%d %d:%d:%d.%d ", &month, &day, &hour,
+                            &minute, &second, &millisecond) == 6;
             }
         }
 
-        timestamp(const char *buffer)
-        {
+        explicit timestamp(const char* buffer) {
             init(buffer);
         }
 
-        bool operator< (timestamp &T)
-        {
-            return !ok || !T.ok
-             || (month < T.month)
-             || ((month == T.month)
-              && ((day < T.day)
-               || ((day == T.day)
-                && ((hour < T.hour)
-                 || ((hour == T.hour)
-                  && ((minute < T.minute)
-                   || ((minute == T.minute)
-                    && ((second < T.second)
-                     || ((second == T.second)
-                      && (millisecond < T.millisecond))))))))));
+        bool operator<(timestamp& T) {
+            return !ok || !T.ok || (month < T.month) ||
+                   ((month == T.month) &&
+                    ((day < T.day) ||
+                     ((day == T.day) &&
+                      ((hour < T.hour) ||
+                       ((hour == T.hour) &&
+                        ((minute < T.minute) ||
+                         ((minute == T.minute) &&
+                          ((second < T.second) ||
+                           ((second == T.second) &&
+                            (millisecond < T.millisecond))))))))));
         }
 
-        bool valid(void)
-        {
+        bool valid(void) {
             return ok;
         }
     } last(NULL);
 
-    char *last_buffer = NULL;
+    char* last_buffer = NULL;
     char buffer[5120];
 
     int count = 0;
@@ -114,15 +112,22 @@
 
     // Allow few fails, happens with readers active
     fprintf(stderr, "%s: %d/%d out of order entries\n",
-            (next_lt_last)
-                ? ((next_lt_last <= max_ok)
-                    ? "WARNING"
-                    : "ERROR")
-                : "INFO",
+            (next_lt_last) ? ((next_lt_last <= max_ok) ? "WARNING" : "ERROR")
+                           : "INFO",
             next_lt_last, count);
 
-    EXPECT_GE(max_ok, next_lt_last);
+    if (next_lt_last > max_ok) {
+        fprintf(stderr, "EXPECT_GE(max_ok=%d, next_lt_last=%d)\n", max_ok,
+                next_lt_last);
+    }
 
     // sample statistically too small
-    EXPECT_LT(100, count);
+    if (count < 100) {
+        fprintf(stderr, "EXPECT_LT(100, count=%d)\n", count);
+    }
+
+    state.KeepRunning();
 }
+BENCHMARK(BM_logcat_sorted_order);
+
+BENCHMARK_MAIN();
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index d79fc08..21868f2 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -20,13 +20,30 @@
 #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>
+#include <unistd.h>
 
+#include <memory>
+#include <string>
+
+#include <android-base/file.h>
 #include <gtest/gtest.h>
 #include <log/log.h>
-#include <log/logger.h>
-#include <log/log_read.h>
+#include <log/log_event_list.h>
+
+#ifndef logcat_popen
+#define logcat_define(context)
+#define logcat_popen(context, command) popen((command), "r")
+#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)
 
@@ -34,25 +51,31 @@
 // 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
 // than try a usleep.
-#define LOG_FAILURE_RETRY(exp) ({  \
-    typeof (exp) _rc;              \
-    do {                           \
-        _rc = (exp);               \
-    } while (((_rc == -1)          \
-           && ((errno == EINTR)    \
-            || (errno == EAGAIN))) \
-          || (_rc == -EINTR)       \
-          || (_rc == -EAGAIN));    \
-    _rc; })
+#define LOG_FAILURE_RETRY(exp)                                               \
+    ({                                                                       \
+        typeof(exp) _rc;                                                     \
+        do {                                                                 \
+            _rc = (exp);                                                     \
+        } while (((_rc == -1) && ((errno == EINTR) || (errno == EAGAIN))) || \
+                 (_rc == -EINTR) || (_rc == -EAGAIN));                       \
+        _rc;                                                                 \
+    })
 
 static const char begin[] = "--------- beginning of ";
 
 TEST(logcat, buckets) {
-    FILE *fp;
+    FILE* fp;
+    logcat_define(ctx);
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -b radio -b events -b system -b main -d 2>/dev/null",
-      "r")));
+#undef LOG_TAG
+#define LOG_TAG "inject"
+    RLOGE(logcat_executable ".buckets");
+    sleep(1);
+
+    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];
 
@@ -61,7 +84,7 @@
 
     while (fgets(buffer, sizeof(buffer), fp)) {
         if (!strncmp(begin, buffer, sizeof(begin) - 1)) {
-            while (char *cp = strrchr(buffer, '\n')) {
+            while (char* cp = strrchr(buffer, '\n')) {
                 *cp = '\0';
             }
             log_id_t id = android_name_to_log_id(buffer + sizeof(begin) - 1);
@@ -70,78 +93,133 @@
         }
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     EXPECT_EQ(15, ids);
 
     EXPECT_EQ(4, count);
 }
 
-TEST(logcat, year) {
+TEST(logcat, event_tag_filter) {
+    FILE* fp;
+    logcat_define(ctx);
 
-    if (android_log_clockid() == CLOCK_MONOTONIC) {
-        fprintf(stderr, "Skipping test, logd is monotonic time\n");
-        return;
-    }
-
-    FILE *fp;
-
-    char needle[32];
-    time_t now;
-    time(&now);
-    struct tm *ptm;
-#if !defined(_WIN32)
-    struct tm tmBuf;
-    ptm = localtime_r(&now, &tmBuf);
-#else
-    ptm = localtime(&&now);
-#endif
-    strftime(needle, sizeof(needle), "[ %Y-", ptm);
-
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v long -v year -b all -t 3 2>/dev/null",
-      "r")));
+    ASSERT_TRUE(NULL !=
+                (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")));
 
     char buffer[BIG_BUFFER];
 
     int count = 0;
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        if (!strncmp(buffer, needle, strlen(needle))) {
-            ++count;
-        }
+        ++count;
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
+
+    EXPECT_LT(4, count);
+}
+
+// If there is not enough background noise in the logs, then spam the logs to
+// permit tail checking so that the tests can progress.
+static size_t inject(ssize_t count) {
+    if (count <= 0) return 0;
+
+    static const size_t retry = 4;
+    size_t errors = retry;
+    size_t num = 0;
+    for (;;) {
+        log_time ts(CLOCK_MONOTONIC);
+        if (__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) >= 0) {
+            if (++num >= (size_t)count) {
+                // let data settle end-to-end
+                sleep(3);
+                return num;
+            }
+            errors = retry;
+            usleep(100);  // ~32 per timer tick, we are a spammer regardless
+        } else if (--errors <= 0) {
+            return num;
+        }
+    }
+    // NOTREACH
+    return num;
+}
+
+TEST(logcat, year) {
+    if (android_log_clockid() == CLOCK_MONOTONIC) {
+        fprintf(stderr, "Skipping test, logd is monotonic time\n");
+        return;
+    }
+
+    int count;
+    int tries = 3;  // in case run too soon after system start or buffer clear
+
+    do {
+        FILE* fp;
+        logcat_define(ctx);
+
+        char needle[32];
+        time_t now;
+        time(&now);
+        struct tm* ptm;
+#if !defined(_WIN32)
+        struct tm tmBuf;
+        ptm = localtime_r(&now, &tmBuf);
+#else
+        ptm = localtime(&&now);
+#endif
+        strftime(needle, sizeof(needle), "[ %Y-", ptm);
+
+        ASSERT_TRUE(NULL != (fp = logcat_popen(
+                                 ctx, logcat_executable
+                                 " -v long -v year -b all -t 3 2>/dev/null")));
+
+        char buffer[BIG_BUFFER];
+
+        count = 0;
+
+        while (fgets(buffer, sizeof(buffer), fp)) {
+            if (!strncmp(buffer, needle, strlen(needle))) {
+                ++count;
+            }
+        }
+        logcat_pclose(ctx, fp);
+
+    } while ((count < 3) && --tries && inject(3 - count));
 
     ASSERT_EQ(3, count);
 }
 
 // Return a pointer to each null terminated -v long time field.
-char *fgetLongTime(char *buffer, size_t buflen, FILE *fp) {
+static char* fgetLongTime(char* buffer, size_t buflen, FILE* fp) {
     while (fgets(buffer, buflen, fp)) {
-        char *cp = buffer;
+        char* cp = buffer;
         if (*cp != '[') {
             continue;
         }
         while (*++cp == ' ') {
             ;
         }
-        char *ep = cp;
+        char* ep = cp;
         while (isdigit(*ep)) {
             ++ep;
         }
         if ((*ep != '-') && (*ep != '.')) {
-           continue;
+            continue;
         }
-        // Find PID field
+        // Find PID field.  Look for ': ' or ':[0-9][0-9][0-9]'
         while (((ep = strchr(ep, ':'))) && (*++ep != ' ')) {
-            ;
+            if (isdigit(ep[0]) && isdigit(ep[1]) && isdigit(ep[2])) break;
         }
         if (!ep) {
             continue;
         }
-        ep -= 7;
+        static const size_t pid_field_width = 7;
+        ep -= pid_field_width;
         *ep = '\0';
         return cp;
     }
@@ -149,21 +227,22 @@
 }
 
 TEST(logcat, tz) {
-
     if (android_log_clockid() == CLOCK_MONOTONIC) {
         fprintf(stderr, "Skipping test, logd is monotonic time\n");
         return;
     }
 
-    int tries = 3; // in case run too soon after system start or buffer clear
+    int tries = 4;  // in case run too soon after system start or buffer clear
     int count;
 
     do {
-        FILE *fp;
+        FILE* fp;
+        logcat_define(ctx);
 
-        ASSERT_TRUE(NULL != (fp = popen(
-          "logcat -v long -v America/Los_Angeles -b all -t 3 2>/dev/null",
-          "r")));
+        ASSERT_TRUE(NULL !=
+                    (fp = logcat_popen(ctx, logcat_executable
+                                       " -v long -v America/Los_Angeles "
+                                       "-b all -t 3 2>/dev/null")));
 
         char buffer[BIG_BUFFER];
 
@@ -172,22 +251,25 @@
         while (fgetLongTime(buffer, sizeof(buffer), fp)) {
             if (strstr(buffer, " -0700") || strstr(buffer, " -0800")) {
                 ++count;
+            } else {
+                fprintf(stderr, "ts=\"%s\"\n", buffer + 2);
             }
         }
 
-        pclose(fp);
+        logcat_pclose(ctx, fp);
 
-    } while ((count < 3) && --tries && (sleep(1), true));
+    } while ((count < 3) && --tries && inject(3 - count));
 
     ASSERT_EQ(3, count);
 }
 
 TEST(logcat, ntz) {
-    FILE *fp;
+    FILE* fp;
+    logcat_define(ctx);
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v long -v America/Los_Angeles -v zone -b all -t 3 2>/dev/null",
-      "r")));
+    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];
 
@@ -199,24 +281,26 @@
         }
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     ASSERT_EQ(0, count);
 }
 
-void do_tail(int num) {
-    int tries = 3; // in case run too soon after system start or buffer clear
+static void do_tail(int num) {
+    int tries = 4;  // in case run too soon after system start or buffer clear
     int count;
 
+    if (num > 10) ++tries;
+    if (num > 100) ++tries;
     do {
         char buffer[BIG_BUFFER];
 
         snprintf(buffer, sizeof(buffer),
-          "logcat -v long -b radio -b events -b system -b main -t %d 2>/dev/null",
-          num);
+                 "ANDROID_PRINTF_LOG=long logcat -b all -t %d 2>/dev/null", num);
 
-        FILE *fp;
-        ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
+        FILE* fp;
+        logcat_define(ctx);
+        ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
         count = 0;
 
@@ -224,9 +308,9 @@
             ++count;
         }
 
-        pclose(fp);
+        logcat_pclose(ctx, fp);
 
-    } while ((count < num) && --tries && (sleep(1), true));
+    } while ((count < num) && --tries && inject(num - count));
 
     ASSERT_EQ(num, count);
 }
@@ -247,62 +331,119 @@
     do_tail(1000);
 }
 
-TEST(logcat, tail_time) {
-    FILE *fp;
-
-    ASSERT_TRUE(NULL != (fp = popen("logcat -v long -b all -t 10 2>&1", "r")));
-
+static void do_tail_time(const char* cmd) {
+    FILE* fp;
+    int count;
     char buffer[BIG_BUFFER];
-    char *last_timestamp = NULL;
-    char *first_timestamp = NULL;
-    int count = 0;
+    char* last_timestamp = NULL;
+    // Hard to predict 100% if first (overlap) or second line will match.
+    // -v nsec will in a substantial majority be the second line.
+    char* first_timestamp = NULL;
+    char* second_timestamp = NULL;
+    char* input;
 
-    char *cp;
-    while ((cp = fgetLongTime(buffer, sizeof(buffer), fp))) {
-        ++count;
-        if (!first_timestamp) {
-            first_timestamp = strdup(cp);
+    int tries = 4;  // in case run too soon after system start or buffer clear
+
+    do {
+        snprintf(buffer, sizeof(buffer), "%s -t 10 2>&1", cmd);
+        logcat_define(ctx);
+        ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
+        count = 0;
+
+        while ((input = fgetLongTime(buffer, sizeof(buffer), fp))) {
+            ++count;
+            if (!first_timestamp) {
+                first_timestamp = strdup(input);
+            } else if (!second_timestamp) {
+                second_timestamp = strdup(input);
+            }
+            free(last_timestamp);
+            last_timestamp = strdup(input);
         }
-        free(last_timestamp);
-        last_timestamp = strdup(cp);
-    }
-    pclose(fp);
+        logcat_pclose(ctx, fp);
 
-    EXPECT_EQ(10, count);
+    } while ((count < 10) && --tries && inject(10 - count));
+
+    EXPECT_EQ(10, count);  // We want _some_ history, too small, falses below
     EXPECT_TRUE(last_timestamp != NULL);
     EXPECT_TRUE(first_timestamp != NULL);
+    EXPECT_TRUE(second_timestamp != NULL);
 
-    snprintf(buffer, sizeof(buffer), "logcat -v long -b all -t '%s' 2>&1",
-             first_timestamp);
-    ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
+    snprintf(buffer, sizeof(buffer), "%s -t '%s' 2>&1", cmd, first_timestamp);
+    logcat_define(ctx);
+    ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
     int second_count = 0;
     int last_timestamp_count = -1;
 
-    while ((cp = fgetLongTime(buffer, sizeof(buffer), fp))) {
+    --count;  // One less unless we match the first_timestamp
+    bool found = false;
+    while ((input = fgetLongTime(buffer, sizeof(buffer), fp))) {
         ++second_count;
+        // We want to highlight if we skip to the next entry.
+        // WAI, if the time in logd is *exactly*
+        // XX-XX XX:XX:XX.XXXXXX000 (usec) or XX-XX XX:XX:XX.XXX000000
+        // this can happen, but it should not happen with nsec.
+        // We can make this WAI behavior happen 1000 times less
+        // frequently if the caller does not use the -v usec flag,
+        // but always the second (always skip) if they use the
+        // (undocumented) -v nsec flag.
         if (first_timestamp) {
-            // we can get a transitory *extremely* rare failure if hidden
-            // underneath the time is *exactly* XX-XX XX:XX:XX.XXX000000
-            EXPECT_STREQ(cp, first_timestamp);
+            found = !strcmp(input, first_timestamp);
+            if (found) {
+                ++count;
+                GTEST_LOG_(INFO)
+                    << "input = first(" << first_timestamp << ")\n";
+            }
             free(first_timestamp);
             first_timestamp = NULL;
         }
-        if (!strcmp(cp, last_timestamp)) {
+        if (second_timestamp) {
+            found = found || !strcmp(input, second_timestamp);
+            if (!found) {
+                GTEST_LOG_(INFO) << "input(" << input << ") != second("
+                                 << second_timestamp << ")\n";
+            }
+            free(second_timestamp);
+            second_timestamp = NULL;
+        }
+        if (!strcmp(input, last_timestamp)) {
             last_timestamp_count = second_count;
         }
     }
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
+    EXPECT_TRUE(found);
+    if (!found) {
+        if (first_timestamp) {
+            GTEST_LOG_(INFO) << "first = " << first_timestamp << "\n";
+        }
+        if (second_timestamp) {
+            GTEST_LOG_(INFO) << "second = " << second_timestamp << "\n";
+        }
+        if (last_timestamp) {
+            GTEST_LOG_(INFO) << "last = " << last_timestamp << "\n";
+        }
+    }
     free(last_timestamp);
     last_timestamp = NULL;
     free(first_timestamp);
+    free(second_timestamp);
 
     EXPECT_TRUE(first_timestamp == NULL);
+    EXPECT_TRUE(second_timestamp == NULL);
     EXPECT_LE(count, second_count);
     EXPECT_LE(count, last_timestamp_count);
 }
 
+TEST(logcat, tail_time) {
+    do_tail_time(logcat_executable " -v long -v nsec -b all");
+}
+
+TEST(logcat, tail_time_epoch) {
+    do_tail_time(logcat_executable " -v long -v nsec -v epoch -b all");
+}
+
 TEST(logcat, End_to_End) {
     pid_t pid = getpid();
 
@@ -310,10 +451,11 @@
 
     ASSERT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
 
-    FILE *fp;
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v brief -b events -t 100 2>/dev/null",
-      "r")));
+    FILE* fp;
+    logcat_define(ctx);
+    ASSERT_TRUE(NULL !=
+                (fp = logcat_popen(ctx, logcat_executable
+                                   " -v brief -b events -t 100 2>/dev/null")));
 
     char buffer[BIG_BUFFER];
 
@@ -323,27 +465,78 @@
         int p;
         unsigned long long t;
 
-        if ((2 != sscanf(buffer, "I/[0]     ( %d): %llu", &p, &t))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0]     ( %d): %llu", &p, &t)) ||
+            (p != pid)) {
             continue;
         }
 
-        log_time tx((const char *) &t);
+        log_time tx((const char*)&t);
         if (ts == tx) {
             ++count;
         }
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     ASSERT_EQ(1, count);
 }
 
-int get_groups(const char *cmd) {
-    FILE *fp;
+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);
 
     // NB: crash log only available in user space
-    EXPECT_TRUE(NULL != (fp = popen(cmd, "r")));
+    EXPECT_TRUE(NULL != (fp = logcat_popen(ctx, cmd)));
 
     if (fp == NULL) {
         return 0;
@@ -361,84 +554,89 @@
         size = consumed = max = payload = 0;
         // NB: crash log can be very small, not hit a Kb of consumed space
         //     doubly lucky we are not including it.
-        if (6 != sscanf(buffer, "%*s ring buffer is %d%2s (%d%2s consumed),"
-                                " max entry is %db, max payload is %db",
-                                &size, size_mult, &consumed, consumed_mult,
-                                &max, &payload)) {
+        if (6 != sscanf(buffer,
+                        "%*s ring buffer is %d%2s (%d%2s consumed),"
+                        " max entry is %db, max payload is %db",
+                        &size, size_mult, &consumed, consumed_mult, &max,
+                        &payload)) {
             fprintf(stderr, "WARNING: Parse error: %s", buffer);
             continue;
         }
         full_size = size;
-        switch(size_mult[0]) {
-        case 'G':
-            full_size *= 1024;
+        switch (size_mult[0]) {
+            case 'G':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'M':
-            full_size *= 1024;
+            case 'M':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'K':
-            full_size *= 1024;
+            case 'K':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'b':
-            break;
+            case 'b':
+                break;
         }
         full_consumed = consumed;
-        switch(consumed_mult[0]) {
-        case 'G':
-            full_consumed *= 1024;
+        switch (consumed_mult[0]) {
+            case 'G':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'M':
-            full_consumed *= 1024;
+            case 'M':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'K':
-            full_consumed *= 1024;
+            case 'K':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'b':
-            break;
+            case 'b':
+                break;
         }
         EXPECT_GT((full_size * 9) / 4, full_consumed);
         EXPECT_GT(full_size, max);
         EXPECT_GT(max, payload);
 
-        if ((((full_size * 9) / 4) >= full_consumed)
-         && (full_size > max)
-         && (max > payload)) {
+        if ((((full_size * 9) / 4) >= full_consumed) && (full_size > max) &&
+            (max > payload)) {
             ++count;
         }
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     return count;
 }
 
 TEST(logcat, get_size) {
-    ASSERT_EQ(4, get_groups(
-      "logcat -v brief -b radio -b events -b system -b main -g 2>/dev/null"));
+    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"));
+    ASSERT_EQ(
+        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"));
 }
 
-static void caught_blocking(int /*signum*/)
-{
+#ifndef logcat
+static void caught_blocking(int signum) {
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
     v += getpid() & 0xFFFF;
+    if (signum == 0) ++v;
 
     LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 }
 
 TEST(logcat, blocking) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xDEADBEEFA55F0000ULL;
 
     pid_t pid = getpid();
@@ -449,10 +647,11 @@
 
     v &= 0xFFFFFFFFFFFAFFFFULL;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -v brief -b events 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -v brief -b events 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -463,7 +662,6 @@
     signal(SIGALRM, caught_blocking);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "DONE", 4)) {
             break;
         }
@@ -473,8 +671,7 @@
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -497,17 +694,17 @@
     EXPECT_EQ(1, signals);
 }
 
-static void caught_blocking_tail(int /*signum*/)
-{
+static void caught_blocking_tail(int signum) {
     unsigned long long v = 0xA55ADEADBEEF0000ULL;
 
     v += getpid() & 0xFFFF;
+    if (signum == 0) ++v;
 
     LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 }
 
 TEST(logcat, blocking_tail) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xA55FDEADBEEF0000ULL;
 
     pid_t pid = getpid();
@@ -518,10 +715,11 @@
 
     v &= 0xFFFAFFFFFFFFFFFFULL;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -v brief -b events -T 5 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -v brief -b events -T 5 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -532,7 +730,6 @@
     signal(SIGALRM, caught_blocking_tail);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "DONE", 4)) {
             break;
         }
@@ -542,8 +739,7 @@
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -567,23 +763,32 @@
 
     EXPECT_EQ(1, signals);
 }
+#endif
+
+// meant to be handed to ASSERT_FALSE / EXPECT_FALSE to expand the message
+static testing::AssertionResult IsFalse(int ret, const char* command) {
+    return ret ? (testing::AssertionSuccess()
+                  << "ret=" << ret << " command=\"" << command << "\"")
+               : testing::AssertionFailure();
+}
 
 TEST(logcat, logrotate) {
     static const char form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
     char buf[sizeof(form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(buf, form)));
 
-    static const char comm[] = "logcat -b radio -b events -b system -b main"
-                                     " -d -f %s/log.txt -n 7 -r 1";
+    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);
 
     int ret;
-    EXPECT_FALSE((ret = system(command)));
+    EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
     if (!ret) {
         snprintf(command, sizeof(command), "ls -s %s 2>/dev/null", buf);
 
-        FILE *fp;
+        FILE* fp;
         EXPECT_TRUE(NULL != (fp = popen(command, "r")));
         if (fp) {
             char buffer[BIG_BUFFER];
@@ -595,7 +800,7 @@
                 char c;
 
                 if ((2 == sscanf(buffer, "%d log.tx%c", &num, &c)) &&
-                        (num <= 40)) {
+                    (num <= 40)) {
                     ++count;
                 } else if (strncmp(buffer, total, sizeof(total) - 1)) {
                     fprintf(stderr, "WARNING: Parse error: %s", buffer);
@@ -609,25 +814,27 @@
         }
     }
     snprintf(command, sizeof(command), "rm -rf %s", buf);
-    EXPECT_FALSE(system(command));
+    EXPECT_FALSE(IsFalse(system(command), command));
 }
 
 TEST(logcat, logrotate_suffix) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     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"
-                                     " -d -f %s/log.txt -n 10 -r 1";
+    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);
 
     int ret;
-    EXPECT_FALSE((ret = system(command)));
+    EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
     if (!ret) {
         snprintf(command, sizeof(command), "ls %s 2>/dev/null", tmp_out_dir);
 
-        FILE *fp;
+        FILE* fp;
         EXPECT_TRUE(NULL != (fp = popen(command, "r")));
         char buffer[BIG_BUFFER];
         int log_file_count = 0;
@@ -638,21 +845,24 @@
                 strlen(rotated_log_filename_prefix);
             static const char log_filename[] = "log.txt";
 
-            if (!strncmp(buffer, rotated_log_filename_prefix, rotated_log_filename_prefix_len)) {
-              // Rotated file should have form log.txt.##
-              char* rotated_log_filename_suffix = buffer + rotated_log_filename_prefix_len;
-              char* endptr;
-              const long int suffix_value = strtol(rotated_log_filename_suffix, &endptr, 10);
-              EXPECT_EQ(rotated_log_filename_suffix + 2, endptr);
-              EXPECT_LE(suffix_value, 10);
-              EXPECT_GT(suffix_value, 0);
-              ++log_file_count;
-              continue;
+            if (!strncmp(buffer, rotated_log_filename_prefix,
+                         rotated_log_filename_prefix_len)) {
+                // Rotated file should have form log.txt.##
+                char* rotated_log_filename_suffix =
+                    buffer + rotated_log_filename_prefix_len;
+                char* endptr;
+                const long int suffix_value =
+                    strtol(rotated_log_filename_suffix, &endptr, 10);
+                EXPECT_EQ(rotated_log_filename_suffix + 2, endptr);
+                EXPECT_LE(suffix_value, 10);
+                EXPECT_GT(suffix_value, 0);
+                ++log_file_count;
+                continue;
             }
 
             if (!strncmp(buffer, log_filename, strlen(log_filename))) {
-              ++log_file_count;
-              continue;
+                ++log_file_count;
+                continue;
             }
 
             fprintf(stderr, "ERROR: Unexpected file: %s", buffer);
@@ -662,40 +872,49 @@
         EXPECT_EQ(11, log_file_count);
     }
     snprintf(command, sizeof(command), "rm -rf %s", tmp_out_dir);
-    EXPECT_FALSE(system(command));
+    EXPECT_FALSE(IsFalse(system(command), command));
 }
 
 TEST(logcat, logrotate_continue) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
     static const char log_filename[] = "log.txt";
-    static const char logcat_cmd[] = "logcat -b all -d -f %s/%s -n 256 -r 1024";
+    static const char logcat_cmd[] =
+        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);
 
     int ret;
-    EXPECT_FALSE((ret = system(command)));
+    EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
     if (ret) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-        EXPECT_FALSE(system(command));
+        EXPECT_FALSE(IsFalse(system(command), command));
         return;
     }
-    FILE *fp;
+    FILE* fp;
     snprintf(command, sizeof(command), "%s/%s", tmp_out_dir, log_filename);
     EXPECT_TRUE(NULL != ((fp = fopen(command, "r"))));
     if (!fp) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-        EXPECT_FALSE(system(command));
+        EXPECT_FALSE(IsFalse(system(command), command));
         return;
     }
-    char *line = NULL;
-    char *last_line = NULL; // this line is allowed to stutter, one-line overlap
-    char *second_last_line = NULL;
+    char* line = NULL;
+    char* last_line =
+        NULL;  // this line is allowed to stutter, one-line overlap
+    char* second_last_line = NULL;  // should never stutter
+    char* first_line = NULL;        // help diagnose failure?
     size_t len = 0;
     while (getline(&line, &len, fp) != -1) {
+        if (!first_line) {
+            first_line = line;
+            line = NULL;
+            continue;
+        }
         free(second_last_line);
         second_last_line = last_line;
         last_line = line;
@@ -712,28 +931,34 @@
     EXPECT_TRUE(NULL != second_last_line);
     if (!second_last_line) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-        EXPECT_FALSE(system(command));
+        EXPECT_FALSE(IsFalse(system(command), command));
+        free(first_line);
         return;
     }
     // re-run the command, it should only add a few lines more content if it
     // continues where it left off.
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir, log_filename);
-    EXPECT_FALSE((ret = system(command)));
+    EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
     if (ret) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-        EXPECT_FALSE(system(command));
+        EXPECT_FALSE(IsFalse(system(command), command));
+        free(second_last_line);
+        free(first_line);
         return;
     }
-    DIR *dir;
-    EXPECT_TRUE(NULL != (dir = opendir(tmp_out_dir)));
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                  closedir);
+    EXPECT_NE(nullptr, dir);
     if (!dir) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-        EXPECT_FALSE(system(command));
+        EXPECT_FALSE(IsFalse(system(command), command));
+        free(second_last_line);
+        free(first_line);
         return;
     }
-    struct dirent *entry;
+    struct dirent* entry;
     unsigned count = 0;
-    while ((entry = readdir(dir))) {
+    while ((entry = readdir(dir.get()))) {
         if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
             continue;
         }
@@ -756,53 +981,61 @@
         free(line);
         unlink(command);
     }
-    closedir(dir);
     if (count > 1) {
-        char *brk = strpbrk(second_last_line, "\r\n");
-        if (!brk) {
-            brk = second_last_line + strlen(second_last_line);
+        char* brk = strpbrk(second_last_line, "\r\n");
+        if (!brk) brk = second_last_line + strlen(second_last_line);
+        fprintf(stderr, "\"%.*s\" occurred %u times\n",
+                (int)(brk - second_last_line), second_last_line, count);
+        if (first_line) {
+            brk = strpbrk(first_line, "\r\n");
+            if (!brk) brk = first_line + strlen(first_line);
+            fprintf(stderr, "\"%.*s\" was first line, fault?\n",
+                    (int)(brk - first_line), first_line);
         }
-        fprintf(stderr, "\"%.*s\" occured %u times\n",
-            (int)(brk - second_last_line), second_last_line, count);
     }
     free(second_last_line);
+    free(first_line);
 
     snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-    EXPECT_FALSE(system(command));
+    EXPECT_FALSE(IsFalse(system(command), command));
 }
 
 TEST(logcat, logrotate_clear) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
     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) + sizeof(log_filename) + sizeof(clear_cmd) + 32];
+    char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) +
+                 sizeof(log_filename) + sizeof(clear_cmd) + 32];
 
     // Run command with all data
     {
-        snprintf(command, sizeof(command) - sizeof(clear_cmd),
-                 logcat_cmd, tmp_out_dir, log_filename, num_val);
+        snprintf(command, sizeof(command) - sizeof(clear_cmd), logcat_cmd,
+                 tmp_out_dir, log_filename, num_val);
 
         int ret;
-        EXPECT_FALSE((ret = system(command)));
+        EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
         if (ret) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-            EXPECT_FALSE(system(command));
+            EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                      closedir);
         EXPECT_NE(nullptr, dir);
         if (!dir) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-            EXPECT_FALSE(system(command));
+            EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        struct dirent *entry;
+        struct dirent* entry;
         unsigned count = 0;
         while ((entry = readdir(dir.get()))) {
             if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -818,20 +1051,22 @@
         strcat(command, clear_cmd);
 
         int ret;
-        EXPECT_FALSE((ret = system(command)));
+        EXPECT_FALSE(IsFalse(ret = logcat_system(command), command));
         if (ret) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
             EXPECT_FALSE(system(command));
+            EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                      closedir);
         EXPECT_NE(nullptr, dir);
         if (!dir) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-            EXPECT_FALSE(system(command));
+            EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        struct dirent *entry;
+        struct dirent* entry;
         unsigned count = 0;
         while ((entry = readdir(dir.get()))) {
             if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -844,27 +1079,105 @@
     }
 
     snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
-    EXPECT_FALSE(system(command));
+    EXPECT_FALSE(IsFalse(system(command), command));
+}
+
+static int logrotate_count_id(const char* logcat_cmd, const char* tmp_out_dir) {
+    static const char log_filename[] = "log.txt";
+    char command[strlen(tmp_out_dir) + strlen(logcat_cmd) +
+                 strlen(log_filename) + 32];
+
+    snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir, log_filename);
+
+    int ret = logcat_system(command);
+    if (ret) {
+        fprintf(stderr, "system(\"%s\")=%d", command, ret);
+        return -1;
+    }
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                  closedir);
+    if (!dir) {
+        fprintf(stderr, "opendir(\"%s\") failed", tmp_out_dir);
+        return -1;
+    }
+    struct dirent* entry;
+    int count = 0;
+    while ((entry = readdir(dir.get()))) {
+        if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
+            continue;
+        }
+        ++count;
+    }
+    return count;
+}
+
+TEST(logcat, logrotate_id) {
+    static const char logcat_cmd[] =
+        logcat_executable " -b all -d -f %s/%s -n 32 -r 1 --id=test";
+    static const char logcat_short_cmd[] =
+        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";
+    char tmp_out_dir[strlen(tmp_out_dir_form) + 1];
+    ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
+
+    EXPECT_EQ(34, logrotate_count_id(logcat_cmd, tmp_out_dir));
+    EXPECT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
+
+    char id_file[strlen(tmp_out_dir_form) + strlen(log_filename) + 5];
+    snprintf(id_file, sizeof(id_file), "%s/%s.id", tmp_out_dir, log_filename);
+    if (getuid() != 0) {
+        chmod(id_file, 0);
+        EXPECT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
+    }
+    unlink(id_file);
+    EXPECT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
+
+    FILE* fp = fopen(id_file, "w");
+    if (fp) {
+        fprintf(fp, "not_a_test");
+        fclose(fp);
+    }
+    if (getuid() != 0) {
+        chmod(id_file,
+              0);  // API to preserve content even with signature change
+        ASSERT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
+        chmod(id_file, 0600);
+    }
+
+    int new_signature;
+    EXPECT_LE(
+        2, (new_signature = logrotate_count_id(logcat_short_cmd, tmp_out_dir)));
+    EXPECT_GT(34, new_signature);
+
+    static const char cleanup_cmd[] = "rm -rf %s";
+    char command[strlen(cleanup_cmd) + strlen(tmp_out_dir_form)];
+    snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+    EXPECT_FALSE(IsFalse(system(command), command));
 }
 
 TEST(logcat, logrotate_nodir) {
-    // expect logcat to error out on writing content and exit(1) for nodir
-    EXPECT_EQ(W_EXITCODE(1, 0),
-              system("logcat -b all -d"
-                     " -f /das/nein/gerfingerpoken/logcat/log.txt"
-                     " -n 256 -r 1024"));
+    // expect logcat to error out on writing content and not exit(0) for nodir
+    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));
 }
 
-static void caught_blocking_clear(int /*signum*/) {
+#ifndef logcat
+static void caught_blocking_clear(int signum) {
     unsigned long long v = 0xDEADBEEFA55C0000ULL;
 
     v += getpid() & 0xFFFF;
+    if (signum == 0) ++v;
 
     LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
 }
 
 TEST(logcat, blocking_clear) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xDEADBEEFA55C0000ULL;
 
     pid_t pid = getpid();
@@ -873,22 +1186,24 @@
 
     // This test is racey; an event occurs between clear and dump.
     // We accept that we will get a false positive, but never a false negative.
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -b events -c 2>&1 ;"
-      " logcat -v brief -b events 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -b events -c 2>&1 ;"
+                    " logcat -b events -g 2>&1 ;"
+                    " logcat -v brief -b events 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
     int count = 0;
+    int minus_g = 0;
 
     int signals = 0;
 
     signal(SIGALRM, caught_blocking_clear);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "clearLog: ", 10)) {
             fprintf(stderr, "WARNING: Test lacks permission to run :-(\n");
             count = signals = 1;
@@ -899,13 +1214,57 @@
             break;
         }
 
+        int size, consumed, max, payload;
+        char size_mult[3], consumed_mult[3];
+        size = consumed = max = payload = 0;
+        if (6 == sscanf(buffer,
+                        "events: ring buffer is %d%2s (%d%2s consumed),"
+                        " max entry is %db, max payload is %db",
+                        &size, size_mult, &consumed, consumed_mult, &max,
+                        &payload)) {
+            long full_size = size, full_consumed = consumed;
+
+            switch (size_mult[0]) {
+                case 'G':
+                    full_size *= 1024;
+                /* FALLTHRU */
+                case 'M':
+                    full_size *= 1024;
+                /* FALLTHRU */
+                case 'K':
+                    full_size *= 1024;
+                /* FALLTHRU */
+                case 'b':
+                    break;
+            }
+            switch (consumed_mult[0]) {
+                case 'G':
+                    full_consumed *= 1024;
+                /* FALLTHRU */
+                case 'M':
+                    full_consumed *= 1024;
+                /* FALLTHRU */
+                case 'K':
+                    full_consumed *= 1024;
+                /* FALLTHRU */
+                case 'b':
+                    break;
+            }
+            EXPECT_GT(full_size, full_consumed);
+            EXPECT_GT(full_size, max);
+            EXPECT_GT(max, payload);
+            EXPECT_GT(max, full_consumed);
+
+            ++minus_g;
+            continue;
+        }
+
         ++count;
 
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -927,14 +1286,17 @@
     pclose(fp);
 
     EXPECT_LE(1, count);
+    EXPECT_EQ(1, minus_g);
 
     EXPECT_EQ(1, signals);
 }
+#endif
 
-static bool get_white_black(char **list) {
-    FILE *fp;
+static bool get_white_black(char** list) {
+    FILE* fp;
+    logcat_define(ctx);
 
-    fp = popen("logcat -p 2>/dev/null", "r");
+    fp = logcat_popen(ctx, logcat_executable " -p 2>/dev/null");
     if (fp == NULL) {
         fprintf(stderr, "ERROR: logcat -p 2>/dev/null\n");
         return false;
@@ -943,12 +1305,12 @@
     char buffer[BIG_BUFFER];
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        char *hold = *list;
-        char *buf = buffer;
-	while (isspace(*buf)) {
+        char* hold = *list;
+        char* buf = buffer;
+        while (isspace(*buf)) {
             ++buf;
         }
-        char *end = buf + strlen(buf);
+        char* end = buf + strlen(buf);
         while (isspace(*--end) && (end >= buf)) {
             *end = '\0';
         }
@@ -962,28 +1324,30 @@
             asprintf(list, "%s", buf);
         }
     }
-    pclose(fp);
+    logcat_pclose(ctx, fp);
     return *list != NULL;
 }
 
-static bool set_white_black(const char *list) {
-    FILE *fp;
+static bool set_white_black(const char* list) {
+    FILE* fp;
+    logcat_define(ctx);
 
     char buffer[BIG_BUFFER];
 
-    snprintf(buffer, sizeof(buffer), "logcat -P '%s' 2>&1", list ? list : "");
-    fp = popen(buffer, "r");
+    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);
         return false;
     }
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        char *buf = buffer;
-	while (isspace(*buf)) {
+        char* buf = buffer;
+        while (isspace(*buf)) {
             ++buf;
         }
-        char *end = buf + strlen(buf);
+        char* end = buf + strlen(buf);
         while ((end > buf) && isspace(*--end)) {
             *end = '\0';
         }
@@ -991,15 +1355,15 @@
             continue;
         }
         fprintf(stderr, "%s\n", buf);
-        pclose(fp);
+        logcat_pclose(ctx, fp);
         return false;
     }
-    return pclose(fp) == 0;
+    return logcat_pclose(ctx, fp) == 0;
 }
 
 TEST(logcat, white_black_adjust) {
-    char *list = NULL;
-    char *adjust = NULL;
+    char* list = NULL;
+    char* adjust = NULL;
 
     get_white_black(&list);
 
@@ -1028,55 +1392,68 @@
 }
 
 TEST(logcat, regex) {
-    FILE *fp;
+    FILE* fp;
+    logcat_define(ctx);
     int count = 0;
 
     char buffer[BIG_BUFFER];
+#define logcat_regex_prefix ___STRING(logcat) "_test"
 
-    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d -e logcat_test_a+b", getpid());
+    snprintf(buffer, sizeof(buffer),
+             logcat_executable " --pid %d -d -e " logcat_regex_prefix "_a+b",
+             getpid());
 
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_ab"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_b"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_aaaab"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_aaaa"));
-
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
+                                          logcat_regex_prefix "_ab"));
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
+                                          logcat_regex_prefix "_b"));
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
+                                          logcat_regex_prefix "_aaaab"));
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
+                                          logcat_regex_prefix "_aaaa"));
     // Let the logs settle
     sleep(1);
 
-    ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
+    ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
     while (fgets(buffer, sizeof(buffer), fp)) {
         if (!strncmp(begin, buffer, sizeof(begin) - 1)) {
             continue;
         }
 
-        EXPECT_TRUE(strstr(buffer, "logcat_test_") != NULL);
+        EXPECT_TRUE(strstr(buffer, logcat_regex_prefix "_") != NULL);
 
         count++;
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     ASSERT_EQ(2, count);
 }
 
 TEST(logcat, maxcount) {
-    FILE *fp;
+    FILE* fp;
+    logcat_define(ctx);
     int count = 0;
 
     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"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
 
     // Let the logs settle
     sleep(1);
 
-    ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
+    ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
     while (fgets(buffer, sizeof(buffer), fp)) {
         if (!strncmp(begin, buffer, sizeof(begin) - 1)) {
@@ -1086,7 +1463,235 @@
         count++;
     }
 
-    pclose(fp);
+    logcat_pclose(ctx, fp);
 
     ASSERT_EQ(3, count);
 }
+
+static bool End_to_End(const char* tag, const char* fmt, ...)
+#if defined(__GNUC__)
+    __attribute__((__format__(printf, 2, 3)))
+#endif
+    ;
+
+static bool End_to_End(const char* tag, const char* fmt, ...) {
+    logcat_define(ctx);
+    FILE* fp = logcat_popen(ctx,
+                            "logcat"
+                            " -v brief"
+                            " -b events"
+                            " -v descriptive"
+                            " -t 100"
+                            " 2>/dev/null");
+    if (!fp) {
+        fprintf(stderr, "End_to_End: popen failed");
+        return false;
+    }
+
+    char buffer[BIG_BUFFER];
+    va_list ap;
+
+    va_start(ap, fmt);
+    vsnprintf(buffer, sizeof(buffer), fmt, ap);
+    va_end(ap);
+
+    char* str = NULL;
+    asprintf(&str, "I/%s ( %%d):%%c%s%%c", tag, buffer);
+    std::string expect(str);
+    free(str);
+
+    int count = 0;
+    pid_t pid = getpid();
+    std::string lastMatch;
+    int maxMatch = 1;
+    while (fgets(buffer, sizeof(buffer), fp)) {
+        char space;
+        char newline;
+        int p;
+        int ret = sscanf(buffer, expect.c_str(), &p, &space, &newline);
+        if ((ret == 3) && (p == pid) && (space == ' ') && (newline == '\n')) {
+            ++count;
+        } else if ((ret >= maxMatch) && (p == pid) && (count == 0)) {
+            lastMatch = buffer;
+            maxMatch = ret;
+        }
+    }
+
+    logcat_pclose(ctx, fp);
+
+    if ((count == 0) && (lastMatch.length() > 0)) {
+        // 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) {
+        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;
+}
+
+TEST(logcat, descriptive) {
+    struct tag {
+        uint32_t tagNo;
+        const char* tagStr;
+    };
+
+    {
+        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();
+        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";
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << id << (int32_t)42 << (int32_t)-1 << (int32_t)0;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr,
+                                   "[id=%s,event=42,source=-1,account=0]", id));
+        }
+
+        // Partial match to description
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << id << (int32_t)43 << (int64_t)-1 << (int32_t)0;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "[id=%s,event=43,-1,0]", id));
+        }
+
+        // Negative Test of End_to_End, ensure it is working
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << id << (int32_t)44 << (int32_t)-1 << (int64_t)0;
+            ctx.write();
+            fprintf(stderr, "Expect a \"Closest match\" message\n");
+            EXPECT_FALSE(End_to_End(
+                sync.tagStr, "[id=%s,event=44,source=-1,account=0]", id));
+        }
+    }
+
+    {
+        static const struct tag sync = { 2747, "contacts_aggregation" };
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint64_t)30 << (int32_t)2;
+            ctx.write();
+            EXPECT_TRUE(
+                End_to_End(sync.tagStr, "[aggregation time=30ms,count=2]"));
+        }
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint64_t)31570 << (int32_t)911;
+            ctx.write();
+            EXPECT_TRUE(
+                End_to_End(sync.tagStr, "[aggregation time=31.57s,count=911]"));
+        }
+    }
+
+    {
+        static const struct tag sync = { 75000, "sqlite_mem_alarm_current" };
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)512;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "current=512B"));
+        }
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)3072;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "current=3KB"));
+        }
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)2097152;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "current=2MB"));
+        }
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)2097153;
+            ctx.write();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "current=2097153B"));
+        }
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)1073741824;
+            ctx.write();
+            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();
+            EXPECT_TRUE(End_to_End(sync.tagStr, "current=-1GB"));
+        }
+    }
+
+    {
+        static const struct tag sync = { 27501, "notification_panel_hidden" };
+        android_log_event_list ctx(sync.tagNo);
+        ctx.write();
+        EXPECT_TRUE(End_to_End(sync.tagStr, ""));
+    }
+}
+
+static bool reportedSecurity(const char* command) {
+    logcat_define(ctx);
+    FILE* fp = logcat_popen(ctx, command);
+    if (!fp) return true;
+
+    std::string ret;
+    bool val = android::base::ReadFdToString(fileno(fp), &ret);
+    logcat_pclose(ctx, fp);
+
+    if (!val) return true;
+    return std::string::npos != ret.find("'security'");
+}
+
+TEST(logcat, security) {
+    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/logcat/tests/logcatd_test.cpp b/logcat/tests/logcatd_test.cpp
new file mode 100644
index 0000000..bb7534e
--- /dev/null
+++ b/logcat/tests/logcatd_test.cpp
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define logcat logcatd
+#define logcat_executable "logcatd"
+
+#include "logcat_test.cpp"
diff --git a/logd/.clang-format b/logd/.clang-format
new file mode 100644
index 0000000..393c309
--- /dev/null
+++ b/logd/.clang-format
@@ -0,0 +1,11 @@
+BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: false
+
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 4
+PointerAlignment: Left
+TabWidth: 4
+PenaltyExcessCharacter: 32
+
+Cpp11BracedListStyle: false
diff --git a/logd/Android.mk b/logd/Android.mk
index feca8d5..9211037 100644
--- a/logd/Android.mk
+++ b/logd/Android.mk
@@ -21,6 +21,7 @@
     libaudit.c \
     LogAudit.cpp \
     LogKlog.cpp \
+    LogTags.cpp \
     event.logtags
 
 LOCAL_SHARED_LIBRARIES := \
@@ -28,7 +29,8 @@
     liblog \
     libcutils \
     libbase \
-    libpackagelistparser
+    libpackagelistparser \
+    libcap
 
 # This is what we want to do:
 #  event_logtags = $(shell \
@@ -37,11 +39,23 @@
 #        $(LOCAL_PATH)/$2/event.logtags)
 #  event_flag := $(call event_logtags,auditd)
 #  event_flag += $(call event_logtags,logd)
+#  event_flag += $(call event_logtags,tag_def)
 # so make sure we do not regret hard-coding it as follows:
-event_flag := -DAUDITD_LOG_TAG=1003 -DLOGD_LOG_TAG=1004
+event_flag := -DAUDITD_LOG_TAG=1003 -DCHATTY_LOG_TAG=1004 -DTAG_DEF_LOG_TAG=1005
+event_flag += -DLIBLOG_LOG_TAG=1006
 
 LOCAL_CFLAGS := -Werror $(event_flag)
 
 include $(BUILD_EXECUTABLE)
 
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := logtagd.rc
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_TAGS := debug
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/init
+
+include $(BUILD_PREBUILT)
+
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/logd/CommandListener.cpp b/logd/CommandListener.cpp
index 7394f11..06c0ab5 100644
--- a/logd/CommandListener.cpp
+++ b/logd/CommandListener.cpp
@@ -15,12 +15,13 @@
  */
 
 #include <arpa/inet.h>
+#include <ctype.h>
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <netinet/in.h>
-#include <string.h>
 #include <stdlib.h>
+#include <string.h>
 #include <sys/prctl.h>
 #include <sys/socket.h>
 #include <sys/types.h>
@@ -36,9 +37,9 @@
 #include "LogCommand.h"
 #include "LogUtils.h"
 
-CommandListener::CommandListener(LogBuffer *buf, LogReader * /*reader*/,
-                                 LogListener * /*swl*/) :
-        FrameworkListener(getLogSocket()) {
+CommandListener::CommandListener(LogBuffer* buf, LogReader* /*reader*/,
+                                 LogListener* /*swl*/)
+    : FrameworkListener(getLogSocket()) {
     // registerCmd(new ShutdownCmd(buf, writer, swl));
     registerCmd(new ClearCmd(buf));
     registerCmd(new GetBufSizeCmd(buf));
@@ -47,27 +48,24 @@
     registerCmd(new GetStatisticsCmd(buf));
     registerCmd(new SetPruneListCmd(buf));
     registerCmd(new GetPruneListCmd(buf));
+    registerCmd(new GetEventTagCmd(buf));
     registerCmd(new ReinitCmd());
+    registerCmd(new ExitCmd(this));
 }
 
-CommandListener::ShutdownCmd::ShutdownCmd(LogReader *reader,
-                                          LogListener *swl) :
-        LogCommand("shutdown"),
-        mReader(*reader),
-        mSwl(*swl) {
+CommandListener::ShutdownCmd::ShutdownCmd(LogReader* reader, LogListener* swl)
+    : LogCommand("shutdown"), mReader(*reader), mSwl(*swl) {
 }
 
-int CommandListener::ShutdownCmd::runCommand(SocketClient * /*cli*/,
-                                             int /*argc*/,
-                                             char ** /*argv*/) {
+int CommandListener::ShutdownCmd::runCommand(SocketClient* /*cli*/,
+                                             int /*argc*/, char** /*argv*/) {
     mSwl.stopListener();
     mReader.stopListener();
     exit(0);
 }
 
-CommandListener::ClearCmd::ClearCmd(LogBuffer *buf) :
-        LogCommand("clear"),
-        mBuf(*buf) {
+CommandListener::ClearCmd::ClearCmd(LogBuffer* buf)
+    : LogCommand("clear"), mBuf(*buf) {
 }
 
 static void setname() {
@@ -78,8 +76,8 @@
     }
 }
 
-int CommandListener::ClearCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::ClearCmd::runCommand(SocketClient* cli, int argc,
+                                          char** argv) {
     setname();
     uid_t uid = cli->getUid();
     if (clientHasLogCredentials(cli)) {
@@ -97,17 +95,16 @@
         return 0;
     }
 
-    cli->sendMsg(mBuf.clear((log_id_t) id, uid) ? "busy" : "success");
+    cli->sendMsg(mBuf.clear((log_id_t)id, uid) ? "busy" : "success");
     return 0;
 }
 
-CommandListener::GetBufSizeCmd::GetBufSizeCmd(LogBuffer *buf) :
-        LogCommand("getLogSize"),
-        mBuf(*buf) {
+CommandListener::GetBufSizeCmd::GetBufSizeCmd(LogBuffer* buf)
+    : LogCommand("getLogSize"), mBuf(*buf) {
 }
 
-int CommandListener::GetBufSizeCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::GetBufSizeCmd::runCommand(SocketClient* cli, int argc,
+                                               char** argv) {
     setname();
     if (argc < 2) {
         cli->sendMsg("Missing Argument");
@@ -120,20 +117,19 @@
         return 0;
     }
 
-    unsigned long size = mBuf.getSize((log_id_t) id);
+    unsigned long size = mBuf.getSize((log_id_t)id);
     char buf[512];
     snprintf(buf, sizeof(buf), "%lu", size);
     cli->sendMsg(buf);
     return 0;
 }
 
-CommandListener::SetBufSizeCmd::SetBufSizeCmd(LogBuffer *buf) :
-        LogCommand("setLogSize"),
-        mBuf(*buf) {
+CommandListener::SetBufSizeCmd::SetBufSizeCmd(LogBuffer* buf)
+    : LogCommand("setLogSize"), mBuf(*buf) {
 }
 
-int CommandListener::SetBufSizeCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::SetBufSizeCmd::runCommand(SocketClient* cli, int argc,
+                                               char** argv) {
     setname();
     if (!clientHasLogCredentials(cli)) {
         cli->sendMsg("Permission Denied");
@@ -152,7 +148,7 @@
     }
 
     unsigned long size = atol(argv[2]);
-    if (mBuf.setSize((log_id_t) id, size)) {
+    if (mBuf.setSize((log_id_t)id, size)) {
         cli->sendMsg("Range Error");
         return 0;
     }
@@ -161,13 +157,12 @@
     return 0;
 }
 
-CommandListener::GetBufSizeUsedCmd::GetBufSizeUsedCmd(LogBuffer *buf) :
-        LogCommand("getLogSizeUsed"),
-        mBuf(*buf) {
+CommandListener::GetBufSizeUsedCmd::GetBufSizeUsedCmd(LogBuffer* buf)
+    : LogCommand("getLogSizeUsed"), mBuf(*buf) {
 }
 
-int CommandListener::GetBufSizeUsedCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::GetBufSizeUsedCmd::runCommand(SocketClient* cli, int argc,
+                                                   char** argv) {
     setname();
     if (argc < 2) {
         cli->sendMsg("Missing Argument");
@@ -180,29 +175,29 @@
         return 0;
     }
 
-    unsigned long size = mBuf.getSizeUsed((log_id_t) id);
+    unsigned long size = mBuf.getSizeUsed((log_id_t)id);
     char buf[512];
     snprintf(buf, sizeof(buf), "%lu", size);
     cli->sendMsg(buf);
     return 0;
 }
 
-CommandListener::GetStatisticsCmd::GetStatisticsCmd(LogBuffer *buf) :
-        LogCommand("getStatistics"),
-        mBuf(*buf) {
+CommandListener::GetStatisticsCmd::GetStatisticsCmd(LogBuffer* buf)
+    : LogCommand("getStatistics"), mBuf(*buf) {
 }
 
-static std::string package_string(const std::string &str) {
+static std::string package_string(const std::string& str) {
     // Calculate total buffer size prefix, count is the string length w/o nul
     char fmt[32];
-    for(size_t l = str.length(), y = 0, x = 6; y != x; y = x, x = strlen(fmt) - 2) {
+    for (size_t l = str.length(), y = 0, x = 6; y != x;
+         y = x, x = strlen(fmt) - 2) {
         snprintf(fmt, sizeof(fmt), "%zu\n%%s\n\f", l + x);
     }
     return android::base::StringPrintf(fmt, str.c_str());
 }
 
-int CommandListener::GetStatisticsCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::GetStatisticsCmd::runCommand(SocketClient* cli, int argc,
+                                                  char** argv) {
     setname();
     uid_t uid = cli->getUid();
     if (clientHasLogCredentials(cli)) {
@@ -233,30 +228,28 @@
         }
     }
 
-    cli->sendMsg(package_string(mBuf.formatStatistics(uid, pid,
-                                                      logMask)).c_str());
+    cli->sendMsg(
+        package_string(mBuf.formatStatistics(uid, pid, logMask)).c_str());
     return 0;
 }
 
-CommandListener::GetPruneListCmd::GetPruneListCmd(LogBuffer *buf) :
-        LogCommand("getPruneList"),
-        mBuf(*buf) {
+CommandListener::GetPruneListCmd::GetPruneListCmd(LogBuffer* buf)
+    : LogCommand("getPruneList"), mBuf(*buf) {
 }
 
-int CommandListener::GetPruneListCmd::runCommand(SocketClient *cli,
-                                         int /*argc*/, char ** /*argv*/) {
+int CommandListener::GetPruneListCmd::runCommand(SocketClient* cli,
+                                                 int /*argc*/, char** /*argv*/) {
     setname();
     cli->sendMsg(package_string(mBuf.formatPrune()).c_str());
     return 0;
 }
 
-CommandListener::SetPruneListCmd::SetPruneListCmd(LogBuffer *buf) :
-        LogCommand("setPruneList"),
-        mBuf(*buf) {
+CommandListener::SetPruneListCmd::SetPruneListCmd(LogBuffer* buf)
+    : LogCommand("setPruneList"), mBuf(*buf) {
 }
 
-int CommandListener::SetPruneListCmd::runCommand(SocketClient *cli,
-                                         int argc, char **argv) {
+int CommandListener::SetPruneListCmd::runCommand(SocketClient* cli, int argc,
+                                                 char** argv) {
     setname();
     if (!clientHasLogCredentials(cli)) {
         cli->sendMsg("Permission Denied");
@@ -283,11 +276,61 @@
     return 0;
 }
 
+CommandListener::GetEventTagCmd::GetEventTagCmd(LogBuffer* buf)
+    : LogCommand("getEventTag"), mBuf(*buf) {
+}
+
+int CommandListener::GetEventTagCmd::runCommand(SocketClient* cli, int argc,
+                                                char** argv) {
+    setname();
+    uid_t uid = cli->getUid();
+    if (clientHasLogCredentials(cli)) {
+        uid = AID_ROOT;
+    }
+
+    const char* name = NULL;
+    const char* format = NULL;
+    const char* id = NULL;
+    for (int i = 1; i < argc; ++i) {
+        static const char _name[] = "name=";
+        if (!strncmp(argv[i], _name, strlen(_name))) {
+            name = argv[i] + strlen(_name);
+            continue;
+        }
+
+        static const char _format[] = "format=";
+        if (!strncmp(argv[i], _format, strlen(_format))) {
+            format = argv[i] + strlen(_format);
+            continue;
+        }
+
+        static const char _id[] = "id=";
+        if (!strncmp(argv[i], _id, strlen(_id))) {
+            id = argv[i] + strlen(_id);
+            continue;
+        }
+    }
+
+    if (id) {
+        if (format || name) {
+            cli->sendMsg("can not mix id= with either format= or name=");
+            return 0;
+        }
+        cli->sendMsg(package_string(mBuf.formatEntry(atoi(id), uid)).c_str());
+        return 0;
+    }
+
+    cli->sendMsg(
+        package_string(mBuf.formatGetEventTag(uid, name, format)).c_str());
+
+    return 0;
+}
+
 CommandListener::ReinitCmd::ReinitCmd() : LogCommand("reinit") {
 }
 
-int CommandListener::ReinitCmd::runCommand(SocketClient *cli,
-                                         int /*argc*/, char ** /*argv*/) {
+int CommandListener::ReinitCmd::runCommand(SocketClient* cli, int /*argc*/,
+                                           char** /*argv*/) {
     setname();
 
     reinit_signal_handler(SIGHUP);
@@ -297,14 +340,27 @@
     return 0;
 }
 
+CommandListener::ExitCmd::ExitCmd(CommandListener* parent)
+    : LogCommand("EXIT"), mParent(*parent) {
+}
+
+int CommandListener::ExitCmd::runCommand(SocketClient* cli, int /*argc*/,
+                                         char** /*argv*/) {
+    setname();
+
+    cli->sendMsg("success");
+    release(cli);
+
+    return 0;
+}
+
 int CommandListener::getLogSocket() {
     static const char socketName[] = "logd";
     int sock = android_get_control_socket(socketName);
 
     if (sock < 0) {
-        sock = socket_local_server(socketName,
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                   SOCK_STREAM);
+        sock = socket_local_server(
+            socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
     }
 
     return sock;
diff --git a/logd/CommandListener.h b/logd/CommandListener.h
index 3877675..ed99419 100644
--- a/logd/CommandListener.h
+++ b/logd/CommandListener.h
@@ -18,57 +18,81 @@
 #define _COMMANDLISTENER_H__
 
 #include <sysutils/FrameworkListener.h>
-#include "LogCommand.h"
 #include "LogBuffer.h"
-#include "LogReader.h"
+#include "LogCommand.h"
 #include "LogListener.h"
+#include "LogReader.h"
 
 // See main.cpp for implementation
 void reinit_signal_handler(int /*signal*/);
 
 class CommandListener : public FrameworkListener {
+   public:
+    CommandListener(LogBuffer* buf, LogReader* reader, LogListener* swl);
+    virtual ~CommandListener() {
+    }
 
-public:
-    CommandListener(LogBuffer *buf, LogReader *reader, LogListener *swl);
-    virtual ~CommandListener() {}
-
-private:
+   private:
     static int getLogSocket();
 
     class ShutdownCmd : public LogCommand {
-        LogReader &mReader;
-        LogListener &mSwl;
+        LogReader& mReader;
+        LogListener& mSwl;
 
-    public:
-        ShutdownCmd(LogReader *reader, LogListener *swl);
-        virtual ~ShutdownCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
+       public:
+        ShutdownCmd(LogReader* reader, LogListener* swl);
+        virtual ~ShutdownCmd() {
+        }
+        int runCommand(SocketClient* c, int argc, char** argv);
     };
 
-#define LogBufferCmd(name)                                       \
-    class name##Cmd : public LogCommand {                        \
-        LogBuffer &mBuf;                                         \
-    public:                                                      \
-        name##Cmd(LogBuffer *buf);                               \
-        virtual ~name##Cmd() {}                                  \
-        int runCommand(SocketClient *c, int argc, char ** argv); \
-    };
+#define LogBufferCmd(name)                                      \
+    class name##Cmd : public LogCommand {                       \
+        LogBuffer& mBuf;                                        \
+                                                                \
+       public:                                                  \
+        explicit name##Cmd(LogBuffer* buf);                     \
+        virtual ~name##Cmd() {                                  \
+        }                                                       \
+        int runCommand(SocketClient* c, int argc, char** argv); \
+    }
 
-    LogBufferCmd(Clear)
-    LogBufferCmd(GetBufSize)
-    LogBufferCmd(SetBufSize)
-    LogBufferCmd(GetBufSizeUsed)
-    LogBufferCmd(GetStatistics)
-    LogBufferCmd(GetPruneList)
-    LogBufferCmd(SetPruneList)
+    LogBufferCmd(Clear);
+    LogBufferCmd(GetBufSize);
+    LogBufferCmd(SetBufSize);
+    LogBufferCmd(GetBufSizeUsed);
+    LogBufferCmd(GetStatistics);
+    LogBufferCmd(GetPruneList);
+    LogBufferCmd(SetPruneList);
+    LogBufferCmd(GetEventTag);
 
-    class ReinitCmd : public LogCommand {
-    public:
-        ReinitCmd();
-        virtual ~ReinitCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
+#define LogCmd(name)                                            \
+    class name##Cmd : public LogCommand {                       \
+       public:                                                  \
+        name##Cmd();                                            \
+        virtual ~name##Cmd() {                                  \
+        }                                                       \
+        int runCommand(SocketClient* c, int argc, char** argv); \
+    }
 
+    LogCmd(Reinit);
+
+#define LogParentCmd(name)                                      \
+    class name##Cmd : public LogCommand {                       \
+        CommandListener& mParent;                               \
+                                                                \
+       public:                                                  \
+        name##Cmd();                                            \
+        explicit name##Cmd(CommandListener* parent);            \
+        virtual ~name##Cmd() {                                  \
+        }                                                       \
+        int runCommand(SocketClient* c, int argc, char** argv); \
+        void release(SocketClient* c) {                         \
+            mParent.release(c);                                 \
+        }                                                       \
+    }
+
+    LogParentCmd(Exit);
 };
 
 #endif
diff --git a/logd/FlushCommand.cpp b/logd/FlushCommand.cpp
index 6a26d00..c67d2bf 100644
--- a/logd/FlushCommand.cpp
+++ b/logd/FlushCommand.cpp
@@ -26,20 +26,16 @@
 #include "LogTimes.h"
 #include "LogUtils.h"
 
-FlushCommand::FlushCommand(LogReader &reader,
-                           bool nonBlock,
-                           unsigned long tail,
-                           unsigned int logMask,
-                           pid_t pid,
-                           uint64_t start,
-                           uint64_t timeout) :
-        mReader(reader),
-        mNonBlock(nonBlock),
-        mTail(tail),
-        mLogMask(logMask),
-        mPid(pid),
-        mStart(start),
-        mTimeout((start > 1) ? timeout : 0) {
+FlushCommand::FlushCommand(LogReader& reader, bool nonBlock, unsigned long tail,
+                           unsigned int logMask, pid_t pid, log_time start,
+                           uint64_t timeout)
+    : mReader(reader),
+      mNonBlock(nonBlock),
+      mTail(tail),
+      mLogMask(logMask),
+      mPid(pid),
+      mStart(start),
+      mTimeout((start != log_time::EPOCH) ? timeout : 0) {
 }
 
 // runSocketCommand is called once for every open client on the
@@ -51,18 +47,28 @@
 // global LogTimeEntry::lock() 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;
+void FlushCommand::runSocketCommand(SocketClient* client) {
+    LogTimeEntry* entry = NULL;
+    LastLogTimes& times = mReader.logbuf().mTimes;
 
     LogTimeEntry::lock();
     LastLogTimes::iterator it = times.begin();
-    while(it != times.end()) {
+    while (it != times.end()) {
         entry = (*it);
         if (entry->mClient == client) {
             if (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec) {
-                LogTimeEntry::unlock();
-                return;
+                if (mReader.logbuf().isMonotonic()) {
+                    LogTimeEntry::unlock();
+                    return;
+                }
+                // If the user changes the time in a gross manner that
+                // invalidates the timeout, fall through and trigger.
+                log_time now(CLOCK_REALTIME);
+                if (((entry->mEnd + entry->mTimeout) > now) &&
+                    (now > entry->mEnd)) {
+                    LogTimeEntry::unlock();
+                    return;
+                }
             }
             entry->triggerReader_Locked();
             if (entry->runningReader_Locked()) {
@@ -77,7 +83,7 @@
 
     if (it == times.end()) {
         // Create LogTimeEntry in notifyNewLog() ?
-        if (mTail == (unsigned long) -1) {
+        if (mTail == (unsigned long)-1) {
             LogTimeEntry::unlock();
             return;
         }
@@ -93,14 +99,14 @@
     LogTimeEntry::unlock();
 }
 
-bool FlushCommand::hasReadLogs(SocketClient *client) {
+bool FlushCommand::hasReadLogs(SocketClient* client) {
     return clientHasLogCredentials(client);
 }
 
-static bool clientHasSecurityCredentials(SocketClient *client) {
+static bool clientHasSecurityCredentials(SocketClient* client) {
     return (client->getUid() == AID_SYSTEM) || (client->getGid() == AID_SYSTEM);
 }
 
-bool FlushCommand::hasSecurityLogs(SocketClient *client) {
+bool FlushCommand::hasSecurityLogs(SocketClient* client) {
     return clientHasSecurityCredentials(client);
 }
diff --git a/logd/FlushCommand.h b/logd/FlushCommand.h
index 9224773..7cdd03f 100644
--- a/logd/FlushCommand.h
+++ b/logd/FlushCommand.h
@@ -16,7 +16,7 @@
 #ifndef _FLUSH_COMMAND_H
 #define _FLUSH_COMMAND_H
 
-#include <log/log_read.h>
+#include <private/android_logger.h>
 #include <sysutils/SocketClientCommand.h>
 
 class LogBufferElement;
@@ -26,26 +26,23 @@
 class LogReader;
 
 class FlushCommand : public SocketClientCommand {
-    LogReader &mReader;
+    LogReader& mReader;
     bool mNonBlock;
     unsigned long mTail;
     unsigned int mLogMask;
     pid_t mPid;
-    uint64_t mStart;
+    log_time mStart;
     uint64_t mTimeout;
 
-public:
-    FlushCommand(LogReader &mReader,
-                 bool nonBlock = false,
-                 unsigned long tail = -1,
-                 unsigned int logMask = -1,
-                 pid_t pid = 0,
-                 uint64_t start = 1,
-                 uint64_t timeout = 0);
-    virtual void runSocketCommand(SocketClient *client);
+   public:
+    explicit FlushCommand(LogReader& mReader, bool nonBlock = false,
+                          unsigned long tail = -1, unsigned int logMask = -1,
+                          pid_t pid = 0, log_time start = log_time::EPOCH,
+                          uint64_t timeout = 0);
+    virtual void runSocketCommand(SocketClient* client);
 
-    static bool hasReadLogs(SocketClient *client);
-    static bool hasSecurityLogs(SocketClient *client);
+    static bool hasReadLogs(SocketClient* client);
+    static bool hasSecurityLogs(SocketClient* client);
 };
 
 #endif
diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp
index 24c3f52..2d9024a 100644
--- a/logd/LogAudit.cpp
+++ b/logd/LogAudit.cpp
@@ -25,40 +25,103 @@
 #include <sys/uio.h>
 #include <syslog.h>
 
-#include <log/logger.h>
+#include <android-base/macros.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
-#include "libaudit.h"
 #include "LogAudit.h"
 #include "LogBuffer.h"
 #include "LogKlog.h"
 #include "LogReader.h"
+#include "LogUtils.h"
+#include "libaudit.h"
 
-#define KMSG_PRIORITY(PRI)                          \
-    '<',                                            \
-    '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) / 10, \
-    '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, \
-    '>'
+#define KMSG_PRIORITY(PRI)                               \
+    '<', '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) / 10, \
+        '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, '>'
 
-LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg) :
-        SocketListener(getLogSocket(), false),
-        logbuf(buf),
-        reader(reader),
-        fdDmesg(fdDmesg),
-        initialized(false) {
+LogAudit::LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg)
+    : SocketListener(mSock = getLogSocket(), false),
+      logbuf(buf),
+      reader(reader),
+      fdDmesg(fdDmesg),
+      main(__android_logger_property_get_bool("ro.logd.auditd.main",
+                                              BOOL_DEFAULT_TRUE)),
+      events(__android_logger_property_get_bool("ro.logd.auditd.events",
+                                                BOOL_DEFAULT_TRUE)),
+      initialized(false),
+      tooFast(false) {
     static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO),
-        'l', 'o', 'g', 'd', '.', 'a', 'u', 'd', 'i', 't', 'd', ':',
-        ' ', 's', 't', 'a', 'r', 't', '\n' };
+                                           'l',
+                                           'o',
+                                           'g',
+                                           'd',
+                                           '.',
+                                           'a',
+                                           'u',
+                                           'd',
+                                           'i',
+                                           't',
+                                           'd',
+                                           ':',
+                                           ' ',
+                                           's',
+                                           't',
+                                           'a',
+                                           'r',
+                                           't',
+                                           '\n' };
     write(fdDmesg, auditd_message, sizeof(auditd_message));
 }
 
-bool LogAudit::onDataAvailable(SocketClient *cli) {
+void LogAudit::checkRateLimit() {
+    // trim list for AUDIT_RATE_LIMIT_BURST_DURATION of history
+    log_time oldest(AUDIT_RATE_LIMIT_BURST_DURATION, 0);
+    bucket.emplace(android_log_clockid());
+    oldest = bucket.back() - oldest;
+    while (bucket.front() < oldest) bucket.pop();
+
+    static const size_t upperThreshold =
+        ((AUDIT_RATE_LIMIT_BURST_DURATION *
+          (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
+         1) /
+        2;
+    if (bucket.size() >= upperThreshold) {
+        // Hit peak, slow down source
+        if (!tooFast) {
+            tooFast = true;
+            audit_rate_limit(mSock, AUDIT_RATE_LIMIT_MAX);
+        }
+
+        // We do not need to hold on to the full set of timing data history,
+        // let's ensure it does not grow without bounds.  This also ensures
+        // that std::dequeue underneath behaves almost like a ring buffer.
+        do {
+            bucket.pop();
+        } while (bucket.size() >= upperThreshold);
+        return;
+    }
+
+    if (!tooFast) return;
+
+    static const size_t lowerThreshold =
+        AUDIT_RATE_LIMIT_BURST_DURATION * AUDIT_RATE_LIMIT_MAX;
+
+    if (bucket.size() >= lowerThreshold) return;
+
+    tooFast = false;
+    // Went below max sustained rate, allow source to speed up
+    audit_rate_limit(mSock, AUDIT_RATE_LIMIT_DEFAULT);
+}
+
+bool LogAudit::onDataAvailable(SocketClient* cli) {
     if (!initialized) {
         prctl(PR_SET_NAME, "logd.auditd");
         initialized = true;
     }
 
+    checkRateLimit();
+
     struct audit_message rep;
 
     rep.nlh.nlmsg_type = 0;
@@ -70,20 +133,19 @@
         return false;
     }
 
-    logPrint("type=%d %.*s",
-        rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data);
+    logPrint("type=%d %.*s", rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data);
 
     return true;
 }
 
-int LogAudit::logPrint(const char *fmt, ...) {
+int LogAudit::logPrint(const char* fmt, ...) {
     if (fmt == NULL) {
         return -EINVAL;
     }
 
     va_list args;
 
-    char *str = NULL;
+    char* str = NULL;
     va_start(args, fmt);
     int rc = vasprintf(&str, fmt, args);
     va_end(args);
@@ -92,7 +154,14 @@
         return rc;
     }
 
-    char *cp;
+    char* cp;
+    // Work around kernels missing
+    // https://github.com/torvalds/linux/commit/b8f89caafeb55fba75b74bea25adc4e4cd91be67
+    // Such kernels improperly add newlines inside audit messages.
+    while ((cp = strchr(str, '\n'))) {
+        *cp = ' ';
+    }
+
     while ((cp = strstr(str, "  "))) {
         memmove(cp, cp + 1, strlen(cp + 1) + 1);
     }
@@ -102,16 +171,73 @@
         struct iovec iov[3];
         static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) };
         static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) };
+        static const char newline[] = "\n";
 
-        iov[0].iov_base = info ? const_cast<char *>(log_info)
-                               : const_cast<char *>(log_warning);
-        iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning);
-        iov[1].iov_base = str;
-        iov[1].iov_len = strlen(str);
-        iov[2].iov_base = const_cast<char *>("\n");
-        iov[2].iov_len = 1;
+        // Dedupe messages, checking for identical messages starting with avc:
+        static unsigned count;
+        static char* last_str;
+        static bool last_info;
 
-        writev(fdDmesg, iov, sizeof(iov) / sizeof(iov[0]));
+        if (last_str != NULL) {
+            static const char avc[] = "): avc: ";
+            char* avcl = strstr(last_str, avc);
+            bool skip = false;
+
+            if (avcl) {
+                char* avcr = strstr(str, avc);
+
+                skip = avcr &&
+                       !fastcmp<strcmp>(avcl + strlen(avc), avcr + strlen(avc));
+                if (skip) {
+                    ++count;
+                    free(last_str);
+                    last_str = strdup(str);
+                    last_info = info;
+                }
+            }
+            if (!skip) {
+                static const char resume[] = " duplicate messages suppressed\n";
+
+                iov[0].iov_base = last_info ? const_cast<char*>(log_info)
+                                            : const_cast<char*>(log_warning);
+                iov[0].iov_len =
+                    last_info ? sizeof(log_info) : sizeof(log_warning);
+                iov[1].iov_base = last_str;
+                iov[1].iov_len = strlen(last_str);
+                if (count > 1) {
+                    iov[2].iov_base = const_cast<char*>(resume);
+                    iov[2].iov_len = strlen(resume);
+                } else {
+                    iov[2].iov_base = const_cast<char*>(newline);
+                    iov[2].iov_len = strlen(newline);
+                }
+
+                writev(fdDmesg, iov, arraysize(iov));
+                free(last_str);
+                last_str = NULL;
+            }
+        }
+        if (last_str == NULL) {
+            count = 0;
+            last_str = strdup(str);
+            last_info = info;
+        }
+        if (count == 0) {
+            iov[0].iov_base = info ? const_cast<char*>(log_info)
+                                   : const_cast<char*>(log_warning);
+            iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning);
+            iov[1].iov_base = str;
+            iov[1].iov_len = strlen(str);
+            iov[2].iov_base = const_cast<char*>(newline);
+            iov[2].iov_len = strlen(newline);
+
+            writev(fdDmesg, iov, arraysize(iov));
+        }
+    }
+
+    if (!main && !events) {
+        free(str);
+        return 0;
     }
 
     pid_t pid = getpid();
@@ -120,10 +246,10 @@
     log_time now;
 
     static const char audit_str[] = " audit(";
-    char *timeptr = strstr(str, audit_str);
-    if (timeptr
-            && ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q")))
-            && (*cp == ':')) {
+    char* timeptr = strstr(str, audit_str);
+    if (timeptr &&
+        ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) &&
+        (*cp == ':')) {
         memcpy(timeptr + sizeof(audit_str) - 1, "0.0", 3);
         memmove(timeptr + sizeof(audit_str) - 1 + 3, cp, strlen(cp) + 1);
         if (!isMonotonic()) {
@@ -142,7 +268,7 @@
     }
 
     static const char pid_str[] = " pid=";
-    char *pidptr = strstr(str, pid_str);
+    char* pidptr = strstr(str, pid_str);
     if (pidptr && isdigit(pidptr[sizeof(pid_str) - 1])) {
         cp = pidptr + sizeof(pid_str) - 1;
         pid = 0;
@@ -164,19 +290,19 @@
 
     bool notify = false;
 
-    {   // begin scope for event buffer
+    if (events) {  // begin scope for event buffer
         uint32_t buffer[(n + sizeof(uint32_t) - 1) / sizeof(uint32_t)];
 
-        android_log_event_string_t *event
-            = reinterpret_cast<android_log_event_string_t *>(buffer);
+        android_log_event_string_t* event =
+            reinterpret_cast<android_log_event_string_t*>(buffer);
         event->header.tag = htole32(AUDITD_LOG_TAG);
         event->type = EVENT_TYPE_STRING;
         event->length = htole32(l);
         memcpy(event->data, str, l);
 
         rc = logbuf->log(LOG_ID_EVENTS, now, uid, pid, tid,
-                         reinterpret_cast<char *>(event),
-                         (n <= USHRT_MAX) ? (unsigned short) n : USHRT_MAX);
+                         reinterpret_cast<char*>(event),
+                         (n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX);
         if (rc >= 0) {
             notify = true;
         }
@@ -186,9 +312,9 @@
     // log to main
 
     static const char comm_str[] = " comm=\"";
-    const char *comm = strstr(str, comm_str);
-    const char *estr = str + strlen(str);
-    const char *commfree = NULL;
+    const char* comm = strstr(str, comm_str);
+    const char* estr = str + strlen(str);
+    const char* commfree = NULL;
     if (comm) {
         estr = comm;
         comm += sizeof(comm_str) - 1;
@@ -204,7 +330,7 @@
         }
     }
 
-    const char *ecomm = strchr(comm, '"');
+    const char* ecomm = strchr(comm, '"');
     if (ecomm) {
         ++ecomm;
         l = ecomm - comm;
@@ -219,7 +345,7 @@
     size_t e = strnlen(ecomm, LOGGER_ENTRY_MAX_PAYLOAD - b);
     n = b + e + l + 2;
 
-    {   // begin scope for main buffer
+    if (main) {  // begin scope for main buffer
         char newstr[n];
 
         *newstr = info ? ANDROID_LOG_INFO : ANDROID_LOG_WARN;
@@ -228,7 +354,7 @@
         strncpy(newstr + 1 + l + b, ecomm, e);
 
         rc = logbuf->log(LOG_ID_MAIN, now, uid, pid, tid, newstr,
-                         (n <= USHRT_MAX) ? (unsigned short) n : USHRT_MAX);
+                         (n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX);
 
         if (rc >= 0) {
             notify = true;
@@ -236,7 +362,7 @@
         // end scope for main buffer
     }
 
-    free(const_cast<char *>(commfree));
+    free(const_cast<char*>(commfree));
     free(str);
 
     if (notify) {
@@ -249,8 +375,8 @@
     return rc;
 }
 
-int LogAudit::log(char *buf, size_t len) {
-    char *audit = strstr(buf, " audit(");
+int LogAudit::log(char* buf, size_t len) {
+    char* audit = strstr(buf, " audit(");
     if (!audit || (audit >= &buf[len])) {
         return 0;
     }
@@ -258,7 +384,7 @@
     *audit = '\0';
 
     int rc;
-    char *type = strstr(buf, "type=");
+    char* type = strstr(buf, "type=");
     if (type && (type < &buf[len])) {
         rc = logPrint("%s %s", type, audit + 1);
     } else {
@@ -277,5 +403,6 @@
         audit_close(fd);
         fd = -1;
     }
+    (void)audit_rate_limit(fd, AUDIT_RATE_LIMIT_DEFAULT);
     return fd;
 }
diff --git a/logd/LogAudit.h b/logd/LogAudit.h
index ab30e28..5947819 100644
--- a/logd/LogAudit.h
+++ b/logd/LogAudit.h
@@ -17,6 +17,8 @@
 #ifndef _LOGD_LOG_AUDIT_H__
 #define _LOGD_LOG_AUDIT_H__
 
+#include <queue>
+
 #include <sysutils/SocketListener.h>
 
 #include "LogBuffer.h"
@@ -24,23 +26,32 @@
 class LogReader;
 
 class LogAudit : public SocketListener {
-    LogBuffer *logbuf;
-    LogReader *reader;
-    int fdDmesg;
+    LogBuffer* logbuf;
+    LogReader* reader;
+    int fdDmesg;  // fdDmesg >= 0 is functionally bool dmesg
+    bool main;
+    bool events;
     bool initialized;
 
-public:
-    LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg);
-    int log(char *buf, size_t len);
-    bool isMonotonic() { return logbuf->isMonotonic(); }
+    bool tooFast;
+    int mSock;
+    std::queue<log_time> bucket;
+    void checkRateLimit();
 
-protected:
-    virtual bool onDataAvailable(SocketClient *cli);
+   public:
+    LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg);
+    int log(char* buf, size_t len);
+    bool isMonotonic() {
+        return logbuf->isMonotonic();
+    }
 
-private:
+   protected:
+    virtual bool onDataAvailable(SocketClient* cli);
+
+   private:
     static int getLogSocket();
-    int logPrint(const char *fmt, ...)
-        __attribute__ ((__format__ (__printf__, 2, 3)));
+    int logPrint(const char* fmt, ...)
+        __attribute__((__format__(__printf__, 2, 3)));
 };
 
 #endif
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 0497a89..4aa2c9f 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -13,11 +13,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+// for manual checking of stale entries during LogBuffer::erase()
+//#define DEBUG_CHECK_FOR_STALE_ENTRIES
 
 #include <ctype.h>
+#include <endian.h>
 #include <errno.h>
 #include <stdio.h>
 #include <string.h>
+#include <sys/cdefs.h>
 #include <sys/user.h>
 #include <time.h>
 #include <unistd.h>
@@ -25,114 +29,28 @@
 #include <unordered_map>
 
 #include <cutils/properties.h>
-#include <log/logger.h>
+#include <private/android_logger.h>
 
 #include "LogBuffer.h"
 #include "LogKlog.h"
 #include "LogReader.h"
+#include "LogUtils.h"
+
+#ifndef __predict_false
+#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
+#endif
 
 // Default
-#define LOG_BUFFER_SIZE (256 * 1024) // Tuned with ro.logd.size per-platform
 #define log_buffer_size(id) mMaxSize[id]
-#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
-#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
 
-static bool valid_size(unsigned long value) {
-    if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
-        return false;
-    }
-
-    long pages = sysconf(_SC_PHYS_PAGES);
-    if (pages < 1) {
-        return true;
-    }
-
-    long pagesize = sysconf(_SC_PAGESIZE);
-    if (pagesize <= 1) {
-        pagesize = PAGE_SIZE;
-    }
-
-    // maximum memory impact a somewhat arbitrary ~3%
-    pages = (pages + 31) / 32;
-    unsigned long maximum = pages * pagesize;
-
-    if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
-        return true;
-    }
-
-    return value <= maximum;
-}
-
-static unsigned long property_get_size(const char *key) {
-    char property[PROPERTY_VALUE_MAX];
-    property_get(key, property, "");
-
-    char *cp;
-    unsigned long value = strtoul(property, &cp, 10);
-
-    switch(*cp) {
-    case 'm':
-    case 'M':
-        value *= 1024;
-    /* FALLTHRU */
-    case 'k':
-    case 'K':
-        value *= 1024;
-    /* FALLTHRU */
-    case '\0':
-        break;
-
-    default:
-        value = 0;
-    }
-
-    if (!valid_size(value)) {
-        value = 0;
-    }
-
-    return value;
-}
+const log_time LogBuffer::pruneMargin(3, 0);
 
 void LogBuffer::init() {
-    static const char global_tuneable[] = "persist.logd.size"; // Settings App
-    static const char global_default[] = "ro.logd.size";       // BoardConfig.mk
-
-    unsigned long default_size = property_get_size(global_tuneable);
-    if (!default_size) {
-        default_size = property_get_size(global_default);
-        if (!default_size) {
-            default_size = property_get_bool("ro.config.low_ram",
-                                             BOOL_DEFAULT_FALSE)
-                ? LOG_BUFFER_MIN_SIZE // 64K
-                : LOG_BUFFER_SIZE;    // 256K
-        }
-    }
-
     log_id_for_each(i) {
         mLastSet[i] = false;
         mLast[i] = mLogElements.begin();
 
-        char key[PROP_NAME_MAX];
-
-        snprintf(key, sizeof(key), "%s.%s",
-                 global_tuneable, android_log_id_to_name(i));
-        unsigned long property_size = property_get_size(key);
-
-        if (!property_size) {
-            snprintf(key, sizeof(key), "%s.%s",
-                     global_default, android_log_id_to_name(i));
-            property_size = property_get_size(key);
-        }
-
-        if (!property_size) {
-            property_size = default_size;
-        }
-
-        if (!property_size) {
-            property_size = LOG_BUFFER_SIZE;
-        }
-
-        if (setSize(i, property_size)) {
+        if (setSize(i, __android_logger_get_buffer_size(i))) {
             setSize(i, LOG_BUFFER_MIN_SIZE);
         }
     }
@@ -156,8 +74,8 @@
         //
         pthread_mutex_lock(&mLogElementsLock);
         LogBufferElementCollection::iterator it = mLogElements.begin();
-        while((it != mLogElements.end())) {
-            LogBufferElement *e = *it;
+        while ((it != mLogElements.end())) {
+            LogBufferElement* e = *it;
             if (monotonic) {
                 if (!android::isMonotonic(e->mRealTime)) {
                     LogKlog::convertRealToMonotonic(e->mRealTime);
@@ -180,8 +98,8 @@
     LogTimeEntry::lock();
 
     LastLogTimes::iterator times = mTimes.begin();
-    while(times != mTimes.end()) {
-        LogTimeEntry *entry = (*times);
+    while (times != mTimes.end()) {
+        LogTimeEntry* entry = (*times);
         if (entry->owned_Locked()) {
             entry->triggerReader_Locked();
         }
@@ -191,28 +109,100 @@
     LogTimeEntry::unlock();
 }
 
-LogBuffer::LogBuffer(LastLogTimes *times):
-        monotonic(android_log_clockid() == CLOCK_MONOTONIC),
-        mTimes(*times) {
-    pthread_mutex_init(&mLogElementsLock, NULL);
+LogBuffer::LogBuffer(LastLogTimes* times)
+    : monotonic(android_log_clockid() == CLOCK_MONOTONIC), mTimes(*times) {
+    pthread_mutex_init(&mLogElementsLock, nullptr);
+
+    log_id_for_each(i) {
+        lastLoggedElements[i] = nullptr;
+        droppedElements[i] = nullptr;
+    }
 
     init();
 }
 
-int LogBuffer::log(log_id_t log_id, log_time realtime,
-                   uid_t uid, pid_t pid, pid_t tid,
-                   const char *msg, unsigned short len) {
+LogBuffer::~LogBuffer() {
+    log_id_for_each(i) {
+        delete lastLoggedElements[i];
+        delete droppedElements[i];
+    }
+}
+
+enum match_type { DIFFERENT, SAME, SAME_LIBLOG };
+
+static enum match_type identical(LogBufferElement* elem,
+                                 LogBufferElement* last) {
+    // is it mostly identical?
+    //  if (!elem) return DIFFERENT;
+    ssize_t lenl = elem->getMsgLen();
+    if (lenl <= 0) return DIFFERENT;  // value if this represents a chatty elem
+    //  if (!last) 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;
+    if (elem->getTid() != last->getTid()) return DIFFERENT;
+
+    // last is more than a minute old, stop squashing identical messages
+    if (elem->getRealTime().nsec() >
+        (last->getRealTime().nsec() + 60 * NS_PER_SEC))
+        return DIFFERENT;
+
+    // Identical message
+    const char* msgl = elem->getMsg();
+    const char* msgr = last->getMsg();
+    if (lenl == lenr) {
+        if (!fastcmp<memcmp>(msgl, msgr, lenl)) return SAME;
+        // liblog tagged messages (content gets summed)
+        if ((elem->getLogId() == LOG_ID_EVENTS) &&
+            (lenl == sizeof(android_log_event_int_t)) &&
+            !fastcmp<memcmp>(msgl, msgr, sizeof(android_log_event_int_t) -
+                                             sizeof(int32_t)) &&
+            (elem->getTag() == LIBLOG_LOG_TAG)) {
+            return SAME_LIBLOG;
+        }
+    }
+
+    // audit message (except sequence number) identical?
+    if (last->isBinary()) {
+        if (fastcmp<memcmp>(msgl, msgr, sizeof(android_log_event_string_t) -
+                                            sizeof(int32_t))) {
+            return DIFFERENT;
+        }
+        msgl += sizeof(android_log_event_string_t);
+        lenl -= sizeof(android_log_event_string_t);
+        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;
+    const char* avcr = android::strnstr(msgr, lenr, avc);
+    if (!avcr) return DIFFERENT;
+    lenr -= avcr - msgr;
+    if (lenl != lenr) return DIFFERENT;
+    if (fastcmp<memcmp>(avcl + strlen(avc), avcr + strlen(avc),
+                        lenl - strlen(avc))) {
+        return DIFFERENT;
+    }
+    return SAME;
+}
+
+int LogBuffer::log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid,
+                   pid_t tid, const char* msg, unsigned short len) {
     if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
         return -EINVAL;
     }
 
-    LogBufferElement *elem = new LogBufferElement(log_id, realtime,
-                                                  uid, pid, tid, msg, len);
+    LogBufferElement* elem =
+        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 = android::tagToName(elem->getTag());
+            tag = tagToName(elem->getTag());
         } else {
             prio = *msg;
             tag = msg + 1;
@@ -229,36 +219,187 @@
     }
 
     pthread_mutex_lock(&mLogElementsLock);
+    LogBufferElement* currentLast = lastLoggedElements[log_id];
+    if (currentLast) {
+        LogBufferElement* dropped = droppedElements[log_id];
+        unsigned short count = dropped ? dropped->getDropped() : 0;
+        //
+        // State Init
+        //     incoming:
+        //         dropped = nullptr
+        //         currentLast = nullptr;
+        //         elem = incoming message
+        //     outgoing:
+        //         dropped = nullptr -> State 0
+        //         currentLast = copy of elem
+        //         log elem
+        // State 0
+        //     incoming:
+        //         count = 0
+        //         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 = nullptr -> State 0
+        //         delete copy of last message (incoming currentLast)
+        //         currentLast = copy of elem
+        //         log elem
+        // State 1
+        //     incoming:
+        //         count = 0
+        //         dropped = copy of first identical message
+        //         currentLast = reference to last held-back incoming
+        //                       message
+        //         elem = incoming message
+        //     outgoing: if match == SAME
+        //         delete copy of first identical message (dropped)
+        //         dropped = reference to last held-back incoming
+        //                   message set to chatty count of 1 -> State 2
+        //         currentLast = reference to elem
+        //     outgoing: if match == SAME_LIBLOG
+        //         dropped = copy of first identical message -> State 1
+        //         take sum of currentLast and elem
+        //         if sum overflows:
+        //             log currentLast
+        //             currentLast = reference to elem
+        //         else
+        //             delete currentLast
+        //             currentLast = reference to elem, sum liblog.
+        //     break: if match == DIFFERENT
+        //         delete dropped
+        //         dropped = nullptr -> State 0
+        //         log reference to last held-back (currentLast)
+        //         currentLast = copy of elem
+        //         log elem
+        // State 2
+        //     incoming:
+        //         count = chatty count
+        //         dropped = chatty message holding count
+        //         currentLast = reference to last held-back incoming
+        //                       message.
+        //         dropped = chatty message holding count
+        //         elem = incoming message
+        //     outgoing: if match != DIFFERENT
+        //         delete chatty message holding count
+        //         dropped = reference to last held-back incoming
+        //                   message, set to chatty count + 1
+        //         currentLast = reference to elem
+        //     break: if match == DIFFERENT
+        //         log dropped (chatty message)
+        //         dropped = nullptr -> State 0
+        //         log reference to last held-back (currentLast)
+        //         currentLast = copy of elem
+        //         log elem
+        //
+        enum match_type match = identical(elem, currentLast);
+        if (match != DIFFERENT) {
+            if (dropped) {
+                // Sum up liblog tag messages?
+                if ((count == 0) /* at Pass 1 */ && (match == SAME_LIBLOG)) {
+                    android_log_event_int_t* event =
+                        reinterpret_cast<android_log_event_int_t*>(
+                            const_cast<char*>(currentLast->getMsg()));
+                    //
+                    // To unit test, differentiate with something like:
+                    //    event->header.tag = htole32(CHATTY_LOG_TAG);
+                    // here, then instead of delete currentLast below,
+                    // log(currentLast) to see the incremental sums form.
+                    //
+                    uint32_t swab = event->payload.data;
+                    unsigned long long total = htole32(swab);
+                    event = reinterpret_cast<android_log_event_int_t*>(
+                        const_cast<char*>(elem->getMsg()));
+                    swab = event->payload.data;
 
+                    lastLoggedElements[LOG_ID_EVENTS] = elem;
+                    total += htole32(swab);
+                    // check for overflow
+                    if (total >= UINT32_MAX) {
+                        log(currentLast);
+                        pthread_mutex_unlock(&mLogElementsLock);
+                        return len;
+                    }
+                    stats.add(currentLast);
+                    stats.subtract(currentLast);
+                    delete currentLast;
+                    swab = total;
+                    event->payload.data = htole32(swab);
+                    pthread_mutex_unlock(&mLogElementsLock);
+                    return len;
+                }
+                if (count == USHRT_MAX) {
+                    log(dropped);
+                    count = 1;
+                } else {
+                    delete dropped;
+                    ++count;
+                }
+            }
+            if (count) {
+                stats.add(currentLast);
+                stats.subtract(currentLast);
+                currentLast->setDropped(count);
+            }
+            droppedElements[log_id] = currentLast;
+            lastLoggedElements[log_id] = elem;
+            pthread_mutex_unlock(&mLogElementsLock);
+            return len;
+        }
+        if (dropped) {         // State 1 or 2
+            if (count) {       // State 2
+                log(dropped);  // report chatty
+            } else {           // State 1
+                delete dropped;
+            }
+            droppedElements[log_id] = nullptr;
+            log(currentLast);  // report last message in the series
+        } else {               // State 0
+            delete currentLast;
+        }
+    }
+    lastLoggedElements[log_id] = new LogBufferElement(*elem);
+
+    log(elem);
+    pthread_mutex_unlock(&mLogElementsLock);
+
+    return len;
+}
+
+// assumes mLogElementsLock held, owns elem, will 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
     // Insert elements in time sorted order if possible
     //  NB: if end is region locked, place element at end of list
     LogBufferElementCollection::iterator it = mLogElements.end();
     LogBufferElementCollection::iterator last = it;
-    while (last != mLogElements.begin()) {
-        --it;
-        if ((*it)->getRealTime() <= realtime) {
-            break;
-        }
-        last = it;
-    }
-
-    if (last == mLogElements.end()) {
+    if (__predict_true(it != mLogElements.begin())) --it;
+    if (__predict_false(it == mLogElements.begin()) ||
+        __predict_true((*it)->getRealTime() <= elem->getRealTime()) ||
+        __predict_false((((*it)->getRealTime().tv_sec - too_far_back) >
+                         elem->getRealTime().tv_sec) &&
+                        (elem->getLogId() != LOG_ID_KERNEL) &&
+                        ((*it)->getLogId() != LOG_ID_KERNEL))) {
         mLogElements.push_back(elem);
     } else {
-        uint64_t end = 1;
+        log_time end = log_time::EPOCH;
         bool end_set = false;
         bool end_always = false;
 
         LogTimeEntry::lock();
 
         LastLogTimes::iterator times = mTimes.begin();
-        while(times != mTimes.end()) {
-            LogTimeEntry *entry = (*times);
+        while (times != mTimes.end()) {
+            LogTimeEntry* entry = (*times);
             if (entry->owned_Locked()) {
                 if (!entry->mNonBlock) {
                     end_always = true;
                     break;
                 }
+                // it passing mEnd is blocked by the following checks.
                 if (!end_set || (end <= entry->mEnd)) {
                     end = entry->mEnd;
                     end_set = true;
@@ -267,21 +408,25 @@
             times++;
         }
 
-        if (end_always
-                || (end_set && (end >= (*last)->getSequence()))) {
+        if (end_always || (end_set && (end > (*it)->getRealTime()))) {
             mLogElements.push_back(elem);
         } else {
-            mLogElements.insert(last,elem);
+            // should be short as timestamps are localized near end()
+            do {
+                last = it;
+                if (__predict_false(it == mLogElements.begin())) {
+                    break;
+                }
+                --it;
+            } while (((*it)->getRealTime() > elem->getRealTime()) &&
+                     (!end_set || (end <= (*it)->getRealTime())));
+            mLogElements.insert(last, elem);
         }
-
         LogTimeEntry::unlock();
     }
 
     stats.add(elem);
-    maybePrune(log_id);
-    pthread_mutex_unlock(&mLogElementsLock);
-
-    return len;
+    maybePrune(elem->getLogId());
 }
 
 // Prune at most 10% of the log entries or maxPrune, whichever is less.
@@ -309,28 +454,31 @@
 }
 
 LogBufferElementCollection::iterator LogBuffer::erase(
-        LogBufferElementCollection::iterator it, bool coalesce) {
-    LogBufferElement *element = *it;
+    LogBufferElementCollection::iterator it, bool coalesce) {
+    LogBufferElement* element = *it;
     log_id_t id = element->getLogId();
 
     // Remove iterator references in the various lists that will become stale
     // after the element is erased from the main logging list.
 
-    {   // start of scope for uid found iterator
-        LogBufferIteratorMap::iterator found =
-            mLastWorstUid[id].find(element->getUid());
-        if ((found != mLastWorstUid[id].end())
-                && (it == found->second)) {
-            mLastWorstUid[id].erase(found);
+    {  // start of scope for found iterator
+        int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY))
+                      ? element->getTag()
+                      : element->getUid();
+        LogBufferIteratorMap::iterator found = mLastWorst[id].find(key);
+        if ((found != mLastWorst[id].end()) && (it == found->second)) {
+            mLastWorst[id].erase(found);
         }
     }
 
-    {   // start of scope for pid found iterator
+    {  // start of scope for pid found iterator
         // element->getUid() may not be AID_SYSTEM for next-best-watermark.
+        // will not assume id != LOG_ID_EVENTS or LOG_ID_SECURITY for KISS and
+        // long term code stability, find() check should be fast for those ids.
         LogBufferPidIteratorMap::iterator found =
             mLastWorstPidOfSystem[id].find(element->getPid());
-        if ((found != mLastWorstPidOfSystem[id].end())
-                && (it == found->second)) {
+        if ((found != mLastWorstPidOfSystem[id].end()) &&
+            (it == found->second)) {
             mLastWorstPidOfSystem[id].erase(found);
         }
     }
@@ -340,18 +488,46 @@
     log_id_for_each(i) {
         doSetLast |= setLast[i] = mLastSet[i] && (it == mLast[i]);
     }
+#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
+    LogBufferElementCollection::iterator bad = it;
+    int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY))
+                  ? element->getTag()
+                  : element->getUid();
+#endif
     it = mLogElements.erase(it);
     if (doSetLast) {
         log_id_for_each(i) {
             if (setLast[i]) {
-                if (it == mLogElements.end()) { // unlikely
+                if (__predict_false(it == mLogElements.end())) {  // impossible
                     mLastSet[i] = false;
+                    mLast[i] = mLogElements.begin();
                 } else {
-                    mLast[i] = it;
+                    mLast[i] = it;  // push down the road as next-best-watermark
                 }
             }
         }
     }
+#ifdef DEBUG_CHECK_FOR_STALE_ENTRIES
+    log_id_for_each(i) {
+        for (auto b : mLastWorst[i]) {
+            if (bad == b.second) {
+                android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n", i,
+                                 b.first, key);
+            }
+        }
+        for (auto b : mLastWorstPidOfSystem[i]) {
+            if (bad == b.second) {
+                android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n", i,
+                                 b.first);
+            }
+        }
+        if (mLastSet[i] && (bad == mLast[i])) {
+            android::prdebug("stale mLast[%d]\n", i);
+            mLastSet[i] = false;
+            mLast[i] = mLogElements.begin();
+        }
+    }
+#endif
     if (coalesce) {
         stats.erase(element);
     } else {
@@ -368,40 +544,36 @@
 class LogBufferElementKey {
     const union {
         struct {
-            uint16_t uid;
+            uint32_t uid;
             uint16_t pid;
             uint16_t tid;
-            uint16_t padding;
         } __packed;
         uint64_t value;
     } __packed;
 
-public:
-    LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid):
-            uid(uid),
-            pid(pid),
-            tid(tid),
-            padding(0) {
+   public:
+    LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid)
+        : uid(uid), pid(pid), tid(tid) {
     }
-    LogBufferElementKey(uint64_t key):value(key) { }
+    explicit LogBufferElementKey(uint64_t key) : value(key) {
+    }
 
-    uint64_t getKey() { return value; }
+    uint64_t getKey() {
+        return value;
+    }
 };
 
 class LogBufferElementLast {
-
-    typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
+    typedef std::unordered_map<uint64_t, LogBufferElement*> LogBufferElementMap;
     LogBufferElementMap map;
 
-public:
-
-    bool coalesce(LogBufferElement *element, unsigned short dropped) {
-        LogBufferElementKey key(element->getUid(),
-                                element->getPid(),
+   public:
+    bool coalesce(LogBufferElement* element, unsigned short dropped) {
+        LogBufferElementKey key(element->getUid(), element->getPid(),
                                 element->getTid());
         LogBufferElementMap::iterator it = map.find(key.getKey());
         if (it != map.end()) {
-            LogBufferElement *found = it->second;
+            LogBufferElement* found = it->second;
             unsigned short moreDropped = found->getDropped();
             if ((dropped + moreDropped) > USHRT_MAX) {
                 map.erase(it);
@@ -413,9 +585,8 @@
         return false;
     }
 
-    void add(LogBufferElement *element) {
-        LogBufferElementKey key(element->getUid(),
-                                element->getPid(),
+    void add(LogBufferElement* element) {
+        LogBufferElementKey key(element->getUid(), element->getPid(),
                                 element->getTid());
         map[key.getKey()] = element;
     }
@@ -424,20 +595,19 @@
         map.clear();
     }
 
-    void clear(LogBufferElement *element) {
-        uint64_t current = element->getRealTime().nsec()
-                         - (EXPIRE_RATELIMIT * NS_PER_SEC);
-        for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
-            LogBufferElement *mapElement = it->second;
-            if ((mapElement->getDropped() >= EXPIRE_THRESHOLD)
-                    && (current > mapElement->getRealTime().nsec())) {
+    void clear(LogBufferElement* element) {
+        log_time current =
+            element->getRealTime() - log_time(EXPIRE_RATELIMIT, 0);
+        for (LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
+            LogBufferElement* mapElement = it->second;
+            if ((mapElement->getDropped() >= EXPIRE_THRESHOLD) &&
+                (current > mapElement->getRealTime())) {
                 it = map.erase(it);
             } else {
                 ++it;
             }
         }
     }
-
 };
 
 // prune "pruneRows" of type "id" from the buffer.
@@ -488,7 +658,7 @@
 // mLogElementsLock 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;
 
@@ -496,27 +666,30 @@
 
     // Region locked?
     LastLogTimes::iterator times = mTimes.begin();
-    while(times != mTimes.end()) {
-        LogTimeEntry *entry = (*times);
-        if (entry->owned_Locked() && entry->isWatching(id)
-                && (!oldest ||
-                    (oldest->mStart > entry->mStart) ||
-                    ((oldest->mStart == entry->mStart) &&
-                     (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) {
+    while (times != mTimes.end()) {
+        LogTimeEntry* entry = (*times);
+        if (entry->owned_Locked() && entry->isWatching(id) &&
+            (!oldest || (oldest->mStart > entry->mStart) ||
+             ((oldest->mStart == entry->mStart) &&
+              (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) {
             oldest = entry;
         }
         times++;
     }
+    log_time watermark(log_time::tv_sec_max, log_time::tv_nsec_max);
+    if (oldest) watermark = oldest->mStart - pruneMargin;
 
     LogBufferElementCollection::iterator it;
 
-    if (caller_uid != AID_ROOT) {
-        // Only here if clearAll condition (pruneRows == ULONG_MAX)
+    if (__predict_false(caller_uid != AID_ROOT)) {  // unlikely
+        // Only here if clear all request from non system source, so chatty
+        // filter logistics is not required.
         it = mLastSet[id] ? mLast[id] : mLogElements.begin();
         while (it != mLogElements.end()) {
-            LogBufferElement *element = *it;
+            LogBufferElement* element = *it;
 
-            if ((element->getLogId() != id) || (element->getUid() != caller_uid)) {
+            if ((element->getLogId() != id) ||
+                (element->getUid() != caller_uid)) {
                 ++it;
                 continue;
             }
@@ -526,7 +699,7 @@
                 mLastSet[id] = true;
             }
 
-            if (oldest && (oldest->mStart <= element->getSequence())) {
+            if (oldest && (watermark <= element->getRealTime())) {
                 busy = true;
                 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
                     oldest->triggerReader_Locked();
@@ -537,7 +710,9 @@
             }
 
             it = erase(it);
-            pruneRows--;
+            if (--pruneRows == 0) {
+                break;
+            }
         }
         LogTimeEntry::unlock();
         return busy;
@@ -547,48 +722,34 @@
     bool hasBlacklist = (id != LOG_ID_SECURITY) && mPrune.naughty();
     while (!clearAll && (pruneRows > 0)) {
         // recalculate the worst offender on every batched pass
-        uid_t worst = (uid_t) -1;
+        int worst = -1;  // not valid for getUid() or getKey()
         size_t worst_sizes = 0;
         size_t second_worst_sizes = 0;
-        pid_t worstPid = 0; // POSIX guarantees PID != 0
+        pid_t worstPid = 0;  // POSIX guarantees PID != 0
 
         if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
-            {   // begin scope for UID sorted list
-                std::unique_ptr<const UidEntry *[]> sorted = stats.sort(
-                    AID_ROOT, (pid_t)0, 2, id);
+            // Calculate threshold as 12.5% of available storage
+            size_t threshold = log_buffer_size(id) / 8;
 
-                if (sorted.get() && sorted[0] && sorted[1]) {
-                    worst_sizes = sorted[0]->getSizes();
-                    // Calculate threshold as 12.5% of available storage
-                    size_t threshold = log_buffer_size(id) / 8;
-                    if ((worst_sizes > threshold)
-                        // Allow time horizon to extend roughly tenfold, assume
-                        // average entry length is 100 characters.
-                            && (worst_sizes > (10 * sorted[0]->getDropped()))) {
-                        worst = sorted[0]->getKey();
-                        second_worst_sizes = sorted[1]->getSizes();
-                        if (second_worst_sizes < threshold) {
-                            second_worst_sizes = threshold;
-                        }
-                    }
-                }
-            }
+            if ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) {
+                stats.sortTags(AID_ROOT, (pid_t)0, 2, id)
+                    .findWorst(worst, worst_sizes, second_worst_sizes,
+                               threshold);
+                // per-pid filter for AID_SYSTEM sources is too complex
+            } else {
+                stats.sort(AID_ROOT, (pid_t)0, 2, id)
+                    .findWorst(worst, worst_sizes, second_worst_sizes,
+                               threshold);
 
-            if ((worst == AID_SYSTEM) && mPrune.worstPidOfSystemEnabled()) {
-                // begin scope of PID sorted list
-                std::unique_ptr<const PidEntry *[]> sorted = stats.sort(
-                    worst, (pid_t)0, 2, id, worst);
-                if (sorted.get() && sorted[0] && sorted[1]) {
-                    worstPid = sorted[0]->getKey();
-                    second_worst_sizes = worst_sizes
-                                       - sorted[0]->getSizes()
-                                       + sorted[1]->getSizes();
+                if ((worst == AID_SYSTEM) && mPrune.worstPidOfSystemEnabled()) {
+                    stats.sortPids(worst, (pid_t)0, 2, id)
+                        .findWorst(worstPid, worst_sizes, second_worst_sizes);
                 }
             }
         }
 
         // skip if we have neither worst nor naughty filters
-        if ((worst == (uid_t) -1) && !hasBlacklist) {
+        if ((worst == -1) && !hasBlacklist) {
             break;
         }
 
@@ -600,37 +761,37 @@
         // - coalesce chatty tags
         // - check age-out of preserved logs
         bool gc = pruneRows <= 1;
-        if (!gc && (worst != (uid_t) -1)) {
-            {   // begin scope for uid worst found iterator
-                LogBufferIteratorMap::iterator found = mLastWorstUid[id].find(worst);
-                if ((found != mLastWorstUid[id].end())
-                        && (found->second != mLogElements.end())) {
+        if (!gc && (worst != -1)) {
+            {  // begin scope for worst found iterator
+                LogBufferIteratorMap::iterator found =
+                    mLastWorst[id].find(worst);
+                if ((found != mLastWorst[id].end()) &&
+                    (found->second != mLogElements.end())) {
                     leading = false;
                     it = found->second;
                 }
             }
-            if (worstPid) {
-                // begin scope for pid worst found iterator
-                LogBufferPidIteratorMap::iterator found
-                    = mLastWorstPidOfSystem[id].find(worstPid);
-                if ((found != mLastWorstPidOfSystem[id].end())
-                        && (found->second != mLogElements.end())) {
+            if (worstPid) {  // begin scope for pid worst found iterator
+                // FYI: worstPid only set if !LOG_ID_EVENTS and
+                //      !LOG_ID_SECURITY, not going to make that assumption ...
+                LogBufferPidIteratorMap::iterator found =
+                    mLastWorstPidOfSystem[id].find(worstPid);
+                if ((found != mLastWorstPidOfSystem[id].end()) &&
+                    (found->second != mLogElements.end())) {
                     leading = false;
                     it = found->second;
                 }
             }
         }
-        static const timespec too_old = {
-            EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
-        };
+        static const timespec too_old = { EXPIRE_HOUR_THRESHOLD * 60 * 60, 0 };
         LogBufferElementCollection::iterator lastt;
         lastt = mLogElements.end();
         --lastt;
         LogBufferElementLast last;
         while (it != mLogElements.end()) {
-            LogBufferElement *element = *it;
+            LogBufferElement* element = *it;
 
-            if (oldest && (oldest->mStart <= element->getSequence())) {
+            if (oldest && (watermark <= element->getRealTime())) {
                 busy = true;
                 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
                     oldest->triggerReader_Locked();
@@ -662,6 +823,10 @@
                 continue;
             }
 
+            int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY))
+                          ? element->getTag()
+                          : element->getUid();
+
             if (hasBlacklist && mPrune.naughty(element)) {
                 last.clear(element);
                 it = erase(it);
@@ -674,7 +839,7 @@
                     break;
                 }
 
-                if (element->getUid() == worst) {
+                if (key == worst) {
                     kick = true;
                     if (worst_sizes < second_worst_sizes) {
                         break;
@@ -684,32 +849,32 @@
                 continue;
             }
 
-            if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old))
-                    || (element->getRealTime() > (*lastt)->getRealTime())) {
+            if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old)) ||
+                (element->getRealTime() > (*lastt)->getRealTime())) {
                 break;
             }
 
             if (dropped) {
                 last.add(element);
-                if (worstPid
-                        && ((!gc && (element->getPid() == worstPid))
-                            || (mLastWorstPidOfSystem[id].find(element->getPid())
-                                == mLastWorstPidOfSystem[id].end()))) {
+                if (worstPid &&
+                    ((!gc && (element->getPid() == worstPid)) ||
+                     (mLastWorstPidOfSystem[id].find(element->getPid()) ==
+                      mLastWorstPidOfSystem[id].end()))) {
                     // element->getUid() may not be AID_SYSTEM, next best
-                    // watermark if current one empty.
+                    // watermark if current one empty. id is not LOG_ID_EVENTS
+                    // or LOG_ID_SECURITY because of worstPid check.
                     mLastWorstPidOfSystem[id][element->getPid()] = it;
                 }
-                if ((!gc && !worstPid && (element->getUid() == worst))
-                        || (mLastWorstUid[id].find(element->getUid())
-                            == mLastWorstUid[id].end())) {
-                    mLastWorstUid[id][element->getUid()] = it;
+                if ((!gc && !worstPid && (key == worst)) ||
+                    (mLastWorst[id].find(key) == mLastWorst[id].end())) {
+                    mLastWorst[id][key] = it;
                 }
                 ++it;
                 continue;
             }
 
-            if ((element->getUid() != worst)
-                    || (worstPid && (element->getPid() != worstPid))) {
+            if ((key != worst) ||
+                (worstPid && (element->getPid() != worstPid))) {
                 leading = false;
                 last.clear(element);
                 ++it;
@@ -737,16 +902,17 @@
                     it = erase(it, true);
                 } else {
                     last.add(element);
-                    if (worstPid && (!gc
-                                || (mLastWorstPidOfSystem[id].find(worstPid)
-                                    == mLastWorstPidOfSystem[id].end()))) {
+                    if (worstPid &&
+                        (!gc || (mLastWorstPidOfSystem[id].find(worstPid) ==
+                                 mLastWorstPidOfSystem[id].end()))) {
                         // element->getUid() may not be AID_SYSTEM, next best
-                        // watermark if current one empty.
+                        // watermark if current one empty. id is not
+                        // LOG_ID_EVENTS or LOG_ID_SECURITY because of worstPid.
                         mLastWorstPidOfSystem[id][worstPid] = it;
                     }
-                    if ((!gc && !worstPid) || (mLastWorstUid[id].find(worst)
-                                == mLastWorstUid[id].end())) {
-                        mLastWorstUid[id][worst] = it;
+                    if ((!gc && !worstPid) ||
+                        (mLastWorst[id].find(worst) == mLastWorst[id].end())) {
+                        mLastWorst[id][worst] = it;
                     }
                     ++it;
                 }
@@ -759,15 +925,15 @@
         last.clear();
 
         if (!kick || !mPrune.worstUidEnabled()) {
-            break; // the following loop will ask bad clients to skip/drop
+            break;  // the following loop will ask bad clients to skip/drop
         }
     }
 
     bool whitelist = false;
     bool hasWhitelist = (id != LOG_ID_SECURITY) && mPrune.nice() && !clearAll;
     it = mLastSet[id] ? mLast[id] : mLogElements.begin();
-    while((pruneRows > 0) && (it != mLogElements.end())) {
-        LogBufferElement *element = *it;
+    while ((pruneRows > 0) && (it != mLogElements.end())) {
+        LogBufferElement* element = *it;
 
         if (element->getLogId() != id) {
             it++;
@@ -779,7 +945,7 @@
             mLastSet[id] = true;
         }
 
-        if (oldest && (oldest->mStart <= element->getSequence())) {
+        if (oldest && (watermark <= element->getRealTime())) {
             busy = true;
             if (whitelist) {
                 break;
@@ -810,8 +976,8 @@
     // Do not save the whitelist if we are reader range limited
     if (whitelist && (pruneRows > 0)) {
         it = mLastSet[id] ? mLast[id] : mLogElements.begin();
-        while((it != mLogElements.end()) && (pruneRows > 0)) {
-            LogBufferElement *element = *it;
+        while ((it != mLogElements.end()) && (pruneRows > 0)) {
+            LogBufferElement* element = *it;
 
             if (element->getLogId() != id) {
                 ++it;
@@ -823,7 +989,7 @@
                 mLastSet[id] = true;
             }
 
-            if (oldest && (oldest->mStart <= element->getSequence())) {
+            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
@@ -851,7 +1017,7 @@
     bool busy = true;
     // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
     for (int retry = 4;;) {
-        if (retry == 1) { // last pass
+        if (retry == 1) {  // last pass
             // Check if it is still busy after the sleep, we say prune
             // one entry, not another clear run, so we are looking for
             // the quick side effect of the return value to tell us if
@@ -867,7 +1033,7 @@
                 LogTimeEntry::lock();
                 LastLogTimes::iterator times = mTimes.begin();
                 while (times != mTimes.end()) {
-                    LogTimeEntry *entry = (*times);
+                    LogTimeEntry* entry = (*times);
                     // Killer punch
                     if (entry->owned_Locked() && entry->isWatching(id)) {
                         entry->release_Locked();
@@ -883,7 +1049,7 @@
         if (!busy || !--retry) {
             break;
         }
-        sleep (1); // Let reader(s) catch up after notification
+        sleep(1);  // Let reader(s) catch up after notification
     }
     return busy;
 }
@@ -899,7 +1065,7 @@
 // set the total space allocated to "id"
 int LogBuffer::setSize(log_id_t id, unsigned long size) {
     // Reasonable limits ...
-    if (!valid_size(size)) {
+    if (!__android_logger_valid_buffer_size(size)) {
         return -1;
     }
     pthread_mutex_lock(&mLogElementsLock);
@@ -916,34 +1082,59 @@
     return retval;
 }
 
-uint64_t LogBuffer::flushTo(
-        SocketClient *reader, const uint64_t 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;
-    uint64_t max = start;
     uid_t uid = reader->getUid();
 
     pthread_mutex_lock(&mLogElementsLock);
 
-    if (start <= 1) {
+    if (start == log_time::EPOCH) {
         // client wants to start from the beginning
         it = mLogElements.begin();
     } else {
+        // 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(); /* do nothing */) {
+        LogBufferElementCollection::iterator last;
+        for (last = it = mLogElements.end(); it != mLogElements.begin();
+             /* do nothing */) {
             --it;
-            LogBufferElement *element = *it;
-            if (element->getSequence() <= start) {
-                it++;
+            LogBufferElement* element = *it;
+            if (element->getRealTime() > start) {
+                last = it;
+            } else if (!--count || (element->getRealTime() < min)) {
                 break;
             }
         }
+        it = last;
     }
 
+    log_time max = start;
+
+    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;
+        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;
@@ -953,7 +1144,7 @@
             continue;
         }
 
-        if (element->getSequence() <= start) {
+        if (element->getRealTime() <= start) {
             continue;
         }
 
@@ -968,15 +1159,28 @@
             }
         }
 
+        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);
 
         // range locking in LastLogTimes looks after us
-        max = element->flushTo(reader, this, privileged);
+        max = element->flushTo(reader, this, privileged, sameTid);
 
         if (max == element->FLUSH_ERROR) {
             return max;
         }
 
+        skip = maxSkip;
         pthread_mutex_lock(&mLogElementsLock);
     }
     pthread_mutex_unlock(&mLogElementsLock);
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index 7e99236..1272c20 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -22,14 +22,14 @@
 #include <list>
 #include <string>
 
-#include <log/log.h>
+#include <android/log.h>
+#include <private/android_filesystem_config.h>
 #include <sysutils/SocketClient.h>
 
-#include <private/android_filesystem_config.h>
-
 #include "LogBufferElement.h"
-#include "LogTimes.h"
 #include "LogStatistics.h"
+#include "LogTags.h"
+#include "LogTimes.h"
 #include "LogWhiteBlackList.h"
 
 //
@@ -41,7 +41,7 @@
 //
 namespace android {
 
-static bool isMonotonic(const log_time &mono) {
+static bool isMonotonic(const log_time& mono) {
     static const uint32_t EPOCH_PLUS_2_YEARS = 2 * 24 * 60 * 60 * 1461 / 4;
     static const uint32_t EPOCH_PLUS_MINUTE = 60;
 
@@ -70,10 +70,9 @@
     /* dividing line half way between monotonic and realtime */
     return mono.tv_sec < ((cpu.tv_sec + now.tv_sec) / 2);
 }
-
 }
 
-typedef std::list<LogBufferElement *> LogBufferElementCollection;
+typedef std::list<LogBufferElement*> LogBufferElementCollection;
 
 class LogBuffer {
     LogBufferElementCollection mLogElements;
@@ -86,60 +85,96 @@
     LogBufferElementCollection::iterator mLast[LOG_ID_MAX];
     bool mLastSet[LOG_ID_MAX];
     // watermark of any worst/chatty uid processing
-    typedef std::unordered_map<uid_t,
-                               LogBufferElementCollection::iterator>
-                LogBufferIteratorMap;
-    LogBufferIteratorMap mLastWorstUid[LOG_ID_MAX];
+    typedef std::unordered_map<uid_t, LogBufferElementCollection::iterator>
+        LogBufferIteratorMap;
+    LogBufferIteratorMap mLastWorst[LOG_ID_MAX];
     // watermark of any worst/chatty pid of system processing
-    typedef std::unordered_map<pid_t,
-                               LogBufferElementCollection::iterator>
-                LogBufferPidIteratorMap;
+    typedef std::unordered_map<pid_t, LogBufferElementCollection::iterator>
+        LogBufferPidIteratorMap;
     LogBufferPidIteratorMap mLastWorstPidOfSystem[LOG_ID_MAX];
 
     unsigned long mMaxSize[LOG_ID_MAX];
 
     bool monotonic;
 
-public:
-    LastLogTimes &mTimes;
+    LogTags tags;
 
-    LogBuffer(LastLogTimes *times);
+    LogBufferElement* lastLoggedElements[LOG_ID_MAX];
+    LogBufferElement* droppedElements[LOG_ID_MAX];
+    void log(LogBufferElement* elem);
+
+   public:
+    LastLogTimes& mTimes;
+
+    explicit LogBuffer(LastLogTimes* times);
+    ~LogBuffer();
     void init();
-    bool isMonotonic() { return monotonic; }
+    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);
-    uint64_t flushTo(SocketClient *writer, const uint64_t start,
+    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);
+    // 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);
+                     int (*filter)(const LogBufferElement* element,
+                                   void* arg) = nullptr,
+                     void* arg = nullptr);
 
     bool clear(log_id_t id, uid_t uid = AID_ROOT);
     unsigned long getSize(log_id_t id);
     int setSize(log_id_t id, unsigned long size);
     unsigned long getSizeUsed(log_id_t id);
-    // *strp uses malloc, use free to release.
+
     std::string formatStatistics(uid_t uid, pid_t pid, unsigned int logMask);
 
     void enableStatistics() {
         stats.enableStatistics();
     }
 
-    int initPrune(const char *cp) { return mPrune.init(cp); }
-    std::string formatPrune() { return mPrune.format(); }
+    int initPrune(const char* cp) {
+        return mPrune.init(cp);
+    }
+    std::string formatPrune() {
+        return mPrune.format();
+    }
+
+    std::string formatGetEventTag(uid_t uid, const char* name,
+                                  const char* format) {
+        return tags.formatGetEventTag(uid, name, format);
+    }
+    std::string formatEntry(uint32_t tag, uid_t uid) {
+        return tags.formatEntry(tag, uid);
+    }
+    const char* tagToName(uint32_t tag) {
+        return tags.tagToName(tag);
+    }
 
     // helper must be protected directly or implicitly by lock()/unlock()
-    const char *pidToName(pid_t pid) { return stats.pidToName(pid); }
-    uid_t pidToUid(pid_t pid) { return stats.pidToUid(pid); }
-    const char *uidToName(uid_t uid) { return stats.uidToName(uid); }
-    void lock() { pthread_mutex_lock(&mLogElementsLock); }
-    void unlock() { pthread_mutex_unlock(&mLogElementsLock); }
+    const char* pidToName(pid_t pid) {
+        return stats.pidToName(pid);
+    }
+    uid_t pidToUid(pid_t pid) {
+        return stats.pidToUid(pid);
+    }
+    const char* uidToName(uid_t uid) {
+        return stats.uidToName(uid);
+    }
+    void lock() {
+        pthread_mutex_lock(&mLogElementsLock);
+    }
+    void unlock() {
+        pthread_mutex_unlock(&mLogElementsLock);
+    }
 
-private:
-
+   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);
@@ -147,4 +182,4 @@
         LogBufferElementCollection::iterator it, bool coalesce = false);
 };
 
-#endif // _LOGD_LOG_BUFFER_H__
+#endif  // _LOGD_LOG_BUFFER_H__
diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp
index eb5194c..04a620c 100644
--- a/logd/LogBufferElement.cpp
+++ b/logd/LogBufferElement.cpp
@@ -22,7 +22,6 @@
 #include <time.h>
 #include <unistd.h>
 
-#include <log/logger.h>
 #include <private/android_logger.h>
 
 #include "LogBuffer.h"
@@ -31,38 +30,44 @@
 #include "LogReader.h"
 #include "LogUtils.h"
 
-const uint64_t LogBufferElement::FLUSH_ERROR(0);
+const log_time LogBufferElement::FLUSH_ERROR((uint32_t)-1, (uint32_t)-1);
 atomic_int_fast64_t LogBufferElement::sequence(1);
 
 LogBufferElement::LogBufferElement(log_id_t log_id, log_time realtime,
                                    uid_t uid, pid_t pid, pid_t tid,
-                                   const char *msg, unsigned short len) :
-        mLogId(log_id),
-        mUid(uid),
-        mPid(pid),
-        mTid(tid),
-        mMsgLen(len),
-        mSequence(sequence.fetch_add(1, memory_order_relaxed)),
-        mRealTime(realtime) {
+                                   const char* msg, unsigned short len)
+    : mUid(uid),
+      mPid(pid),
+      mTid(tid),
+      mRealTime(realtime),
+      mMsgLen(len),
+      mLogId(log_id) {
     mMsg = new char[len];
     memcpy(mMsg, msg, len);
+    mTag = (isBinary() && (mMsgLen >= sizeof(uint32_t)))
+               ? le32toh(reinterpret_cast<android_event_header_t*>(mMsg)->tag)
+               : 0;
+}
+
+LogBufferElement::LogBufferElement(const LogBufferElement& elem)
+    : mTag(elem.mTag),
+      mUid(elem.mUid),
+      mPid(elem.mPid),
+      mTid(elem.mTid),
+      mRealTime(elem.mRealTime),
+      mMsgLen(elem.mMsgLen),
+      mLogId(elem.mLogId) {
+    mMsg = new char[mMsgLen];
+    memcpy(mMsg, elem.mMsg, mMsgLen);
 }
 
 LogBufferElement::~LogBufferElement() {
-    delete [] mMsg;
-}
-
-uint32_t LogBufferElement::getTag() const {
-    if (((mLogId != LOG_ID_EVENTS) && (mLogId != LOG_ID_SECURITY)) ||
-            !mMsg || (mMsgLen < sizeof(uint32_t))) {
-        return 0;
-    }
-    return le32toh(reinterpret_cast<android_event_header_t *>(mMsg)->tag);
+    delete[] mMsg;
 }
 
 // caller must own and free character string
-char *android::tidToName(pid_t tid) {
-    char *retval = NULL;
+char* android::tidToName(pid_t tid) {
+    char* retval = NULL;
     char buffer[256];
     snprintf(buffer, sizeof(buffer), "/proc/%u/comm", tid);
     int fd = open(buffer, O_RDONLY);
@@ -82,7 +87,7 @@
     }
 
     // if nothing for comm, check out cmdline
-    char *name = android::pidToName(tid);
+    char* name = android::pidToName(tid);
     if (!retval) {
         retval = name;
         name = NULL;
@@ -94,8 +99,8 @@
         size_t retval_len = strlen(retval);
         size_t name_len = strlen(name);
         // KISS: ToDo: Only checks prefix truncated, not suffix, or both
-        if ((retval_len < name_len)
-                && !fast<strcmp>(retval, name + name_len - retval_len)) {
+        if ((retval_len < name_len) &&
+            !fastcmp<strcmp>(retval, name + name_len - retval_len)) {
             free(retval);
             retval = name;
         } else {
@@ -106,19 +111,20 @@
 }
 
 // assumption: mMsg == NULL
-size_t LogBufferElement::populateDroppedMessage(char *&buffer,
-        LogBuffer *parent) {
+size_t LogBufferElement::populateDroppedMessage(char*& buffer, LogBuffer* parent,
+                                                bool lastSame) {
     static const char tag[] = "chatty";
 
-    if (!__android_log_is_loggable(ANDROID_LOG_INFO, tag, ANDROID_LOG_VERBOSE)) {
+    if (!__android_log_is_loggable_len(ANDROID_LOG_INFO, tag, strlen(tag),
+                                       ANDROID_LOG_VERBOSE)) {
         return 0;
     }
 
-    static const char format_uid[] = "uid=%u%s%s expire %u line%s";
+    static const char format_uid[] = "uid=%u%s%s %s %u line%s";
     parent->lock();
-    const char *name = parent->uidToName(mUid);
+    const char* name = parent->uidToName(mUid);
     parent->unlock();
-    const char *commName = android::tidToName(mTid);
+    const char* commName = android::tidToName(mTid);
     if (!commName && (mTid != mPid)) {
         commName = android::tidToName(mPid);
     }
@@ -131,57 +137,56 @@
         size_t len = strlen(name + 1);
         if (!strncmp(name + 1, commName + 1, len)) {
             if (commName[len + 1] == '\0') {
-                free(const_cast<char *>(commName));
+                free(const_cast<char*>(commName));
                 commName = NULL;
             } else {
-                free(const_cast<char *>(name));
+                free(const_cast<char*>(name));
                 name = NULL;
             }
         }
     }
     if (name) {
-        char *buf = NULL;
+        char* buf = NULL;
         asprintf(&buf, "(%s)", name);
         if (buf) {
-            free(const_cast<char *>(name));
+            free(const_cast<char*>(name));
             name = buf;
         }
     }
     if (commName) {
-        char *buf = NULL;
+        char* buf = NULL;
         asprintf(&buf, " %s", commName);
         if (buf) {
-            free(const_cast<char *>(commName));
+            free(const_cast<char*>(commName));
             commName = buf;
         }
     }
     // identical to below to calculate the buffer size required
+    const char* type = lastSame ? "identical" : "expire";
     size_t len = snprintf(NULL, 0, format_uid, mUid, name ? name : "",
-                          commName ? commName : "",
-                          mDropped, (mDropped > 1) ? "s" : "");
+                          commName ? commName : "", type, mDropped,
+                          (mDropped > 1) ? "s" : "");
 
     size_t hdrLen;
-    // LOG_ID_SECURITY not strictly needed since spam filter not activated,
-    // but required for accuracy.
-    if ((mLogId == LOG_ID_EVENTS) || (mLogId == LOG_ID_SECURITY)) {
+    if (isBinary()) {
         hdrLen = sizeof(android_log_event_string_t);
     } else {
         hdrLen = 1 + sizeof(tag);
     }
 
-    buffer = static_cast<char *>(calloc(1, hdrLen + len + 1));
+    buffer = static_cast<char*>(calloc(1, hdrLen + len + 1));
     if (!buffer) {
-        free(const_cast<char *>(name));
-        free(const_cast<char *>(commName));
+        free(const_cast<char*>(name));
+        free(const_cast<char*>(commName));
         return 0;
     }
 
     size_t retval = hdrLen + len;
-    if ((mLogId == LOG_ID_EVENTS) || (mLogId == LOG_ID_SECURITY)) {
-        android_log_event_string_t *event =
-            reinterpret_cast<android_log_event_string_t *>(buffer);
+    if (isBinary()) {
+        android_log_event_string_t* event =
+            reinterpret_cast<android_log_event_string_t*>(buffer);
 
-        event->header.tag = htole32(LOGD_LOG_TAG);
+        event->header.tag = htole32(CHATTY_LOG_TAG);
         event->type = EVENT_TYPE_STRING;
         event->length = htole32(len);
     } else {
@@ -191,23 +196,22 @@
     }
 
     snprintf(buffer + hdrLen, len + 1, format_uid, mUid, name ? name : "",
-             commName ? commName : "",
-             mDropped, (mDropped > 1) ? "s" : "");
-    free(const_cast<char *>(name));
-    free(const_cast<char *>(commName));
+             commName ? commName : "", type, mDropped,
+             (mDropped > 1) ? "s" : "");
+    free(const_cast<char*>(name));
+    free(const_cast<char*>(commName));
 
     return retval;
 }
 
-uint64_t LogBufferElement::flushTo(SocketClient *reader, LogBuffer *parent,
-                                   bool privileged) {
+log_time LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent,
+                                   bool privileged, bool lastSame) {
     struct logger_entry_v4 entry;
 
     memset(&entry, 0, sizeof(struct logger_entry_v4));
 
-    entry.hdr_size = privileged ?
-                         sizeof(struct logger_entry_v4) :
-                         sizeof(struct logger_entry_v3);
+    entry.hdr_size = privileged ? sizeof(struct logger_entry_v4)
+                                : sizeof(struct logger_entry_v3);
     entry.lid = mLogId;
     entry.pid = mPid;
     entry.tid = mTid;
@@ -219,13 +223,11 @@
     iovec[0].iov_base = &entry;
     iovec[0].iov_len = entry.hdr_size;
 
-    char *buffer = NULL;
+    char* buffer = NULL;
 
     if (!mMsg) {
-        entry.len = populateDroppedMessage(buffer, parent);
-        if (!entry.len) {
-            return mSequence;
-        }
+        entry.len = populateDroppedMessage(buffer, parent, lastSame);
+        if (!entry.len) return mRealTime;
         iovec[1].iov_base = buffer;
     } else {
         entry.len = mMsgLen;
@@ -233,11 +235,11 @@
     }
     iovec[1].iov_len = entry.len;
 
-    uint64_t retval = reader->sendDatav(iovec, 2) ? FLUSH_ERROR : mSequence;
+    log_time retval = reader->sendDatav(iovec, 1 + (entry.len != 0))
+                          ? FLUSH_ERROR
+                          : mRealTime;
 
-    if (buffer) {
-        free(buffer);
-    }
+    if (buffer) free(buffer);
 
     return retval;
 }
diff --git a/logd/LogBufferElement.h b/logd/LogBufferElement.h
index e7f88b9..814ec87 100644
--- a/logd/LogBufferElement.h
+++ b/logd/LogBufferElement.h
@@ -21,66 +21,87 @@
 #include <stdlib.h>
 #include <sys/types.h>
 
-#include <sysutils/SocketClient.h>
 #include <log/log.h>
-#include <log/log_read.h>
+#include <sysutils/SocketClient.h>
 
 class LogBuffer;
 
-#define EXPIRE_HOUR_THRESHOLD 24 // Only expire chatty UID logs to preserve
-                                 // non-chatty UIDs less than this age in hours
-#define EXPIRE_THRESHOLD 10      // A smaller expire count is considered too
-                                 // chatty for the temporal expire messages
-#define EXPIRE_RATELIMIT 10      // maximum rate in seconds to report expiration
+#define EXPIRE_HOUR_THRESHOLD 24  // Only expire chatty UID logs to preserve
+                                  // non-chatty UIDs less than this age in hours
+#define EXPIRE_THRESHOLD 10       // A smaller expire count is considered too
+                                  // chatty for the temporal expire messages
+#define EXPIRE_RATELIMIT 10  // maximum rate in seconds to report expiration
 
 class LogBufferElement {
-
     friend LogBuffer;
 
-    const log_id_t mLogId;
-    const uid_t mUid;
-    const pid_t mPid;
-    const pid_t mTid;
-    char *mMsg;
-    union {
-        const unsigned short mMsgLen; // mMSg != NULL
-        unsigned short mDropped;      // mMsg == NULL
-    };
-    const uint64_t mSequence;
+    // sized to match reality of incoming log packets
+    uint32_t mTag;  // only valid for isBinary()
+    const uint32_t mUid;
+    const uint32_t mPid;
+    const uint32_t mTid;
     log_time mRealTime;
+    char* mMsg;
+    union {
+        const uint16_t mMsgLen;  // mMSg != NULL
+        uint16_t mDropped;       // mMsg == NULL
+    };
+    const uint8_t mLogId;
+
     static atomic_int_fast64_t sequence;
 
     // assumption: mMsg == NULL
-    size_t populateDroppedMessage(char *&buffer,
-                                  LogBuffer *parent);
+    size_t populateDroppedMessage(char*& buffer, LogBuffer* parent,
+                                  bool lastSame);
 
-public:
-    LogBufferElement(log_id_t log_id, log_time realtime,
-                     uid_t uid, pid_t pid, pid_t tid,
-                     const char *msg, unsigned short len);
+   public:
+    LogBufferElement(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid,
+                     pid_t tid, const char* msg, unsigned short len);
+    LogBufferElement(const LogBufferElement& elem);
     virtual ~LogBufferElement();
 
-    log_id_t getLogId() const { return mLogId; }
-    uid_t getUid(void) const { return mUid; }
-    pid_t getPid(void) const { return mPid; }
-    pid_t getTid(void) const { return mTid; }
-    unsigned short getDropped(void) const { return mMsg ? 0 : mDropped; }
+    bool isBinary(void) const {
+        return (mLogId == LOG_ID_EVENTS) || (mLogId == LOG_ID_SECURITY);
+    }
+
+    log_id_t getLogId() const {
+        return static_cast<log_id_t>(mLogId);
+    }
+    uid_t getUid(void) const {
+        return mUid;
+    }
+    pid_t getPid(void) const {
+        return mPid;
+    }
+    pid_t getTid(void) const {
+        return mTid;
+    }
+    uint32_t getTag() const {
+        return mTag;
+    }
+    unsigned short getDropped(void) const {
+        return mMsg ? 0 : mDropped;
+    }
     unsigned short setDropped(unsigned short value) {
         if (mMsg) {
-            delete [] mMsg;
+            delete[] mMsg;
             mMsg = NULL;
         }
         return mDropped = value;
     }
-    unsigned short getMsgLen() const { return mMsg ? mMsgLen : 0; }
-    uint64_t getSequence(void) const { return mSequence; }
-    static uint64_t getCurrentSequence(void) { return sequence.load(memory_order_relaxed); }
-    log_time getRealTime(void) const { return mRealTime; }
+    unsigned short getMsgLen() const {
+        return mMsg ? mMsgLen : 0;
+    }
+    const char* getMsg() const {
+        return mMsg;
+    }
+    log_time getRealTime(void) const {
+        return mRealTime;
+    }
 
-    uint32_t getTag(void) const;
-
-    static const uint64_t FLUSH_ERROR;
-    uint64_t flushTo(SocketClient *writer, LogBuffer *parent, bool privileged);
+    static const log_time FLUSH_ERROR;
+    log_time flushTo(SocketClient* writer, LogBuffer* parent, bool privileged,
+                     bool lastSame);
 };
 
 #endif
diff --git a/logd/LogCommand.cpp b/logd/LogCommand.cpp
index 3b17576..6d7c0a5 100644
--- a/logd/LogCommand.cpp
+++ b/logd/LogCommand.cpp
@@ -24,7 +24,7 @@
 #include "LogCommand.h"
 #include "LogUtils.h"
 
-LogCommand::LogCommand(const char *cmd) : FrameworkCommand(cmd) {
+LogCommand::LogCommand(const char* cmd) : FrameworkCommand(cmd) {
 }
 
 // gets a list of supplementary group IDs associated with
@@ -40,8 +40,8 @@
 // has open permissions, and one that has restricted
 // permissions.
 
-static bool groupIsLog(char *buf) {
-    char *ptr;
+static bool groupIsLog(char* buf) {
+    char* ptr;
     static const char ws[] = " \n";
 
     for (buf = strtok_r(buf, ws, &ptr); buf; buf = strtok_r(NULL, ws, &ptr)) {
@@ -91,15 +91,14 @@
     // doubt, but we expect the falses  should be reduced significantly as
     // three times is a charm.
     //
-    for (int retry = 3;
-            !(ret = foundGid && foundUid && foundLog) && retry;
-            --retry) {
-        FILE *file = fopen(filename, "r");
+    for (int retry = 3; !(ret = foundGid && foundUid && foundLog) && retry;
+         --retry) {
+        FILE* file = fopen(filename, "r");
         if (!file) {
             continue;
         }
 
-        char *line = NULL;
+        char* line = NULL;
         size_t len = 0;
         while (getline(&line, &len, file) > 0) {
             static const char groups_string[] = "Groups:\t";
@@ -111,29 +110,25 @@
                     foundLog = true;
                 }
             } else if (strncmp(uid_string, line, sizeof(uid_string) - 1) == 0) {
-                uid_t u[4] = { (uid_t) -1, (uid_t) -1, (uid_t) -1, (uid_t) -1};
+                uid_t u[4] = { (uid_t)-1, (uid_t)-1, (uid_t)-1, (uid_t)-1 };
 
-                sscanf(line + sizeof(uid_string) - 1, "%u\t%u\t%u\t%u",
-                       &u[0], &u[1], &u[2], &u[3]);
+                sscanf(line + sizeof(uid_string) - 1, "%u\t%u\t%u\t%u", &u[0],
+                       &u[1], &u[2], &u[3]);
 
                 // Protect against PID reuse by checking that UID is the same
-                if ((uid == u[0])
-                        && (uid == u[1])
-                        && (uid == u[2])
-                        && (uid == u[3])) {
+                if ((uid == u[0]) && (uid == u[1]) && (uid == u[2]) &&
+                    (uid == u[3])) {
                     foundUid = true;
                 }
             } else if (strncmp(gid_string, line, sizeof(gid_string) - 1) == 0) {
-                gid_t g[4] = { (gid_t) -1, (gid_t) -1, (gid_t) -1, (gid_t) -1};
+                gid_t g[4] = { (gid_t)-1, (gid_t)-1, (gid_t)-1, (gid_t)-1 };
 
-                sscanf(line + sizeof(gid_string) - 1, "%u\t%u\t%u\t%u",
-                       &g[0], &g[1], &g[2], &g[3]);
+                sscanf(line + sizeof(gid_string) - 1, "%u\t%u\t%u\t%u", &g[0],
+                       &g[1], &g[2], &g[3]);
 
                 // Protect against PID reuse by checking that GID is the same
-                if ((gid == g[0])
-                        && (gid == g[1])
-                        && (gid == g[2])
-                        && (gid == g[3])) {
+                if ((gid == g[0]) && (gid == g[1]) && (gid == g[2]) &&
+                    (gid == g[3])) {
                     foundGid = true;
                 }
             }
@@ -145,6 +140,6 @@
     return ret;
 }
 
-bool clientHasLogCredentials(SocketClient *cli) {
+bool clientHasLogCredentials(SocketClient* cli) {
     return clientHasLogCredentials(cli->getUid(), cli->getGid(), cli->getPid());
 }
diff --git a/logd/LogCommand.h b/logd/LogCommand.h
index c944478..e10ffa0 100644
--- a/logd/LogCommand.h
+++ b/logd/LogCommand.h
@@ -17,13 +17,14 @@
 #ifndef _LOGD_COMMAND_H
 #define _LOGD_COMMAND_H
 
-#include <sysutils/SocketClient.h>
 #include <sysutils/FrameworkCommand.h>
+#include <sysutils/SocketClient.h>
 
 class LogCommand : public FrameworkCommand {
-public:
-    LogCommand(const char *cmd);
-    virtual ~LogCommand() {}
+   public:
+    explicit LogCommand(const char* cmd);
+    virtual ~LogCommand() {
+    }
 };
 
 #endif
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index c7506ef..d23254d 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -25,187 +25,174 @@
 #include <sys/uio.h>
 #include <syslog.h>
 
-#include <log/logger.h>
 #include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
 
 #include "LogBuffer.h"
 #include "LogKlog.h"
 #include "LogReader.h"
 
-#define KMSG_PRIORITY(PRI)           \
-    '<',                             \
-    '0' + (LOG_SYSLOG | (PRI)) / 10, \
-    '0' + (LOG_SYSLOG | (PRI)) % 10, \
-    '>'
+#define KMSG_PRIORITY(PRI) \
+    '<', '0' + (LOG_SYSLOG | (PRI)) / 10, '0' + (LOG_SYSLOG | (PRI)) % 10, '>'
 
 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)
-//  \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[] *[0-9]+[.][0-9]+[]] \)
+//  \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[]
+//  *[0-9]+[.][0-9]+[]] \)
 // and split if we see a second one without a newline.
 // We allow nuls in content, monitoring the overall length and sub-length of
 // the discovered tokens.
 
-#define SIGNATURE_MASK     0xF0
+#define SIGNATURE_MASK 0xF0
 // <digit> following ('0' to '9' masked with ~SIGNATURE_MASK) added to signature
-#define LESS_THAN_SIG      SIGNATURE_MASK
-#define OPEN_BRACKET_SIG   ((SIGNATURE_MASK << 1) & SIGNATURE_MASK)
+#define LESS_THAN_SIG SIGNATURE_MASK
+#define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK)
 // 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;
-            return tok;
-
-        case '<':
-            peek = is_prio(s, *len);
-            if (!peek) {
-                break;
-            }
-            if (s != (tok + 1)) { // not first?
+            case '\r':
+            case '\n':
                 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;
-            }
-            *sublen += adjust;
-            *len -= adjust;
-            s = peek;
-            if ((*s == '[') && ((peek = is_timestamp(s + 1, *len - 1)))) {
-                adjust = peek - s;
-                if (adjust > *len) {
-                    adjust = *len;
-                }
-                *sublen += adjust;
-                *len -= adjust;
-                s = peek;
-            }
-            break;
 
-        case '[':
-            peek = is_timestamp(s, *len);
-            if (!peek) {
-                break;
-            }
-            if (s != (tok + 1)) { // not first?
-                s[-1] = '\0';
-                if (*s == ' ') {
-                    *s = OPEN_BRACKET_SPACE;
-                } else {
+            case '<':
+                peek = is_prio(s, len);
+                if (!peek) break;
+                if (s != (tok + 1)) {  // not first?
+                    s[-1] = '\0';
                     *s &= ~SIGNATURE_MASK;
-                    *s |= OPEN_BRACKET_SIG; // signature for '['
+                    *s |= LESS_THAN_SIG;  // signature for '<'
+                    last = s;
+                    return tok;
                 }
-                *last = s;
-                return tok;
-            }
-            adjust = peek - s;
-            if (adjust > *len) {
-                adjust = *len;
-            }
-            *sublen += adjust;
-            *len -= adjust;
-            s = peek;
-            break;
+                adjust = peek - s;
+                if (adjust > len) {
+                    adjust = len;
+                }
+                sublen += adjust;
+                len -= adjust;
+                s = peek;
+                if ((*s == '[') && ((peek = is_timestamp(s + 1, len - 1)))) {
+                    adjust = peek - s;
+                    if (adjust > len) {
+                        adjust = len;
+                    }
+                    sublen += adjust;
+                    len -= adjust;
+                    s = peek;
+                }
+                break;
+
+            case '[':
+                peek = is_timestamp(s, len);
+                if (!peek) break;
+                if (s != (tok + 1)) {  // not first?
+                    s[-1] = '\0';
+                    if (*s == ' ') {
+                        *s = OPEN_BRACKET_SPACE;
+                    } else {
+                        *s &= ~SIGNATURE_MASK;
+                        *s |= OPEN_BRACKET_SIG;  // signature for '['
+                    }
+                    last = s;
+                    return tok;
+                }
+                adjust = peek - s;
+                if (adjust > len) {
+                    adjust = len;
+                }
+                sublen += adjust;
+                len -= adjust;
+                s = peek;
+                break;
         }
-        ++*sublen;
+        ++sublen;
     }
     // NOTREACHED
 }
@@ -215,22 +202,24 @@
         ? log_time::EPOCH
         : (log_time(CLOCK_REALTIME) - log_time(CLOCK_MONOTONIC));
 
-LogKlog::LogKlog(LogBuffer *buf, LogReader *reader, int fdWrite, int fdRead, bool auditd) :
-        SocketListener(fdRead, false),
-        logbuf(buf),
-        reader(reader),
-        signature(CLOCK_MONOTONIC),
-        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,
-        signature.nsec());
+LogKlog::LogKlog(LogBuffer* buf, LogReader* reader, int fdWrite, int fdRead,
+                 bool auditd)
+    : SocketListener(fdRead, false),
+      logbuf(buf),
+      reader(reader),
+      signature(CLOCK_MONOTONIC),
+      initialized(false),
+      enableLogging(true),
+      auditd(auditd) {
+    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));
 }
 
-bool LogKlog::onDataAvailable(SocketClient *cli) {
+bool LogKlog::onDataAvailable(SocketClient* cli) {
     if (!initialized) {
         prctl(PR_SET_NAME, "logd.klogd");
         initialized = true;
@@ -238,14 +227,15 @@
     }
 
     char buffer[LOGGER_ENTRY_MAX_PAYLOAD];
-    size_t len = 0;
+    ssize_t len = 0;
 
-    for(;;) {
+    for (;;) {
         ssize_t retval = 0;
-        if ((sizeof(buffer) - 1 - len) > 0) {
-            retval = read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len);
+        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) {
@@ -253,18 +243,18 @@
         }
         len += retval;
         bool full = len == (sizeof(buffer) - 1);
-        char *ep = buffer + len;
+        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,12 +263,13 @@
     return true;
 }
 
+void LogKlog::calculateCorrection(const log_time& monotonic,
+                                  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;
 
-void LogKlog::calculateCorrection(const log_time &monotonic,
-                                  const char *real_string,
-                                  size_t len) {
     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;
     }
@@ -302,78 +293,50 @@
     }
 }
 
-static const char suspendStr[] = "PM: suspend entry ";
-static const char resumeStr[] = "PM: suspend exit ";
-static const char suspendedStr[] = "Suspended for ";
-
-static const char *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 (fast<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 = strnstr(cp, len, suspendStr)))
-                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {
+        const char* b;
+        if (((b = android::strnstr(cp, len, suspendStr))) &&
+            (((b += strlen(suspendStr)) - cp) < len)) {
             len -= b - cp;
             calculateCorrection(now, b, len);
-        } else if (((b = strnstr(cp, len, resumeStr)))
-                && ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) {
+        } else if (((b = android::strnstr(cp, len, resumeStr))) &&
+                   (((b += strlen(resumeStr)) - cp) < len)) {
             len -= b - cp;
             calculateCorrection(now, b, len);
-        } else if (((b = strnstr(cp, len, healthd)))
-                && ((size_t)((b += sizeof(healthd) - 1) - cp) < len)
-                && ((b = 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 = strnstr(cp, len, suspendedStr)))
-                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {
+        } else if (((b = android::strnstr(cp, len, suspendedStr))) &&
+                   (((b += strlen(suspendStr)) - cp) < len)) {
             len -= b - cp;
             log_time real;
-            char *endp;
+            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;
@@ -402,14 +365,18 @@
     }
 }
 
-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] == ' ')) {
+    if ((len > 9) && (cp[0] == 'c') && isdigit(cp[1]) &&
+        (isdigit(cp[2]) || (cp[2] == ' ')) && (cp[3] == ' ')) {
         bool gotDigit = false;
         int i;
         for (i = 4; i < 9; ++i) {
@@ -423,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;
             }
         }
@@ -436,7 +403,7 @@
             if (sscanf(cp, "[%d:%*[a-z_./0-9:A-Z]]%c", &pid, &dummy) == 2) {
                 return pid;
             }
-            break; // Only the first one
+            break;  // Only the first one
         }
         ++cp;
         --len;
@@ -445,39 +412,35 @@
 }
 
 // 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)) {
+        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) {
-    const char *cp = strnstr(buf, len, suspendStr);
+void LogKlog::synchronize(const char* buf, ssize_t len) {
+    const char* cp = android::strnstr(buf, len, suspendStr);
     if (!cp) {
-        cp = strnstr(buf, len, resumeStr);
-        if (!cp) {
-            return;
-        }
+        cp = android::strnstr(buf, len, resumeStr);
+        if (!cp) return;
     } else {
-        const char *rp = strnstr(buf, len, resumeStr);
-        if (rp && (rp < cp)) {
-            cp = rp;
-        }
+        const char* rp = android::strnstr(buf, len, resumeStr);
+        if (rp && (rp < cp)) cp = rp;
     }
 
     do {
@@ -486,12 +449,12 @@
     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 = strnstr(buf, len, suspendedStr);
+    const char* suspended = android::strnstr(buf, len, suspendedStr);
     if (!suspended || (suspended > cp)) {
         return;
     }
@@ -503,49 +466,49 @@
     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
 static int convertKernelPrioToAndroidPrio(int pri) {
-    switch(pri & LOG_PRIMASK) {
-    case LOG_EMERG:
+    switch (pri & LOG_PRIMASK) {
+        case LOG_EMERG:
         // FALLTHRU
-    case LOG_ALERT:
+        case LOG_ALERT:
         // FALLTHRU
-    case LOG_CRIT:
-        return ANDROID_LOG_FATAL;
+        case LOG_CRIT:
+            return ANDROID_LOG_FATAL;
 
-    case LOG_ERR:
-        return ANDROID_LOG_ERROR;
+        case LOG_ERR:
+            return ANDROID_LOG_ERROR;
 
-    case LOG_WARNING:
-        return ANDROID_LOG_WARN;
+        case LOG_WARNING:
+            return ANDROID_LOG_WARN;
 
-    default:
+        default:
         // FALLTHRU
-    case LOG_NOTICE:
+        case LOG_NOTICE:
         // FALLTHRU
-    case LOG_INFO:
-        break;
+        case LOG_INFO:
+            break;
 
-    case LOG_DEBUG:
-        return ANDROID_LOG_DEBUG;
+        case LOG_DEBUG:
+            return ANDROID_LOG_DEBUG;
     }
 
     return ANDROID_LOG_INFO;
 }
 
-static const char *strnrchr(const char *s, size_t len, char c) {
-  const char *save = NULL;
-  for (;len; ++s, len--) {
-    if (*s == c) {
-      save = s;
+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;
+        }
     }
-  }
-  return save;
+    return save;
 }
 
 //
@@ -581,22 +544,21 @@
 //  logd.klogd:
 // return -1 if message logd.klogd: <signature>
 //
-int LogKlog::log(const char *buf, size_t len) {
-    if (auditd && 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);
+    const char* p = buf;
+    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 = 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;
@@ -613,7 +575,7 @@
     }
 
     // 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) {
@@ -629,42 +591,45 @@
     while ((p < &buf[len]) && (isspace(*p) || !*p)) {
         ++p;
     }
-    if (p >= &buf[len]) { // timestamp, no content
+    if (p >= &buf[len]) {  // timestamp, no content
         return 0;
     }
     start = p;
-    const char *tag = "";
-    const char *etag = tag;
-    size_t taglen = len - (p - buf);
-    const char *bt = p;
+    const char* tag = "";
+    const char* etag = tag;
+    ssize_t taglen = len - (p - buf);
+    const char* bt = p;
 
     static const char infoBrace[] = "[INFO]";
-    static const size_t infoBraceLen = strlen(infoBrace);
-    if ((taglen >= infoBraceLen) && !fast<strncmp>(p, infoBrace, infoBraceLen)) {
+    static const ssize_t infoBraceLen = strlen(infoBrace);
+    if ((taglen >= infoBraceLen) &&
+        !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) {
         // <PRI>[<TIME>] "[INFO]"<tag> ":" message
         bt = p + infoBraceLen;
         taglen -= infoBraceLen;
     }
 
-    const char *et;
-    for (et = bt; taglen && *et && (*et != ':') && !isspace(*et); ++et, --taglen) {
-       // skip ':' within [ ... ]
-       if (*et == '[') {
-           while (taglen && *et && *et != ']') {
-               ++et;
-               --taglen;
-           }
-           if (!taglen) {
-               break;
-           }
-       }
+    const char* et;
+    for (et = bt; (taglen > 0) && *et && (*et != ':') && !isspace(*et);
+         ++et, --taglen) {
+        // skip ':' within [ ... ]
+        if (*et == '[') {
+            while ((taglen > 0) && *et && *et != ']') {
+                ++et;
+                --taglen;
+            }
+            if (taglen <= 0) {
+                break;
+            }
+        }
     }
-    const char *cp;
-    for (cp = et; taglen && isspace(*cp); ++cp, --taglen);
+    const char* cp;
+    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>: ...
@@ -675,19 +640,21 @@
             p = cp + 1;
         } else if ((taglen > size) && (tolower(*bt) == tolower(*cp))) {
             // clean up any tag stutter
-            if (!fast<strncasecmp>(bt + 1, cp + 1, size - 1)) { // no match
+            if (!fastcmp<strncasecmp>(bt + 1, cp + 1, size - 1)) {  // no match
                 // <PRI>[<TIME>] <tag> <tag> : message
                 // <PRI>[<TIME>] <tag> <tag>: message
                 // <PRI>[<TIME>] <tag> '<tag>.<num>' : message
                 // <PRI>[<TIME>] <tag> '<tag><num>' : message
                 // <PRI>[<TIME>] <tag> '<tag><stuff>' : message
-                const char *b = cp;
+                const char* b = cp;
                 cp += size;
                 taglen -= size;
-                while (--taglen && !isspace(*++cp) && (*cp != ':'));
-                const char *e;
-                for (e = cp; taglen && isspace(*cp); ++cp, --taglen);
-                if (taglen && (*cp == ':')) {
+                while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
+                }
+                const char* e;
+                for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
+                }
+                if ((taglen > 0) && (*cp == ':')) {
                     tag = b;
                     etag = e;
                     p = cp + 1;
@@ -695,18 +662,22 @@
             } 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) &&
-                        !fast<strncmp>(bt + size - hostlen, host, hostlen) &&
-                        !fast<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
-                    const char *b = cp;
+                    !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) &&
+                    !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
+                    const char* b = cp;
                     cp += size - hostlen;
                     taglen -= size - hostlen;
                     if (*cp == '.') {
-                        while (--taglen && !isspace(*++cp) && (*cp != ':'));
-                        const char *e;
-                        for (e = cp; taglen && isspace(*cp); ++cp, --taglen);
-                        if (taglen && (*cp == ':')) {
+                        while ((--taglen > 0) && !isspace(*++cp) &&
+                               (*cp != ':')) {
+                        }
+                        const char* e;
+                        for (e = cp; (taglen > 0) && isspace(*cp);
+                             ++cp, --taglen) {
+                        }
+                        if ((taglen > 0) && (*cp == ':')) {
                             tag = b;
                             etag = e;
                             p = cp + 1;
@@ -717,39 +688,43 @@
                 }
             }
         } else {
-            // <PRI>[<TIME>] <tag> <stuff>' : message
-twoWord:    while (--taglen && !isspace(*++cp) && (*cp != ':'));
-            const char *e;
-            for (e = cp; taglen && isspace(*cp); ++cp, --taglen);
+        // <PRI>[<TIME>] <tag> <stuff>' : message
+        twoWord:
+            while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
+            }
+            const char* e;
+            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;
             }
         }
-    } // else no tag
+    }  // 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)
+    if ((size <= 1) ||
         // register names like x9
-            || ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1])))
+        ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1]))) ||
         // register names like x18 but not driver names like en0
-            || ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2])))
+        ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2]))) ||
         // blacklist
-            || ((size == cpuLen) && !fast<strncmp>(tag, cpu, cpuLen))
-            || ((size == warningLen) && !fast<strncasecmp>(tag, warning, warningLen))
-            || ((size == errorLen) && !fast<strncasecmp>(tag, error, errorLen))
-            || ((size == infoLen) && !fast<strncasecmp>(tag, info, infoLen))) {
+        ((size == cpuLen) && !fastcmp<strncmp>(tag, cpu, cpuLen)) ||
+        ((size == warningLen) &&
+         !fastcmp<strncasecmp>(tag, warning, warningLen)) ||
+        ((size == errorLen) && !fastcmp<strncasecmp>(tag, error, errorLen)) ||
+        ((size == infoLen) && !fastcmp<strncasecmp>(tag, info, infoLen))) {
         p = start;
         etag = tag = "";
     }
@@ -758,15 +733,15 @@
     //   eg: [143:healthd]healthd -> [143:healthd]
     taglen = etag - tag;
     // Mediatek-special printk induced stutter
-    const char *mp = strnrchr(tag, ']', taglen);
+    const char* mp = strnrchr(tag, taglen, ']');
     if (mp && (++mp < etag)) {
-        size_t s = etag - mp;
-        if (((s + s) < taglen) && !fast<memcmp>(mp, mp - 1 - s, s)) {
+        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
@@ -774,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;
     }
@@ -791,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;
     }
 
@@ -804,7 +779,7 @@
     // truncating length argument to logbuf->log() below. Gain is protection
     // of stack sanity and speedup, loss is truncated long-line content.
     char newstr[n];
-    char *np = newstr;
+    char* np = newstr;
 
     // Convert priority into single-byte Android logger priority
     *np = convertKernelPrioToAndroidPrio(pri);
@@ -836,10 +811,10 @@
             unsigned abs0 = (diff0 < 0) ? -diff0 : diff0;
             int diff1 = (vote_time[1] - vote_time[2]) / near_seconds;
             unsigned abs1 = (diff1 < 0) ? -diff1 : diff1;
-            if ((abs1 <= 1) && // last two were in agreement on timezone
-                    ((abs0 + 1) % (timezones_seconds / near_seconds)) <= 2) {
+            if ((abs1 <= 1) &&  // last two were in agreement on timezone
+                ((abs0 + 1) % (timezones_seconds / near_seconds)) <= 2) {
                 abs0 = (abs0 + 1) / (timezones_seconds / near_seconds) *
-                                     timezones_seconds;
+                       timezones_seconds;
                 now.tv_sec -= (diff0 < 0) ? -abs0 : abs0;
             }
         }
@@ -847,7 +822,7 @@
 
     // Log message
     int rc = logbuf->log(LOG_ID_KERNEL, now, uid, pid, tid, newstr,
-                         (unsigned short) n);
+                         (unsigned short)n);
 
     // notify readers
     if (!rc) {
diff --git a/logd/LogKlog.h b/logd/LogKlog.h
index a4f871e..bb92dd2 100644
--- a/logd/LogKlog.h
+++ b/logd/LogKlog.h
@@ -17,17 +17,15 @@
 #ifndef _LOGD_LOG_KLOG_H__
 #define _LOGD_LOG_KLOG_H__
 
+#include <private/android_logger.h>
 #include <sysutils/SocketListener.h>
-#include <log/log_read.h>
-
-char *log_strntok_r(char *s, size_t *len, char **saveptr, size_t *sublen);
 
 class LogBuffer;
 class LogReader;
 
 class LogKlog : public SocketListener {
-    LogBuffer *logbuf;
-    LogReader *reader;
+    LogBuffer* logbuf;
+    LogReader* reader;
     const log_time signature;
     // Set once thread is started, separates KLOG_ACTION_READ_ALL
     // and KLOG_ACTION_READ phases.
@@ -40,22 +38,28 @@
 
     static log_time correction;
 
-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);
+   public:
+    LogKlog(LogBuffer* buf, LogReader* reader, int fdWrite, int fdRead,
+            bool auditd);
+    int log(const char* buf, ssize_t len);
+    void synchronize(const char* buf, ssize_t len);
 
-    bool isMonotonic() { return logbuf->isMonotonic(); }
-    static void convertMonotonicToReal(log_time &real) { real += correction; }
-    static void convertRealToMonotonic(log_time &real) { real -= correction; }
+    bool isMonotonic() {
+        return logbuf->isMonotonic();
+    }
+    static void convertMonotonicToReal(log_time& real) {
+        real += correction;
+    }
+    static void convertRealToMonotonic(log_time& real) {
+        real -= correction;
+    }
 
-protected:
-    void sniffTime(log_time &now, const char **buf, size_t len, bool reverse);
-    pid_t sniffPid(const char **buf, size_t len);
-    void calculateCorrection(const log_time &monotonic,
-                             const char *real_string, size_t len);
-    virtual bool onDataAvailable(SocketClient *cli);
-
+   protected:
+    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,
+                             ssize_t len);
+    virtual bool onDataAvailable(SocketClient* cli);
 };
 
 #endif
diff --git a/logd/LogListener.cpp b/logd/LogListener.cpp
index 39dd227..dadc75f 100644
--- a/logd/LogListener.cpp
+++ b/logd/LogListener.cpp
@@ -23,7 +23,6 @@
 #include <unistd.h>
 
 #include <cutils/sockets.h>
-#include <log/logger.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
@@ -31,32 +30,24 @@
 #include "LogListener.h"
 #include "LogUtils.h"
 
-LogListener::LogListener(LogBuffer *buf, LogReader *reader) :
-        SocketListener(getLogSocket(), false),
-        logbuf(buf),
-        reader(reader) {
+LogListener::LogListener(LogBuffer* buf, LogReader* reader)
+    : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {
 }
 
-bool LogListener::onDataAvailable(SocketClient *cli) {
+bool LogListener::onDataAvailable(SocketClient* cli) {
     static bool name_set;
     if (!name_set) {
         prctl(PR_SET_NAME, "logd.writer");
         name_set = true;
     }
 
-    char buffer[sizeof_log_id_t + sizeof(uint16_t) + sizeof(log_time)
-        + LOGGER_ENTRY_MAX_PAYLOAD];
+    char buffer[sizeof_log_id_t + sizeof(uint16_t) + sizeof(log_time) +
+                LOGGER_ENTRY_MAX_PAYLOAD];
     struct iovec iov = { buffer, sizeof(buffer) };
 
-    char control[CMSG_SPACE(sizeof(struct ucred))] __aligned(4);
+    alignas(4) char control[CMSG_SPACE(sizeof(struct ucred))];
     struct msghdr hdr = {
-        NULL,
-        0,
-        &iov,
-        1,
-        control,
-        sizeof(control),
-        0,
+        NULL, 0, &iov, 1, control, sizeof(control), 0,
     };
 
     int socket = cli->getSocket();
@@ -69,13 +60,13 @@
         return false;
     }
 
-    struct ucred *cred = NULL;
+    struct ucred* cred = NULL;
 
-    struct cmsghdr *cmsg = CMSG_FIRSTHDR(&hdr);
+    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
     while (cmsg != NULL) {
-        if (cmsg->cmsg_level == SOL_SOCKET
-                && cmsg->cmsg_type  == SCM_CREDENTIALS) {
-            cred = (struct ucred *)CMSG_DATA(cmsg);
+        if (cmsg->cmsg_level == SOL_SOCKET &&
+            cmsg->cmsg_type == SCM_CREDENTIALS) {
+            cred = (struct ucred*)CMSG_DATA(cmsg);
             break;
         }
         cmsg = CMSG_NXTHDR(&hdr, cmsg);
@@ -92,26 +83,29 @@
         return false;
     }
 
-    android_log_header_t *header = reinterpret_cast<android_log_header_t *>(buffer);
-    if (/* header->id < LOG_ID_MIN || */ header->id >= LOG_ID_MAX || header->id == LOG_ID_KERNEL) {
+    android_log_header_t* header =
+        reinterpret_cast<android_log_header_t*>(buffer);
+    if (/* header->id < LOG_ID_MIN || */ header->id >= LOG_ID_MAX ||
+        header->id == LOG_ID_KERNEL) {
         return false;
     }
 
     if ((header->id == LOG_ID_SECURITY) &&
-            (!__android_log_security() ||
-             !clientHasLogCredentials(cred->uid, cred->gid, cred->pid))) {
+        (!__android_log_security() ||
+         !clientHasLogCredentials(cred->uid, cred->gid, cred->pid))) {
         return false;
     }
 
-    char *msg = ((char *)buffer) + sizeof(android_log_header_t);
+    char* msg = ((char*)buffer) + sizeof(android_log_header_t);
     n -= sizeof(android_log_header_t);
 
     // 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) {
+    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();
     }
 
@@ -123,9 +117,8 @@
     int sock = android_get_control_socket(socketName);
 
     if (sock < 0) {
-        sock = socket_local_server(socketName,
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                   SOCK_DGRAM);
+        sock = socket_local_server(
+            socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_DGRAM);
     }
 
     int on = 1;
diff --git a/logd/LogListener.h b/logd/LogListener.h
index 7099e13..2973b8b 100644
--- a/logd/LogListener.h
+++ b/logd/LogListener.h
@@ -21,16 +21,16 @@
 #include "LogReader.h"
 
 class LogListener : public SocketListener {
-    LogBuffer *logbuf;
-    LogReader *reader;
+    LogBuffer* logbuf;
+    LogReader* reader;
 
-public:
-    LogListener(LogBuffer *buf, LogReader *reader);
+   public:
+    LogListener(LogBuffer* buf, LogReader* reader);
 
-protected:
-    virtual bool onDataAvailable(SocketClient *cli);
+   protected:
+    virtual bool onDataAvailable(SocketClient* cli);
 
-private:
+   private:
     static int getLogSocket();
 };
 
diff --git a/logd/LogReader.cpp b/logd/LogReader.cpp
index 2c07984..af19279 100644
--- a/logd/LogReader.cpp
+++ b/logd/LogReader.cpp
@@ -21,6 +21,7 @@
 #include <sys/types.h>
 
 #include <cutils/sockets.h>
+#include <private/android_logger.h>
 
 #include "FlushCommand.h"
 #include "LogBuffer.h"
@@ -28,9 +29,8 @@
 #include "LogReader.h"
 #include "LogUtils.h"
 
-LogReader::LogReader(LogBuffer *logbuf) :
-        SocketListener(getLogSocket(), true),
-        mLogbuf(*logbuf) {
+LogReader::LogReader(LogBuffer* logbuf)
+    : SocketListener(getLogSocket(), true), mLogbuf(*logbuf) {
 }
 
 // When we are notified a new log entry is available, inform
@@ -40,7 +40,7 @@
     runOnEachSocket(&command);
 }
 
-bool LogReader::onDataAvailable(SocketClient *cli) {
+bool LogReader::onDataAvailable(SocketClient* cli) {
     static bool name_set;
     if (!name_set) {
         prctl(PR_SET_NAME, "logd.reader");
@@ -58,7 +58,7 @@
 
     unsigned long tail = 0;
     static const char _tail[] = " tail=";
-    char *cp = strstr(buffer, _tail);
+    char* cp = strstr(buffer, _tail);
     if (cp) {
         tail = atol(cp + sizeof(_tail) - 1);
     }
@@ -107,7 +107,7 @@
     }
 
     bool nonBlock = false;
-    if (!fast<strncmp>(buffer, "dumpAndClose", 12)) {
+    if (!fastcmp<strncmp>(buffer, "dumpAndClose", 12)) {
         // Allow writer to get some cycles, and wait for pending notifications
         sched_yield();
         LogTimeEntry::lock();
@@ -116,66 +116,79 @@
         nonBlock = true;
     }
 
-    uint64_t sequence = 1;
-    // Convert realtime to sequence number
-    if (start != log_time::EPOCH) {
-        class LogFindStart {
+    log_time sequence = start;
+    //
+    // This somewhat expensive data validation operation is required
+    // for non-blocking, with timeout.  The incoming timestamp must be
+    // in range of the list, if not, return immediately.  This is
+    // used to prevent us from from getting stuck in timeout processing
+    // with an invalid time.
+    //
+    // Find if time is really present in the logs, monotonic or real, implicit
+    // conversion from monotonic or real as necessary to perform the check.
+    // Exit in the check loop ASAP as you find a transition from older to
+    // newer, but use the last entry found to ensure overlap.
+    //
+    if (nonBlock && (sequence != log_time::EPOCH) && timeout) {
+        class LogFindStart {  // A lambda by another name
+           private:
             const pid_t mPid;
             const unsigned mLogMask;
-            bool startTimeSet;
-            log_time &start;
-            uint64_t &sequence;
-            uint64_t last;
-            bool isMonotonic;
+            bool mStartTimeSet;
+            log_time mStart;
+            log_time& mSequence;
+            log_time mLast;
+            bool mIsMonotonic;
 
-        public:
-            LogFindStart(unsigned logMask, pid_t pid, log_time &start, uint64_t &sequence, bool isMonotonic) :
-                    mPid(pid),
-                    mLogMask(logMask),
-                    startTimeSet(false),
-                    start(start),
-                    sequence(sequence),
-                    last(sequence),
-                    isMonotonic(isMonotonic) {
+           public:
+            LogFindStart(pid_t pid, unsigned logMask, log_time& sequence,
+                         bool isMonotonic)
+                : mPid(pid),
+                  mLogMask(logMask),
+                  mStartTimeSet(false),
+                  mStart(sequence),
+                  mSequence(sequence),
+                  mLast(sequence),
+                  mIsMonotonic(isMonotonic) {
             }
 
-            static int callback(const LogBufferElement *element, void *obj) {
-                LogFindStart *me = reinterpret_cast<LogFindStart *>(obj);
-                if ((!me->mPid || (me->mPid == element->getPid()))
-                        && (me->mLogMask & (1 << element->getLogId()))) {
-                    if (me->start == element->getRealTime()) {
-                        me->sequence = element->getSequence();
-                        me->startTimeSet = true;
+            static int callback(const LogBufferElement* element, void* obj) {
+                LogFindStart* me = reinterpret_cast<LogFindStart*>(obj);
+                if ((!me->mPid || (me->mPid == element->getPid())) &&
+                    (me->mLogMask & (1 << element->getLogId()))) {
+                    log_time real = element->getRealTime();
+                    if (me->mStart == real) {
+                        me->mSequence = real;
+                        me->mStartTimeSet = true;
                         return -1;
-                    } else if (!me->isMonotonic ||
-                            android::isMonotonic(element->getRealTime())) {
-                        if (me->start < element->getRealTime()) {
-                            me->sequence = me->last;
-                            me->startTimeSet = true;
+                    } else if (!me->mIsMonotonic || android::isMonotonic(real)) {
+                        if (me->mStart < real) {
+                            me->mSequence = me->mLast;
+                            me->mStartTimeSet = true;
                             return -1;
                         }
-                        me->last = element->getSequence();
+                        me->mLast = real;
                     } else {
-                        me->last = element->getSequence();
+                        me->mLast = real;
                     }
                 }
                 return false;
             }
 
-            bool found() { return startTimeSet; }
-        } logFindStart(logMask, pid, start, sequence,
+            bool found() {
+                return mStartTimeSet;
+            }
+
+        } 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);
 
         if (!logFindStart.found()) {
-            if (nonBlock) {
-                doSocketDelete(cli);
-                return false;
-            }
-            sequence = LogBufferElement::getCurrentSequence();
+            doSocketDelete(cli);
+            return false;
         }
     }
 
@@ -183,18 +196,19 @@
 
     // Set acceptable upper limit to wait for slow reader processing b/27242723
     struct timeval t = { LOGD_SNDTIMEO, 0 };
-    setsockopt(cli->getSocket(), SOL_SOCKET, SO_SNDTIMEO, (const char *)&t, sizeof(t));
+    setsockopt(cli->getSocket(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&t,
+               sizeof(t));
 
     command.runSocketCommand(cli);
     return true;
 }
 
-void LogReader::doSocketDelete(SocketClient *cli) {
-    LastLogTimes &times = mLogbuf.mTimes;
+void LogReader::doSocketDelete(SocketClient* cli) {
+    LastLogTimes& times = mLogbuf.mTimes;
     LogTimeEntry::lock();
     LastLogTimes::iterator it = times.begin();
-    while(it != times.end()) {
-        LogTimeEntry *entry = (*it);
+    while (it != times.end()) {
+        LogTimeEntry* entry = (*it);
         if (entry->mClient == cli) {
             times.erase(it);
             entry->release_Locked();
@@ -210,9 +224,8 @@
     int sock = android_get_control_socket(socketName);
 
     if (sock < 0) {
-        sock = socket_local_server(socketName,
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                   SOCK_SEQPACKET);
+        sock = socket_local_server(
+            socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET);
     }
 
     return sock;
diff --git a/logd/LogReader.h b/logd/LogReader.h
index 98674b8..271e08c 100644
--- a/logd/LogReader.h
+++ b/logd/LogReader.h
@@ -24,22 +24,23 @@
 class LogBuffer;
 
 class LogReader : public SocketListener {
-    LogBuffer &mLogbuf;
+    LogBuffer& mLogbuf;
 
-public:
-    LogReader(LogBuffer *logbuf);
+   public:
+    explicit LogReader(LogBuffer* logbuf);
     void notifyNewLog();
 
-    LogBuffer &logbuf(void) const { return mLogbuf; }
+    LogBuffer& logbuf(void) const {
+        return mLogbuf;
+    }
 
-protected:
-    virtual bool onDataAvailable(SocketClient *cli);
+   protected:
+    virtual bool onDataAvailable(SocketClient* cli);
 
-private:
+   private:
     static int getLogSocket();
 
-    void doSocketDelete(SocketClient *cli);
-
+    void doSocketDelete(SocketClient* cli);
 };
 
 #endif
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 2b02bc1..cc30f77 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -15,14 +15,20 @@
  */
 
 #include <fcntl.h>
+#include <pwd.h>
 #include <stdio.h>
 #include <string.h>
+#include <sys/types.h>
 #include <unistd.h>
 
-#include <log/logger.h>
+#include <list>
+
+#include <android/log.h>
 
 #include "LogStatistics.h"
 
+size_t LogStatistics::SizesTotal;
+
 LogStatistics::LogStatistics() : enable(false) {
     log_id_for_each(id) {
         mSizes[id] = 0;
@@ -35,10 +41,14 @@
 
 namespace android {
 
+size_t sizesTotal() {
+    return LogStatistics::sizesTotal();
+}
+
 // caller must own and free character string
-char *pidToName(pid_t pid) {
-    char *retval = NULL;
-    if (pid == 0) { // special case from auditd/klogd for kernel
+char* pidToName(pid_t pid) {
+    char* retval = NULL;
+    if (pid == 0) {  // special case from auditd/klogd for kernel
         retval = strdup("logd");
     } else {
         char buffer[512];
@@ -47,9 +57,9 @@
         if (fd >= 0) {
             ssize_t ret = read(fd, buffer, sizeof(buffer));
             if (ret > 0) {
-                buffer[sizeof(buffer)-1] = '\0';
+                buffer[sizeof(buffer) - 1] = '\0';
                 // frameworks intermediate state
-                if (fast<strcmp>(buffer, "<pre-initialized>")) {
+                if (fastcmp<strcmp>(buffer, "<pre-initialized>")) {
                     retval = strdup(buffer);
                 }
             }
@@ -58,17 +68,26 @@
     }
     return retval;
 }
-
 }
 
-void LogStatistics::add(LogBufferElement *element) {
+void LogStatistics::add(LogBufferElement* element) {
     log_id_t log_id = element->getLogId();
     unsigned short size = element->getMsgLen();
     mSizes[log_id] += size;
     ++mElements[log_id];
 
-    mSizesTotal[log_id] += size;
-    ++mElementsTotal[log_id];
+    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];
+    }
 
     if (log_id == LOG_ID_KERNEL) {
         return;
@@ -96,7 +115,7 @@
     }
 }
 
-void LogStatistics::subtract(LogBufferElement *element) {
+void LogStatistics::subtract(LogBufferElement* element) {
     log_id_t log_id = element->getLogId();
     unsigned short size = element->getMsgLen();
     mSizes[log_id] -= size;
@@ -133,7 +152,7 @@
 
 // Atomically set an entry to drop
 // entry->setDropped(1) must follow this call, caller should do this explicitly.
-void LogStatistics::drop(LogBufferElement *element) {
+void LogStatistics::drop(LogBufferElement* element) {
     log_id_t log_id = element->getLogId();
     unsigned short size = element->getMsgLen();
     mSizes[log_id] -= size;
@@ -150,28 +169,36 @@
 
     pidTable.drop(element->getPid(), element);
     tidTable.drop(element->getTid(), element);
+
+    uint32_t tag = element->getTag();
+    if (tag) {
+        if (log_id == LOG_ID_SECURITY) {
+            securityTagTable.drop(tag, element);
+        } else {
+            tagTable.drop(tag, element);
+        }
+    }
 }
 
 // caller must own and free character string
-const char *LogStatistics::uidToName(uid_t uid) const {
+const char* LogStatistics::uidToName(uid_t uid) const {
     // Local hard coded favourites
     if (uid == AID_LOGD) {
         return strdup("auditd");
     }
 
-    // Android hard coded
-    const struct android_id_info *info = android_ids;
-
-    for (size_t i = 0; i < android_id_count; ++i) {
-        if (info->aid == uid) {
-            return strdup(info->name);
+    // Android system
+    if (uid < AID_APP) {
+        // in bionic, thread safe as long as we copy the results
+        struct passwd* pwd = getpwuid(uid);
+        if (pwd) {
+            return strdup(pwd->pw_name);
         }
-        ++info;
     }
 
     // Parse /data/system/packages.list
-    uid_t userId = uid % AID_USER;
-    const char *name = android::uidToName(userId);
+    uid_t userId = uid % AID_USER_OFFSET;
+    const char* name = android::uidToName(userId);
     if (!name && (userId > (AID_SHARED_GID_START - AID_APP))) {
         name = android::uidToName(userId - (AID_SHARED_GID_START - AID_APP));
     }
@@ -179,18 +206,27 @@
         return name;
     }
 
+    // Android application
+    if (uid >= AID_APP) {
+        struct passwd* pwd = getpwuid(uid);
+        if (pwd) {
+            return strdup(pwd->pw_name);
+        }
+    }
+
     // report uid -> pid(s) -> pidToName if unique
-    for(pidTable_t::const_iterator it = pidTable.begin(); it != pidTable.end(); ++it) {
-        const PidEntry &entry = it->second;
+    for (pidTable_t::const_iterator it = pidTable.begin(); it != pidTable.end();
+         ++it) {
+        const PidEntry& entry = it->second;
 
         if (entry.getUid() == uid) {
-            const char *nameTmp = entry.getName();
+            const char* nameTmp = entry.getName();
 
             if (nameTmp) {
                 if (!name) {
                     name = strdup(nameTmp);
-                } else if (fast<strcmp>(name, nameTmp)) {
-                    free(const_cast<char *>(name));
+                } else if (fastcmp<strcmp>(name, nameTmp)) {
+                    free(const_cast<char*>(name));
                     name = NULL;
                     break;
                 }
@@ -202,26 +238,24 @@
     return name;
 }
 
-std::string UidEntry::formatHeader(const std::string &name, log_id_t id) const {
+std::string UidEntry::formatHeader(const std::string& name, log_id_t id) const {
     bool isprune = worstUidEnabledForLogid(id);
-    return formatLine(android::base::StringPrintf(
-                          name.c_str(), android_log_id_to_name(id)),
+    return formatLine(android::base::StringPrintf(name.c_str(),
+                                                  android_log_id_to_name(id)),
                       std::string("Size"),
-                      std::string(isprune ? "+/-  Pruned" : ""))
-         + formatLine(std::string("UID   PACKAGE"),
-                      std::string("BYTES"),
+                      std::string(isprune ? "+/-  Pruned" : "")) +
+           formatLine(std::string("UID   PACKAGE"), std::string("BYTES"),
                       std::string(isprune ? "NUM" : ""));
 }
 
-std::string UidEntry::format(const LogStatistics &stat, log_id_t id) const {
+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);
+    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));
+            "%*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());
@@ -229,15 +263,16 @@
     std::string pruned = "";
     if (worstUidEnabledForLogid(id)) {
         size_t totalDropped = 0;
-        for (LogStatistics::uidTable_t::const_iterator it = stat.uidTable[id].begin();
-                it != stat.uidTable[id].end(); ++it) {
+        for (LogStatistics::uidTable_t::const_iterator it =
+                 stat.uidTable[id].begin();
+             it != stat.uidTable[id].end(); ++it) {
             totalDropped += it->second.getDropped();
         }
         size_t sizes = stat.sizes(id);
         size_t totalSize = stat.sizesTotal(id);
         size_t totalElements = stat.elementsTotal(id);
-        float totalVirtualSize = (float)sizes + (float)totalDropped * totalSize
-                                / totalElements;
+        float totalVirtualSize =
+            (float)sizes + (float)totalDropped * totalSize / totalElements;
         size_t entrySize = getSizes();
         float virtualEntrySize = entrySize;
         int realPermille = virtualEntrySize * 1000.0 / sizes;
@@ -247,31 +282,29 @@
             virtualEntrySize += (float)dropped * totalSize / totalElements;
         }
         int virtualPermille = virtualEntrySize * 1000.0 / totalVirtualSize;
-        int permille = (realPermille - virtualPermille) * 1000L
-                     / (virtualPermille ?: 1);
+        int permille =
+            (realPermille - virtualPermille) * 1000L / (virtualPermille ?: 1);
         if ((permille < -1) || (1 < permille)) {
             std::string change;
-            const char *units = "%";
-            const char *prefix = (permille > 0) ? "+" : "";
+            const char* units = "%";
+            const char* prefix = (permille > 0) ? "+" : "";
 
             if (permille > 999) {
-                permille = (permille + 1000) / 100; // Now tenths fold
+                permille = (permille + 1000) / 100;  // Now tenths fold
                 units = "X";
                 prefix = "";
             }
             if ((-99 < permille) && (permille < 99)) {
-                change = android::base::StringPrintf("%s%d.%u%s",
-                    prefix,
-                    permille / 10,
+                change = android::base::StringPrintf(
+                    "%s%d.%u%s", prefix, permille / 10,
                     ((permille < 0) ? (-permille % 10) : (permille % 10)),
                     units);
             } else {
-                change = android::base::StringPrintf("%s%d%s",
-                    prefix,
-                    (permille + 5) / 10, units);
+                change = android::base::StringPrintf(
+                    "%s%d%s", prefix, (permille + 5) / 10, units);
             }
-            ssize_t spaces = EntryBaseConstants::pruned_len
-                           - 2 - pruned.length() - change.length();
+            ssize_t spaces = EntryBaseConstants::pruned_len - 2 -
+                             pruned.length() - change.length();
             if ((spaces <= 0) && pruned.length()) {
                 spaces = 1;
             }
@@ -289,8 +322,8 @@
     }
 
     static const size_t maximum_sorted_entries = 32;
-    std::unique_ptr<const PidEntry *[]> sorted
-        = stat.pidSystemTable[id].sort(uid, (pid_t)0, maximum_sorted_entries);
+    std::unique_ptr<const PidEntry* []> sorted =
+        stat.pidSystemTable[id].sort(uid, (pid_t)0, maximum_sorted_entries);
 
     if (!sorted.get()) {
         return output;
@@ -299,7 +332,7 @@
     size_t index;
     bool hasDropped = false;
     for (index = 0; index < maximum_sorted_entries; ++index) {
-        const PidEntry *entry = sorted[index];
+        const PidEntry* entry = sorted[index];
         if (!entry) {
             break;
         }
@@ -311,43 +344,39 @@
         }
         byPid += entry->format(stat, id);
     }
-    if (index > 1) { // print this only if interesting
+    if (index > 1) {  // print this only if interesting
         std::string ditto("\" ");
-        output += formatLine(std::string("  PID/UID   COMMAND LINE"),
-                             ditto, hasDropped ? ditto : std::string(""));
+        output += formatLine(std::string("  PID/UID   COMMAND LINE"), ditto,
+                             hasDropped ? ditto : std::string(""));
         output += byPid;
     }
 
     return output;
 }
 
-std::string PidEntry::formatHeader(const std::string &name, log_id_t /* id */) const {
-    return formatLine(name,
-                      std::string("Size"),
-                      std::string("Pruned"))
-         + formatLine(std::string("  PID/UID   COMMAND LINE"),
-                      std::string("BYTES"),
-                      std::string("NUM"));
+std::string PidEntry::formatHeader(const std::string& name,
+                                   log_id_t /* id */) const {
+    return formatLine(name, std::string("Size"), std::string("Pruned")) +
+           formatLine(std::string("  PID/UID   COMMAND LINE"),
+                      std::string("BYTES"), std::string("NUM"));
 }
 
-std::string PidEntry::format(const LogStatistics &stat, log_id_t /* id */) const {
+std::string PidEntry::format(const LogStatistics& stat,
+                             log_id_t /* id */) const {
     uid_t uid = getUid();
     pid_t pid = getPid();
     std::string name = android::base::StringPrintf("%5u/%u", pid, uid);
-    const char *nameTmp = getName();
+    const char* nameTmp = getName();
     if (nameTmp) {
         name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(12 - name.length(), (size_t)1),
-            "", nameTmp);
+            "%*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));
+            "%*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());
+    std::string size = android::base::StringPrintf("%zu", getSizes());
 
     std::string pruned = "";
     size_t dropped = getDropped();
@@ -358,36 +387,31 @@
     return formatLine(name, size, pruned);
 }
 
-std::string TidEntry::formatHeader(const std::string &name, log_id_t /* id */) const {
-    return formatLine(name,
-                      std::string("Size"),
-                      std::string("Pruned"))
-         + formatLine(std::string("  TID/UID   COMM"),
-                      std::string("BYTES"),
+std::string TidEntry::formatHeader(const std::string& name,
+                                   log_id_t /* id */) const {
+    return formatLine(name, std::string("Size"), std::string("Pruned")) +
+           formatLine(std::string("  TID/UID   COMM"), std::string("BYTES"),
                       std::string("NUM"));
 }
 
-std::string TidEntry::format(const LogStatistics &stat, log_id_t /* id */) const {
+std::string TidEntry::format(const LogStatistics& stat,
+                             log_id_t /* id */) const {
     uid_t uid = getUid();
-    std::string name = android::base::StringPrintf("%5u/%u",
-                                                   getTid(), uid);
-    const char *nameTmp = getName();
+    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);
+            "%*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));
+            "%*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());
+    std::string size = android::base::StringPrintf("%zu", getSizes());
 
     std::string pruned = "";
     size_t dropped = getDropped();
@@ -398,37 +422,36 @@
     return formatLine(name, size, pruned);
 }
 
-std::string TagEntry::formatHeader(const std::string &name, log_id_t id) const {
+std::string TagEntry::formatHeader(const std::string& name, log_id_t id) const {
     bool isprune = worstUidEnabledForLogid(id);
-    return formatLine(name,
-                      std::string("Size"),
-                      std::string(isprune ? "Prune" : ""))
-         + formatLine(std::string("    TAG/UID   TAGNAME"),
-                      std::string("BYTES"),
-                      std::string(isprune ? "NUM" : ""));
+    return formatLine(name, std::string("Size"),
+                      std::string(isprune ? "Prune" : "")) +
+           formatLine(std::string("    TAG/UID   TAGNAME"),
+                      std::string("BYTES"), std::string(isprune ? "NUM" : ""));
 }
 
-std::string TagEntry::format(const LogStatistics & /* stat */, log_id_t /* id */) const {
+std::string TagEntry::format(const LogStatistics& /* stat */,
+                             log_id_t /* id */) const {
     std::string name;
     uid_t uid = getUid();
     if (uid == (uid_t)-1) {
-        name = android::base::StringPrintf("%7u",
-                                           getKey());
+        name = android::base::StringPrintf("%7u", getKey());
     } else {
-        name = android::base::StringPrintf("%7u/%u",
-                                           getKey(), uid);
+        name = android::base::StringPrintf("%7u/%u", getKey(), uid);
     }
-    const char *nameTmp = getName();
+    const char* nameTmp = getName();
     if (nameTmp) {
         name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(14 - name.length(), (size_t)1),
-            "", nameTmp);
+            "%*s%s", (int)std::max(14 - name.length(), (size_t)1), "", nameTmp);
     }
 
-    std::string size = android::base::StringPrintf("%zu",
-                                                   getSizes());
+    std::string size = android::base::StringPrintf("%zu", getSizes());
 
     std::string pruned = "";
+    size_t dropped = getDropped();
+    if (dropped) {
+        pruned = android::base::StringPrintf("%zu", dropped);
+    }
 
     return formatLine(name, size, pruned);
 }
@@ -444,55 +467,91 @@
     short spaces = 1;
 
     log_id_for_each(id) {
-        if (!(logMask & (1 << id))) {
-            continue;
-        }
+        if (!(logMask & (1 << id))) continue;
         oldLength = output.length();
-        if (spaces < 0) {
-            spaces = 0;
-        }
+        if (spaces < 0) spaces = 0;
         output += android::base::StringPrintf("%*s%s", spaces, "",
                                               android_log_id_to_name(id));
         spaces += spaces_total + oldLength - output.length();
     }
+    if (spaces < 0) spaces = 0;
+    output += android::base::StringPrintf("%*sTotal", spaces, "");
 
-    spaces = 4;
-    output += "\nTotal";
+    static const char TotalStr[] = "\nTotal";
+    spaces = 10 - strlen(TotalStr);
+    output += TotalStr;
 
+    size_t totalSize = 0;
+    size_t totalEls = 0;
     log_id_for_each(id) {
-        if (!(logMask & (1 << id))) {
-            continue;
-        }
+        if (!(logMask & (1 << id))) continue;
         oldLength = output.length();
-        if (spaces < 0) {
-            spaces = 0;
-        }
-        output += android::base::StringPrintf("%*s%zu/%zu", spaces, "",
-                                              sizesTotal(id),
-                                              elementsTotal(id));
+        if (spaces < 0) spaces = 0;
+        size_t szs = sizesTotal(id);
+        totalSize += szs;
+        size_t els = elementsTotal(id);
+        totalEls += els;
+        output +=
+            android::base::StringPrintf("%*s%zu/%zu", spaces, "", szs, els);
         spaces += spaces_total + oldLength - output.length();
     }
+    if (spaces < 0) spaces = 0;
+    output += android::base::StringPrintf("%*s%zu/%zu", spaces, "", totalSize,
+                                          totalEls);
 
-    spaces = 6;
-    output += "\nNow";
+    static const char NowStr[] = "\nNow";
+    spaces = 10 - strlen(NowStr);
+    output += NowStr;
 
+    totalSize = 0;
+    totalEls = 0;
     log_id_for_each(id) {
-        if (!(logMask & (1 << id))) {
-            continue;
-        }
+        if (!(logMask & (1 << id))) continue;
 
         size_t els = elements(id);
         if (els) {
             oldLength = output.length();
-            if (spaces < 0) {
-                spaces = 0;
-            }
-            output += android::base::StringPrintf("%*s%zu/%zu", spaces, "",
-                                                  sizes(id), els);
+            if (spaces < 0) spaces = 0;
+            size_t szs = sizes(id);
+            totalSize += szs;
+            totalEls += els;
+            output +=
+                android::base::StringPrintf("%*s%zu/%zu", spaces, "", szs, els);
             spaces -= output.length() - oldLength;
         }
         spaces += spaces_total;
     }
+    if (spaces < 0) spaces = 0;
+    output += android::base::StringPrintf("%*s%zu/%zu", spaces, "", totalSize,
+                                          totalEls);
+
+    static const char OverheadStr[] = "\nOverhead";
+    spaces = 10 - strlen(OverheadStr);
+    output += OverheadStr;
+
+    totalSize = 0;
+    log_id_for_each(id) {
+        if (!(logMask & (1 << id))) continue;
+
+        size_t els = elements(id);
+        if (els) {
+            oldLength = output.length();
+            if (spaces < 0) spaces = 0;
+            // estimate the std::list overhead.
+            static const size_t overhead =
+                ((sizeof(LogBufferElement) + sizeof(uint64_t) - 1) &
+                 -sizeof(uint64_t)) +
+                sizeof(std::list<LogBufferElement*>);
+            size_t szs = sizes(id) + els * overhead;
+            totalSize += szs;
+            output += android::base::StringPrintf("%*s%zu", spaces, "", szs);
+            spaces -= output.length() - oldLength;
+        }
+        spaces += spaces_total;
+    }
+    totalSize += sizeOf();
+    if (spaces < 0) spaces = 0;
+    output += android::base::StringPrintf("%*s%zu", spaces, "", totalSize);
 
     // Report on Chattiest
 
@@ -500,45 +559,36 @@
 
     // Chattiest by application (UID)
     log_id_for_each(id) {
-        if (!(logMask & (1 << id))) {
-            continue;
-        }
+        if (!(logMask & (1 << id))) continue;
 
-        name = (uid == AID_ROOT)
-            ? "Chattiest UIDs in %s log buffer:"
-            : "Logging for your UID in %s log buffer:";
+        name = (uid == AID_ROOT) ? "Chattiest UIDs in %s log buffer:"
+                                 : "Logging for your UID in %s log buffer:";
         output += uidTable[id].format(*this, uid, pid, name, id);
     }
 
     if (enable) {
-        name = ((uid == AID_ROOT) && !pid)
-            ? "Chattiest PIDs:"
-            : "Logging for this PID:";
+        name = ((uid == AID_ROOT) && !pid) ? "Chattiest PIDs:"
+                                           : "Logging for this PID:";
         output += pidTable.format(*this, uid, pid, name);
         name = "Chattiest TIDs";
-        if (pid) {
-            name += android::base::StringPrintf(" for PID %d", pid);
-        }
+        if (pid) name += android::base::StringPrintf(" for PID %d", pid);
         name += ":";
         output += tidTable.format(*this, uid, pid, name);
     }
 
     if (enable && (logMask & (1 << LOG_ID_EVENTS))) {
         name = "Chattiest events log buffer TAGs";
-        if (pid) {
-            name += android::base::StringPrintf(" for PID %d", pid);
-        }
+        if (pid) name += android::base::StringPrintf(" for PID %d", pid);
         name += ":";
         output += tagTable.format(*this, uid, pid, name, LOG_ID_EVENTS);
     }
 
     if (enable && (logMask & (1 << LOG_ID_SECURITY))) {
         name = "Chattiest security log buffer TAGs";
-        if (pid) {
-            name += android::base::StringPrintf(" for PID %d", pid);
-        }
+        if (pid) name += android::base::StringPrintf(" for PID %d", pid);
         name += ":";
-        output += securityTagTable.format(*this, uid, pid, name, LOG_ID_SECURITY);
+        output +=
+            securityTagTable.format(*this, uid, pid, name, LOG_ID_SECURITY);
     }
 
     return output;
@@ -549,7 +599,7 @@
 uid_t pidToUid(pid_t pid) {
     char buffer[512];
     snprintf(buffer, sizeof(buffer), "/proc/%u/status", pid);
-    FILE *fp = fopen(buffer, "r");
+    FILE* fp = fopen(buffer, "r");
     if (fp) {
         while (fgets(buffer, sizeof(buffer), fp)) {
             int uid;
@@ -560,9 +610,8 @@
         }
         fclose(fp);
     }
-    return AID_LOGD; // associate this with the logger
+    return AID_LOGD;  // associate this with the logger
 }
-
 }
 
 uid_t LogStatistics::pidToUid(pid_t pid) {
@@ -570,10 +619,10 @@
 }
 
 // caller must free character string
-const char *LogStatistics::pidToName(pid_t pid) const {
+const char* LogStatistics::pidToName(pid_t pid) const {
     // An inconvenient truth ... getName() can alter the object
-    pidTable_t &writablePidTable = const_cast<pidTable_t &>(pidTable);
-    const char *name = writablePidTable.add(pid)->second.getName();
+    pidTable_t& writablePidTable = const_cast<pidTable_t&>(pidTable);
+    const char* name = writablePidTable.add(pid)->second.getName();
     if (!name) {
         return NULL;
     }
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 6f7d264..066b7de 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -17,48 +17,74 @@
 #ifndef _LOGD_LOG_STATISTICS_H__
 #define _LOGD_LOG_STATISTICS_H__
 
-#include <memory>
+#include <ctype.h>
 #include <stdlib.h>
 #include <sys/types.h>
 
-#include <algorithm> // std::max
-#include <string>    // std::string
+#include <algorithm>  // std::max
+#include <memory>
+#include <string>  // std::string
 #include <unordered_map>
 
 #include <android-base/stringprintf.h>
-#include <log/log.h>
+#include <android/log.h>
 #include <private/android_filesystem_config.h>
 
 #include "LogBufferElement.h"
 #include "LogUtils.h"
 
 #define log_id_for_each(i) \
-    for (log_id_t i = LOG_ID_MIN; i < LOG_ID_MAX; i = (log_id_t) (i + 1))
+    for (log_id_t i = LOG_ID_MIN; (i) < LOG_ID_MAX; (i) = (log_id_t)((i) + 1))
 
 class LogStatistics;
 
 template <typename TKey, typename TEntry>
 class LogHashtable {
-
     std::unordered_map<TKey, TEntry> map;
 
-public:
+    size_t bucket_size() const {
+        size_t count = 0;
+        for (size_t idx = 0; idx < map.bucket_count(); ++idx) {
+            size_t bucket_size = map.bucket_size(idx);
+            if (bucket_size == 0) bucket_size = 1;
+            count += bucket_size;
+        }
+        float load_factor = map.max_load_factor();
+        if (load_factor < 1.0) return count;
+        return count * load_factor;
+    }
+
+    static const size_t unordered_map_per_entry_overhead = sizeof(void*);
+    static const size_t unordered_map_bucket_overhead = sizeof(void*);
+
+   public:
+    size_t size() const {
+        return map.size();
+    }
+
+    // Estimate unordered_map memory usage.
+    size_t sizeOf() const {
+        return sizeof(*this) +
+               (size() * (sizeof(TEntry) + unordered_map_per_entry_overhead)) +
+               (bucket_size() * sizeof(size_t) + unordered_map_bucket_overhead);
+    }
 
     typedef typename std::unordered_map<TKey, TEntry>::iterator iterator;
-    typedef typename std::unordered_map<TKey, TEntry>::const_iterator const_iterator;
+    typedef
+        typename std::unordered_map<TKey, TEntry>::const_iterator const_iterator;
 
-    std::unique_ptr<const TEntry *[]> sort(uid_t uid, pid_t pid,
+    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(NULL);
             return sorted;
         }
 
-        const TEntry **retval = new const TEntry* [len];
+        const TEntry** retval = new const TEntry*[len];
         memset(retval, 0, sizeof(*retval) * len);
 
-        for(const_iterator it = map.begin(); it != map.end(); ++it) {
-            const TEntry &entry = it->second;
+        for (const_iterator it = map.begin(); it != map.end(); ++it) {
+            const TEntry& entry = it->second;
 
             if ((uid != AID_ROOT) && (uid != entry.getUid())) {
                 continue;
@@ -69,8 +95,8 @@
 
             size_t sizes = entry.getSizes();
             ssize_t index = len - 1;
-            while ((!retval[index] || (sizes > retval[index]->getSizes()))
-                    && (--index >= 0))
+            while ((!retval[index] || (sizes > retval[index]->getSizes())) &&
+                   (--index >= 0))
                 ;
             if (++index < (ssize_t)len) {
                 size_t num = len - index - 1;
@@ -81,11 +107,11 @@
                 retval[index] = &entry;
             }
         }
-        std::unique_ptr<const TEntry *[]> sorted(retval);
+        std::unique_ptr<const TEntry* []> sorted(retval);
         return sorted;
     }
 
-    inline iterator add(TKey key, LogBufferElement *element) {
+    inline iterator add(TKey key, LogBufferElement* element) {
         iterator it = map.find(key);
         if (it == map.end()) {
             it = map.insert(std::make_pair(key, TEntry(element))).first;
@@ -105,41 +131,46 @@
         return it;
     }
 
-    void subtract(TKey key, LogBufferElement *element) {
+    void subtract(TKey key, 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, LogBufferElement* element) {
         iterator it = map.find(key);
         if (it != map.end()) {
             it->second.drop(element);
         }
     }
 
-    inline iterator begin() { return map.begin(); }
-    inline const_iterator begin() const { return map.begin(); }
-    inline iterator end() { return map.end(); }
-    inline const_iterator end() const { return map.end(); }
+    inline iterator begin() {
+        return map.begin();
+    }
+    inline const_iterator begin() const {
+        return map.begin();
+    }
+    inline iterator end() {
+        return map.end();
+    }
+    inline const_iterator end() const {
+        return map.end();
+    }
 
-    std::string format(
-            const LogStatistics &stat,
-            uid_t uid,
-            pid_t pid,
-            const std::string &name = std::string(""),
-            log_id_t id = LOG_ID_MAX) const {
+    std::string format(const LogStatistics& stat, uid_t uid, pid_t pid,
+                       const std::string& name = std::string(""),
+                       log_id_t id = LOG_ID_MAX) const {
         static const size_t maximum_sorted_entries = 32;
         std::string output;
-        std::unique_ptr<const TEntry *[]> sorted = sort(uid, pid,
-                                                        maximum_sorted_entries);
+        std::unique_ptr<const TEntry* []> sorted =
+            sort(uid, pid, maximum_sorted_entries);
         if (!sorted.get()) {
             return output;
         }
         bool headerPrinted = false;
         for (size_t index = 0; index < maximum_sorted_entries; ++index) {
-            const TEntry *entry = sorted[index];
+            const TEntry* entry = sorted[index];
             if (!entry) {
                 break;
             }
@@ -158,65 +189,73 @@
 };
 
 namespace EntryBaseConstants {
-    static constexpr size_t pruned_len = 14;
-    static constexpr size_t total_len = 80;
+static constexpr size_t pruned_len = 14;
+static constexpr size_t total_len = 80;
 }
 
 struct EntryBase {
     size_t size;
 
-    EntryBase():size(0) { }
-    EntryBase(LogBufferElement *element):size(element->getMsgLen()) { }
+    EntryBase() : size(0) {
+    }
+    explicit EntryBase(LogBufferElement* element) : size(element->getMsgLen()) {
+    }
 
-    size_t getSizes() const { return size; }
+    size_t getSizes() const {
+        return size;
+    }
 
-    inline void add(LogBufferElement *element) { size += element->getMsgLen(); }
-    inline bool subtract(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
+        size += element->getMsgLen();
+    }
+    inline bool subtract(LogBufferElement* element) {
         size -= element->getMsgLen();
         return !size;
     }
 
-    static std::string formatLine(
-            const std::string &name,
-            const std::string &size,
-            const std::string &pruned) {
-        ssize_t drop_len = std::max(pruned.length() + 1,
-                                    EntryBaseConstants::pruned_len);
-        ssize_t size_len = std::max(size.length() + 1,
-                                    EntryBaseConstants::total_len
-                                        - name.length() - drop_len - 1);
+    static std::string formatLine(const std::string& name,
+                                  const std::string& size,
+                                  const std::string& pruned) {
+        ssize_t drop_len =
+            std::max(pruned.length() + 1, EntryBaseConstants::pruned_len);
+        ssize_t size_len =
+            std::max(size.length() + 1, EntryBaseConstants::total_len -
+                                            name.length() - drop_len - 1);
 
-        if (pruned.length()) {
-            return android::base::StringPrintf("%s%*s%*s\n", name.c_str(),
-                                               (int)size_len, size.c_str(),
-                                               (int)drop_len, pruned.c_str());
-        } else {
-            return android::base::StringPrintf("%s%*s\n", name.c_str(),
-                                               (int)size_len, size.c_str());
-        }
+        std::string ret = android::base::StringPrintf(
+            "%s%*s%*s", name.c_str(), (int)size_len, size.c_str(),
+            (int)drop_len, pruned.c_str());
+        // remove any trailing spaces
+        size_t pos = ret.size();
+        size_t len = 0;
+        while (pos && isspace(ret[--pos])) ++len;
+        if (len) ret.erase(pos + 1, len);
+        return ret + "\n";
     }
 };
 
 struct EntryBaseDropped : public EntryBase {
     size_t dropped;
 
-    EntryBaseDropped():dropped(0) { }
-    EntryBaseDropped(LogBufferElement *element):
-            EntryBase(element),
-            dropped(element->getDropped()){
+    EntryBaseDropped() : dropped(0) {
+    }
+    explicit EntryBaseDropped(LogBufferElement* element)
+        : EntryBase(element), dropped(element->getDropped()) {
     }
 
-    size_t getDropped() const { return dropped; }
+    size_t getDropped() const {
+        return dropped;
+    }
 
-    inline void add(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
         dropped += element->getDropped();
         EntryBase::add(element);
     }
-    inline bool subtract(LogBufferElement *element) {
+    inline bool subtract(LogBufferElement* element) {
         dropped -= element->getDropped();
         return EntryBase::subtract(element) && !dropped;
     }
-    inline void drop(LogBufferElement *element) {
+    inline void drop(LogBufferElement* element) {
         dropped += 1;
         EntryBase::subtract(element);
     }
@@ -226,25 +265,31 @@
     const uid_t uid;
     pid_t pid;
 
-    UidEntry(LogBufferElement *element):
-            EntryBaseDropped(element),
-            uid(element->getUid()),
-            pid(element->getPid()) {
+    explicit UidEntry(LogBufferElement* element)
+        : EntryBaseDropped(element),
+          uid(element->getUid()),
+          pid(element->getPid()) {
     }
 
-    inline const uid_t&getKey() const { return uid; }
-    inline const uid_t&getUid() const { return getKey(); }
-    inline const pid_t&getPid() const { return pid; }
+    inline const uid_t& getKey() const {
+        return uid;
+    }
+    inline const uid_t& getUid() const {
+        return getKey();
+    }
+    inline const pid_t& getPid() const {
+        return pid;
+    }
 
-    inline void add(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
         if (pid != element->getPid()) {
             pid = -1;
         }
-        EntryBase::add(element);
+        EntryBaseDropped::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;
+    std::string formatHeader(const std::string& name, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id) const;
 };
 
 namespace android {
@@ -254,35 +299,45 @@
 struct PidEntry : public EntryBaseDropped {
     const pid_t pid;
     uid_t uid;
-    char *name;
+    char* name;
 
-    PidEntry(pid_t pid):
-            EntryBaseDropped(),
-            pid(pid),
-            uid(android::pidToUid(pid)),
-            name(android::pidToName(pid)) {
+    explicit PidEntry(pid_t pid)
+        : EntryBaseDropped(),
+          pid(pid),
+          uid(android::pidToUid(pid)),
+          name(android::pidToName(pid)) {
     }
-    PidEntry(LogBufferElement *element):
-            EntryBaseDropped(element),
-            pid(element->getPid()),
-            uid(element->getUid()),
-            name(android::pidToName(pid)) {
+    explicit PidEntry(LogBufferElement* element)
+        : EntryBaseDropped(element),
+          pid(element->getPid()),
+          uid(element->getUid()),
+          name(android::pidToName(pid)) {
     }
-    PidEntry(const PidEntry &element):
-            EntryBaseDropped(element),
-            pid(element.pid),
-            uid(element.uid),
-            name(element.name ? strdup(element.name) : NULL) {
+    PidEntry(const PidEntry& element)
+        : EntryBaseDropped(element),
+          pid(element.pid),
+          uid(element.uid),
+          name(element.name ? strdup(element.name) : NULL) {
     }
-    ~PidEntry() { free(name); }
+    ~PidEntry() {
+        free(name);
+    }
 
-    const pid_t&getKey() const { return pid; }
-    const pid_t&getPid() const { return getKey(); }
-    const uid_t&getUid() const { return uid; }
-    const char*getName() const { return name; }
+    const pid_t& getKey() const {
+        return pid;
+    }
+    const pid_t& getPid() const {
+        return getKey();
+    }
+    const uid_t& getUid() const {
+        return uid;
+    }
+    const char* getName() const {
+        return name;
+    }
 
     inline void add(pid_t newPid) {
-        if (name && !fast<strncmp>(name, "zygote", 6)) {
+        if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
             name = NULL;
         }
@@ -291,7 +346,7 @@
         }
     }
 
-    inline void add(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
         uid_t incomingUid = element->getUid();
         if (getUid() != incomingUid) {
             uid = incomingUid;
@@ -303,47 +358,59 @@
         EntryBaseDropped::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;
+    std::string formatHeader(const std::string& name, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id) const;
 };
 
 struct TidEntry : public EntryBaseDropped {
     const pid_t tid;
     pid_t pid;
     uid_t uid;
-    char *name;
+    char* name;
 
-    TidEntry(pid_t tid, pid_t pid):
-            EntryBaseDropped(),
-            tid(tid),
-            pid(pid),
-            uid(android::pidToUid(tid)),
-            name(android::tidToName(tid)) {
+    TidEntry(pid_t tid, pid_t pid)
+        : EntryBaseDropped(),
+          tid(tid),
+          pid(pid),
+          uid(android::pidToUid(tid)),
+          name(android::tidToName(tid)) {
     }
-    TidEntry(LogBufferElement *element):
-            EntryBaseDropped(element),
-            tid(element->getTid()),
-            pid(element->getPid()),
-            uid(element->getUid()),
-            name(android::tidToName(tid)) {
+    explicit TidEntry(LogBufferElement* element)
+        : EntryBaseDropped(element),
+          tid(element->getTid()),
+          pid(element->getPid()),
+          uid(element->getUid()),
+          name(android::tidToName(tid)) {
     }
-    TidEntry(const TidEntry &element):
-            EntryBaseDropped(element),
-            tid(element.tid),
-            pid(element.pid),
-            uid(element.uid),
-            name(element.name ? strdup(element.name) : NULL) {
+    TidEntry(const TidEntry& element)
+        : EntryBaseDropped(element),
+          tid(element.tid),
+          pid(element.pid),
+          uid(element.uid),
+          name(element.name ? strdup(element.name) : NULL) {
     }
-    ~TidEntry() { free(name); }
+    ~TidEntry() {
+        free(name);
+    }
 
-    const pid_t&getKey() const { return tid; }
-    const pid_t&getTid() const { return getKey(); }
-    const pid_t&getPid() const { return pid; }
-    const uid_t&getUid() const { return uid; }
-    const char*getName() const { return name; }
+    const pid_t& getKey() const {
+        return tid;
+    }
+    const pid_t& getTid() const {
+        return getKey();
+    }
+    const pid_t& getPid() const {
+        return pid;
+    }
+    const uid_t& getUid() const {
+        return uid;
+    }
+    const char* getName() const {
+        return name;
+    }
 
     inline void add(pid_t incomingTid) {
-        if (name && !fast<strncmp>(name, "zygote", 6)) {
+        if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
             name = NULL;
         }
@@ -352,7 +419,7 @@
         }
     }
 
-    inline void add(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
         uid_t incomingUid = element->getUid();
         pid_t incomingPid = element->getPid();
         if ((getUid() != incomingUid) || (getPid() != incomingPid)) {
@@ -366,39 +433,82 @@
         EntryBaseDropped::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;
+    std::string formatHeader(const std::string& name, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id) const;
 };
 
-struct TagEntry : public EntryBase {
+struct TagEntry : public EntryBaseDropped {
     const uint32_t tag;
     pid_t pid;
     uid_t uid;
 
-    TagEntry(LogBufferElement *element):
-            EntryBase(element),
-            tag(element->getTag()),
-            pid(element->getPid()),
-            uid(element->getUid()) {
+    explicit TagEntry(LogBufferElement* element)
+        : EntryBaseDropped(element),
+          tag(element->getTag()),
+          pid(element->getPid()),
+          uid(element->getUid()) {
     }
 
-    const uint32_t&getKey() const { return tag; }
-    const pid_t&getPid() const { return pid; }
-    const uid_t&getUid() const { return uid; }
-    const char*getName() const { return android::tagToName(tag); }
+    const uint32_t& getKey() const {
+        return tag;
+    }
+    const pid_t& getPid() const {
+        return pid;
+    }
+    const uid_t& getUid() const {
+        return uid;
+    }
+    const char* getName() const {
+        return android::tagToName(tag);
+    }
 
-    inline void add(LogBufferElement *element) {
+    inline void add(LogBufferElement* element) {
         if (uid != element->getUid()) {
             uid = -1;
         }
         if (pid != element->getPid()) {
             pid = -1;
         }
-        EntryBase::add(element);
+        EntryBaseDropped::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;
+    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;
+
+   public:
+    explicit LogFindWorst(std::unique_ptr<const TEntry* []>&& sorted)
+        : sorted(std::move(sorted)) {
+    }
+
+    void findWorst(int& worst, size_t& worst_sizes, size_t& second_worst_sizes,
+                   size_t threshold) {
+        if (sorted.get() && sorted[0] && sorted[1]) {
+            worst_sizes = sorted[0]->getSizes();
+            if ((worst_sizes > threshold)
+                // Allow time horizon to extend roughly tenfold, assume
+                // average entry length is 100 characters.
+                && (worst_sizes > (10 * sorted[0]->getDropped()))) {
+                worst = sorted[0]->getKey();
+                second_worst_sizes = sorted[1]->getSizes();
+                if (second_worst_sizes < threshold) {
+                    second_worst_sizes = threshold;
+                }
+            }
+        }
+    }
+
+    void findWorst(int& worst, size_t worst_sizes, size_t& second_worst_sizes) {
+        if (sorted.get() && sorted[0] && sorted[1]) {
+            worst = sorted[0]->getKey();
+            second_worst_sizes =
+                worst_sizes - sorted[0]->getSizes() + sorted[1]->getSizes();
+        }
+    }
 };
 
 // Log Statistics
@@ -410,6 +520,7 @@
     size_t mDroppedElements[LOG_ID_MAX];
     size_t mSizesTotal[LOG_ID_MAX];
     size_t mElementsTotal[LOG_ID_MAX];
+    static size_t SizesTotal;
     bool enable;
 
     // uid to size list
@@ -435,46 +546,84 @@
     // security tag list
     tagTable_t securityTagTable;
 
-public:
+    size_t sizeOf() const {
+        size_t size = sizeof(*this) + pidTable.sizeOf() + tidTable.sizeOf() +
+                      tagTable.sizeOf() + securityTagTable.sizeOf() +
+                      (pidTable.size() * sizeof(pidTable_t::iterator)) +
+                      (tagTable.size() * sizeof(tagTable_t::iterator));
+        for (auto it : pidTable) {
+            const char* name = it.second.getName();
+            if (name) size += strlen(name) + 1;
+        }
+        for (auto it : tidTable) {
+            const char* name = it.second.getName();
+            if (name) size += strlen(name) + 1;
+        }
+        log_id_for_each(id) {
+            size += uidTable[id].sizeOf();
+            size += uidTable[id].size() * sizeof(uidTable_t::iterator);
+            size += pidSystemTable[id].sizeOf();
+            size +=
+                pidSystemTable[id].size() * sizeof(pidSystemTable_t::iterator);
+        }
+        return size;
+    }
+
+   public:
     LogStatistics();
 
-    void enableStatistics() { enable = true; }
+    void enableStatistics() {
+        enable = true;
+    }
 
-    void add(LogBufferElement *entry);
-    void subtract(LogBufferElement *entry);
+    void add(LogBufferElement* entry);
+    void subtract(LogBufferElement* entry);
     // entry->setDropped(1) must follow this call
-    void drop(LogBufferElement *entry);
+    void drop(LogBufferElement* entry);
     // Correct for coalescing two entries referencing dropped content
-    void erase(LogBufferElement *element) {
+    void erase(LogBufferElement* element) {
         log_id_t log_id = element->getLogId();
         --mElements[log_id];
         --mDroppedElements[log_id];
     }
 
-    std::unique_ptr<const UidEntry *[]> sort(uid_t uid, pid_t pid,
-                                             size_t len, log_id id) {
-        return uidTable[id].sort(uid, pid, len);
+    LogFindWorst<UidEntry> sort(uid_t uid, pid_t pid, size_t len, log_id id) {
+        return LogFindWorst<UidEntry>(uidTable[id].sort(uid, pid, len));
     }
-    std::unique_ptr<const PidEntry *[]> sort(uid_t uid, pid_t pid,
-                                             size_t len, log_id id, uid_t) {
-        return pidSystemTable[id].sort(uid, pid, len);
+    LogFindWorst<PidEntry> sortPids(uid_t uid, pid_t pid, size_t len,
+                                    log_id id) {
+        return LogFindWorst<PidEntry>(pidSystemTable[id].sort(uid, pid, len));
+    }
+    LogFindWorst<TagEntry> sortTags(uid_t uid, pid_t pid, size_t len, log_id) {
+        return LogFindWorst<TagEntry>(tagTable.sort(uid, pid, len));
     }
 
     // fast track current value by id only
-    size_t sizes(log_id_t id) const { return mSizes[id]; }
-    size_t elements(log_id_t id) const { return mElements[id]; }
+    size_t sizes(log_id_t id) const {
+        return mSizes[id];
+    }
+    size_t elements(log_id_t id) const {
+        return mElements[id];
+    }
     size_t realElements(log_id_t id) const {
         return mElements[id] - mDroppedElements[id];
     }
-    size_t sizesTotal(log_id_t id) const { return mSizesTotal[id]; }
-    size_t elementsTotal(log_id_t id) const { return mElementsTotal[id]; }
+    size_t sizesTotal(log_id_t id) const {
+        return mSizesTotal[id];
+    }
+    size_t elementsTotal(log_id_t id) const {
+        return mElementsTotal[id];
+    }
+    static size_t sizesTotal() {
+        return SizesTotal;
+    }
 
     std::string format(uid_t uid, pid_t pid, unsigned int logMask) const;
 
     // helper (must be locked directly or implicitly by mLogElementsLock)
-    const char *pidToName(pid_t pid) const;
+    const char* pidToName(pid_t pid) const;
     uid_t pidToUid(pid_t pid);
-    const char *uidToName(uid_t uid) const;
+    const char* uidToName(uid_t uid) const;
 };
 
-#endif // _LOGD_LOG_STATISTICS_H__
+#endif  // _LOGD_LOG_STATISTICS_H__
diff --git a/logd/LogTags.cpp b/logd/LogTags.cpp
new file mode 100644
index 0000000..fcd45bd
--- /dev/null
+++ b/logd/LogTags.cpp
@@ -0,0 +1,888 @@
+/*
+ * 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 <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/file.h>
+#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 "LogTags.h"
+#include "LogUtils.h"
+
+static LogTags* logtags;
+
+const char LogTags::system_event_log_tags[] = "/system/etc/event-log-tags";
+const char LogTags::dynamic_event_log_tags[] = "/dev/event-log-tags";
+// Only for debug
+const char LogTags::debug_event_log_tags[] = "/data/misc/logd/event-log-tags";
+
+// Sniff for first uid=%d in utf8z comment string
+static uid_t sniffUid(const char* comment, const char* endp) {
+    if (!comment) return AID_ROOT;
+
+    if (*comment == '#') ++comment;
+    while ((comment < endp) && (*comment != '\n') && isspace(*comment))
+        ++comment;
+    static const char uid_str[] = "uid=";
+    if (((comment + strlen(uid_str)) >= endp) ||
+        fastcmp<strncmp>(comment, uid_str, strlen(uid_str)) ||
+        !isdigit(comment[strlen(uid_str)]))
+        return AID_ROOT;
+    char* cp;
+    unsigned long Uid = strtoul(comment + 4, &cp, 10);
+    if ((cp > endp) || (Uid >= INT_MAX)) return AID_ROOT;
+
+    return Uid;
+}
+
+// Checks for file corruption, and report false if there was no need
+// to rebuild the referenced file.  Failure to rebuild is only logged,
+// does not cause a return value of false.
+bool LogTags::RebuildFileEventLogTags(const char* filename, bool warn) {
+    int fd;
+
+    {
+        android::RWLock::AutoRLock readLock(rwlock);
+
+        if (tag2total.begin() == tag2total.end()) {
+            return false;
+        }
+
+        file2watermark_const_iterator iwater = file2watermark.find(filename);
+        if (iwater == file2watermark.end()) {
+            return false;
+        }
+
+        struct stat sb;
+        if (!stat(filename, &sb) && ((size_t)sb.st_size >= iwater->second)) {
+            return false;
+        }
+
+        // dump what we already know back into the file?
+        fd = TEMP_FAILURE_RETRY(open(
+            filename, O_WRONLY | O_TRUNC | O_CLOEXEC | O_NOFOLLOW | O_BINARY));
+        if (fd >= 0) {
+            time_t now = time(NULL);
+            struct tm tm;
+            localtime_r(&now, &tm);
+            char timebuf[20];
+            size_t len =
+                strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", &tm);
+            android::base::WriteStringToFd(
+                android::base::StringPrintf(
+                    "# Rebuilt %.20s, content owned by logd\n", timebuf),
+                fd);
+            for (const auto& it : tag2total) {
+                android::base::WriteStringToFd(
+                    formatEntry_locked(it.first, AID_ROOT), fd);
+            }
+            TEMP_FAILURE_RETRY(close(fd));
+        }
+    }
+
+    if (warn) {
+        android::prdebug(
+            ((fd < 0) ? "%s failed to rebuild"
+                      : "%s missing, damaged or truncated; rebuilt"),
+            filename);
+    }
+
+    if (fd >= 0) {
+        android::RWLock::AutoWLock writeLock(rwlock);
+
+        struct stat sb;
+        if (!stat(filename, &sb)) file2watermark[filename] = sb.st_size;
+    }
+
+    return true;
+}
+
+void LogTags::AddEventLogTags(uint32_t tag, uid_t uid, const std::string& Name,
+                              const std::string& Format, const char* source,
+                              bool warn) {
+    std::string Key = Name;
+    if (Format.length()) Key += "+" + Format;
+
+    bool update = !source || !!strcmp(source, system_event_log_tags);
+    bool newOne;
+
+    {
+        android::RWLock::AutoWLock writeLock(rwlock);
+
+        tag2total_const_iterator itot = tag2total.find(tag);
+
+        // unlikely except for dupes, or updates to uid list (more later)
+        if (itot != tag2total.end()) update = false;
+
+        newOne = tag2name.find(tag) == tag2name.end();
+        key2tag[Key] = tag;
+
+        if (Format.length()) {
+            if (key2tag.find(Name) == key2tag.end()) {
+                key2tag[Name] = tag;
+            }
+            tag2format[tag] = Format;
+        }
+        tag2name[tag] = Name;
+
+        tag2uid_const_iterator ut = tag2uid.find(tag);
+        if (ut != tag2uid.end()) {
+            if (uid == AID_ROOT) {
+                tag2uid.erase(ut);
+                update = true;
+            } else if (ut->second.find(uid) == ut->second.end()) {
+                const_cast<uid_list&>(ut->second).emplace(uid);
+                update = true;
+            }
+        } else if (newOne && (uid != AID_ROOT)) {
+            tag2uid[tag].emplace(uid);
+            update = true;
+        }
+
+        // updatePersist -> trigger output on modified
+        // content, reset tag2total if available
+        if (update && (itot != tag2total.end())) tag2total[tag] = 0;
+    }
+
+    if (update) {
+        WritePersistEventLogTags(tag, uid, source);
+    } else if (warn && !newOne && source) {
+        // For the files, we want to report dupes.
+        android::prdebug("Multiple tag %" PRIu32 " %s %s %s", tag, Name.c_str(),
+                         Format.c_str(), source);
+    }
+}
+
+// Read the event log tags file, and build up our internal database
+void LogTags::ReadFileEventLogTags(const char* filename, bool warn) {
+    bool etc = !strcmp(filename, system_event_log_tags);
+    bool debug = !etc && !strcmp(filename, debug_event_log_tags);
+
+    if (!etc) {
+        RebuildFileEventLogTags(filename, warn);
+    }
+    std::string content;
+    if (android::base::ReadFileToString(filename, &content)) {
+        char* cp = (char*)content.c_str();
+        char* endp = cp + content.length();
+
+        {
+            android::RWLock::AutoRLock writeLock(rwlock);
+
+            file2watermark[filename] = content.length();
+        }
+
+        char* lineStart = cp;
+        while (cp < endp) {
+            if (*cp == '\n') {
+                lineStart = cp;
+            } else if (lineStart) {
+                if (*cp == '#') {
+                    /* comment; just scan to end */
+                    lineStart = NULL;
+                } else if (isdigit(*cp)) {
+                    unsigned long Tag = strtoul(cp, &cp, 10);
+                    if (warn && (Tag > emptyTag)) {
+                        android::prdebug("tag too large %lu", Tag);
+                    }
+                    while ((cp < endp) && (*cp != '\n') && isspace(*cp)) ++cp;
+                    if (cp >= endp) break;
+                    if (*cp == '\n') continue;
+                    const char* name = cp;
+                    /* Determine whether it is a valid tag name [a-zA-Z0-9_] */
+                    bool hasAlpha = false;
+                    while ((cp < endp) && (isalnum(*cp) || (*cp == '_'))) {
+                        if (!isdigit(*cp)) hasAlpha = true;
+                        ++cp;
+                    }
+                    std::string Name(name, cp - name);
+#ifdef ALLOW_NOISY_LOGGING_OF_PROBLEM_WITH_LOTS_OF_TECHNICAL_DEBT
+                    static const size_t maximum_official_tag_name_size = 24;
+                    if (warn &&
+                        (Name.length() > maximum_official_tag_name_size)) {
+                        android::prdebug("tag name too long %s", Name.c_str());
+                    }
+#endif
+                    if (hasAlpha &&
+                        ((cp >= endp) || (*cp == '#') || isspace(*cp))) {
+                        if (Tag > emptyTag) {
+                            if (*cp != '\n') lineStart = NULL;
+                            continue;
+                        }
+                        while ((cp < endp) && (*cp != '\n') && isspace(*cp))
+                            ++cp;
+                        const char* format = cp;
+                        uid_t uid = AID_ROOT;
+                        while ((cp < endp) && (*cp != '\n')) {
+                            if (*cp == '#') {
+                                uid = sniffUid(cp, endp);
+                                lineStart = NULL;
+                                break;
+                            }
+                            ++cp;
+                        }
+                        while ((cp > format) && isspace(cp[-1])) {
+                            --cp;
+                            lineStart = NULL;
+                        }
+                        std::string Format(format, cp - format);
+
+                        AddEventLogTags((uint32_t)Tag, uid, Name, Format,
+                                        filename, warn);
+                    } else {
+                        if (warn) {
+                            android::prdebug("tag name invalid %.*s",
+                                             (int)(cp - name + 1), name);
+                        }
+                        lineStart = NULL;
+                    }
+                } else if (!isspace(*cp)) {
+                    break;
+                }
+            }
+            cp++;
+        }
+    } else if (warn) {
+        android::prdebug("Cannot read %s", filename);
+    }
+}
+
+// Extract a 4-byte value from a byte stream.
+static inline uint32_t get4LE(const char* msg) {
+    const uint8_t* src = reinterpret_cast<const uint8_t*>(msg);
+    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+}
+
+// Additional persistent sources for invented log tags.  Read the
+// special pmsg event for log tags, and build up our internal
+// database with any found.
+void LogTags::ReadPersistEventLogTags() {
+    struct logger_list* logger_list = android_logger_list_alloc(
+        ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK, 0,
+        (pid_t)0);
+    if (!logger_list) return;
+
+    struct logger* e = android_logger_open(logger_list, LOG_ID_EVENTS);
+    struct logger* s = android_logger_open(logger_list, LOG_ID_SECURITY);
+    if (!e && !s) {
+        android_logger_list_free(logger_list);
+        return;
+    }
+
+    for (;;) {
+        struct log_msg log_msg;
+        int ret = android_logger_list_read(logger_list, &log_msg);
+        if (ret <= 0) break;
+
+        const char* msg = log_msg.msg();
+        if (!msg) continue;
+        if (log_msg.entry.len <= sizeof(uint32_t)) continue;
+        uint32_t Tag = get4LE(msg);
+        if (Tag != TAG_DEF_LOG_TAG) continue;
+        uid_t uid = (log_msg.entry.hdr_size >= sizeof(logger_entry_v4))
+                        ? log_msg.entry.uid
+                        : AID_ROOT;
+
+        std::string Name;
+        std::string Format;
+        android_log_list_element elem;
+        {
+            android_log_event_list ctx(log_msg);
+            elem = ctx.read();
+            if (elem.type != EVENT_TYPE_LIST) {
+                continue;
+            }
+            elem = ctx.read();
+            if (elem.type != EVENT_TYPE_INT) {
+                continue;
+            }
+            Tag = elem.data.int32;
+            elem = ctx.read();
+            if (elem.type != EVENT_TYPE_STRING) {
+                continue;
+            }
+            Name = std::string(elem.data.string, elem.len);
+            elem = ctx.read();
+            if (elem.type != EVENT_TYPE_STRING) {
+                continue;
+            }
+            Format = std::string(elem.data.string, elem.len);
+            elem = ctx.read();
+        }
+        if ((elem.type != EVENT_TYPE_LIST_STOP) || !elem.complete) continue;
+
+        AddEventLogTags(Tag, uid, Name, Format);
+    }
+    android_logger_list_free(logger_list);
+}
+
+LogTags::LogTags() {
+    ReadFileEventLogTags(system_event_log_tags);
+    // Following will likely fail on boot, but is required if logd restarts
+    ReadFileEventLogTags(dynamic_event_log_tags, false);
+    if (__android_log_is_debuggable()) {
+        ReadFileEventLogTags(debug_event_log_tags, false);
+    }
+    ReadPersistEventLogTags();
+
+    logtags = this;
+}
+
+// Converts an event tag into a name
+const char* LogTags::tagToName(uint32_t tag) const {
+    tag2name_const_iterator it;
+
+    android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+
+    it = tag2name.find(tag);
+    if ((it == tag2name.end()) || (it->second.length() == 0)) return NULL;
+
+    return it->second.c_str();
+}
+
+// Prototype in LogUtils.h allowing external access to our database.
+//
+// This must be a pure reader to our database, as everything else is
+// guaranteed single-threaded except this access point which is
+// asynchonous and can be multithreaded and thus rentrant.  The
+// object's rwlock is only used to guarantee atomic access to the
+// unordered_map to prevent corruption, with a requirement to be a
+// low chance of contention for this call.  If we end up changing
+// this algorithm resulting in write, then we should use a different
+// lock than the object's rwlock to protect groups of associated
+// actions.
+const char* android::tagToName(uint32_t tag) {
+    LogTags* me = logtags;
+
+    if (!me) return NULL;
+    me->WritePmsgEventLogTags(tag);
+    return me->tagToName(tag);
+}
+
+// Prototype in LogUtils.h allowing external access to our database.
+//
+// This only works on userdebug and eng devices to re-read the
+// /data/misc/logd/event-log-tags file right after /data is mounted.
+// The operation is near to boot and should only happen once.  There
+// are races associated with its use since it can trigger a Rebuild
+// of the file, but that is a can-not-happen since the file was not
+// read yet.  More dangerous if called later, but if all is well it
+// should just skip over everything and not write any new entries.
+void android::ReReadEventLogTags() {
+    LogTags* me = logtags;
+
+    if (me && __android_log_is_debuggable()) {
+        me->ReadFileEventLogTags(me->debug_event_log_tags);
+    }
+}
+
+// converts an event tag into a format
+const char* LogTags::tagToFormat(uint32_t tag) const {
+    tag2format_const_iterator iform;
+
+    android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+
+    iform = tag2format.find(tag);
+    if (iform == tag2format.end()) return NULL;
+
+    return iform->second.c_str();
+}
+
+// converts a name into an event tag
+uint32_t LogTags::nameToTag(const char* name) const {
+    uint32_t ret = emptyTag;
+
+    // Bug: Only works for a single entry, we can have multiple entries,
+    // one for each format, so we find first entry recorded, or entry with
+    // no format associated with it.
+
+    android::RWLock::AutoRLock readLock(const_cast<android::RWLock&>(rwlock));
+
+    key2tag_const_iterator ik = key2tag.find(std::string(name));
+    if (ik != key2tag.end()) ret = ik->second;
+
+    return ret;
+}
+
+// Caller must perform locks, can be under reader (for pre-check) or
+// writer lock.  We use this call to invent a new deterministically
+// random tag, unique is cleared if no conflicts.  If format is NULL,
+// we are in readonly mode.
+uint32_t LogTags::nameToTag_locked(const std::string& name, const char* format,
+                                   bool& unique) {
+    key2tag_const_iterator ik;
+
+    bool write = format != NULL;
+    unique = write;
+
+    if (!write) {
+        // Bug: Only works for a single entry, we can have multiple entries,
+        // one for each format, so we find first entry recorded, or entry with
+        // no format associated with it.
+        ik = key2tag.find(name);
+        if (ik == key2tag.end()) return emptyTag;
+        return ik->second;
+    }
+
+    std::string Key(name);
+    if (*format) Key += std::string("+") + format;
+
+    ik = key2tag.find(Key);
+    if (ik != key2tag.end()) {
+        unique = false;
+        return ik->second;
+    }
+
+    size_t Hash = key2tag.hash_function()(Key);
+    uint32_t Tag = Hash;
+    // This sets an upper limit on the conflics we are allowed to deal with.
+    for (unsigned i = 0; i < 256;) {
+        tag2name_const_iterator it = tag2name.find(Tag);
+        if (it == tag2name.end()) return Tag;
+        std::string localKey(it->second);
+        tag2format_const_iterator iform = tag2format.find(Tag);
+        if ((iform == tag2format.end()) && iform->second.length()) {
+            localKey += "+" + iform->second;
+        }
+        unique = !!it->second.compare(localKey);
+        if (!unique) return Tag;  // unlikely except in a race
+
+        ++i;
+        // Algorithm to convert hash to next tag
+        if (i < 32) {
+            Tag = (Hash >> i);
+            // size_t is 32 bits, or upper word zero, rotate
+            if ((sizeof(Hash) <= 4) || ((Hash & (uint64_t(-1LL) << 32)) == 0)) {
+                Tag |= Hash << (32 - i);
+            }
+        } else {
+            Tag = Hash + i - 31;
+        }
+    }
+    return emptyTag;
+}
+
+static int openFile(const char* name, int mode, bool warning) {
+    int fd = TEMP_FAILURE_RETRY(open(name, mode));
+    if ((fd < 0) && warning) {
+        android::prdebug("Failed open %s (%d)", name, errno);
+    }
+    return fd;
+}
+
+void LogTags::WritePmsgEventLogTags(uint32_t tag, uid_t uid) {
+    android::RWLock::AutoRLock readLock(rwlock);
+
+    tag2total_const_iterator itot = tag2total.find(tag);
+    if (itot == tag2total.end()) return;  // source is a static entry
+
+    size_t lastTotal = itot->second;
+
+    // Every 16K (half the smallest configurable pmsg buffer size) record
+    static const size_t rate_to_pmsg = 16 * 1024;
+    if (lastTotal && ((android::sizesTotal() - lastTotal) < rate_to_pmsg)) {
+        return;
+    }
+
+    static int pmsg_fd = -1;
+    if (pmsg_fd < 0) {
+        pmsg_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY | O_CLOEXEC));
+        // unlikely, but deal with partners with borken pmsg
+        if (pmsg_fd < 0) return;
+    }
+
+    std::string Name = tag2name[tag];
+    tag2format_const_iterator iform = tag2format.find(tag);
+    std::string Format = (iform != tag2format.end()) ? iform->second : "";
+
+    __android_log_event_list ctx(TAG_DEF_LOG_TAG);
+    ctx << tag << Name << Format;
+    std::string buffer(ctx);
+    if (buffer.length() <= 0) return;  // unlikely
+
+    /*
+     *  struct {
+     *      // what we provide to pstore
+     *      android_pmsg_log_header_t pmsgHeader;
+     *      // what we provide to file
+     *      android_log_header_t header;
+     *      // caller provides
+     *      union {
+     *          struct {
+     *              char     prio;
+     *              char     payload[];
+     *          } string;
+     *          struct {
+     *              uint32_t tag
+     *              char     payload[];
+     *          } binary;
+     *      };
+     *  };
+     */
+
+    struct timespec ts;
+    clock_gettime(android_log_clockid(), &ts);
+
+    android_log_header_t header = {
+        .id = LOG_ID_EVENTS,
+        .tid = (uint16_t)gettid(),
+        .realtime.tv_sec = (uint32_t)ts.tv_sec,
+        .realtime.tv_nsec = (uint32_t)ts.tv_nsec,
+    };
+
+    uint32_t outTag = TAG_DEF_LOG_TAG;
+    outTag = get4LE((const char*)&outTag);
+
+    android_pmsg_log_header_t pmsgHeader = {
+        .magic = LOGGER_MAGIC,
+        .len = (uint16_t)(sizeof(pmsgHeader) + sizeof(header) + sizeof(outTag) +
+                          buffer.length()),
+        .uid = (uint16_t)AID_ROOT,
+        .pid = (uint16_t)getpid(),
+    };
+
+    struct iovec Vec[] = { { (unsigned char*)&pmsgHeader, sizeof(pmsgHeader) },
+                           { (unsigned char*)&header, sizeof(header) },
+                           { (unsigned char*)&outTag, sizeof(outTag) },
+                           { (unsigned char*)const_cast<char*>(buffer.data()),
+                             buffer.length() } };
+
+    tag2uid_const_iterator ut = tag2uid.find(tag);
+    if (ut == tag2uid.end()) {
+        TEMP_FAILURE_RETRY(writev(pmsg_fd, Vec, arraysize(Vec)));
+    } else if (uid != AID_ROOT) {
+        pmsgHeader.uid = (uint16_t)uid;
+        TEMP_FAILURE_RETRY(writev(pmsg_fd, Vec, arraysize(Vec)));
+    } else {
+        for (auto& it : ut->second) {
+            pmsgHeader.uid = (uint16_t)it;
+            TEMP_FAILURE_RETRY(writev(pmsg_fd, Vec, arraysize(Vec)));
+        }
+    }
+}
+
+void LogTags::WriteDynamicEventLogTags(uint32_t tag, uid_t uid) {
+    static const int mode =
+        O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW | O_BINARY;
+
+    int fd = openFile(dynamic_event_log_tags, mode, true);
+    if (fd < 0) return;
+
+    android::RWLock::AutoWLock writeLock(rwlock);
+
+    std::string ret = formatEntry_locked(tag, uid, false);
+    android::base::WriteStringToFd(ret, fd);
+    TEMP_FAILURE_RETRY(close(fd));
+
+    size_t size = 0;
+    file2watermark_const_iterator iwater;
+
+    iwater = file2watermark.find(dynamic_event_log_tags);
+    if (iwater != file2watermark.end()) size = iwater->second;
+
+    file2watermark[dynamic_event_log_tags] = size + ret.length();
+}
+
+void LogTags::WriteDebugEventLogTags(uint32_t tag, uid_t uid) {
+    static const int mode =
+        O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW | O_BINARY;
+
+    static bool one = true;
+    int fd = openFile(debug_event_log_tags, mode, one);
+    one = fd >= 0;
+    if (!one) return;
+
+    android::RWLock::AutoWLock writeLock(rwlock);
+
+    std::string ret = formatEntry_locked(tag, uid, false);
+    android::base::WriteStringToFd(ret, fd);
+    TEMP_FAILURE_RETRY(close(fd));
+
+    size_t size = 0;
+    file2watermark_const_iterator iwater;
+
+    iwater = file2watermark.find(debug_event_log_tags);
+    if (iwater != file2watermark.end()) size = iwater->second;
+
+    file2watermark[debug_event_log_tags] = size + ret.length();
+}
+
+// How we maintain some runtime or reboot stickiness
+void LogTags::WritePersistEventLogTags(uint32_t tag, uid_t uid,
+                                       const char* source) {
+    // very unlikely
+    bool etc = source && !strcmp(source, system_event_log_tags);
+    if (etc) return;
+
+    bool dynamic = source && !strcmp(source, dynamic_event_log_tags);
+    bool debug = (!dynamic && source && !strcmp(source, debug_event_log_tags)) ||
+                 !__android_log_is_debuggable();
+
+    WritePmsgEventLogTags(tag, uid);
+
+    size_t lastTotal = 0;
+    {
+        android::RWLock::AutoRLock readLock(rwlock);
+
+        tag2total_const_iterator itot = tag2total.find(tag);
+        if (itot != tag2total.end()) lastTotal = itot->second;
+    }
+
+    if (lastTotal == 0) {  // denotes first time for this one
+        if (!dynamic || !RebuildFileEventLogTags(dynamic_event_log_tags)) {
+            WriteDynamicEventLogTags(tag, uid);
+        }
+
+        if (!debug && !RebuildFileEventLogTags(debug_event_log_tags)) {
+            WriteDebugEventLogTags(tag, uid);
+        }
+    }
+
+    lastTotal = android::sizesTotal();
+    if (!lastTotal) ++lastTotal;
+
+    // record totals for next watermark.
+    android::RWLock::AutoWLock writeLock(rwlock);
+    tag2total[tag] = lastTotal;
+}
+
+// nameToTag converts a name into an event tag. If format is NULL, then we
+// are in readonly mode.
+uint32_t LogTags::nameToTag(uid_t uid, const char* name, const char* format) {
+    std::string Name = std::string(name);
+    bool write = format != NULL;
+    bool updateUid = uid != AID_ROOT;
+    bool updateFormat = format && *format;
+    bool unique;
+    uint32_t Tag;
+
+    {
+        android::RWLock::AutoRLock readLock(rwlock);
+
+        Tag = nameToTag_locked(Name, format, unique);
+        if (updateUid && (Tag != emptyTag) && !unique) {
+            tag2uid_const_iterator ut = tag2uid.find(Tag);
+            if (updateUid) {
+                if ((ut != tag2uid.end()) &&
+                    (ut->second.find(uid) == ut->second.end())) {
+                    unique = write;  // write passthrough to update uid counts
+                    if (!write) Tag = emptyTag;  // deny read access
+                }
+            } else {
+                unique = write && (ut != tag2uid.end());
+            }
+        }
+    }
+
+    if (Tag == emptyTag) return Tag;
+    WritePmsgEventLogTags(Tag, uid);  // record references periodically
+    if (!unique) return Tag;
+
+    bool updateWrite = false;
+    bool updateTag;
+
+    // Special case of AddEventLogTags, checks per-uid counter which makes
+    // no sense there, and is also optimized somewhat to reduce write times.
+    {
+        android::RWLock::AutoWLock writeLock(rwlock);
+
+        // double check after switch from read lock to write lock for Tag
+        updateTag = tag2name.find(Tag) == tag2name.end();
+        // unlikely, either update, race inviting conflict or multiple uids
+        if (!updateTag) {
+            Tag = nameToTag_locked(Name, format, unique);
+            if (Tag == emptyTag) return Tag;
+            // is it multiple uid's setting this value
+            if (!unique) {
+                tag2uid_const_iterator ut = tag2uid.find(Tag);
+                if (updateUid) {
+                    // Add it to the uid list
+                    if ((ut == tag2uid.end()) ||
+                        (ut->second.find(uid) != ut->second.end())) {
+                        return Tag;
+                    }
+                    const_cast<uid_list&>(ut->second).emplace(uid);
+                    updateWrite = true;
+                } else {
+                    if (ut == tag2uid.end()) return Tag;
+                    // (system) adding a global one, erase the uid list
+                    tag2uid.erase(ut);
+                    updateWrite = true;
+                }
+            }
+        }
+
+        // Update section
+        size_t count;
+        if (updateUid) {
+            count = 0;
+            uid2count_const_iterator ci = uid2count.find(uid);
+            if (ci != uid2count.end()) {
+                count = ci->second;
+                if (count >= max_per_uid) {
+                    if (!updateWrite) return emptyTag;
+                    // If we are added to the per-Uid perms, leak the Tag
+                    // if it already exists.
+                    updateUid = false;
+                    updateTag = false;
+                    updateFormat = false;
+                }
+            }
+        }
+
+        // updateWrite -> trigger output on modified content, reset tag2total
+        //    also sets static to dynamic entries if they are alterred,
+        //    only occurs if they have a uid, and runtime adds another uid.
+        if (updateWrite) tag2total[Tag] = 0;
+
+        if (updateTag) {
+            // mark as a dynamic entry, but do not upset current total counter
+            tag2total_const_iterator itot = tag2total.find(Tag);
+            if (itot == tag2total.end()) tag2total[Tag] = 0;
+
+            if (*format) {
+                key2tag[Name + "+" + format] = Tag;
+                if (key2tag.find(Name) == key2tag.end()) key2tag[Name] = Tag;
+            } else {
+                key2tag[Name] = Tag;
+            }
+            tag2name[Tag] = Name;
+        }
+        if (updateFormat) tag2format[Tag] = format;
+
+        if (updateUid) {
+            tag2uid[Tag].emplace(uid);
+            uid2count[uid] = count + 1;
+        }
+    }
+
+    if (updateTag || updateFormat || updateWrite) {
+        WritePersistEventLogTags(Tag, uid);
+    }
+
+    return Tag;
+}
+
+std::string LogTags::formatEntry(uint32_t tag, uid_t uid, const char* name,
+                                 const char* format) {
+    if (!format || !format[0]) {
+        return android::base::StringPrintf("%" PRIu32 "\t%s\n", tag, name);
+    }
+    size_t len = (strlen(name) + 7) / 8;
+    static const char tabs[] = "\t\t\t";
+    if (len > strlen(tabs)) len = strlen(tabs);
+    std::string Uid;
+    if (uid != AID_ROOT) Uid = android::base::StringPrintf(" # uid=%u", uid);
+    return android::base::StringPrintf("%" PRIu32 "\t%s%s\t%s%s\n", tag, name,
+                                       &tabs[len], format, Uid.c_str());
+}
+
+std::string LogTags::formatEntry_locked(uint32_t tag, uid_t uid,
+                                        bool authenticate) {
+    const char* name = tag2name[tag].c_str();
+
+    const char* format = "";
+    tag2format_const_iterator iform = tag2format.find(tag);
+    if (iform != tag2format.end()) format = iform->second.c_str();
+
+    // Access permission test, do not report dynamic entries
+    // that do not belong to us.
+    tag2uid_const_iterator ut = tag2uid.find(tag);
+    if (ut == tag2uid.end()) {
+        return formatEntry(tag, AID_ROOT, name, format);
+    }
+    if (uid != AID_ROOT) {
+        if (authenticate && (ut->second.find(uid) == ut->second.end())) {
+            return std::string("");
+        }
+        return formatEntry(tag, uid, name, format);
+    }
+
+    // Show all, one for each registered uid (we are group root)
+    std::string ret;
+    for (auto& it : ut->second) {
+        ret += formatEntry(tag, it, name, format);
+    }
+    return ret;
+}
+
+std::string LogTags::formatEntry(uint32_t tag, uid_t uid) {
+    android::RWLock::AutoRLock readLock(rwlock);
+    return formatEntry_locked(tag, uid);
+}
+
+std::string LogTags::formatGetEventTag(uid_t uid, const char* name,
+                                       const char* format) {
+    bool all = name && (name[0] == '*') && !name[1];
+    bool list = !name || all;
+    std::string ret;
+
+    if (!list) {
+        // switch to read entry only if format == "*"
+        if (format && (format[0] == '*') && !format[1]) format = NULL;
+
+        // WAI: for null format, only works for a single entry, we can have
+        // multiple entries, one for each format, so we find first entry
+        // recorded, or entry with no format associated with it.
+        // We may desire to print all that match the name, but we did not
+        // add a mapping table for that and the cost is too high.
+        uint32_t tag = nameToTag(uid, name, format);
+        if (tag == emptyTag) return std::string("-1 ESRCH");
+        if (uid == AID_ROOT) {
+            android::RWLock::AutoRLock readLock(rwlock);
+
+            // first uid in list so as to manufacture an accurate reference
+            tag2uid_const_iterator ut = tag2uid.find(tag);
+            if ((ut != tag2uid.end()) &&
+                (ut->second.begin() != ut->second.end())) {
+                uid = *(ut->second.begin());
+            }
+        }
+        ret = formatEntry(tag, uid, name, format ?: tagToFormat(tag));
+        if (!ret.length()) return std::string("-1 ESRCH");
+        return ret;
+    }
+
+    android::RWLock::AutoRLock readLock(rwlock);
+    if (all) {
+        // everything under the sun
+        for (const auto& it : tag2name) {
+            ret += formatEntry_locked(it.first, uid);
+        }
+    } else {
+        // set entries are dynamic
+        for (const auto& it : tag2total) {
+            ret += formatEntry_locked(it.first, uid);
+        }
+    }
+    return ret;
+}
diff --git a/logd/LogTags.h b/logd/LogTags.h
new file mode 100644
index 0000000..203318d
--- /dev/null
+++ b/logd/LogTags.h
@@ -0,0 +1,124 @@
+/*
+ * 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 _LOGD_LOG_TAGS_H__
+#define _LOGD_LOG_TAGS_H__
+
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+
+#include <utils/RWLock.h>
+
+class LogTags {
+    // This lock protects all the unordered_map accesses below.  It
+    // is a reader/writer lock so that contentions are kept to a
+    // minimum since writes are rare, even administratably when
+    // reads are extended.  Resist the temptation to use the writer
+    // lock to protect anything outside the following unordered_maps
+    // as that would increase the reader contentions.  Use a separate
+    // mutex to protect the other entities.
+    android::RWLock rwlock;
+
+    // key is Name + "+" + Format
+    std::unordered_map<std::string, uint32_t> key2tag;
+    typedef std::unordered_map<std::string, uint32_t>::const_iterator
+        key2tag_const_iterator;
+
+    // Allows us to manage access permissions based on uid registrants
+    // Global entries are specifically erased.
+    typedef std::unordered_set<uid_t> uid_list;
+    std::unordered_map<uint32_t, uid_list> tag2uid;
+    typedef std::unordered_map<uint32_t, uid_list>::const_iterator
+        tag2uid_const_iterator;
+
+    std::unordered_map<uint32_t, std::string> tag2name;
+    typedef std::unordered_map<uint32_t, std::string>::const_iterator
+        tag2name_const_iterator;
+
+    std::unordered_map<uint32_t, std::string> tag2format;
+    typedef std::unordered_map<uint32_t, std::string>::const_iterator
+        tag2format_const_iterator;
+
+    static const size_t max_per_uid = 256;  // Put a cap on the tags per uid
+    std::unordered_map<uid_t, size_t> uid2count;
+    typedef std::unordered_map<uid_t, size_t>::const_iterator
+        uid2count_const_iterator;
+
+    // Dynamic entries are assigned
+    std::unordered_map<uint32_t, size_t> tag2total;
+    typedef std::unordered_map<uint32_t, size_t>::const_iterator
+        tag2total_const_iterator;
+
+    // emplace unique tag
+    uint32_t nameToTag(uid_t uid, const char* name, const char* format);
+    // find unique or associated tag
+    uint32_t nameToTag_locked(const std::string& name, const char* format,
+                              bool& unique);
+
+    // Record expected file watermarks to detect corruption.
+    std::unordered_map<std::string, size_t> file2watermark;
+    typedef std::unordered_map<std::string, size_t>::const_iterator
+        file2watermark_const_iterator;
+
+    void ReadPersistEventLogTags();
+
+    // format helpers
+    // format a single entry, does not need object data
+    static std::string formatEntry(uint32_t tag, uid_t uid, const char* name,
+                                   const char* format);
+    // caller locks, database lookup, authenticate against uid
+    std::string formatEntry_locked(uint32_t tag, uid_t uid,
+                                   bool authenticate = true);
+
+    bool RebuildFileEventLogTags(const char* filename, bool warn = true);
+
+    void AddEventLogTags(uint32_t tag, uid_t uid, const std::string& Name,
+                         const std::string& Format, const char* source = NULL,
+                         bool warn = false);
+
+    void WriteDynamicEventLogTags(uint32_t tag, uid_t uid);
+    void WriteDebugEventLogTags(uint32_t tag, uid_t uid);
+    // push tag details to persistent storage
+    void WritePersistEventLogTags(uint32_t tag, uid_t uid = AID_ROOT,
+                                  const char* source = NULL);
+
+    static const uint32_t emptyTag = uint32_t(-1);
+
+   public:
+    static const char system_event_log_tags[];
+    static const char dynamic_event_log_tags[];
+    // Only for userdebug and eng
+    static const char debug_event_log_tags[];
+
+    LogTags();
+
+    void WritePmsgEventLogTags(uint32_t tag, uid_t uid = AID_ROOT);
+    void ReadFileEventLogTags(const char* filename, bool warn = true);
+
+    // reverse lookup from tag
+    const char* tagToName(uint32_t tag) const;
+    const char* tagToFormat(uint32_t tag) const;
+    std::string formatEntry(uint32_t tag, uid_t uid);
+    // find associated tag
+    uint32_t nameToTag(const char* name) const;
+
+    // emplace tag if necessary, provide event-log-tag formated output in string
+    std::string formatGetEventTag(uid_t uid, const char* name,
+                                  const char* format);
+};
+
+#endif  // _LOGD_LOG_TAGS_H__
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index 2a04880..ccc550a 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -15,37 +15,41 @@
  */
 
 #include <errno.h>
+#include <string.h>
 #include <sys/prctl.h>
 
+#include <private/android_logger.h>
+
 #include "FlushCommand.h"
 #include "LogBuffer.h"
-#include "LogTimes.h"
 #include "LogReader.h"
+#include "LogTimes.h"
 
 pthread_mutex_t LogTimeEntry::timesLock = PTHREAD_MUTEX_INITIALIZER;
 
-LogTimeEntry::LogTimeEntry(LogReader &reader, SocketClient *client,
+LogTimeEntry::LogTimeEntry(LogReader& reader, SocketClient* client,
                            bool nonBlock, unsigned long tail,
-                           unsigned int logMask, pid_t pid,
-                           uint64_t start, uint64_t timeout) :
-        mRefCount(1),
-        mRelease(false),
-        mError(false),
-        threadRunning(false),
-        leadingDropped(false),
-        mReader(reader),
-        mLogMask(logMask),
-        mPid(pid),
-        mCount(0),
-        mTail(tail),
-        mIndex(0),
-        mClient(client),
-        mStart(start),
-        mNonBlock(nonBlock),
-        mEnd(LogBufferElement::getCurrentSequence()) {
+                           unsigned int logMask, pid_t pid, log_time start,
+                           uint64_t timeout)
+    : mRefCount(1),
+      mRelease(false),
+      mError(false),
+      threadRunning(false),
+      leadingDropped(false),
+      mReader(reader),
+      mLogMask(logMask),
+      mPid(pid),
+      mCount(0),
+      mTail(tail),
+      mIndex(0),
+      mClient(client),
+      mStart(start),
+      mNonBlock(nonBlock),
+      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();
 }
 
@@ -56,8 +60,8 @@
 
     if (!pthread_attr_init(&attr)) {
         if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
-            if (!pthread_create(&mThread, &attr,
-                                LogTimeEntry::threadStart, this)) {
+            if (!pthread_create(&mThread, &attr, LogTimeEntry::threadStart,
+                                this)) {
                 pthread_attr_destroy(&attr);
                 return;
             }
@@ -71,8 +75,8 @@
     decRef_Locked();
 }
 
-void LogTimeEntry::threadStop(void *obj) {
-    LogTimeEntry *me = reinterpret_cast<LogTimeEntry *>(obj);
+void LogTimeEntry::threadStop(void* obj) {
+    LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
     lock();
 
@@ -80,14 +84,14 @@
         me->error_Locked();
     }
 
-    SocketClient *client = me->mClient;
+    SocketClient* client = me->mClient;
 
     if (me->isError_Locked()) {
-        LogReader &reader = me->mReader;
-        LastLogTimes &times = reader.logbuf().mTimes;
+        LogReader& reader = me->mReader;
+        LastLogTimes& times = reader.logbuf().mTimes;
 
         LastLogTimes::iterator it = times.begin();
-        while(it != times.end()) {
+        while (it != times.end()) {
             if (*it == me) {
                 times.erase(it);
                 me->release_nodelete_Locked();
@@ -96,7 +100,7 @@
             it++;
         }
 
-        me->mClient = NULL;
+        me->mClient = nullptr;
         reader.release(client);
     }
 
@@ -110,20 +114,20 @@
     unlock();
 }
 
-void *LogTimeEntry::threadStart(void *obj) {
+void* LogTimeEntry::threadStart(void* obj) {
     prctl(PR_SET_NAME, "logd.reader.per");
 
-    LogTimeEntry *me = reinterpret_cast<LogTimeEntry *>(obj);
+    LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
     pthread_cleanup_push(threadStop, obj);
 
-    SocketClient *client = me->mClient;
+    SocketClient* client = me->mClient;
     if (!client) {
         me->error();
-        return NULL;
+        return nullptr;
     }
 
-    LogBuffer &logbuf = me->mReader.logbuf();
+    LogBuffer& logbuf = me->mReader.logbuf();
 
     bool privileged = FlushCommand::hasReadLogs(client);
     bool security = FlushCommand::hasSecurityLogs(client);
@@ -132,14 +136,12 @@
 
     lock();
 
-    uint64_t start = me->mStart;
+    log_time start = me->mStart;
 
     while (me->threadRunning && !me->isError_Locked()) {
-
         if (me->mTimeout.tv_sec || me->mTimeout.tv_nsec) {
             if (pthread_cond_timedwait(&me->threadTriggeredCondition,
-                                       &timesLock,
-                                       &me->mTimeout) == ETIMEDOUT) {
+                                       &timesLock, &me->mTimeout) == ETIMEDOUT) {
                 me->mTimeout.tv_sec = 0;
                 me->mTimeout.tv_nsec = 0;
             }
@@ -151,10 +153,12 @@
         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();
 
@@ -163,7 +167,7 @@
             break;
         }
 
-        me->mStart = start + 1;
+        me->mStart = start + log_time(0, 1);
 
         if (me->mNonBlock || !me->threadRunning || me->isError_Locked()) {
             break;
@@ -180,12 +184,12 @@
 
     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);
+int LogTimeEntry::FilterFirstPass(const LogBufferElement* element, void* obj) {
+    LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
     LogTimeEntry::lock();
 
@@ -198,11 +202,11 @@
     }
 
     if (me->mCount == 0) {
-        me->mStart = element->getSequence();
+        me->mStart = element->getRealTime();
     }
 
-    if ((!me->mPid || (me->mPid == element->getPid()))
-            && (me->isWatching(element->getLogId()))) {
+    if ((!me->mPid || (me->mPid == element->getPid())) &&
+        (me->isWatching(element->getLogId()))) {
         ++me->mCount;
     }
 
@@ -212,12 +216,12 @@
 }
 
 // A second pass to send the selected elements
-int LogTimeEntry::FilterSecondPass(const LogBufferElement *element, void *obj) {
-    LogTimeEntry *me = reinterpret_cast<LogTimeEntry *>(obj);
+int LogTimeEntry::FilterSecondPass(const LogBufferElement* element, void* obj) {
+    LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
     LogTimeEntry::lock();
 
-    me->mStart = element->getSequence();
+    me->mStart = element->getRealTime();
 
     if (me->skipAhead[element->getLogId()]) {
         me->skipAhead[element->getLogId()]--;
@@ -267,7 +271,7 @@
         LogTimeEntry::unlock();
         return true;
     }
-    // FALLTHRU
+// FALLTHRU
 
 skip:
     LogTimeEntry::unlock();
@@ -279,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 b66ff9e..ec8252e 100644
--- a/logd/LogTimes.h
+++ b/logd/LogTimes.h
@@ -18,13 +18,13 @@
 #define _LOGD_LOG_TIMES_H__
 
 #include <pthread.h>
-#include <time.h>
 #include <sys/types.h>
+#include <time.h>
 
 #include <list>
 
-#include <sysutils/SocketClient.h>
 #include <log/log.h>
+#include <sysutils/SocketClient.h>
 
 class LogReader;
 class LogBufferElement;
@@ -38,30 +38,35 @@
     bool leadingDropped;
     pthread_cond_t threadTriggeredCondition;
     pthread_t mThread;
-    LogReader &mReader;
-    static void *threadStart(void *me);
-    static void threadStop(void *me);
+    LogReader& mReader;
+    static void* threadStart(void* me);
+    static void threadStop(void* me);
     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;
 
-public:
-    LogTimeEntry(LogReader &reader, SocketClient *client, bool nonBlock,
+   public:
+    LogTimeEntry(LogReader& reader, SocketClient* client, bool nonBlock,
                  unsigned long tail, unsigned int logMask, pid_t pid,
-                 uint64_t start, uint64_t timeout);
+                 log_time start, uint64_t timeout);
 
-    SocketClient *mClient;
-    uint64_t mStart;
+    SocketClient* mClient;
+    log_time mStart;
     struct timespec mTimeout;
     const bool mNonBlock;
-    const uint64_t mEnd; // only relevant if mNonBlock
+    const log_time mEnd;  // only relevant if mNonBlock
 
     // Protect List manipulations
-    static void lock(void) { pthread_mutex_lock(&timesLock); }
-    static void unlock(void) { pthread_mutex_unlock(&timesLock); }
+    static void lock(void) {
+        pthread_mutex_lock(&timesLock);
+    }
+    static void unlock(void) {
+        pthread_mutex_unlock(&timesLock);
+    }
 
     void startReader_Locked(void);
 
@@ -72,7 +77,9 @@
         pthread_cond_signal(&threadTriggeredCondition);
     }
 
-    void triggerSkip_Locked(log_id_t id, unsigned int skip) { skipAhead[id] = skip; }
+    void triggerSkip_Locked(log_id_t id, unsigned int skip) {
+        skipAhead[id] = skip;
+    }
     void cleanSkip_Locked(void);
 
     // These called after LogTimeEntry removed from list, lock implicitly held
@@ -93,16 +100,28 @@
     }
 
     // Called to mark socket in jeopardy
-    void error_Locked(void) { mError = true; }
-    void error(void) { lock(); error_Locked(); unlock(); }
+    void error_Locked(void) {
+        mError = true;
+    }
+    void error(void) {
+        lock();
+        error_Locked();
+        unlock();
+    }
 
-    bool isError_Locked(void) const { return mRelease || mError; }
+    bool isError_Locked(void) const {
+        return mRelease || mError;
+    }
 
     // Mark Used
     //  Locking implied, grabbed when protection around loop iteration
-    void incRef_Locked(void) { ++mRefCount; }
+    void incRef_Locked(void) {
+        ++mRefCount;
+    }
 
-    bool owned_Locked(void) const { return mRefCount != 0; }
+    bool owned_Locked(void) const {
+        return mRefCount != 0;
+    }
 
     void decRef_Locked(void) {
         if ((mRefCount && --mRefCount) || !mRelease || threadRunning) {
@@ -111,12 +130,14 @@
         // No one else is holding a reference to this
         delete this;
     }
-    bool isWatching(log_id_t id) { return (mLogMask & (1<<id)) != 0; }
+    bool isWatching(log_id_t id) {
+        return (mLogMask & (1 << id)) != 0;
+    }
     // flushTo filter callbacks
-    static int FilterFirstPass(const LogBufferElement *element, void *me);
-    static int FilterSecondPass(const LogBufferElement *element, void *me);
+    static int FilterFirstPass(const LogBufferElement* element, void* me);
+    static int FilterSecondPass(const LogBufferElement* element, void* me);
 };
 
-typedef std::list<LogTimeEntry *> LastLogTimes;
+typedef std::list<LogTimeEntry*> LastLogTimes;
 
-#endif // _LOGD_LOG_TIMES_H__
+#endif  // _LOGD_LOG_TIMES_H__
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index fd4800e..fa9f398 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -17,10 +17,12 @@
 #ifndef _LOGD_LOG_UTILS_H__
 #define _LOGD_LOG_UTILS_H__
 
+#include <sys/cdefs.h>
 #include <sys/types.h>
 
-#include <log/log.h>
+#include <private/android_logger.h>
 #include <sysutils/SocketClient.h>
+#include <utils/FastStrcmp.h>
 
 // Hijack this header as a common include file used by most all sources
 // to report some utilities defined here and there.
@@ -28,50 +30,47 @@
 namespace android {
 
 // Furnished in main.cpp. Caller must own and free returned value
-char *uidToName(uid_t uid);
+char* uidToName(uid_t uid);
+void prdebug(const char* fmt, ...) __printflike(1, 2);
 
-// Furnished in LogStatistics.cpp. Caller must own and free returned value
-char *pidToName(pid_t pid);
-char *tidToName(pid_t tid);
+// Furnished in LogStatistics.cpp.
+size_t sizesTotal();
+// Caller must own and free returned value
+char* pidToName(pid_t pid);
+char* tidToName(pid_t tid);
 
-// Furnished in main.cpp. Thread safe.
-const char *tagToName(uint32_t tag);
+// Furnished in LogTags.cpp. Thread safe.
+const char* tagToName(uint32_t tag);
+void ReReadEventLogTags();
 
+// 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
 bool clientHasLogCredentials(uid_t uid, gid_t gid, pid_t pid);
-bool clientHasLogCredentials(SocketClient *cli);
-
-// Furnished in main.cpp
-#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
-#define BOOL_DEFAULT_FLAG_PERSIST    0x2 // <key>, persist.<key>, ro.<key>
-#define BOOL_DEFAULT_FLAG_ENG        0x4 // off for user
-#define BOOL_DEFAULT_FLAG_SVELTE     0x8 // off for low_ram
-
-bool property_get_bool(const char *key, int def);
+bool clientHasLogCredentials(SocketClient* cli);
 
 static inline bool worstUidEnabledForLogid(log_id_t id) {
-    return (id == LOG_ID_MAIN) || (id == LOG_ID_SYSTEM) || (id == LOG_ID_RADIO);
+    return (id == LOG_ID_MAIN) || (id == LOG_ID_SYSTEM) ||
+           (id == LOG_ID_RADIO) || (id == LOG_ID_EVENTS);
 }
 
-template <int (*cmp)(const char *l, const char *r, const size_t s)>
-static inline int fast(const char *l, const char *r, const size_t s) {
-    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
-}
-
-template <int (*cmp)(const void *l, const void *r, const size_t s)>
-static inline int fast(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)>
-static inline int fast(const char *l, const char *r) {
-    return (*l != *r) || cmp(l + 1, r + 1);
-}
-
-#endif // _LOGD_LOG_UTILS_H__
+#endif  // _LOGD_LOG_UTILS_H__
diff --git a/logd/LogWhiteBlackList.cpp b/logd/LogWhiteBlackList.cpp
index ae933b5..4b8b080 100644
--- a/logd/LogWhiteBlackList.cpp
+++ b/logd/LogWhiteBlackList.cpp
@@ -64,7 +64,7 @@
     }
 }
 
-int PruneList::init(const char *str) {
+int PruneList::init(const char* str) {
     mWorstUidEnabled = true;
     mWorstPidOfSystemEnabled = true;
     PruneCollection::iterator it;
@@ -113,13 +113,13 @@
     mWorstUidEnabled = false;
     mWorstPidOfSystemEnabled = false;
 
-    for(str = filter.c_str(); *str; ++str) {
+    for (str = filter.c_str(); *str; ++str) {
         if (isspace(*str)) {
             continue;
         }
 
-        PruneCollection *list;
-        if ((*str == '~') || (*str == '!')) { // ~ supported, ! undocumented
+        PruneCollection* list;
+        if ((*str == '~') || (*str == '!')) {  // ~ supported, ! undocumented
             ++str;
             // special case, translates to worst UID at priority in blacklist
             if (*str == '!') {
@@ -184,7 +184,7 @@
         // insert sequentially into list
         PruneCollection::iterator it = list->begin();
         while (it != list->end()) {
-            Prune &p = *it;
+            Prune& p = *it;
             int m = uid - p.mUid;
             if (m == 0) {
                 if (p.mPid == p.pid_all) {
@@ -198,14 +198,14 @@
             }
             if (m <= 0) {
                 if (m < 0) {
-                    list->insert(it, Prune(uid,pid));
+                    list->insert(it, Prune(uid, pid));
                 }
                 break;
             }
             ++it;
         }
         if (it == list->end()) {
-            list->push_back(Prune(uid,pid));
+            list->push_back(Prune(uid, pid));
         }
         if (!*str) {
             break;
@@ -217,7 +217,7 @@
 
 std::string PruneList::format() {
     static const char nice_format[] = " %s";
-    const char *fmt = nice_format + 1;
+    const char* fmt = nice_format + 1;
 
     std::string string;
 
@@ -250,7 +250,7 @@
 // If there is scaling issues, resort to a better algorithm than linear
 // based on these assumptions.
 
-bool PruneList::naughty(LogBufferElement *element) {
+bool PruneList::naughty(LogBufferElement* element) {
     PruneCollection::iterator it;
     for (it = mNaughty.begin(); it != mNaughty.end(); ++it) {
         if (!(*it).cmp(element)) {
@@ -260,7 +260,7 @@
     return false;
 }
 
-bool PruneList::nice(LogBufferElement *element) {
+bool PruneList::nice(LogBufferElement* element) {
     PruneCollection::iterator it;
     for (it = mNice.begin(); it != mNice.end(); ++it) {
         if (!(*it).cmp(element)) {
diff --git a/logd/LogWhiteBlackList.h b/logd/LogWhiteBlackList.h
index 8b8e02f..6e9893b 100644
--- a/logd/LogWhiteBlackList.h
+++ b/logd/LogWhiteBlackList.h
@@ -19,8 +19,8 @@
 
 #include <sys/types.h>
 
-#include <list>
 #include <string.h>
+#include <list>
 
 #include "LogBufferElement.h"
 
@@ -33,16 +33,22 @@
     const pid_t mPid;
     int cmp(uid_t uid, pid_t pid) const;
 
-public:
-    static const uid_t uid_all = (uid_t) -1;
-    static const pid_t pid_all = (pid_t) -1;
+   public:
+    static const uid_t uid_all = (uid_t)-1;
+    static const pid_t pid_all = (pid_t)-1;
 
     Prune(uid_t uid, pid_t pid);
 
-    uid_t getUid() const { return mUid; }
-    pid_t getPid() const { return mPid; }
+    uid_t getUid() const {
+        return mUid;
+    }
+    pid_t getPid() const {
+        return mPid;
+    }
 
-    int cmp(LogBufferElement *e) const { return cmp(e->getUid(), e->getPid()); }
+    int cmp(LogBufferElement* e) const {
+        return cmp(e->getUid(), e->getPid());
+    }
 
     std::string format();
 };
@@ -55,20 +61,28 @@
     bool mWorstUidEnabled;
     bool mWorstPidOfSystemEnabled;
 
-public:
+   public:
     PruneList();
     ~PruneList();
 
-    int init(const char *str);
+    int init(const char* str);
 
-    bool naughty(LogBufferElement *element);
-    bool naughty(void) { return !mNaughty.empty(); }
-    bool nice(LogBufferElement *element);
-    bool nice(void) { return !mNice.empty(); }
-    bool worstUidEnabled() const { return mWorstUidEnabled; }
-    bool worstPidOfSystemEnabled() const { return mWorstPidOfSystemEnabled; }
+    bool naughty(LogBufferElement* element);
+    bool naughty(void) {
+        return !mNaughty.empty();
+    }
+    bool nice(LogBufferElement* element);
+    bool nice(void) {
+        return !mNice.empty();
+    }
+    bool worstUidEnabled() const {
+        return mWorstUidEnabled;
+    }
+    bool worstPidOfSystemEnabled() const {
+        return mWorstPidOfSystemEnabled;
+    }
 
     std::string format();
 };
 
-#endif // _LOGD_LOG_WHITE_BLACK_LIST_H__
+#endif  // _LOGD_LOG_WHITE_BLACK_LIST_H__
diff --git a/logd/README.property b/logd/README.property
index b2708e4..de6767a 100644
--- a/logd/README.property
+++ b/logd/README.property
@@ -2,13 +2,14 @@
 
 name                       type default  description
 ro.logd.auditd             bool   true   Enable selinux audit daemon
-ro.logd.auditd.dmesg       bool   true   selinux audit messages duplicated and
-                                         sent on to dmesg log
+ro.logd.auditd.dmesg       bool   true   selinux audit messages sent to dmesg.
+ro.logd.auditd.main        bool   true   selinux audit messages sent to main.
+ro.logd.auditd.events      bool   true   selinux audit messages sent to events.
 persist.logd.security      bool   false  Enable security buffer.
 ro.device_owner            bool   false  Override persist.logd.security to false
 ro.logd.kernel             bool+ svelte+ Enable klogd daemon
 ro.logd.statistics         bool+ svelte+ Enable logcat -S statistics.
-ro.build.type              string        if user, logd.statistics &
+ro.debuggable              number        if not "1", logd.statistics &
                                          ro.logd.kernel default false.
 logd.logpersistd.enable    bool   auto   Safe to start logpersist daemon service
 logd.logpersistd          string persist Enable logpersist daemon, "logcatd"
@@ -55,10 +56,10 @@
 NB:
 - auto - managed by /init
 - bool+ - "true", "false" and comma separated list of "eng" (forced false if
-  ro.build.type is "user") or "svelte" (forced false if ro.config.low_ram is
+  ro.debuggable is not "1") or "svelte" (forced false if ro.config.low_ram is
   true).
 - svelte - see ro.config.low_ram for details.
-- svelte+ - see ro.config.low_ram and ro.build.type for details.
+- svelte+ - see ro.config.low_ram and ro.debuggable for details.
 - ro - <base property> temporary override, ro.<base property> platform default.
 - persist - <base property> override, persist.<base property> platform default.
 - build - VERBOSE for native, DEBUG for jvm isLoggable, or developer option.
diff --git a/logd/event.logtags b/logd/event.logtags
index db8c19b..39063a9 100644
--- a/logd/event.logtags
+++ b/logd/event.logtags
@@ -34,4 +34,5 @@
 # TODO: generate ".java" and ".h" files with integer constants from this file.
 
 1003  auditd (avc|3)
-1004  logd (dropped|3)
+1004  chatty (dropped|3)
+1005  tag_def (tag|1),(name|3),(format|3)
diff --git a/logd/libaudit.c b/logd/libaudit.c
index d00d579..dfd56f2 100644
--- a/logd/libaudit.c
+++ b/logd/libaudit.c
@@ -22,22 +22,16 @@
 #include <string.h>
 #include <unistd.h>
 
-#define LOG_TAG "libaudit"
-#include <log/log.h>
-
 #include "libaudit.h"
 
 /**
  * Waits for an ack from the kernel
  * @param fd
  *  The netlink socket fd
- * @param seq
- *  The current sequence number were acking on
  * @return
  *  This function returns 0 on success, else -errno.
  */
-static int get_ack(int fd, int16_t seq)
-{
+static int get_ack(int fd) {
     int rc;
     struct audit_message rep;
 
@@ -53,17 +47,12 @@
 
     if (rep.nlh.nlmsg_type == NLMSG_ERROR) {
         audit_get_reply(fd, &rep, GET_REPLY_BLOCKING, 0);
-        rc = ((struct nlmsgerr *)rep.data)->error;
+        rc = ((struct nlmsgerr*)rep.data)->error;
         if (rc) {
             return -rc;
         }
     }
 
-    if ((int16_t)rep.nlh.nlmsg_seq != seq) {
-        SLOGW("Expected sequence number between user space and kernel space is out of skew, "
-          "expected %u got %u", seq, rep.nlh.nlmsg_seq);
-    }
-
     return 0;
 }
 
@@ -80,8 +69,7 @@
  * @return
  *  This function returns a positive sequence number on success, else -errno.
  */
-static int audit_send(int fd, int type, const void *data, size_t size)
-{
+static int audit_send(int fd, int type, const void* data, size_t size) {
     int rc;
     static int16_t sequence = 0;
     struct audit_message req;
@@ -108,7 +96,6 @@
 
     /* Ensure the message is not too big */
     if (NLMSG_SPACE(size) > MAX_AUDIT_MESSAGE_LENGTH) {
-        SLOGE("netlink message is too large");
         return -EINVAL;
     }
 
@@ -134,36 +121,33 @@
     /* While failing and its due to interrupts */
 
     rc = TEMP_FAILURE_RETRY(sendto(fd, &req, req.nlh.nlmsg_len, 0,
-                                   (struct sockaddr*) &addr, sizeof(addr)));
+                                   (struct sockaddr*)&addr, sizeof(addr)));
 
     /* Not all the bytes were sent */
     if (rc < 0) {
         rc = -errno;
-        SLOGE("Error sending data over the netlink socket: %s", strerror(-errno));
         goto out;
-    } else if ((uint32_t) rc != req.nlh.nlmsg_len) {
+    } else if ((uint32_t)rc != req.nlh.nlmsg_len) {
         rc = -EPROTO;
         goto out;
     }
 
     /* We sent all the bytes, get the ack */
-    rc = get_ack(fd, sequence);
+    rc = get_ack(fd);
 
     /* If the ack failed, return the error, else return the sequence number */
-    rc = (rc == 0) ? (int) sequence : rc;
+    rc = (rc == 0) ? (int)sequence : rc;
 
 out:
     /* Don't let sequence roll to negative */
     if (sequence < 0) {
-        SLOGW("Auditd to Kernel sequence number has rolled over");
         sequence = 0;
     }
 
     return rc;
 }
 
-int audit_setup(int fd, uint32_t pid)
-{
+int audit_setup(int fd, pid_t pid) {
     int rc;
     struct audit_message rep;
     struct audit_status status;
@@ -176,13 +160,11 @@
      * and the the mask set to AUDIT_STATUS_PID
      */
     status.pid = pid;
-    status.mask = AUDIT_STATUS_PID | AUDIT_STATUS_RATE_LIMIT;
-    status.rate_limit = 20; // audit entries per second
+    status.mask = AUDIT_STATUS_PID;
 
     /* Let the kernel know this pid will be registering for audit events */
     rc = audit_send(fd, AUDIT_SET, &status, sizeof(status));
     if (rc < 0) {
-        SLOGE("Could net set pid for audit events, error: %s", strerror(-rc));
         return rc;
     }
 
@@ -201,13 +183,31 @@
     return 0;
 }
 
-int audit_open()
-{
+int audit_rate_limit(int fd, unsigned rate_limit) {
+    int rc;
+    struct audit_message rep;
+    struct audit_status status;
+
+    memset(&status, 0, sizeof(status));
+
+    status.mask = AUDIT_STATUS_RATE_LIMIT;
+    status.rate_limit = rate_limit; /* audit entries per second */
+
+    rc = audit_send(fd, AUDIT_SET, &status, sizeof(status));
+    if (rc < 0) {
+        return rc;
+    }
+
+    audit_get_reply(fd, &rep, GET_REPLY_NONBLOCKING, 0);
+
+    return 0;
+}
+
+int audit_open() {
     return socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT);
 }
 
-int audit_get_reply(int fd, struct audit_message *rep, reply_t block, int peek)
-{
+int audit_get_reply(int fd, struct audit_message* rep, reply_t block, int peek) {
     ssize_t len;
     int flags;
     int rc = 0;
@@ -229,7 +229,7 @@
      * however, can be returned.
      */
     len = TEMP_FAILURE_RETRY(recvfrom(fd, rep, sizeof(*rep), flags,
-                                      (struct sockaddr*) &nladdr, &nladdrlen));
+                                      (struct sockaddr*)&nladdr, &nladdrlen));
 
     /*
      * EAGAIN should be re-tried until success or another error manifests.
@@ -240,35 +240,26 @@
             /* If request is non blocking and errno is EAGAIN, just return 0 */
             return 0;
         }
-        SLOGE("Error receiving from netlink socket, error: %s", strerror(-rc));
         return rc;
     }
 
     if (nladdrlen != sizeof(nladdr)) {
-        SLOGE("Protocol fault, error: %s", strerror(EPROTO));
         return -EPROTO;
     }
 
     /* Make sure the netlink message was not spoof'd */
     if (nladdr.nl_pid) {
-        SLOGE("Invalid netlink pid received, expected 0 got: %d", nladdr.nl_pid);
         return -EINVAL;
     }
 
     /* Check if the reply from the kernel was ok */
     if (!NLMSG_OK(&rep->nlh, (size_t)len)) {
         rc = (len == sizeof(*rep)) ? -EFBIG : -EBADE;
-        SLOGE("Bad kernel response %s", strerror(-rc));
     }
 
     return rc;
 }
 
-void audit_close(int fd)
-{
-    int rc = close(fd);
-    if (rc < 0) {
-        SLOGE("Attempting to close invalid fd %d, error: %s", fd, strerror(errno));
-    }
-    return;
+void audit_close(int fd) {
+    close(fd);
 }
diff --git a/logd/libaudit.h b/logd/libaudit.h
index b9e330d..a2afe47 100644
--- a/logd/libaudit.h
+++ b/logd/libaudit.h
@@ -25,17 +25,14 @@
 #include <sys/socket.h>
 #include <sys/types.h>
 
-#include <linux/netlink.h>
 #include <linux/audit.h>
+#include <linux/netlink.h>
 
 __BEGIN_DECLS
 
-#define MAX_AUDIT_MESSAGE_LENGTH    8970
+#define MAX_AUDIT_MESSAGE_LENGTH 8970
 
-typedef enum {
-    GET_REPLY_BLOCKING=0,
-    GET_REPLY_NONBLOCKING
-} reply_t;
+typedef enum { GET_REPLY_BLOCKING = 0, GET_REPLY_NONBLOCKING } reply_t;
 
 /* type == AUDIT_SIGNAL_INFO */
 struct audit_sig_info {
@@ -46,7 +43,7 @@
 
 struct audit_message {
     struct nlmsghdr nlh;
-    char   data[MAX_AUDIT_MESSAGE_LENGTH];
+    char data[MAX_AUDIT_MESSAGE_LENGTH];
 };
 
 /**
@@ -55,7 +52,7 @@
  *  A valid fd on success or < 0 on error with errno set.
  *  Returns the same errors as man 2 socket.
  */
-extern int  audit_open(void);
+extern int audit_open(void);
 
 /**
  * Closes the fd returned from audit_open()
@@ -78,19 +75,36 @@
  * @return
  *  This function returns 0 on success, else -errno.
  */
-extern int  audit_get_reply(int fd, struct audit_message *rep, reply_t block,
-               int peek);
+extern int audit_get_reply(int fd, struct audit_message* rep, reply_t block,
+                           int peek);
 
 /**
- * Sets a pid to recieve audit netlink events from the kernel
+ * Sets a pid to receive audit netlink events from the kernel
  * @param fd
  *  The fd returned by a call to audit_open()
  * @param pid
- *  The pid whom to set as the reciever of audit messages
+ *  The pid whom to set as the receiver of audit messages
  * @return
  *  This function returns 0 on success, -errno on error.
  */
-extern int  audit_setup(int fd, uint32_t pid);
+extern int audit_setup(int fd, pid_t pid);
+
+/**
+ * Sets the rate limit to receive audit netlink events from the kernel
+ * @param fd
+ *  The fd returned by a call to audit_open()
+ * @param max_rate
+ *  The cap of the maximum number of audit messages a second
+ * @return
+ *  This function returns 0 on success, -errno on error.
+ */
+
+/* Guidelines to follow for dynamic rate_limit */
+#define AUDIT_RATE_LIMIT_DEFAULT 20        /* acceptable burst rate      */
+#define AUDIT_RATE_LIMIT_BURST_DURATION 10 /* number of seconds of burst */
+#define AUDIT_RATE_LIMIT_MAX 5             /* acceptable sustained rate  */
+
+extern int audit_rate_limit(int fd, unsigned rate_limit);
 
 __END_DECLS
 
diff --git a/logd/logd.rc b/logd/logd.rc
index 31ed4df..ee89b83 100644
--- a/logd/logd.rc
+++ b/logd/logd.rc
@@ -2,10 +2,22 @@
     socket logd stream 0666 logd logd
     socket logdr seqpacket 0666 logd logd
     socket logdw dgram 0222 logd logd
-    group root system readproc
+    file /proc/kmsg r
+    file /dev/kmsg w
+    user logd
+    group logd system readproc
     writepid /dev/cpuset/system-background/tasks
 
 service logd-reinit /system/bin/logd --reinit
     oneshot
     disabled
+    user logd
+    group logd
     writepid /dev/cpuset/system-background/tasks
+
+on fs
+    write /dev/event-log-tags "# content owned by logd
+"
+    chown logd logd /dev/event-log-tags
+    chmod 0644 /dev/event-log-tags
+    restorecon /dev/event-log-tags
diff --git a/logd/logtagd.rc b/logd/logtagd.rc
new file mode 100644
index 0000000..46aa8c1
--- /dev/null
+++ b/logd/logtagd.rc
@@ -0,0 +1,9 @@
+#
+# logtagd event log tag service (debug only)
+#
+on post-fs-data
+    mkdir /data/misc/logd 0700 logd log
+    write /data/misc/logd/event-log-tags ""
+    chown logd log /data/misc/logd/event-log-tags
+    chmod 0600 /data/misc/logd/event-log-tags
+    restorecon /data/misc/logd/event-log-tags
diff --git a/logd/main.cpp b/logd/main.cpp
index 8aa1abb..946485b 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -36,36 +36,37 @@
 #include <cstdbool>
 #include <memory>
 
+#include <android-base/macros.h>
+#include <cutils/android_get_control_file.h>
 #include <cutils/properties.h>
 #include <cutils/sched_policy.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
 #include <packagelistparser/packagelistparser.h>
 #include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
 #include <utils/threads.h>
 
 #include "CommandListener.h"
-#include "LogBuffer.h"
-#include "LogListener.h"
 #include "LogAudit.h"
+#include "LogBuffer.h"
 #include "LogKlog.h"
+#include "LogListener.h"
 #include "LogUtils.h"
 
-#define KMSG_PRIORITY(PRI)                            \
-    '<',                                              \
-    '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) / 10, \
-    '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) % 10, \
-    '>'
+#define KMSG_PRIORITY(PRI)                                 \
+    '<', '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) / 10, \
+        '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) % 10, '>'
 
 //
-//  The service is designed to be run by init, it does not respond well
+// The service is designed to be run by init, it does not respond well
 // to starting up manually. When starting up manually the sockets will
 // fail to open typically for one of the following reasons:
 //     EADDRINUSE if logger is running.
 //     EACCESS if started without precautions (below)
 //
 // Here is a cookbook procedure for starting up logd manually assuming
-// init is out of the way, pedantically all permissions and selinux
+// init is out of the way, pedantically all permissions and SELinux
 // security is put back in place:
 //
 //    setenforce 0
@@ -86,65 +87,95 @@
 //    logd
 //
 
-static int drop_privs() {
+static int drop_privs(bool klogd, bool auditd) {
+    // Tricky, if ro.build.type is "eng" then this is true because of the
+    // side effect that ro.debuggable == 1 as well, else it is false.
+    bool eng =
+        __android_logger_property_get_bool("ro.build.type", BOOL_DEFAULT_FALSE);
+
     struct sched_param param;
     memset(&param, 0, sizeof(param));
 
     if (set_sched_policy(0, SP_BACKGROUND) < 0) {
-        return -1;
+        android::prdebug("failed to set background scheduling policy");
+        if (!eng) return -1;
     }
 
-    if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
-        return -1;
+    if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
+        android::prdebug("failed to set batch scheduler");
+        if (!eng) return -1;
     }
 
     if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
+        android::prdebug("failed to set background cgroup");
+        if (!eng) return -1;
+    }
+
+    if (!eng && (prctl(PR_SET_DUMPABLE, 0) < 0)) {
+        android::prdebug("failed to clear PR_SET_DUMPABLE");
         return -1;
     }
 
     if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
+        android::prdebug("failed to set PR_SET_KEEPCAPS");
+        if (!eng) return -1;
+    }
+
+    std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(),
+                                                             cap_free);
+    if (cap_clear(caps.get()) < 0) return -1;
+    cap_value_t cap_value[] = { CAP_SETGID,  // must be first for below
+                                klogd ? CAP_SYSLOG : CAP_SETGID,
+                                auditd ? CAP_AUDIT_CONTROL : CAP_SETGID };
+    if (cap_set_flag(caps.get(), CAP_PERMITTED, arraysize(cap_value), cap_value,
+                     CAP_SET) < 0) {
         return -1;
     }
+    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, arraysize(cap_value), cap_value,
+                     CAP_SET) < 0) {
+        return -1;
+    }
+    if (cap_set_proc(caps.get()) < 0) {
+        android::prdebug(
+            "failed to set CAP_SETGID, CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)",
+            errno);
+        if (!eng) return -1;
+    }
 
     gid_t groups[] = { AID_READPROC };
 
-    if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) == -1) {
-        return -1;
+    if (setgroups(arraysize(groups), groups) == -1) {
+        android::prdebug("failed to set AID_READPROC groups");
+        if (!eng) return -1;
     }
 
     if (setgid(AID_LOGD) != 0) {
-        return -1;
+        android::prdebug("failed to set AID_LOGD gid");
+        if (!eng) return -1;
     }
 
     if (setuid(AID_LOGD) != 0) {
-        return -1;
+        android::prdebug("failed to set AID_LOGD uid");
+        if (!eng) return -1;
     }
 
-    struct __user_cap_header_struct capheader;
-    struct __user_cap_data_struct capdata[2];
-    memset(&capheader, 0, sizeof(capheader));
-    memset(&capdata, 0, sizeof(capdata));
-    capheader.version = _LINUX_CAPABILITY_VERSION_3;
-    capheader.pid = 0;
-
-    capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
-    capdata[CAP_TO_INDEX(CAP_AUDIT_CONTROL)].permitted |= CAP_TO_MASK(CAP_AUDIT_CONTROL);
-
-    capdata[0].effective = capdata[0].permitted;
-    capdata[1].effective = capdata[1].permitted;
-    capdata[0].inheritable = 0;
-    capdata[1].inheritable = 0;
-
-    if (capset(&capheader, &capdata[0]) < 0) {
+    if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, cap_value, CAP_CLEAR) < 0) {
         return -1;
     }
+    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, cap_value, CAP_CLEAR) < 0) {
+        return -1;
+    }
+    if (cap_set_proc(caps.get()) < 0) {
+        android::prdebug("failed to clear CAP_SETGID (%d)", errno);
+        if (!eng) return -1;
+    }
 
     return 0;
 }
 
 // Property helper
-static bool check_flag(const char *prop, const char *flag) {
-    const char *cp = strcasestr(prop, flag);
+static bool check_flag(const char* prop, const char* flag) {
+    const char* cp = strcasestr(prop, flag);
     if (!cp) {
         return false;
     }
@@ -157,75 +188,42 @@
     return !*cp || !!strchr(sep, *cp);
 }
 
-bool property_get_bool(const char *key, int flag) {
-    char def[PROPERTY_VALUE_MAX];
-    char property[PROPERTY_VALUE_MAX];
-    def[0] = '\0';
-    if (flag & BOOL_DEFAULT_FLAG_PERSIST) {
-        char newkey[PROPERTY_KEY_MAX];
-        snprintf(newkey, sizeof(newkey), "ro.%s", key);
-        property_get(newkey, property, "");
-        // persist properties set by /data require inoculation with
-        // logd-reinit. They may be set in init.rc early and function, but
-        // otherwise are defunct unless reset. Do not rely on persist
-        // properties for startup-only keys unless you are willing to restart
-        // logd daemon (not advised).
-        snprintf(newkey, sizeof(newkey), "persist.%s", key);
-        property_get(newkey, def, property);
-    }
-
-    property_get(key, property, def);
-
-    if (check_flag(property, "true")) {
-        return true;
-    }
-    if (check_flag(property, "false")) {
-        return false;
-    }
-    if (check_flag(property, "eng")) {
-       flag |= BOOL_DEFAULT_FLAG_ENG;
-    }
-    // this is really a "not" flag
-    if (check_flag(property, "svelte")) {
-       flag |= BOOL_DEFAULT_FLAG_SVELTE;
-    }
-
-    // Sanity Check
-    if (flag & (BOOL_DEFAULT_FLAG_SVELTE | BOOL_DEFAULT_FLAG_ENG)) {
-        flag &= ~BOOL_DEFAULT_FLAG_TRUE_FALSE;
-        flag |= BOOL_DEFAULT_TRUE;
-    }
-
-    if ((flag & BOOL_DEFAULT_FLAG_SVELTE)
-            && property_get_bool("ro.config.low_ram",
-                                 BOOL_DEFAULT_FALSE)) {
-        return false;
-    }
-    if (flag & BOOL_DEFAULT_FLAG_ENG) {
-        property_get("ro.build.type", property, "");
-        if (!strcmp(property, "user")) {
-            return false;
-        }
-    }
-
-    return (flag & BOOL_DEFAULT_FLAG_TRUE_FALSE) != BOOL_DEFAULT_FALSE;
-}
-
-// Remove the static, and use this variable
-// globally for debugging if necessary. eg:
-//   write(fdDmesg, "I am here\n", 10);
 static int fdDmesg = -1;
+void android::prdebug(const char* fmt, ...) {
+    if (fdDmesg < 0) {
+        return;
+    }
+
+    static const char message[] = {
+        KMSG_PRIORITY(LOG_DEBUG), 'l', 'o', 'g', 'd', ':', ' '
+    };
+    char buffer[256];
+    memcpy(buffer, message, sizeof(message));
+
+    va_list ap;
+    va_start(ap, fmt);
+    int n = vsnprintf(buffer + sizeof(message),
+                      sizeof(buffer) - sizeof(message), fmt, ap);
+    va_end(ap);
+    if (n > 0) {
+        buffer[sizeof(buffer) - 1] = '\0';
+        if (!strchr(buffer, '\n')) {
+            buffer[sizeof(buffer) - 2] = '\0';
+            strlcat(buffer, "\n", sizeof(buffer));
+        }
+        write(fdDmesg, buffer, strlen(buffer));
+    }
+}
 
 static sem_t uidName;
 static uid_t uid;
-static char *name;
+static char* name;
 
 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 */) {
-
+static bool package_list_parser_cb(pkg_info* info, void* /* userdata */) {
     bool rc = true;
     if (info->uid == uid) {
         name = strdup(info->name);
@@ -237,24 +235,28 @@
     return rc;
 }
 
-static void *reinit_thread_start(void * /*obj*/) {
+static void* reinit_thread_start(void* /*obj*/) {
     prctl(PR_SET_NAME, "logd.daemon");
     set_sched_policy(0, SP_BACKGROUND);
     setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND);
 
-    // If we are AID_ROOT, we should drop to AID_SYSTEM, if we are anything
-    // else, we have even lesser privileges and accept our fate. Not worth
-    // checking for error returns setting this thread's privileges.
-    (void)setgid(AID_SYSTEM);
-    (void)setuid(AID_SYSTEM);
+    cap_t caps = cap_init();
+    (void)cap_clear(caps);
+    (void)cap_set_proc(caps);
+    (void)cap_free(caps);
+
+    // If we are AID_ROOT, we should drop to AID_LOGD+AID_SYSTEM, if we are
+    // anything else, we have even lesser privileges and accept our fate. Not
+    // worth checking for error returns setting this thread's privileges.
+    (void)setgid(AID_SYSTEM);  // readonly access to /data/system/packages.list
+    (void)setuid(AID_LOGD);    // access to everything logd, eg /data/misc/logd
 
     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);
@@ -263,26 +265,45 @@
 
         if (fdDmesg >= 0) {
             static const char reinit_message[] = { KMSG_PRIORITY(LOG_INFO),
-                'l', 'o', 'g', 'd', '.', 'd', 'a', 'e', 'm', 'o', 'n', ':',
-                ' ', 'r', 'e', 'i', 'n', 'i', 't', '\n' };
+                                                   'l',
+                                                   'o',
+                                                   'g',
+                                                   'd',
+                                                   '.',
+                                                   'd',
+                                                   'a',
+                                                   'e',
+                                                   'm',
+                                                   'o',
+                                                   'n',
+                                                   ':',
+                                                   ' ',
+                                                   'r',
+                                                   'e',
+                                                   'i',
+                                                   'n',
+                                                   'i',
+                                                   't',
+                                                   '\n' };
             write(fdDmesg, reinit_message, sizeof(reinit_message));
         }
 
         // 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) {
+char* android::uidToName(uid_t u) {
     if (!u || !reinit_running) {
-        return NULL;
+        return nullptr;
     }
 
     sem_wait(&sem_name);
@@ -290,10 +311,10 @@
     // 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;
+    char* ret = name;
 
     sem_post(&sem_name);
 
@@ -306,42 +327,26 @@
     sem_post(&reinit);
 }
 
-// tagToName converts an events tag into a name
-const char *android::tagToName(uint32_t tag) {
-    static const EventTagMap *map;
-
-    if (!map) {
-        sem_wait(&sem_name);
-        if (!map) {
-            map = android_openEventTagMap(EVENT_TAG_MAP_FILE);
-        }
-        sem_post(&sem_name);
-        if (!map) {
-            return NULL;
-        }
-    }
-    return android_lookupEventTag(map, tag);
-}
-
-static void readDmesg(LogAudit *al, LogKlog *kl) {
+static void readDmesg(LogAudit* al, LogKlog* kl) {
     if (!al && !kl) {
         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
-    std::unique_ptr<char []> buf(new char[len]);
+    // 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);
     if (rc <= 0) {
         return;
     }
 
-    if ((size_t)rc < len) {
+    if (rc < len) {
         len = rc + 1;
     }
     buf[--len] = '\0';
@@ -350,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);
         }
@@ -363,57 +369,67 @@
     }
 }
 
+static int issueReinit() {
+    cap_t caps = cap_init();
+    (void)cap_clear(caps);
+    (void)cap_set_proc(caps);
+    (void)cap_free(caps);
+
+    int sock = TEMP_FAILURE_RETRY(socket_local_client(
+        "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
+    if (sock < 0) return -errno;
+
+    static const char reinitStr[] = "reinit";
+    ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinitStr, sizeof(reinitStr)));
+    if (ret < 0) return -errno;
+
+    struct pollfd p;
+    memset(&p, 0, sizeof(p));
+    p.fd = sock;
+    p.events = POLLIN;
+    ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
+    if (ret < 0) return -errno;
+    if ((ret == 0) || !(p.revents & POLLIN)) return -ETIME;
+
+    static const char success[] = "success";
+    char buffer[sizeof(success) - 1];
+    memset(buffer, 0, sizeof(buffer));
+    ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
+    if (ret < 0) return -errno;
+
+    return strncmp(buffer, success, sizeof(success) - 1) != 0;
+}
+
 // Foreground waits for exit of the main persistent threads
 // that are started here. The threads are created to manage
 // UNIX domain client sockets for writing, reading and
 // controlling the user space logger, and for any additional
 // logging plugins like auditd and restart control. Additional
 // transitory per-client threads are created for each reader.
-int main(int argc, char *argv[]) {
-    int fdPmesg = -1;
-    bool klogd = property_get_bool("logd.kernel",
-                                   BOOL_DEFAULT_TRUE |
-                                   BOOL_DEFAULT_FLAG_PERSIST |
-                                   BOOL_DEFAULT_FLAG_ENG |
-                                   BOOL_DEFAULT_FLAG_SVELTE);
-    if (klogd) {
-        fdPmesg = open("/proc/kmsg", O_RDONLY | O_NDELAY);
-    }
-    fdDmesg = open("/dev/kmsg", O_WRONLY);
-
+int main(int argc, char* argv[]) {
     // issue reinit command. KISS argument parsing.
     if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
-        int sock = TEMP_FAILURE_RETRY(
-            socket_local_client("logd",
-                                ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                SOCK_STREAM));
-        if (sock < 0) {
-            return -errno;
+        return issueReinit();
+    }
+
+    static const char dev_kmsg[] = "/dev/kmsg";
+    fdDmesg = android_get_control_file(dev_kmsg);
+    if (fdDmesg < 0) {
+        fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
+    }
+
+    int fdPmesg = -1;
+    bool klogd = __android_logger_property_get_bool(
+        "logd.kernel", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_PERSIST |
+                           BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
+    if (klogd) {
+        static const char proc_kmsg[] = "/proc/kmsg";
+        fdPmesg = android_get_control_file(proc_kmsg);
+        if (fdPmesg < 0) {
+            fdPmesg = TEMP_FAILURE_RETRY(
+                open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
         }
-        static const char reinit[] = "reinit";
-        ssize_t ret = TEMP_FAILURE_RETRY(write(sock, reinit, sizeof(reinit)));
-        if (ret < 0) {
-            return -errno;
-        }
-        struct pollfd p;
-        memset(&p, 0, sizeof(p));
-        p.fd = sock;
-        p.events = POLLIN;
-        ret = TEMP_FAILURE_RETRY(poll(&p, 1, 1000));
-        if (ret < 0) {
-            return -errno;
-        }
-        if ((ret == 0) || !(p.revents & POLLIN)) {
-            return -ETIME;
-        }
-        static const char success[] = "success";
-        char buffer[sizeof(success) - 1];
-        memset(buffer, 0, sizeof(buffer));
-        ret = TEMP_FAILURE_RETRY(read(sock, buffer, sizeof(buffer)));
-        if (ret < 0) {
-            return -errno;
-        }
-        return strncmp(buffer, success, sizeof(success) - 1) != 0;
+        if (fdPmesg < 0) android::prdebug("Failed to open %s\n", proc_kmsg);
     }
 
     // Reinit Thread
@@ -427,18 +443,19 @@
         memset(&param, 0, sizeof(param));
         pthread_attr_setschedparam(&attr, &param);
         pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
-        if (!pthread_attr_setdetachstate(&attr,
-                                         PTHREAD_CREATE_DETACHED)) {
+        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;
             }
         }
         pthread_attr_destroy(&attr);
     }
 
-    if (drop_privs() != 0) {
+    bool auditd =
+        __android_logger_property_get_bool("ro.logd.auditd", BOOL_DEFAULT_TRUE);
+    if (drop_privs(klogd, auditd) != 0) {
         return -1;
     }
 
@@ -446,7 +463,7 @@
     // socket connection, and as a reader lock on a range of log
     // entries.
 
-    LastLogTimes *times = new LastLogTimes();
+    LastLogTimes* times = new LastLogTimes();
 
     // LogBuffer is the object which is responsible for holding all
     // log entries.
@@ -455,18 +472,17 @@
 
     signal(SIGHUP, reinit_signal_handler);
 
-    if (property_get_bool("logd.statistics",
-                          BOOL_DEFAULT_TRUE |
-                          BOOL_DEFAULT_FLAG_PERSIST |
-                          BOOL_DEFAULT_FLAG_ENG |
-                          BOOL_DEFAULT_FLAG_SVELTE)) {
+    if (__android_logger_property_get_bool(
+            "logd.statistics", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_PERSIST |
+                                   BOOL_DEFAULT_FLAG_ENG |
+                                   BOOL_DEFAULT_FLAG_SVELTE)) {
         logBuf->enableStatistics();
     }
 
     // LogReader listens on /dev/socket/logdr. When a client
     // connects, log entries in the LogBuffer are written to the client.
 
-    LogReader *reader = new LogReader(logBuf);
+    LogReader* reader = new LogReader(logBuf);
     if (reader->startListener()) {
         exit(1);
     }
@@ -475,7 +491,7 @@
     // initiated log messages. New log entries are added to LogBuffer
     // and LogReader is notified to send updates to connected clients.
 
-    LogListener *swl = new LogListener(logBuf, reader);
+    LogListener* swl = new LogListener(logBuf, reader);
     // Backlog and /proc/sys/net/unix/max_dgram_qlen set to large value
     if (swl->startListener(600)) {
         exit(1);
@@ -484,7 +500,7 @@
     // Command listener listens on /dev/socket/logd for incoming logd
     // administrative commands.
 
-    CommandListener *cl = new CommandListener(logBuf, reader, swl);
+    CommandListener* cl = new CommandListener(logBuf, reader, swl);
     if (cl->startListener()) {
         exit(1);
     }
@@ -493,22 +509,18 @@
     // initiated log messages. New log entries are added to LogBuffer
     // and LogReader is notified to send updates to connected clients.
 
-    bool auditd = property_get_bool("logd.auditd",
-                                    BOOL_DEFAULT_TRUE |
-                                    BOOL_DEFAULT_FLAG_PERSIST);
-    LogAudit *al = NULL;
+    LogAudit* al = nullptr;
     if (auditd) {
         al = new LogAudit(logBuf, reader,
-                          property_get_bool("logd.auditd.dmesg",
-                                            BOOL_DEFAULT_TRUE |
-                                            BOOL_DEFAULT_FLAG_PERSIST)
+                          __android_logger_property_get_bool(
+                              "ro.logd.auditd.dmesg", BOOL_DEFAULT_TRUE)
                               ? fdDmesg
                               : -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 808087a..c053993 100644
--- a/logd/tests/Android.mk
+++ b/logd/tests/Android.mk
@@ -27,12 +27,15 @@
 # Unit tests.
 # -----------------------------------------------------------------------------
 
+event_flag := -DAUDITD_LOG_TAG=1003 -DCHATTY_LOG_TAG=1004
+
 test_c_flags := \
     -fstack-protector-all \
     -g \
     -Wall -Wextra \
     -Werror \
     -fno-builtin \
+    $(event_flag)
 
 test_src_files := \
     logd_test.cpp
@@ -43,6 +46,6 @@
 LOCAL_MODULE := $(test_module_prefix)unit-tests
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
+LOCAL_SHARED_LIBRARIES := libbase libcutils liblog libselinux
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 2014374..c81aa32 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -20,42 +20,39 @@
 #include <signal.h>
 #include <stdio.h>
 #include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #include <string>
 
-#include <gtest/gtest.h>
-
+#include <android-base/macros.h>
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
+#include <gtest/gtest.h>
 #include <log/log.h>
-#include <log/logger.h>
+#include <private/android_filesystem_config.h>
+#ifdef __ANDROID__
+#include <selinux/selinux.h>
+#endif
 
-#include "../LogReader.h" // pickup LOGD_SNDTIMEO
+#include "../LogReader.h"  // pickup LOGD_SNDTIMEO
+#include "../libaudit.h"   // pickup AUDIT_RATE_LIMIT_*
 
-/*
- * returns statistics
- */
-static void my_android_logger_get_statistics(char *buf, size_t len)
-{
-    snprintf(buf, len, "getStatistics 0 1 2 3 4");
-    int sock = socket_local_client("logd",
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
+static void send_to_control(char* buf, size_t len) {
+    int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                    SOCK_STREAM);
     if (sock >= 0) {
         if (write(sock, buf, strlen(buf) + 1) > 0) {
             ssize_t ret;
             while ((ret = read(sock, buf, len)) > 0) {
-                if ((size_t)ret == len) {
+                if (((size_t)ret == len) || (len < PAGE_SIZE)) {
                     break;
                 }
                 len -= ret;
                 buf += ret;
 
-                struct pollfd p = {
-                    .fd = sock,
-                    .events = POLLIN,
-                    .revents = 0
-                };
+                struct pollfd p = {.fd = sock, .events = POLLIN, .revents = 0 };
 
                 ret = poll(&p, 1, 20);
                 if ((ret <= 0) || !(p.revents & POLLIN)) {
@@ -67,19 +64,26 @@
     }
 }
 
-static void alloc_statistics(char **buffer, size_t *length)
-{
-    size_t len = 8192;
-    char *buf;
+/*
+ * returns statistics
+ */
+static void my_android_logger_get_statistics(char* buf, size_t len) {
+    snprintf(buf, len, "getStatistics 0 1 2 3 4");
+    send_to_control(buf, len);
+}
 
-    for(int retry = 32; (retry >= 0); delete [] buf, --retry) {
-        buf = new char [len];
+static void alloc_statistics(char** buffer, size_t* length) {
+    size_t len = 8192;
+    char* buf;
+
+    for (int retry = 32; (retry >= 0); delete[] buf, --retry) {
+        buf = new char[len];
         my_android_logger_get_statistics(buf, len);
 
-        buf[len-1] = '\0';
+        buf[len - 1] = '\0';
         size_t ret = atol(buf) + 1;
         if (ret < 4) {
-            delete [] buf;
+            delete[] buf;
             buf = NULL;
             break;
         }
@@ -88,14 +92,13 @@
         if (check) {
             break;
         }
-        len += len / 8; // allow for some slop
+        len += len / 8;  // allow for some slop
     }
     *buffer = buf;
     *length = len;
 }
 
-static char *find_benchmark_spam(char *cp)
-{
+static char* find_benchmark_spam(char* cp) {
     // liblog_benchmarks has been run designed to SPAM.  The signature of
     // a noisiest UID statistics is:
     //
@@ -103,7 +106,7 @@
     // UID   PACKAGE                                                BYTES LINES
     // 0     root                                                  54164 147569
     //
-    char *benchmark = NULL;
+    char* benchmark = NULL;
     do {
         static const char signature[] = "\n0     root ";
 
@@ -117,7 +120,7 @@
         }
         benchmark = cp;
 #ifdef DEBUG
-        char *end = strstr(benchmark, "\n");
+        char* end = strstr(benchmark, "\n");
         if (end == NULL) {
             end = benchmark + strlen(benchmark);
         }
@@ -133,8 +136,8 @@
         }
         // optional +/- field?
         if ((*cp == '-') || (*cp == '+')) {
-            while (isdigit(*++cp) ||
-                   (*cp == '.') || (*cp == '%') || (*cp == 'X')) {
+            while (isdigit(*++cp) || (*cp == '.') || (*cp == '%') ||
+                   (*cp == 'X')) {
                 ;
             }
             while (isspace(*cp)) {
@@ -157,14 +160,14 @@
 
 TEST(logd, statistics) {
     size_t len;
-    char *buf;
+    char* buf;
 
     alloc_statistics(&buf, &len);
 
     ASSERT_TRUE(NULL != buf);
 
     // remove trailing FF
-    char *cp = buf + len - 1;
+    char* cp = buf + len - 1;
     *cp = '\0';
     bool truncated = *--cp != '\f';
     if (!truncated) {
@@ -185,92 +188,107 @@
 
     EXPECT_EQ(0, truncated);
 
-    char *main_logs = strstr(cp, "\nChattiest UIDs in main ");
+    char* main_logs = strstr(cp, "\nChattiest UIDs in main ");
     EXPECT_TRUE(NULL != main_logs);
 
-    char *radio_logs = strstr(cp, "\nChattiest UIDs in radio ");
-    EXPECT_TRUE(NULL != radio_logs);
+    char* radio_logs = strstr(cp, "\nChattiest UIDs in radio ");
+    if (!radio_logs)
+        GTEST_LOG_(INFO) << "Value of: NULL != radio_logs\n"
+                            "Actual: false\n"
+                            "Expected: false\n";
 
-    char *system_logs = strstr(cp, "\nChattiest UIDs in system ");
+    char* system_logs = strstr(cp, "\nChattiest UIDs in system ");
     EXPECT_TRUE(NULL != system_logs);
 
-    char *events_logs = strstr(cp, "\nChattiest UIDs in events ");
+    char* events_logs = strstr(cp, "\nChattiest UIDs in events ");
     EXPECT_TRUE(NULL != events_logs);
 
-    delete [] buf;
+    delete[] buf;
 }
 
-static void caught_signal(int /* signum */) { }
+static void caught_signal(int /* signum */) {
+}
 
-static void dump_log_msg(const char *prefix,
-                         log_msg *msg, unsigned int version, int lid) {
+static void dump_log_msg(const char* prefix, log_msg* msg, unsigned int version,
+                         int lid) {
     std::cout << std::flush;
     std::cerr << std::flush;
     fflush(stdout);
     fflush(stderr);
-    switch(msg->entry.hdr_size) {
-    case 0:
-        version = 1;
-        break;
+    switch (msg->entry.hdr_size) {
+        case 0:
+            version = 1;
+            break;
 
-    case sizeof(msg->entry_v2):
-        if (version == 0) {
-            version = 2;
-        }
-        break;
+        case sizeof(msg->entry_v2): /* PLUS case sizeof(msg->entry_v3): */
+            if (version == 0) {
+                version = (msg->entry_v3.lid < LOG_ID_MAX) ? 3 : 2;
+            }
+            break;
+
+        case sizeof(msg->entry_v4):
+            if (version == 0) {
+                version = 4;
+            }
+            break;
     }
 
     fprintf(stderr, "%s: v%u[%u] ", prefix, version, msg->len());
     if (version != 1) {
         fprintf(stderr, "hdr_size=%u ", msg->entry.hdr_size);
     }
-    fprintf(stderr, "pid=%u tid=%u %u.%09u ",
-            msg->entry.pid, msg->entry.tid, msg->entry.sec, msg->entry.nsec);
-    switch(version) {
-    case 1:
-         break;
-    case 2:
-        fprintf(stderr, "euid=%u ", msg->entry_v2.euid);
-        break;
-    case 3:
-    default:
-        lid = msg->entry.lid;
-        break;
+    fprintf(stderr, "pid=%u tid=%u %u.%09u ", msg->entry.pid, msg->entry.tid,
+            msg->entry.sec, msg->entry.nsec);
+    switch (version) {
+        case 1:
+            break;
+        case 2:
+            fprintf(stderr, "euid=%u ", msg->entry_v2.euid);
+            break;
+        case 3:
+        default:
+            lid = msg->entry.lid;
+            break;
     }
 
-    switch(lid) {
-    case 0:
-        fprintf(stderr, "lid=main ");
-        break;
-    case 1:
-        fprintf(stderr, "lid=radio ");
-        break;
-    case 2:
-        fprintf(stderr, "lid=events ");
-        break;
-    case 3:
-        fprintf(stderr, "lid=system ");
-        break;
-    case 4:
-        fprintf(stderr, "lid=crash ");
-        break;
-    case 5:
-        fprintf(stderr, "lid=security ");
-        break;
-    case 6:
-        fprintf(stderr, "lid=kernel ");
-        break;
-    default:
-        if (lid >= 0) {
-            fprintf(stderr, "lid=%d ", lid);
-        }
+    switch (lid) {
+        case 0:
+            fprintf(stderr, "lid=main ");
+            break;
+        case 1:
+            fprintf(stderr, "lid=radio ");
+            break;
+        case 2:
+            fprintf(stderr, "lid=events ");
+            break;
+        case 3:
+            fprintf(stderr, "lid=system ");
+            break;
+        case 4:
+            fprintf(stderr, "lid=crash ");
+            break;
+        case 5:
+            fprintf(stderr, "lid=security ");
+            break;
+        case 6:
+            fprintf(stderr, "lid=kernel ");
+            break;
+        default:
+            if (lid >= 0) {
+                fprintf(stderr, "lid=%d ", lid);
+            }
     }
 
     unsigned int len = msg->entry.len;
     fprintf(stderr, "msg[%u]={", len);
-    unsigned char *cp = reinterpret_cast<unsigned char *>(msg->msg());
-    while(len) {
-        unsigned char *p = cp;
+    unsigned char* cp = reinterpret_cast<unsigned char*>(msg->msg());
+    if (!cp) {
+        static const unsigned char garbage[] = "<INVALID>";
+        cp = const_cast<unsigned char*>(garbage);
+        len = strlen(reinterpret_cast<const char*>(garbage));
+    }
+    while (len) {
+        unsigned char* p = cp;
         while (*p && (((' ' <= *p) && (*p < 0x7F)) || (*p == '\n'))) {
             ++p;
         }
@@ -305,8 +323,7 @@
     bool user_logger_available = false;
     bool user_logger_content = false;
 
-    int fd = socket_local_client("logdr",
-                                 ANDROID_SOCKET_NAMESPACE_RESERVED,
+    int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                  SOCK_SEQPACKET);
     if (fd >= 0) {
         struct sigaction ignore, old_sigaction;
@@ -335,14 +352,13 @@
     bool kernel_logger_available = false;
     bool kernel_logger_content = false;
 
-    static const char *loggers[] = {
-        "/dev/log/main",   "/dev/log_main",
-        "/dev/log/radio",  "/dev/log_radio",
-        "/dev/log/events", "/dev/log_events",
+    static const char* loggers[] = {
+        "/dev/log/main",   "/dev/log_main",   "/dev/log/radio",
+        "/dev/log_radio",  "/dev/log/events", "/dev/log_events",
         "/dev/log/system", "/dev/log_system",
     };
 
-    for (unsigned int i = 0; i < (sizeof(loggers) / sizeof(loggers[0])); ++i) {
+    for (unsigned int i = 0; i < arraysize(loggers); ++i) {
         fd = open(loggers[i], O_RDONLY);
         if (fd < 0) {
             continue;
@@ -364,10 +380,9 @@
             "user    %-13s%s\n"
             "kernel  %-13s%s\n"
             " status %-11s%s\n",
-            (user_logger_available)   ? yes : no,
-            (user_logger_content)     ? yes : no,
+            (user_logger_available) ? yes : no, (user_logger_content) ? yes : no,
             (kernel_logger_available) ? yes : no,
-            (kernel_logger_content)   ? yes : no,
+            (kernel_logger_content) ? yes : no,
             (user_logger_available && kernel_logger_available) ? "ERROR" : "ok",
             (user_logger_content && kernel_logger_content) ? "ERROR" : "ok");
 
@@ -390,33 +405,37 @@
 //
 TEST(logd, benchmark) {
     size_t len;
-    char *buf;
+    char* buf;
 
     alloc_statistics(&buf, &len);
     bool benchmark_already_run = buf && find_benchmark_spam(buf);
-    delete [] buf;
+    delete[] buf;
 
     if (benchmark_already_run) {
-        fprintf(stderr, "WARNING: spam already present and too much history\n"
-                        "         false OK for prune by worst UID check\n");
+        fprintf(stderr,
+                "WARNING: spam already present and too much history\n"
+                "         false OK for prune by worst UID check\n");
     }
 
-    FILE *fp;
+    FILE* fp;
 
     // Introduce some extreme spam for the worst UID filter
-    ASSERT_TRUE(NULL != (fp = popen(
-        "/data/nativetest/liblog-benchmarks/liblog-benchmarks",
-        "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("/data/nativetest/liblog-benchmarks/liblog-benchmarks"
+                    " BM_log_maximum_retry"
+                    " BM_log_maximum"
+                    " BM_clock_overhead"
+                    " BM_log_overhead"
+                    " BM_log_latency"
+                    " BM_log_delay",
+                    "r")));
 
     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 "
+    static const char* benchmarks[] = {
+        "BM_log_maximum_retry ", "BM_log_maximum ", "BM_clock_overhead ",
+        "BM_log_overhead ",      "BM_log_latency ", "BM_log_delay "
     };
     static const unsigned int log_maximum_retry = 0;
     static const unsigned int log_maximum = 1;
@@ -425,13 +444,13 @@
     static const unsigned int log_latency = 4;
     static const unsigned int log_delay = 5;
 
-    unsigned long ns[sizeof(benchmarks) / sizeof(benchmarks[0])];
+    unsigned long ns[arraysize(benchmarks)];
 
     memset(ns, 0, sizeof(ns));
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        for (unsigned i = 0; i < sizeof(ns) / sizeof(ns[0]); ++i) {
-            char *cp = strstr(buffer, benchmarks[i]);
+        for (unsigned i = 0; i < arraysize(ns); ++i) {
+            char* cp = strstr(buffer, benchmarks[i]);
             if (!cp) {
                 continue;
             }
@@ -449,19 +468,20 @@
         return;
     }
 
-    EXPECT_GE(200000UL, ns[log_maximum_retry]); // 104734 user
+    EXPECT_GE(200000UL, ns[log_maximum_retry]);  // 104734 user
 
-    EXPECT_GE(90000UL, ns[log_maximum]); // 46913 user
+    EXPECT_GE(90000UL, ns[log_maximum]);  // 46913 user
 
-    EXPECT_GE(4096UL, ns[clock_overhead]); // 4095
+    EXPECT_GE(4096UL, ns[clock_overhead]);  // 4095
 
-    EXPECT_GE(250000UL, ns[log_overhead]); // 126886 user
+    EXPECT_GE(250000UL, ns[log_overhead]);  // 126886 user
 
-    EXPECT_GE(10000000UL, ns[log_latency]); // 1453559 user space (background cgroup)
+    EXPECT_GE(10000000UL,
+              ns[log_latency]);  // 1453559 user space (background cgroup)
 
-    EXPECT_GE(20000000UL, ns[log_delay]); // 10500289 user
+    EXPECT_GE(20000000UL, ns[log_delay]);  // 10500289 user
 
-    for (unsigned i = 0; i < sizeof(ns) / sizeof(ns[0]); ++i) {
+    for (unsigned i = 0; i < arraysize(ns); ++i) {
         EXPECT_NE(0UL, ns[i]);
     }
 
@@ -472,7 +492,7 @@
 
     ASSERT_TRUE(NULL != buf);
 
-    char *benchmark_statistics_found = find_benchmark_spam(buf);
+    char* benchmark_statistics_found = find_benchmark_spam(buf);
     ASSERT_TRUE(benchmark_statistics_found != NULL);
 
     // Check how effective the SPAM filter is, parse out Now size.
@@ -481,13 +501,12 @@
 
     unsigned long nowSpamSize = atol(benchmark_statistics_found);
 
-    delete [] buf;
+    delete[] buf;
 
     ASSERT_NE(0UL, nowSpamSize);
 
     // Determine if we have the spam filter enabled
-    int sock = socket_local_client("logd",
-                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
+    int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                    SOCK_STREAM);
 
     ASSERT_TRUE(sock >= 0);
@@ -497,26 +516,27 @@
         char buffer[80];
         memset(buffer, 0, sizeof(buffer));
         read(sock, buffer, sizeof(buffer));
-        char *cp = strchr(buffer, '\n');
+        char* cp = strchr(buffer, '\n');
         if (!cp || (cp[1] != '~') || (cp[2] != '!')) {
             close(sock);
             fprintf(stderr,
                     "WARNING: "
-                    "Logger has SPAM filtration turned off \"%s\"\n", buffer);
+                    "Logger has SPAM filtration turned off \"%s\"\n",
+                    buffer);
             return;
         }
     } else {
         int save_errno = errno;
         close(sock);
-        FAIL() << "Can not send " << getPruneList << " to logger -- " << strerror(save_errno);
+        FAIL() << "Can not send " << getPruneList << " to logger -- "
+               << strerror(save_errno);
     }
 
     static const unsigned long expected_absolute_minimum_log_size = 65536UL;
     unsigned long totalSize = expected_absolute_minimum_log_size;
-    static const char getSize[] = {
-        'g', 'e', 't', 'L', 'o', 'g', 'S', 'i', 'z', 'e', ' ',
-        LOG_ID_MAIN + '0', '\0'
-    };
+    static const char getSize[] = { 'g', 'e', 't', 'L', 'o', 'g',
+                                    'S', 'i', 'z', 'e', ' ', LOG_ID_MAIN + '0',
+                                    '\0' };
     if (write(sock, getSize, sizeof(getSize)) > 0) {
         char buffer[80];
         memset(buffer, 0, sizeof(buffer));
@@ -525,21 +545,22 @@
         if (totalSize < expected_absolute_minimum_log_size) {
             fprintf(stderr,
                     "WARNING: "
-                    "Logger had unexpected referenced size \"%s\"\n", buffer);
+                    "Logger had unexpected referenced size \"%s\"\n",
+                    buffer);
             totalSize = expected_absolute_minimum_log_size;
         }
     }
     close(sock);
 
     // logd allows excursions to 110% of total size
-    totalSize = (totalSize * 11 ) / 10;
+    totalSize = (totalSize * 11) / 10;
 
     // 50% threshold for SPAM filter (<20% typical, lots of engineering margin)
     ASSERT_GT(totalSize, nowSpamSize * 2);
 }
 
 // b/26447386 confirm fixed
-void timeout_negative(const char *command) {
+void timeout_negative(const char* command) {
     log_msg msg_wrap, msg_timeout;
     bool content_wrap = false, content_timeout = false, written = false;
     unsigned int alarm_wrap = 0, alarm_timeout = 0;
@@ -548,8 +569,7 @@
     int i = 3;
 
     while (--i) {
-        int fd = socket_local_client("logdr",
-                                     ANDROID_SOCKET_NAMESPACE_RESERVED,
+        int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                      SOCK_SEQPACKET);
         ASSERT_LT(0, fd);
 
@@ -571,20 +591,23 @@
             continue;
         }
 
+        // alarm triggers at 50% of the --wrap time out
         content_wrap = recv(fd, msg_wrap.buf, sizeof(msg_wrap), 0) > 0;
 
         alarm_wrap = alarm(5);
 
+        // alarm triggers at 133% of the --wrap time out
         content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
-        if (!content_timeout) { // make sure we hit dumpAndClose
-            content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+        if (!content_timeout) {  // make sure we hit dumpAndClose
+            content_timeout =
+                recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
         }
 
-        alarm_timeout = alarm((old_alarm <= 0)
-            ? old_alarm
-            : (old_alarm > (1 + 3 - alarm_wrap))
-                ? old_alarm - 3 + alarm_wrap
-                : 2);
+        alarm_timeout =
+            alarm((old_alarm <= 0) ? old_alarm
+                                   : (old_alarm > (1 + 3 - alarm_wrap))
+                                         ? old_alarm - 3 + alarm_wrap
+                                         : 2);
         sigaction(SIGALRM, &old_sigaction, NULL);
 
         close(fd);
@@ -614,29 +637,47 @@
 }
 
 TEST(logd, timeout_start_epoch) {
-    timeout_negative("dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=0.000000000");
+    timeout_negative(
+        "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=0.000000000");
 }
 
 // b/26447386 refined behavior
 TEST(logd, timeout) {
+    // 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.
+
+    pid_t pid = fork();
+
+    if (pid) {
+        siginfo_t info = {};
+        ASSERT_EQ(0, TEMP_FAILURE_RETRY(waitid(P_PID, pid, &info, WEXITED)));
+        ASSERT_EQ(0, info.si_status);
+        return;
+    }
+
     log_msg msg_wrap, msg_timeout;
     bool content_wrap = false, content_timeout = false, written = false;
     unsigned int alarm_wrap = 0, alarm_timeout = 0;
     // A few tries to get it right just in case wrap kicks in due to
-    // content providers being active during the test
+    // content providers being active during the test.
     int i = 5;
     log_time now(android_log_clockid());
-    now.tv_sec -= 30; // reach back a moderate period of time
+    now.tv_sec -= 30;  // reach back a moderate period of time
 
     while (--i) {
-        int fd = socket_local_client("logdr",
-                                     ANDROID_SOCKET_NAMESPACE_RESERVED,
+        int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                      SOCK_SEQPACKET);
-        ASSERT_LT(0, 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 ".%09" PRIu32,
+            "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=%" PRIu32
+            ".%09" PRIu32,
             now.tv_sec, now.tv_nsec);
 
         struct sigaction ignore, old_sigaction;
@@ -655,20 +696,23 @@
             continue;
         }
 
+        // alarm triggers at 50% of the --wrap time out
         content_wrap = recv(fd, msg_wrap.buf, sizeof(msg_wrap), 0) > 0;
 
         alarm_wrap = alarm(5);
 
+        // alarm triggers at 133% of the --wrap time out
         content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
-        if (!content_timeout) { // make sure we hit dumpAndClose
-            content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+        if (!content_timeout) {  // make sure we hit dumpAndClose
+            content_timeout =
+                recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
         }
 
-        alarm_timeout = alarm((old_alarm <= 0)
-            ? old_alarm
-            : (old_alarm > (1 + 3 - alarm_wrap))
-                ? old_alarm - 3 + alarm_wrap
-                : 2);
+        alarm_timeout =
+            alarm((old_alarm <= 0) ? old_alarm
+                                   : (old_alarm > (1 + 3 - alarm_wrap))
+                                         ? old_alarm - 3 + alarm_wrap
+                                         : 2);
         sigaction(SIGALRM, &old_sigaction, NULL);
 
         close(fd);
@@ -681,7 +725,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) {
+                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;
@@ -692,7 +741,7 @@
                 }
             }
         } else {
-            now.tv_sec -= 120; // inactive, reach further back!
+            now.tv_sec -= 120;  // inactive, reach further back!
         }
     }
 
@@ -705,8 +754,8 @@
     }
 
     if (content_wrap || !content_timeout) {
-        fprintf(stderr, "now=%" PRIu32 ".%09" PRIu32 "\n",
-                now.tv_sec, now.tv_nsec);
+        fprintf(stderr, "now=%" PRIu32 ".%09" PRIu32 "\n", now.tv_sec,
+                now.tv_nsec);
     }
 
     EXPECT_TRUE(written);
@@ -714,19 +763,23 @@
     EXPECT_EQ(0U, alarm_wrap);
     EXPECT_TRUE(content_timeout);
     EXPECT_NE(0U, alarm_timeout);
+
+    _exit(!written + content_wrap + alarm_wrap + !content_timeout +
+          !alarm_timeout);
 }
 
 // b/27242723 confirmed fixed
 TEST(logd, SNDTIMEO) {
-    static const unsigned sndtimeo = LOGD_SNDTIMEO; // <sigh> it has to be done!
+    static const unsigned sndtimeo =
+        LOGD_SNDTIMEO;  // <sigh> it has to be done!
     static const unsigned sleep_time = sndtimeo + 3;
     static const unsigned alarm_time = sleep_time + 5;
 
     int fd;
 
-    ASSERT_TRUE((fd = socket_local_client("logdr",
-                                 ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                 SOCK_SEQPACKET)) > 0);
+    ASSERT_TRUE(
+        (fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
+                                  SOCK_SEQPACKET)) > 0);
 
     struct sigaction ignore, old_sigaction;
     memset(&ignore, 0, sizeof(ignore));
@@ -735,7 +788,7 @@
     sigaction(SIGALRM, &ignore, &old_sigaction);
     unsigned int old_alarm = alarm(alarm_time);
 
-    static const char ask[] = "stream lids=0,1,2,3,4,5,6"; // all sources
+    static const char ask[] = "stream lids=0,1,2,3,4,5,6";  // all sources
     bool reader_requested = write(fd, ask, sizeof(ask)) == sizeof(ask);
     EXPECT_TRUE(reader_requested);
 
@@ -747,7 +800,7 @@
         dump_log_msg("user", &msg, 3, -1);
     }
 
-    fprintf (stderr, "Sleep for >%d seconds logd SO_SNDTIMEO ...\n", sndtimeo);
+    fprintf(stderr, "Sleep for >%d seconds logd SO_SNDTIMEO ...\n", sndtimeo);
     sleep(sleep_time);
 
     // flush will block if we did not trigger. if it did, last entry returns 0
@@ -768,3 +821,328 @@
 
     close(fd);
 }
+
+TEST(logd, getEventTag_list) {
+#ifdef __ANDROID__
+    char buffer[256];
+    memset(buffer, 0, sizeof(buffer));
+    snprintf(buffer, sizeof(buffer), "getEventTag name=*");
+    send_to_control(buffer, sizeof(buffer));
+    buffer[sizeof(buffer) - 1] = '\0';
+    char* cp;
+    long ret = strtol(buffer, &cp, 10);
+    EXPECT_GT(ret, 4096);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(logd, getEventTag_42) {
+#ifdef __ANDROID__
+    char buffer[256];
+    memset(buffer, 0, sizeof(buffer));
+    snprintf(buffer, sizeof(buffer), "getEventTag id=42");
+    send_to_control(buffer, sizeof(buffer));
+    buffer[sizeof(buffer) - 1] = '\0';
+    char* cp;
+    long ret = strtol(buffer, &cp, 10);
+    EXPECT_GT(ret, 16);
+    EXPECT_TRUE(strstr(buffer, "\t(to life the universe etc|3)") != NULL);
+    EXPECT_TRUE(strstr(buffer, "answer") != NULL);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(logd, getEventTag_newentry) {
+#ifdef __ANDROID__
+    char buffer[256];
+    memset(buffer, 0, sizeof(buffer));
+    log_time now(CLOCK_MONOTONIC);
+    char name[64];
+    snprintf(name, sizeof(name), "a%" PRIu64, now.nsec());
+    snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"(new|1)\"",
+             name);
+    send_to_control(buffer, sizeof(buffer));
+    buffer[sizeof(buffer) - 1] = '\0';
+    char* cp;
+    long ret = strtol(buffer, &cp, 10);
+    EXPECT_GT(ret, 16);
+    EXPECT_TRUE(strstr(buffer, "\t(new|1)") != NULL);
+    EXPECT_TRUE(strstr(buffer, name) != NULL);
+// ToDo: also look for this in /data/misc/logd/event-log-tags and
+// /dev/event-log-tags.
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+static inline int32_t get4LE(const char* src) {
+    return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
+}
+
+void __android_log_btwrite_multiple__helper(int count) {
+    log_time ts(CLOCK_MONOTONIC);
+
+    log_time ts1(CLOCK_MONOTONIC);
+
+    // We fork to create a unique pid for the submitted log messages
+    // so that we do not collide with the other _multiple_ tests.
+
+    pid_t pid = fork();
+
+    if (pid == 0) {
+        // child
+        for (int i = count; i; --i) {
+            ASSERT_LT(
+                0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+            usleep(100);
+        }
+        ASSERT_LT(0,
+                  __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
+        usleep(1000000);
+
+        _exit(0);
+    }
+
+    siginfo_t info = {};
+    ASSERT_EQ(0, TEMP_FAILURE_RETRY(waitid(P_PID, pid, &info, WEXITED)));
+    ASSERT_EQ(0, info.si_status);
+
+    struct logger_list* logger_list;
+    ASSERT_TRUE(NULL !=
+                (logger_list = android_logger_list_open(
+                     LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
+                     0, pid)));
+
+    int expected_count = (count < 2) ? count : 2;
+    int expected_chatty_count = (count <= 2) ? 0 : 1;
+    int expected_identical_count = (count < 2) ? 0 : (count - 2);
+    static const int expected_expire_count = 0;
+
+    count = 0;
+    int second_count = 0;
+    int chatty_count = 0;
+    int identical_count = 0;
+    int expire_count = 0;
+
+    for (;;) {
+        log_msg log_msg;
+        if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
+
+        if ((log_msg.entry.pid != pid) || (log_msg.entry.len < (4 + 1 + 8)) ||
+            (log_msg.id() != LOG_ID_EVENTS))
+            continue;
+
+        char* eventData = log_msg.msg();
+        if (!eventData) continue;
+
+        uint32_t tag = get4LE(eventData);
+
+        if ((eventData[4] == EVENT_TYPE_LONG) &&
+            (log_msg.entry.len == (4 + 1 + 8))) {
+            if (tag != 0) continue;
+
+            log_time tx(eventData + 4 + 1);
+            if (ts == tx) {
+                ++count;
+            } else if (ts1 == tx) {
+                ++second_count;
+            }
+        } else if (eventData[4] == EVENT_TYPE_STRING) {
+            if (tag != CHATTY_LOG_TAG) continue;
+            ++chatty_count;
+            // int len = get4LE(eventData + 4 + 1);
+            log_msg.buf[LOGGER_ENTRY_MAX_LEN] = '\0';
+            const char* cp;
+            if ((cp = strstr(eventData + 4 + 1 + 4, " identical "))) {
+                unsigned val = 0;
+                sscanf(cp, " identical %u lines", &val);
+                identical_count += val;
+            } else if ((cp = strstr(eventData + 4 + 1 + 4, " expire "))) {
+                unsigned val = 0;
+                sscanf(cp, " expire %u lines", &val);
+                expire_count += val;
+            }
+        }
+    }
+
+    android_logger_list_close(logger_list);
+
+    EXPECT_EQ(expected_count, count);
+    EXPECT_EQ(1, second_count);
+    EXPECT_EQ(expected_chatty_count, chatty_count);
+    EXPECT_EQ(expected_identical_count, identical_count);
+    EXPECT_EQ(expected_expire_count, expire_count);
+}
+
+TEST(logd, multiple_test_1) {
+    __android_log_btwrite_multiple__helper(1);
+}
+
+TEST(logd, multiple_test_2) {
+    __android_log_btwrite_multiple__helper(2);
+}
+
+TEST(logd, multiple_test_3) {
+    __android_log_btwrite_multiple__helper(3);
+}
+
+TEST(logd, multiple_test_10) {
+    __android_log_btwrite_multiple__helper(10);
+}
+
+#ifdef __ANDROID__
+// returns violating pid
+static pid_t sepolicy_rate(unsigned rate, unsigned num) {
+    pid_t pid = fork();
+
+    if (pid) {
+        siginfo_t info = {};
+        if (TEMP_FAILURE_RETRY(waitid(P_PID, pid, &info, WEXITED))) return 0;
+        if (info.si_status) return 0;
+        return pid;
+    }
+
+    // We may have DAC, but let's not have MAC
+    if (setcon("u:object_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;
+    }
+
+    // The key here is we are root, but we are in u:r:shell:s0,
+    // and the directory does not provide us DAC access
+    // (eg: 0700 system system) so we trigger the pair dac_override
+    // and dac_read_search on every try to get past the message
+    // de-duper.  We will also rotate the file name in the directory
+    // as another measure.
+    static const char file[] = "/data/backup/cannot_access_directory_%u";
+    static const unsigned avc_requests_per_access = 2;
+
+    rate /= avc_requests_per_access;
+    useconds_t usec;
+    if (rate == 0) {
+        rate = 1;
+        usec = 2000000;
+    } else {
+        usec = (1000000 + (rate / 2)) / rate;
+    }
+    num = (num + (avc_requests_per_access / 2)) / avc_requests_per_access;
+
+    if (usec < 2) usec = 2;
+
+    while (num > 0) {
+        if (access(android::base::StringPrintf(file, num).c_str(), F_OK) == 0) {
+            _exit(-1);
+            // NOTREACHED
+            return 0;
+        }
+        usleep(usec);
+        --num;
+    }
+    _exit(0);
+    // NOTREACHED
+    return 0;
+}
+
+static int count_avc(pid_t pid) {
+    int count = 0;
+
+    if (pid == 0) return count;
+
+    struct logger_list* logger_list;
+    if (!(logger_list = android_logger_list_open(
+              LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, pid)))
+        return count;
+    for (;;) {
+        log_msg log_msg;
+
+        if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
+
+        if ((log_msg.entry.pid != pid) || (log_msg.entry.len < (4 + 1 + 8)) ||
+            (log_msg.id() != LOG_ID_EVENTS))
+            continue;
+
+        char* eventData = log_msg.msg();
+        if (!eventData) continue;
+
+        uint32_t tag = get4LE(eventData);
+        if (tag != AUDITD_LOG_TAG) continue;
+
+        if (eventData[4] != EVENT_TYPE_STRING) continue;
+
+        // int len = get4LE(eventData + 4 + 1);
+        log_msg.buf[LOGGER_ENTRY_MAX_LEN] = '\0';
+        const char* cp = strstr(eventData + 4 + 1 + 4, "): avc: denied");
+        if (!cp) continue;
+
+        ++count;
+    }
+
+    android_logger_list_close(logger_list);
+
+    return count;
+}
+#endif
+
+TEST(logd, sepolicy_rate_limiter_maximum) {
+#ifdef __ANDROID__
+    static const int rate = AUDIT_RATE_LIMIT_MAX;
+    static const int duration = 2;
+    // Two seconds of a liveable sustained rate
+    EXPECT_EQ(rate * duration, count_avc(sepolicy_rate(rate, rate * duration)));
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(logd, sepolicy_rate_limiter_sub_burst) {
+#ifdef __ANDROID__
+    // maximum period below half way between sustainable and burst rate.
+    static const int threshold =
+        ((AUDIT_RATE_LIMIT_BURST_DURATION *
+          (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
+         1) /
+        2;
+    static const int rate = (threshold / AUDIT_RATE_LIMIT_BURST_DURATION) - 1;
+    static const int duration = AUDIT_RATE_LIMIT_BURST_DURATION;
+    EXPECT_EQ(rate * duration, count_avc(sepolicy_rate(rate, rate * duration)));
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(logd, sepolicy_rate_limiter_spam) {
+#ifdef __ANDROID__
+    // maximum period of double the maximum burst rate
+    static const int threshold =
+        ((AUDIT_RATE_LIMIT_BURST_DURATION *
+          (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
+         1) /
+        2;
+    static const int rate = AUDIT_RATE_LIMIT_DEFAULT * 2;
+    static const int duration = threshold / AUDIT_RATE_LIMIT_DEFAULT;
+    EXPECT_GE(
+        ((AUDIT_RATE_LIMIT_DEFAULT * duration) * 115) / 100,  // +15% margin
+        count_avc(sepolicy_rate(rate, rate * duration)));
+    // give logd another 3 seconds to react to the burst before checking
+    sepolicy_rate(rate, rate * 3);
+    // maximum period at double the maximum burst rate (spam filter kicked in)
+    EXPECT_GE(
+        threshold * 2,
+        count_avc(sepolicy_rate(rate, rate * AUDIT_RATE_LIMIT_BURST_DURATION)));
+    // cool down, and check unspammy rate still works
+    sleep(2);
+    EXPECT_LE(AUDIT_RATE_LIMIT_BURST_DURATION - 1,  // allow _one_ to be lost
+              count_avc(sepolicy_rate(1, AUDIT_RATE_LIMIT_BURST_DURATION)));
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
diff --git a/logwrapper/Android.bp b/logwrapper/Android.bp
new file mode 100644
index 0000000..ccb1aa6
--- /dev/null
+++ b/logwrapper/Android.bp
@@ -0,0 +1,53 @@
+
+
+// ========================================================
+// Static and shared library
+// ========================================================
+cc_library {
+    name: "liblogwrap",
+    srcs: ["logwrap.c"],
+    shared_libs: [
+        "libcutils",
+        "liblog",
+    ],
+    export_include_dirs: ["include"],
+    local_include_dirs: ["include"],
+    cflags: [
+        "-Werror",
+    ],
+}
+
+// ========================================================
+// Executable
+// ========================================================
+cc_binary {
+    name: "logwrapper",
+    srcs: ["logwrapper.c"],
+    static_libs: [
+        "liblog",
+        "liblogwrap",
+        "libcutils",
+    ],
+    cflags: [
+        "-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.mk b/logwrapper/Android.mk
deleted file mode 100644
index ad45b2c..0000000
--- a/logwrapper/Android.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# ========================================================
-# Static library
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := liblogwrap
-LOCAL_SRC_FILES := logwrap.c
-LOCAL_SHARED_LIBRARIES := libcutils liblog
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror -std=gnu99
-include $(BUILD_STATIC_LIBRARY)
-
-# ========================================================
-# Shared library
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := liblogwrap
-LOCAL_SHARED_LIBRARIES := libcutils liblog
-LOCAL_WHOLE_STATIC_LIBRARIES := liblogwrap
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror -std=gnu99
-include $(BUILD_SHARED_LIBRARY)
-
-# ========================================================
-# Executable
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= logwrapper.c
-LOCAL_MODULE := logwrapper
-LOCAL_STATIC_LIBRARIES := liblog liblogwrap libcutils
-LOCAL_CFLAGS := -Werror -std=gnu99
-include $(BUILD_EXECUTABLE)
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 28d6de7..7076078 100644
--- a/logwrapper/logwrap.c
+++ b/logwrapper/logwrap.c
@@ -14,24 +14,24 @@
  * limitations under the License.
  */
 
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <poll.h>
-#include <sys/wait.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <libgen.h>
-#include <stdbool.h>
+#include <poll.h>
 #include <pthread.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
 
-#include <logwrap/logwrap.h>
-#include "private/android_filesystem_config.h"
-#include "cutils/log.h"
 #include <cutils/klog.h>
+#include <log/log.h>
+#include <logwrap/logwrap.h>
+#include <private/android_filesystem_config.h>
 
 #define ARRAY_SIZE(x)   (sizeof(x) / sizeof(*(x)))
 #define MIN(a,b) (((a)<(b))?(a):(b))
@@ -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++) {
@@ -408,7 +400,7 @@
         if (poll_fds[0].revents & POLLHUP) {
             int ret;
 
-            ret = waitpid(pid, &status, WNOHANG);
+            ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
             if (ret < 0) {
                 rc = errno;
                 ALOG(LOG_ERROR, "logwrap", "waitpid failed with %s\n", strerror(errno));
@@ -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/logwrapper/logwrapper.c b/logwrapper/logwrapper.c
index 55b71c7..33454c6 100644
--- a/logwrapper/logwrapper.c
+++ b/logwrapper/logwrapper.c
@@ -20,10 +20,9 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <logwrap/logwrap.h>
 #include <cutils/klog.h>
-
-#include "cutils/log.h"
+#include <log/log.h>
+#include <logwrap/logwrap.h>
 
 void fatal(const char *msg) {
     fprintf(stderr, "%s", msg);
diff --git a/metricsd/.clang-format b/metricsd/.clang-format
deleted file mode 100644
index c98efc2..0000000
--- a/metricsd/.clang-format
+++ /dev/null
@@ -1,10 +0,0 @@
-BasedOnStyle: Google
-AllowShortFunctionsOnASingleLine: Inline
-AllowShortIfStatementsOnASingleLine: false
-AllowShortLoopsOnASingleLine: false
-BinPackArguments: false
-BinPackParameters: false
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-PointerAlignment: Left
-TabWidth: 2
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
deleted file mode 100644
index bb262b4..0000000
--- a/metricsd/Android.mk
+++ /dev/null
@@ -1,232 +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)
-
-metrics_cpp_extension := .cc
-libmetrics_sources := \
-  c_metrics_library.cc \
-  metrics_library.cc \
-  timer.cc
-
-metrics_client_sources := \
-  metrics_client.cc
-
-metrics_collector_common := \
-  collectors/averaged_statistics_collector.cc \
-  collectors/cpu_usage_collector.cc \
-  collectors/disk_usage_collector.cc \
-  metrics_collector.cc \
-  metrics_collector_service_impl.cc \
-  persistent_integer.cc
-
-metricsd_common := \
-  persistent_integer.cc \
-  uploader/bn_metricsd_impl.cc \
-  uploader/crash_counters.cc \
-  uploader/metrics_hashes.cc \
-  uploader/metrics_log_base.cc \
-  uploader/metrics_log.cc \
-  uploader/metricsd_service_runner.cc \
-  uploader/sender_http.cc \
-  uploader/system_profile_cache.cc \
-  uploader/upload_service.cc
-
-metrics_collector_tests_sources := \
-  collectors/averaged_statistics_collector_test.cc \
-  collectors/cpu_usage_collector_test.cc \
-  metrics_collector_test.cc \
-  metrics_library_test.cc \
-  persistent_integer_test.cc \
-  timer_test.cc
-
-metricsd_tests_sources := \
-  uploader/metrics_hashes_unittest.cc \
-  uploader/metrics_log_base_unittest.cc \
-  uploader/mock/sender_mock.cc \
-  uploader/upload_service_test.cc
-
-metrics_CFLAGS := -Wall \
-  -Wno-char-subscripts \
-  -Wno-missing-field-initializers \
-  -Wno-unused-parameter \
-  -Werror \
-  -fvisibility=default
-metrics_CPPFLAGS := -Wno-non-virtual-dtor \
-  -Wno-sign-promo \
-  -Wno-strict-aliasing \
-  -fvisibility=default
-metrics_includes := external/gtest/include \
-  $(LOCAL_PATH)/include
-libmetrics_shared_libraries := libchrome libbinder libbrillo libutils
-metrics_collector_shared_libraries := $(libmetrics_shared_libraries) \
-  libbrillo-binder \
-  libbrillo-http \
-  libmetrics \
-  librootdev \
-  libweaved
-
-metrics_collector_static_libraries := libmetricscollectorservice
-
-metricsd_shared_libraries := \
-  libbinder \
-  libbrillo \
-  libbrillo-binder \
-  libbrillo-http \
-  libchrome \
-  libprotobuf-cpp-lite \
-  libupdate_engine_client \
-  libutils
-
-# Static proxy library for the metricsd binder interface.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metricsd_binder_proxy
-LOCAL_SHARED_LIBRARIES := libbinder libutils
-LOCAL_SRC_FILES := aidl/android/brillo/metrics/IMetricsd.aidl
-include $(BUILD_STATIC_LIBRARY)
-
-# Static library for the metrics_collector binder interface.
-# ==========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := libmetricscollectorservice
-LOCAL_CLANG := true
-LOCAL_SHARED_LIBRARIES := libbinder libbrillo-binder libchrome libutils
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SRC_FILES := \
-  aidl/android/brillo/metrics/IMetricsCollectorService.aidl \
-  metrics_collector_service_client.cc
-include $(BUILD_STATIC_LIBRARY)
-
-# Shared library for metrics.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := libmetrics
-LOCAL_C_INCLUDES := $(metrics_includes)
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SHARED_LIBRARIES := $(libmetrics_shared_libraries)
-LOCAL_SRC_FILES := $(libmetrics_sources)
-LOCAL_STATIC_LIBRARIES := metricsd_binder_proxy
-include $(BUILD_SHARED_LIBRARY)
-
-# CLI client for metrics.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metrics_client
-LOCAL_C_INCLUDES := $(metrics_includes)
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
-LOCAL_SHARED_LIBRARIES := $(libmetrics_shared_libraries) \
-  libmetrics
-LOCAL_SRC_FILES := $(metrics_client_sources)
-LOCAL_STATIC_LIBRARIES := metricsd_binder_proxy
-include $(BUILD_EXECUTABLE)
-
-# Protobuf library for metricsd.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metricsd_protos
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-generated_sources_dir := $(call local-generated-sources-dir)
-LOCAL_EXPORT_C_INCLUDE_DIRS += \
-    $(generated_sources_dir)/proto/system/core/metricsd
-LOCAL_SRC_FILES :=  $(call all-proto-files-under,uploader/proto)
-include $(BUILD_STATIC_LIBRARY)
-
-# metrics_collector daemon.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metrics_collector
-LOCAL_C_INCLUDES := $(metrics_includes)
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
-LOCAL_INIT_RC := metrics_collector.rc
-LOCAL_REQUIRED_MODULES := metrics.json
-LOCAL_SHARED_LIBRARIES := $(metrics_collector_shared_libraries)
-LOCAL_SRC_FILES := $(metrics_collector_common) \
-  metrics_collector_main.cc
-LOCAL_STATIC_LIBRARIES := metricsd_binder_proxy \
-  $(metrics_collector_static_libraries)
-include $(BUILD_EXECUTABLE)
-
-# metricsd daemon.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metricsd
-LOCAL_C_INCLUDES := $(metrics_includes)
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
-LOCAL_INIT_RC := metricsd.rc
-LOCAL_REQUIRED_MODULES := \
-  metrics_collector
-LOCAL_SHARED_LIBRARIES := $(metricsd_shared_libraries)
-LOCAL_STATIC_LIBRARIES := metricsd_protos metricsd_binder_proxy
-LOCAL_SRC_FILES := $(metricsd_common) \
-  metricsd_main.cc
-include $(BUILD_EXECUTABLE)
-
-# Unit tests for metricsd.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metricsd_tests
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS) -Wno-sign-compare
-LOCAL_SHARED_LIBRARIES := $(metricsd_shared_libraries)
-LOCAL_SRC_FILES := $(metricsd_tests_sources) $(metricsd_common)
-LOCAL_STATIC_LIBRARIES := libBionicGtestMain libgmock metricsd_protos metricsd_binder_proxy
-ifdef BRILLO
-LOCAL_MODULE_TAGS := eng
-endif
-include $(BUILD_NATIVE_TEST)
-
-# Unit tests for metrics_collector.
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metrics_collector_tests
-LOCAL_CFLAGS := $(metrics_CFLAGS)
-LOCAL_CLANG := true
-LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
-LOCAL_CPPFLAGS := $(metrics_CPPFLAGS) -Wno-sign-compare
-LOCAL_SHARED_LIBRARIES := $(metrics_collector_shared_libraries)
-LOCAL_SRC_FILES := $(metrics_collector_tests_sources) \
-  $(metrics_collector_common)
-LOCAL_STATIC_LIBRARIES := libBionicGtestMain libgmock metricsd_binder_proxy \
-  $(metrics_collector_static_libraries)
-ifdef BRILLO
-LOCAL_MODULE_TAGS := eng
-endif
-include $(BUILD_NATIVE_TEST)
-
-# Weave schema files
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_MODULE := metrics.json
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/weaved/traits
-LOCAL_SRC_FILES := etc/weaved/traits/$(LOCAL_MODULE)
-include $(BUILD_PREBUILT)
diff --git a/metricsd/OWNERS b/metricsd/OWNERS
deleted file mode 100644
index 7f5e50d..0000000
--- a/metricsd/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-semenzato@chromium.org
-derat@chromium.org
-bsimonnet@chromium.org
diff --git a/metricsd/README.md b/metricsd/README.md
deleted file mode 100644
index 8d4828c..0000000
--- a/metricsd/README.md
+++ /dev/null
@@ -1,124 +0,0 @@
-Metricsd
-========
-
-The metricsd daemon is used to gather metrics from the platform and application,
-aggregate them and upload them periodically to a server.
-The metrics will then be available in their aggregated form to the developer
-for analysis.
-
-Three components are provided to interact with `metricsd`: `libmetrics`,
-`metrics_collector` and `metrics_client`.
-
-The Metrics Library: libmetrics
--------------------------------
-
-`libmetrics` is a small library that implements the basic C++ API for
-metrics collection. All metrics collection is funneled through this library. The
-easiest and recommended way for a client-side module to collect user metrics is
-to link `libmetrics` and use its APIs to send metrics to `metricsd` for transport to
-UMA. In order to use the library in a module, you need to do the following:
-
-- Add a dependency on the shared library in your Android.mk file:
-  `LOCAL_SHARED_LIBRARIES += libmetrics`
-
-- To access the metrics library API in the module, include the
-  <metrics/metrics_library.h> header file.
-
-- The API is documented in `metrics_library.h`. Before using the API methods, a
-  MetricsLibrary object needs to be constructed and initialized through its
-  Init method.
-
-- Samples are uploaded only if the `/data/misc/metrics/enabled` file exists.
-
-
-Server Side
------------
-
-You will be able to see all uploaded metrics on the metrics dashboard,
-accessible via the developer console.
-
-*** note
-It usually takes a day for metrics to be available on the dashboard.
-***
-
-
-The Metrics Client: metrics_client
-----------------------------------
-
-`metrics_client` is a simple shell command-line utility for sending histogram
-samples and querying `metricsd`. It's installed under `/system/bin` on the target
-platform and uses `libmetrics`.
-
-For usage information and command-line options, run `metrics_client` on the
-target platform or look for "Usage:" in `metrics_client.cc`.
-
-
-The Metrics Daemon: metricsd
-----------------------------
-
-`metricsd` is the daemon that listens for metrics logging calls (via Binder),
-aggregates the metrics and uploads them periodically. This daemon should start as
-early as possible so that depending daemons can log at any time.
-
-`metricsd` is made of two threads that work as follows:
-
-* The binder thread listens for one-way Binder calls, aggregates the metrics in
-  memory (via `base::StatisticsRecorder`) and increments the crash counters when a
-  crash is reported. This thread is kept as simple as possible to ensure the
-  maximum throughput possible.
-* The uploader thread takes care of backing up the metrics to disk periodically
-  (to avoid losing metrics on crashes), collecting metadata about the client
-  (version number, channel, etc..) and uploading the metrics periodically to the
-  server.
-
-
-The Metrics Collector: metrics_collector
-----------------------------------------
-
-metrics_collector is a daemon that runs in the background on the target platform,
-gathers health information about the system and maintains long running counters
-(ex: number of crashes per week).
-
-The recommended way to generate metrics data from a module is to link and use
-libmetrics directly. However, we may not want to add a dependency on libmetrics
-to some modules (ex: kernel). In this case, we can add a collector to
-metrics_collector that will, for example, take measurements and report them
-periodically to metricsd (this is the case for the disk utilization histogram).
-
-
-FAQ
----
-
-### What should my histogram's |min| and |max| values be set at?
-
-You should set the values to a range that covers the vast majority of samples
-that would appear in the field. Note that samples below the |min| will still
-be collected in the underflow bucket and samples above the |max| will end up
-in the overflow bucket. Also, the reported mean of the data will be correct
-regardless of the range.
-
-### How many buckets should I use in my histogram?
-
-You should allocate as many buckets as necessary to perform proper analysis
-on the collected data. Note, however, that the memory allocated in metricsd
-for each histogram is proportional to the number of buckets. Therefore, it is
-strongly recommended to keep this number low (e.g., 50 is normal, while 100
-is probably high).
-
-### When should I use an enumeration (linear) histogram vs. a regular (exponential) histogram?
-
-Enumeration histograms should really be used only for sampling enumerated
-events and, in some cases, percentages. Normally, you should use a regular
-histogram with exponential bucket layout that provides higher resolution at
-the low end of the range and lower resolution at the high end. Regular
-histograms are generally used for collecting performance data (e.g., timing,
-memory usage, power) as well as aggregated event counts.
-
-### How can I test that my histogram was reported correctly?
-
-* Make sure no error messages appear in logcat when you log a sample.
-* Run `metrics_client -d` to dump the currently aggregated metrics. Your
-  histogram should appear in the list.
-* Make sure that the aggregated metrics were uploaded to the server successfully
-  (check for an OK message from `metricsd` in logcat).
-* After a day, your histogram should be available on the dashboard.
diff --git a/metricsd/WATCHLISTS b/metricsd/WATCHLISTS
deleted file mode 100644
index a051f35..0000000
--- a/metricsd/WATCHLISTS
+++ /dev/null
@@ -1,16 +0,0 @@
-# See http://dev.chromium.org/developers/contributing-code/watchlists for
-# a description of this file's format.
-# Please keep these keys in alphabetical order.
-
-{
-  'WATCHLIST_DEFINITIONS': {
-    'all': {
-      'filepath': '.',
-    },
-  },
-  'WATCHLISTS': {
-    'all': ['petkov@chromium.org',
-                'semenzato@chromium.org',
-                'sosa@chromium.org']
-  },
-}
diff --git a/metricsd/aidl/android/brillo/metrics/IMetricsCollectorService.aidl b/metricsd/aidl/android/brillo/metrics/IMetricsCollectorService.aidl
deleted file mode 100644
index 49f484f..0000000
--- a/metricsd/aidl/android/brillo/metrics/IMetricsCollectorService.aidl
+++ /dev/null
@@ -1,21 +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.
- */
-
-package android.brillo.metrics;
-
-interface IMetricsCollectorService {
-  oneway void notifyUserCrash();
-}
diff --git a/metricsd/aidl/android/brillo/metrics/IMetricsd.aidl b/metricsd/aidl/android/brillo/metrics/IMetricsd.aidl
deleted file mode 100644
index aa3cb34..0000000
--- a/metricsd/aidl/android/brillo/metrics/IMetricsd.aidl
+++ /dev/null
@@ -1,26 +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.
- */
-
-package android.brillo.metrics;
-
-interface IMetricsd {
-  oneway void recordHistogram(String name, int sample, int min, int max,
-                              int nbuckets);
-  oneway void recordLinearHistogram(String name, int sample, int max);
-  oneway void recordSparseHistogram(String name, int sample);
-  oneway void recordCrash(String type);
-  String getHistogramsDump();
-}
diff --git a/metricsd/c_metrics_library.cc b/metricsd/c_metrics_library.cc
deleted file mode 100644
index 47a543e..0000000
--- a/metricsd/c_metrics_library.cc
+++ /dev/null
@@ -1,82 +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.
- */
-
-//
-// C wrapper to libmetrics
-//
-
-#include "metrics/c_metrics_library.h"
-
-#include <string>
-
-#include "metrics/metrics_library.h"
-
-extern "C" CMetricsLibrary CMetricsLibraryNew(void) {
-  MetricsLibrary* lib = new MetricsLibrary;
-  return reinterpret_cast<CMetricsLibrary>(lib);
-}
-
-extern "C" void CMetricsLibraryDelete(CMetricsLibrary handle) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  delete lib;
-}
-
-extern "C" void CMetricsLibraryInit(CMetricsLibrary handle) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib != NULL)
-    lib->Init();
-}
-
-extern "C" int CMetricsLibrarySendToUMA(CMetricsLibrary handle,
-                                        const char* name, int sample,
-                                        int min, int max, int nbuckets) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib == NULL)
-    return 0;
-  return lib->SendToUMA(std::string(name), sample, min, max, nbuckets);
-}
-
-extern "C" int CMetricsLibrarySendEnumToUMA(CMetricsLibrary handle,
-                                            const char* name, int sample,
-                                            int max) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib == NULL)
-    return 0;
-  return lib->SendEnumToUMA(std::string(name), sample, max);
-}
-
-extern "C" int CMetricsLibrarySendSparseToUMA(CMetricsLibrary handle,
-                                              const char* name, int sample) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib == NULL)
-    return 0;
-  return lib->SendSparseToUMA(std::string(name), sample);
-}
-
-extern "C" int CMetricsLibrarySendCrashToUMA(CMetricsLibrary handle,
-                                            const char* crash_kind) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib == NULL)
-    return 0;
-  return lib->SendCrashToUMA(crash_kind);
-}
-
-extern "C" int CMetricsLibraryAreMetricsEnabled(CMetricsLibrary handle) {
-  MetricsLibrary* lib = reinterpret_cast<MetricsLibrary*>(handle);
-  if (lib == NULL)
-    return 0;
-  return lib->AreMetricsEnabled();
-}
diff --git a/metricsd/collectors/averaged_statistics_collector.cc b/metricsd/collectors/averaged_statistics_collector.cc
deleted file mode 100644
index a3aaa98..0000000
--- a/metricsd/collectors/averaged_statistics_collector.cc
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "averaged_statistics_collector.h"
-
-#include <base/bind.h>
-#include <base/files/file_util.h>
-#include <base/files/file_path.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_split.h>
-
-#include "metrics_collector.h"
-
-namespace {
-
-// disk stats metrics
-
-// The {Read,Write}Sectors numbers are in sectors/second.
-// A sector is usually 512 bytes.
-const char kReadSectorsHistogramName[] = "Platform.ReadSectors";
-const char kWriteSectorsHistogramName[] = "Platform.WriteSectors";
-const int kDiskMetricsStatItemCount = 11;
-
-// Assume a max rate of 250Mb/s for reads (worse for writes) and 512 byte
-// sectors.
-const int kSectorsIOMax = 500000;  // sectors/second
-const int kSectorsBuckets = 50;    // buckets
-
-// Page size is 4k, sector size is 0.5k.  We're not interested in page fault
-// rates that the disk cannot sustain.
-const int kPageFaultsMax = kSectorsIOMax / 8;  // Page faults/second
-const int kPageFaultsBuckets = 50;
-
-// Major page faults, i.e. the ones that require data to be read from disk.
-const char kPageFaultsHistogramName[] = "Platform.PageFaults";
-
-// Swap in and Swap out
-const char kSwapInHistogramName[] = "Platform.SwapIn";
-const char kSwapOutHistogramName[] = "Platform.SwapOut";
-
-const int kIntervalBetweenCollection = 60;  // seconds
-const int kCollectionDuration = 1;  // seconds
-
-}  // namespace
-
-AveragedStatisticsCollector::AveragedStatisticsCollector(
-    MetricsLibraryInterface* metrics_library,
-    const std::string& diskstats_path,
-    const std::string& vmstats_path) :
-  metrics_lib_(metrics_library),
-  diskstats_path_(diskstats_path),
-  vmstats_path_(vmstats_path) {
-}
-
-void AveragedStatisticsCollector::ScheduleWait() {
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&AveragedStatisticsCollector::WaitCallback,
-                 base::Unretained(this)),
-      base::TimeDelta::FromSeconds(
-          kIntervalBetweenCollection - kCollectionDuration));
-}
-
-void AveragedStatisticsCollector::ScheduleCollect() {
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&AveragedStatisticsCollector::CollectCallback,
-                 base::Unretained(this)),
-      base::TimeDelta::FromSeconds(kCollectionDuration));
-}
-
-void AveragedStatisticsCollector::WaitCallback() {
-  ReadInitialValues();
-  ScheduleCollect();
-}
-
-void AveragedStatisticsCollector::CollectCallback() {
-  Collect();
-  ScheduleWait();
-}
-
-void AveragedStatisticsCollector::ReadInitialValues() {
-  stats_start_time_ = MetricsCollector::GetActiveTime();
-  DiskStatsReadStats(&read_sectors_, &write_sectors_);
-  VmStatsReadStats(&vmstats_);
-}
-
-bool AveragedStatisticsCollector::DiskStatsReadStats(
-    uint64_t* read_sectors, uint64_t* write_sectors) {
-  CHECK(read_sectors);
-  CHECK(write_sectors);
-  std::string line;
-  if (diskstats_path_.empty()) {
-    return false;
-  }
-
-  if (!base::ReadFileToString(base::FilePath(diskstats_path_), &line)) {
-    PLOG(WARNING) << "Could not read disk stats from "
-                  << diskstats_path_.value();
-    return false;
-  }
-
-  std::vector<std::string> parts = base::SplitString(
-      line, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
-  if (parts.size() != kDiskMetricsStatItemCount) {
-    LOG(ERROR) << "Could not parse disk stat correctly. Expected "
-               << kDiskMetricsStatItemCount << " elements but got "
-               << parts.size();
-    return false;
-  }
-  if (!base::StringToUint64(parts[2], read_sectors)) {
-    LOG(ERROR) << "Couldn't convert read sectors " << parts[2] << " to uint64";
-    return false;
-  }
-  if (!base::StringToUint64(parts[6], write_sectors)) {
-    LOG(ERROR) << "Couldn't convert write sectors " << parts[6] << " to uint64";
-    return false;
-  }
-
-  return true;
-}
-
-bool AveragedStatisticsCollector::VmStatsParseStats(
-    const char* stats, struct VmstatRecord* record) {
-  CHECK(stats);
-  CHECK(record);
-  base::StringPairs pairs;
-  base::SplitStringIntoKeyValuePairs(stats, ' ', '\n', &pairs);
-
-  for (base::StringPairs::iterator it = pairs.begin();
-       it != pairs.end(); ++it) {
-    if (it->first == "pgmajfault" &&
-        !base::StringToUint64(it->second, &record->page_faults)) {
-      return false;
-    }
-    if (it->first == "pswpin" &&
-        !base::StringToUint64(it->second, &record->swap_in)) {
-      return false;
-    }
-    if (it->first == "pswpout" &&
-        !base::StringToUint64(it->second, &record->swap_out)) {
-      return false;
-    }
-  }
-  return true;
-}
-
-bool AveragedStatisticsCollector::VmStatsReadStats(struct VmstatRecord* stats) {
-  CHECK(stats);
-  std::string value_string;
-  if (!base::ReadFileToString(vmstats_path_, &value_string)) {
-    LOG(WARNING) << "cannot read " << vmstats_path_.value();
-    return false;
-  }
-  return VmStatsParseStats(value_string.c_str(), stats);
-}
-
-void AveragedStatisticsCollector::Collect() {
-  uint64_t read_sectors_now, write_sectors_now;
-  struct VmstatRecord vmstats_now;
-  double time_now = MetricsCollector::GetActiveTime();
-  double delta_time = time_now - stats_start_time_;
-  bool diskstats_success = DiskStatsReadStats(&read_sectors_now,
-                                              &write_sectors_now);
-
-  int delta_read = read_sectors_now - read_sectors_;
-  int delta_write = write_sectors_now - write_sectors_;
-  int read_sectors_per_second = delta_read / delta_time;
-  int write_sectors_per_second = delta_write / delta_time;
-  bool vmstats_success = VmStatsReadStats(&vmstats_now);
-  uint64_t delta_faults = vmstats_now.page_faults - vmstats_.page_faults;
-  uint64_t delta_swap_in = vmstats_now.swap_in - vmstats_.swap_in;
-  uint64_t delta_swap_out = vmstats_now.swap_out - vmstats_.swap_out;
-  uint64_t page_faults_per_second = delta_faults / delta_time;
-  uint64_t swap_in_per_second = delta_swap_in / delta_time;
-  uint64_t swap_out_per_second = delta_swap_out / delta_time;
-  if (diskstats_success) {
-    metrics_lib_->SendToUMA(kReadSectorsHistogramName,
-                            read_sectors_per_second,
-                            1,
-                            kSectorsIOMax,
-                            kSectorsBuckets);
-    metrics_lib_->SendToUMA(kWriteSectorsHistogramName,
-                            write_sectors_per_second,
-                            1,
-                            kSectorsIOMax,
-                            kSectorsBuckets);
-  }
-  if (vmstats_success) {
-    metrics_lib_->SendToUMA(kPageFaultsHistogramName,
-                            page_faults_per_second,
-                            1,
-                            kPageFaultsMax,
-                            kPageFaultsBuckets);
-    metrics_lib_->SendToUMA(kSwapInHistogramName,
-                            swap_in_per_second,
-                            1,
-                            kPageFaultsMax,
-                            kPageFaultsBuckets);
-    metrics_lib_->SendToUMA(kSwapOutHistogramName,
-                            swap_out_per_second,
-                            1,
-                            kPageFaultsMax,
-                            kPageFaultsBuckets);
-  }
-}
diff --git a/metricsd/collectors/averaged_statistics_collector.h b/metricsd/collectors/averaged_statistics_collector.h
deleted file mode 100644
index 753f70c..0000000
--- a/metricsd/collectors/averaged_statistics_collector.h
+++ /dev/null
@@ -1,79 +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.
- */
-
-#ifndef METRICSD_COLLECTORS_AVERAGED_STATISTICS_COLLECTOR_H_
-#define METRICSD_COLLECTORS_AVERAGED_STATISTICS_COLLECTOR_H_
-
-#include "metrics/metrics_library.h"
-
-class AveragedStatisticsCollector {
- public:
-  AveragedStatisticsCollector(MetricsLibraryInterface* metrics_library,
-                              const std::string& diskstats_path,
-                              const std::string& vmstat_path);
-
-  // Schedule a wait period.
-  void ScheduleWait();
-
-  // Schedule a collection period.
-  void ScheduleCollect();
-
-  // Callback used by the main loop.
-  void CollectCallback();
-
-  // Callback used by the main loop.
-  void WaitCallback();
-
-  // Read and store the initial values at the beginning of a collection cycle.
-  void ReadInitialValues();
-
-  // Collect the disk usage statistics and report them.
-  void Collect();
-
- private:
-  friend class AveragedStatisticsTest;
-  FRIEND_TEST(AveragedStatisticsTest, ParseDiskStats);
-  FRIEND_TEST(AveragedStatisticsTest, ParseVmStats);
-
-  // Record for retrieving and reporting values from /proc/vmstat
-  struct VmstatRecord {
-    uint64_t page_faults;    // major faults
-    uint64_t swap_in;        // pages swapped in
-    uint64_t swap_out;       // pages swapped out
-  };
-
-  // Read the disk read/write statistics for the main disk.
-  bool DiskStatsReadStats(uint64_t* read_sectors, uint64_t* write_sectors);
-
-  // Parse the content of the vmstats file into |record|.
-  bool VmStatsParseStats(const char* stats, struct VmstatRecord* record);
-
-  // Read the vmstats into |stats|.
-  bool VmStatsReadStats(struct VmstatRecord* stats);
-
-  MetricsLibraryInterface* metrics_lib_;
-  base::FilePath diskstats_path_;
-  base::FilePath vmstats_path_;
-
-  // Values observed at the beginning of the collection period.
-  uint64_t read_sectors_;
-  uint64_t write_sectors_;
-  struct VmstatRecord vmstats_;
-
-  double stats_start_time_;
-};
-
-#endif  // METRICSD_COLLECTORS_AVERAGED_STATISTICS_COLLECTOR_H_
diff --git a/metricsd/collectors/averaged_statistics_collector_test.cc b/metricsd/collectors/averaged_statistics_collector_test.cc
deleted file mode 100644
index 68f9f2f..0000000
--- a/metricsd/collectors/averaged_statistics_collector_test.cc
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "averaged_statistics_collector.h"
-
-#include <memory>
-
-#include <inttypes.h>
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/stringprintf.h>
-#include <gtest/gtest.h>
-
-
-static const char kFakeDiskStatsFormat[] =
-    "    1793     1788    %" PRIu64 "   105580    "
-    "    196      175     %" PRIu64 "    30290    "
-    "    0    44060   135850\n";
-static const uint64_t kFakeReadSectors[] = {80000, 100000};
-static const uint64_t kFakeWriteSectors[] = {3000, 4000};
-
-
-class AveragedStatisticsTest : public testing::Test {
- protected:
-  std::string kFakeDiskStats0;
-  std::string kFakeDiskStats1;
-
-  virtual void SetUp() {
-    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
-    disk_stats_path_ = temp_dir_.path().Append("disk_stats");
-    collector_.reset(new AveragedStatisticsCollector(
-        &metrics_lib_, disk_stats_path_.value(), ""));
-
-    kFakeDiskStats0 = base::StringPrintf(kFakeDiskStatsFormat,
-                                         kFakeReadSectors[0],
-                                         kFakeWriteSectors[0]);
-    kFakeDiskStats1 = base::StringPrintf(kFakeDiskStatsFormat,
-                                         kFakeReadSectors[1],
-                                         kFakeWriteSectors[1]);
-
-    CreateFakeDiskStatsFile(kFakeDiskStats0);
-  }
-
-  // Creates or overwrites an input file containing fake disk stats.
-  void CreateFakeDiskStatsFile(const std::string& fake_stats) {
-    EXPECT_EQ(base::WriteFile(disk_stats_path_,
-                              fake_stats.data(), fake_stats.size()),
-              fake_stats.size());
-  }
-
-  // Collector used for tests.
-  std::unique_ptr<AveragedStatisticsCollector> collector_;
-
-  // Temporary directory used for tests.
-  base::ScopedTempDir temp_dir_;
-
-  // Path for the fake files.
-  base::FilePath disk_stats_path_;
-
-  MetricsLibrary metrics_lib_;
-};
-
-TEST_F(AveragedStatisticsTest, ParseDiskStats) {
-  uint64_t read_sectors_now, write_sectors_now;
-  CreateFakeDiskStatsFile(kFakeDiskStats0);
-  ASSERT_TRUE(collector_->DiskStatsReadStats(&read_sectors_now,
-                                             &write_sectors_now));
-  EXPECT_EQ(read_sectors_now, kFakeReadSectors[0]);
-  EXPECT_EQ(write_sectors_now, kFakeWriteSectors[0]);
-
-  CreateFakeDiskStatsFile(kFakeDiskStats1);
-  ASSERT_TRUE(collector_->DiskStatsReadStats(&read_sectors_now,
-                                             &write_sectors_now));
-  EXPECT_EQ(read_sectors_now, kFakeReadSectors[1]);
-  EXPECT_EQ(write_sectors_now, kFakeWriteSectors[1]);
-}
-
-TEST_F(AveragedStatisticsTest, ParseVmStats) {
-  static char kVmStats[] = "pswpin 1345\npswpout 8896\n"
-    "foo 100\nbar 200\npgmajfault 42\netcetc 300\n";
-  struct AveragedStatisticsCollector::VmstatRecord stats;
-  EXPECT_TRUE(collector_->VmStatsParseStats(kVmStats, &stats));
-  EXPECT_EQ(stats.page_faults, 42);
-  EXPECT_EQ(stats.swap_in, 1345);
-  EXPECT_EQ(stats.swap_out, 8896);
-}
diff --git a/metricsd/collectors/cpu_usage_collector.cc b/metricsd/collectors/cpu_usage_collector.cc
deleted file mode 100644
index 9b0bb34..0000000
--- a/metricsd/collectors/cpu_usage_collector.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "collectors/cpu_usage_collector.h"
-
-#include <base/bind.h>
-#include <base/files/file_path.h>
-#include <base/files/file_util.h>
-#include <base/message_loop/message_loop.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/sys_info.h>
-
-#include "metrics/metrics_library.h"
-
-namespace {
-
-const char kCpuUsagePercent[] = "Platform.CpuUsage.Percent";
-const char kMetricsProcStatFileName[] = "/proc/stat";
-const int kMetricsProcStatFirstLineItemsCount = 11;
-
-// Collect every minute.
-const int kCollectionIntervalSecs = 60;
-
-}  // namespace
-
-using base::TimeDelta;
-
-CpuUsageCollector::CpuUsageCollector(MetricsLibraryInterface* metrics_library) {
-  CHECK(metrics_library);
-  metrics_lib_ = metrics_library;
-  collect_interval_ = TimeDelta::FromSeconds(kCollectionIntervalSecs);
-}
-
-void CpuUsageCollector::Init() {
-  num_cpu_ = base::SysInfo::NumberOfProcessors();
-
-  // Get ticks per second (HZ) on this system.
-  // Sysconf cannot fail, so no sanity checks are needed.
-  ticks_per_second_ = sysconf(_SC_CLK_TCK);
-  CHECK_GT(ticks_per_second_, uint64_t(0))
-      << "Number of ticks per seconds should be positive.";
-
-  latest_cpu_use_ = GetCumulativeCpuUse();
-}
-
-void CpuUsageCollector::CollectCallback() {
-  Collect();
-  Schedule();
-}
-
-void CpuUsageCollector::Schedule() {
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&CpuUsageCollector::CollectCallback, base::Unretained(this)),
-      collect_interval_);
-}
-
-void CpuUsageCollector::Collect() {
-  TimeDelta cpu_use = GetCumulativeCpuUse();
-  TimeDelta diff_per_cpu = (cpu_use - latest_cpu_use_) / num_cpu_;
-  latest_cpu_use_ = cpu_use;
-
-  // Report the cpu usage as a percentage of the total cpu usage possible.
-  int percent_use = diff_per_cpu.InMilliseconds() * 100 /
-      (kCollectionIntervalSecs * 1000);
-
-  metrics_lib_->SendEnumToUMA(kCpuUsagePercent, percent_use, 101);
-}
-
-TimeDelta CpuUsageCollector::GetCumulativeCpuUse() {
-  base::FilePath proc_stat_path(kMetricsProcStatFileName);
-  std::string proc_stat_string;
-  if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
-    LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
-    return TimeDelta();
-  }
-
-  uint64_t user_ticks, user_nice_ticks, system_ticks;
-  if (!ParseProcStat(proc_stat_string, &user_ticks, &user_nice_ticks,
-                     &system_ticks)) {
-    return TimeDelta();
-  }
-
-  uint64_t total = user_ticks + user_nice_ticks + system_ticks;
-  return TimeDelta::FromMicroseconds(
-      total * 1000 * 1000 / ticks_per_second_);
-}
-
-bool CpuUsageCollector::ParseProcStat(const std::string& stat_content,
-                                      uint64_t *user_ticks,
-                                      uint64_t *user_nice_ticks,
-                                      uint64_t *system_ticks) {
-  std::vector<std::string> proc_stat_lines = base::SplitString(
-      stat_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-  if (proc_stat_lines.empty()) {
-    LOG(WARNING) << "No lines found in " << kMetricsProcStatFileName;
-    return false;
-  }
-  std::vector<std::string> proc_stat_totals =
-      base::SplitString(proc_stat_lines[0], base::kWhitespaceASCII,
-                        base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
-
-  if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
-      proc_stat_totals[0] != "cpu" ||
-      !base::StringToUint64(proc_stat_totals[1], user_ticks) ||
-      !base::StringToUint64(proc_stat_totals[2], user_nice_ticks) ||
-      !base::StringToUint64(proc_stat_totals[3], system_ticks)) {
-    LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
-    return false;
-  }
-  return true;
-}
diff --git a/metricsd/collectors/cpu_usage_collector.h b/metricsd/collectors/cpu_usage_collector.h
deleted file mode 100644
index f81dfcb..0000000
--- a/metricsd/collectors/cpu_usage_collector.h
+++ /dev/null
@@ -1,59 +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.
- */
-
-#ifndef METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
-#define METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
-
-#include <base/time/time.h>
-
-#include "metrics/metrics_library.h"
-
-class CpuUsageCollector {
- public:
-  CpuUsageCollector(MetricsLibraryInterface* metrics_library);
-
-  // Initialize this collector's state.
-  void Init();
-
-  // Schedule a collection interval.
-  void Schedule();
-
-  // Callback called at the end of the collection interval.
-  void CollectCallback();
-
-  // Measure the cpu use and report it.
-  void Collect();
-
-  // Gets the current cumulated Cpu usage.
-  base::TimeDelta GetCumulativeCpuUse();
-
- private:
-  FRIEND_TEST(CpuUsageTest, ParseProcStat);
-  bool ParseProcStat(const std::string& stat_content,
-                     uint64_t *user_ticks,
-                     uint64_t *user_nice_ticks,
-                     uint64_t *system_ticks);
-
-  int num_cpu_;
-  uint32_t ticks_per_second_;
-
-  base::TimeDelta collect_interval_;
-  base::TimeDelta latest_cpu_use_;
-
-  MetricsLibraryInterface* metrics_lib_;
-};
-
-#endif  // METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
diff --git a/metricsd/collectors/cpu_usage_collector_test.cc b/metricsd/collectors/cpu_usage_collector_test.cc
deleted file mode 100644
index ee5c92b..0000000
--- a/metricsd/collectors/cpu_usage_collector_test.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <gtest/gtest.h>
-
-#include "collectors/cpu_usage_collector.h"
-#include "metrics/metrics_library_mock.h"
-
-
-TEST(CpuUsageTest, ParseProcStat) {
-  MetricsLibraryMock metrics_lib_mock;
-  CpuUsageCollector collector(&metrics_lib_mock);
-  std::vector<std::string> invalid_contents = {
-    "",
-    // First line does not start with cpu.
-    "spu  17191 11 36579 151118 289 0 2 0 0 0\n"
-    "cpu0 1564 2 866 48650 68 0 2 0 0 0\n"
-    "cpu1 14299 0 35116 1844 81 0 0 0 0 0\n",
-    // One of the field is not a number.
-    "cpu  a17191 11 36579 151118 289 0 2 0 0 0",
-    // To many numbers in the first line.
-    "cpu  17191 11 36579 151118 289 0 2 0 0 0 102"
-  };
-
-  uint64_t user, nice, system;
-  for (int i = 0; i < invalid_contents.size(); i++) {
-    ASSERT_FALSE(collector.ParseProcStat(invalid_contents[i], &user, &nice,
-                                         &system));
-  }
-
-  ASSERT_TRUE(collector.ParseProcStat(
-      std::string("cpu  17191 11 36579 151118 289 0 2 0 0 0"),
-      &user, &nice, &system));
-  ASSERT_EQ(17191, user);
-  ASSERT_EQ(11, nice);
-  ASSERT_EQ(36579, system);
-}
diff --git a/metricsd/collectors/disk_usage_collector.cc b/metricsd/collectors/disk_usage_collector.cc
deleted file mode 100644
index 5ab51fb..0000000
--- a/metricsd/collectors/disk_usage_collector.cc
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "collectors/disk_usage_collector.h"
-
-#include <base/bind.h>
-#include <base/bind_helpers.h>
-#include <base/message_loop/message_loop.h>
-#include <sys/statvfs.h>
-
-#include "metrics/metrics_library.h"
-
-namespace {
-
-const char kDiskUsageMB[] = "Platform.DataPartitionUsed.MB";
-const char kDiskUsagePercent[] = "Platform.DataPartitionUsed.Percent";
-const char kDataPartitionPath[] = "/data";
-
-// Collect every 15 minutes.
-const int kDiskUsageCollectorIntervalSeconds = 900;
-
-}  // namespace
-
-DiskUsageCollector::DiskUsageCollector(
-    MetricsLibraryInterface* metrics_library) {
-  collect_interval_ = base::TimeDelta::FromSeconds(
-      kDiskUsageCollectorIntervalSeconds);
-  CHECK(metrics_library);
-  metrics_lib_ = metrics_library;
-}
-
-void DiskUsageCollector::Collect() {
-  struct statvfs buf;
-  int result = statvfs(kDataPartitionPath, &buf);
-  if (result != 0) {
-    PLOG(ERROR) << "Failed to check the available space in "
-                << kDataPartitionPath;
-    return;
-  }
-
-  unsigned long total_space = buf.f_blocks * buf.f_bsize;
-  unsigned long used_space = (buf.f_blocks - buf.f_bfree) * buf.f_bsize;
-  int percent_used = (used_space * 100) / total_space;
-
-  metrics_lib_->SendToUMA(kDiskUsageMB,
-                          used_space / (1024 * 1024),
-                          0,
-                          1024, // up to 1 GB.
-                          100);
-  metrics_lib_->SendEnumToUMA(kDiskUsagePercent, percent_used, 101);
-}
-
-void DiskUsageCollector::CollectCallback() {
-  Collect();
-  Schedule();
-}
-
-void DiskUsageCollector::Schedule() {
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&DiskUsageCollector::CollectCallback, base::Unretained(this)),
-      collect_interval_);
-}
diff --git a/metricsd/collectors/disk_usage_collector.h b/metricsd/collectors/disk_usage_collector.h
deleted file mode 100644
index c1d4546..0000000
--- a/metricsd/collectors/disk_usage_collector.h
+++ /dev/null
@@ -1,42 +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.
- */
-
-#ifndef METRICSD_COLLECTORS_DISK_USAGE_COLLECTOR_H_
-#define METRICSD_COLLECTORS_DISK_USAGE_COLLECTOR_H_
-
-#include <base/time/time.h>
-
-#include "metrics/metrics_library.h"
-
-class DiskUsageCollector {
- public:
-  DiskUsageCollector(MetricsLibraryInterface* metrics_library);
-
-  // Schedule the next collection.
-  void Schedule();
-
-  // Callback used by the main loop.
-  void CollectCallback();
-
-  // Collect the disk usage statistics and report them.
-  void Collect();
-
- private:
-  base::TimeDelta collect_interval_;
-  MetricsLibraryInterface* metrics_lib_;
-};
-
-#endif  // METRICSD_COLLECTORS_DISK_USAGE_COLLECTOR_H_
diff --git a/metricsd/constants.h b/metricsd/constants.h
deleted file mode 100644
index b702737..0000000
--- a/metricsd/constants.h
+++ /dev/null
@@ -1,42 +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.
-//
-
-#ifndef METRICS_CONSTANTS_H_
-#define METRICS_CONSTANTS_H_
-
-namespace metrics {
-static const char kSharedMetricsDirectory[] = "/data/misc/metrics/";
-static const char kMetricsdDirectory[] = "/data/misc/metricsd/";
-static const char kMetricsCollectorDirectory[] =
-    "/data/misc/metrics_collector/";
-static const char kMetricsGUIDFileName[] = "Sysinfo.GUID";
-static const char kMetricsServer[] = "https://clients4.google.com/uma/v2";
-static const char kConsentFileName[] = "enabled";
-static const char kStagedLogName[] = "staged_log";
-static const char kSavedLogName[] = "saved_log";
-static const char kFailedUploadCountName[] = "failed_upload_count";
-static const char kDefaultVersion[] = "0.0.0.0";
-
-// Build time properties name.
-static const char kProductId[] = "product_id";
-static const char kProductVersion[] = "product_version";
-
-// Weave configuration.
-static const char kWeaveConfigurationFile[] = "/system/etc/weaved/weaved.conf";
-static const char kModelManifestId[] = "model_id";
-}  // namespace metrics
-
-#endif  // METRICS_CONSTANTS_H_
diff --git a/metricsd/etc/weaved/traits/metrics.json b/metricsd/etc/weaved/traits/metrics.json
deleted file mode 100644
index 7583270..0000000
--- a/metricsd/etc/weaved/traits/metrics.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
-  "_metrics": {
-    "commands": {
-      "enableAnalyticsReporting": {
-        "minimalRole": "manager",
-        "parameters": {}
-      },
-      "disableAnalyticsReporting": {
-        "minimalRole": "manager",
-        "parameters": {}
-      }
-    },
-    "state": {
-      "analyticsReportingState": {
-        "type": "string",
-        "enum": [ "enabled", "disabled" ]
-      }
-    }
-  }
-}
diff --git a/metricsd/include/metrics/c_metrics_library.h b/metricsd/include/metrics/c_metrics_library.h
deleted file mode 100644
index 1e597c2..0000000
--- a/metricsd/include/metrics/c_metrics_library.h
+++ /dev/null
@@ -1,57 +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.
- */
-
-#ifndef METRICS_C_METRICS_LIBRARY_H_
-#define METRICS_C_METRICS_LIBRARY_H_
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-typedef struct CMetricsLibraryOpaque* CMetricsLibrary;
-
-// C wrapper for MetricsLibrary::MetricsLibrary.
-CMetricsLibrary CMetricsLibraryNew(void);
-
-// C wrapper for MetricsLibrary::~MetricsLibrary.
-void CMetricsLibraryDelete(CMetricsLibrary handle);
-
-// C wrapper for MetricsLibrary::Init.
-void CMetricsLibraryInit(CMetricsLibrary handle);
-
-// C wrapper for MetricsLibrary::SendToUMA.
-int CMetricsLibrarySendToUMA(CMetricsLibrary handle,
-                             const char* name, int sample,
-                             int min, int max, int nbuckets);
-
-// C wrapper for MetricsLibrary::SendEnumToUMA.
-int CMetricsLibrarySendEnumToUMA(CMetricsLibrary handle,
-                                 const char* name, int sample, int max);
-
-// C wrapper for MetricsLibrary::SendSparseToUMA.
-int CMetricsLibrarySendSparseToUMA(CMetricsLibrary handle,
-                                   const char* name, int sample);
-
-// C wrapper for MetricsLibrary::SendCrashToUMA.
-int CMetricsLibrarySendCrashToUMA(CMetricsLibrary handle,
-                                  const char* crash_kind);
-
-// C wrapper for MetricsLibrary::AreMetricsEnabled.
-int CMetricsLibraryAreMetricsEnabled(CMetricsLibrary handle);
-
-#if defined(__cplusplus)
-}
-#endif
-#endif  // METRICS_C_METRICS_LIBRARY_H_
diff --git a/metricsd/include/metrics/metrics_collector_service_client.h b/metricsd/include/metrics/metrics_collector_service_client.h
deleted file mode 100644
index c800eae..0000000
--- a/metricsd/include/metrics/metrics_collector_service_client.h
+++ /dev/null
@@ -1,44 +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.
- */
-
-// Client interface to IMetricsCollectorService.
-
-#ifndef METRICS_METRICS_COLLECTOR_SERVICE_CLIENT_H_
-#define METRICS_METRICS_COLLECTOR_SERVICE_CLIENT_H_
-
-#include "android/brillo/metrics/IMetricsCollectorService.h"
-
-class MetricsCollectorServiceClient {
- public:
-  MetricsCollectorServiceClient() = default;
-  ~MetricsCollectorServiceClient() = default;
-
-  // Initialize.  Returns true if OK, or false if IMetricsCollectorService
-  // is not registered.
-  bool Init();
-
-  // Called by crash_reporter to report a userspace crash event.  Returns
-  // true if successfully called the IMetricsCollectorService method of the
-  // same name, or false if the service was not registered at Init() time.
-  bool notifyUserCrash();
-
- private:
-  // IMetricsCollectorService binder proxy
-  android::sp<android::brillo::metrics::IMetricsCollectorService>
-      metrics_collector_service_;
-};
-
-#endif  // METRICS_METRICS_COLLECTOR_SERVICE_CLIENT_H_
diff --git a/metricsd/include/metrics/metrics_library.h b/metricsd/include/metrics/metrics_library.h
deleted file mode 100644
index a1bb926..0000000
--- a/metricsd/include/metrics/metrics_library.h
+++ /dev/null
@@ -1,175 +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.
- */
-
-#ifndef METRICS_METRICS_LIBRARY_H_
-#define METRICS_METRICS_LIBRARY_H_
-
-#include <sys/types.h>
-#include <string>
-#include <unistd.h>
-
-#include <base/compiler_specific.h>
-#include <base/files/file_path.h>
-#include <base/macros.h>
-#include <binder/IServiceManager.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-namespace android {
-namespace brillo {
-namespace metrics {
-class IMetricsd;
-}  // namespace metrics
-}  // namespace brillo
-}  // namespace android
-
-class MetricsLibraryInterface {
- public:
-  virtual void Init() = 0;
-  virtual bool AreMetricsEnabled() = 0;
-  virtual bool SendToUMA(const std::string& name, int sample,
-                         int min, int max, int nbuckets) = 0;
-  virtual bool SendEnumToUMA(const std::string& name, int sample, int max) = 0;
-  virtual bool SendBoolToUMA(const std::string& name, bool sample) = 0;
-  virtual bool SendSparseToUMA(const std::string& name, int sample) = 0;
-  virtual ~MetricsLibraryInterface() {}
-};
-
-// Library used to send metrics to Chrome/UMA.
-class MetricsLibrary : public MetricsLibraryInterface {
- public:
-  MetricsLibrary();
-  virtual ~MetricsLibrary();
-
-  // Initializes the library.
-  void Init() override;
-
-  // Initializes the library and disables the cache of whether or not the
-  // metrics collection is enabled.
-  // By disabling this, we may have to check for the metrics status more often
-  // but the result will never be stale.
-  void InitWithNoCaching();
-
-  // Returns whether or not the machine is running in guest mode.
-  bool IsGuestMode();
-
-  // Returns whether or not metrics collection is enabled.
-  bool AreMetricsEnabled() override;
-
-  // Sends histogram data to Chrome for transport to UMA and returns
-  // true on success. This method results in the equivalent of an
-  // asynchronous non-blocking RPC to UMA_HISTOGRAM_CUSTOM_COUNTS
-  // inside Chrome (see base/histogram.h).
-  //
-  // |sample| is the sample value to be recorded (|min| <= |sample| < |max|).
-  // |min| is the minimum value of the histogram samples (|min| > 0).
-  // |max| is the maximum value of the histogram samples.
-  // |nbuckets| is the number of histogram buckets.
-  // [0,min) is the implicit underflow bucket.
-  // [|max|,infinity) is the implicit overflow bucket.
-  //
-  // Note that the memory allocated in Chrome for each histogram is
-  // proportional to the number of buckets. Therefore, it is strongly
-  // recommended to keep this number low (e.g., 50 is normal, while
-  // 100 is high).
-  bool SendToUMA(const std::string& name, int sample,
-                 int min, int max, int nbuckets) override;
-
-  // Sends linear histogram data to Chrome for transport to UMA and
-  // returns true on success. This method results in the equivalent of
-  // an asynchronous non-blocking RPC to UMA_HISTOGRAM_ENUMERATION
-  // inside Chrome (see base/histogram.h).
-  //
-  // |sample| is the sample value to be recorded (1 <= |sample| < |max|).
-  // |max| is the maximum value of the histogram samples.
-  // 0 is the implicit underflow bucket.
-  // [|max|,infinity) is the implicit overflow bucket.
-  //
-  // An enumeration histogram requires |max| + 1 number of
-  // buckets. Note that the memory allocated in Chrome for each
-  // histogram is proportional to the number of buckets. Therefore, it
-  // is strongly recommended to keep this number low (e.g., 50 is
-  // normal, while 100 is high).
-  bool SendEnumToUMA(const std::string& name, int sample, int max) override;
-
-  // Specialization of SendEnumToUMA for boolean values.
-  bool SendBoolToUMA(const std::string& name, bool sample) override;
-
-  // Sends sparse histogram sample to Chrome for transport to UMA.  Returns
-  // true on success.
-  //
-  // |sample| is the 32-bit integer value to be recorded.
-  bool SendSparseToUMA(const std::string& name, int sample) override;
-
-  // Sends a signal to UMA that a crash of the given |crash_kind|
-  // has occurred.  Used by UMA to generate stability statistics.
-  bool SendCrashToUMA(const char *crash_kind);
-
-  // Sends a "generic Chrome OS event" to UMA.  This is an event name
-  // that is translated into an enumerated histogram entry.  Event names
-  // are added to metrics_library.cc.  Optionally, they can be added
-  // to histograms.xml---but part of the reason for this is to simplify
-  // the addition of events (at the cost of having to look them up by
-  // number in the histograms dashboard).
-  bool SendCrosEventToUMA(const std::string& event);
-
-  // Debugging only.
-  // Dumps the histograms aggregated since metricsd started into |dump|.
-  // Returns true iff the dump succeeds.
-  bool GetHistogramsDump(std::string* dump);
-
- private:
-  friend class CMetricsLibraryTest;
-  friend class MetricsLibraryTest;
-  friend class UploadServiceTest;
-  FRIEND_TEST(MetricsLibraryTest, AreMetricsEnabled);
-  FRIEND_TEST(MetricsLibraryTest, AreMetricsEnabledNoCaching);
-  FRIEND_TEST(MetricsLibraryTest, FormatChromeMessage);
-  FRIEND_TEST(MetricsLibraryTest, FormatChromeMessageTooLong);
-  FRIEND_TEST(MetricsLibraryTest, IsDeviceMounted);
-  FRIEND_TEST(MetricsLibraryTest, SendMessageToChrome);
-  FRIEND_TEST(MetricsLibraryTest, SendMessageToChromeUMAEventsBadFileLocation);
-
-  void InitForTest(const base::FilePath& metrics_directory);
-
-  // Sets |*result| to whether or not the |mounts_file| indicates that
-  // the |device_name| is currently mounted.  Uses |buffer| of
-  // |buffer_size| to read the file.  Returns false if any error.
-  bool IsDeviceMounted(const char* device_name,
-                       const char* mounts_file,
-                       char* buffer, int buffer_size,
-                       bool* result);
-
-  // Connects to IMetricsd if the proxy does not exist or is not alive.
-  // Don't block if we fail to get the proxy for any reason.
-  bool CheckService();
-
-  // Time at which we last checked if metrics were enabled.
-  time_t cached_enabled_time_;
-
-  // Cached state of whether or not metrics were enabled.
-  bool cached_enabled_;
-
-  // True iff we should cache the enabled/disabled status.
-  bool use_caching_;
-
-  android::sp<android::IServiceManager> manager_;
-  android::sp<android::brillo::metrics::IMetricsd> metricsd_proxy_;
-  base::FilePath consent_file_;
-
-  DISALLOW_COPY_AND_ASSIGN(MetricsLibrary);
-};
-
-#endif  // METRICS_METRICS_LIBRARY_H_
diff --git a/metricsd/include/metrics/metrics_library_mock.h b/metricsd/include/metrics/metrics_library_mock.h
deleted file mode 100644
index 3b0b24d..0000000
--- a/metricsd/include/metrics/metrics_library_mock.h
+++ /dev/null
@@ -1,41 +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.
- */
-
-#ifndef METRICS_METRICS_LIBRARY_MOCK_H_
-#define METRICS_METRICS_LIBRARY_MOCK_H_
-
-#include <string>
-
-#include "metrics/metrics_library.h"
-
-#include <gmock/gmock.h>
-
-class MetricsLibraryMock : public MetricsLibraryInterface {
- public:
-  bool metrics_enabled_ = true;
-
-  MOCK_METHOD0(Init, void());
-  MOCK_METHOD5(SendToUMA, bool(const std::string& name, int sample,
-                               int min, int max, int nbuckets));
-  MOCK_METHOD3(SendEnumToUMA, bool(const std::string& name, int sample,
-                                   int max));
-  MOCK_METHOD2(SendBoolToUMA, bool(const std::string& name, bool sample));
-  MOCK_METHOD2(SendSparseToUMA, bool(const std::string& name, int sample));
-
-  bool AreMetricsEnabled() override {return metrics_enabled_;};
-};
-
-#endif  // METRICS_METRICS_LIBRARY_MOCK_H_
diff --git a/metricsd/include/metrics/timer.h b/metricsd/include/metrics/timer.h
deleted file mode 100644
index c1b8ede..0000000
--- a/metricsd/include/metrics/timer.h
+++ /dev/null
@@ -1,170 +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.
- */
-
-// Timer - class that provides timer tracking.
-
-#ifndef METRICS_TIMER_H_
-#define METRICS_TIMER_H_
-
-#include <memory>
-#include <string>
-
-#include <base/macros.h>
-#include <base/time/time.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-class MetricsLibraryInterface;
-
-namespace chromeos_metrics {
-
-class TimerInterface {
- public:
-  virtual ~TimerInterface() {}
-
-  virtual bool Start() = 0;
-  virtual bool Stop() = 0;
-  virtual bool Reset() = 0;
-  virtual bool HasStarted() const = 0;
-};
-
-// Wrapper for calls to the system clock.
-class ClockWrapper {
- public:
-  ClockWrapper() {}
-  virtual ~ClockWrapper() {}
-
-  // Returns the current time from the system.
-  virtual base::TimeTicks GetCurrentTime() const;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ClockWrapper);
-};
-
-// Implements a Timer.
-class Timer : public TimerInterface {
- public:
-  Timer();
-  virtual ~Timer() {}
-
-  // Starts the timer. If a timer is already running, also resets current
-  // timer. Always returns true.
-  virtual bool Start();
-
-  // Stops the timer and calculates the total time elapsed between now and when
-  // Start() was called. Note that this method needs a prior call to Start().
-  // Otherwise, it fails (returns false).
-  virtual bool Stop();
-
-  // Pauses a timer.  If the timer is stopped, this call starts the timer in
-  // the paused state. Fails (returns false) if the timer is already paused.
-  virtual bool Pause();
-
-  // Restarts a paused timer (or starts a stopped timer). This method fails
-  // (returns false) if the timer is already running; otherwise, returns true.
-  virtual bool Resume();
-
-  // Resets the timer, erasing the current duration being tracked. Always
-  // returns true.
-  virtual bool Reset();
-
-  // Returns whether the timer has started or not.
-  virtual bool HasStarted() const;
-
-  // Stores the current elapsed time in |elapsed_time|. If timer is stopped,
-  // stores the elapsed time from when Stop() was last called. Otherwise,
-  // calculates and stores the elapsed time since the last Start().
-  // Returns false if the timer was never Start()'ed or if called with a null
-  // pointer argument.
-  virtual bool GetElapsedTime(base::TimeDelta* elapsed_time) const;
-
- private:
-  enum TimerState { kTimerStopped, kTimerRunning, kTimerPaused };
-  friend class TimerTest;
-  friend class TimerReporterTest;
-  FRIEND_TEST(TimerReporterTest, StartStopReport);
-  FRIEND_TEST(TimerTest, InvalidElapsedTime);
-  FRIEND_TEST(TimerTest, InvalidStop);
-  FRIEND_TEST(TimerTest, PauseResumeStop);
-  FRIEND_TEST(TimerTest, PauseStartStopResume);
-  FRIEND_TEST(TimerTest, PauseStop);
-  FRIEND_TEST(TimerTest, Reset);
-  FRIEND_TEST(TimerTest, ReStart);
-  FRIEND_TEST(TimerTest, ResumeStartStopPause);
-  FRIEND_TEST(TimerTest, SeparatedTimers);
-  FRIEND_TEST(TimerTest, StartPauseResumePauseResumeStop);
-  FRIEND_TEST(TimerTest, StartPauseResumePauseStop);
-  FRIEND_TEST(TimerTest, StartPauseResumeStop);
-  FRIEND_TEST(TimerTest, StartPauseStop);
-  FRIEND_TEST(TimerTest, StartResumeStop);
-  FRIEND_TEST(TimerTest, StartStop);
-
-  // Elapsed time of the last use of the timer.
-  base::TimeDelta elapsed_time_;
-
-  // Starting time value.
-  base::TimeTicks start_time_;
-
-  // Whether the timer is running, stopped, or paused.
-  TimerState timer_state_;
-
-  // Wrapper for the calls to the system clock.
-  std::unique_ptr<ClockWrapper> clock_wrapper_;
-
-  DISALLOW_COPY_AND_ASSIGN(Timer);
-};
-
-// Extends the Timer class to report the elapsed time in milliseconds through
-// the UMA metrics library.
-class TimerReporter : public Timer {
- public:
-  // Initializes the timer by providing a |histogram_name| to report to with
-  // |min|, |max| and |num_buckets| attributes for the histogram.
-  TimerReporter(const std::string& histogram_name, int min, int max,
-                int num_buckets);
-  virtual ~TimerReporter() {}
-
-  // Sets the metrics library used by all instances of this class.
-  static void set_metrics_lib(MetricsLibraryInterface* metrics_lib) {
-    metrics_lib_ = metrics_lib;
-  }
-
-  // Reports the current duration to UMA, in milliseconds. Returns false if
-  // there is nothing to report, e.g. a metrics library is not set.
-  virtual bool ReportMilliseconds() const;
-
-  // Accessor methods.
-  const std::string& histogram_name() const { return histogram_name_; }
-  int min() const { return min_; }
-  int max() const { return max_; }
-  int num_buckets() const { return num_buckets_; }
-
- private:
-  friend class TimerReporterTest;
-  FRIEND_TEST(TimerReporterTest, StartStopReport);
-  FRIEND_TEST(TimerReporterTest, InvalidReport);
-
-  static MetricsLibraryInterface* metrics_lib_;
-  std::string histogram_name_;
-  int min_;
-  int max_;
-  int num_buckets_;
-
-  DISALLOW_COPY_AND_ASSIGN(TimerReporter);
-};
-
-}  // namespace chromeos_metrics
-
-#endif  // METRICS_TIMER_H_
diff --git a/metricsd/include/metrics/timer_mock.h b/metricsd/include/metrics/timer_mock.h
deleted file mode 100644
index 200ee9a..0000000
--- a/metricsd/include/metrics/timer_mock.h
+++ /dev/null
@@ -1,59 +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.
- */
-
-#ifndef METRICS_TIMER_MOCK_H_
-#define METRICS_TIMER_MOCK_H_
-
-#include <string>
-
-#include <gmock/gmock.h>
-
-#include "metrics/timer.h"
-
-namespace chromeos_metrics {
-
-class TimerMock : public Timer {
- public:
-  MOCK_METHOD0(Start, bool());
-  MOCK_METHOD0(Stop, bool());
-  MOCK_METHOD0(Reset, bool());
-  MOCK_CONST_METHOD0(HasStarted, bool());
-  MOCK_CONST_METHOD1(GetElapsedTime, bool(base::TimeDelta* elapsed_time));
-};
-
-class TimerReporterMock : public TimerReporter {
- public:
-  TimerReporterMock() : TimerReporter("", 0, 0, 0) {}
-  MOCK_METHOD0(Start, bool());
-  MOCK_METHOD0(Stop, bool());
-  MOCK_METHOD0(Reset, bool());
-  MOCK_CONST_METHOD0(HasStarted, bool());
-  MOCK_CONST_METHOD1(GetElapsedTime, bool(base::TimeDelta* elapsed_time));
-  MOCK_CONST_METHOD0(ReportMilliseconds, bool());
-  MOCK_CONST_METHOD0(histogram_name, std::string&());
-  MOCK_CONST_METHOD0(min, int());
-  MOCK_CONST_METHOD0(max, int());
-  MOCK_CONST_METHOD0(num_buckets, int());
-};
-
-class ClockWrapperMock : public ClockWrapper {
- public:
-  MOCK_CONST_METHOD0(GetCurrentTime, base::TimeTicks());
-};
-
-}  // namespace chromeos_metrics
-
-#endif  // METRICS_TIMER_MOCK_H_
diff --git a/metricsd/libmetrics-369476.gyp b/metricsd/libmetrics-369476.gyp
deleted file mode 100644
index b545d35..0000000
--- a/metricsd/libmetrics-369476.gyp
+++ /dev/null
@@ -1,8 +0,0 @@
-{
-  'variables': {
-    'libbase_ver': 369476,
-  },
-  'includes': [
-    'libmetrics.gypi',
-  ],
-}
diff --git a/metricsd/libmetrics.gypi b/metricsd/libmetrics.gypi
deleted file mode 100644
index 3c8fc7c..0000000
--- a/metricsd/libmetrics.gypi
+++ /dev/null
@@ -1,33 +0,0 @@
-{
-  'target_defaults': {
-    'variables': {
-      'deps': [
-        'libbrillo-<(libbase_ver)',
-        'libchrome-<(libbase_ver)',
-      ]
-    },
-    'cflags_cc': [
-      '-fno-exceptions',
-    ],
-  },
-  'targets': [
-    {
-      'target_name': 'libmetrics-<(libbase_ver)',
-      'type': 'shared_library',
-      'cflags': [
-        '-fvisibility=default',
-      ],
-      'libraries+': [
-        '-lpolicy-<(libbase_ver)',
-      ],
-      'sources': [
-        'c_metrics_library.cc',
-        'metrics_library.cc',
-        'serialization/metric_sample.cc',
-        'serialization/serialization_utils.cc',
-        'timer.cc',
-      ],
-      'include_dirs': ['.'],
-    },
-  ],
-}
diff --git a/metricsd/libmetrics.pc.in b/metricsd/libmetrics.pc.in
deleted file mode 100644
index 233f318..0000000
--- a/metricsd/libmetrics.pc.in
+++ /dev/null
@@ -1,7 +0,0 @@
-bslot=@BSLOT@
-
-Name: libmetrics
-Description: Chrome OS metrics library
-Version: ${bslot}
-Requires.private: libchrome-${bslot}
-Libs: -lmetrics-${bslot}
diff --git a/metricsd/metrics.gyp b/metricsd/metrics.gyp
deleted file mode 100644
index c9c02d7..0000000
--- a/metricsd/metrics.gyp
+++ /dev/null
@@ -1,184 +0,0 @@
-{
-  'target_defaults': {
-    'variables': {
-      'deps': [
-        'dbus-1',
-        'libbrillo-<(libbase_ver)',
-        'libchrome-<(libbase_ver)',
-      ]
-    },
-    'cflags_cc': [
-      '-fno-exceptions',
-    ],
-  },
-  'targets': [
-    {
-      'target_name': 'libmetrics_daemon',
-      'type': 'static_library',
-      'dependencies': [
-        '../metrics/libmetrics-<(libbase_ver).gyp:libmetrics-<(libbase_ver)',
-        'libupload_service',
-        'metrics_proto',
-      ],
-      'link_settings': {
-        'libraries': [
-          '-lrootdev',
-        ],
-      },
-      'sources': [
-        'persistent_integer.cc',
-        'metrics_daemon.cc',
-        'metrics_daemon_main.cc',
-      ],
-      'include_dirs': ['.'],
-    },
-    {
-      'target_name': 'metrics_client',
-      'type': 'executable',
-      'dependencies': [
-        '../metrics/libmetrics-<(libbase_ver).gyp:libmetrics-<(libbase_ver)',
-      ],
-      'sources': [
-        'metrics_client.cc',
-      ]
-    },
-    {
-      'target_name': 'libupload_service',
-      'type': 'static_library',
-      'dependencies': [
-        'metrics_proto',
-        '../metrics/libmetrics-<(libbase_ver).gyp:libmetrics-<(libbase_ver)',
-      ],
-      'link_settings': {
-        'libraries': [
-          '-lvboot_host',
-        ],
-      },
-      'variables': {
-        'exported_deps': [
-          'protobuf-lite',
-        ],
-        'deps': [
-          '<@(exported_deps)',
-        ],
-      },
-      'all_dependent_settings': {
-        'variables': {
-          'deps+': [
-            '<@(exported_deps)',
-          ],
-        },
-      },
-      'sources': [
-        'uploader/upload_service.cc',
-        'uploader/metrics_hashes.cc',
-        'uploader/metrics_log.cc',
-        'uploader/metrics_log_base.cc',
-        'uploader/system_profile_cache.cc',
-        'uploader/sender_http.cc',
-      ],
-      'include_dirs': ['.']
-    },
-    {
-      'target_name': 'metrics_proto',
-      'type': 'static_library',
-      'variables': {
-        'proto_in_dir': 'uploader/proto',
-        'proto_out_dir': 'include/metrics/uploader/proto',
-      },
-      'sources': [
-        '<(proto_in_dir)/chrome_user_metrics_extension.proto',
-        '<(proto_in_dir)/histogram_event.proto',
-        '<(proto_in_dir)/system_profile.proto',
-        '<(proto_in_dir)/user_action_event.proto',
-      ],
-      'includes': [
-        '../common-mk/protoc.gypi'
-      ],
-    },
-  ],
-  'conditions': [
-    ['USE_passive_metrics == 1', {
-      'targets': [
-        {
-          'target_name': 'metrics_daemon',
-          'type': 'executable',
-          'dependencies': ['libmetrics_daemon'],
-        },
-      ],
-    }],
-    ['USE_test == 1', {
-      'targets': [
-        {
-          'target_name': 'persistent_integer_test',
-          'type': 'executable',
-          'includes': ['../common-mk/common_test.gypi'],
-          'sources': [
-            'persistent_integer.cc',
-            'persistent_integer_test.cc',
-          ]
-        },
-        {
-          'target_name': 'metrics_library_test',
-          'type': 'executable',
-          'dependencies': [
-            '../metrics/libmetrics-<(libbase_ver).gyp:libmetrics-<(libbase_ver)',
-          ],
-          'includes': ['../common-mk/common_test.gypi'],
-          'sources': [
-            'metrics_library_test.cc',
-            'serialization/serialization_utils_unittest.cc',
-          ],
-          'link_settings': {
-            'libraries': [
-              '-lpolicy-<(libbase_ver)',
-            ]
-          }
-        },
-        {
-          'target_name': 'timer_test',
-          'type': 'executable',
-          'includes': ['../common-mk/common_test.gypi'],
-          'sources': [
-            'timer.cc',
-            'timer_test.cc',
-          ]
-        },
-        {
-          'target_name': 'upload_service_test',
-          'type': 'executable',
-          'sources': [
-            'persistent_integer.cc',
-            'uploader/metrics_hashes_unittest.cc',
-            'uploader/metrics_log_base_unittest.cc',
-            'uploader/mock/sender_mock.cc',
-            'uploader/upload_service_test.cc',
-          ],
-          'dependencies': [
-            'libupload_service',
-          ],
-          'includes':[
-            '../common-mk/common_test.gypi',
-          ],
-          'include_dirs': ['.']
-        },
-      ],
-    }],
-    ['USE_passive_metrics == 1 and USE_test == 1', {
-      'targets': [
-        {
-          'target_name': 'metrics_daemon_test',
-          'type': 'executable',
-          'dependencies': [
-            'libmetrics_daemon',
-          ],
-          'includes': ['../common-mk/common_test.gypi'],
-          'sources': [
-            'metrics_daemon_test.cc',
-          ],
-          'include_dirs': ['.'],
-        },
-      ],
-    }],
-  ]
-}
diff --git a/metricsd/metrics_client.cc b/metricsd/metrics_client.cc
deleted file mode 100644
index c66b975..0000000
--- a/metricsd/metrics_client.cc
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <cstdio>
-#include <cstdlib>
-
-#include "constants.h"
-#include "metrics/metrics_library.h"
-
-enum Mode {
-    kModeDumpHistograms,
-    kModeSendSample,
-    kModeSendEnumSample,
-    kModeSendSparseSample,
-    kModeSendCrosEvent,
-    kModeHasConsent,
-    kModeIsGuestMode,
-};
-
-void ShowUsage() {
-  fprintf(stderr,
-          "Usage:  metrics_client [-t] name sample min max nbuckets\n"
-          "        metrics_client -e   name sample max\n"
-          "        metrics_client -s   name sample\n"
-          "        metrics_client -v   event\n"
-          "        metrics_client [-cdg]\n"
-          "\n"
-          "  default: send metric with integer values \n"
-          "           |min| > 0, |min| <= sample < |max|\n"
-          "  -c: return exit status 0 if user consents to stats, 1 otherwise,\n"
-          "      in guest mode always return 1\n"
-          "  -d: dump the histograms recorded by metricsd to stdout\n"
-          "  -e: send linear/enumeration histogram data\n"
-          "  -g: return exit status 0 if machine in guest mode, 1 otherwise\n"
-          "  -s: send a sparse histogram sample\n"
-          "  -t: convert sample from double seconds to int milliseconds\n"
-          "  -v: send a Platform.CrOSEvent enum histogram sample\n");
-  exit(1);
-}
-
-static int ParseInt(const char *arg) {
-  char *endptr;
-  int value = strtol(arg, &endptr, 0);
-  if (*endptr != '\0') {
-    fprintf(stderr, "metrics client: bad integer \"%s\"\n", arg);
-    ShowUsage();
-  }
-  return value;
-}
-
-static double ParseDouble(const char *arg) {
-  char *endptr;
-  double value = strtod(arg, &endptr);
-  if (*endptr != '\0') {
-    fprintf(stderr, "metrics client: bad double \"%s\"\n", arg);
-    ShowUsage();
-  }
-  return value;
-}
-
-static int DumpHistograms() {
-  MetricsLibrary metrics_lib;
-  metrics_lib.Init();
-
-  std::string dump;
-  if (!metrics_lib.GetHistogramsDump(&dump)) {
-    printf("Failed to dump the histograms.");
-    return 1;
-  }
-
-  printf("%s\n", dump.c_str());
-  return 0;
-}
-
-static int SendStats(char* argv[],
-                     int name_index,
-                     enum Mode mode,
-                     bool secs_to_msecs) {
-  const char* name = argv[name_index];
-  int sample;
-  if (secs_to_msecs) {
-    sample = static_cast<int>(ParseDouble(argv[name_index + 1]) * 1000.0);
-  } else {
-    sample = ParseInt(argv[name_index + 1]);
-  }
-
-  MetricsLibrary metrics_lib;
-  metrics_lib.Init();
-  if (mode == kModeSendSparseSample) {
-    metrics_lib.SendSparseToUMA(name, sample);
-  } else if (mode == kModeSendEnumSample) {
-    int max = ParseInt(argv[name_index + 2]);
-    metrics_lib.SendEnumToUMA(name, sample, max);
-  } else {
-    int min = ParseInt(argv[name_index + 2]);
-    int max = ParseInt(argv[name_index + 3]);
-    int nbuckets = ParseInt(argv[name_index + 4]);
-    metrics_lib.SendToUMA(name, sample, min, max, nbuckets);
-  }
-  return 0;
-}
-
-static int SendCrosEvent(char* argv[], int action_index) {
-  const char* event = argv[action_index];
-  bool result;
-  MetricsLibrary metrics_lib;
-  metrics_lib.Init();
-  result = metrics_lib.SendCrosEventToUMA(event);
-  if (!result) {
-    fprintf(stderr, "metrics_client: could not send event %s\n", event);
-    return 1;
-  }
-  return 0;
-}
-
-static int HasConsent() {
-  MetricsLibrary metrics_lib;
-  metrics_lib.Init();
-  return metrics_lib.AreMetricsEnabled() ? 0 : 1;
-}
-
-static int IsGuestMode() {
-  MetricsLibrary metrics_lib;
-  metrics_lib.Init();
-  return metrics_lib.IsGuestMode() ? 0 : 1;
-}
-
-int main(int argc, char** argv) {
-  enum Mode mode = kModeSendSample;
-  bool secs_to_msecs = false;
-
-  // Parse arguments
-  int flag;
-  while ((flag = getopt(argc, argv, "abcdegstv")) != -1) {
-    switch (flag) {
-      case 'c':
-        mode = kModeHasConsent;
-        break;
-      case 'd':
-        mode = kModeDumpHistograms;
-        break;
-      case 'e':
-        mode = kModeSendEnumSample;
-        break;
-      case 'g':
-        mode = kModeIsGuestMode;
-        break;
-      case 's':
-        mode = kModeSendSparseSample;
-        break;
-      case 't':
-        secs_to_msecs = true;
-        break;
-      case 'v':
-        mode = kModeSendCrosEvent;
-        break;
-      default:
-        ShowUsage();
-        break;
-    }
-  }
-  int arg_index = optind;
-
-  int expected_args = 0;
-  if (mode == kModeSendSample)
-    expected_args = 5;
-  else if (mode == kModeSendEnumSample)
-    expected_args = 3;
-  else if (mode == kModeSendSparseSample)
-    expected_args = 2;
-  else if (mode == kModeSendCrosEvent)
-    expected_args = 1;
-
-  if ((arg_index + expected_args) != argc) {
-    ShowUsage();
-  }
-
-  switch (mode) {
-    case kModeDumpHistograms:
-      return DumpHistograms();
-    case kModeSendSample:
-    case kModeSendEnumSample:
-    case kModeSendSparseSample:
-      if ((mode != kModeSendSample) && secs_to_msecs) {
-        ShowUsage();
-      }
-      return SendStats(argv,
-                       arg_index,
-                       mode,
-                       secs_to_msecs);
-    case kModeSendCrosEvent:
-      return SendCrosEvent(argv, arg_index);
-    case kModeHasConsent:
-      return HasConsent();
-    case kModeIsGuestMode:
-      return IsGuestMode();
-    default:
-      ShowUsage();
-      return 0;
-  }
-}
diff --git a/metricsd/metrics_collector.cc b/metricsd/metrics_collector.cc
deleted file mode 100644
index 45ae0a4..0000000
--- a/metricsd/metrics_collector.cc
+++ /dev/null
@@ -1,756 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "metrics_collector.h"
-
-#include <sysexits.h>
-#include <time.h>
-
-#include <memory>
-
-#include <base/bind.h>
-#include <base/files/file_path.h>
-#include <base/files/file_util.h>
-#include <base/hash.h>
-#include <base/logging.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_split.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <brillo/binder_watcher.h>
-#include <brillo/osrelease_reader.h>
-
-#include "constants.h"
-#include "metrics_collector_service_impl.h"
-
-using base::FilePath;
-using base::StringPrintf;
-using base::Time;
-using base::TimeDelta;
-using base::TimeTicks;
-using chromeos_metrics::PersistentInteger;
-using std::map;
-using std::string;
-using std::vector;
-
-namespace {
-
-const int kSecondsPerMinute = 60;
-const int kMinutesPerHour = 60;
-const int kHoursPerDay = 24;
-const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
-const int kSecondsPerDay = kSecondsPerMinute * kMinutesPerDay;
-const int kDaysPerWeek = 7;
-const int kSecondsPerWeek = kSecondsPerDay * kDaysPerWeek;
-
-// Interval between calls to UpdateStats().
-const uint32_t kUpdateStatsIntervalMs = 300000;
-
-const char kKernelCrashDetectedFile[] =
-    "/data/misc/crash_reporter/run/kernel-crash-detected";
-const char kUncleanShutdownDetectedFile[] =
-    "/var/run/unclean-shutdown-detected";
-
-const int kMetricMeminfoInterval = 30;    // seconds
-
-const char kMeminfoFileName[] = "/proc/meminfo";
-const char kVmStatFileName[] = "/proc/vmstat";
-
-const char kWeaveComponent[] = "metrics";
-const char kWeaveTrait[] = "_metrics";
-
-}  // namespace
-
-// Zram sysfs entries.
-
-const char MetricsCollector::kComprDataSizeName[] = "compr_data_size";
-const char MetricsCollector::kOrigDataSizeName[] = "orig_data_size";
-const char MetricsCollector::kZeroPagesName[] = "zero_pages";
-
-// Memory use stats collection intervals.  We collect some memory use interval
-// at these intervals after boot, and we stop collecting after the last one,
-// with the assumption that in most cases the memory use won't change much
-// after that.
-static const int kMemuseIntervals[] = {
-  1 * kSecondsPerMinute,    // 1 minute mark
-  4 * kSecondsPerMinute,    // 5 minute mark
-  25 * kSecondsPerMinute,   // 0.5 hour mark
-  120 * kSecondsPerMinute,  // 2.5 hour mark
-  600 * kSecondsPerMinute,  // 12.5 hour mark
-};
-
-MetricsCollector::MetricsCollector()
-    : memuse_final_time_(0),
-      memuse_interval_index_(0) {}
-
-MetricsCollector::~MetricsCollector() {
-}
-
-// static
-double MetricsCollector::GetActiveTime() {
-  struct timespec ts;
-  int r = clock_gettime(CLOCK_MONOTONIC, &ts);
-  if (r < 0) {
-    PLOG(WARNING) << "clock_gettime(CLOCK_MONOTONIC) failed";
-    return 0;
-  } else {
-    return ts.tv_sec + static_cast<double>(ts.tv_nsec) / (1000 * 1000 * 1000);
-  }
-}
-
-int MetricsCollector::Run() {
-  if (CheckSystemCrash(kKernelCrashDetectedFile)) {
-    ProcessKernelCrash();
-  }
-
-  if (CheckSystemCrash(kUncleanShutdownDetectedFile)) {
-    ProcessUncleanShutdown();
-  }
-
-  // On OS version change, clear version stats (which are reported daily).
-  int32_t version = GetOsVersionHash();
-  if (version_cycle_->Get() != version) {
-    version_cycle_->Set(version);
-    kernel_crashes_version_count_->Set(0);
-    version_cumulative_active_use_->Set(0);
-    version_cumulative_cpu_use_->Set(0);
-  }
-
-  // Start metricscollectorservice
-  android::sp<BnMetricsCollectorServiceImpl> metrics_collector_service =
-      new BnMetricsCollectorServiceImpl(this);
-  android::status_t status = android::defaultServiceManager()->addService(
-      metrics_collector_service->getInterfaceDescriptor(),
-      metrics_collector_service);
-  CHECK(status == android::OK)
-      << "failed to register service metricscollectorservice";
-
-  // Watch Binder events in the main loop
-  brillo::BinderWatcher binder_watcher;
-  CHECK(binder_watcher.Init()) << "Binder FD watcher init failed";
-  return brillo::Daemon::Run();
-}
-
-uint32_t MetricsCollector::GetOsVersionHash() {
-  brillo::OsReleaseReader reader;
-  reader.Load();
-  string version;
-  if (!reader.GetString(metrics::kProductVersion, &version)) {
-    LOG(ERROR) << "failed to read the product version.";
-    version = metrics::kDefaultVersion;
-  }
-
-  uint32_t version_hash = base::Hash(version);
-  if (testing_) {
-    version_hash = 42;  // return any plausible value for the hash
-  }
-  return version_hash;
-}
-
-void MetricsCollector::Init(bool testing, MetricsLibraryInterface* metrics_lib,
-                            const string& diskstats_path,
-                            const base::FilePath& private_metrics_directory,
-                            const base::FilePath& shared_metrics_directory) {
-  CHECK(metrics_lib);
-  testing_ = testing;
-  shared_metrics_directory_ = shared_metrics_directory;
-  metrics_lib_ = metrics_lib;
-
-  daily_active_use_.reset(new PersistentInteger("Platform.UseTime.PerDay",
-                                                private_metrics_directory));
-  version_cumulative_active_use_.reset(new PersistentInteger(
-      "Platform.CumulativeUseTime", private_metrics_directory));
-  version_cumulative_cpu_use_.reset(new PersistentInteger(
-      "Platform.CumulativeCpuTime", private_metrics_directory));
-
-  kernel_crash_interval_.reset(new PersistentInteger(
-      "Platform.KernelCrashInterval", private_metrics_directory));
-  unclean_shutdown_interval_.reset(new PersistentInteger(
-      "Platform.UncleanShutdownInterval", private_metrics_directory));
-  user_crash_interval_.reset(new PersistentInteger("Platform.UserCrashInterval",
-                                                   private_metrics_directory));
-
-  any_crashes_daily_count_.reset(new PersistentInteger(
-      "Platform.AnyCrashes.PerDay", private_metrics_directory));
-  any_crashes_weekly_count_.reset(new PersistentInteger(
-      "Platform.AnyCrashes.PerWeek", private_metrics_directory));
-  user_crashes_daily_count_.reset(new PersistentInteger(
-      "Platform.UserCrashes.PerDay", private_metrics_directory));
-  user_crashes_weekly_count_.reset(new PersistentInteger(
-      "Platform.UserCrashes.PerWeek", private_metrics_directory));
-  kernel_crashes_daily_count_.reset(new PersistentInteger(
-      "Platform.KernelCrashes.PerDay", private_metrics_directory));
-  kernel_crashes_weekly_count_.reset(new PersistentInteger(
-      "Platform.KernelCrashes.PerWeek", private_metrics_directory));
-  kernel_crashes_version_count_.reset(new PersistentInteger(
-      "Platform.KernelCrashesSinceUpdate", private_metrics_directory));
-  unclean_shutdowns_daily_count_.reset(new PersistentInteger(
-      "Platform.UncleanShutdown.PerDay", private_metrics_directory));
-  unclean_shutdowns_weekly_count_.reset(new PersistentInteger(
-      "Platform.UncleanShutdowns.PerWeek", private_metrics_directory));
-
-  daily_cycle_.reset(
-      new PersistentInteger("daily.cycle", private_metrics_directory));
-  weekly_cycle_.reset(
-      new PersistentInteger("weekly.cycle", private_metrics_directory));
-  version_cycle_.reset(
-      new PersistentInteger("version.cycle", private_metrics_directory));
-
-  disk_usage_collector_.reset(new DiskUsageCollector(metrics_lib_));
-  averaged_stats_collector_.reset(
-      new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
-                                      kVmStatFileName));
-  cpu_usage_collector_.reset(new CpuUsageCollector(metrics_lib_));
-}
-
-int MetricsCollector::OnInit() {
-  int return_code = brillo::Daemon::OnInit();
-  if (return_code != EX_OK)
-    return return_code;
-
-  StatsReporterInit();
-
-  // Start collecting meminfo stats.
-  ScheduleMeminfoCallback(kMetricMeminfoInterval);
-  memuse_final_time_ = GetActiveTime() + kMemuseIntervals[0];
-  ScheduleMemuseCallback(kMemuseIntervals[0]);
-
-  if (testing_)
-    return EX_OK;
-
-  weave_service_subscription_ = weaved::Service::Connect(
-      brillo::MessageLoop::current(),
-      base::Bind(&MetricsCollector::OnWeaveServiceConnected,
-                 weak_ptr_factory_.GetWeakPtr()));
-
-  latest_cpu_use_microseconds_ = cpu_usage_collector_->GetCumulativeCpuUse();
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&MetricsCollector::HandleUpdateStatsTimeout,
-                 weak_ptr_factory_.GetWeakPtr()),
-      base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
-
-  return EX_OK;
-}
-
-void MetricsCollector::OnWeaveServiceConnected(
-    const std::weak_ptr<weaved::Service>& service) {
-  service_ = service;
-  auto weave_service = service_.lock();
-  if (!weave_service)
-    return;
-
-  weave_service->AddComponent(kWeaveComponent, {kWeaveTrait}, nullptr);
-  weave_service->AddCommandHandler(
-      kWeaveComponent, kWeaveTrait, "enableAnalyticsReporting",
-      base::Bind(&MetricsCollector::OnEnableMetrics,
-                 weak_ptr_factory_.GetWeakPtr()));
-  weave_service->AddCommandHandler(
-      kWeaveComponent, kWeaveTrait, "disableAnalyticsReporting",
-      base::Bind(&MetricsCollector::OnDisableMetrics,
-                 weak_ptr_factory_.GetWeakPtr()));
-
-  UpdateWeaveState();
-}
-
-void MetricsCollector::OnEnableMetrics(
-    std::unique_ptr<weaved::Command> command) {
-  if (base::WriteFile(
-          shared_metrics_directory_.Append(metrics::kConsentFileName), "", 0) !=
-      0) {
-    PLOG(ERROR) << "Could not create the consent file.";
-    command->Abort("metrics_error", "Could not create the consent file",
-                   nullptr);
-    return;
-  }
-
-  UpdateWeaveState();
-  command->Complete({}, nullptr);
-}
-
-void MetricsCollector::OnDisableMetrics(
-    std::unique_ptr<weaved::Command> command) {
-  if (!base::DeleteFile(
-          shared_metrics_directory_.Append(metrics::kConsentFileName), false)) {
-    PLOG(ERROR) << "Could not delete the consent file.";
-    command->Abort("metrics_error", "Could not delete the consent file",
-                   nullptr);
-    return;
-  }
-
-  UpdateWeaveState();
-  command->Complete({}, nullptr);
-}
-
-void MetricsCollector::UpdateWeaveState() {
-  auto weave_service = service_.lock();
-  if (!weave_service)
-    return;
-
-  std::string enabled =
-      metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled";
-
-  if (!weave_service->SetStateProperty(kWeaveComponent, kWeaveTrait,
-                                       "analyticsReportingState",
-                                       *brillo::ToValue(enabled),
-                                       nullptr)) {
-    LOG(ERROR) << "failed to update weave's state";
-  }
-}
-
-void MetricsCollector::ProcessUserCrash() {
-  // Counts the active time up to now.
-  UpdateStats(TimeTicks::Now(), Time::Now());
-
-  // Reports the active use time since the last crash and resets it.
-  SendAndResetCrashIntervalSample(user_crash_interval_);
-
-  any_crashes_daily_count_->Add(1);
-  any_crashes_weekly_count_->Add(1);
-  user_crashes_daily_count_->Add(1);
-  user_crashes_weekly_count_->Add(1);
-}
-
-void MetricsCollector::ProcessKernelCrash() {
-  // Counts the active time up to now.
-  UpdateStats(TimeTicks::Now(), Time::Now());
-
-  // Reports the active use time since the last crash and resets it.
-  SendAndResetCrashIntervalSample(kernel_crash_interval_);
-
-  any_crashes_daily_count_->Add(1);
-  any_crashes_weekly_count_->Add(1);
-  kernel_crashes_daily_count_->Add(1);
-  kernel_crashes_weekly_count_->Add(1);
-
-  kernel_crashes_version_count_->Add(1);
-}
-
-void MetricsCollector::ProcessUncleanShutdown() {
-  // Counts the active time up to now.
-  UpdateStats(TimeTicks::Now(), Time::Now());
-
-  // Reports the active use time since the last crash and resets it.
-  SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
-
-  unclean_shutdowns_daily_count_->Add(1);
-  unclean_shutdowns_weekly_count_->Add(1);
-  any_crashes_daily_count_->Add(1);
-  any_crashes_weekly_count_->Add(1);
-}
-
-bool MetricsCollector::CheckSystemCrash(const string& crash_file) {
-  FilePath crash_detected(crash_file);
-  if (!base::PathExists(crash_detected))
-    return false;
-
-  // Deletes the crash-detected file so that the daemon doesn't report
-  // another kernel crash in case it's restarted.
-  base::DeleteFile(crash_detected, false);  // not recursive
-  return true;
-}
-
-void MetricsCollector::StatsReporterInit() {
-  disk_usage_collector_->Schedule();
-
-  cpu_usage_collector_->Init();
-  cpu_usage_collector_->Schedule();
-
-  // Don't start a collection cycle during the first run to avoid delaying the
-  // boot.
-  averaged_stats_collector_->ScheduleWait();
-}
-
-void MetricsCollector::ScheduleMeminfoCallback(int wait) {
-  if (testing_) {
-    return;
-  }
-  base::TimeDelta waitDelta = base::TimeDelta::FromSeconds(wait);
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&MetricsCollector::MeminfoCallback,
-                 weak_ptr_factory_.GetWeakPtr(), waitDelta),
-      waitDelta);
-}
-
-void MetricsCollector::MeminfoCallback(base::TimeDelta wait) {
-  string meminfo_raw;
-  const FilePath meminfo_path(kMeminfoFileName);
-  if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
-    LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
-    return;
-  }
-  // Make both calls even if the first one fails.
-  if (ProcessMeminfo(meminfo_raw)) {
-    base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-        base::Bind(&MetricsCollector::MeminfoCallback,
-                   weak_ptr_factory_.GetWeakPtr(), wait),
-        wait);
-  }
-}
-
-// static
-bool MetricsCollector::ReadFileToUint64(const base::FilePath& path,
-                                         uint64_t* value) {
-  std::string content;
-  if (!base::ReadFileToString(path, &content)) {
-    PLOG(WARNING) << "cannot read " << path.MaybeAsASCII();
-    return false;
-  }
-  // Remove final newline.
-  base::TrimWhitespaceASCII(content, base::TRIM_TRAILING, &content);
-  if (!base::StringToUint64(content, value)) {
-    LOG(WARNING) << "invalid integer: " << content;
-    return false;
-  }
-  return true;
-}
-
-bool MetricsCollector::ReportZram(const base::FilePath& zram_dir) {
-  // Data sizes are in bytes.  |zero_pages| is in number of pages.
-  uint64_t compr_data_size, orig_data_size, zero_pages;
-  const size_t page_size = 4096;
-
-  if (!ReadFileToUint64(zram_dir.Append(kComprDataSizeName),
-                        &compr_data_size) ||
-      !ReadFileToUint64(zram_dir.Append(kOrigDataSizeName), &orig_data_size) ||
-      !ReadFileToUint64(zram_dir.Append(kZeroPagesName), &zero_pages)) {
-    return false;
-  }
-
-  // |orig_data_size| does not include zero-filled pages.
-  orig_data_size += zero_pages * page_size;
-
-  const int compr_data_size_mb = compr_data_size >> 20;
-  const int savings_mb = (orig_data_size - compr_data_size) >> 20;
-  const int zero_ratio_percent = zero_pages * page_size * 100 / orig_data_size;
-
-  // Report compressed size in megabytes.  100 MB or less has little impact.
-  SendSample("Platform.ZramCompressedSize", compr_data_size_mb, 100, 4000, 50);
-  SendSample("Platform.ZramSavings", savings_mb, 100, 4000, 50);
-  // The compression ratio is multiplied by 100 for better resolution.  The
-  // ratios of interest are between 1 and 6 (100% and 600% as reported).  We
-  // don't want samples when very little memory is being compressed.
-  if (compr_data_size_mb >= 1) {
-    SendSample("Platform.ZramCompressionRatioPercent",
-               orig_data_size * 100 / compr_data_size, 100, 600, 50);
-  }
-  // The values of interest for zero_pages are between 1MB and 1GB.  The units
-  // are number of pages.
-  SendSample("Platform.ZramZeroPages", zero_pages, 256, 256 * 1024, 50);
-  SendSample("Platform.ZramZeroRatioPercent", zero_ratio_percent, 1, 50, 50);
-
-  return true;
-}
-
-bool MetricsCollector::ProcessMeminfo(const string& meminfo_raw) {
-  static const MeminfoRecord fields_array[] = {
-    { "MemTotal", "MemTotal" },  // SPECIAL CASE: total system memory
-    { "MemFree", "MemFree" },
-    { "Buffers", "Buffers" },
-    { "Cached", "Cached" },
-    // { "SwapCached", "SwapCached" },
-    { "Active", "Active" },
-    { "Inactive", "Inactive" },
-    { "ActiveAnon", "Active(anon)" },
-    { "InactiveAnon", "Inactive(anon)" },
-    { "ActiveFile" , "Active(file)" },
-    { "InactiveFile", "Inactive(file)" },
-    { "Unevictable", "Unevictable", kMeminfoOp_HistLog },
-    // { "Mlocked", "Mlocked" },
-    { "SwapTotal", "SwapTotal", kMeminfoOp_SwapTotal },
-    { "SwapFree", "SwapFree", kMeminfoOp_SwapFree },
-    // { "Dirty", "Dirty" },
-    // { "Writeback", "Writeback" },
-    { "AnonPages", "AnonPages" },
-    { "Mapped", "Mapped" },
-    { "Shmem", "Shmem", kMeminfoOp_HistLog },
-    { "Slab", "Slab", kMeminfoOp_HistLog },
-    // { "SReclaimable", "SReclaimable" },
-    // { "SUnreclaim", "SUnreclaim" },
-  };
-  vector<MeminfoRecord> fields(fields_array,
-                               fields_array + arraysize(fields_array));
-  if (!FillMeminfo(meminfo_raw, &fields)) {
-    return false;
-  }
-  int total_memory = fields[0].value;
-  if (total_memory == 0) {
-    // this "cannot happen"
-    LOG(WARNING) << "borked meminfo parser";
-    return false;
-  }
-  int swap_total = 0;
-  int swap_free = 0;
-  // Send all fields retrieved, except total memory.
-  for (unsigned int i = 1; i < fields.size(); i++) {
-    string metrics_name = base::StringPrintf("Platform.Meminfo%s",
-                                             fields[i].name);
-    int percent;
-    switch (fields[i].op) {
-      case kMeminfoOp_HistPercent:
-        // report value as percent of total memory
-        percent = fields[i].value * 100 / total_memory;
-        SendLinearSample(metrics_name, percent, 100, 101);
-        break;
-      case kMeminfoOp_HistLog:
-        // report value in kbytes, log scale, 4Gb max
-        SendSample(metrics_name, fields[i].value, 1, 4 * 1000 * 1000, 100);
-        break;
-      case kMeminfoOp_SwapTotal:
-        swap_total = fields[i].value;
-      case kMeminfoOp_SwapFree:
-        swap_free = fields[i].value;
-        break;
-    }
-  }
-  if (swap_total > 0) {
-    int swap_used = swap_total - swap_free;
-    int swap_used_percent = swap_used * 100 / swap_total;
-    SendSample("Platform.MeminfoSwapUsed", swap_used, 1, 8 * 1000 * 1000, 100);
-    SendLinearSample("Platform.MeminfoSwapUsed.Percent", swap_used_percent,
-                     100, 101);
-  }
-  return true;
-}
-
-bool MetricsCollector::FillMeminfo(const string& meminfo_raw,
-                                    vector<MeminfoRecord>* fields) {
-  vector<std::string> lines =
-      base::SplitString(meminfo_raw, "\n", base::KEEP_WHITESPACE,
-                        base::SPLIT_WANT_NONEMPTY);
-
-  // Scan meminfo output and collect field values.  Each field name has to
-  // match a meminfo entry (case insensitive) after removing non-alpha
-  // characters from the entry.
-  size_t ifield = 0;
-  for (size_t iline = 0;
-       iline < lines.size() && ifield < fields->size();
-       iline++) {
-    vector<string> tokens =
-        base::SplitString(lines[iline], ": ", base::KEEP_WHITESPACE,
-                          base::SPLIT_WANT_NONEMPTY);
-    if (strcmp((*fields)[ifield].match, tokens[0].c_str()) == 0) {
-      // Name matches. Parse value and save.
-      if (!base::StringToInt(tokens[1], &(*fields)[ifield].value)) {
-        LOG(WARNING) << "Cound not convert " << tokens[1] << " to int";
-        return false;
-      }
-      ifield++;
-    }
-  }
-  if (ifield < fields->size()) {
-    // End of input reached while scanning.
-    LOG(WARNING) << "cannot find field " << (*fields)[ifield].match
-                 << " and following";
-    return false;
-  }
-  return true;
-}
-
-void MetricsCollector::ScheduleMemuseCallback(double interval) {
-  if (testing_) {
-    return;
-  }
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&MetricsCollector::MemuseCallback,
-                 weak_ptr_factory_.GetWeakPtr()),
-      base::TimeDelta::FromSeconds(interval));
-}
-
-void MetricsCollector::MemuseCallback() {
-  // Since we only care about active time (i.e. uptime minus sleep time) but
-  // the callbacks are driven by real time (uptime), we check if we should
-  // reschedule this callback due to intervening sleep periods.
-  double now = GetActiveTime();
-  // Avoid intervals of less than one second.
-  double remaining_time = ceil(memuse_final_time_ - now);
-  if (remaining_time > 0) {
-    ScheduleMemuseCallback(remaining_time);
-  } else {
-    // Report stats and advance the measurement interval unless there are
-    // errors or we've completed the last interval.
-    if (MemuseCallbackWork() &&
-        memuse_interval_index_ < arraysize(kMemuseIntervals)) {
-      double interval = kMemuseIntervals[memuse_interval_index_++];
-      memuse_final_time_ = now + interval;
-      ScheduleMemuseCallback(interval);
-    }
-  }
-}
-
-bool MetricsCollector::MemuseCallbackWork() {
-  string meminfo_raw;
-  const FilePath meminfo_path(kMeminfoFileName);
-  if (!base::ReadFileToString(meminfo_path, &meminfo_raw)) {
-    LOG(WARNING) << "cannot read " << meminfo_path.value().c_str();
-    return false;
-  }
-  return ProcessMemuse(meminfo_raw);
-}
-
-bool MetricsCollector::ProcessMemuse(const string& meminfo_raw) {
-  static const MeminfoRecord fields_array[] = {
-    { "MemTotal", "MemTotal" },  // SPECIAL CASE: total system memory
-    { "ActiveAnon", "Active(anon)" },
-    { "InactiveAnon", "Inactive(anon)" },
-  };
-  vector<MeminfoRecord> fields(fields_array,
-                               fields_array + arraysize(fields_array));
-  if (!FillMeminfo(meminfo_raw, &fields)) {
-    return false;
-  }
-  int total = fields[0].value;
-  int active_anon = fields[1].value;
-  int inactive_anon = fields[2].value;
-  if (total == 0) {
-    // this "cannot happen"
-    LOG(WARNING) << "borked meminfo parser";
-    return false;
-  }
-  string metrics_name = base::StringPrintf("Platform.MemuseAnon%d",
-                                           memuse_interval_index_);
-  SendLinearSample(metrics_name, (active_anon + inactive_anon) * 100 / total,
-                   100, 101);
-  return true;
-}
-
-void MetricsCollector::SendSample(const string& name, int sample,
-                                   int min, int max, int nbuckets) {
-  metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
-}
-
-void MetricsCollector::SendKernelCrashesCumulativeCountStats() {
-  // Report the number of crashes for this OS version, but don't clear the
-  // counter.  It is cleared elsewhere on version change.
-  int64_t crashes_count = kernel_crashes_version_count_->Get();
-  SendSample(kernel_crashes_version_count_->Name(),
-             crashes_count,
-             1,                         // value of first bucket
-             500,                       // value of last bucket
-             100);                      // number of buckets
-
-
-  int64_t cpu_use_ms = version_cumulative_cpu_use_->Get();
-  SendSample(version_cumulative_cpu_use_->Name(),
-             cpu_use_ms / 1000,         // stat is in seconds
-             1,                         // device may be used very little...
-             8 * 1000 * 1000,           // ... or a lot (a little over 90 days)
-             100);
-
-  // On the first run after an autoupdate, cpu_use_ms and active_use_seconds
-  // can be zero.  Avoid division by zero.
-  if (cpu_use_ms > 0) {
-    // Send the crash frequency since update in number of crashes per CPU year.
-    SendSample("Logging.KernelCrashesPerCpuYear",
-               crashes_count * kSecondsPerDay * 365 * 1000 / cpu_use_ms,
-               1,
-               1000 * 1000,     // about one crash every 30s of CPU time
-               100);
-  }
-
-  int64_t active_use_seconds = version_cumulative_active_use_->Get();
-  if (active_use_seconds > 0) {
-    SendSample(version_cumulative_active_use_->Name(),
-               active_use_seconds,
-               1,                          // device may be used very little...
-               8 * 1000 * 1000,            // ... or a lot (about 90 days)
-               100);
-    // Same as above, but per year of active time.
-    SendSample("Logging.KernelCrashesPerActiveYear",
-               crashes_count * kSecondsPerDay * 365 / active_use_seconds,
-               1,
-               1000 * 1000,     // about one crash every 30s of active time
-               100);
-  }
-}
-
-void MetricsCollector::SendAndResetDailyUseSample(
-    const unique_ptr<PersistentInteger>& use) {
-  SendSample(use->Name(),
-             use->GetAndClear(),
-             1,                        // value of first bucket
-             kSecondsPerDay,           // value of last bucket
-             50);                      // number of buckets
-}
-
-void MetricsCollector::SendAndResetCrashIntervalSample(
-    const unique_ptr<PersistentInteger>& interval) {
-  SendSample(interval->Name(),
-             interval->GetAndClear(),
-             1,                        // value of first bucket
-             4 * kSecondsPerWeek,      // value of last bucket
-             50);                      // number of buckets
-}
-
-void MetricsCollector::SendAndResetCrashFrequencySample(
-    const unique_ptr<PersistentInteger>& frequency) {
-  SendSample(frequency->Name(),
-             frequency->GetAndClear(),
-             1,                        // value of first bucket
-             100,                      // value of last bucket
-             50);                      // number of buckets
-}
-
-void MetricsCollector::SendLinearSample(const string& name, int sample,
-                                         int max, int nbuckets) {
-  // TODO(semenzato): add a proper linear histogram to the Chrome external
-  // metrics API.
-  LOG_IF(FATAL, nbuckets != max + 1) << "unsupported histogram scale";
-  metrics_lib_->SendEnumToUMA(name, sample, max);
-}
-
-void MetricsCollector::UpdateStats(TimeTicks now_ticks,
-                                    Time now_wall_time) {
-  const int elapsed_seconds = (now_ticks - last_update_stats_time_).InSeconds();
-  daily_active_use_->Add(elapsed_seconds);
-  version_cumulative_active_use_->Add(elapsed_seconds);
-  user_crash_interval_->Add(elapsed_seconds);
-  kernel_crash_interval_->Add(elapsed_seconds);
-  TimeDelta cpu_use = cpu_usage_collector_->GetCumulativeCpuUse();
-  version_cumulative_cpu_use_->Add(
-      (cpu_use - latest_cpu_use_microseconds_).InMilliseconds());
-  latest_cpu_use_microseconds_ = cpu_use;
-  last_update_stats_time_ = now_ticks;
-
-  const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
-  const int day = since_epoch.InDays();
-  const int week = day / 7;
-
-  if (daily_cycle_->Get() != day) {
-    daily_cycle_->Set(day);
-    SendAndResetDailyUseSample(daily_active_use_);
-    SendAndResetCrashFrequencySample(any_crashes_daily_count_);
-    SendAndResetCrashFrequencySample(user_crashes_daily_count_);
-    SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
-    SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
-    SendKernelCrashesCumulativeCountStats();
-  }
-
-  if (weekly_cycle_->Get() != week) {
-    weekly_cycle_->Set(week);
-    SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
-    SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
-    SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
-    SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
-  }
-}
-
-void MetricsCollector::HandleUpdateStatsTimeout() {
-  UpdateStats(TimeTicks::Now(), Time::Now());
-  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
-      base::Bind(&MetricsCollector::HandleUpdateStatsTimeout,
-                 weak_ptr_factory_.GetWeakPtr()),
-      base::TimeDelta::FromMilliseconds(kUpdateStatsIntervalMs));
-}
diff --git a/metricsd/metrics_collector.h b/metricsd/metrics_collector.h
deleted file mode 100644
index 30659bd..0000000
--- a/metricsd/metrics_collector.h
+++ /dev/null
@@ -1,284 +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.
- */
-
-#ifndef METRICS_METRICS_COLLECTOR_H_
-#define METRICS_METRICS_COLLECTOR_H_
-
-#include <stdint.h>
-
-#include <map>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include <base/files/file_path.h>
-#include <base/memory/weak_ptr.h>
-#include <base/time/time.h>
-#include <brillo/binder_watcher.h>
-#include <brillo/daemons/daemon.h>
-#include <libweaved/command.h>
-#include <libweaved/service.h>
-#include <gtest/gtest_prod.h>  // for FRIEND_TEST
-
-#include "collectors/averaged_statistics_collector.h"
-#include "collectors/cpu_usage_collector.h"
-#include "collectors/disk_usage_collector.h"
-#include "metrics/metrics_library.h"
-#include "persistent_integer.h"
-
-using chromeos_metrics::PersistentInteger;
-using std::unique_ptr;
-
-class MetricsCollector : public brillo::Daemon {
- public:
-  MetricsCollector();
-  ~MetricsCollector();
-
-  // Initializes metrics class variables.
-  void Init(bool testing,
-            MetricsLibraryInterface* metrics_lib,
-            const std::string& diskstats_path,
-            const base::FilePath& private_metrics_directory,
-            const base::FilePath& shared_metrics_directory);
-
-  // Initializes the daemon.
-  int OnInit() override;
-
-  // Does all the work.
-  int Run() override;
-
-  // Returns the active time since boot (uptime minus sleep time) in seconds.
-  static double GetActiveTime();
-
-  // Updates the active use time and logs time between user-space
-  // process crashes.  Called via MetricsCollectorServiceTrampoline.
-  void ProcessUserCrash();
-
- protected:
-  // Used also by the unit tests.
-  static const char kComprDataSizeName[];
-  static const char kOrigDataSizeName[];
-  static const char kZeroPagesName[];
-
- private:
-  friend class MetricsCollectorTest;
-  FRIEND_TEST(MetricsCollectorTest, CheckSystemCrash);
-  FRIEND_TEST(MetricsCollectorTest, ComputeEpochNoCurrent);
-  FRIEND_TEST(MetricsCollectorTest, ComputeEpochNoLast);
-  FRIEND_TEST(MetricsCollectorTest, GetHistogramPath);
-  FRIEND_TEST(MetricsCollectorTest, IsNewEpoch);
-  FRIEND_TEST(MetricsCollectorTest, MessageFilter);
-  FRIEND_TEST(MetricsCollectorTest, ProcessKernelCrash);
-  FRIEND_TEST(MetricsCollectorTest, ProcessMeminfo);
-  FRIEND_TEST(MetricsCollectorTest, ProcessMeminfo2);
-  FRIEND_TEST(MetricsCollectorTest, ProcessUncleanShutdown);
-  FRIEND_TEST(MetricsCollectorTest, ProcessUserCrash);
-  FRIEND_TEST(MetricsCollectorTest, ReportCrashesDailyFrequency);
-  FRIEND_TEST(MetricsCollectorTest, ReportKernelCrashInterval);
-  FRIEND_TEST(MetricsCollectorTest, ReportUncleanShutdownInterval);
-  FRIEND_TEST(MetricsCollectorTest, ReportUserCrashInterval);
-  FRIEND_TEST(MetricsCollectorTest, SendSample);
-  FRIEND_TEST(MetricsCollectorTest, SendZramMetrics);
-
-  // Type of scale to use for meminfo histograms.  For most of them we use
-  // percent of total RAM, but for some we use absolute numbers, usually in
-  // megabytes, on a log scale from 0 to 4000, and 0 to 8000 for compressed
-  // swap (since it can be larger than total RAM).
-  enum MeminfoOp {
-    kMeminfoOp_HistPercent = 0,
-    kMeminfoOp_HistLog,
-    kMeminfoOp_SwapTotal,
-    kMeminfoOp_SwapFree,
-  };
-
-  // Record for retrieving and reporting values from /proc/meminfo.
-  struct MeminfoRecord {
-    const char* name;        // print name
-    const char* match;       // string to match in output of /proc/meminfo
-    MeminfoOp op;            // histogram scale selector, or other operator
-    int value;               // value from /proc/meminfo
-  };
-
-  // Enables metrics reporting.
-  void OnEnableMetrics(std::unique_ptr<weaved::Command> command);
-
-  // Disables metrics reporting.
-  void OnDisableMetrics(std::unique_ptr<weaved::Command> command);
-
-  // Updates the weave device state.
-  void UpdateWeaveState();
-
-  // Updates the active use time and logs time between kernel crashes.
-  void ProcessKernelCrash();
-
-  // Updates the active use time and logs time between unclean shutdowns.
-  void ProcessUncleanShutdown();
-
-  // Checks if a kernel crash has been detected and returns true if
-  // so.  The method assumes that a kernel crash has happened if
-  // |crash_file| exists.  It removes the file immediately if it
-  // exists, so it must not be called more than once.
-  bool CheckSystemCrash(const std::string& crash_file);
-
-  // Sends a regular (exponential) histogram sample to Chrome for
-  // transport to UMA. See MetricsLibrary::SendToUMA in
-  // metrics_library.h for a description of the arguments.
-  void SendSample(const std::string& name, int sample,
-                  int min, int max, int nbuckets);
-
-  // Sends a linear histogram sample to Chrome for transport to UMA. See
-  // MetricsLibrary::SendToUMA in metrics_library.h for a description of the
-  // arguments.
-  void SendLinearSample(const std::string& name, int sample,
-                        int max, int nbuckets);
-
-  // Sends various cumulative kernel crash-related stats, for instance the
-  // total number of kernel crashes since the last version update.
-  void SendKernelCrashesCumulativeCountStats();
-
-  // Sends a sample representing the number of seconds of active use
-  // for a 24-hour period and reset |use|.
-  void SendAndResetDailyUseSample(const unique_ptr<PersistentInteger>& use);
-
-  // Sends a sample representing a time interval between two crashes of the
-  // same type and reset |interval|.
-  void SendAndResetCrashIntervalSample(
-      const unique_ptr<PersistentInteger>& interval);
-
-  // Sends a sample representing a frequency of crashes of some type and reset
-  // |frequency|.
-  void SendAndResetCrashFrequencySample(
-      const unique_ptr<PersistentInteger>& frequency);
-
-  // Initializes vm and disk stats reporting.
-  void StatsReporterInit();
-
-  // Schedules meminfo collection callback.
-  void ScheduleMeminfoCallback(int wait);
-
-  // Reports memory statistics.  Reschedules callback on success.
-  void MeminfoCallback(base::TimeDelta wait);
-
-  // Parses content of /proc/meminfo and sends fields of interest to UMA.
-  // Returns false on errors.  |meminfo_raw| contains the content of
-  // /proc/meminfo.
-  bool ProcessMeminfo(const std::string& meminfo_raw);
-
-  // Parses meminfo data from |meminfo_raw|.  |fields| is a vector containing
-  // the fields of interest.  The order of the fields must be the same in which
-  // /proc/meminfo prints them.  The result of parsing fields[i] is placed in
-  // fields[i].value.
-  bool FillMeminfo(const std::string& meminfo_raw,
-                   std::vector<MeminfoRecord>* fields);
-
-  // Schedule a memory use callback in |interval| seconds.
-  void ScheduleMemuseCallback(double interval);
-
-  // Calls MemuseCallbackWork, and possibly schedules next callback, if enough
-  // active time has passed.  Otherwise reschedules itself to simulate active
-  // time callbacks (i.e. wall clock time minus sleep time).
-  void MemuseCallback();
-
-  // Reads /proc/meminfo and sends total anonymous memory usage to UMA.
-  bool MemuseCallbackWork();
-
-  // Parses meminfo data and sends it to UMA.
-  bool ProcessMemuse(const std::string& meminfo_raw);
-
-  // Reads the current OS version from /etc/lsb-release and hashes it
-  // to a unsigned 32-bit int.
-  uint32_t GetOsVersionHash();
-
-  // Updates stats, additionally sending them to UMA if enough time has elapsed
-  // since the last report.
-  void UpdateStats(base::TimeTicks now_ticks, base::Time now_wall_time);
-
-  // Invoked periodically by |update_stats_timeout_id_| to call UpdateStats().
-  void HandleUpdateStatsTimeout();
-
-  // Reports zram statistics.
-  bool ReportZram(const base::FilePath& zram_dir);
-
-  // Reads a string from a file and converts it to uint64_t.
-  static bool ReadFileToUint64(const base::FilePath& path, uint64_t* value);
-
-  // Callback invoked when a connection to weaved's service is established
-  // over Binder interface.
-  void OnWeaveServiceConnected(const std::weak_ptr<weaved::Service>& service);
-
-  // VARIABLES
-
-  // Test mode.
-  bool testing_;
-
-  // Publicly readable metrics directory.
-  base::FilePath shared_metrics_directory_;
-
-  // The metrics library handle.
-  MetricsLibraryInterface* metrics_lib_;
-
-  // The last time that UpdateStats() was called.
-  base::TimeTicks last_update_stats_time_;
-
-  // End time of current memuse stat collection interval.
-  double memuse_final_time_;
-
-  // Selects the wait time for the next memory use callback.
-  unsigned int memuse_interval_index_;
-
-  // Used internally by GetIncrementalCpuUse() to return the CPU utilization
-  // between calls.
-  base::TimeDelta latest_cpu_use_microseconds_;
-
-  // Persistent values and accumulators for crash statistics.
-  unique_ptr<PersistentInteger> daily_cycle_;
-  unique_ptr<PersistentInteger> weekly_cycle_;
-  unique_ptr<PersistentInteger> version_cycle_;
-
-  // Active use accumulated in a day.
-  unique_ptr<PersistentInteger> daily_active_use_;
-  // Active use accumulated since the latest version update.
-  unique_ptr<PersistentInteger> version_cumulative_active_use_;
-
-  // The CPU time accumulator.  This contains the CPU time, in milliseconds,
-  // used by the system since the most recent OS version update.
-  unique_ptr<PersistentInteger> version_cumulative_cpu_use_;
-
-  unique_ptr<PersistentInteger> user_crash_interval_;
-  unique_ptr<PersistentInteger> kernel_crash_interval_;
-  unique_ptr<PersistentInteger> unclean_shutdown_interval_;
-
-  unique_ptr<PersistentInteger> any_crashes_daily_count_;
-  unique_ptr<PersistentInteger> any_crashes_weekly_count_;
-  unique_ptr<PersistentInteger> user_crashes_daily_count_;
-  unique_ptr<PersistentInteger> user_crashes_weekly_count_;
-  unique_ptr<PersistentInteger> kernel_crashes_daily_count_;
-  unique_ptr<PersistentInteger> kernel_crashes_weekly_count_;
-  unique_ptr<PersistentInteger> kernel_crashes_version_count_;
-  unique_ptr<PersistentInteger> unclean_shutdowns_daily_count_;
-  unique_ptr<PersistentInteger> unclean_shutdowns_weekly_count_;
-
-  unique_ptr<CpuUsageCollector> cpu_usage_collector_;
-  unique_ptr<DiskUsageCollector> disk_usage_collector_;
-  unique_ptr<AveragedStatisticsCollector> averaged_stats_collector_;
-
-  unique_ptr<weaved::Service::Subscription> weave_service_subscription_;
-  std::weak_ptr<weaved::Service> service_;
-
-  base::WeakPtrFactory<MetricsCollector> weak_ptr_factory_{this};
-};
-
-#endif  // METRICS_METRICS_COLLECTOR_H_
diff --git a/metricsd/metrics_collector.rc b/metricsd/metrics_collector.rc
deleted file mode 100644
index 2d7667d..0000000
--- a/metricsd/metrics_collector.rc
+++ /dev/null
@@ -1,4 +0,0 @@
-service metricscollector /system/bin/metrics_collector --foreground --logtosyslog
-    class late_start
-    user metrics_coll
-    group metrics_coll
diff --git a/metricsd/metrics_collector_main.cc b/metricsd/metrics_collector_main.cc
deleted file mode 100644
index 14bb935..0000000
--- a/metricsd/metrics_collector_main.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <base/at_exit.h>
-#include <base/command_line.h>
-#include <base/logging.h>
-#include <base/strings/string_util.h>
-#include <brillo/flag_helper.h>
-#include <brillo/syslog_logging.h>
-#include <rootdev.h>
-
-#include "constants.h"
-#include "metrics_collector.h"
-
-
-// Returns the path to the disk stats in the sysfs.  Returns the null string if
-// it cannot find the disk stats file.
-static
-const std::string MetricsMainDiskStatsPath() {
-  char dev_path_cstr[PATH_MAX];
-  std::string dev_prefix = "/dev/block/";
-  std::string dev_path;
-
-  int ret = rootdev(dev_path_cstr, sizeof(dev_path_cstr), true, true);
-  if (ret != 0) {
-    LOG(WARNING) << "error " << ret << " determining root device";
-    return "";
-  }
-  dev_path = dev_path_cstr;
-  // Check that rootdev begins with "/dev/block/".
-  if (!base::StartsWith(dev_path, dev_prefix,
-                        base::CompareCase::INSENSITIVE_ASCII)) {
-    LOG(WARNING) << "unexpected root device " << dev_path;
-    return "";
-  }
-  return "/sys/class/block/" + dev_path.substr(dev_prefix.length()) + "/stat";
-}
-
-int main(int argc, char** argv) {
-  DEFINE_bool(foreground, false, "Don't daemonize");
-
-  DEFINE_string(private_directory, metrics::kMetricsCollectorDirectory,
-                "Path to the private directory used by metrics_collector "
-                "(testing only)");
-  DEFINE_string(shared_directory, metrics::kSharedMetricsDirectory,
-                "Path to the shared metrics directory, used by "
-                "metrics_collector, metricsd and all metrics clients "
-                "(testing only)");
-
-  DEFINE_bool(logtostderr, false, "Log to standard error");
-  DEFINE_bool(logtosyslog, false, "Log to syslog");
-
-  brillo::FlagHelper::Init(argc, argv, "Chromium OS Metrics Daemon");
-
-  int logging_location = (FLAGS_foreground ? brillo::kLogToStderr
-                          : brillo::kLogToSyslog);
-  if (FLAGS_logtosyslog)
-    logging_location = brillo::kLogToSyslog;
-
-  if (FLAGS_logtostderr)
-    logging_location = brillo::kLogToStderr;
-
-  // Also log to stderr when not running as daemon.
-  brillo::InitLog(logging_location | brillo::kLogHeader);
-
-  if (FLAGS_logtostderr && FLAGS_logtosyslog) {
-    LOG(ERROR) << "only one of --logtosyslog and --logtostderr can be set";
-    return 1;
-  }
-
-  if (!FLAGS_foreground && daemon(0, 0) != 0) {
-    return errno;
-  }
-
-  MetricsLibrary metrics_lib;
-  metrics_lib.InitWithNoCaching();
-  MetricsCollector daemon;
-  daemon.Init(false,
-              &metrics_lib,
-              MetricsMainDiskStatsPath(),
-              base::FilePath(FLAGS_private_directory),
-              base::FilePath(FLAGS_shared_directory));
-
-  daemon.Run();
-}
diff --git a/metricsd/metrics_collector_service_client.cc b/metricsd/metrics_collector_service_client.cc
deleted file mode 100644
index 08aaa4a..0000000
--- a/metricsd/metrics_collector_service_client.cc
+++ /dev/null
@@ -1,50 +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.
- */
-
-// Client interface to IMetricsCollectorService.
-
-#include "metrics/metrics_collector_service_client.h"
-
-#include <base/logging.h>
-#include <binder/IServiceManager.h>
-#include <utils/String16.h>
-
-#include "android/brillo/metrics/IMetricsCollectorService.h"
-
-namespace {
-const char kMetricsCollectorServiceName[] =
-    "android.brillo.metrics.IMetricsCollectorService";
-}
-
-bool MetricsCollectorServiceClient::Init() {
-  const android::String16 name(kMetricsCollectorServiceName);
-  metrics_collector_service_ = android::interface_cast<
-      android::brillo::metrics::IMetricsCollectorService>(
-      android::defaultServiceManager()->checkService(name));
-
-  if (metrics_collector_service_ == nullptr)
-    LOG(ERROR) << "Unable to lookup service " << kMetricsCollectorServiceName;
-
-  return metrics_collector_service_ != nullptr;
-}
-
-bool MetricsCollectorServiceClient::notifyUserCrash() {
-  if (metrics_collector_service_ == nullptr)
-    return false;
-
-  metrics_collector_service_->notifyUserCrash();
-  return true;
-}
diff --git a/metricsd/metrics_collector_service_impl.cc b/metricsd/metrics_collector_service_impl.cc
deleted file mode 100644
index 4d9a05a..0000000
--- a/metricsd/metrics_collector_service_impl.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "metrics_collector_service_impl.h"
-
-#include <binder/IServiceManager.h>
-#include <binder/Status.h>
-#include <utils/Errors.h>
-
-#include "metrics_collector.h"
-
-using namespace android;
-
-BnMetricsCollectorServiceImpl::BnMetricsCollectorServiceImpl(
-    MetricsCollector* metrics_collector)
-    : metrics_collector_(metrics_collector) {
-}
-
-android::binder::Status BnMetricsCollectorServiceImpl::notifyUserCrash() {
-  metrics_collector_->ProcessUserCrash();
-  return android::binder::Status::ok();
-}
diff --git a/metricsd/metrics_collector_service_impl.h b/metricsd/metrics_collector_service_impl.h
deleted file mode 100644
index 8db418a..0000000
--- a/metricsd/metrics_collector_service_impl.h
+++ /dev/null
@@ -1,48 +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.
- */
-
-#ifndef METRICSD_METRICS_COLLECTOR_SERVICE_IMPL_H_
-#define METRICSD_METRICS_COLLECTOR_SERVICE_IMPL_H_
-
-// metrics_collector binder service implementation.  Constructed by
-// MetricsCollector.
-
-#include "android/brillo/metrics/BnMetricsCollectorService.h"
-
-#include <binder/Status.h>
-
-class MetricsCollector;
-
-class BnMetricsCollectorServiceImpl
-    : public android::brillo::metrics::BnMetricsCollectorService {
- public:
-  // Passed a this pointer from the MetricsCollector object that constructs us.
-  explicit BnMetricsCollectorServiceImpl(
-      MetricsCollector* metrics_collector_service);
-
-  virtual ~BnMetricsCollectorServiceImpl() = default;
-
-  // Called by crash_reporter to report a userspace crash event.  We relay
-  // this to MetricsCollector.
-  android::binder::Status notifyUserCrash();
-
- private:
-  // MetricsCollector object that constructs us, we use this to call back
-  // to it.
-  MetricsCollector* metrics_collector_;
-};
-
-#endif  // METRICSD_METRICS_COLLECTOR_SERVICE_IMPL_H_
diff --git a/metricsd/metrics_collector_test.cc b/metricsd/metrics_collector_test.cc
deleted file mode 100644
index 8dda529..0000000
--- a/metricsd/metrics_collector_test.cc
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <vector>
-
-#include <base/at_exit.h>
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/strings/string_number_conversions.h>
-#include <brillo/flag_helper.h>
-#include <gtest/gtest.h>
-
-#include "constants.h"
-#include "metrics_collector.h"
-#include "metrics/metrics_library_mock.h"
-#include "persistent_integer_mock.h"
-
-using base::FilePath;
-using base::TimeDelta;
-using std::string;
-using std::vector;
-using ::testing::_;
-using ::testing::AnyNumber;
-using ::testing::AtLeast;
-using ::testing::Return;
-using ::testing::StrictMock;
-using chromeos_metrics::PersistentIntegerMock;
-
-
-class MetricsCollectorTest : public testing::Test {
- protected:
-  virtual void SetUp() {
-    brillo::FlagHelper::Init(0, nullptr, "");
-    EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
-
-    base::FilePath private_dir = temp_dir_.path().Append("private");
-    base::FilePath shared_dir = temp_dir_.path().Append("shared");
-
-    EXPECT_TRUE(base::CreateDirectory(private_dir));
-    EXPECT_TRUE(base::CreateDirectory(shared_dir));
-
-    daemon_.Init(true, &metrics_lib_, "", private_dir, shared_dir);
-  }
-
-  // Adds a metrics library mock expectation that the specified metric
-  // will be generated.
-  void ExpectSample(const std::string& name, int sample) {
-    EXPECT_CALL(metrics_lib_, SendToUMA(name, sample, _, _, _))
-        .Times(1)
-        .WillOnce(Return(true))
-        .RetiresOnSaturation();
-  }
-
-  // Creates or overwrites the file in |path| so that it contains the printable
-  // representation of |value|.
-  void CreateUint64ValueFile(const base::FilePath& path, uint64_t value) {
-    std::string value_string = base::Uint64ToString(value);
-    ASSERT_EQ(value_string.length(),
-              base::WriteFile(path, value_string.c_str(),
-                              value_string.length()));
-  }
-
-  // The MetricsCollector under test.
-  MetricsCollector daemon_;
-
-  // Temporary directory used for tests.
-  base::ScopedTempDir temp_dir_;
-
-  // Mocks. They are strict mock so that all unexpected
-  // calls are marked as failures.
-  StrictMock<MetricsLibraryMock> metrics_lib_;
-};
-
-TEST_F(MetricsCollectorTest, SendSample) {
-  ExpectSample("Dummy.Metric", 3);
-  daemon_.SendSample("Dummy.Metric", /* sample */ 3,
-                     /* min */ 1, /* max */ 100, /* buckets */ 50);
-}
-
-TEST_F(MetricsCollectorTest, ProcessMeminfo) {
-  string meminfo =
-      "MemTotal:        2000000 kB\nMemFree:          500000 kB\n"
-      "Buffers:         1000000 kB\nCached:           213652 kB\n"
-      "SwapCached:            0 kB\nActive:           133400 kB\n"
-      "Inactive:         183396 kB\nActive(anon):      92984 kB\n"
-      "Inactive(anon):    58860 kB\nActive(file):      40416 kB\n"
-      "Inactive(file):   124536 kB\nUnevictable:           0 kB\n"
-      "Mlocked:               0 kB\nSwapTotal:             0 kB\n"
-      "SwapFree:              0 kB\nDirty:                40 kB\n"
-      "Writeback:             0 kB\nAnonPages:         92652 kB\n"
-      "Mapped:            59716 kB\nShmem:             59196 kB\n"
-      "Slab:              16656 kB\nSReclaimable:       6132 kB\n"
-      "SUnreclaim:        10524 kB\nKernelStack:        1648 kB\n"
-      "PageTables:         2780 kB\nNFS_Unstable:          0 kB\n"
-      "Bounce:                0 kB\nWritebackTmp:          0 kB\n"
-      "CommitLimit:      970656 kB\nCommitted_AS:    1260528 kB\n"
-      "VmallocTotal:     122880 kB\nVmallocUsed:       12144 kB\n"
-      "VmallocChunk:     103824 kB\nDirectMap4k:        9636 kB\n"
-      "DirectMap2M:     1955840 kB\n";
-
-  // All enum calls must report percents.
-  EXPECT_CALL(metrics_lib_, SendEnumToUMA(_, _, 100)).Times(AtLeast(1));
-  // Check that MemFree is correctly computed at 25%.
-  EXPECT_CALL(metrics_lib_, SendEnumToUMA("Platform.MeminfoMemFree", 25, 100))
-      .Times(AtLeast(1));
-  // Check that we call SendToUma at least once (log histogram).
-  EXPECT_CALL(metrics_lib_, SendToUMA(_, _, _, _, _))
-      .Times(AtLeast(1));
-  // Make sure we don't report fields not in the list.
-  EXPECT_CALL(metrics_lib_, SendToUMA("Platform.MeminfoMlocked", _, _, _, _))
-      .Times(0);
-  EXPECT_CALL(metrics_lib_, SendEnumToUMA("Platform.MeminfoMlocked", _, _))
-      .Times(0);
-  EXPECT_TRUE(daemon_.ProcessMeminfo(meminfo));
-}
-
-TEST_F(MetricsCollectorTest, ProcessMeminfo2) {
-  string meminfo = "MemTotal:        2000000 kB\nMemFree:         1000000 kB\n";
-  // Not enough fields.
-  EXPECT_FALSE(daemon_.ProcessMeminfo(meminfo));
-}
-
-TEST_F(MetricsCollectorTest, SendZramMetrics) {
-  EXPECT_TRUE(daemon_.testing_);
-
-  // |compr_data_size| is the size in bytes of compressed data.
-  const uint64_t compr_data_size = 50 * 1000 * 1000;
-  // The constant '3' is a realistic but random choice.
-  // |orig_data_size| does not include zero pages.
-  const uint64_t orig_data_size = compr_data_size * 3;
-  const uint64_t page_size = 4096;
-  const uint64_t zero_pages = 10 * 1000 * 1000 / page_size;
-
-  CreateUint64ValueFile(
-      temp_dir_.path().Append(MetricsCollector::kComprDataSizeName),
-      compr_data_size);
-  CreateUint64ValueFile(
-      temp_dir_.path().Append(MetricsCollector::kOrigDataSizeName),
-      orig_data_size);
-  CreateUint64ValueFile(
-      temp_dir_.path().Append(MetricsCollector::kZeroPagesName), zero_pages);
-
-  const uint64_t real_orig_size = orig_data_size + zero_pages * page_size;
-  const uint64_t zero_ratio_percent =
-      zero_pages * page_size * 100 / real_orig_size;
-  // Ratio samples are in percents.
-  const uint64_t actual_ratio_sample = real_orig_size * 100 / compr_data_size;
-
-  EXPECT_CALL(metrics_lib_, SendToUMA(_, compr_data_size >> 20, _, _, _));
-  EXPECT_CALL(metrics_lib_,
-              SendToUMA(_, (real_orig_size - compr_data_size) >> 20, _, _, _));
-  EXPECT_CALL(metrics_lib_, SendToUMA(_, actual_ratio_sample, _, _, _));
-  EXPECT_CALL(metrics_lib_, SendToUMA(_, zero_pages, _, _, _));
-  EXPECT_CALL(metrics_lib_, SendToUMA(_, zero_ratio_percent, _, _, _));
-
-  EXPECT_TRUE(daemon_.ReportZram(temp_dir_.path()));
-}
diff --git a/metricsd/metrics_library.cc b/metricsd/metrics_library.cc
deleted file mode 100644
index d211ab4..0000000
--- a/metricsd/metrics_library.cc
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "metrics/metrics_library.h"
-
-#include <base/logging.h>
-#include <base/strings/stringprintf.h>
-#include <binder/IServiceManager.h>
-#include <errno.h>
-#include <sys/file.h>
-#include <sys/stat.h>
-#include <utils/String16.h>
-
-#include <cstdio>
-#include <cstring>
-
-#include "android/brillo/metrics/IMetricsd.h"
-#include "constants.h"
-
-static const char kCrosEventHistogramName[] = "Platform.CrOSEvent";
-static const int kCrosEventHistogramMax = 100;
-static const char kMetricsServiceName[] = "android.brillo.metrics.IMetricsd";
-
-/* Add new cros events here.
- *
- * The index of the event is sent in the message, so please do not
- * reorder the names.
- */
-static const char *kCrosEventNames[] = {
-  "ModemManagerCommandSendFailure",  // 0
-  "HwWatchdogReboot",  // 1
-  "Cras.NoCodecsFoundAtBoot",  // 2
-  "Chaps.DatabaseCorrupted",  // 3
-  "Chaps.DatabaseRepairFailure",  // 4
-  "Chaps.DatabaseCreateFailure",  // 5
-  "Attestation.OriginSpecificExhausted",  // 6
-  "SpringPowerSupply.Original.High",  // 7
-  "SpringPowerSupply.Other.High",  // 8
-  "SpringPowerSupply.Original.Low",  // 9
-  "SpringPowerSupply.ChargerIdle",  // 10
-  "TPM.NonZeroDictionaryAttackCounter",  // 11
-  "TPM.EarlyResetDuringCommand",  // 12
-};
-
-using android::binder::Status;
-using android::brillo::metrics::IMetricsd;
-using android::String16;
-
-MetricsLibrary::MetricsLibrary() {}
-MetricsLibrary::~MetricsLibrary() {}
-
-// We take buffer and buffer_size as parameters in order to simplify testing
-// of various alignments of the |device_name| with |buffer_size|.
-bool MetricsLibrary::IsDeviceMounted(const char* device_name,
-                                     const char* mounts_file,
-                                     char* buffer,
-                                     int buffer_size,
-                                     bool* result) {
-  if (buffer == nullptr || buffer_size < 1)
-    return false;
-  int mounts_fd = open(mounts_file, O_RDONLY);
-  if (mounts_fd < 0)
-    return false;
-  // match_offset describes:
-  //   -1 -- not beginning of line
-  //   0..strlen(device_name)-1 -- this offset in device_name is next to match
-  //   strlen(device_name) -- matched full name, just need a space.
-  int match_offset = 0;
-  bool match = false;
-  while (!match) {
-    int read_size = read(mounts_fd, buffer, buffer_size);
-    if (read_size <= 0) {
-      if (errno == -EINTR)
-        continue;
-      break;
-    }
-    for (int i = 0; i < read_size; ++i) {
-      if (buffer[i] == '\n') {
-        match_offset = 0;
-        continue;
-      }
-      if (match_offset < 0) {
-        continue;
-      }
-      if (device_name[match_offset] == '\0') {
-        if (buffer[i] == ' ') {
-          match = true;
-          break;
-        }
-        match_offset = -1;
-        continue;
-      }
-
-      if (buffer[i] == device_name[match_offset]) {
-        ++match_offset;
-      } else {
-        match_offset = -1;
-      }
-    }
-  }
-  close(mounts_fd);
-  *result = match;
-  return true;
-}
-
-bool MetricsLibrary::IsGuestMode() {
-  char buffer[256];
-  bool result = false;
-  if (!IsDeviceMounted("guestfs",
-                       "/proc/mounts",
-                       buffer,
-                       sizeof(buffer),
-                       &result)) {
-    return false;
-  }
-  return result && (access("/var/run/state/logged-in", F_OK) == 0);
-}
-
-bool MetricsLibrary::CheckService() {
-  if (metricsd_proxy_.get() &&
-      android::IInterface::asBinder(metricsd_proxy_)->isBinderAlive())
-    return true;
-
-  const String16 name(kMetricsServiceName);
-  metricsd_proxy_ = android::interface_cast<IMetricsd>(
-      android::defaultServiceManager()->checkService(name));
-  return metricsd_proxy_.get();
-}
-
-bool MetricsLibrary::AreMetricsEnabled() {
-  static struct stat stat_buffer;
-  time_t this_check_time = time(nullptr);
-  if (!use_caching_ || this_check_time != cached_enabled_time_) {
-    cached_enabled_time_ = this_check_time;
-    cached_enabled_ = stat(consent_file_.value().data(), &stat_buffer) >= 0;
-  }
-  return cached_enabled_;
-}
-
-void MetricsLibrary::Init() {
-  base::FilePath dir = base::FilePath(metrics::kSharedMetricsDirectory);
-  consent_file_ = dir.Append(metrics::kConsentFileName);
-  cached_enabled_ = false;
-  cached_enabled_time_ = 0;
-  use_caching_ = true;
-}
-
-void MetricsLibrary::InitWithNoCaching() {
-  Init();
-  use_caching_ = false;
-}
-
-void MetricsLibrary::InitForTest(const base::FilePath& metrics_directory) {
-  consent_file_ = metrics_directory.Append(metrics::kConsentFileName);
-  cached_enabled_ = false;
-  cached_enabled_time_ = 0;
-  use_caching_ = true;
-}
-
-bool MetricsLibrary::SendToUMA(
-    const std::string& name, int sample, int min, int max, int nbuckets) {
-  return CheckService() &&
-         metricsd_proxy_->recordHistogram(String16(name.c_str()), sample, min,
-                                          max, nbuckets)
-             .isOk();
-}
-
-bool MetricsLibrary::SendEnumToUMA(const std::string& name,
-                                   int sample,
-                                   int max) {
-  return CheckService() &&
-         metricsd_proxy_->recordLinearHistogram(String16(name.c_str()), sample,
-                                                max)
-             .isOk();
-}
-
-bool MetricsLibrary::SendBoolToUMA(const std::string& name, bool sample) {
-  return CheckService() &&
-         metricsd_proxy_->recordLinearHistogram(String16(name.c_str()),
-                                                sample ? 1 : 0, 2)
-             .isOk();
-}
-
-bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
-  return CheckService() &&
-         metricsd_proxy_->recordSparseHistogram(String16(name.c_str()), sample)
-             .isOk();
-}
-
-bool MetricsLibrary::SendCrashToUMA(const char* crash_kind) {
-  return CheckService() &&
-         metricsd_proxy_->recordCrash(String16(crash_kind)).isOk();
-}
-
-bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
-  for (size_t i = 0; i < arraysize(kCrosEventNames); i++) {
-    if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
-      return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
-    }
-  }
-  return false;
-}
-
-bool MetricsLibrary::GetHistogramsDump(std::string* dump) {
-  android::String16 temp_dump;
-  if (!CheckService() ||
-      !metricsd_proxy_->getHistogramsDump(&temp_dump).isOk()) {
-    return false;
-  }
-
-  *dump = android::String8(temp_dump).string();
-  return true;
-}
diff --git a/metricsd/metrics_library_test.cc b/metricsd/metrics_library_test.cc
deleted file mode 100644
index 52fcce3..0000000
--- a/metricsd/metrics_library_test.cc
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include "metrics/c_metrics_library.h"
-#include "metrics/metrics_library.h"
-
-
-class MetricsLibraryTest : public testing::Test {
- protected:
-  virtual void SetUp() {
-    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
-    lib_.InitForTest(temp_dir_.path());
-    // Defeat metrics enabled caching between tests.
-    lib_.cached_enabled_time_ = 0;
-  }
-
-  void SetMetricsConsent(bool enabled) {
-    if (enabled) {
-      ASSERT_EQ(base::WriteFile(lib_.consent_file_, "", 0), 0);
-    } else {
-      ASSERT_TRUE(base::DeleteFile(lib_.consent_file_, false));
-    }
-  }
-
-  void VerifyEnabledCacheHit(bool to_value);
-  void VerifyEnabledCacheEviction(bool to_value);
-
-  MetricsLibrary lib_;
-  base::ScopedTempDir temp_dir_;
-};
-
-TEST_F(MetricsLibraryTest, AreMetricsEnabledFalse) {
-  SetMetricsConsent(false);
-  EXPECT_FALSE(lib_.AreMetricsEnabled());
-}
-
-TEST_F(MetricsLibraryTest, AreMetricsEnabledTrue) {
-  SetMetricsConsent(true);
-  EXPECT_TRUE(lib_.AreMetricsEnabled());
-}
-
-void MetricsLibraryTest::VerifyEnabledCacheHit(bool to_value) {
-  // We might step from one second to the next one time, but not 100
-  // times in a row.
-  for (int i = 0; i < 100; ++i) {
-    lib_.cached_enabled_time_ = 0;
-    SetMetricsConsent(to_value);
-    lib_.AreMetricsEnabled();
-    // If we check the metrics status twice in a row, we use the cached value
-    // the second time.
-    SetMetricsConsent(!to_value);
-    if (lib_.AreMetricsEnabled() == to_value)
-      return;
-  }
-  ADD_FAILURE() << "Did not see evidence of caching";
-}
-
-void MetricsLibraryTest::VerifyEnabledCacheEviction(bool to_value) {
-  lib_.cached_enabled_time_ = 0;
-  SetMetricsConsent(!to_value);
-  ASSERT_EQ(!to_value, lib_.AreMetricsEnabled());
-
-  SetMetricsConsent(to_value);
-  // Sleep one second (or cheat to be faster) and check that we are not using
-  // the cached value.
-  --lib_.cached_enabled_time_;
-  ASSERT_EQ(to_value, lib_.AreMetricsEnabled());
-}
-
-TEST_F(MetricsLibraryTest, AreMetricsEnabledCaching) {
-  VerifyEnabledCacheHit(false);
-  VerifyEnabledCacheHit(true);
-  VerifyEnabledCacheEviction(false);
-  VerifyEnabledCacheEviction(true);
-}
-
-TEST_F(MetricsLibraryTest, AreMetricsEnabledNoCaching) {
-  // disable caching.
-  lib_.use_caching_ = false;
-
-  // Checking the consent repeatedly should return the right result.
-  for (int i=0; i<100; ++i) {
-    SetMetricsConsent(true);
-    ASSERT_EQ(true, lib_.AreMetricsEnabled());
-    SetMetricsConsent(false);
-    ASSERT_EQ(false, lib_.AreMetricsEnabled());
-  }
-}
diff --git a/metricsd/metricsd.rc b/metricsd/metricsd.rc
deleted file mode 100644
index 3d3e695..0000000
--- a/metricsd/metricsd.rc
+++ /dev/null
@@ -1,9 +0,0 @@
-on post-fs-data
-    mkdir /data/misc/metrics 0750 metrics_coll system
-    mkdir /data/misc/metricsd 0700 metricsd metricsd
-    mkdir /data/misc/metrics_collector 0700 metrics_coll metrics_coll
-
-service metricsd /system/bin/metricsd --foreground --logtosyslog
-    class late_start
-    user metricsd
-    group system inet
diff --git a/metricsd/metricsd_main.cc b/metricsd/metricsd_main.cc
deleted file mode 100644
index 0178342..0000000
--- a/metricsd/metricsd_main.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <base/command_line.h>
-#include <base/files/file_path.h>
-#include <base/logging.h>
-#include <base/time/time.h>
-#include <brillo/flag_helper.h>
-#include <brillo/syslog_logging.h>
-
-#include "constants.h"
-#include "uploader/metricsd_service_runner.h"
-#include "uploader/upload_service.h"
-
-int main(int argc, char** argv) {
-  DEFINE_bool(foreground, false, "Don't daemonize");
-
-  // Upload the metrics once and exit. (used for testing)
-  DEFINE_bool(uploader_test, false, "run the uploader once and exit");
-
-  // Upload Service flags.
-  DEFINE_int32(upload_interval_secs, 1800,
-               "Interval at which metricsd uploads the metrics.");
-  DEFINE_int32(disk_persistence_interval_secs, 300,
-               "Interval at which metricsd saves the aggregated metrics to "
-               "disk to avoid losing them if metricsd stops in between "
-               "two uploads.");
-  DEFINE_string(server, metrics::kMetricsServer,
-                "Server to upload the metrics to.");
-  DEFINE_string(private_directory, metrics::kMetricsdDirectory,
-                "Path to the private directory used by metricsd "
-                "(testing only)");
-  DEFINE_string(shared_directory, metrics::kSharedMetricsDirectory,
-                "Path to the shared metrics directory, used by "
-                "metrics_collector, metricsd and all metrics clients "
-                "(testing only)");
-
-  DEFINE_bool(logtostderr, false, "Log to standard error");
-  DEFINE_bool(logtosyslog, false, "Log to syslog");
-
-  brillo::FlagHelper::Init(argc, argv, "Brillo metrics daemon.");
-
-  int logging_location =
-      (FLAGS_foreground ? brillo::kLogToStderr : brillo::kLogToSyslog);
-  if (FLAGS_logtosyslog)
-    logging_location = brillo::kLogToSyslog;
-
-  if (FLAGS_logtostderr)
-    logging_location = brillo::kLogToStderr;
-
-  // Also log to stderr when not running as daemon.
-  brillo::InitLog(logging_location | brillo::kLogHeader);
-
-  if (FLAGS_logtostderr && FLAGS_logtosyslog) {
-    LOG(ERROR) << "only one of --logtosyslog and --logtostderr can be set";
-    return 1;
-  }
-
-  if (!FLAGS_foreground && daemon(0, 0) != 0) {
-    return errno;
-  }
-
-  UploadService upload_service(
-      FLAGS_server, base::TimeDelta::FromSeconds(FLAGS_upload_interval_secs),
-      base::TimeDelta::FromSeconds(FLAGS_disk_persistence_interval_secs),
-      base::FilePath(FLAGS_private_directory),
-      base::FilePath(FLAGS_shared_directory));
-
-  return upload_service.Run();
-}
diff --git a/metricsd/persistent_integer.cc b/metricsd/persistent_integer.cc
deleted file mode 100644
index 7fe355e..0000000
--- a/metricsd/persistent_integer.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "persistent_integer.h"
-
-#include <fcntl.h>
-
-#include <base/logging.h>
-#include <base/posix/eintr_wrapper.h>
-
-#include "constants.h"
-
-namespace chromeos_metrics {
-
-PersistentInteger::PersistentInteger(const std::string& name,
-                                     const base::FilePath& directory)
-    : value_(0),
-      version_(kVersion),
-      name_(name),
-      backing_file_path_(directory.Append(name_)),
-      synced_(false) {}
-
-PersistentInteger::~PersistentInteger() {}
-
-void PersistentInteger::Set(int64_t value) {
-  value_ = value;
-  Write();
-}
-
-int64_t PersistentInteger::Get() {
-  // If not synced, then read.  If the read fails, it's a good idea to write.
-  if (!synced_ && !Read())
-    Write();
-  return value_;
-}
-
-int64_t PersistentInteger::GetAndClear() {
-  int64_t v = Get();
-  Set(0);
-  return v;
-}
-
-void PersistentInteger::Add(int64_t x) {
-  Set(Get() + x);
-}
-
-void PersistentInteger::Write() {
-  int fd = HANDLE_EINTR(open(backing_file_path_.value().c_str(),
-                             O_WRONLY | O_CREAT | O_TRUNC,
-                             S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH));
-  PCHECK(fd >= 0) << "cannot open " << backing_file_path_.value()
-                  << " for writing";
-  PCHECK((HANDLE_EINTR(write(fd, &version_, sizeof(version_))) ==
-          sizeof(version_)) &&
-         (HANDLE_EINTR(write(fd, &value_, sizeof(value_))) ==
-          sizeof(value_)))
-      << "cannot write to " << backing_file_path_.value();
-  close(fd);
-  synced_ = true;
-}
-
-bool PersistentInteger::Read() {
-  int fd = HANDLE_EINTR(open(backing_file_path_.value().c_str(), O_RDONLY));
-  if (fd < 0) {
-    PLOG(WARNING) << "cannot open " << backing_file_path_.value()
-                  << " for reading";
-    return false;
-  }
-  int32_t version;
-  int64_t value;
-  bool read_succeeded = false;
-  if (HANDLE_EINTR(read(fd, &version, sizeof(version))) == sizeof(version) &&
-      version == version_ &&
-      HANDLE_EINTR(read(fd, &value, sizeof(value))) == sizeof(value)) {
-    value_ = value;
-    read_succeeded = true;
-    synced_ = true;
-  }
-  close(fd);
-  return read_succeeded;
-}
-
-}  // namespace chromeos_metrics
diff --git a/metricsd/persistent_integer.h b/metricsd/persistent_integer.h
deleted file mode 100644
index 96d9fc0..0000000
--- a/metricsd/persistent_integer.h
+++ /dev/null
@@ -1,75 +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.
- */
-
-#ifndef METRICS_PERSISTENT_INTEGER_H_
-#define METRICS_PERSISTENT_INTEGER_H_
-
-#include <stdint.h>
-
-#include <string>
-
-#include <base/files/file_path.h>
-
-namespace chromeos_metrics {
-
-// PersistentIntegers is a named 64-bit integer value backed by a file.
-// The in-memory value acts as a write-through cache of the file value.
-// If the backing file doesn't exist or has bad content, the value is 0.
-
-class PersistentInteger {
- public:
-  PersistentInteger(const std::string& name, const base::FilePath& directory);
-
-  // Virtual only because of mock.
-  virtual ~PersistentInteger();
-
-  // Sets the value.  This writes through to the backing file.
-  void Set(int64_t v);
-
-  // Gets the value.  May sync from backing file first.
-  int64_t Get();
-
-  // Returns the name of the object.
-  std::string Name() { return name_; }
-
-  // Convenience function for Get() followed by Set(0).
-  int64_t GetAndClear();
-
-  // Convenience function for v = Get, Set(v + x).
-  // Virtual only because of mock.
-  virtual void Add(int64_t x);
-
- private:
-  static const int kVersion = 1001;
-
-  // Writes |value_| to the backing file, creating it if necessary.
-  void Write();
-
-  // Reads the value from the backing file, stores it in |value_|, and returns
-  // true if the backing file is valid.  Returns false otherwise, and creates
-  // a valid backing file as a side effect.
-  bool Read();
-
-  int64_t value_;
-  int32_t version_;
-  std::string name_;
-  base::FilePath backing_file_path_;
-  bool synced_;
-};
-
-}  // namespace chromeos_metrics
-
-#endif  // METRICS_PERSISTENT_INTEGER_H_
diff --git a/metricsd/persistent_integer_mock.h b/metricsd/persistent_integer_mock.h
deleted file mode 100644
index 0be54d4..0000000
--- a/metricsd/persistent_integer_mock.h
+++ /dev/null
@@ -1,38 +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.
- */
-
-#ifndef METRICS_PERSISTENT_INTEGER_MOCK_H_
-#define METRICS_PERSISTENT_INTEGER_MOCK_H_
-
-#include <string>
-
-#include <gmock/gmock.h>
-
-#include "persistent_integer.h"
-
-namespace chromeos_metrics {
-
-class PersistentIntegerMock : public PersistentInteger {
- public:
-  explicit PersistentIntegerMock(const std::string& name,
-                                 const base::FilePath& directory)
-      : PersistentInteger(name, directory) {}
-  MOCK_METHOD1(Add, void(int64_t count));
-};
-
-}  // namespace chromeos_metrics
-
-#endif  // METRICS_PERSISTENT_INTEGER_MOCK_H_
diff --git a/metricsd/persistent_integer_test.cc b/metricsd/persistent_integer_test.cc
deleted file mode 100644
index bf76261..0000000
--- a/metricsd/persistent_integer_test.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <memory>
-
-#include <base/compiler_specific.h>
-#include <base/files/file_enumerator.h>
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <gtest/gtest.h>
-
-#include "persistent_integer.h"
-
-const char kBackingFileName[] = "1.pibakf";
-
-using chromeos_metrics::PersistentInteger;
-
-class PersistentIntegerTest : public testing::Test {
-  void SetUp() override {
-    // Set testing mode.
-    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
-  }
-
- protected:
-  base::ScopedTempDir temp_dir_;
-};
-
-TEST_F(PersistentIntegerTest, BasicChecks) {
-  std::unique_ptr<PersistentInteger> pi(
-      new PersistentInteger(kBackingFileName, temp_dir_.path()));
-
-  // Test initialization.
-  EXPECT_EQ(0, pi->Get());
-  EXPECT_EQ(kBackingFileName, pi->Name());  // boring
-
-  // Test set and add.
-  pi->Set(2);
-  pi->Add(3);
-  EXPECT_EQ(5, pi->Get());
-
-  // Test persistence.
-  pi.reset(new PersistentInteger(kBackingFileName, temp_dir_.path()));
-  EXPECT_EQ(5, pi->Get());
-
-  // Test GetAndClear.
-  EXPECT_EQ(5, pi->GetAndClear());
-  EXPECT_EQ(pi->Get(), 0);
-
-  // Another persistence test.
-  pi.reset(new PersistentInteger(kBackingFileName, temp_dir_.path()));
-  EXPECT_EQ(0, pi->Get());
-}
diff --git a/metricsd/timer.cc b/metricsd/timer.cc
deleted file mode 100644
index 06fc336..0000000
--- a/metricsd/timer.cc
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "metrics/timer.h"
-
-#include <string>
-
-#include "metrics/metrics_library.h"
-
-namespace chromeos_metrics {
-
-base::TimeTicks ClockWrapper::GetCurrentTime() const {
-  return base::TimeTicks::Now();
-}
-
-Timer::Timer()
-    : timer_state_(kTimerStopped),
-      clock_wrapper_(new ClockWrapper()) {}
-
-bool Timer::Start() {
-  elapsed_time_ = base::TimeDelta();  // Sets elapsed_time_ to zero.
-  start_time_ = clock_wrapper_->GetCurrentTime();
-  timer_state_ = kTimerRunning;
-  return true;
-}
-
-bool Timer::Stop() {
-  if (timer_state_ == kTimerStopped)
-    return false;
-  if (timer_state_ == kTimerRunning)
-    elapsed_time_ += clock_wrapper_->GetCurrentTime() - start_time_;
-  timer_state_ = kTimerStopped;
-  return true;
-}
-
-bool Timer::Pause() {
-  switch (timer_state_) {
-    case kTimerStopped:
-      if (!Start())
-        return false;
-      timer_state_ = kTimerPaused;
-      return true;
-    case kTimerRunning:
-      timer_state_ = kTimerPaused;
-      elapsed_time_ += clock_wrapper_->GetCurrentTime() - start_time_;
-      return true;
-    default:
-      return false;
-  }
-}
-
-bool Timer::Resume() {
-  switch (timer_state_) {
-    case kTimerStopped:
-      return Start();
-    case kTimerPaused:
-      start_time_ = clock_wrapper_->GetCurrentTime();
-      timer_state_ = kTimerRunning;
-      return true;
-    default:
-      return false;
-  }
-}
-
-bool Timer::Reset() {
-  elapsed_time_ = base::TimeDelta();  // Sets elapsed_time_ to zero.
-  timer_state_ = kTimerStopped;
-  return true;
-}
-
-bool Timer::HasStarted() const {
-  return timer_state_ != kTimerStopped;
-}
-
-bool Timer::GetElapsedTime(base::TimeDelta* elapsed_time) const {
-  if (start_time_.is_null() || !elapsed_time)
-    return false;
-  *elapsed_time = elapsed_time_;
-  if (timer_state_ == kTimerRunning) {
-    *elapsed_time += clock_wrapper_->GetCurrentTime() - start_time_;
-  }
-  return true;
-}
-
-// static
-MetricsLibraryInterface* TimerReporter::metrics_lib_ = nullptr;
-
-TimerReporter::TimerReporter(const std::string& histogram_name, int min,
-                             int max, int num_buckets)
-    : histogram_name_(histogram_name),
-      min_(min),
-      max_(max),
-      num_buckets_(num_buckets) {}
-
-bool TimerReporter::ReportMilliseconds() const {
-  base::TimeDelta elapsed_time;
-  if (!metrics_lib_ || !GetElapsedTime(&elapsed_time)) return false;
-  return metrics_lib_->SendToUMA(histogram_name_,
-                                 elapsed_time.InMilliseconds(),
-                                 min_,
-                                 max_,
-                                 num_buckets_);
-}
-
-}  // namespace chromeos_metrics
diff --git a/metricsd/timer_test.cc b/metricsd/timer_test.cc
deleted file mode 100644
index 7a67e11..0000000
--- a/metricsd/timer_test.cc
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdint.h>
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <memory>
-
-#include "metrics/metrics_library_mock.h"
-#include "metrics/timer.h"
-#include "metrics/timer_mock.h"
-
-using ::testing::_;
-using ::testing::Return;
-
-namespace chromeos_metrics {
-
-namespace {
-const int64_t kStime1MSec = 1400;
-const int64_t kEtime1MSec = 3000;
-const int64_t kDelta1MSec = 1600;
-
-const int64_t kStime2MSec = 4200;
-const int64_t kEtime2MSec = 5000;
-const int64_t kDelta2MSec = 800;
-
-const int64_t kStime3MSec = 6600;
-const int64_t kEtime3MSec = 6800;
-const int64_t kDelta3MSec = 200;
-}  // namespace
-
-class TimerTest : public testing::Test {
- public:
-  TimerTest() : clock_wrapper_mock_(new ClockWrapperMock()) {}
-
- protected:
-  virtual void SetUp() {
-    EXPECT_EQ(Timer::kTimerStopped, timer_.timer_state_);
-    stime += base::TimeDelta::FromMilliseconds(kStime1MSec);
-    etime += base::TimeDelta::FromMilliseconds(kEtime1MSec);
-    stime2 += base::TimeDelta::FromMilliseconds(kStime2MSec);
-    etime2 += base::TimeDelta::FromMilliseconds(kEtime2MSec);
-    stime3 += base::TimeDelta::FromMilliseconds(kStime3MSec);
-    etime3 += base::TimeDelta::FromMilliseconds(kEtime3MSec);
-  }
-
-  virtual void TearDown() {}
-
-  Timer timer_;
-  std::unique_ptr<ClockWrapperMock> clock_wrapper_mock_;
-  base::TimeTicks stime, etime, stime2, etime2, stime3, etime3;
-};
-
-TEST_F(TimerTest, StartStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_FALSE(timer_.HasStarted());
-}
-
-TEST_F(TimerTest, ReStart) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  timer_.Start();
-  base::TimeTicks buffer = timer_.start_time_;
-  timer_.Start();
-  ASSERT_FALSE(timer_.start_time_ == buffer);
-}
-
-TEST_F(TimerTest, Reset) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  timer_.Start();
-  ASSERT_TRUE(timer_.Reset());
-  ASSERT_FALSE(timer_.HasStarted());
-}
-
-TEST_F(TimerTest, SeparatedTimers) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime2);
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, InvalidStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_FALSE(timer_.Stop());
-  // Now we try it again, but after a valid start/stop.
-  timer_.Start();
-  timer_.Stop();
-  base::TimeDelta elapsed_time = timer_.elapsed_time_;
-  ASSERT_FALSE(timer_.Stop());
-  ASSERT_TRUE(elapsed_time == timer_.elapsed_time_);
-}
-
-TEST_F(TimerTest, InvalidElapsedTime) {
-  base::TimeDelta elapsed_time;
-  ASSERT_FALSE(timer_.GetElapsedTime(&elapsed_time));
-}
-
-TEST_F(TimerTest, PauseStartStopResume) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2))
-      .WillOnce(Return(stime3))
-      .WillOnce(Return(etime3));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Pause());  // Starts timer paused.
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Start());  // Restarts timer.
-  ASSERT_TRUE(timer_.start_time_ == stime2);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(kDelta3MSec, elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, ResumeStartStopPause) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2))
-      .WillOnce(Return(stime3));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime2);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(0, elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, StartResumeStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_FALSE(timer_.Resume());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, StartPauseStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, StartPauseResumeStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec + kDelta2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, PauseStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), 0);
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), 0);
-  ASSERT_FALSE(timer_.HasStarted());
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, PauseResumeStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, StartPauseResumePauseStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(stime3))
-      .WillOnce(Return(etime3));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-  // Make sure GetElapsedTime works while we're running.
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(kDelta1MSec + kStime3MSec - kStime2MSec,
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            kDelta1MSec + kEtime3MSec - kStime2MSec);
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            kDelta1MSec + kEtime3MSec - kStime2MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-TEST_F(TimerTest, StartPauseResumePauseResumeStop) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime))
-      .WillOnce(Return(stime2))
-      .WillOnce(Return(etime2))
-      .WillOnce(Return(stime3))
-      .WillOnce(Return(etime3));
-  timer_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  ASSERT_TRUE(timer_.Start());
-  ASSERT_TRUE(timer_.start_time_ == stime);
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec);
-  base::TimeDelta elapsed_time;
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Pause());
-  ASSERT_TRUE(timer_.HasStarted());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(), kDelta1MSec + kDelta2MSec);
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-
-  ASSERT_TRUE(timer_.Resume());
-  ASSERT_TRUE(timer_.HasStarted());
-
-  ASSERT_TRUE(timer_.Stop());
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            kDelta1MSec + kDelta2MSec + kDelta3MSec);
-  ASSERT_FALSE(timer_.HasStarted());
-  ASSERT_TRUE(timer_.GetElapsedTime(&elapsed_time));
-  ASSERT_EQ(timer_.elapsed_time_.InMilliseconds(),
-            elapsed_time.InMilliseconds());
-}
-
-static const char kMetricName[] = "test-timer";
-static const int kMinSample = 0;
-static const int kMaxSample = 120 * 1E6;
-static const int kNumBuckets = 50;
-
-class TimerReporterTest : public testing::Test {
- public:
-  TimerReporterTest() : timer_reporter_(kMetricName, kMinSample, kMaxSample,
-                                        kNumBuckets),
-                        clock_wrapper_mock_(new ClockWrapperMock()) {}
-
- protected:
-  virtual void SetUp() {
-    timer_reporter_.set_metrics_lib(&lib_);
-    EXPECT_EQ(timer_reporter_.histogram_name_, kMetricName);
-    EXPECT_EQ(timer_reporter_.min_, kMinSample);
-    EXPECT_EQ(timer_reporter_.max_, kMaxSample);
-    EXPECT_EQ(timer_reporter_.num_buckets_, kNumBuckets);
-    stime += base::TimeDelta::FromMilliseconds(kStime1MSec);
-    etime += base::TimeDelta::FromMilliseconds(kEtime1MSec);
-  }
-
-  virtual void TearDown() {
-    timer_reporter_.set_metrics_lib(nullptr);
-  }
-
-  TimerReporter timer_reporter_;
-  MetricsLibraryMock lib_;
-  std::unique_ptr<ClockWrapperMock> clock_wrapper_mock_;
-  base::TimeTicks stime, etime;
-};
-
-TEST_F(TimerReporterTest, StartStopReport) {
-  EXPECT_CALL(*clock_wrapper_mock_, GetCurrentTime())
-      .WillOnce(Return(stime))
-      .WillOnce(Return(etime));
-  timer_reporter_.clock_wrapper_.reset(clock_wrapper_mock_.release());
-  EXPECT_CALL(lib_, SendToUMA(kMetricName, kDelta1MSec, kMinSample, kMaxSample,
-                              kNumBuckets)).WillOnce(Return(true));
-  ASSERT_TRUE(timer_reporter_.Start());
-  ASSERT_TRUE(timer_reporter_.Stop());
-  ASSERT_TRUE(timer_reporter_.ReportMilliseconds());
-}
-
-TEST_F(TimerReporterTest, InvalidReport) {
-  ASSERT_FALSE(timer_reporter_.ReportMilliseconds());
-}
-
-}  // namespace chromeos_metrics
-
-int main(int argc, char **argv) {
-  testing::InitGoogleTest(&argc, argv);
-  return RUN_ALL_TESTS();
-}
diff --git a/metricsd/uploader/bn_metricsd_impl.cc b/metricsd/uploader/bn_metricsd_impl.cc
deleted file mode 100644
index 219ed60..0000000
--- a/metricsd/uploader/bn_metricsd_impl.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/bn_metricsd_impl.h"
-
-#include <base/metrics/histogram.h>
-#include <base/metrics/sparse_histogram.h>
-#include <base/metrics/statistics_recorder.h>
-#include <utils/Errors.h>
-#include <utils/String16.h>
-#include <utils/String8.h>
-
-using android::binder::Status;
-using android::String16;
-
-static const char16_t kCrashTypeKernel[] = u"kernel";
-static const char16_t kCrashTypeUncleanShutdown[] = u"uncleanshutdown";
-static const char16_t kCrashTypeUser[] = u"user";
-
-BnMetricsdImpl::BnMetricsdImpl(const std::shared_ptr<CrashCounters>& counters)
-    : counters_(counters) {
-  CHECK(counters_) << "Invalid counters argument to constructor";
-}
-
-Status BnMetricsdImpl::recordHistogram(
-    const String16& name, int sample, int min, int max, int nbuckets) {
-  base::HistogramBase* histogram = base::Histogram::FactoryGet(
-      android::String8(name).string(), min, max, nbuckets,
-      base::Histogram::kUmaTargetedHistogramFlag);
-  // |histogram| may be null if a client reports two contradicting histograms
-  // with the same name but different limits.
-  // FactoryGet will print a useful message if that is the case.
-  if (histogram) {
-    histogram->Add(sample);
-  }
-  return Status::ok();
-}
-
-Status BnMetricsdImpl::recordLinearHistogram(const String16& name,
-                                             int sample,
-                                             int max) {
-  base::HistogramBase* histogram = base::LinearHistogram::FactoryGet(
-      android::String8(name).string(), 1, max, max + 1,
-      base::Histogram::kUmaTargetedHistogramFlag);
-  // |histogram| may be null if a client reports two contradicting histograms
-  // with the same name but different limits.
-  // FactoryGet will print a useful message if that is the case.
-  if (histogram) {
-    histogram->Add(sample);
-  }
-  return Status::ok();
-}
-
-Status BnMetricsdImpl::recordSparseHistogram(const String16& name, int sample) {
-  base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
-      android::String8(name).string(),
-      base::Histogram::kUmaTargetedHistogramFlag);
-  // |histogram| may be null if a client reports two contradicting histograms
-  // with the same name but different limits.
-  // FactoryGet will print a useful message if that is the case.
-  if (histogram) {
-    histogram->Add(sample);
-  }
-  return Status::ok();
-}
-
-Status BnMetricsdImpl::recordCrash(const String16& type) {
-  if (type == kCrashTypeUser) {
-    counters_->IncrementUserCrashCount();
-  } else if (type == kCrashTypeKernel) {
-    counters_->IncrementKernelCrashCount();
-  } else if (type == kCrashTypeUncleanShutdown) {
-    counters_->IncrementUncleanShutdownCount();
-  } else {
-    LOG(ERROR) << "Unknown crash type received: " << type;
-  }
-  return Status::ok();
-}
-
-Status BnMetricsdImpl::getHistogramsDump(String16* dump) {
-  std::string str_dump;
-  base::StatisticsRecorder::WriteGraph(std::string(), &str_dump);
-  *dump = String16(str_dump.c_str());
-  return Status::ok();
-}
diff --git a/metricsd/uploader/bn_metricsd_impl.h b/metricsd/uploader/bn_metricsd_impl.h
deleted file mode 100644
index bf47e80..0000000
--- a/metricsd/uploader/bn_metricsd_impl.h
+++ /dev/null
@@ -1,54 +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.
- */
-
-#ifndef METRICSD_UPLOADER_BN_METRICSD_IMPL_H_
-#define METRICSD_UPLOADER_BN_METRICSD_IMPL_H_
-
-#include "android/brillo/metrics/BnMetricsd.h"
-#include "uploader/crash_counters.h"
-
-class BnMetricsdImpl : public android::brillo::metrics::BnMetricsd {
- public:
-  explicit BnMetricsdImpl(const std::shared_ptr<CrashCounters>& counters);
-  virtual ~BnMetricsdImpl() = default;
-
-  // Records a histogram.
-  android::binder::Status recordHistogram(const android::String16& name,
-                                          int sample,
-                                          int min,
-                                          int max,
-                                          int nbuckets) override;
-
-  // Records a linear histogram.
-  android::binder::Status recordLinearHistogram(const android::String16& name,
-                                                int sample,
-                                                int max) override;
-
-  // Records a sparse histogram.
-  android::binder::Status recordSparseHistogram(const android::String16& name,
-                                                int sample) override;
-
-  // Records a crash.
-  android::binder::Status recordCrash(const android::String16& type) override;
-
-  // Returns a dump of the histograms aggregated in memory.
-  android::binder::Status getHistogramsDump(android::String16* dump) override;
-
- private:
-  std::shared_ptr<CrashCounters> counters_;
-};
-
-#endif  // METRICSD_UPLOADER_BN_METRICSD_IMPL_H_
diff --git a/metricsd/uploader/crash_counters.cc b/metricsd/uploader/crash_counters.cc
deleted file mode 100644
index 1478b9a..0000000
--- a/metricsd/uploader/crash_counters.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/crash_counters.h"
-
-CrashCounters::CrashCounters()
-    : kernel_crashes_(0), unclean_shutdowns_(0), user_crashes_(0) {}
-
-void CrashCounters::IncrementKernelCrashCount() {
-  kernel_crashes_++;
-}
-
-unsigned int CrashCounters::GetAndResetKernelCrashCount() {
-  return kernel_crashes_.exchange(0);
-}
-
-void CrashCounters::IncrementUncleanShutdownCount() {
-  unclean_shutdowns_++;
-}
-
-unsigned int CrashCounters::GetAndResetUncleanShutdownCount() {
-  return unclean_shutdowns_.exchange(0);
-}
-
-void CrashCounters::IncrementUserCrashCount() {
-  user_crashes_++;
-}
-
-unsigned int CrashCounters::GetAndResetUserCrashCount() {
-  return user_crashes_.exchange(0);
-}
diff --git a/metricsd/uploader/crash_counters.h b/metricsd/uploader/crash_counters.h
deleted file mode 100644
index 3fdbf3f..0000000
--- a/metricsd/uploader/crash_counters.h
+++ /dev/null
@@ -1,45 +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.
- */
-
-#ifndef METRICSD_UPLOADER_CRASH_COUNTERS_H_
-#define METRICSD_UPLOADER_CRASH_COUNTERS_H_
-
-#include <atomic>
-
-// This class is used to keep track of the crash counters.
-// An instance of it will be used by both the binder thread (to increment the
-// counters) and the uploader thread (to gather and reset the counters).
-// As such, the internal counters are atomic uints to allow concurrent access.
-class CrashCounters {
- public:
-  CrashCounters();
-
-  void IncrementKernelCrashCount();
-  unsigned int GetAndResetKernelCrashCount();
-
-  void IncrementUserCrashCount();
-  unsigned int GetAndResetUserCrashCount();
-
-  void IncrementUncleanShutdownCount();
-  unsigned int GetAndResetUncleanShutdownCount();
-
- private:
-  std::atomic_uint kernel_crashes_;
-  std::atomic_uint unclean_shutdowns_;
-  std::atomic_uint user_crashes_;
-};
-
-#endif  // METRICSD_UPLOADER_CRASH_COUNTERS_H_
diff --git a/metricsd/uploader/metrics_hashes.cc b/metricsd/uploader/metrics_hashes.cc
deleted file mode 100644
index 208c560..0000000
--- a/metricsd/uploader/metrics_hashes.cc
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metrics_hashes.h"
-
-#include "base/logging.h"
-#include "base/md5.h"
-#include "base/sys_byteorder.h"
-
-namespace metrics {
-
-namespace {
-
-// Converts the 8-byte prefix of an MD5 hash into a uint64 value.
-inline uint64_t HashToUInt64(const std::string& hash) {
-  uint64_t value;
-  DCHECK_GE(hash.size(), sizeof(value));
-  memcpy(&value, hash.data(), sizeof(value));
-  return base::HostToNet64(value);
-}
-
-}  // namespace
-
-uint64_t HashMetricName(const std::string& name) {
-  // Create an MD5 hash of the given |name|, represented as a byte buffer
-  // encoded as an std::string.
-  base::MD5Context context;
-  base::MD5Init(&context);
-  base::MD5Update(&context, name);
-
-  base::MD5Digest digest;
-  base::MD5Final(&digest, &context);
-
-  std::string hash_str(reinterpret_cast<char*>(digest.a), arraysize(digest.a));
-  return HashToUInt64(hash_str);
-}
-
-}  // namespace metrics
diff --git a/metricsd/uploader/metrics_hashes.h b/metricsd/uploader/metrics_hashes.h
deleted file mode 100644
index 1082b42..0000000
--- a/metricsd/uploader/metrics_hashes.h
+++ /dev/null
@@ -1,30 +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.
- */
-
-#ifndef METRICS_UPLOADER_METRICS_HASHES_H_
-#define METRICS_UPLOADER_METRICS_HASHES_H_
-
-#include <string>
-
-namespace metrics {
-
-// Computes a uint64 hash of a given string based on its MD5 hash. Suitable for
-// metric names.
-uint64_t HashMetricName(const std::string& name);
-
-}  // namespace metrics
-
-#endif  // METRICS_UPLOADER_METRICS_HASHES_H_
diff --git a/metricsd/uploader/metrics_hashes_unittest.cc b/metricsd/uploader/metrics_hashes_unittest.cc
deleted file mode 100644
index b8c2575..0000000
--- a/metricsd/uploader/metrics_hashes_unittest.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metrics_hashes.h"
-
-#include <base/format_macros.h>
-#include <base/macros.h>
-#include <base/strings/stringprintf.h>
-#include <gtest/gtest.h>
-
-namespace metrics {
-
-// Make sure our ID hashes are the same as what we see on the server side.
-TEST(MetricsUtilTest, HashMetricName) {
-  static const struct {
-    std::string input;
-    std::string output;
-  } cases[] = {
-    {"Back", "0x0557fa923dcee4d0"},
-    {"Forward", "0x67d2f6740a8eaebf"},
-    {"NewTab", "0x290eb683f96572f1"},
-  };
-
-  for (size_t i = 0; i < arraysize(cases); ++i) {
-    uint64_t hash = HashMetricName(cases[i].input);
-    std::string hash_hex = base::StringPrintf("0x%016" PRIx64, hash);
-    EXPECT_EQ(cases[i].output, hash_hex);
-  }
-}
-
-}  // namespace metrics
diff --git a/metricsd/uploader/metrics_log.cc b/metricsd/uploader/metrics_log.cc
deleted file mode 100644
index fcaa8c1..0000000
--- a/metricsd/uploader/metrics_log.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metrics_log.h"
-
-#include <string>
-
-#include <base/files/file_util.h>
-
-#include "uploader/proto/system_profile.pb.h"
-#include "uploader/system_profile_setter.h"
-
-// We use default values for the MetricsLogBase constructor as the setter will
-// override them.
-MetricsLog::MetricsLog()
-    : MetricsLogBase("", 0, metrics::MetricsLogBase::ONGOING_LOG, "") {
-}
-
-bool MetricsLog::LoadFromFile(const base::FilePath& saved_log) {
-  std::string encoded_log;
-  if (!base::ReadFileToString(saved_log, &encoded_log)) {
-    LOG(ERROR) << "Failed to read the metrics log backup from "
-               << saved_log.value();
-    return false;
-  }
-
-  if (!uma_proto()->ParseFromString(encoded_log)) {
-    LOG(ERROR) << "Failed to parse log from " << saved_log.value()
-               << ", deleting the log";
-    base::DeleteFile(saved_log, false);
-    uma_proto()->Clear();
-    return false;
-  }
-
-  VLOG(1) << uma_proto()->histogram_event_size() << " histograms loaded from "
-          << saved_log.value();
-
-  return true;
-}
-
-bool MetricsLog::SaveToFile(const base::FilePath& path) {
-  std::string encoded_log;
-  GetEncodedLog(&encoded_log);
-
-  if (static_cast<int>(encoded_log.size()) !=
-      base::WriteFile(path, encoded_log.data(), encoded_log.size())) {
-    LOG(ERROR) << "Failed to persist the current log to " << path.value();
-    return false;
-  }
-  return true;
-}
-
-void MetricsLog::IncrementUserCrashCount(unsigned int count) {
-  metrics::SystemProfileProto::Stability* stability(
-      uma_proto()->mutable_system_profile()->mutable_stability());
-  int current = stability->other_user_crash_count();
-  stability->set_other_user_crash_count(current + count);
-}
-
-void MetricsLog::IncrementKernelCrashCount(unsigned int count) {
-  metrics::SystemProfileProto::Stability* stability(
-      uma_proto()->mutable_system_profile()->mutable_stability());
-  int current = stability->kernel_crash_count();
-  stability->set_kernel_crash_count(current + count);
-}
-
-void MetricsLog::IncrementUncleanShutdownCount(unsigned int count) {
-  metrics::SystemProfileProto::Stability* stability(
-      uma_proto()->mutable_system_profile()->mutable_stability());
-  int current = stability->unclean_system_shutdown_count();
-  stability->set_unclean_system_shutdown_count(current + count);
-}
-
-bool MetricsLog::PopulateSystemProfile(SystemProfileSetter* profile_setter) {
-  CHECK(profile_setter);
-  return profile_setter->Populate(uma_proto());
-}
diff --git a/metricsd/uploader/metrics_log.h b/metricsd/uploader/metrics_log.h
deleted file mode 100644
index 9e60b97..0000000
--- a/metricsd/uploader/metrics_log.h
+++ /dev/null
@@ -1,67 +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.
- */
-
-#ifndef METRICSD_UPLOADER_METRICS_LOG_H_
-#define METRICSD_UPLOADER_METRICS_LOG_H_
-
-#include <string>
-
-#include <base/files/file_path.h>
-#include <base/macros.h>
-
-#include "uploader/metrics_log_base.h"
-
-// This file defines a set of user experience metrics data recorded by
-// the MetricsService. This is the unit of data that is sent to the server.
-class SystemProfileSetter;
-
-// This class provides base functionality for logging metrics data.
-class MetricsLog : public metrics::MetricsLogBase {
- public:
-  // The constructor doesn't set any metadata. The metadata is only set by a
-  // SystemProfileSetter.
-  MetricsLog();
-
-  // Increment the crash counters in the protobuf.
-  // These methods don't have to be thread safe as metrics logs are only
-  // accessed by the uploader thread.
-  void IncrementUserCrashCount(unsigned int count);
-  void IncrementKernelCrashCount(unsigned int count);
-  void IncrementUncleanShutdownCount(unsigned int count);
-
-  // Populate the system profile with system information using setter.
-  bool PopulateSystemProfile(SystemProfileSetter* setter);
-
-  // Load the log from |path|.
-  bool LoadFromFile(const base::FilePath& path);
-
-  // Save this log to |path|.
-  bool SaveToFile(const base::FilePath& path);
-
- private:
-  friend class UploadServiceTest;
-  FRIEND_TEST(UploadServiceTest, CurrentLogSavedAndResumed);
-  FRIEND_TEST(UploadServiceTest, LogContainsAggregatedValues);
-  FRIEND_TEST(UploadServiceTest, LogContainsCrashCounts);
-  FRIEND_TEST(UploadServiceTest, LogKernelCrash);
-  FRIEND_TEST(UploadServiceTest, LogUncleanShutdown);
-  FRIEND_TEST(UploadServiceTest, LogUserCrash);
-  FRIEND_TEST(UploadServiceTest, UnknownCrashIgnored);
-
-  DISALLOW_COPY_AND_ASSIGN(MetricsLog);
-};
-
-#endif  // METRICSD_UPLOADER_METRICS_LOG_H_
diff --git a/metricsd/uploader/metrics_log_base.cc b/metricsd/uploader/metrics_log_base.cc
deleted file mode 100644
index 1a60b4f..0000000
--- a/metricsd/uploader/metrics_log_base.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metrics_log_base.h"
-
-#include "base/build_time.h"
-#include "base/metrics/histogram_base.h"
-#include "base/metrics/histogram_samples.h"
-#include "uploader/metrics_hashes.h"
-#include "uploader/proto/histogram_event.pb.h"
-#include "uploader/proto/system_profile.pb.h"
-#include "uploader/proto/user_action_event.pb.h"
-
-using base::Histogram;
-using base::HistogramBase;
-using base::HistogramSamples;
-using base::SampleCountIterator;
-using base::Time;
-using base::TimeDelta;
-using metrics::HistogramEventProto;
-using metrics::SystemProfileProto;
-using metrics::UserActionEventProto;
-
-namespace metrics {
-namespace {
-
-// Any id less than 16 bytes is considered to be a testing id.
-bool IsTestingID(const std::string& id) {
-  return id.size() < 16;
-}
-
-}  // namespace
-
-MetricsLogBase::MetricsLogBase(const std::string& client_id,
-                               int session_id,
-                               LogType log_type,
-                               const std::string& version_string)
-    : num_events_(0),
-      locked_(false),
-      log_type_(log_type) {
-  DCHECK_NE(NO_LOG, log_type);
-  if (IsTestingID(client_id))
-    uma_proto_.set_client_id(0);
-  else
-    uma_proto_.set_client_id(Hash(client_id));
-
-  uma_proto_.set_session_id(session_id);
-  uma_proto_.mutable_system_profile()->set_build_timestamp(GetBuildTime());
-  uma_proto_.mutable_system_profile()->set_app_version(version_string);
-}
-
-MetricsLogBase::~MetricsLogBase() {}
-
-// static
-uint64_t MetricsLogBase::Hash(const std::string& value) {
-  uint64_t hash = metrics::HashMetricName(value);
-
-  // The following log is VERY helpful when folks add some named histogram into
-  // the code, but forgot to update the descriptive list of histograms.  When
-  // that happens, all we get to see (server side) is a hash of the histogram
-  // name.  We can then use this logging to find out what histogram name was
-  // being hashed to a given MD5 value by just running the version of Chromium
-  // in question with --enable-logging.
-  VLOG(1) << "Metrics: Hash numeric [" << value << "]=[" << hash << "]";
-
-  return hash;
-}
-
-// static
-int64_t MetricsLogBase::GetBuildTime() {
-  static int64_t integral_build_time = 0;
-  if (!integral_build_time) {
-    Time time = base::GetBuildTime();
-    integral_build_time = static_cast<int64_t>(time.ToTimeT());
-  }
-  return integral_build_time;
-}
-
-// static
-int64_t MetricsLogBase::GetCurrentTime() {
-  return (base::TimeTicks::Now() - base::TimeTicks()).InSeconds();
-}
-
-void MetricsLogBase::CloseLog() {
-  DCHECK(!locked_);
-  locked_ = true;
-}
-
-void MetricsLogBase::GetEncodedLog(std::string* encoded_log) {
-  DCHECK(locked_);
-  uma_proto_.SerializeToString(encoded_log);
-}
-
-void MetricsLogBase::RecordUserAction(const std::string& key) {
-  DCHECK(!locked_);
-
-  UserActionEventProto* user_action = uma_proto_.add_user_action_event();
-  user_action->set_name_hash(Hash(key));
-  user_action->set_time(GetCurrentTime());
-
-  ++num_events_;
-}
-
-void MetricsLogBase::RecordHistogramDelta(const std::string& histogram_name,
-                                          const HistogramSamples& snapshot) {
-  DCHECK(!locked_);
-  DCHECK_NE(0, snapshot.TotalCount());
-
-  // We will ignore the MAX_INT/infinite value in the last element of range[].
-
-  HistogramEventProto* histogram_proto = uma_proto_.add_histogram_event();
-  histogram_proto->set_name_hash(Hash(histogram_name));
-  histogram_proto->set_sum(snapshot.sum());
-
-  for (scoped_ptr<SampleCountIterator> it = snapshot.Iterator(); !it->Done();
-       it->Next()) {
-    HistogramBase::Sample min;
-    HistogramBase::Sample max;
-    HistogramBase::Count count;
-    it->Get(&min, &max, &count);
-    HistogramEventProto::Bucket* bucket = histogram_proto->add_bucket();
-    bucket->set_min(min);
-    bucket->set_max(max);
-    bucket->set_count(count);
-  }
-
-  // Omit fields to save space (see rules in histogram_event.proto comments).
-  for (int i = 0; i < histogram_proto->bucket_size(); ++i) {
-    HistogramEventProto::Bucket* bucket = histogram_proto->mutable_bucket(i);
-    if (i + 1 < histogram_proto->bucket_size() &&
-        bucket->max() == histogram_proto->bucket(i + 1).min()) {
-      bucket->clear_max();
-    } else if (bucket->max() == bucket->min() + 1) {
-      bucket->clear_min();
-    }
-  }
-}
-
-}  // namespace metrics
diff --git a/metricsd/uploader/metrics_log_base.h b/metricsd/uploader/metrics_log_base.h
deleted file mode 100644
index f4e1995..0000000
--- a/metricsd/uploader/metrics_log_base.h
+++ /dev/null
@@ -1,122 +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.
- */
-
-// This file defines a set of user experience metrics data recorded by
-// the MetricsService.  This is the unit of data that is sent to the server.
-
-#ifndef METRICS_UPLOADER_METRICS_LOG_BASE_H_
-#define METRICS_UPLOADER_METRICS_LOG_BASE_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "base/metrics/histogram.h"
-#include "base/time/time.h"
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-
-namespace base {
-class HistogramSamples;
-}  // namespace base
-
-namespace metrics {
-
-// This class provides base functionality for logging metrics data.
-class MetricsLogBase {
- public:
-  // TODO(asvitkine): Remove the NO_LOG value.
-  enum LogType {
-    INITIAL_STABILITY_LOG,  // The initial log containing stability stats.
-    ONGOING_LOG,            // Subsequent logs in a session.
-    NO_LOG,                 // Placeholder value for when there is no log.
-  };
-
-  // Creates a new metrics log of the specified type.
-  // client_id is the identifier for this profile on this installation
-  // session_id is an integer that's incremented on each application launch
-  MetricsLogBase(const std::string& client_id,
-                 int session_id,
-                 LogType log_type,
-                 const std::string& version_string);
-  virtual ~MetricsLogBase();
-
-  // Computes the MD5 hash of the given string, and returns the first 8 bytes of
-  // the hash.
-  static uint64_t Hash(const std::string& value);
-
-  // Get the GMT buildtime for the current binary, expressed in seconds since
-  // January 1, 1970 GMT.
-  // The value is used to identify when a new build is run, so that previous
-  // reliability stats, from other builds, can be abandoned.
-  static int64_t GetBuildTime();
-
-  // Convenience function to return the current time at a resolution in seconds.
-  // This wraps base::TimeTicks, and hence provides an abstract time that is
-  // always incrementing for use in measuring time durations.
-  static int64_t GetCurrentTime();
-
-  // Records a user-initiated action.
-  void RecordUserAction(const std::string& key);
-
-  // Record any changes in a given histogram for transmission.
-  void RecordHistogramDelta(const std::string& histogram_name,
-                            const base::HistogramSamples& snapshot);
-
-  // Stop writing to this record and generate the encoded representation.
-  // None of the Record* methods can be called after this is called.
-  void CloseLog();
-
-  // Fills |encoded_log| with the serialized protobuf representation of the
-  // record.  Must only be called after CloseLog() has been called.
-  void GetEncodedLog(std::string* encoded_log);
-
-  int num_events() { return num_events_; }
-
-  void set_hardware_class(const std::string& hardware_class) {
-    uma_proto_.mutable_system_profile()->mutable_hardware()->set_hardware_class(
-        hardware_class);
-  }
-
-  LogType log_type() const { return log_type_; }
-
- protected:
-  bool locked() const { return locked_; }
-
-  metrics::ChromeUserMetricsExtension* uma_proto() { return &uma_proto_; }
-  const metrics::ChromeUserMetricsExtension* uma_proto() const {
-    return &uma_proto_;
-  }
-
-  // TODO(isherman): Remove this once the XML pipeline is outta here.
-  int num_events_;  // the number of events recorded in this log
-
- private:
-  // locked_ is true when record has been packed up for sending, and should
-  // no longer be written to.  It is only used for sanity checking and is
-  // not a real lock.
-  bool locked_;
-
-  // The type of the log, i.e. initial or ongoing.
-  const LogType log_type_;
-
-  // Stores the protocol buffer representation for this log.
-  metrics::ChromeUserMetricsExtension uma_proto_;
-
-  DISALLOW_COPY_AND_ASSIGN(MetricsLogBase);
-};
-
-}  // namespace metrics
-
-#endif  // METRICS_UPLOADER_METRICS_LOG_BASE_H_
diff --git a/metricsd/uploader/metrics_log_base_unittest.cc b/metricsd/uploader/metrics_log_base_unittest.cc
deleted file mode 100644
index 980afd5..0000000
--- a/metricsd/uploader/metrics_log_base_unittest.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metrics_log_base.h"
-
-#include <string>
-
-#include <base/metrics/bucket_ranges.h>
-#include <base/metrics/sample_vector.h>
-#include <gtest/gtest.h>
-
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-
-namespace metrics {
-
-namespace {
-
-class TestMetricsLogBase : public MetricsLogBase {
- public:
-  TestMetricsLogBase()
-      : MetricsLogBase("client_id", 1, MetricsLogBase::ONGOING_LOG, "1.2.3.4") {
-  }
-  virtual ~TestMetricsLogBase() {}
-
-  using MetricsLogBase::uma_proto;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(TestMetricsLogBase);
-};
-
-}  // namespace
-
-TEST(MetricsLogBaseTest, LogType) {
-  MetricsLogBase log1("id", 0, MetricsLogBase::ONGOING_LOG, "1.2.3");
-  EXPECT_EQ(MetricsLogBase::ONGOING_LOG, log1.log_type());
-
-  MetricsLogBase log2("id", 0, MetricsLogBase::INITIAL_STABILITY_LOG, "1.2.3");
-  EXPECT_EQ(MetricsLogBase::INITIAL_STABILITY_LOG, log2.log_type());
-}
-
-TEST(MetricsLogBaseTest, EmptyRecord) {
-  MetricsLogBase log("totally bogus client ID", 137,
-                     MetricsLogBase::ONGOING_LOG, "bogus version");
-  log.set_hardware_class("sample-class");
-  log.CloseLog();
-
-  std::string encoded;
-  log.GetEncodedLog(&encoded);
-
-  // A couple of fields are hard to mock, so these will be copied over directly
-  // for the expected output.
-  metrics::ChromeUserMetricsExtension parsed;
-  ASSERT_TRUE(parsed.ParseFromString(encoded));
-
-  metrics::ChromeUserMetricsExtension expected;
-  expected.set_client_id(5217101509553811875);  // Hashed bogus client ID
-  expected.set_session_id(137);
-  expected.mutable_system_profile()->set_build_timestamp(
-      parsed.system_profile().build_timestamp());
-  expected.mutable_system_profile()->set_app_version("bogus version");
-  expected.mutable_system_profile()->mutable_hardware()->set_hardware_class(
-      "sample-class");
-
-  EXPECT_EQ(expected.SerializeAsString(), encoded);
-}
-
-TEST(MetricsLogBaseTest, HistogramBucketFields) {
-  // Create buckets: 1-5, 5-7, 7-8, 8-9, 9-10, 10-11, 11-12.
-  base::BucketRanges ranges(8);
-  ranges.set_range(0, 1);
-  ranges.set_range(1, 5);
-  ranges.set_range(2, 7);
-  ranges.set_range(3, 8);
-  ranges.set_range(4, 9);
-  ranges.set_range(5, 10);
-  ranges.set_range(6, 11);
-  ranges.set_range(7, 12);
-
-  base::SampleVector samples(&ranges);
-  samples.Accumulate(3, 1);   // Bucket 1-5.
-  samples.Accumulate(6, 1);   // Bucket 5-7.
-  samples.Accumulate(8, 1);   // Bucket 8-9. (7-8 skipped)
-  samples.Accumulate(10, 1);  // Bucket 10-11. (9-10 skipped)
-  samples.Accumulate(11, 1);  // Bucket 11-12.
-
-  TestMetricsLogBase log;
-  log.RecordHistogramDelta("Test", samples);
-
-  const metrics::ChromeUserMetricsExtension* uma_proto = log.uma_proto();
-  const metrics::HistogramEventProto& histogram_proto =
-      uma_proto->histogram_event(uma_proto->histogram_event_size() - 1);
-
-  // Buckets with samples: 1-5, 5-7, 8-9, 10-11, 11-12.
-  // Should become: 1-/, 5-7, /-9, 10-/, /-12.
-  ASSERT_EQ(5, histogram_proto.bucket_size());
-
-  // 1-5 becomes 1-/ (max is same as next min).
-  EXPECT_TRUE(histogram_proto.bucket(0).has_min());
-  EXPECT_FALSE(histogram_proto.bucket(0).has_max());
-  EXPECT_EQ(1, histogram_proto.bucket(0).min());
-
-  // 5-7 stays 5-7 (no optimization possible).
-  EXPECT_TRUE(histogram_proto.bucket(1).has_min());
-  EXPECT_TRUE(histogram_proto.bucket(1).has_max());
-  EXPECT_EQ(5, histogram_proto.bucket(1).min());
-  EXPECT_EQ(7, histogram_proto.bucket(1).max());
-
-  // 8-9 becomes /-9 (min is same as max - 1).
-  EXPECT_FALSE(histogram_proto.bucket(2).has_min());
-  EXPECT_TRUE(histogram_proto.bucket(2).has_max());
-  EXPECT_EQ(9, histogram_proto.bucket(2).max());
-
-  // 10-11 becomes 10-/ (both optimizations apply, omit max is prioritized).
-  EXPECT_TRUE(histogram_proto.bucket(3).has_min());
-  EXPECT_FALSE(histogram_proto.bucket(3).has_max());
-  EXPECT_EQ(10, histogram_proto.bucket(3).min());
-
-  // 11-12 becomes /-12 (last record must keep max, min is same as max - 1).
-  EXPECT_FALSE(histogram_proto.bucket(4).has_min());
-  EXPECT_TRUE(histogram_proto.bucket(4).has_max());
-  EXPECT_EQ(12, histogram_proto.bucket(4).max());
-}
-
-}  // namespace metrics
diff --git a/metricsd/uploader/metricsd_service_runner.cc b/metricsd/uploader/metricsd_service_runner.cc
deleted file mode 100644
index 4361cac..0000000
--- a/metricsd/uploader/metricsd_service_runner.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/metricsd_service_runner.h"
-
-#include <thread>
-
-#include <binder/IServiceManager.h>
-#include <brillo/binder_watcher.h>
-#include <brillo/message_loops/base_message_loop.h>
-#include <utils/Errors.h>
-
-#include "uploader/bn_metricsd_impl.h"
-
-MetricsdServiceRunner::MetricsdServiceRunner(
-    std::shared_ptr<CrashCounters> counters)
-    : counters_(counters) {}
-
-void MetricsdServiceRunner::Start() {
-  thread_.reset(new std::thread(&MetricsdServiceRunner::Run, this));
-}
-
-void MetricsdServiceRunner::Run() {
-  android::sp<BnMetricsdImpl> metrics_service(new BnMetricsdImpl(counters_));
-
-  android::status_t status = android::defaultServiceManager()->addService(
-      metrics_service->getInterfaceDescriptor(), metrics_service);
-  CHECK(status == android::OK) << "Metricsd service registration failed";
-
-  message_loop_for_io_.reset(new base::MessageLoopForIO);
-  message_loop_.reset(new brillo::BaseMessageLoop(message_loop_for_io_.get()));
-
-  brillo::BinderWatcher watcher(message_loop_.get());
-  CHECK(watcher.Init()) << "failed to initialize the binder file descriptor "
-                        << "watcher";
-
-  message_loop_->Run();
-
-  // Delete the message loop here as it needs to be deconstructed in the thread
-  // it is attached to.
-  message_loop_.reset();
-  message_loop_for_io_.reset();
-}
-
-void MetricsdServiceRunner::Stop() {
-  message_loop_for_io_->PostTask(FROM_HERE,
-                                 message_loop_for_io_->QuitWhenIdleClosure());
-
-  thread_->join();
-}
diff --git a/metricsd/uploader/metricsd_service_runner.h b/metricsd/uploader/metricsd_service_runner.h
deleted file mode 100644
index f5dad21..0000000
--- a/metricsd/uploader/metricsd_service_runner.h
+++ /dev/null
@@ -1,49 +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.
- */
-
-#ifndef METRICS_UPLOADER_METRISCD_SERVICE_RUNNER_H_
-#define METRICS_UPLOADER_METRISCD_SERVICE_RUNNER_H_
-
-#include <memory>
-#include <thread>
-
-#include <base/message_loop/message_loop.h>
-#include <brillo/message_loops/message_loop.h>
-
-#include "uploader/crash_counters.h"
-
-class MetricsdServiceRunner {
- public:
-  MetricsdServiceRunner(std::shared_ptr<CrashCounters> counters);
-
-  // Start the Metricsd Binder service in a new thread.
-  void Start();
-
-  // Stop the Metricsd service and wait for its thread to exit.
-  void Stop();
-
- private:
-  // Creates and run the main loop for metricsd's Binder service.
-  void Run();
-
-  std::unique_ptr<base::MessageLoopForIO> message_loop_for_io_;
-  std::unique_ptr<brillo::MessageLoop> message_loop_;
-
-  std::unique_ptr<std::thread> thread_;
-  std::shared_ptr<CrashCounters> counters_;
-};
-
-#endif  // METRICS_UPLOADER_METRISCD_SERVICE_RUNNER_H_
diff --git a/metricsd/uploader/mock/mock_system_profile_setter.h b/metricsd/uploader/mock/mock_system_profile_setter.h
deleted file mode 100644
index 9b20291..0000000
--- a/metricsd/uploader/mock/mock_system_profile_setter.h
+++ /dev/null
@@ -1,34 +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.
- */
-
-#ifndef METRICS_UPLOADER_MOCK_MOCK_SYSTEM_PROFILE_SETTER_H_
-#define METRICS_UPLOADER_MOCK_MOCK_SYSTEM_PROFILE_SETTER_H_
-
-#include "uploader/system_profile_setter.h"
-
-namespace metrics {
-class ChromeUserMetricsExtension;
-}
-
-// Mock profile setter used for testing.
-class MockSystemProfileSetter : public SystemProfileSetter {
- public:
-  bool Populate(metrics::ChromeUserMetricsExtension* profile_proto) override {
-    return true;
-  }
-};
-
-#endif  // METRICS_UPLOADER_MOCK_MOCK_SYSTEM_PROFILE_SETTER_H_
diff --git a/metricsd/uploader/mock/sender_mock.cc b/metricsd/uploader/mock/sender_mock.cc
deleted file mode 100644
index bb4dc7d..0000000
--- a/metricsd/uploader/mock/sender_mock.cc
+++ /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.
- */
-
-#include "uploader/mock/sender_mock.h"
-
-SenderMock::SenderMock() {
-  Reset();
-}
-
-bool SenderMock::Send(const std::string& content, const std::string& hash) {
-  send_call_count_ += 1;
-  last_message_ = content;
-  is_good_proto_ = last_message_proto_.ParseFromString(content);
-  return should_succeed_;
-}
-
-void SenderMock::Reset() {
-  send_call_count_ = 0;
-  last_message_ = "";
-  should_succeed_ = true;
-  last_message_proto_.Clear();
-  is_good_proto_ = false;
-}
diff --git a/metricsd/uploader/mock/sender_mock.h b/metricsd/uploader/mock/sender_mock.h
deleted file mode 100644
index e79233f..0000000
--- a/metricsd/uploader/mock/sender_mock.h
+++ /dev/null
@@ -1,60 +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.
- */
-
-#ifndef METRICS_UPLOADER_MOCK_SENDER_MOCK_H_
-#define METRICS_UPLOADER_MOCK_SENDER_MOCK_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-#include "uploader/sender.h"
-
-class SenderMock : public Sender {
- public:
-  SenderMock();
-
-  bool Send(const std::string& content, const std::string& hash) override;
-  void Reset();
-
-  bool is_good_proto() { return is_good_proto_; }
-  int send_call_count() { return send_call_count_; }
-  const std::string last_message() { return last_message_; }
-  metrics::ChromeUserMetricsExtension last_message_proto() {
-    return last_message_proto_;
-  }
-  void set_should_succeed(bool succeed) { should_succeed_ = succeed; }
-
- private:
-  // Is set to true if the proto was parsed successfully.
-  bool is_good_proto_;
-
-  // If set to true, the Send method will return true to simulate a successful
-  // send.
-  bool should_succeed_;
-
-  // Count of how many times Send was called since the last reset.
-  int send_call_count_;
-
-  // Last message received by Send.
-  std::string last_message_;
-
-  // If is_good_proto is true, last_message_proto is the deserialized
-  // representation of last_message.
-  metrics::ChromeUserMetricsExtension last_message_proto_;
-};
-
-#endif  // METRICS_UPLOADER_MOCK_SENDER_MOCK_H_
diff --git a/metricsd/uploader/proto/README b/metricsd/uploader/proto/README
deleted file mode 100644
index 4292a40..0000000
--- a/metricsd/uploader/proto/README
+++ /dev/null
@@ -1,37 +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.
-
-
-
-
-This directory contains the protocol buffers used by the standalone metrics
-uploader. Those protobuffers are copied from the chromium protobuffers from
-https://chromium.googlesource.com/chromium/src/+/master/components/metrics/proto/
-at 3bfe5f2b4c03d2cac718d137ed14cd2c6354bfed.
-
-Any change to this protobuf must first be made to the backend's protobuf and be
-compatible with the chromium protobuffers.
-
-
-Q: Why fork the chromium protobuffers ?
-A: The standalone metrics uploader needs chromium os fields that are not defined
-by the chromium protobufs. Instead of pushing chromium os specific changes to
-chromium, we can add them only to chromium os (and to the backend of course).
-
-
-Q: What's the difference between those protobuffers and chromium's protobuffers?
-A: When the protobuffers were copied, some chromium specific protobuffers were
-not imported:
-* omnibox related protobuffers.
-* performance profiling protobuffers (not used in chromium os).
diff --git a/metricsd/uploader/proto/chrome_user_metrics_extension.proto b/metricsd/uploader/proto/chrome_user_metrics_extension.proto
deleted file mode 100644
index a07830f..0000000
--- a/metricsd/uploader/proto/chrome_user_metrics_extension.proto
+++ /dev/null
@@ -1,72 +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.
- */
-//
-// Protocol buffer for Chrome UMA (User Metrics Analysis).
-//
-// Note: this protobuf must be compatible with the one in chromium.
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-option java_outer_classname = "ChromeUserMetricsExtensionProtos";
-option java_package = "org.chromium.components.metrics";
-
-package metrics;
-
-import "system/core/metricsd/uploader/proto/histogram_event.proto";
-import "system/core/metricsd/uploader/proto/system_profile.proto";
-import "system/core/metricsd/uploader/proto/user_action_event.proto";
-
-// Next tag: 13
-message ChromeUserMetricsExtension {
-  // The product (i.e. end user application) for a given UMA log.
-  enum Product {
-    // Google Chrome product family.
-    CHROME = 0;
-  }
-  // The product corresponding to this log. The field type is int32 instead of
-  // Product so that downstream users of the Chromium metrics component can
-  // introduce products without needing to make changes to the Chromium code
-  // (though they still need to add the new product to the server-side enum).
-  // Note: The default value is Chrome, so Chrome products will not transmit
-  // this field.
-  optional int32 product = 10 [default = 0];
-
-  // The id of the client install that generated these events.
-  //
-  // For Chrome clients, this id is unique to a top-level (one level above the
-  // "Default" directory) Chrome user data directory [1], and so is shared among
-  // all Chrome user profiles contained in this user data directory.
-  // An id of 0 is reserved for test data (monitoring and internal testing) and
-  // should normally be ignored in analysis of the data.
-  // [1] http://www.chromium.org/user-experience/user-data-directory
-  optional fixed64 client_id = 1;
-
-  // The session id for this user.
-  // Values such as tab ids are only meaningful within a particular session.
-  // The client keeps track of the session id and sends it with each event.
-  // The session id is simply an integer that is incremented each time the user
-  // relaunches Chrome.
-  optional int32 session_id = 2;
-
-  // Information about the user's browser and system configuration.
-  optional SystemProfileProto system_profile = 3;
-
-  // This message will log one or more of the following event types:
-  repeated UserActionEventProto user_action_event = 4;
-  repeated HistogramEventProto histogram_event = 6;
-
-}
diff --git a/metricsd/uploader/proto/histogram_event.proto b/metricsd/uploader/proto/histogram_event.proto
deleted file mode 100644
index 3825063..0000000
--- a/metricsd/uploader/proto/histogram_event.proto
+++ /dev/null
@@ -1,59 +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.
- */
-//
-// Histogram-collected metrics.
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-option java_outer_classname = "HistogramEventProtos";
-option java_package = "org.chromium.components.metrics";
-
-package metrics;
-
-// Next tag: 4
-message HistogramEventProto {
-  // The name of the histogram, hashed.
-  optional fixed64 name_hash = 1;
-
-  // The sum of all the sample values.
-  // Together with the total count of the sample values, this allows us to
-  // compute the average value.  The count of all sample values is just the sum
-  // of the counts of all the buckets.
-  optional int64 sum = 2;
-
-  // The per-bucket data.
-  message Bucket {
-    // Each bucket's range is bounded by min <= x < max.
-    // It is valid to omit one of these two fields in a bucket, but not both.
-    // If the min field is omitted, its value is assumed to be equal to max - 1.
-    // If the max field is omitted, its value is assumed to be equal to the next
-    // bucket's min value (possibly computed per above).  The last bucket in a
-    // histogram should always include the max field.
-    optional int64 min = 1;
-    optional int64 max = 2;
-
-    // The bucket's index in the list of buckets, sorted in ascending order.
-    // This field was intended to provide extra redundancy to detect corrupted
-    // records, but was never used.  As of M31, it is no longer sent by Chrome
-    // clients to reduce the UMA upload size.
-    optional int32 bucket_index = 3 [deprecated = true];
-
-    // The number of entries in this bucket.
-    optional int64 count = 4;
-  }
-  repeated Bucket bucket = 3;
-}
diff --git a/metricsd/uploader/proto/system_profile.proto b/metricsd/uploader/proto/system_profile.proto
deleted file mode 100644
index bac828b..0000000
--- a/metricsd/uploader/proto/system_profile.proto
+++ /dev/null
@@ -1,759 +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.
- */
-//
-// Stores information about the user's brower and system configuration.
-// The system configuration fields are recorded once per client session.
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-option java_outer_classname = "SystemProfileProtos";
-option java_package = "org.chromium.components.metrics";
-
-package metrics;
-
-// Next tag: 21
-message SystemProfileProto {
-  // The time when the client was compiled/linked, in seconds since the epoch.
-  optional int64 build_timestamp = 1;
-
-  // A version number string for the application.
-  // Most commonly this is the browser version number found in a user agent
-  // string, and is typically a 4-tuple of numbers separated by periods.  In
-  // cases where the user agent version might be ambiguous (example: Linux 64-
-  // bit build, rather than 32-bit build, or a Windows version used in some
-  // special context, such as ChromeFrame running in IE), then this may include
-  // some additional postfix to provide clarification not available in the UA
-  // string.
-  //
-  // An example of a browser version 4-tuple is "5.0.322.0".  Currently used
-  // postfixes are:
-  //
-  //   "-64": a 64-bit build
-  //   "-F": Chrome is running under control of ChromeFrame
-  //   "-devel": this is not an official build of Chrome
-  //
-  // A full version number string could look similar to:
-  // "5.0.322.0-F-devel".
-  //
-  // This value, when available, is more trustworthy than the UA string
-  // associated with the request; and including the postfix, may be more
-  // specific.
-  optional string app_version = 2;
-
-  // The brand code or distribution tag assigned to a partner, if available.
-  // Brand codes are only available on Windows.  Not every Windows install
-  // though will have a brand code.
-  optional string brand_code = 12;
-
-  // The possible channels for an installation, from least to most stable.
-  enum Channel {
-    CHANNEL_UNKNOWN = 0;  // Unknown channel -- perhaps an unofficial build?
-    CHANNEL_CANARY = 1;
-    CHANNEL_DEV = 2;
-    CHANNEL_BETA = 3;
-    CHANNEL_STABLE = 4;
-  }
-  optional Channel channel = 10;
-
-  // True if Chrome build is ASan-instrumented.
-  optional bool is_asan_build = 20 [default = false];
-
-  // The date the user enabled UMA, in seconds since the epoch.
-  // If the user has toggled the UMA enabled state multiple times, this will
-  // be the most recent date on which UMA was enabled.
-  // For privacy, this is rounded to the nearest hour.
-  optional int64 uma_enabled_date = 3;
-
-  // The time when the client was installed, in seconds since the epoch.
-  // For privacy, this is rounded to the nearest hour.
-  optional int64 install_date = 16;
-
-  // The user's selected application locale, i.e. the user interface language.
-  // The locale includes a language code and, possibly, also a country code,
-  // e.g. "en-US".
-  optional string application_locale = 4;
-
-  message BrilloDeviceData {
-    optional string product_id = 1;
-  }
-  optional BrilloDeviceData brillo = 21;
-
-  // Information on the user's operating system.
-  message OS {
-    // The user's operating system. This should be one of:
-    // - Android
-    // - Windows NT
-    // - Linux (includes ChromeOS)
-    // - iPhone OS
-    // - Mac OS X
-    optional string name = 1;
-
-    // The version of the OS.  The meaning of this field is OS-dependent.
-    optional string version = 2;
-
-    // The fingerprint of the build.  This field is used only on Android.
-    optional string fingerprint = 3;
-
-    // Whether the version of iOS appears to be "jailbroken". This field is
-    // used only on iOS. Chrome for iOS detects whether device contains a
-    // DynamicLibraries/ directory. It's a necessary but insufficient indicator
-    // of whether the operating system has been jailbroken.
-    optional bool is_jailbroken = 4;
-  }
-  optional OS os = 5;
-
-  // Next tag for Hardware: 18
-  // Information on the user's hardware.
-  message Hardware {
-    // The CPU architecture (x86, PowerPC, x86_64, ...)
-    optional string cpu_architecture = 1;
-
-    // The amount of RAM present on the system, in megabytes.
-    optional int64 system_ram_mb = 2;
-
-    // The base memory address that chrome.dll was loaded at.
-    // (Logged only on Windows.)
-    optional int64 dll_base = 3;
-
-    // The Chrome OS device hardware class ID is a unique string associated with
-    // each Chrome OS device product revision generally assigned at hardware
-    // qualification time.  The hardware class effectively identifies the
-    // configured system components such as CPU, WiFi adapter, etc.
-    //
-    // An example of such a hardware class is "IEC MARIO PONY 6101".  An
-    // internal database associates this hardware class with the qualified
-    // device specifications including OEM information, schematics, hardware
-    // qualification reports, test device tags, etc.
-    optional string hardware_class = 4;
-
-    // The number of physical screens.
-    optional int32 screen_count = 5;
-
-    // The screen dimensions of the primary screen, in pixels.
-    optional int32 primary_screen_width = 6;
-    optional int32 primary_screen_height = 7;
-
-    // The device scale factor of the primary screen.
-    optional float primary_screen_scale_factor = 12;
-
-    // Max DPI for any attached screen. (Windows only)
-    optional float max_dpi_x = 9;
-    optional float max_dpi_y = 10;
-
-    // Information on the CPU obtained by CPUID.
-    message CPU {
-      // A 12 character string naming the vendor, e.g. "GeniuneIntel".
-      optional string vendor_name = 1;
-
-      // The signature reported by CPUID (from EAX).
-      optional uint32 signature = 2;
-
-      // Number of logical processors/cores on the current machine.
-      optional uint32 num_cores = 3;
-    }
-    optional CPU cpu = 13;
-
-    // Information on the GPU
-    message Graphics {
-      // The GPU manufacturer's vendor id.
-      optional uint32 vendor_id = 1;
-
-      // The GPU manufacturer's device id for the chip set.
-      optional uint32 device_id = 2;
-
-      // The driver version on the GPU.
-      optional string driver_version = 3;
-
-      // The driver date on the GPU.
-      optional string driver_date = 4;
-
-      // The GL_VENDOR string. An example of a gl_vendor string is
-      // "Imagination Technologies". "" if we are not using OpenGL.
-      optional string gl_vendor = 6;
-
-      // The GL_RENDERER string. An example of a gl_renderer string is
-      // "PowerVR SGX 540". "" if we are not using OpenGL.
-      optional string gl_renderer = 7;
-    }
-    optional Graphics gpu = 8;
-
-    // Information about Bluetooth devices paired with the system.
-    message Bluetooth {
-      // Whether Bluetooth is present on this system.
-      optional bool is_present = 1;
-
-      // Whether Bluetooth is enabled on this system.
-      optional bool is_enabled = 2;
-
-      // Describes a paired device.
-      message PairedDevice {
-        // Assigned class of the device. This is a bitfield according to the
-        // Bluetooth specification available at the following URL:
-        // https://www.bluetooth.org/en-us/specification/assigned-numbers-overview/baseband
-        optional uint32 bluetooth_class = 1;
-
-        // Decoded device type.
-        enum Type {
-          DEVICE_UNKNOWN = 0;
-          DEVICE_COMPUTER = 1;
-          DEVICE_PHONE = 2;
-          DEVICE_MODEM = 3;
-          DEVICE_AUDIO = 4;
-          DEVICE_CAR_AUDIO = 5;
-          DEVICE_VIDEO = 6;
-          DEVICE_PERIPHERAL = 7;
-          DEVICE_JOYSTICK = 8;
-          DEVICE_GAMEPAD = 9;
-          DEVICE_KEYBOARD = 10;
-          DEVICE_MOUSE = 11;
-          DEVICE_TABLET = 12;
-          DEVICE_KEYBOARD_MOUSE_COMBO = 13;
-        }
-        optional Type type = 2;
-
-        // Vendor prefix of the Bluetooth address, these are OUI registered by
-        // the IEEE and are encoded with the first byte in bits 16-23, the
-        // second byte in bits 8-15 and the third byte in bits 0-7.
-        //
-        // ie. Google's OUI (00:1A:11) is encoded as 0x00001A11
-        optional uint32 vendor_prefix = 4;
-
-        // The Vendor ID of a device, returned in vendor_id below, can be
-        // either allocated by the Bluetooth SIG or USB IF, providing two
-        // completely overlapping namespaces for identifiers.
-        //
-        // This field should be read along with vendor_id to correctly
-        // identify the vendor. For example Google is identified by either
-        // vendor_id_source = VENDOR_ID_BLUETOOTH, vendor_id = 0x00E0 or
-        // vendor_id_source = VENDOR_ID_USB, vendor_id = 0x18D1.
-        //
-        // If the device does not support the Device ID specification the
-        // unknown value will be set.
-        enum VendorIDSource {
-          VENDOR_ID_UNKNOWN = 0;
-          VENDOR_ID_BLUETOOTH = 1;
-          VENDOR_ID_USB = 2;
-        }
-        optional VendorIDSource vendor_id_source = 8;
-
-        // Vendor ID of the device, where available.
-        optional uint32 vendor_id = 5;
-
-        // Product ID of the device, where available.
-        optional uint32 product_id = 6;
-
-        // Device ID of the device, generally the release or version number in
-        // BCD format, where available.
-        optional uint32 device_id = 7;
-      }
-      repeated PairedDevice paired_device = 3;
-    }
-    optional Bluetooth bluetooth = 11;
-
-    // Whether the internal display produces touch events. Omitted if unknown.
-    // Logged on ChromeOS only.
-    optional bool internal_display_supports_touch = 14;
-
-    // Vendor ids and product ids of external touchscreens.
-    message TouchScreen {
-      // Touch screen vendor id.
-      optional uint32 vendor_id = 1;
-      // Touch screen product id.
-      optional uint32 product_id = 2;
-    }
-    // Lists vendor and product ids of external touchscreens.
-    // Logged on ChromeOS only.
-    repeated TouchScreen external_touchscreen = 15;
-
-    // Drive messages are currently logged on Windows 7+, iOS, and Android.
-    message Drive {
-      // Whether this drive incurs a time penalty when randomly accessed. This
-      // should be true for spinning disks but false for SSDs or other
-      // flash-based drives.
-      optional bool has_seek_penalty = 1;
-    }
-    // The drive that the application executable was loaded from.
-    optional Drive app_drive = 16;
-    // The drive that the current user data directory was loaded from.
-    optional Drive user_data_drive = 17;
-  }
-  optional Hardware hardware = 6;
-
-  // Information about the network connection.
-  message Network {
-    // Set to true if connection_type changed during the lifetime of the log.
-    optional bool connection_type_is_ambiguous = 1;
-
-    // See net::NetworkChangeNotifier::ConnectionType.
-    enum ConnectionType {
-      CONNECTION_UNKNOWN = 0;
-      CONNECTION_ETHERNET = 1;
-      CONNECTION_WIFI = 2;
-      CONNECTION_2G = 3;
-      CONNECTION_3G = 4;
-      CONNECTION_4G = 5;
-      CONNECTION_BLUETOOTH = 6;
-    }
-    // The connection type according to NetworkChangeNotifier.
-    optional ConnectionType connection_type = 2;
-
-    // Set to true if wifi_phy_layer_protocol changed during the lifetime of the log.
-    optional bool wifi_phy_layer_protocol_is_ambiguous = 3;
-
-    // See net::WifiPHYLayerProtocol.
-    enum WifiPHYLayerProtocol {
-      WIFI_PHY_LAYER_PROTOCOL_NONE = 0;
-      WIFI_PHY_LAYER_PROTOCOL_ANCIENT = 1;
-      WIFI_PHY_LAYER_PROTOCOL_A = 2;
-      WIFI_PHY_LAYER_PROTOCOL_B = 3;
-      WIFI_PHY_LAYER_PROTOCOL_G = 4;
-      WIFI_PHY_LAYER_PROTOCOL_N = 5;
-      WIFI_PHY_LAYER_PROTOCOL_UNKNOWN = 6;
-    }
-    // The physical layer mode of the associated wifi access point, if any.
-    optional WifiPHYLayerProtocol wifi_phy_layer_protocol = 4;
-
-    // Describe wifi access point information.
-    message WifiAccessPoint {
-      // Vendor prefix of the access point's BSSID, these are OUIs
-      // (Organizationally Unique Identifiers) registered by
-      // the IEEE and are encoded with the first byte in bits 16-23, the
-      // second byte in bits 8-15 and the third byte in bits 0-7.
-      optional uint32 vendor_prefix = 1;
-
-      // Access point seurity mode definitions.
-      enum SecurityMode {
-        SECURITY_UNKNOWN = 0;
-        SECURITY_WPA = 1;
-        SECURITY_WEP = 2;
-        SECURITY_RSN = 3;
-        SECURITY_802_1X = 4;
-        SECURITY_PSK = 5;
-        SECURITY_NONE = 6;
-      }
-      // The security mode of the access point.
-      optional SecurityMode security_mode = 2;
-
-      // Vendor specific information.
-      message VendorInformation {
-        // The model number, for example "0".
-        optional string model_number = 1;
-
-        // The model name (sometimes the same as the model_number),
-        // for example "WZR-HP-AG300H".
-        optional string model_name = 2;
-
-        // The device name (sometimes the same as the model_number),
-        // for example "Dummynet"
-        optional string device_name = 3;
-
-        // The list of vendor-specific OUIs (Organziationally Unqiue
-        // Identifiers). These are provided by the vendor through WPS
-        // (Wireless Provisioning Service) information elements, which
-        // identifies the content of the element.
-        repeated uint32 element_identifier = 4;
-      }
-      // The wireless access point vendor information.
-      optional VendorInformation vendor_info = 3;
-    }
-    // Information of the wireless AP that device is connected to.
-    optional WifiAccessPoint access_point_info = 5;
-  }
-  optional Network network = 13;
-
-  // Information on the Google Update install that is managing this client.
-  message GoogleUpdate {
-    // Whether the Google Update install is system-level or user-level.
-    optional bool is_system_install = 1;
-
-    // The date at which Google Update last started performing an automatic
-    // update check, in seconds since the Unix epoch.
-    optional int64 last_automatic_start_timestamp = 2;
-
-    // The date at which Google Update last successfully sent an update check
-    // and recieved an intact response from the server, in seconds since the
-    // Unix epoch. (The updates don't need to be successfully installed.)
-    optional int64 last_update_check_timestamp = 3;
-
-    // Describes a product being managed by Google Update. (This can also
-    // describe Google Update itself.)
-    message ProductInfo {
-      // The current version of the product that is installed.
-      optional string version = 1;
-
-      // The date at which Google Update successfully updated this product,
-      // stored in seconds since the Unix epoch.  This is updated when an update
-      // is successfully applied, or if the server reports that no update
-      // is available.
-      optional int64 last_update_success_timestamp = 2;
-
-      // The result reported by the product updater on its last run.
-      enum InstallResult {
-        INSTALL_RESULT_SUCCESS = 0;
-        INSTALL_RESULT_FAILED_CUSTOM_ERROR = 1;
-        INSTALL_RESULT_FAILED_MSI_ERROR = 2;
-        INSTALL_RESULT_FAILED_SYSTEM_ERROR = 3;
-        INSTALL_RESULT_EXIT_CODE = 4;
-      }
-      optional InstallResult last_result = 3;
-
-      // The error code reported by the product updater on its last run.  This
-      // will typically be a error code specific to the product installer.
-      optional int32 last_error = 4;
-
-      // The extra error code reported by the product updater on its last run.
-      // This will typically be a Win32 error code.
-      optional int32 last_extra_error = 5;
-    }
-    optional ProductInfo google_update_status = 4;
-    optional ProductInfo client_status = 5;
-  }
-  optional GoogleUpdate google_update = 11;
-
-  // Information on all installed plugins.
-  message Plugin {
-    // The plugin's self-reported name and filename (without path).
-    optional string name = 1;
-    optional string filename = 2;
-
-    // The plugin's version.
-    optional string version = 3;
-
-    // True if the plugin is disabled.
-    // If a client has multiple local Chrome user accounts, this is logged based
-    // on the first user account launched during the current session.
-    optional bool is_disabled = 4;
-
-    // True if the plugin is PPAPI.
-    optional bool is_pepper = 5;
-  }
-  repeated Plugin plugin = 7;
-
-  // Figures that can be used to generate application stability metrics.
-  // All values are counts of events since the last time that these
-  // values were reported.
-  // Next tag: 24
-  message Stability {
-    // Total amount of time that the program was running, in seconds,
-    // since the last time a log was recorded, as measured using a client-side
-    // clock implemented via TimeTicks, which guarantees that it is monotonic
-    // and does not jump if the user changes his/her clock.  The TimeTicks
-    // implementation also makes the clock not count time the computer is
-    // suspended.
-    optional int64 incremental_uptime_sec = 1;
-
-    // Total amount of time that the program was running, in seconds,
-    // since startup, as measured using a client-side clock implemented
-    // via TimeTicks, which guarantees that it is monotonic and does not
-    // jump if the user changes his/her clock.  The TimeTicks implementation
-    // also makes the clock not count time the computer is suspended.
-    // This field was added for M-35.
-    optional int64 uptime_sec = 23;
-
-    // Page loads along with renderer crashes and hangs, since page load count
-    // roughly corresponds to usage.
-    optional int32 page_load_count = 2;
-    optional int32 renderer_crash_count = 3;
-    optional int32 renderer_hang_count = 4;
-
-    // Number of renderer crashes that were for extensions. These crashes are
-    // not counted in renderer_crash_count.
-    optional int32 extension_renderer_crash_count = 5;
-
-    // Number of non-renderer child process crashes.
-    optional int32 child_process_crash_count = 6;
-
-    // Number of times the browser has crashed while logged in as the "other
-    // user" (guest) account.
-    // Logged on ChromeOS only.
-    optional int32 other_user_crash_count = 7;
-
-    // Number of times the kernel has crashed.
-    // Logged on ChromeOS only.
-    optional int32 kernel_crash_count = 8;
-
-    // Number of times the system has shut down uncleanly.
-    // Logged on ChromeOS only.
-    optional int32 unclean_system_shutdown_count = 9;
-
-    //
-    // All the remaining fields in the Stability are recorded at most once per
-    // client session.
-    //
-
-    // The number of times the program was launched.
-    // This will typically be equal to 1.  However, it is possible that Chrome
-    // was unable to upload stability metrics for previous launches (e.g. due to
-    // crashing early during startup), and hence this value might be greater
-    // than 1.
-    optional int32 launch_count = 15;
-    // The number of times that it didn't exit cleanly (which we assume to be
-    // mostly crashes).
-    optional int32 crash_count = 16;
-
-    // The number of times the program began, but did not complete, the shutdown
-    // process.  (For example, this may occur when Windows is shutting down, and
-    // it only gives the process a few seconds to clean up.)
-    optional int32 incomplete_shutdown_count = 17;
-
-    // The number of times the program was able register with breakpad crash
-    // services.
-    optional int32 breakpad_registration_success_count = 18;
-
-    // The number of times the program failed to register with breakpad crash
-    // services.  If crash registration fails then when the program crashes no
-    // crash report will be generated.
-    optional int32 breakpad_registration_failure_count = 19;
-
-    // The number of times the program has run under a debugger.  This should
-    // be an exceptional condition.  Running under a debugger prevents crash
-    // dumps from being generated.
-    optional int32 debugger_present_count = 20;
-
-    // The number of times the program has run without a debugger attached.
-    // This should be most common scenario and should be very close to
-    // |launch_count|.
-    optional int32 debugger_not_present_count = 21;
-
-    // Stability information for all installed plugins.
-    message PluginStability {
-      // The relevant plugin's information (name, etc.)
-      optional Plugin plugin = 1;
-
-      // The number of times this plugin's process was launched.
-      optional int32 launch_count = 2;
-
-      // The number of times this plugin was instantiated on a web page.
-      // This will be >= |launch_count|.
-      // (A page load with multiple sections drawn by this plugin will
-      // increase this count multiple times.)
-      optional int32 instance_count = 3;
-
-      // The number of times this plugin process crashed.
-      // This value will be <= |launch_count|.
-      optional int32 crash_count = 4;
-
-      // The number of times this plugin could not be loaded.
-      optional int32 loading_error_count = 5;
-    }
-    repeated PluginStability plugin_stability = 22;
-  }
-  optional Stability stability = 8;
-
-  // Description of a field trial or experiment that the user is currently
-  // enrolled in.
-  // All metrics reported in this upload can potentially be influenced by the
-  // field trial.
-  message FieldTrial {
-    // The name of the field trial, as a 32-bit identifier.
-    // Currently, the identifier is a hash of the field trial's name.
-    optional fixed32 name_id = 1;
-
-    // The user's group within the field trial, as a 32-bit identifier.
-    // Currently, the identifier is a hash of the group's name.
-    optional fixed32 group_id = 2;
-  }
-  repeated FieldTrial field_trial = 9;
-
-  // Information about the A/V output device(s) (typically just a TV).
-  // However, a configuration may have one or more intermediate A/V devices
-  // between the source device and the TV (e.g. an A/V receiver, video
-  // processor, etc.).
-  message ExternalAudioVideoDevice {
-    // The manufacturer name (possibly encoded as a 3-letter code, e.g. "YMH"
-    // for Yamaha).
-    optional string manufacturer_name = 1;
-
-    // The model name (e.g. "RX-V1900"). Some devices may report generic names
-    // like "receiver" or use the full manufacturer name (e.g "PHILIPS").
-    optional string model_name = 2;
-
-    // The product code (e.g. "0218").
-    optional string product_code = 3;
-
-    // The device types. A single device can have multiple types (e.g. a set-top
-    // box could be both a tuner and a player).  The same type may even be
-    // repeated (e.g a device that reports two tuners).
-    enum AVDeviceType {
-      AV_DEVICE_TYPE_UNKNOWN = 0;
-      AV_DEVICE_TYPE_TV = 1;
-      AV_DEVICE_TYPE_RECORDER = 2;
-      AV_DEVICE_TYPE_TUNER = 3;
-      AV_DEVICE_TYPE_PLAYER = 4;
-      AV_DEVICE_TYPE_AUDIO_SYSTEM = 5;
-    }
-    repeated AVDeviceType av_device_type = 4;
-
-    // The year of manufacture.
-    optional int32 manufacture_year = 5;
-
-    // The week of manufacture.
-    // Note: per the Wikipedia EDID article, numbering for this field may not
-    // be consistent between manufacturers.
-    optional int32 manufacture_week = 6;
-
-    // Max horizontal resolution in pixels.
-    optional int32 horizontal_resolution = 7;
-
-    // Max vertical resolution in pixels.
-    optional int32 vertical_resolution = 8;
-
-    // Audio capabilities of the device.
-    // Ref: http://en.wikipedia.org/wiki/Extended_display_identification_data
-    message AudioDescription {
-      // Audio format
-      enum AudioFormat {
-        AUDIO_FORMAT_UNKNOWN = 0;
-        AUDIO_FORMAT_LPCM = 1;
-        AUDIO_FORMAT_AC_3 = 2;
-        AUDIO_FORMAT_MPEG1 = 3;
-        AUDIO_FORMAT_MP3 = 4;
-        AUDIO_FORMAT_MPEG2 = 5;
-        AUDIO_FORMAT_AAC = 6;
-        AUDIO_FORMAT_DTS = 7;
-        AUDIO_FORMAT_ATRAC = 8;
-        AUDIO_FORMAT_ONE_BIT = 9;
-        AUDIO_FORMAT_DD_PLUS = 10;
-        AUDIO_FORMAT_DTS_HD = 11;
-        AUDIO_FORMAT_MLP_DOLBY_TRUEHD = 12;
-        AUDIO_FORMAT_DST_AUDIO = 13;
-        AUDIO_FORMAT_MICROSOFT_WMA_PRO = 14;
-      }
-      optional AudioFormat audio_format = 1;
-
-      // Number of channels (e.g. 1, 2, 8, etc.).
-      optional int32 num_channels = 2;
-
-      // Supported sample frequencies in Hz (e.g. 32000, 44100, etc.).
-      // Multiple frequencies may be specified.
-      repeated int32 sample_frequency_hz = 3;
-
-      // Maximum bit rate in bits/s.
-      optional int32 max_bit_rate_per_second = 4;
-
-      // Bit depth (e.g. 16, 20, 24, etc.).
-      optional int32 bit_depth = 5;
-    }
-    repeated AudioDescription audio_description = 9;
-
-    // The position in AV setup.
-    // A value of 0 means this device is the TV.
-    // A value of 1 means this device is directly connected to one of
-    // the TV's inputs.
-    // Values > 1 indicate there are 1 or more devices between this device
-    // and the TV.
-    optional int32 position_in_setup = 10;
-
-    // Whether this device is in the path to the TV.
-    optional bool is_in_path_to_tv = 11;
-
-    // The CEC version the device supports.
-    // CEC stands for Consumer Electronics Control, a part of the HDMI
-    // specification.  Not all HDMI devices support CEC.
-    // Only devices that support CEC will report a value here.
-    optional int32 cec_version = 12;
-
-    // This message reports CEC commands seen by a device.
-    // After each log is sent, this information is cleared and gathered again.
-    // By collecting CEC status information by opcode we can determine
-    // which CEC features can be supported.
-    message CECCommand {
-      // The CEC command opcode.  CEC supports up to 256 opcodes.
-      // We add only one CECCommand message per unique opcode.  Only opcodes
-      // seen by the device will be reported. The remainder of the message
-      // accumulates status for this opcode (and device).
-      optional int32 opcode = 1;
-
-      // The total number of commands received from the external device.
-      optional int32 num_received_direct = 2;
-
-      // The number of commands received from the external device as part of a
-      // broadcast message.
-      optional int32 num_received_broadcast = 3;
-
-      // The total number of commands sent to the external device.
-      optional int32 num_sent_direct = 4;
-
-      // The number of commands sent to the external device as part of a
-      // broadcast message.
-      optional int32 num_sent_broadcast = 5;
-
-      // The number of aborted commands for unknown reasons.
-      optional int32 num_aborted_unknown_reason = 6;
-
-      // The number of aborted commands because of an unrecognized opcode.
-      optional int32 num_aborted_unrecognized = 7;
-    }
-    repeated CECCommand cec_command = 13;
-  }
-  repeated ExternalAudioVideoDevice external_audio_video_device = 14;
-
-  // Information about the current wireless access point. Collected directly
-  // from the wireless access point via standard apis if the device is
-  // connected to the Internet wirelessly. Introduced for Chrome on TV devices
-  // but also can be collected by ChromeOS, Android or other clients.
-  message ExternalAccessPoint {
-    // The manufacturer name, for example "ASUSTeK Computer Inc.".
-    optional string manufacturer = 1;
-
-    // The model name, for example "Wi-Fi Protected Setup Router".
-    optional string model_name = 2;
-
-    // The model number, for example "RT-N16".
-    optional string model_number = 3;
-
-    // The device name (sometime same as model_number), for example "RT-N16".
-    optional string device_name = 4;
-  }
-  optional ExternalAccessPoint external_access_point = 15;
-
-  // Number of users currently signed into a multiprofile session.
-  // A zero value indicates that the user count changed while the log is open.
-  // Logged only on ChromeOS.
-  optional uint32 multi_profile_user_count = 17;
-
-  // Information about extensions that are installed, masked to provide better
-  // privacy.  Only extensions from a single profile are reported; this will
-  // generally be the profile used when the browser is started.  The profile
-  // reported on will remain consistent at least until the browser is
-  // relaunched (or the profile is deleted by the user).
-  //
-  // Each client first picks a value for client_key derived from its UMA
-  // client_id:
-  //   client_key = client_id % 4096
-  // Then, each installed extension is mapped into a hash bucket according to
-  //   bucket = CityHash64(StringPrintf("%d:%s",
-  //                                    client_key, extension_id)) % 1024
-  // The client reports the set of hash buckets occupied by all installed
-  // extensions.  If multiple extensions map to the same bucket, that bucket is
-  // still only reported once.
-  repeated int32 occupied_extension_bucket = 18;
-
-  // The state of loaded extensions for this system. The system can have either
-  // no applicable extensions, extensions only from the webstore and verified by
-  // the webstore, extensions only from the webstore but not verified, or
-  // extensions not from the store. If there is a single off-store extension,
-  // then HAS_OFFSTORE is reported. This should be kept in sync with the
-  // corresponding enum in chrome/browser/metrics/extensions_metrics_provider.cc
-  enum ExtensionsState {
-    NO_EXTENSIONS = 0;
-    NO_OFFSTORE_VERIFIED = 1;
-    NO_OFFSTORE_UNVERIFIED = 2;
-    HAS_OFFSTORE = 3;
-  }
-  optional ExtensionsState offstore_extensions_state = 19;
-}
diff --git a/metricsd/uploader/proto/user_action_event.proto b/metricsd/uploader/proto/user_action_event.proto
deleted file mode 100644
index 464f3c8..0000000
--- a/metricsd/uploader/proto/user_action_event.proto
+++ /dev/null
@@ -1,35 +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.
- */
-//
-// Stores information about an event that occurs in response to a user action,
-// e.g. an interaction with a browser UI element.
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-option java_outer_classname = "UserActionEventProtos";
-option java_package = "org.chromium.components.metrics";
-
-package metrics;
-
-// Next tag: 3
-message UserActionEventProto {
-  // The name of the action, hashed.
-  optional fixed64 name_hash = 1;
-
-  // The timestamp for the event, in seconds since the epoch.
-  optional int64 time = 2;
-}
diff --git a/metricsd/uploader/sender.h b/metricsd/uploader/sender.h
deleted file mode 100644
index 369c9c2..0000000
--- a/metricsd/uploader/sender.h
+++ /dev/null
@@ -1,30 +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.
- */
-
-#ifndef METRICS_UPLOADER_SENDER_H_
-#define METRICS_UPLOADER_SENDER_H_
-
-#include <string>
-
-// Abstract class for a Sender that uploads a metrics message.
-class Sender {
- public:
-  virtual ~Sender() {}
-  // Sends a message |content| with its sha1 hash |hash|
-  virtual bool Send(const std::string& content, const std::string& hash) = 0;
-};
-
-#endif  // METRICS_UPLOADER_SENDER_H_
diff --git a/metricsd/uploader/sender_http.cc b/metricsd/uploader/sender_http.cc
deleted file mode 100644
index 4b572a6..0000000
--- a/metricsd/uploader/sender_http.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/sender_http.h"
-
-#include <string>
-
-#include <base/logging.h>
-#include <base/strings/string_number_conversions.h>
-#include <brillo/http/http_utils.h>
-#include <brillo/mime_utils.h>
-
-HttpSender::HttpSender(const std::string server_url)
-    : server_url_(server_url) {}
-
-bool HttpSender::Send(const std::string& content,
-                      const std::string& content_hash) {
-  const std::string hash =
-      base::HexEncode(content_hash.data(), content_hash.size());
-
-  brillo::http::HeaderList headers = {{"X-Chrome-UMA-Log-SHA1", hash}};
-  brillo::ErrorPtr error;
-  auto response = brillo::http::PostTextAndBlock(
-      server_url_,
-      content,
-      brillo::mime::application::kWwwFormUrlEncoded,
-      headers,
-      brillo::http::Transport::CreateDefault(),
-      &error);
-  if (!response || response->ExtractDataAsString() != "OK") {
-    if (error) {
-      DLOG(ERROR) << "Failed to send data: " << error->GetMessage();
-    }
-    return false;
-  }
-  return true;
-}
diff --git a/metricsd/uploader/sender_http.h b/metricsd/uploader/sender_http.h
deleted file mode 100644
index 4f1c08f..0000000
--- a/metricsd/uploader/sender_http.h
+++ /dev/null
@@ -1,41 +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.
- */
-
-#ifndef METRICS_UPLOADER_SENDER_HTTP_H_
-#define METRICS_UPLOADER_SENDER_HTTP_H_
-
-#include <string>
-
-#include <base/macros.h>
-
-#include "uploader/sender.h"
-
-// Sender implemented using http_utils from libbrillo
-class HttpSender : public Sender {
- public:
-  explicit HttpSender(std::string server_url);
-  ~HttpSender() override = default;
-  // Sends |content| whose SHA1 hash is |hash| to server_url with a synchronous
-  // POST request to server_url.
-  bool Send(const std::string& content, const std::string& hash) override;
-
- private:
-  const std::string server_url_;
-
-  DISALLOW_COPY_AND_ASSIGN(HttpSender);
-};
-
-#endif  // METRICS_UPLOADER_SENDER_HTTP_H_
diff --git a/metricsd/uploader/system_profile_cache.cc b/metricsd/uploader/system_profile_cache.cc
deleted file mode 100644
index e6f6617..0000000
--- a/metricsd/uploader/system_profile_cache.cc
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/system_profile_cache.h"
-
-#include <base/files/file_util.h>
-#include <base/guid.h>
-#include <base/logging.h>
-#include <base/strings/string_number_conversions.h>
-#include <base/strings/string_util.h>
-#include <brillo/osrelease_reader.h>
-#include <string>
-#include <update_engine/client.h>
-#include <vector>
-
-#include "constants.h"
-#include "persistent_integer.h"
-#include "uploader/metrics_log_base.h"
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-
-namespace {
-
-const char kPersistentSessionIdFilename[] = "Sysinfo.SessionId";
-
-}  // namespace
-
-std::string ChannelToString(
-    const metrics::SystemProfileProto_Channel& channel) {
-  switch (channel) {
-    case metrics::SystemProfileProto::CHANNEL_STABLE:
-    return "STABLE";
-  case metrics::SystemProfileProto::CHANNEL_DEV:
-    return "DEV";
-  case metrics::SystemProfileProto::CHANNEL_BETA:
-    return "BETA";
-  case metrics::SystemProfileProto::CHANNEL_CANARY:
-    return "CANARY";
-  default:
-    return "UNKNOWN";
-  }
-}
-
-SystemProfileCache::SystemProfileCache()
-    : initialized_(false),
-      testing_(false),
-      metrics_directory_(metrics::kMetricsdDirectory),
-      session_id_(new chromeos_metrics::PersistentInteger(
-          kPersistentSessionIdFilename, metrics_directory_)) {}
-
-SystemProfileCache::SystemProfileCache(bool testing,
-                                       const base::FilePath& metrics_directory)
-    : initialized_(false),
-      testing_(testing),
-      metrics_directory_(metrics_directory),
-      session_id_(new chromeos_metrics::PersistentInteger(
-          kPersistentSessionIdFilename, metrics_directory)) {}
-
-bool SystemProfileCache::Initialize() {
-  CHECK(!initialized_)
-      << "this should be called only once in the metrics_daemon lifetime.";
-
-  brillo::OsReleaseReader reader;
-  std::string channel;
-  if (testing_) {
-    reader.LoadTestingOnly(metrics_directory_);
-    channel = "unknown";
-  } else {
-    reader.Load();
-    auto client = update_engine::UpdateEngineClient::CreateInstance();
-    if (!client) {
-      LOG(ERROR) << "failed to create the update engine client";
-      return false;
-    }
-    if (!client->GetChannel(&channel)) {
-      LOG(ERROR) << "failed to read the current channel from update engine.";
-      return false;
-    }
-  }
-
-  if (!reader.GetString(metrics::kProductId, &profile_.product_id)
-      || profile_.product_id.empty()) {
-    LOG(ERROR) << "product_id is not set.";
-    return false;
-  }
-
-  if (!reader.GetString(metrics::kProductVersion, &profile_.version)) {
-    LOG(ERROR) << "failed to read the product version";
-  }
-
-  if (channel.empty() || profile_.version.empty()) {
-    // If the channel or version is missing, the image is not official.
-    // In this case, set the channel to unknown and the version to 0.0.0.0 to
-    // avoid polluting the production data.
-    channel = "";
-    profile_.version = metrics::kDefaultVersion;
-  }
-  std::string guid_path = metrics_directory_.Append(
-      metrics::kMetricsGUIDFileName).value();
-  profile_.client_id = testing_ ?
-      "client_id_test" :
-      GetPersistentGUID(guid_path);
-  profile_.model_manifest_id = "unknown";
-  if (!testing_) {
-    brillo::KeyValueStore weave_config;
-    if (!weave_config.Load(base::FilePath(metrics::kWeaveConfigurationFile))) {
-      LOG(ERROR) << "Failed to load the weave configuration file.";
-    } else if (!weave_config.GetString(metrics::kModelManifestId,
-                                       &profile_.model_manifest_id)) {
-      LOG(ERROR) << "The model manifest id (model_id) is undefined in "
-                 << metrics::kWeaveConfigurationFile;
-    }
-  }
-
-  profile_.channel = ProtoChannelFromString(channel);
-
-  // Increment the session_id everytime we initialize this. If metrics_daemon
-  // does not crash, this should correspond to the number of reboots of the
-  // system.
-  session_id_->Add(1);
-  profile_.session_id = static_cast<int32_t>(session_id_->Get());
-
-  initialized_ = true;
-  return initialized_;
-}
-
-bool SystemProfileCache::InitializeOrCheck() {
-  return initialized_ || Initialize();
-}
-
-bool SystemProfileCache::Populate(
-    metrics::ChromeUserMetricsExtension* metrics_proto) {
-  CHECK(metrics_proto);
-  if (not InitializeOrCheck()) {
-    return false;
-  }
-
-  // The client id is hashed before being sent.
-  metrics_proto->set_client_id(
-      metrics::MetricsLogBase::Hash(profile_.client_id));
-  metrics_proto->set_session_id(profile_.session_id);
-
-  // Sets the product id.
-  metrics_proto->set_product(9);
-
-  metrics::SystemProfileProto* profile_proto =
-      metrics_proto->mutable_system_profile();
-  profile_proto->mutable_hardware()->set_hardware_class(
-      profile_.model_manifest_id);
-  profile_proto->set_app_version(profile_.version);
-  profile_proto->set_channel(profile_.channel);
-  metrics::SystemProfileProto_BrilloDeviceData* device_data =
-      profile_proto->mutable_brillo();
-  device_data->set_product_id(profile_.product_id);
-
-  return true;
-}
-
-std::string SystemProfileCache::GetPersistentGUID(
-    const std::string& filename) {
-  std::string guid;
-  base::FilePath filepath(filename);
-  if (!base::ReadFileToString(filepath, &guid)) {
-    guid = base::GenerateGUID();
-    // If we can't read or write the file, the guid will not be preserved during
-    // the next reboot. Crash.
-    CHECK(base::WriteFile(filepath, guid.c_str(), guid.size()));
-  }
-  return guid;
-}
-
-metrics::SystemProfileProto_Channel SystemProfileCache::ProtoChannelFromString(
-    const std::string& channel) {
-  if (channel == "stable-channel") {
-    return metrics::SystemProfileProto::CHANNEL_STABLE;
-  } else if (channel == "dev-channel") {
-    return metrics::SystemProfileProto::CHANNEL_DEV;
-  } else if (channel == "beta-channel") {
-    return metrics::SystemProfileProto::CHANNEL_BETA;
-  } else if (channel == "canary-channel") {
-    return metrics::SystemProfileProto::CHANNEL_CANARY;
-  }
-
-  DLOG(INFO) << "unknown channel: " << channel;
-  return metrics::SystemProfileProto::CHANNEL_UNKNOWN;
-}
diff --git a/metricsd/uploader/system_profile_cache.h b/metricsd/uploader/system_profile_cache.h
deleted file mode 100644
index f9c484c..0000000
--- a/metricsd/uploader/system_profile_cache.h
+++ /dev/null
@@ -1,87 +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.
- */
-
-#ifndef METRICS_UPLOADER_SYSTEM_PROFILE_CACHE_H_
-#define METRICS_UPLOADER_SYSTEM_PROFILE_CACHE_H_
-
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/compiler_specific.h"
-#include "base/files/file_path.h"
-#include "base/gtest_prod_util.h"
-#include "persistent_integer.h"
-#include "uploader/proto/system_profile.pb.h"
-#include "uploader/system_profile_setter.h"
-
-namespace metrics {
-class ChromeUserMetricsExtension;
-}
-
-struct SystemProfile {
-  std::string version;
-  std::string model_manifest_id;
-  std::string client_id;
-  int session_id;
-  metrics::SystemProfileProto::Channel channel;
-  std::string product_id;
-};
-
-// Retrieves general system informations needed by the protobuf for context and
-// remembers them to avoid expensive calls.
-//
-// The cache is populated lazily. The only method needed is Populate.
-class SystemProfileCache : public SystemProfileSetter {
- public:
-  SystemProfileCache();
-
-  SystemProfileCache(bool testing, const base::FilePath& metrics_directory);
-
-  // Populates the ProfileSystem protobuf with system information.
-  bool Populate(metrics::ChromeUserMetricsExtension* metrics_proto) override;
-
-  // Converts a string representation of the channel to a
-  // SystemProfileProto_Channel
-  static metrics::SystemProfileProto_Channel ProtoChannelFromString(
-      const std::string& channel);
-
-  // Gets the persistent GUID and create it if it has not been created yet.
-  static std::string GetPersistentGUID(const std::string& filename);
-
- private:
-  friend class UploadServiceTest;
-  FRIEND_TEST(UploadServiceTest, ExtractChannelFromDescription);
-  FRIEND_TEST(UploadServiceTest, ReadKeyValueFromFile);
-  FRIEND_TEST(UploadServiceTest, SessionIdIncrementedAtInitialization);
-  FRIEND_TEST(UploadServiceTest, ValuesInConfigFileAreSent);
-  FRIEND_TEST(UploadServiceTest, ProductIdMandatory);
-
-  // Fetches all informations and populates |profile_|
-  bool Initialize();
-
-  // Initializes |profile_| only if it has not been yet initialized.
-  bool InitializeOrCheck();
-
-  bool initialized_;
-  bool testing_;
-  base::FilePath metrics_directory_;
-  std::unique_ptr<chromeos_metrics::PersistentInteger> session_id_;
-  SystemProfile profile_;
-};
-
-#endif  // METRICS_UPLOADER_SYSTEM_PROFILE_CACHE_H_
diff --git a/metricsd/uploader/system_profile_setter.h b/metricsd/uploader/system_profile_setter.h
deleted file mode 100644
index bd3ff42..0000000
--- a/metricsd/uploader/system_profile_setter.h
+++ /dev/null
@@ -1,33 +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.
- */
-
-#ifndef METRICS_UPLOADER_SYSTEM_PROFILE_SETTER_H_
-#define METRICS_UPLOADER_SYSTEM_PROFILE_SETTER_H_
-
-namespace metrics {
-class ChromeUserMetricsExtension;
-}
-
-// Abstract class used to delegate populating SystemProfileProto with system
-// information to simplify testing.
-class SystemProfileSetter {
- public:
-  virtual ~SystemProfileSetter() {}
-  // Populates the protobuf with system informations.
-  virtual bool Populate(metrics::ChromeUserMetricsExtension* profile_proto) = 0;
-};
-
-#endif  // METRICS_UPLOADER_SYSTEM_PROFILE_SETTER_H_
diff --git a/metricsd/uploader/upload_service.cc b/metricsd/uploader/upload_service.cc
deleted file mode 100644
index 0dc59a4..0000000
--- a/metricsd/uploader/upload_service.cc
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "uploader/upload_service.h"
-
-#include <sysexits.h>
-
-#include <memory>
-#include <string>
-
-#include <base/bind.h>
-#include <base/files/file_util.h>
-#include <base/logging.h>
-#include <base/memory/scoped_vector.h>
-#include <base/message_loop/message_loop.h>
-#include <base/metrics/histogram.h>
-#include <base/metrics/histogram_base.h>
-#include <base/metrics/histogram_snapshot_manager.h>
-#include <base/metrics/sparse_histogram.h>
-#include <base/metrics/statistics_recorder.h>
-#include <base/sha1.h>
-
-#include "constants.h"
-#include "uploader/metrics_log.h"
-#include "uploader/sender_http.h"
-#include "uploader/system_profile_setter.h"
-
-const int UploadService::kMaxFailedUpload = 10;
-
-UploadService::UploadService(const std::string& server,
-                             const base::TimeDelta& upload_interval,
-                             const base::TimeDelta& disk_persistence_interval,
-                             const base::FilePath& private_metrics_directory,
-                             const base::FilePath& shared_metrics_directory)
-    : brillo::Daemon(),
-      histogram_snapshot_manager_(this),
-      sender_(new HttpSender(server)),
-      failed_upload_count_(metrics::kFailedUploadCountName,
-                           private_metrics_directory),
-      counters_(new CrashCounters),
-      upload_interval_(upload_interval),
-      disk_persistence_interval_(disk_persistence_interval),
-      metricsd_service_runner_(counters_) {
-  staged_log_path_ = private_metrics_directory.Append(metrics::kStagedLogName);
-  saved_log_path_ = private_metrics_directory.Append(metrics::kSavedLogName);
-  consent_file_ = shared_metrics_directory.Append(metrics::kConsentFileName);
-}
-
-void UploadService::LoadSavedLog() {
-  if (base::PathExists(saved_log_path_)) {
-    GetOrCreateCurrentLog()->LoadFromFile(saved_log_path_);
-  }
-}
-
-int UploadService::OnInit() {
-  brillo::Daemon::OnInit();
-
-  base::StatisticsRecorder::Initialize();
-  metricsd_service_runner_.Start();
-
-  system_profile_setter_.reset(new SystemProfileCache());
-
-  base::MessageLoop::current()->PostDelayedTask(
-      FROM_HERE,
-      base::Bind(&UploadService::UploadEventCallback, base::Unretained(this)),
-      upload_interval_);
-
-  base::MessageLoop::current()->PostDelayedTask(
-      FROM_HERE,
-      base::Bind(&UploadService::PersistEventCallback, base::Unretained(this)),
-      disk_persistence_interval_);
-
-  LoadSavedLog();
-
-  return EX_OK;
-}
-
-void UploadService::OnShutdown(int* exit_code) {
-  metricsd_service_runner_.Stop();
-  PersistToDisk();
-}
-
-void UploadService::InitForTest(SystemProfileSetter* setter) {
-  LoadSavedLog();
-  system_profile_setter_.reset(setter);
-}
-
-void UploadService::StartNewLog() {
-  current_log_.reset(new MetricsLog());
-}
-
-void UploadService::UploadEventCallback() {
-  UploadEvent();
-
-  base::MessageLoop::current()->PostDelayedTask(
-      FROM_HERE,
-      base::Bind(&UploadService::UploadEventCallback, base::Unretained(this)),
-      upload_interval_);
-}
-
-void UploadService::PersistEventCallback() {
-  PersistToDisk();
-
-  base::MessageLoop::current()->PostDelayedTask(
-      FROM_HERE,
-      base::Bind(&UploadService::PersistEventCallback, base::Unretained(this)),
-      disk_persistence_interval_);
-}
-
-void UploadService::PersistToDisk() {
-  GatherHistograms();
-  if (current_log_) {
-    current_log_->SaveToFile(saved_log_path_);
-  }
-}
-
-void UploadService::UploadEvent() {
-  // If the system shutdown or crashed while uploading a report, we may not have
-  // deleted an old log.
-  RemoveFailedLog();
-
-  if (HasStagedLog()) {
-    // Previous upload failed, retry sending the logs.
-    SendStagedLog();
-    return;
-  }
-
-  // Previous upload successful, stage another log.
-  GatherHistograms();
-  StageCurrentLog();
-
-  // If a log is available for upload, upload it.
-  if (HasStagedLog()) {
-    SendStagedLog();
-  }
-}
-
-void UploadService::SendStagedLog() {
-  // If metrics are not enabled, discard the log and exit.
-  if (!AreMetricsEnabled()) {
-    LOG(INFO) << "Metrics disabled. Don't upload metrics samples.";
-    base::DeleteFile(staged_log_path_, false);
-    return;
-  }
-
-  std::string staged_log;
-  CHECK(base::ReadFileToString(staged_log_path_, &staged_log));
-
-  // Increase the failed count in case the daemon crashes while sending the log.
-  failed_upload_count_.Add(1);
-
-  if (!sender_->Send(staged_log, base::SHA1HashString(staged_log))) {
-    LOG(WARNING) << "log failed to upload";
-  } else {
-    VLOG(1) << "uploaded " << staged_log.length() << " bytes";
-    base::DeleteFile(staged_log_path_, false);
-  }
-
-  RemoveFailedLog();
-}
-
-void UploadService::Reset() {
-  base::DeleteFile(staged_log_path_, false);
-  current_log_.reset();
-  failed_upload_count_.Set(0);
-}
-
-void UploadService::GatherHistograms() {
-  base::StatisticsRecorder::Histograms histograms;
-  base::StatisticsRecorder::GetHistograms(&histograms);
-
-  histogram_snapshot_manager_.PrepareDeltas(
-      base::Histogram::kNoFlags, base::Histogram::kUmaTargetedHistogramFlag);
-
-  // Gather and reset the crash counters, shared with the binder threads.
-  unsigned int kernel_crashes = counters_->GetAndResetKernelCrashCount();
-  unsigned int unclean_shutdowns = counters_->GetAndResetUncleanShutdownCount();
-  unsigned int user_crashes = counters_->GetAndResetUserCrashCount();
-
-  // Only create a log if the counters have changed.
-  if (kernel_crashes > 0 || unclean_shutdowns > 0 || user_crashes > 0) {
-    GetOrCreateCurrentLog()->IncrementKernelCrashCount(kernel_crashes);
-    GetOrCreateCurrentLog()->IncrementUncleanShutdownCount(unclean_shutdowns);
-    GetOrCreateCurrentLog()->IncrementUserCrashCount(user_crashes);
-  }
-}
-
-void UploadService::RecordDelta(const base::HistogramBase& histogram,
-                                const base::HistogramSamples& snapshot) {
-  GetOrCreateCurrentLog()->RecordHistogramDelta(histogram.histogram_name(),
-                                                snapshot);
-}
-
-void UploadService::StageCurrentLog() {
-  // If we haven't logged anything since the last upload, don't upload an empty
-  // report.
-  if (!current_log_)
-    return;
-
-  std::unique_ptr<MetricsLog> staged_log;
-  staged_log.swap(current_log_);
-  staged_log->CloseLog();
-  if (!staged_log->PopulateSystemProfile(system_profile_setter_.get())) {
-    LOG(WARNING) << "Error while adding metadata to the log. Discarding the "
-                 << "log.";
-    return;
-  }
-
-  if (!base::DeleteFile(saved_log_path_, false)) {
-    // There is a chance that we will upload the same metrics twice but, if we
-    // are lucky, the backup should be overridden before that. In doubt, try not
-    // to lose any metrics.
-    LOG(ERROR) << "failed to delete the last backup of the current log.";
-  }
-
-  failed_upload_count_.Set(0);
-  staged_log->SaveToFile(staged_log_path_);
-}
-
-MetricsLog* UploadService::GetOrCreateCurrentLog() {
-  if (!current_log_) {
-    StartNewLog();
-  }
-  return current_log_.get();
-}
-
-bool UploadService::HasStagedLog() {
-  return base::PathExists(staged_log_path_);
-}
-
-void UploadService::RemoveFailedLog() {
-  if (failed_upload_count_.Get() > kMaxFailedUpload) {
-    LOG(INFO) << "log failed more than " << kMaxFailedUpload << " times.";
-    CHECK(base::DeleteFile(staged_log_path_, false))
-        << "failed to delete staged log at " << staged_log_path_.value();
-    failed_upload_count_.Set(0);
-  }
-}
-
-bool UploadService::AreMetricsEnabled() {
-  return base::PathExists(consent_file_);
-}
diff --git a/metricsd/uploader/upload_service.h b/metricsd/uploader/upload_service.h
deleted file mode 100644
index a1d9d3b..0000000
--- a/metricsd/uploader/upload_service.h
+++ /dev/null
@@ -1,183 +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.
- */
-
-#ifndef METRICS_UPLOADER_UPLOAD_SERVICE_H_
-#define METRICS_UPLOADER_UPLOAD_SERVICE_H_
-
-#include <memory>
-#include <string>
-
-#include <base/metrics/histogram_base.h>
-#include <base/metrics/histogram_flattener.h>
-#include <base/metrics/histogram_snapshot_manager.h>
-#include <brillo/daemons/daemon.h>
-
-#include "persistent_integer.h"
-#include "uploader/crash_counters.h"
-#include "uploader/metrics_log.h"
-#include "uploader/metricsd_service_runner.h"
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-#include "uploader/sender.h"
-#include "uploader/system_profile_cache.h"
-
-class SystemProfileSetter;
-
-// Service responsible for backing up the currently aggregated metrics to disk
-// and uploading them periodically to the server.
-//
-// A given metrics sample can be in one of three locations.
-// * in-memory metrics: in memory aggregated metrics, waiting to be staged for
-//   upload.
-// * saved log: protobuf message, written to disk periodically and on shutdown
-//   to make a backup of metrics data for uploading later.
-// * staged log: protobuf message waiting to be uploaded.
-//
-// The service works as follows:
-// On startup, we create the in-memory metrics from the saved log if it exists.
-//
-// Periodically (every |disk_persistence_interval_| seconds), we take a snapshot
-// of the in-memory metrics and save them to disk.
-//
-// Periodically (every |upload_interval| seconds), we:
-// * take a snapshot of the in-memory metrics and create the staged log
-// * save the staged log to disk to avoid losing it if metricsd or the system
-//   crashes between two uploads.
-// * delete the last saved log: all the metrics contained in it are also in the
-//   newly created staged log.
-//
-// On shutdown (SIGINT or SIGTERM), we save the in-memory metrics to disk.
-//
-// Note: the in-memory metrics can be stored in |current_log_| or
-// base::StatisticsRecorder.
-class UploadService : public base::HistogramFlattener, public brillo::Daemon {
- public:
-  UploadService(const std::string& server,
-                const base::TimeDelta& upload_interval,
-                const base::TimeDelta& disk_persistence_interval,
-                const base::FilePath& private_metrics_directory,
-                const base::FilePath& shared_metrics_directory);
-
-  // Initializes the upload service.
-  int OnInit() override;
-
-  // Cleans up the internal state before exiting.
-  void OnShutdown(int* exit_code) override;
-
-  // Starts a new log. The log needs to be regenerated after each successful
-  // launch as it is destroyed when staging the log.
-  void StartNewLog();
-
-  // Saves the current metrics to a file.
-  void PersistToDisk();
-
-  // Triggers an upload event.
-  void UploadEvent();
-
-  // Sends the staged log.
-  void SendStagedLog();
-
-  // Implements inconsistency detection to match HistogramFlattener's
-  // interface.
-  void InconsistencyDetected(
-      base::HistogramBase::Inconsistency problem) override {}
-  void UniqueInconsistencyDetected(
-      base::HistogramBase::Inconsistency problem) override {}
-  void InconsistencyDetectedInLoggedCount(int amount) override {}
-
- private:
-  friend class UploadServiceTest;
-
-  FRIEND_TEST(UploadServiceTest, CanSendMultipleTimes);
-  FRIEND_TEST(UploadServiceTest, CorruptedSavedLog);
-  FRIEND_TEST(UploadServiceTest, CurrentLogSavedAndResumed);
-  FRIEND_TEST(UploadServiceTest, DiscardLogsAfterTooManyFailedUpload);
-  FRIEND_TEST(UploadServiceTest, EmptyLogsAreNotSent);
-  FRIEND_TEST(UploadServiceTest, FailedSendAreRetried);
-  FRIEND_TEST(UploadServiceTest, LogContainsAggregatedValues);
-  FRIEND_TEST(UploadServiceTest, LogContainsCrashCounts);
-  FRIEND_TEST(UploadServiceTest, LogEmptyAfterUpload);
-  FRIEND_TEST(UploadServiceTest, LogEmptyByDefault);
-  FRIEND_TEST(UploadServiceTest, LogFromTheMetricsLibrary);
-  FRIEND_TEST(UploadServiceTest, LogKernelCrash);
-  FRIEND_TEST(UploadServiceTest, LogUncleanShutdown);
-  FRIEND_TEST(UploadServiceTest, LogUserCrash);
-  FRIEND_TEST(UploadServiceTest, PersistEmptyLog);
-  FRIEND_TEST(UploadServiceTest, UnknownCrashIgnored);
-  FRIEND_TEST(UploadServiceTest, ValuesInConfigFileAreSent);
-
-  // Initializes the upload service for testing.
-  void InitForTest(SystemProfileSetter* setter);
-
-  // If a staged log fails to upload more than kMaxFailedUpload times, it
-  // will be discarded.
-  static const int kMaxFailedUpload;
-
-  // Loads the log saved to disk if it exists.
-  void LoadSavedLog();
-
-  // Resets the internal state.
-  void Reset();
-
-  // Returns true iff metrics reporting is enabled.
-  bool AreMetricsEnabled();
-
-  // Event callback for handling Upload events.
-  void UploadEventCallback();
-
-  // Event callback for handling Persist events.
-  void PersistEventCallback();
-
-  // Aggregates all histogram available in memory and store them in the current
-  // log.
-  void GatherHistograms();
-
-  // Callback for HistogramSnapshotManager to store the histograms.
-  void RecordDelta(const base::HistogramBase& histogram,
-                   const base::HistogramSamples& snapshot) override;
-
-  // Compiles all the samples received into a single protobuf and adds all
-  // system information.
-  void StageCurrentLog();
-
-  // Returns true iff a log is staged.
-  bool HasStagedLog();
-
-  // Remove the staged log iff the upload failed more than |kMaxFailedUpload|.
-  void RemoveFailedLog();
-
-  // Returns the current log. If there is no current log, creates it first.
-  MetricsLog* GetOrCreateCurrentLog();
-
-  std::unique_ptr<SystemProfileSetter> system_profile_setter_;
-  base::HistogramSnapshotManager histogram_snapshot_manager_;
-  std::unique_ptr<Sender> sender_;
-  chromeos_metrics::PersistentInteger failed_upload_count_;
-  std::unique_ptr<MetricsLog> current_log_;
-  std::shared_ptr<CrashCounters> counters_;
-
-  base::TimeDelta upload_interval_;
-  base::TimeDelta disk_persistence_interval_;
-
-  MetricsdServiceRunner metricsd_service_runner_;
-
-  base::FilePath consent_file_;
-  base::FilePath staged_log_path_;
-  base::FilePath saved_log_path_;
-
-  bool testing_;
-};
-
-#endif  // METRICS_UPLOADER_UPLOAD_SERVICE_H_
diff --git a/metricsd/uploader/upload_service_test.cc b/metricsd/uploader/upload_service_test.cc
deleted file mode 100644
index 70112f4..0000000
--- a/metricsd/uploader/upload_service_test.cc
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <memory>
-
-#include <base/at_exit.h>
-#include <base/files/file_util.h>
-#include <base/files/scoped_temp_dir.h>
-#include <base/logging.h>
-#include <base/metrics/sparse_histogram.h>
-#include <base/metrics/statistics_recorder.h>
-#include <base/sys_info.h>
-#include <gtest/gtest.h>
-
-#include "constants.h"
-#include "persistent_integer.h"
-#include "uploader/metrics_log.h"
-#include "uploader/mock/mock_system_profile_setter.h"
-#include "uploader/mock/sender_mock.h"
-#include "uploader/proto/chrome_user_metrics_extension.pb.h"
-#include "uploader/proto/histogram_event.pb.h"
-#include "uploader/proto/system_profile.pb.h"
-#include "uploader/system_profile_cache.h"
-#include "uploader/upload_service.h"
-
-class UploadServiceTest : public testing::Test {
- protected:
-  virtual void SetUp() {
-    CHECK(dir_.CreateUniqueTempDir());
-    // Make sure the statistics recorder is inactive (contains no metrics) then
-    // initialize it.
-    ASSERT_FALSE(base::StatisticsRecorder::IsActive());
-    base::StatisticsRecorder::Initialize();
-
-    private_dir_ = dir_.path().Append("private");
-    shared_dir_ = dir_.path().Append("shared");
-
-    EXPECT_TRUE(base::CreateDirectory(private_dir_));
-    EXPECT_TRUE(base::CreateDirectory(shared_dir_));
-
-    ASSERT_EQ(0, base::WriteFile(shared_dir_.Append(metrics::kConsentFileName),
-                                 "", 0));
-
-    upload_service_.reset(new UploadService(
-        "", base::TimeDelta(), base::TimeDelta(), private_dir_, shared_dir_));
-    counters_ = upload_service_->counters_;
-
-    upload_service_->sender_.reset(new SenderMock);
-    upload_service_->InitForTest(new MockSystemProfileSetter);
-    upload_service_->GatherHistograms();
-    upload_service_->Reset();
-  }
-
-  void SendSparseHistogram(const std::string& name, int sample) {
-    base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
-        name, base::Histogram::kUmaTargetedHistogramFlag);
-    histogram->Add(sample);
-  }
-
-  void SendHistogram(
-      const std::string& name, int sample, int min, int max, int nbuckets) {
-    base::HistogramBase* histogram = base::Histogram::FactoryGet(
-        name, min, max, nbuckets, base::Histogram::kUmaTargetedHistogramFlag);
-    histogram->Add(sample);
-  }
-
-  void SetTestingProperty(const std::string& name, const std::string& value) {
-    base::FilePath filepath =
-        dir_.path().Append("etc/os-release.d").Append(name);
-    ASSERT_TRUE(base::CreateDirectory(filepath.DirName()));
-    ASSERT_EQ(value.size(),
-              base::WriteFile(filepath, value.data(), value.size()));
-  }
-
-  const metrics::SystemProfileProto_Stability GetCurrentStability() {
-    EXPECT_TRUE(upload_service_->current_log_.get());
-
-    return upload_service_->current_log_->uma_proto()
-        ->system_profile()
-        .stability();
-  }
-
-  base::ScopedTempDir dir_;
-  std::unique_ptr<UploadService> upload_service_;
-
-  std::unique_ptr<base::AtExitManager> exit_manager_;
-  std::shared_ptr<CrashCounters> counters_;
-  base::FilePath private_dir_;
-  base::FilePath shared_dir_;
-};
-
-TEST_F(UploadServiceTest, FailedSendAreRetried) {
-  SenderMock* sender = new SenderMock();
-  upload_service_->sender_.reset(sender);
-
-  sender->set_should_succeed(false);
-
-  SendSparseHistogram("hello", 1);
-  upload_service_->UploadEvent();
-  EXPECT_EQ(1, sender->send_call_count());
-  std::string sent_string = sender->last_message();
-
-  upload_service_->UploadEvent();
-  EXPECT_EQ(2, sender->send_call_count());
-  EXPECT_EQ(sent_string, sender->last_message());
-}
-
-TEST_F(UploadServiceTest, DiscardLogsAfterTooManyFailedUpload) {
-  SenderMock* sender = new SenderMock();
-  upload_service_->sender_.reset(sender);
-
-  sender->set_should_succeed(false);
-
-  SendSparseHistogram("hello", 1);
-
-  for (int i = 0; i < UploadService::kMaxFailedUpload; i++) {
-    upload_service_->UploadEvent();
-  }
-
-  EXPECT_TRUE(upload_service_->HasStagedLog());
-  upload_service_->UploadEvent();
-  EXPECT_FALSE(upload_service_->HasStagedLog());
-
-  // Log a new sample. The failed upload counter should be reset.
-  SendSparseHistogram("hello", 1);
-  for (int i = 0; i < UploadService::kMaxFailedUpload; i++) {
-    upload_service_->UploadEvent();
-  }
-  // The log is not discarded after multiple failed uploads.
-  EXPECT_TRUE(upload_service_->HasStagedLog());
-}
-
-TEST_F(UploadServiceTest, EmptyLogsAreNotSent) {
-  SenderMock* sender = new SenderMock();
-  upload_service_->sender_.reset(sender);
-  upload_service_->UploadEvent();
-  EXPECT_FALSE(upload_service_->current_log_);
-  EXPECT_EQ(0, sender->send_call_count());
-}
-
-TEST_F(UploadServiceTest, LogEmptyByDefault) {
-  // current_log_ should be initialized later as it needs AtExitManager to exist
-  // in order to gather system information from SysInfo.
-  EXPECT_FALSE(upload_service_->current_log_);
-}
-
-TEST_F(UploadServiceTest, CanSendMultipleTimes) {
-  SenderMock* sender = new SenderMock();
-  upload_service_->sender_.reset(sender);
-
-  SendSparseHistogram("hello", 1);
-
-  upload_service_->UploadEvent();
-
-  std::string first_message = sender->last_message();
-  SendSparseHistogram("hello", 2);
-
-  upload_service_->UploadEvent();
-
-  EXPECT_NE(first_message, sender->last_message());
-}
-
-TEST_F(UploadServiceTest, LogEmptyAfterUpload) {
-  SendSparseHistogram("hello", 2);
-
-  upload_service_->UploadEvent();
-  EXPECT_FALSE(upload_service_->current_log_);
-}
-
-TEST_F(UploadServiceTest, LogContainsAggregatedValues) {
-  SendHistogram("foo", 11, 0, 42, 10);
-  SendHistogram("foo", 12, 0, 42, 10);
-
-  upload_service_->GatherHistograms();
-  metrics::ChromeUserMetricsExtension* proto =
-      upload_service_->current_log_->uma_proto();
-  EXPECT_EQ(1, proto->histogram_event().size());
-}
-
-TEST_F(UploadServiceTest, LogContainsCrashCounts) {
-  // By default, there is no current log.
-  upload_service_->GatherHistograms();
-  EXPECT_FALSE(upload_service_->current_log_);
-
-  // If the user crash counter is incremented, we add the count to the current
-  // log.
-  counters_->IncrementUserCrashCount();
-  upload_service_->GatherHistograms();
-  EXPECT_EQ(1, GetCurrentStability().other_user_crash_count());
-
-  // If the kernel crash counter is incremented, we add the count to the current
-  // log.
-  counters_->IncrementKernelCrashCount();
-  upload_service_->GatherHistograms();
-  EXPECT_EQ(1, GetCurrentStability().kernel_crash_count());
-
-  // If the kernel crash counter is incremented, we add the count to the current
-  // log.
-  counters_->IncrementUncleanShutdownCount();
-  counters_->IncrementUncleanShutdownCount();
-  upload_service_->GatherHistograms();
-  EXPECT_EQ(2, GetCurrentStability().unclean_system_shutdown_count());
-
-  // If no counter is incremented, the reported numbers don't change.
-  upload_service_->GatherHistograms();
-  EXPECT_EQ(1, GetCurrentStability().other_user_crash_count());
-  EXPECT_EQ(1, GetCurrentStability().kernel_crash_count());
-  EXPECT_EQ(2, GetCurrentStability().unclean_system_shutdown_count());
-}
-
-TEST_F(UploadServiceTest, ExtractChannelFromString) {
-  EXPECT_EQ(SystemProfileCache::ProtoChannelFromString("developer-build"),
-            metrics::SystemProfileProto::CHANNEL_UNKNOWN);
-
-  EXPECT_EQ(metrics::SystemProfileProto::CHANNEL_DEV,
-            SystemProfileCache::ProtoChannelFromString("dev-channel"));
-
-  EXPECT_EQ(metrics::SystemProfileProto::CHANNEL_STABLE,
-            SystemProfileCache::ProtoChannelFromString("stable-channel"));
-
-  EXPECT_EQ(metrics::SystemProfileProto::CHANNEL_UNKNOWN,
-            SystemProfileCache::ProtoChannelFromString("this is a test"));
-}
-
-TEST_F(UploadServiceTest, ValuesInConfigFileAreSent) {
-  SenderMock* sender = new SenderMock();
-  upload_service_->sender_.reset(sender);
-
-  SetTestingProperty(metrics::kProductId, "hello");
-  SetTestingProperty(metrics::kProductVersion, "1.2.3.4");
-
-  SendSparseHistogram("hello", 1);
-
-  // Reset to create the new log with the profile setter.
-  upload_service_->system_profile_setter_.reset(
-      new SystemProfileCache(true, dir_.path()));
-  upload_service_->Reset();
-  upload_service_->UploadEvent();
-
-  EXPECT_EQ(1, sender->send_call_count());
-  EXPECT_TRUE(sender->is_good_proto());
-  EXPECT_EQ(1, sender->last_message_proto().histogram_event().size());
-
-  EXPECT_NE(0, sender->last_message_proto().client_id());
-  EXPECT_NE(0, sender->last_message_proto().system_profile().build_timestamp());
-  EXPECT_NE(0, sender->last_message_proto().session_id());
-}
-
-TEST_F(UploadServiceTest, PersistentGUID) {
-  std::string tmp_file = dir_.path().Append("tmpfile").value();
-
-  std::string first_guid = SystemProfileCache::GetPersistentGUID(tmp_file);
-  std::string second_guid = SystemProfileCache::GetPersistentGUID(tmp_file);
-
-  // The GUID are cached.
-  EXPECT_EQ(first_guid, second_guid);
-
-  base::DeleteFile(base::FilePath(tmp_file), false);
-
-  first_guid = SystemProfileCache::GetPersistentGUID(tmp_file);
-  base::DeleteFile(base::FilePath(tmp_file), false);
-  second_guid = SystemProfileCache::GetPersistentGUID(tmp_file);
-
-  // Random GUIDs are generated (not all the same).
-  EXPECT_NE(first_guid, second_guid);
-}
-
-TEST_F(UploadServiceTest, SessionIdIncrementedAtInitialization) {
-  SetTestingProperty(metrics::kProductId, "hello");
-  SystemProfileCache cache(true, dir_.path());
-  cache.Initialize();
-  int session_id = cache.profile_.session_id;
-  cache.initialized_ = false;
-  cache.Initialize();
-  EXPECT_EQ(cache.profile_.session_id, session_id + 1);
-}
-
-// The product id must be set for metrics to be uploaded.
-// If it is not set, the system profile cache should fail to initialize.
-TEST_F(UploadServiceTest, ProductIdMandatory) {
-  SystemProfileCache cache(true, dir_.path());
-  ASSERT_FALSE(cache.Initialize());
-  SetTestingProperty(metrics::kProductId, "");
-  ASSERT_FALSE(cache.Initialize());
-  SetTestingProperty(metrics::kProductId, "hello");
-  ASSERT_TRUE(cache.Initialize());
-}
-
-TEST_F(UploadServiceTest, CurrentLogSavedAndResumed) {
-  SendHistogram("hello", 10, 0, 100, 10);
-  upload_service_->PersistToDisk();
-  EXPECT_EQ(
-      1, upload_service_->current_log_->uma_proto()->histogram_event().size());
-  upload_service_.reset(new UploadService(
-      "", base::TimeDelta(), base::TimeDelta(), private_dir_, shared_dir_));
-  upload_service_->InitForTest(nullptr);
-
-  SendHistogram("hello", 10, 0, 100, 10);
-  upload_service_->GatherHistograms();
-  EXPECT_EQ(2, upload_service_->GetOrCreateCurrentLog()
-                   ->uma_proto()
-                   ->histogram_event()
-                   .size());
-}
-
-TEST_F(UploadServiceTest, PersistEmptyLog) {
-  upload_service_->PersistToDisk();
-  EXPECT_FALSE(base::PathExists(upload_service_->saved_log_path_));
-}
-
-TEST_F(UploadServiceTest, CorruptedSavedLog) {
-  // Write a bogus saved log.
-  EXPECT_EQ(5, base::WriteFile(upload_service_->saved_log_path_, "hello", 5));
-
-  upload_service_.reset(new UploadService(
-      "", base::TimeDelta(), base::TimeDelta(), private_dir_, shared_dir_));
-
-  upload_service_->InitForTest(nullptr);
-  // If the log is unreadable, we drop it and continue execution.
-  ASSERT_NE(nullptr, upload_service_->GetOrCreateCurrentLog());
-  ASSERT_FALSE(base::PathExists(upload_service_->saved_log_path_));
-}
diff --git a/reboot/Android.bp b/reboot/Android.bp
new file mode 100644
index 0000000..805fd9a
--- /dev/null
+++ b/reboot/Android.bp
@@ -0,0 +1,8 @@
+// Copyright 2013 The Android Open Source Project
+
+cc_binary {
+    name: "reboot",
+    srcs: ["reboot.c"],
+    shared_libs: ["libcutils"],
+    cflags: ["-Werror"],
+}
diff --git a/reboot/Android.mk b/reboot/Android.mk
deleted file mode 100644
index 7a24f99..0000000
--- a/reboot/Android.mk
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2013 The Android Open Source Project
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := reboot.c
-
-LOCAL_SHARED_LIBRARIES := libcutils
-
-LOCAL_MODULE := reboot
-
-LOCAL_CFLAGS := -Werror
-
-include $(BUILD_EXECUTABLE)
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 7d0c87d..48a46c6 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -53,7 +53,7 @@
 
 # Pretty comprehensive set of native services. This list is helpful if all that's to be checked is an
 # app.
-ifeq ($(SANITIZE_LITE),true)
+ifeq ($(SANITIZE_LITE_SERVICES),true)
 SANITIZE_ASAN_OPTIONS_FOR := \
   adbd \
   ATFWD-daemon \
@@ -116,6 +116,12 @@
   EXPORT_GLOBAL_ASAN_OPTIONS := export ASAN_OPTIONS include=/system/asan.options
   LOCAL_REQUIRED_MODULES := asan.options $(ASAN_OPTIONS_FILES)
 endif
+
+EXPORT_GLOBAL_GCOV_OPTIONS :=
+ifeq ($(NATIVE_COVERAGE),true)
+  EXPORT_GLOBAL_GCOV_OPTIONS := export GCOV_PREFIX /data/misc/gcov
+endif
+
 # Put it here instead of in init.rc module definition,
 # because init.rc is conditionally included.
 #
@@ -163,7 +169,22 @@
 	$(hide) sed -e 's?%BOOTCLASSPATH%?$(PRODUCT_BOOTCLASSPATH)?g' $< >$@
 	$(hide) sed -i -e 's?%SYSTEMSERVERCLASSPATH%?$(PRODUCT_SYSTEM_SERVER_CLASSPATH)?g' $@
 	$(hide) sed -i -e 's?%EXPORT_GLOBAL_ASAN_OPTIONS%?$(EXPORT_GLOBAL_ASAN_OPTIONS)?g' $@
+	$(hide) sed -i -e 's?%EXPORT_GLOBAL_GCOV_OPTIONS%?$(EXPORT_GLOBAL_GCOV_OPTIONS)?g' $@
 
 bcp_md5 :=
 bcp_dep :=
+
 #######################################
+# ld.config.txt
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := ld.config.txt
+ifeq ($(PRODUCT_FULL_TREBLE),true)
+LOCAL_SRC_FILES := etc/ld.config.txt
+else
+LOCAL_SRC_FILES := etc/ld.config.legacy.txt
+endif
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
diff --git a/rootdir/etc/ld.config.legacy.txt b/rootdir/etc/ld.config.legacy.txt
new file mode 100644
index 0000000..c22edfe
--- /dev/null
+++ b/rootdir/etc/ld.config.legacy.txt
@@ -0,0 +1,15 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Bionic loader config file.
+# This gives the exactly the same namespace setup in pre-O.
+#
+
+# All binaries gets the same configuration 'legacy'
+dir.legacy = /system
+dir.legacy = /vendor
+dir.legacy = /sbin
+
+[legacy]
+namespace.default.isolated = false
+namespace.default.search.paths = /system/${LIB}:/vendor/${LIB}
+namespace.default.asan.search.paths = /data/asan/system/${LIB}:/system/${LIB}:/data/asan/vendor/${LIB}:/vendor/${LIB}
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
new file mode 100644
index 0000000..e2c70f3
--- /dev/null
+++ b/rootdir/etc/ld.config.txt
@@ -0,0 +1,113 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Bionic loader config file.
+#
+
+# Don't change the order here.
+dir.system = /system/bin/
+dir.system = /system/xbin/
+dir.vendor = /vendor/bin/
+
+[system]
+additional.namespaces = sphal,vndk,rs
+
+###############################################################################
+# "default" namespace
+#
+# Framework-side code runs in this namespace. Anything from /vendor partition
+# can't be loaded in this namespace.
+###############################################################################
+namespace.default.isolated = false
+namespace.default.search.paths = /system/${LIB}:/vendor/${LIB}
+namespace.default.permitted.paths = /system/${LIB}:/vendor/${LIB}
+
+namespace.default.asan.search.paths = /data/asan/system/${LIB}:/system/${LIB}:/data/asan/vendor/${LIB}:/vendor/${LIB}
+namespace.default.asan.permitted.paths = /data/asan/system/${LIB}:/system/${LIB}:/data/asan/vendor/${LIB}:/vendor/${LIB}
+
+# TODO(b/37013858): remove all dependencies to /vendor/lib from system processes
+# When this is done, comment out following three lines and remove the three
+# lines above
+#namespace.default.isolated = true
+#namespace.default.search.paths = /system/${LIB}
+#namespace.default.permitted.paths = /system/${LIB}
+#
+#namespace.default.asan.search.paths = /data/asan/system/${LIB}:/system/${LIB}
+#namespace.default.asan.permitted.paths = /data/asan/system/${LIB}:/system/${LIB}
+
+###############################################################################
+# "sphal" namespace
+#
+# SP-HAL(Sameprocess-HAL)s are the only vendor libraries that are allowed to be
+# loaded inside system processes. libEGL_<chipset>.so, libGLESv2_<chipset>.so,
+# android.hardware.graphics.mapper@2.0-impl.so, etc are SP-HALs.
+#
+# This namespace is exclusivly for SP-HALs. When the framework tries to dynami-
+# cally load SP-HALs, android_dlopen_ext() is used to explicitly specifying
+# that they should be searched and loaded from this namespace.
+#
+# Note that there is no link from the default namespace to this namespace.
+###############################################################################
+namespace.sphal.isolated = true
+namespace.sphal.visible = true
+namespace.sphal.search.paths = /vendor/${LIB}/egl:/vendor/${LIB}/hw:/vendor/${LIB}
+namespace.sphal.permitted.paths = /vendor/${LIB}
+
+namespace.sphal.asan.search.paths = /data/asan/vendor/${LIB}/egl:/vendor/${LIB}/egl:/data/asan/vendor/${LIB}/hw:/vendor/${LIB}/hw:/data/asan/vendor/${LIB}:/vendor/${LIB}
+namespace.sphal.asan.permitted.paths = /data/asan/vendor/${LIB}:/vendor/${LIB}
+
+# Once in this namespace, access to libraries in /system/lib is restricted. Only
+# libs listed here can be used.
+namespace.sphal.links = default,vndk,rs
+
+# WARNING: only NDK libs can be listed here.
+namespace.sphal.link.default.shared_libs = libc.so:libz.so:libm.so:libdl.so:libstdc++.so:liblog.so:libnativewindow.so:libEGL.so:libsync.so:libGLESv1_CM.so:libGLESv2.so:libvndksupport.so
+
+# WARNING: only VNDK-SP libs can be listed here. DO NOT EDIT this line.
+namespace.sphal.link.vndk.shared_libs = android.hardware.renderscript@1.0.so:android.hardware.graphics.allocator@2.0.so:android.hardware.graphics.mapper@2.0.so:android.hardware.graphics.common@1.0.so:android.hidl.base@1.0.so:android.hidl.memory@1.0.so:libhwbinder.so:libbase.so:libcutils.so:libhardware.so:libhidlbase.so:libhidlmemory.so:libhidltransport.so:libion.so:libutils.so:libc++.so
+
+# Renderscript gets separate namespace
+namespace.sphal.link.rs.shared_libs = libRS_internal.so
+
+###############################################################################
+# "rs" namespace
+#
+# This namespace is exclusively for Renderscript internal libraries.
+# This namespace has slightly looser restriction than the vndk namespace because
+# of the genuine characteristics of Renderscript; /data is in the permitted path
+# to load the compiled *.so file and libmediandk.so can be used here.
+###############################################################################
+namespace.rs.isolated = true
+namespace.rs.search.paths = /vendor/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/vendor/${LIB}
+namespace.rs.permitted.paths = /vendor/${LIB}:/data
+
+namespace.rs.asan.search.paths = /data/asan/vendor/${LIB}/vndk-sp:/vendor/${LIB}/vndk-sp:/data/asan/system/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/data/asan/vendor/${LIB}:/vendor/${LIB}
+namespace.rs.asan.permitted.paths = /data/asan/vendor/${LIB}:/vendor/${LIB}:/data
+
+namespace.rs.links = default,vndk
+namespace.rs.link.default.shared_libs = libc.so:libz.so:libm.so:libdl.so:libstdc++.so:liblog.so:libnativewindow.so:libEGL.so:libsync.so:libGLESv1_CM.so:libGLESv2.so:libmediandk.so:libui.so:libvndksupport.so
+namespace.rs.link.vndk.shared_libs = android.hardware.renderscript@1.0.so:android.hardware.graphics.allocator@2.0.so:android.hardware.graphics.mapper@2.0.so:android.hardware.graphics.common@1.0.so:android.hidl.base@1.0.so:android.hidl.memory@1.0.so:libhwbinder.so:libbase.so:libcutils.so:libhardware.so:libhidlbase.so:libhidlmemory.so:libhidltransport.so:libion.so:libutils.so:libc++.so
+
+###############################################################################
+# "vndk" namespace
+#
+# This namespace is exclusively for vndk-sp libs.
+###############################################################################
+namespace.vndk.isolated = true
+namespace.vndk.search.paths = /vendor/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/vendor/${LIB}
+namespace.vndk.permitted.paths = /vendor/${LIB}/hw:/vendor/${LIB}/egl
+
+namespace.vndk.asan.search.paths = /data/asan/vendor/${LIB}/vndk-sp:/vendor/${LIB}/vndk-sp:/data/asan/system/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/data/asan/vendor/${LIB}:/vendor/${LIB}
+namespace.vndk.asan.permitted.paths = /data/asan/vendor/${LIB}/hw:/vendor/${LIB}/hw:/data/asan/vendor/${LIB}/egl:/vendor/${LIB}/egl
+
+# When these NDK libs are required inside this namespace, then it is redirected
+# to the default namespace. This is possible since their ABI is stable across
+# Android releases.
+namespace.vndk.links = default
+namespace.vndk.link.default.shared_libs = android.hidl.memory@1.0-impl.so:libc.so:libz.so:libm.so:libdl.so:libstdc++.so:liblog.so:libnativewindow.so:libEGL.so:libsync.so:libvndksupport.so
+
+
+[vendor]
+namespace.default.isolated = false
+namespace.default.search.paths = /vendor/${LIB}:/vendor/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/system/${LIB}
+
+namespace.default.asan.search.paths = /data/asan/vendor/${LIB}:/vendor/${LIB}:/data/asan/vendor/${LIB}/vndk-sp:/vendor/${LIB}/vndk-sp:/data/asan/system/${LIB}/vndk-sp:/system/${LIB}/vndk-sp:/data/asan/system/${LIB}:/system/${LIB}
diff --git a/rootdir/etc/public.libraries.android.txt b/rootdir/etc/public.libraries.android.txt
index e6c94ff..bcdecf2 100644
--- a/rootdir/etc/public.libraries.android.txt
+++ b/rootdir/etc/public.libraries.android.txt
@@ -1,4 +1,5 @@
 libandroid.so
+libaaudio.so
 libc.so
 libcamera2ndk.so
 libdl.so
@@ -12,10 +13,12 @@
 liblog.so
 libmediandk.so
 libm.so
+libnativewindow.so
 libOpenMAXAL.so
 libOpenSLES.so
 libRS.so
 libstdc++.so
+libsync.so
 libvulkan.so
 libwebviewchromium_plat_support.so
 libz.so
diff --git a/rootdir/etc/public.libraries.wear.txt b/rootdir/etc/public.libraries.wear.txt
index 292730a..f4da09d 100644
--- a/rootdir/etc/public.libraries.wear.txt
+++ b/rootdir/etc/public.libraries.wear.txt
@@ -1,4 +1,5 @@
 libandroid.so
+libaaudio.so
 libc.so
 libcamera2ndk.so
 libdl.so
@@ -12,9 +13,11 @@
 liblog.so
 libmediandk.so
 libm.so
+libnativewindow.so
 libOpenMAXAL.so
 libOpenSLES.so
 libRS.so
 libstdc++.so
+libsync.so
 libvulkan.so
 libz.so
diff --git a/rootdir/init.environ.rc.in b/rootdir/init.environ.rc.in
index 32817fa..2e2ab74 100644
--- a/rootdir/init.environ.rc.in
+++ b/rootdir/init.environ.rc.in
@@ -10,3 +10,4 @@
     export BOOTCLASSPATH %BOOTCLASSPATH%
     export SYSTEMSERVERCLASSPATH %SYSTEMSERVERCLASSPATH%
     %EXPORT_GLOBAL_ASAN_OPTIONS%
+    %EXPORT_GLOBAL_GCOV_OPTIONS%
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 7dc9e55..3b996a4 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -7,6 +7,7 @@
 import /init.environ.rc
 import /init.usb.rc
 import /init.${ro.hardware}.rc
+import /vendor/etc/init/hw/init.${ro.hardware}.rc
 import /init.usb.configfs.rc
 import /init.${ro.zygote}.rc
 
@@ -118,13 +119,18 @@
     write /proc/sys/kernel/sched_child_runs_first 0
 
     write /proc/sys/kernel/randomize_va_space 2
-    write /proc/sys/kernel/kptr_restrict 2
     write /proc/sys/vm/mmap_min_addr 32768
     write /proc/sys/net/ipv4/ping_group_range "0 2147483647"
     write /proc/sys/net/unix/max_dgram_qlen 600
     write /proc/sys/kernel/sched_rt_runtime_us 950000
     write /proc/sys/kernel/sched_rt_period_us 1000000
 
+    # Assign reasonable ceiling values for socket rcv/snd buffers.
+    # These should almost always be overridden by the target per the
+    # the corresponding technology maximums.
+    write /proc/sys/net/core/rmem_max  262144
+    write /proc/sys/net/core/wmem_max  262144
+
     # reflect fwmark from incoming packets onto generated replies
     write /proc/sys/net/ipv4/fwmark_reflect 1
     write /proc/sys/net/ipv6/fwmark_reflect 1
@@ -152,25 +158,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
@@ -230,16 +236,16 @@
     # set RLIMIT_NICE to allow priorities from 19 to -20
     setrlimit 13 40 40
 
+    # This allows the ledtrig-transient properties to be created here so
+    # that they can be chown'd to system:system later on boot
+    write /sys/class/leds/vibrator/trigger "transient"
+
 # Healthd can trigger a full boot from charger mode by signaling this
 # property when the power button is held.
 on property:sys.boot_from_charger_mode=1
     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
@@ -260,11 +266,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.
@@ -276,6 +277,9 @@
     # /data, which in turn can only be loaded when system properties are present.
     trigger post-fs-data
 
+    # Now we can start zygote for devices with file based encryption
+    trigger zygote-start
+
     # Load persist properties and override properties (if enabled) from /data.
     trigger load_persist_props_action
 
@@ -285,18 +289,31 @@
     trigger early-boot
     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 servicemanager
+    start hwservicemanager
+    start vndservicemanager
+
     # once everything is setup, no need to modify /
     mount rootfs rootfs / ro remount
     # Mount shared so changes propagate into child namespaces
     mount rootfs rootfs / shared rec
     # Mount default storage into root namespace
-    mount none /mnt/runtime/default /storage slave bind rec
+    mount none /mnt/runtime/default /storage bind rec
+    mount none none /storage slave rec
 
     # Make sure /sys/kernel/debug (if present) is labeled properly
-    restorecon_recursive /sys/kernel/debug
+    # Note that tracefs may be mounted under debug, so we need to cross filesystems
+    restorecon --recursive --cross-filesystems /sys/kernel/debug
+    chmod 0755 /sys/kernel/debug/tracing
 
     # We chown/chmod /cache again so because mount is run as root + defaults
     chown system cache /cache
@@ -333,6 +350,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
@@ -340,10 +361,6 @@
     # We restorecon /data in case the userdata partition has been reset.
     restorecon /data
 
-    # start debuggerd to make debugging early-boot crashes easier.
-    start debuggerd
-    start debuggerd64
-
     # Make sure we have the device encryption key.
     start vold
     installkey /data
@@ -351,19 +368,19 @@
     # Start bootcharting as soon as possible after the data partition is
     # mounted to collect more data.
     mkdir /data/bootchart 0755 shell shell
-    bootchart_init
+    bootchart start
 
     # Avoid predictable entropy pool. Carry over entropy from previous boot.
     copy /data/system/entropy.dat /dev/urandom
 
     # create basic filesystem structure
     mkdir /data/misc 01771 system misc
-    mkdir /data/misc/bluedroid 02770 bluetooth net_bt_stack
+    mkdir /data/misc/bluedroid 02770 bluetooth bluetooth
     # Fix the access permissions and group ownership for 'bt_config.conf'
     chmod 0660 /data/misc/bluedroid/bt_config.conf
-    chown bluetooth net_bt_stack /data/misc/bluedroid/bt_config.conf
-    mkdir /data/misc/bluetooth 0770 bluetooth net_bt_stack
-    mkdir /data/misc/bluetooth/logs 0770 bluetooth net_bt_stack
+    chown bluetooth bluetooth /data/misc/bluedroid/bt_config.conf
+    mkdir /data/misc/bluetooth 0770 bluetooth bluetooth
+    mkdir /data/misc/bluetooth/logs 0770 bluetooth bluetooth
     mkdir /data/misc/keystore 0700 keystore keystore
     mkdir /data/misc/gatekeeper 0700 system system
     mkdir /data/misc/keychain 0771 system system
@@ -371,6 +388,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
@@ -391,11 +409,16 @@
     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 system system
     # profile file layout
     mkdir /data/misc/profiles 0771 system system
     mkdir /data/misc/profiles/cur 0771 system system
     mkdir /data/misc/profiles/ref 0771 system system
     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
@@ -436,9 +459,6 @@
 
     mkdir /data/anr 0775 system system
 
-    # Separate location for storing security policy files on data
-    mkdir /data/security 0711 system system
-
     # Create all remaining /data root dirs so that they are made through init
     # and get proper encryption policy installed
     mkdir /data/backup 0700 system system
@@ -468,21 +488,41 @@
 
     init_user0
 
-    # Reload policy from /data/security if present.
-    setprop selinux.reload_policy 1
-
     # Set SELinux security contexts on upgrade or policy update.
-    restorecon_recursive /data
+    restorecon --recursive --skip-ce /data
 
     # Check any timezone data in /data is newer than the copy in /system, delete if not.
     exec - system system -- /system/bin/tzdatacheck /system/usr/share/zoneinfo /data/misc/zoneinfo
 
-    # If there is no fs-post-data action in the init.<device>.rc file, you
+    # If there is no post-fs-data action in the init.<device>.rc file, you
     # must uncomment this line, otherwise encrypted filesystems
     # won't work.
     # Set indication (checked by vold) that we have finished this action
     #setprop vold.post_fs_data_done 1
 
+# 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
+    # 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
     ifup lo
@@ -546,6 +586,11 @@
     chown system system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
     chmod 0660 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
 
+    chown system system /sys/class/leds/vibrator/trigger
+    chown system system /sys/class/leds/vibrator/activate
+    chown system system /sys/class/leds/vibrator/brightness
+    chown system system /sys/class/leds/vibrator/duration
+    chown system system /sys/class/leds/vibrator/state
     chown system system /sys/class/timed_output/vibrator/enable
     chown system system /sys/class/leds/keyboard-backlight/brightness
     chown system system /sys/class/leds/lcd-backlight/brightness
@@ -557,7 +602,6 @@
     chown system system /sys/class/leds/red/device/grpfreq
     chown system system /sys/class/leds/red/device/grppwm
     chown system system /sys/class/leds/red/device/blink
-    chown system system /sys/class/timed_output/vibrator/enable
     chown system system /sys/module/sco/parameters/disable_esco
     chown system system /sys/kernel/ipv4/tcp_wmem_min
     chown system system /sys/kernel/ipv4/tcp_wmem_def
@@ -570,11 +614,12 @@
     # Define default initial receive window size in segments.
     setprop net.tcp.default_init_rwnd 60
 
+    # 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
 
@@ -597,12 +642,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
 
@@ -610,8 +655,8 @@
     class_reset late_start
     class_reset main
 
-on property:sys.powerctl=*
-    powerctl ${sys.powerctl}
+on property:sys.boot_completed=1
+    bootchart stop
 
 # system server cannot write to /proc/sys files,
 # and chown/chmod does not work for /proc/sys/ entries.
@@ -636,10 +681,9 @@
     critical
     seclabel u:r:ueventd:s0
 
-service healthd /sbin/healthd
+service healthd /system/bin/healthd
     class core
     critical
-    seclabel u:r:healthd:s0
     group root system wakelock
 
 service console /system/bin/sh
diff --git a/rootdir/init.usb.configfs.rc b/rootdir/init.usb.configfs.rc
index 186384b..32f0198 100644
--- a/rootdir/init.usb.configfs.rc
+++ b/rootdir/init.usb.configfs.rc
@@ -1,9 +1,14 @@
 on property:sys.usb.config=none && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/UDC "none"
     stop adbd
+    setprop sys.usb.ffs.ready 0
     write /config/usb_gadget/g1/bDeviceClass 0
     write /config/usb_gadget/g1/bDeviceSubClass 0
     write /config/usb_gadget/g1/bDeviceProtocol 0
+    rm /config/usb_gadget/g1/configs/b.1/f1
+    rm /config/usb_gadget/g1/configs/b.1/f2
+    rm /config/usb_gadget/g1/configs/b.1/f3
+    rmdir /config/usb_gadget/g1/functions/rndis.gs4
     setprop sys.usb.state ${sys.usb.config}
 
 on property:sys.usb.config=adb && property:sys.usb.configfs=1
@@ -11,18 +16,12 @@
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f1
     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
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     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}
     setprop sys.usb.state ${sys.usb.config}
@@ -32,9 +31,6 @@
 
 on property:sys.usb.ffs.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"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     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}
@@ -42,9 +38,6 @@
 
 on property:sys.usb.config=ptp && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "ptp"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     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}
     setprop sys.usb.state ${sys.usb.config}
@@ -54,9 +47,6 @@
 
 on property:sys.usb.ffs.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"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     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
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
@@ -64,9 +54,6 @@
 
 on property:sys.usb.config=accessory && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
@@ -76,9 +63,6 @@
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=accessory,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/accessory.gs2 /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}
@@ -86,10 +70,7 @@
 
 on property:sys.usb.config=audio_source && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "audiosource"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
-    symlink /config/usb_gadget/g1/functions/audio_source.gs2 /config/usb_gadget/g1/configs/b.1/f1
+    symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
 
@@ -98,19 +79,13 @@
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=audio_source,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "audiosource_adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
-    symlink /config/usb_gadget/g1/functions/audio_source.gs2 /config/usb_gadget/g1/configs/b.1/f1
+    symlink /config/usb_gadget/g1/functions/audio_source.gs3 /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=accessory,audio_source && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_audiosource"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1
     symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f2
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
@@ -121,9 +96,6 @@
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=accessory,audio_source,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_audiosource_adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1
     symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f2
     symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f3
@@ -132,9 +104,6 @@
 
 on property:sys.usb.config=midi && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "midi"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/midi.gs5 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
@@ -144,19 +113,14 @@
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=midi,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "midi_adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/midi.gs5 /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=rndis && property:sys.usb.configfs=1
+    mkdir /config/usb_gadget/g1/functions/rndis.gs4
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "rndis"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/rndis.gs4 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
@@ -165,10 +129,8 @@
     start adbd
 
 on property:sys.usb.ffs.ready=1 && property:sys.usb.config=rndis,adb && property:sys.usb.configfs=1
+    mkdir /config/usb_gadget/g1/functions/rndis.gs4
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "rndis_adb"
-    rm /config/usb_gadget/g1/configs/b.1/f1
-    rm /config/usb_gadget/g1/configs/b.1/f2
-    rm /config/usb_gadget/g1/configs/b.1/f3
     symlink /config/usb_gadget/g1/functions/rndis.gs4 /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}
diff --git a/rootdir/init.zygote32.rc b/rootdir/init.zygote32.rc
index b41af92..d836c4e 100644
--- a/rootdir/init.zygote32.rc
+++ b/rootdir/init.zygote32.rc
@@ -1,5 +1,8 @@
 service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -7,4 +10,5 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
+    onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote32_64.rc b/rootdir/init.zygote32_64.rc
index 2914f07..80bb673 100644
--- a/rootdir/init.zygote32_64.rc
+++ b/rootdir/init.zygote32_64.rc
@@ -1,5 +1,8 @@
 service zygote /system/bin/app_process32 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -7,10 +10,14 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
+    onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks
 
 service zygote_secondary /system/bin/app_process64 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote64.rc b/rootdir/init.zygote64.rc
index 2cc0966..05ec16f 100644
--- a/rootdir/init.zygote64.rc
+++ b/rootdir/init.zygote64.rc
@@ -1,5 +1,8 @@
 service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -7,4 +10,5 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
+    onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index a422fcc..09db7b0 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -1,5 +1,8 @@
 service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -7,10 +10,14 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
+    onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks
 
-service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
+service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload
     class main
+    priority -20
+    user root
+    group root readproc
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index 6ef491c..f5c93b7 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -19,6 +19,8 @@
 /dev/hw_random            0440   root       system
 /dev/ashmem               0666   root       root
 /dev/binder               0666   root       root
+/dev/hwbinder             0666   root       root
+/dev/vndbinder            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.
@@ -37,11 +39,9 @@
 # these should not be world writable
 /dev/diag                 0660   radio      radio
 /dev/diag_arm9            0660   radio      radio
-/dev/android_adb          0660   adb        adb
-/dev/android_adb_enable   0660   adb        adb
 /dev/ttyMSM0              0600   bluetooth  bluetooth
-/dev/uhid                 0660   system     net_bt_stack
-/dev/uinput               0660   system     net_bt_stack
+/dev/uhid                 0660   system     bluetooth
+/dev/uinput               0660   system     bluetooth
 /dev/alarm                0664   system     radio
 /dev/rtc0                 0640   system     system
 /dev/tty0                 0660   root       system
diff --git a/run-as/Android.mk b/run-as/Android.mk
index 3774acc..7111fbe 100644
--- a/run-as/Android.mk
+++ b/run-as/Android.mk
@@ -1,12 +1,8 @@
 LOCAL_PATH:= $(call my-dir)
+
 include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := run-as.c package.c
-
-LOCAL_SHARED_LIBRARIES := libselinux
-
+LOCAL_CFLAGS := -Wall -Werror
 LOCAL_MODULE := run-as
-
-LOCAL_CFLAGS := -Werror
-
+LOCAL_SHARED_LIBRARIES := libselinux libpackagelistparser libminijail
+LOCAL_SRC_FILES := run-as.cpp
 include $(BUILD_EXECUTABLE)
diff --git a/run-as/package.c b/run-as/package.c
deleted file mode 100644
index 86824c2..0000000
--- a/run-as/package.c
+++ /dev/null
@@ -1,560 +0,0 @@
-/*
-**
-** Copyright 2010, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <private/android_filesystem_config.h>
-#include "package.h"
-
-/*
- *  WARNING WARNING WARNING WARNING
- *
- *  The following code runs as root on production devices, before
- *  the run-as command has dropped the uid/gid. Hence be very
- *  conservative and keep in mind the following:
- *
- *  - Performance does not matter here, clarity and safety of the code
- *    does however. Documentation is a must.
- *
- *  - Avoid calling C library functions with complex implementations
- *    like malloc() and printf(). You want to depend on simple system
- *    calls instead, which behaviour is not going to be altered in
- *    unpredictible ways by environment variables or system properties.
- *
- *  - Do not trust user input and/or the filesystem whenever possible.
- *
- */
-
-/* The file containing the list of installed packages on the system */
-#define PACKAGES_LIST_FILE  "/data/system/packages.list"
-
-/* Copy 'srclen' string bytes from 'src' into buffer 'dst' of size 'dstlen'
- * This function always zero-terminate the destination buffer unless
- * 'dstlen' is 0, even in case of overflow.
- * Returns a pointer into the src string, leaving off where the copy
- * has stopped. The copy will stop when dstlen, srclen or a null
- * character on src has been reached.
- */
-static const char*
-string_copy(char* dst, size_t dstlen, const char* src, size_t srclen)
-{
-    const char* srcend = src + srclen;
-    const char* dstend = dst + dstlen;
-
-    if (dstlen == 0)
-        return src;
-
-    dstend--; /* make room for terminating zero */
-
-    while (dst < dstend && src < srcend && *src != '\0')
-        *dst++ = *src++;
-
-    *dst = '\0'; /* zero-terminate result */
-    return src;
-}
-
-/* Open 'filename' and map it into our address-space.
- * Returns buffer address, or NULL on error
- * On exit, *filesize will be set to the file's size, or 0 on error
- */
-static void*
-map_file(const char* filename, size_t* filesize)
-{
-    int  fd, ret, old_errno;
-    struct stat  st;
-    size_t  length = 0;
-    void*   address = NULL;
-    gid_t   oldegid;
-
-    *filesize = 0;
-
-    /*
-     * Temporarily switch effective GID to allow us to read
-     * the packages file
-     */
-
-    oldegid = getegid();
-    if (setegid(AID_PACKAGE_INFO) < 0) {
-        return NULL;
-    }
-
-    /* open the file for reading */
-    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
-    if (fd < 0) {
-        return NULL;
-    }
-
-    /* restore back to our old egid */
-    if (setegid(oldegid) < 0) {
-        goto EXIT;
-    }
-
-    /* get its size */
-    ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
-    if (ret < 0)
-        goto EXIT;
-
-    /* Ensure that the file is owned by the system user */
-    if ((st.st_uid != AID_SYSTEM) || (st.st_gid != AID_PACKAGE_INFO)) {
-        goto EXIT;
-    }
-
-    /* Ensure that the file has sane permissions */
-    if ((st.st_mode & S_IWOTH) != 0) {
-        goto EXIT;
-    }
-
-    /* Ensure that the size is not ridiculously large */
-    length = (size_t)st.st_size;
-    if ((off_t)length != st.st_size) {
-        errno = ENOMEM;
-        goto EXIT;
-    }
-
-    /* Memory-map the file now */
-    do {
-        address = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
-    } while (address == MAP_FAILED && errno == EINTR);
-    if (address == MAP_FAILED) {
-        address = NULL;
-        goto EXIT;
-    }
-
-    /* We're good, return size */
-    *filesize = length;
-
-EXIT:
-    /* close the file, preserve old errno for better diagnostics */
-    old_errno = errno;
-    close(fd);
-    errno = old_errno;
-
-    return address;
-}
-
-/* unmap the file, but preserve errno */
-static void
-unmap_file(void*  address, size_t  size)
-{
-    int old_errno = errno;
-    TEMP_FAILURE_RETRY(munmap(address, size));
-    errno = old_errno;
-}
-
-/* Check that a given directory:
- * - exists
- * - is owned by a given uid/gid
- * - is a real directory, not a symlink
- * - isn't readable or writable by others
- *
- * Return 0 on success, or -1 on error.
- * errno is set to EINVAL in case of failed check.
- */
-static int
-check_directory_ownership(const char* path, uid_t uid)
-{
-    int ret;
-    struct stat st;
-
-    do {
-        ret = lstat(path, &st);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0)
-        return -1;
-
-    /* /data/user/0 is a known safe symlink */
-    if (strcmp("/data/user/0", path) == 0)
-        return 0;
-
-    /* must be a real directory, not a symlink */
-    if (!S_ISDIR(st.st_mode))
-        goto BAD;
-
-    /* must be owned by specific uid/gid */
-    if (st.st_uid != uid || st.st_gid != uid)
-        goto BAD;
-
-    /* must not be readable or writable by others */
-    if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0)
-        goto BAD;
-
-    /* everything ok */
-    return 0;
-
-BAD:
-    errno = EINVAL;
-    return -1;
-}
-
-/* This function is used to check the data directory path for safety.
- * We check that every sub-directory is owned by the 'system' user
- * and exists and is not a symlink. We also check that the full directory
- * path is properly owned by the user ID.
- *
- * Return 0 on success, -1 on error.
- */
-int
-check_data_path(const char* dataPath, uid_t  uid)
-{
-    int  nn;
-
-    /* the path should be absolute */
-    if (dataPath[0] != '/') {
-        errno = EINVAL;
-        return -1;
-    }
-
-    /* look for all sub-paths, we do that by finding
-     * directory separators in the input path and
-     * checking each sub-path independently
-     */
-    for (nn = 1; dataPath[nn] != '\0'; nn++)
-    {
-        char subpath[PATH_MAX];
-
-        /* skip non-separator characters */
-        if (dataPath[nn] != '/')
-            continue;
-
-        /* handle trailing separator case */
-        if (dataPath[nn+1] == '\0') {
-            break;
-        }
-
-        /* found a separator, check that dataPath is not too long. */
-        if (nn >= (int)(sizeof subpath)) {
-            errno = EINVAL;
-            return -1;
-        }
-
-        /* reject any '..' subpath */
-        if (nn >= 3               &&
-            dataPath[nn-3] == '/' &&
-            dataPath[nn-2] == '.' &&
-            dataPath[nn-1] == '.') {
-            errno = EINVAL;
-            return -1;
-        }
-
-        /* copy to 'subpath', then check ownership */
-        memcpy(subpath, dataPath, nn);
-        subpath[nn] = '\0';
-
-        if (check_directory_ownership(subpath, AID_SYSTEM) < 0)
-            return -1;
-    }
-
-    /* All sub-paths were checked, now verify that the full data
-     * directory is owned by the application uid
-     */
-    if (check_directory_ownership(dataPath, uid) < 0)
-        return -1;
-
-    /* all clear */
-    return 0;
-}
-
-/* Return TRUE iff a character is a space or tab */
-static inline int
-is_space(char c)
-{
-    return (c == ' ' || c == '\t');
-}
-
-/* Skip any space or tab character from 'p' until 'end' is reached.
- * Return new position.
- */
-static const char*
-skip_spaces(const char*  p, const char*  end)
-{
-    while (p < end && is_space(*p))
-        p++;
-
-    return p;
-}
-
-/* Skip any non-space and non-tab character from 'p' until 'end'.
- * Return new position.
- */
-static const char*
-skip_non_spaces(const char* p, const char* end)
-{
-    while (p < end && !is_space(*p))
-        p++;
-
-    return p;
-}
-
-/* Find the first occurence of 'ch' between 'p' and 'end'
- * Return its position, or 'end' if none is found.
- */
-static const char*
-find_first(const char* p, const char* end, char ch)
-{
-    while (p < end && *p != ch)
-        p++;
-
-    return p;
-}
-
-/* Check that the non-space string starting at 'p' and eventually
- * ending at 'end' equals 'name'. Return new position (after name)
- * on success, or NULL on failure.
- *
- * This function fails is 'name' is NULL, empty or contains any space.
- */
-static const char*
-compare_name(const char* p, const char* end, const char* name)
-{
-    /* 'name' must not be NULL or empty */
-    if (name == NULL || name[0] == '\0' || p == end)
-        return NULL;
-
-    /* compare characters to those in 'name', excluding spaces */
-    while (*name) {
-        /* note, we don't check for *p == '\0' since
-         * it will be caught in the next conditional.
-         */
-        if (p >= end || is_space(*p))
-            goto BAD;
-
-        if (*p != *name)
-            goto BAD;
-
-        p++;
-        name++;
-    }
-
-    /* must be followed by end of line or space */
-    if (p < end && !is_space(*p))
-        goto BAD;
-
-    return p;
-
-BAD:
-    return NULL;
-}
-
-/* Parse one or more whitespace characters starting from '*pp'
- * until 'end' is reached. Updates '*pp' on exit.
- *
- * Return 0 on success, -1 on failure.
- */
-static int
-parse_spaces(const char** pp, const char* end)
-{
-    const char* p = *pp;
-
-    if (p >= end || !is_space(*p)) {
-        errno = EINVAL;
-        return -1;
-    }
-    p   = skip_spaces(p, end);
-    *pp = p;
-    return 0;
-}
-
-/* Parse a positive decimal number starting from '*pp' until 'end'
- * is reached. Adjust '*pp' on exit. Return decimal value or -1
- * in case of error.
- *
- * If the value is larger than INT_MAX, -1 will be returned,
- * and errno set to EOVERFLOW.
- *
- * If '*pp' does not start with a decimal digit, -1 is returned
- * and errno set to EINVAL.
- */
-static int
-parse_positive_decimal(const char** pp, const char* end)
-{
-    const char* p = *pp;
-    int value = 0;
-    int overflow = 0;
-
-    if (p >= end || *p < '0' || *p > '9') {
-        errno = EINVAL;
-        return -1;
-    }
-
-    while (p < end) {
-        int      ch = *p;
-        unsigned d  = (unsigned)(ch - '0');
-        int      val2;
-
-        if (d >= 10U) /* d is unsigned, no lower bound check */
-            break;
-
-        val2 = value*10 + (int)d;
-        if (val2 < value)
-            overflow = 1;
-        value = val2;
-        p++;
-    }
-    *pp = p;
-
-    if (overflow) {
-        errno = EOVERFLOW;
-        value = -1;
-    }
-    return value;
-}
-
-/* Read the system's package database and extract information about
- * 'pkgname'. Return 0 in case of success, or -1 in case of error.
- *
- * If the package is unknown, return -1 and set errno to ENOENT
- * If the package database is corrupted, return -1 and set errno to EINVAL
- */
-int
-get_package_info(const char* pkgName, uid_t userId, PackageInfo *info)
-{
-    char*        buffer;
-    size_t       buffer_len;
-    const char*  p;
-    const char*  buffer_end;
-    int          result = -1;
-
-    info->uid          = 0;
-    info->isDebuggable = 0;
-    info->dataDir[0]   = '\0';
-    info->seinfo[0]    = '\0';
-
-    buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
-    if (buffer == NULL)
-        return -1;
-
-    p          = buffer;
-    buffer_end = buffer + buffer_len;
-
-    /* expect the following format on each line of the control file:
-     *
-     *  <pkgName> <uid> <debugFlag> <dataDir> <seinfo>
-     *
-     * where:
-     *  <pkgName>    is the package's name
-     *  <uid>        is the application-specific user Id (decimal)
-     *  <debugFlag>  is 1 if the package is debuggable, or 0 otherwise
-     *  <dataDir>    is the path to the package's data directory (e.g. /data/data/com.example.foo)
-     *  <seinfo>     is the seinfo label associated with the package
-     *
-     * The file is generated in com.android.server.PackageManagerService.Settings.writeLP()
-     */
-
-    while (p < buffer_end) {
-        /* find end of current line and start of next one */
-        const char*  end  = find_first(p, buffer_end, '\n');
-        const char*  next = (end < buffer_end) ? end + 1 : buffer_end;
-        const char*  q;
-        int          uid, debugFlag;
-
-        /* first field is the package name */
-        p = compare_name(p, end, pkgName);
-        if (p == NULL)
-            goto NEXT_LINE;
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* second field is the pid */
-        uid = parse_positive_decimal(&p, end);
-        if (uid < 0)
-            return -1;
-
-        info->uid = (uid_t) uid;
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* third field is debug flag (0 or 1) */
-        debugFlag = parse_positive_decimal(&p, end);
-        switch (debugFlag) {
-        case 0:
-            info->isDebuggable = 0;
-            break;
-        case 1:
-            info->isDebuggable = 1;
-            break;
-        default:
-            goto BAD_FORMAT;
-        }
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* fourth field is data directory path and must not contain
-         * spaces.
-         */
-        q = skip_non_spaces(p, end);
-        if (q == p)
-            goto BAD_FORMAT;
-
-        /* If userId == 0 (i.e. user is device owner) we can use dataDir value
-         * from packages.list, otherwise compose data directory as
-         * /data/user/$uid/$packageId
-         */
-        if (userId == 0) {
-            p = string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
-        } else {
-            snprintf(info->dataDir,
-                     sizeof info->dataDir,
-                     "/data/user/%d/%s",
-                     userId,
-                     pkgName);
-            p = q;
-        }
-
-        /* skip spaces */
-        if (parse_spaces(&p, end) < 0)
-            goto BAD_FORMAT;
-
-        /* fifth field is the seinfo string */
-        q = skip_non_spaces(p, end);
-        if (q == p)
-            goto BAD_FORMAT;
-
-        string_copy(info->seinfo, sizeof info->seinfo, p, q - p);
-
-        /* Ignore the rest */
-        result = 0;
-        goto EXIT;
-
-    NEXT_LINE:
-        p = next;
-    }
-
-    /* the package is unknown */
-    errno = ENOENT;
-    result = -1;
-    goto EXIT;
-
-BAD_FORMAT:
-    errno = EINVAL;
-    result = -1;
-
-EXIT:
-    unmap_file(buffer, buffer_len);
-    return result;
-}
diff --git a/run-as/package.h b/run-as/package.h
deleted file mode 100644
index eeb5913..0000000
--- a/run-as/package.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-**
-** Copyright 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 RUN_AS_PACKAGE_H
-#define RUN_AS_PACKAGE_H
-
-#include <limits.h>
-#include <sys/types.h>
-
-typedef enum {
-    PACKAGE_IS_DEBUGGABLE = 0,
-    PACKAGE_IS_NOT_DEBUGGABLE,
-    PACKAGE_IS_UNKNOWN,
-} PackageStatus;
-
-typedef struct {
-    uid_t  uid;
-    char   isDebuggable;
-    char   dataDir[PATH_MAX];
-    char   seinfo[PATH_MAX];
-} PackageInfo;
-
-/* see documentation in package.c for these functions */
-
-extern int  get_package_info(const char* packageName,
-                             uid_t userId,
-                             PackageInfo*  info);
-
-extern int  check_data_path(const char* dataDir, uid_t uid);
-
-#endif /* RUN_AS_PACKAGE_H */
diff --git a/run-as/run-as.c b/run-as/run-as.c
deleted file mode 100644
index f0fd2fe..0000000
--- a/run-as/run-as.c
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
-**
-** Copyright 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.
-*/
-
-#define PROGNAME "run-as"
-#define LOG_TAG  PROGNAME
-
-#include <dirent.h>
-#include <errno.h>
-#include <paths.h>
-#include <pwd.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/capability.h>
-#include <sys/cdefs.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <private/android_filesystem_config.h>
-#include <selinux/android.h>
-
-#include "package.h"
-
-/*
- *  WARNING WARNING WARNING WARNING
- *
- *  This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
- *  production devices. Be very conservative when modifying it to avoid any
- *  serious security issue. Keep in mind the following:
- *
- *  - This program should only run for the 'root' or 'shell' users
- *
- *  - Avoid anything that is more complex than simple system calls
- *    until the uid/gid has been dropped to that of a normal user
- *    or you are sure to exit.
- *
- *    This avoids depending on environment variables, system properties
- *    and other external factors that may affect the C library in
- *    unpredictable ways.
- *
- *  - Do not trust user input and/or the filesystem whenever possible.
- *
- *  Read README.TXT for more details.
- *
- *
- *
- * The purpose of this program is to run a command as a specific
- * application user-id. Typical usage is:
- *
- *   run-as <package-name> <command> <args>
- *
- *  The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
- *  capabilities, but will check the following:
- *
- *  - that it is invoked from the 'shell' or 'root' user (abort otherwise)
- *  - that '<package-name>' is the name of an installed and debuggable package
- *  - that the package's data directory is well-formed (see package.c)
- *
- *  If so, it will drop to the application's user id / group id, cd to the
- *  package's data directory, then run the command there.
- *
- *  NOTE: In the future it might not be possible to cd to the package's data
- *  directory under that package's user id / group id, in which case this
- *  utility will need to be changed accordingly.
- *
- *  This can be useful for a number of different things on production devices:
- *
- *  - Allow application developers to look at their own applicative data
- *    during development.
- *
- *  - Run the 'gdbserver' binary executable to allow native debugging
- */
-
-__noreturn static void
-panic(const char* format, ...)
-{
-    va_list args;
-    int e = errno;
-
-    fprintf(stderr, "%s: ", PROGNAME);
-    va_start(args, format);
-    vfprintf(stderr, format, args);
-    va_end(args);
-    exit(e ? -e : 1);
-}
-
-static void
-usage(void)
-{
-    panic("Usage:\n    " PROGNAME " <package-name> [--user <uid>] <command> [<args>]\n");
-}
-
-int main(int argc, char **argv)
-{
-    const char* pkgname;
-    uid_t myuid, uid, gid, userAppId = 0;
-    int commandArgvOfs = 2, userId = 0;
-    PackageInfo info;
-    struct __user_cap_header_struct capheader;
-    struct __user_cap_data_struct capdata[2];
-
-    /* check arguments */
-    if (argc < 2) {
-        usage();
-    }
-
-    /* check userid of caller - must be 'shell' or 'root' */
-    myuid = getuid();
-    if (myuid != AID_SHELL && myuid != AID_ROOT) {
-        panic("only 'shell' or 'root' users can run this program\n");
-    }
-
-    memset(&capheader, 0, sizeof(capheader));
-    memset(&capdata, 0, sizeof(capdata));
-    capheader.version = _LINUX_CAPABILITY_VERSION_3;
-    capdata[CAP_TO_INDEX(CAP_SETUID)].effective |= CAP_TO_MASK(CAP_SETUID);
-    capdata[CAP_TO_INDEX(CAP_SETGID)].effective |= CAP_TO_MASK(CAP_SETGID);
-    capdata[CAP_TO_INDEX(CAP_SETUID)].permitted |= CAP_TO_MASK(CAP_SETUID);
-    capdata[CAP_TO_INDEX(CAP_SETGID)].permitted |= CAP_TO_MASK(CAP_SETGID);
-
-    if (capset(&capheader, &capdata[0]) < 0) {
-        panic("Could not set capabilities: %s\n", strerror(errno));
-    }
-
-    pkgname = argv[1];
-
-    /* get user_id from command line if provided */
-    if ((argc >= 4) && !strcmp(argv[2], "--user")) {
-        userId = atoi(argv[3]);
-        if (userId < 0)
-            panic("Negative user id %d is provided\n", userId);
-        commandArgvOfs += 2;
-    }
-
-    /* retrieve package information from system (does setegid) */
-    if (get_package_info(pkgname, userId, &info) < 0) {
-        panic("Package '%s' is unknown\n", pkgname);
-    }
-
-    /* verify that user id is not too big. */
-    if ((UID_MAX - info.uid) / AID_USER < (uid_t)userId) {
-        panic("User id %d is too big\n", userId);
-    }
-
-    /* calculate user app ID. */
-    userAppId = (AID_USER * userId) + info.uid;
-
-    /* reject system packages */
-    if (userAppId < AID_APP) {
-        panic("Package '%s' is not an application\n", pkgname);
-    }
-
-    /* reject any non-debuggable package */
-    if (!info.isDebuggable) {
-        panic("Package '%s' is not debuggable\n", pkgname);
-    }
-
-    /* check that the data directory path is valid */
-    if (check_data_path(info.dataDir, userAppId) < 0) {
-        panic("Package '%s' has corrupt installation\n", pkgname);
-    }
-
-    /* Ensure that we change all real/effective/saved IDs at the
-     * same time to avoid nasty surprises.
-     */
-    uid = gid = userAppId;
-    if(setresgid(gid,gid,gid) || setresuid(uid,uid,uid)) {
-        panic("Permission denied\n");
-    }
-
-    /* Required if caller has uid and gid all non-zero */
-    memset(&capdata, 0, sizeof(capdata));
-    if (capset(&capheader, &capdata[0]) < 0) {
-        panic("Could not clear all capabilities: %s\n", strerror(errno));
-    }
-
-    if (selinux_android_setcontext(uid, 0, info.seinfo, pkgname) < 0) {
-        panic("Could not set SELinux security context: %s\n", strerror(errno));
-    }
-
-    // cd into the data directory, and set $HOME correspondingly.
-    if (TEMP_FAILURE_RETRY(chdir(info.dataDir)) < 0) {
-        panic("Could not cd to package's data directory: %s\n", strerror(errno));
-    }
-    setenv("HOME", info.dataDir, 1);
-
-    // Reset parts of the environment, like su would.
-    setenv("PATH", _PATH_DEFPATH, 1);
-    unsetenv("IFS");
-
-    // Set the user-specific parts for this user.
-    struct passwd* pw = getpwuid(uid);
-    setenv("LOGNAME", pw->pw_name, 1);
-    setenv("SHELL", pw->pw_shell, 1);
-    setenv("USER", pw->pw_name, 1);
-
-    /* User specified command for exec. */
-    if ((argc >= commandArgvOfs + 1) &&
-        (execvp(argv[commandArgvOfs], argv+commandArgvOfs) < 0)) {
-        panic("exec failed for %s: %s\n", argv[commandArgvOfs], strerror(errno));
-    }
-
-    /* Default exec shell. */
-    execlp("/system/bin/sh", "sh", NULL);
-
-    panic("exec failed: %s\n", strerror(errno));
-}
diff --git a/run-as/run-as.cpp b/run-as/run-as.cpp
new file mode 100644
index 0000000..e7b8cc2
--- /dev/null
+++ b/run-as/run-as.cpp
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <error.h>
+#include <paths.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/capability.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <libminijail.h>
+#include <scoped_minijail.h>
+
+#include <packagelistparser/packagelistparser.h>
+#include <private/android_filesystem_config.h>
+#include <selinux/android.h>
+
+// The purpose of this program is to run a command as a specific
+// application user-id. Typical usage is:
+//
+//   run-as <package-name> <command> <args>
+//
+//  The 'run-as' binary is installed with CAP_SETUID and CAP_SETGID file
+//  capabilities, but will check the following:
+//
+//  - that it is invoked from the 'shell' or 'root' user (abort otherwise)
+//  - that '<package-name>' is the name of an installed and debuggable package
+//  - that the package's data directory is well-formed
+//
+//  If so, it will drop to the application's user id / group id, cd to the
+//  package's data directory, then run the command there.
+//
+//  This can be useful for a number of different things on production devices:
+//
+//  - Allow application developers to look at their own application data
+//    during development.
+//
+//  - Run the 'gdbserver' binary executable to allow native debugging
+//
+
+static bool packagelist_parse_callback(pkg_info* this_package, void* userdata) {
+  pkg_info* p = reinterpret_cast<pkg_info*>(userdata);
+  if (strcmp(p->name, this_package->name) == 0) {
+    *p = *this_package;
+    return false; // Stop searching.
+  }
+  packagelist_free(this_package);
+  return true; // Keep searching.
+}
+
+static bool check_directory(const char* path, uid_t uid) {
+  struct stat st;
+  if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) return false;
+
+  // /data/user/0 is a known safe symlink.
+  if (strcmp("/data/user/0", path) == 0) return true;
+
+  // Must be a real directory, not a symlink.
+  if (!S_ISDIR(st.st_mode)) return false;
+
+  // Must be owned by specific uid/gid.
+  if (st.st_uid != uid || st.st_gid != uid) return false;
+
+  // Must not be readable or writable by others.
+  if ((st.st_mode & (S_IROTH|S_IWOTH)) != 0) return false;
+
+  return true;
+}
+
+// This function is used to check the data directory path for safety.
+// We check that every sub-directory is owned by the 'system' user
+// and exists and is not a symlink. We also check that the full directory
+// path is properly owned by the user ID.
+static bool check_data_path(const char* data_path, uid_t uid) {
+  // The path should be absolute.
+  if (data_path[0] != '/') return false;
+
+  // Look for all sub-paths, we do that by finding
+  // directory separators in the input path and
+  // checking each sub-path independently.
+  for (int nn = 1; data_path[nn] != '\0'; nn++) {
+    char subpath[PATH_MAX];
+
+    /* skip non-separator characters */
+    if (data_path[nn] != '/') continue;
+
+    /* handle trailing separator case */
+    if (data_path[nn+1] == '\0') break;
+
+    /* found a separator, check that data_path is not too long. */
+    if (nn >= (int)(sizeof subpath)) return false;
+
+    /* reject any '..' subpath */
+    if (nn >= 3               &&
+        data_path[nn-3] == '/' &&
+        data_path[nn-2] == '.' &&
+        data_path[nn-1] == '.') {
+      return false;
+    }
+
+    /* copy to 'subpath', then check ownership */
+    memcpy(subpath, data_path, nn);
+    subpath[nn] = '\0';
+
+    if (!check_directory(subpath, AID_SYSTEM)) return false;
+  }
+
+  // All sub-paths were checked, now verify that the full data
+  // directory is owned by the application uid.
+  return check_directory(data_path, uid);
+}
+
+int main(int argc, char* argv[]) {
+  // Check arguments.
+  if (argc < 2) {
+    error(1, 0, "usage: run-as <package-name> [--user <uid>] <command> [<args>]\n");
+  }
+
+  // This program runs with CAP_SETUID and CAP_SETGID capabilities on Android
+  // production devices. Check user id of caller --- must be 'shell' or 'root'.
+  if (getuid() != AID_SHELL && getuid() != AID_ROOT) {
+    error(1, 0, "only 'shell' or 'root' users can run this program");
+  }
+
+  char* pkgname = argv[1];
+  int cmd_argv_offset = 2;
+
+  // Get user_id from command line if provided.
+  int userId = 0;
+  if ((argc >= 4) && !strcmp(argv[2], "--user")) {
+    userId = atoi(argv[3]);
+    if (userId < 0) error(1, 0, "negative user id: %d", userId);
+    cmd_argv_offset += 2;
+  }
+
+  // Retrieve package information from system, switching egid so we can read the file.
+  gid_t old_egid = getegid();
+  if (setegid(AID_PACKAGE_INFO) == -1) error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
+  pkg_info info;
+  memset(&info, 0, sizeof(info));
+  info.name = pkgname;
+  if (!packagelist_parse(packagelist_parse_callback, &info)) {
+    error(1, errno, "packagelist_parse failed");
+  }
+  if (info.uid == 0) {
+    error(1, 0, "unknown package: %s", pkgname);
+  }
+  if (setegid(old_egid) == -1) error(1, errno, "couldn't restore egid");
+
+  // Verify that user id is not too big.
+  if ((UID_MAX - info.uid) / AID_USER_OFFSET < (uid_t)userId) {
+    error(1, 0, "user id too big: %d", userId);
+  }
+
+  // Calculate user app ID.
+  uid_t userAppId = (AID_USER_OFFSET * userId) + info.uid;
+
+  // Reject system packages.
+  if (userAppId < AID_APP) {
+    error(1, 0, "package not an application: %s", pkgname);
+  }
+
+  // Reject any non-debuggable package.
+  if (!info.debuggable) {
+    error(1, 0, "package not debuggable: %s", pkgname);
+  }
+
+  // Check that the data directory path is valid.
+  if (!check_data_path(info.data_dir, userAppId)) {
+    error(1, 0, "package has corrupt installation: %s", pkgname);
+  }
+
+  // Ensure that we change all real/effective/saved IDs at the
+  // same time to avoid nasty surprises.
+  uid_t uid = userAppId;
+  uid_t gid = userAppId;
+  ScopedMinijail j(minijail_new());
+  minijail_change_uid(j.get(), uid);
+  minijail_change_gid(j.get(), gid);
+  minijail_enter(j.get());
+
+  if (selinux_android_setcontext(uid, 0, info.seinfo, pkgname) < 0) {
+    error(1, errno, "couldn't set SELinux security context");
+  }
+
+  // cd into the data directory, and set $HOME correspondingly.
+  if (TEMP_FAILURE_RETRY(chdir(info.data_dir)) == -1) {
+    error(1, errno, "couldn't chdir to package's data directory");
+  }
+  setenv("HOME", info.data_dir, 1);
+
+  // Reset parts of the environment, like su would.
+  setenv("PATH", _PATH_DEFPATH, 1);
+  unsetenv("IFS");
+
+  // Set the user-specific parts for this user.
+  passwd* pw = getpwuid(uid);
+  setenv("LOGNAME", pw->pw_name, 1);
+  setenv("SHELL", pw->pw_shell, 1);
+  setenv("USER", pw->pw_name, 1);
+
+  // User specified command for exec.
+  if ((argc >= cmd_argv_offset + 1) &&
+      (execvp(argv[cmd_argv_offset], argv+cmd_argv_offset) == -1)) {
+    error(1, errno, "exec failed for %s", argv[cmd_argv_offset]);
+  }
+
+  // Default exec shell.
+  execlp(_PATH_BSHELL, "sh", NULL);
+  error(1, errno, "exec failed");
+}
diff --git a/sdcard/Android.mk b/sdcard/Android.mk
index c5f3d1d..0c58574 100644
--- a/sdcard/Android.mk
+++ b/sdcard/Android.mk
@@ -2,9 +2,12 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := sdcard.c
+LOCAL_SRC_FILES := sdcard.cpp fuse.cpp
 LOCAL_MODULE := sdcard
 LOCAL_CFLAGS := -Wall -Wno-unused-parameter -Werror
-LOCAL_SHARED_LIBRARIES := libcutils libpackagelistparser
+LOCAL_SHARED_LIBRARIES := libbase libcutils libminijail libpackagelistparser
+
+LOCAL_SANITIZE := integer
+LOCAL_CLANG := true
 
 include $(BUILD_EXECUTABLE)
diff --git a/sdcard/fuse.cpp b/sdcard/fuse.cpp
new file mode 100644
index 0000000..95559d7
--- /dev/null
+++ b/sdcard/fuse.cpp
@@ -0,0 +1,1476 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#define LOG_TAG "sdcard"
+
+#include "fuse.h"
+
+#include <android-base/logging.h>
+
+/* FUSE_CANONICAL_PATH is not currently upstreamed */
+#define FUSE_CANONICAL_PATH 2016
+
+#define FUSE_UNKNOWN_INO 0xffffffff
+
+/* Pseudo-error constant used to indicate that no fuse status is needed
+ * or that a reply has already been written. */
+#define NO_STATUS 1
+
+static inline void *id_to_ptr(__u64 nid)
+{
+    return (void *) (uintptr_t) nid;
+}
+
+static inline __u64 ptr_to_id(void *ptr)
+{
+    return (__u64) (uintptr_t) ptr;
+}
+
+static void acquire_node_locked(struct node* node)
+{
+    node->refcount++;
+    DLOG(INFO) << "ACQUIRE " << std::hex << node << std::dec
+               << " (" << node->name << ") rc=" << node->refcount;
+}
+
+static void remove_node_from_parent_locked(struct node* node);
+
+static void release_node_locked(struct node* node)
+{
+    DLOG(INFO) << "RELEASE " << std::hex << node << std::dec
+               << " (" << node->name << ") rc=" << node->refcount;
+    if (node->refcount > 0) {
+        node->refcount--;
+        if (!node->refcount) {
+            DLOG(INFO) << "DESTROY " << std::hex << node << std::dec << " (" << node->name << ")";
+            remove_node_from_parent_locked(node);
+
+            /* TODO: remove debugging - poison memory */
+            memset(node->name, 0xef, node->namelen);
+            free(node->name);
+            free(node->actual_name);
+            memset(node, 0xfc, sizeof(*node));
+            free(node);
+        }
+    } else {
+        LOG(ERROR) << std::hex << node << std::dec << " refcount=0";
+    }
+}
+
+static void add_node_to_parent_locked(struct node *node, struct node *parent) {
+    node->parent = parent;
+    node->next = parent->child;
+    parent->child = node;
+    acquire_node_locked(parent);
+}
+
+static void remove_node_from_parent_locked(struct node* node)
+{
+    if (node->parent) {
+        if (node->parent->child == node) {
+            node->parent->child = node->parent->child->next;
+        } else {
+            struct node *node2;
+            node2 = node->parent->child;
+            while (node2->next != node)
+                node2 = node2->next;
+            node2->next = node->next;
+        }
+        release_node_locked(node->parent);
+        node->parent = NULL;
+        node->next = NULL;
+    }
+}
+
+/* Gets the absolute path to a node into the provided buffer.
+ *
+ * Populates 'buf' with the path and returns the length of the path on success,
+ * or returns -1 if the path is too long for the provided buffer.
+ */
+static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
+    const char* name;
+    size_t namelen;
+    if (node->graft_path) {
+        name = node->graft_path;
+        namelen = node->graft_pathlen;
+    } else if (node->actual_name) {
+        name = node->actual_name;
+        namelen = node->namelen;
+    } else {
+        name = node->name;
+        namelen = node->namelen;
+    }
+
+    if (bufsize < namelen + 1) {
+        return -1;
+    }
+
+    ssize_t pathlen = 0;
+    if (node->parent && node->graft_path == NULL) {
+        pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
+        if (pathlen < 0) {
+            return -1;
+        }
+        buf[pathlen++] = '/';
+    }
+
+    memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
+    return pathlen + namelen;
+}
+
+/* Finds the absolute path of a file within a given directory.
+ * Performs a case-insensitive search for the file and sets the buffer to the path
+ * of the first matching file.  If 'search' is zero or if no match is found, sets
+ * the buffer to the path that the file would have, assuming the name were case-sensitive.
+ *
+ * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
+ * or returns NULL if the path is too long for the provided buffer.
+ */
+static char* find_file_within(const char* path, const char* name,
+        char* buf, size_t bufsize, int search)
+{
+    size_t pathlen = strlen(path);
+    size_t namelen = strlen(name);
+    size_t childlen = pathlen + namelen + 1;
+    char* actual;
+
+    if (bufsize <= childlen) {
+        return NULL;
+    }
+
+    memcpy(buf, path, pathlen);
+    buf[pathlen] = '/';
+    actual = buf + pathlen + 1;
+    memcpy(actual, name, namelen + 1);
+
+    if (search && access(buf, F_OK)) {
+        struct dirent* entry;
+        DIR* dir = opendir(path);
+        if (!dir) {
+            PLOG(ERROR) << "opendir(" << path << ") failed";
+            return actual;
+        }
+        while ((entry = readdir(dir))) {
+            if (!strcasecmp(entry->d_name, name)) {
+                /* we have a match - replace the name, don't need to copy the null again */
+                memcpy(actual, entry->d_name, namelen);
+                break;
+            }
+        }
+        closedir(dir);
+    }
+    return actual;
+}
+
+static void attr_from_stat(struct fuse* fuse, struct fuse_attr *attr,
+        const struct stat *s, const struct node* node) {
+    attr->ino = node->ino;
+    attr->size = s->st_size;
+    attr->blocks = s->st_blocks;
+    attr->atime = s->st_atim.tv_sec;
+    attr->mtime = s->st_mtim.tv_sec;
+    attr->ctime = s->st_ctim.tv_sec;
+    attr->atimensec = s->st_atim.tv_nsec;
+    attr->mtimensec = s->st_mtim.tv_nsec;
+    attr->ctimensec = s->st_ctim.tv_nsec;
+    attr->mode = s->st_mode;
+    attr->nlink = s->st_nlink;
+
+    attr->uid = node->uid;
+
+    if (fuse->gid == AID_SDCARD_RW) {
+        /* As an optimization, certain trusted system components only run
+         * as owner but operate across all users. Since we're now handing
+         * out the sdcard_rw GID only to trusted apps, we're okay relaxing
+         * the user boundary enforcement for the default view. The UIDs
+         * assigned to app directories are still multiuser aware. */
+        attr->gid = AID_SDCARD_RW;
+    } else {
+        attr->gid = multiuser_get_uid(node->userid, fuse->gid);
+    }
+
+    int visible_mode = 0775 & ~fuse->mask;
+    if (node->perm == PERM_PRE_ROOT) {
+        /* Top of multi-user view should always be visible to ensure
+         * secondary users can traverse inside. */
+        visible_mode = 0711;
+    } else if (node->under_android) {
+        /* Block "other" access to Android directories, since only apps
+         * belonging to a specific user should be in there; we still
+         * leave +x open for the default view. */
+        if (fuse->gid == AID_SDCARD_RW) {
+            visible_mode = visible_mode & ~0006;
+        } else {
+            visible_mode = visible_mode & ~0007;
+        }
+    }
+    int owner_mode = s->st_mode & 0700;
+    int filtered_mode = visible_mode & (owner_mode | (owner_mode >> 3) | (owner_mode >> 6));
+    attr->mode = (attr->mode & S_IFMT) | filtered_mode;
+}
+
+static int touch(char* path, mode_t mode) {
+    int fd = TEMP_FAILURE_RETRY(open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
+                                     mode));
+    if (fd == -1) {
+        if (errno == EEXIST) {
+            return 0;
+        } else {
+            PLOG(ERROR) << "open(" << path << ") failed";
+            return -1;
+        }
+    }
+    close(fd);
+    return 0;
+}
+
+static void derive_permissions_locked(struct fuse* fuse, struct node *parent,
+        struct node *node) {
+    appid_t appid;
+
+    /* By default, each node inherits from its parent */
+    node->perm = PERM_INHERIT;
+    node->userid = parent->userid;
+    node->uid = parent->uid;
+    node->under_android = parent->under_android;
+
+    /* Derive custom permissions based on parent and current node */
+    switch (parent->perm) {
+    case PERM_INHERIT:
+        /* Already inherited above */
+        break;
+    case PERM_PRE_ROOT:
+        /* Legacy internal layout places users at top level */
+        node->perm = PERM_ROOT;
+        node->userid = strtoul(node->name, NULL, 10);
+        break;
+    case PERM_ROOT:
+        /* Assume masked off by default. */
+        if (!strcasecmp(node->name, "Android")) {
+            /* App-specific directories inside; let anyone traverse */
+            node->perm = PERM_ANDROID;
+            node->under_android = true;
+        }
+        break;
+    case PERM_ANDROID:
+        if (!strcasecmp(node->name, "data")) {
+            /* App-specific directories inside; let anyone traverse */
+            node->perm = PERM_ANDROID_DATA;
+        } else if (!strcasecmp(node->name, "obb")) {
+            /* App-specific directories inside; let anyone traverse */
+            node->perm = PERM_ANDROID_OBB;
+            /* Single OBB directory is always shared */
+            node->graft_path = fuse->global->obb_path;
+            node->graft_pathlen = strlen(fuse->global->obb_path);
+        } else if (!strcasecmp(node->name, "media")) {
+            /* App-specific directories inside; let anyone traverse */
+            node->perm = PERM_ANDROID_MEDIA;
+        }
+        break;
+    case PERM_ANDROID_DATA:
+    case PERM_ANDROID_OBB:
+    case PERM_ANDROID_MEDIA:
+        const auto& iter = fuse->global->package_to_appid->find(node->name);
+        if (iter != fuse->global->package_to_appid->end()) {
+            appid = iter->second;
+            node->uid = multiuser_get_uid(parent->userid, appid);
+        }
+        break;
+    }
+}
+
+void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent) {
+    struct node *node;
+    for (node = parent->child; node; node = node->next) {
+        derive_permissions_locked(fuse, parent, node);
+        if (node->child) {
+            derive_permissions_recursive_locked(fuse, node);
+        }
+    }
+}
+
+/* Kernel has already enforced everything we returned through
+ * derive_permissions_locked(), so this is used to lock down access
+ * even further, such as enforcing that apps hold sdcard_rw. */
+static bool check_caller_access_to_name(struct fuse* fuse,
+        const struct fuse_in_header *hdr, const struct node* parent_node,
+        const char* name, int mode) {
+    /* Always block security-sensitive files at root */
+    if (parent_node && parent_node->perm == PERM_ROOT) {
+        if (!strcasecmp(name, "autorun.inf")
+                || !strcasecmp(name, ".android_secure")
+                || !strcasecmp(name, "android_secure")) {
+            return false;
+        }
+    }
+
+    /* Root always has access; access for any other UIDs should always
+     * be controlled through packages.list. */
+    if (hdr->uid == 0) {
+        return true;
+    }
+
+    /* No extra permissions to enforce */
+    return true;
+}
+
+static bool check_caller_access_to_node(struct fuse* fuse,
+        const struct fuse_in_header *hdr, const struct node* node, int mode) {
+    return check_caller_access_to_name(fuse, hdr, node->parent, node->name, mode);
+}
+
+struct node *create_node_locked(struct fuse* fuse,
+        struct node *parent, const char *name, const char* actual_name)
+{
+    struct node *node;
+    size_t namelen = strlen(name);
+
+    // Detect overflows in the inode counter. "4 billion nodes should be enough
+    // for everybody".
+    if (fuse->global->inode_ctr == 0) {
+        LOG(ERROR) << "No more inode numbers available";
+        return NULL;
+    }
+
+    node = static_cast<struct node*>(calloc(1, sizeof(struct node)));
+    if (!node) {
+        return NULL;
+    }
+    node->name = static_cast<char*>(malloc(namelen + 1));
+    if (!node->name) {
+        free(node);
+        return NULL;
+    }
+    memcpy(node->name, name, namelen + 1);
+    if (strcmp(name, actual_name)) {
+        node->actual_name = static_cast<char*>(malloc(namelen + 1));
+        if (!node->actual_name) {
+            free(node->name);
+            free(node);
+            return NULL;
+        }
+        memcpy(node->actual_name, actual_name, namelen + 1);
+    }
+    node->namelen = namelen;
+    node->nid = ptr_to_id(node);
+    node->ino = fuse->global->inode_ctr++;
+    node->gen = fuse->global->next_generation++;
+
+    node->deleted = false;
+
+    derive_permissions_locked(fuse, parent, node);
+    acquire_node_locked(node);
+    add_node_to_parent_locked(node, parent);
+    return node;
+}
+
+static int rename_node_locked(struct node *node, const char *name,
+        const char* actual_name)
+{
+    size_t namelen = strlen(name);
+    int need_actual_name = strcmp(name, actual_name);
+
+    /* make the storage bigger without actually changing the name
+     * in case an error occurs part way */
+    if (namelen > node->namelen) {
+        char* new_name = static_cast<char*>(realloc(node->name, namelen + 1));
+        if (!new_name) {
+            return -ENOMEM;
+        }
+        node->name = new_name;
+        if (need_actual_name && node->actual_name) {
+            char* new_actual_name = static_cast<char*>(realloc(node->actual_name, namelen + 1));
+            if (!new_actual_name) {
+                return -ENOMEM;
+            }
+            node->actual_name = new_actual_name;
+        }
+    }
+
+    /* update the name, taking care to allocate storage before overwriting the old name */
+    if (need_actual_name) {
+        if (!node->actual_name) {
+            node->actual_name = static_cast<char*>(malloc(namelen + 1));
+            if (!node->actual_name) {
+                return -ENOMEM;
+            }
+        }
+        memcpy(node->actual_name, actual_name, namelen + 1);
+    } else {
+        free(node->actual_name);
+        node->actual_name = NULL;
+    }
+    memcpy(node->name, name, namelen + 1);
+    node->namelen = namelen;
+    return 0;
+}
+
+static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
+{
+    if (nid == FUSE_ROOT_ID) {
+        return &fuse->global->root;
+    } else {
+        return static_cast<struct node*>(id_to_ptr(nid));
+    }
+}
+
+static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
+        char* buf, size_t bufsize)
+{
+    struct node* node = lookup_node_by_id_locked(fuse, nid);
+    if (node && get_node_path_locked(node, buf, bufsize) < 0) {
+        node = NULL;
+    }
+    return node;
+}
+
+static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
+{
+    for (node = node->child; node; node = node->next) {
+        /* use exact string comparison, nodes that differ by case
+         * must be considered distinct even if they refer to the same
+         * underlying file as otherwise operations such as "mv x x"
+         * will not work because the source and target nodes are the same. */
+        if (!strcmp(name, node->name) && !node->deleted) {
+            return node;
+        }
+    }
+    return 0;
+}
+
+static struct node* acquire_or_create_child_locked(
+        struct fuse* fuse, struct node* parent,
+        const char* name, const char* actual_name)
+{
+    struct node* child = lookup_child_by_name_locked(parent, name);
+    if (child) {
+        acquire_node_locked(child);
+    } else {
+        child = create_node_locked(fuse, parent, name, actual_name);
+    }
+    return child;
+}
+
+static void fuse_status(struct fuse *fuse, __u64 unique, int err)
+{
+    struct fuse_out_header hdr;
+    hdr.len = sizeof(hdr);
+    hdr.error = err;
+    hdr.unique = unique;
+    ssize_t ret = TEMP_FAILURE_RETRY(write(fuse->fd, &hdr, sizeof(hdr)));
+    if (ret == -1) {
+        PLOG(ERROR) << "*** STATUS FAILED ***";
+    } else if (static_cast<size_t>(ret) != sizeof(hdr)) {
+        LOG(ERROR) << "*** STATUS FAILED: written " << ret << " expected "
+                   << sizeof(hdr) << " ***";
+    }
+}
+
+static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
+{
+    struct fuse_out_header hdr;
+    hdr.len = len + sizeof(hdr);
+    hdr.error = 0;
+    hdr.unique = unique;
+
+    struct iovec vec[2];
+    vec[0].iov_base = &hdr;
+    vec[0].iov_len = sizeof(hdr);
+    vec[1].iov_base = data;
+    vec[1].iov_len = len;
+
+    ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 2));
+    if (ret == -1) {
+        PLOG(ERROR) << "*** REPLY FAILED ***";
+    } else if (static_cast<size_t>(ret) != sizeof(hdr) + len) {
+        LOG(ERROR) << "*** REPLY FAILED: written " << ret << " expected "
+                   << sizeof(hdr) + len << " ***";
+    }
+}
+
+static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
+        struct node* parent, const char* name, const char* actual_name,
+        const char* path)
+{
+    struct node* node;
+    struct fuse_entry_out out;
+    struct stat s;
+
+    if (lstat(path, &s) == -1) {
+        return -errno;
+    }
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
+    if (!node) {
+        pthread_mutex_unlock(&fuse->global->lock);
+        return -ENOMEM;
+    }
+    memset(&out, 0, sizeof(out));
+    attr_from_stat(fuse, &out.attr, &s, node);
+    out.attr_valid = 10;
+    out.entry_valid = 10;
+    out.nodeid = node->nid;
+    out.generation = node->gen;
+    pthread_mutex_unlock(&fuse->global->lock);
+    fuse_reply(fuse, unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int fuse_reply_attr(struct fuse* fuse, __u64 unique, const struct node* node,
+        const char* path)
+{
+    struct fuse_attr_out out;
+    struct stat s;
+
+    if (lstat(path, &s) == -1) {
+        return -errno;
+    }
+    memset(&out, 0, sizeof(out));
+    attr_from_stat(fuse, &out.attr, &s, node);
+    out.attr_valid = 10;
+    fuse_reply(fuse, unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static void fuse_notify_delete(struct fuse* fuse, const __u64 parent,
+        const __u64 child, const char* name) {
+    struct fuse_out_header hdr;
+    struct fuse_notify_delete_out data;
+    size_t namelen = strlen(name);
+    hdr.len = sizeof(hdr) + sizeof(data) + namelen + 1;
+    hdr.error = FUSE_NOTIFY_DELETE;
+    hdr.unique = 0;
+
+    data.parent = parent;
+    data.child = child;
+    data.namelen = namelen;
+    data.padding = 0;
+
+    struct iovec vec[3];
+    vec[0].iov_base = &hdr;
+    vec[0].iov_len = sizeof(hdr);
+    vec[1].iov_base = &data;
+    vec[1].iov_len = sizeof(data);
+    vec[2].iov_base = (void*) name;
+    vec[2].iov_len = namelen + 1;
+
+    ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 3));
+    /* Ignore ENOENT, since other views may not have seen the entry */
+    if (ret == -1) {
+        if (errno != ENOENT) {
+            PLOG(ERROR) << "*** NOTIFY FAILED ***";
+        }
+    } else if (static_cast<size_t>(ret) != sizeof(hdr) + sizeof(data) + namelen + 1) {
+        LOG(ERROR) << "*** NOTIFY FAILED: written " << ret << " expected "
+                   << sizeof(hdr) + sizeof(data) + namelen + 1 << " ***";
+    }
+}
+
+static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    DLOG(INFO) << "[" << handler->token << "] LOOKUP " << name << " @ " << hdr->nodeid
+               << " (" << (parent_node ? parent_node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, R_OK)) {
+        return -EACCES;
+    }
+
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
+{
+    struct node* node;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_by_id_locked(fuse, hdr->nodeid);
+    DLOG(INFO) << "[" << handler->token << "] FORGET #" << req->nlookup
+               << " @ " << std::hex << hdr->nodeid
+               << " (" << (node ? node->name : "?") << ")";
+    if (node) {
+        __u64 n = req->nlookup;
+        while (n) {
+            n--;
+            release_node_locked(node);
+        }
+    }
+    pthread_mutex_unlock(&fuse->global->lock);
+    return NO_STATUS; /* no reply */
+}
+
+static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    DLOG(INFO) << "[" << handler->token << "] GETATTR flags=" << req->getattr_flags
+               << " fh=" << std::hex << req->fh << " @ " << hdr->nodeid << std::dec
+               << " (" << (node ? node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
+        return -EACCES;
+    }
+
+    return fuse_reply_attr(fuse, hdr->unique, node, path);
+}
+
+static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct timespec times[2];
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    DLOG(INFO) << "[" << handler->token << "] SETATTR fh=" << std::hex << req->fh
+               << " valid=" << std::hex << req->valid << " @ " << hdr->nodeid << std::dec
+               << " (" << (node ? node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+
+    if (!(req->valid & FATTR_FH) &&
+            !check_caller_access_to_node(fuse, hdr, node, W_OK)) {
+        return -EACCES;
+    }
+
+    /* XXX: incomplete implementation on purpose.
+     * chmod/chown should NEVER be implemented.*/
+
+    if ((req->valid & FATTR_SIZE) && TEMP_FAILURE_RETRY(truncate64(path, req->size)) == -1) {
+        return -errno;
+    }
+
+    /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
+     * are both set, then set it to the current time.  Else, set it to the
+     * time specified in the request.  Same goes for mtime.  Use utimensat(2)
+     * as it allows ATIME and MTIME to be changed independently, and has
+     * nanosecond resolution which fuse also has.
+     */
+    if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
+        times[0].tv_nsec = UTIME_OMIT;
+        times[1].tv_nsec = UTIME_OMIT;
+        if (req->valid & FATTR_ATIME) {
+            if (req->valid & FATTR_ATIME_NOW) {
+              times[0].tv_nsec = UTIME_NOW;
+            } else {
+              times[0].tv_sec = req->atime;
+              times[0].tv_nsec = req->atimensec;
+            }
+        }
+        if (req->valid & FATTR_MTIME) {
+            if (req->valid & FATTR_MTIME_NOW) {
+              times[1].tv_nsec = UTIME_NOW;
+            } else {
+              times[1].tv_sec = req->mtime;
+              times[1].tv_nsec = req->mtimensec;
+            }
+        }
+        DLOG(INFO) << "[" << handler->token << "] Calling utimensat on " << path
+                   << " with atime " << times[0].tv_sec << ", mtime=" << times[1].tv_sec;
+        if (utimensat(-1, path, times, 0) < 0) {
+            return -errno;
+        }
+    }
+    return fuse_reply_attr(fuse, hdr->unique, node, path);
+}
+
+static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    DLOG(INFO) << "[" << handler->token << "] MKNOD " << name << " 0" << std::oct << req->mode
+               << " @ " << std::hex << hdr->nodeid
+               << " (" << (parent_node ? parent_node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
+        return -EACCES;
+    }
+    __u32 mode = (req->mode & (~0777)) | 0664;
+    if (mknod(child_path, mode, req->rdev) == -1) {
+        return -errno;
+    }
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    DLOG(INFO) << "[" << handler->token << "] MKDIR " << name << " 0" << std::oct << req->mode
+               << " @ " << std::hex << hdr->nodeid
+               << " (" << (parent_node ? parent_node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
+        return -EACCES;
+    }
+    __u32 mode = (req->mode & (~0777)) | 0775;
+    if (mkdir(child_path, mode) == -1) {
+        return -errno;
+    }
+
+    /* When creating /Android/data and /Android/obb, mark them as .nomedia */
+    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "data")) {
+        char nomedia[PATH_MAX];
+        snprintf(nomedia, PATH_MAX, "%s/.nomedia", child_path);
+        if (touch(nomedia, 0664) != 0) {
+            PLOG(ERROR) << "touch(" << nomedia << ") failed";
+            return -ENOENT;
+        }
+    }
+    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "obb")) {
+        char nomedia[PATH_MAX];
+        snprintf(nomedia, PATH_MAX, "%s/.nomedia", fuse->global->obb_path);
+        if (touch(nomedia, 0664) != 0) {
+            PLOG(ERROR) << "touch(" << nomedia << ") failed";
+            return -ENOENT;
+        }
+    }
+
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const char* name)
+{
+    struct node* parent_node;
+    struct node* child_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->global->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
+               << " (" << (parent_node ? parent_node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!parent_node || !find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1)) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
+        return -EACCES;
+    }
+    if (unlink(child_path) == -1) {
+        return -errno;
+    }
+    pthread_mutex_lock(&fuse->global->lock);
+    child_node = lookup_child_by_name_locked(parent_node, name);
+    if (child_node) {
+        child_node->deleted = true;
+    }
+    pthread_mutex_unlock(&fuse->global->lock);
+    if (parent_node && child_node) {
+        /* Tell all other views that node is gone */
+        DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
+                   << " parent=" << std::hex << parent_node->nid
+                   << ", child=" << std::hex << child_node->nid << std::dec
+                   << ", name=" << name;
+        if (fuse != fuse->global->fuse_default) {
+            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
+        }
+        if (fuse != fuse->global->fuse_read) {
+            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
+        }
+        if (fuse != fuse->global->fuse_write) {
+            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
+        }
+    }
+    return 0;
+}
+
+static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const char* name)
+{
+    struct node* child_node;
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->global->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
+               << " (" << (parent_node ? parent_node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!parent_node || !find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1)) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
+        return -EACCES;
+    }
+    if (rmdir(child_path) == -1) {
+        return -errno;
+    }
+    pthread_mutex_lock(&fuse->global->lock);
+    child_node = lookup_child_by_name_locked(parent_node, name);
+    if (child_node) {
+        child_node->deleted = true;
+    }
+    pthread_mutex_unlock(&fuse->global->lock);
+    if (parent_node && child_node) {
+        /* Tell all other views that node is gone */
+        DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
+                   << " parent=" << std::hex << parent_node->nid
+                   << ", child=" << std::hex << child_node->nid << std::dec
+                   << ", name=" << name;
+        if (fuse != fuse->global->fuse_default) {
+            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
+        }
+        if (fuse != fuse->global->fuse_read) {
+            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
+        }
+        if (fuse != fuse->global->fuse_write) {
+            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
+        }
+    }
+    return 0;
+}
+
+static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
+        const char* old_name, const char* new_name)
+{
+    struct node* old_parent_node;
+    struct node* new_parent_node;
+    struct node* child_node;
+    char old_parent_path[PATH_MAX];
+    char new_parent_path[PATH_MAX];
+    char old_child_path[PATH_MAX];
+    char new_child_path[PATH_MAX];
+    const char* new_actual_name;
+    int search;
+    int res;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            old_parent_path, sizeof(old_parent_path));
+    new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
+            new_parent_path, sizeof(new_parent_path));
+    DLOG(INFO) << "[" << handler->token << "] RENAME " << old_name << "->" << new_name
+               << " @ " << std::hex << hdr->nodeid
+               << " (" << (old_parent_node ? old_parent_node->name : "?") << ") -> "
+               << std::hex << req->newdir
+               << " (" << (new_parent_node ? new_parent_node->name : "?") << ")";
+    if (!old_parent_node || !new_parent_node) {
+        res = -ENOENT;
+        goto lookup_error;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, old_parent_node, old_name, W_OK)) {
+        res = -EACCES;
+        goto lookup_error;
+    }
+    if (!check_caller_access_to_name(fuse, hdr, new_parent_node, new_name, W_OK)) {
+        res = -EACCES;
+        goto lookup_error;
+    }
+    child_node = lookup_child_by_name_locked(old_parent_node, old_name);
+    if (!child_node || get_node_path_locked(child_node,
+            old_child_path, sizeof(old_child_path)) < 0) {
+        res = -ENOENT;
+        goto lookup_error;
+    }
+    acquire_node_locked(child_node);
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    /* Special case for renaming a file where destination is same path
+     * differing only by case.  In this case we don't want to look for a case
+     * insensitive match.  This allows commands like "mv foo FOO" to work as expected.
+     */
+    search = old_parent_node != new_parent_node
+            || strcasecmp(old_name, new_name);
+    if (!(new_actual_name = find_file_within(new_parent_path, new_name,
+            new_child_path, sizeof(new_child_path), search))) {
+        res = -ENOENT;
+        goto io_error;
+    }
+
+    DLOG(INFO) << "[" << handler->token << "] RENAME " << old_child_path << "->" << new_child_path;
+    res = rename(old_child_path, new_child_path);
+    if (res == -1) {
+        res = -errno;
+        goto io_error;
+    }
+
+    pthread_mutex_lock(&fuse->global->lock);
+    res = rename_node_locked(child_node, new_name, new_actual_name);
+    if (!res) {
+        remove_node_from_parent_locked(child_node);
+        derive_permissions_locked(fuse, new_parent_node, child_node);
+        derive_permissions_recursive_locked(fuse, child_node);
+        add_node_to_parent_locked(child_node, new_parent_node);
+    }
+    goto done;
+
+io_error:
+    pthread_mutex_lock(&fuse->global->lock);
+done:
+    release_node_locked(child_node);
+lookup_error:
+    pthread_mutex_unlock(&fuse->global->lock);
+    return res;
+}
+
+static int open_flags_to_access_mode(int open_flags) {
+    if ((open_flags & O_ACCMODE) == O_RDONLY) {
+        return R_OK;
+    } else if ((open_flags & O_ACCMODE) == O_WRONLY) {
+        return W_OK;
+    } else {
+        /* Probably O_RDRW, but treat as default to be safe */
+        return R_OK | W_OK;
+    }
+}
+
+static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct fuse_open_out out = {};
+    struct handle *h;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    DLOG(INFO) << "[" << handler->token << "] OPEN 0" << std::oct << req->flags
+               << " @ " << std::hex << hdr->nodeid << std::dec
+               << " (" << (node ? node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_node(fuse, hdr, node,
+            open_flags_to_access_mode(req->flags))) {
+        return -EACCES;
+    }
+    h = static_cast<struct handle*>(malloc(sizeof(*h)));
+    if (!h) {
+        return -ENOMEM;
+    }
+    DLOG(INFO) << "[" << handler->token << "] OPEN " << path;
+    h->fd = TEMP_FAILURE_RETRY(open(path, req->flags));
+    if (h->fd == -1) {
+        free(h);
+        return -errno;
+    }
+    out.fh = ptr_to_id(h);
+    out.open_flags = 0;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
+{
+    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
+    __u64 unique = hdr->unique;
+    __u32 size = req->size;
+    __u64 offset = req->offset;
+    int res;
+    __u8 *read_buffer = (__u8 *) ((uintptr_t)(handler->read_buffer + PAGE_SIZE) & ~((uintptr_t)PAGE_SIZE-1));
+
+    /* Don't access any other fields of hdr or req beyond this point, the read buffer
+     * overlaps the request buffer and will clobber data in the request.  This
+     * saves us 128KB per request handler thread at the cost of this scary comment. */
+
+    DLOG(INFO) << "[" << handler->token << "] READ " << std::hex << h << std::dec
+               << "(" << h->fd << ") " << size << "@" << offset;
+    if (size > MAX_READ) {
+        return -EINVAL;
+    }
+    res = TEMP_FAILURE_RETRY(pread64(h->fd, read_buffer, size, offset));
+    if (res == -1) {
+        return -errno;
+    }
+    fuse_reply(fuse, unique, read_buffer, res);
+    return NO_STATUS;
+}
+
+static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_write_in* req,
+        const void* buffer)
+{
+    struct fuse_write_out out;
+    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
+    int res;
+    __u8 aligned_buffer[req->size] __attribute__((__aligned__(PAGE_SIZE)));
+
+    if (req->flags & O_DIRECT) {
+        memcpy(aligned_buffer, buffer, req->size);
+        buffer = (const __u8*) aligned_buffer;
+    }
+
+    DLOG(INFO) << "[" << handler->token << "] WRITE " << std::hex << h << std::dec
+               << "(" << h->fd << ") " << req->size << "@" << req->offset;
+    res = TEMP_FAILURE_RETRY(pwrite64(h->fd, buffer, req->size, req->offset));
+    if (res == -1) {
+        return -errno;
+    }
+    out.size = res;
+    out.padding = 0;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr)
+{
+    char path[PATH_MAX];
+    struct statfs stat;
+    struct fuse_statfs_out out;
+    int res;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    DLOG(INFO) << "[" << handler->token << "] STATFS";
+    res = get_node_path_locked(&fuse->global->root, path, sizeof(path));
+    pthread_mutex_unlock(&fuse->global->lock);
+    if (res < 0) {
+        return -ENOENT;
+    }
+    if (TEMP_FAILURE_RETRY(statfs(fuse->global->root.name, &stat)) == -1) {
+        return -errno;
+    }
+    memset(&out, 0, sizeof(out));
+    out.st.blocks = stat.f_blocks;
+    out.st.bfree = stat.f_bfree;
+    out.st.bavail = stat.f_bavail;
+    out.st.files = stat.f_files;
+    out.st.ffree = stat.f_ffree;
+    out.st.bsize = stat.f_bsize;
+    out.st.namelen = stat.f_namelen;
+    out.st.frsize = stat.f_frsize;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
+{
+    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
+
+    DLOG(INFO) << "[" << handler->token << "] RELEASE " << std::hex << h << std::dec
+               << "(" << h->fd << ")";
+    close(h->fd);
+    free(h);
+    return 0;
+}
+
+static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
+{
+    bool is_dir = (hdr->opcode == FUSE_FSYNCDIR);
+    bool is_data_sync = req->fsync_flags & 1;
+
+    int fd = -1;
+    if (is_dir) {
+      struct dirhandle *dh = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
+      fd = dirfd(dh->d);
+    } else {
+      struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
+      fd = h->fd;
+    }
+
+    DLOG(INFO) << "[" << handler->token << "] " << (is_dir ? "FSYNCDIR" : "FSYNC") << " "
+               << std::hex << req->fh << std::dec << "(" << fd << ") is_data_sync=" << is_data_sync;
+    int res = is_data_sync ? fdatasync(fd) : fsync(fd);
+    if (res == -1) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr)
+{
+    DLOG(INFO) << "[" << handler->token << "] FLUSH";
+    return 0;
+}
+
+static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct fuse_open_out out = {};
+    struct dirhandle *h;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    DLOG(INFO) << "[" << handler->token << "] OPENDIR @ " << std::hex << hdr->nodeid
+               << " (" << (node ? node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
+        return -EACCES;
+    }
+    h = static_cast<struct dirhandle*>(malloc(sizeof(*h)));
+    if (!h) {
+        return -ENOMEM;
+    }
+    DLOG(INFO) << "[" << handler->token << "] OPENDIR " << path;
+    h->d = opendir(path);
+    if (!h->d) {
+        free(h);
+        return -errno;
+    }
+    out.fh = ptr_to_id(h);
+    out.open_flags = 0;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
+{
+    char buffer[8192];
+    struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
+    struct dirent *de;
+    struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
+
+    DLOG(INFO) << "[" << handler->token << "] READDIR " << h;
+    if (req->offset == 0) {
+        /* rewinddir() might have been called above us, so rewind here too */
+        DLOG(INFO) << "[" << handler->token << "] calling rewinddir()";
+        rewinddir(h->d);
+    }
+    de = readdir(h->d);
+    if (!de) {
+        return 0;
+    }
+    fde->ino = FUSE_UNKNOWN_INO;
+    /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
+    fde->off = req->offset + 1;
+    fde->type = de->d_type;
+    fde->namelen = strlen(de->d_name);
+    memcpy(fde->name, de->d_name, fde->namelen + 1);
+    fuse_reply(fuse, hdr->unique, fde,
+            FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
+    return NO_STATUS;
+}
+
+static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
+{
+    struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
+
+    DLOG(INFO) << "[" << handler->token << "] RELEASEDIR " << h;
+    closedir(h->d);
+    free(h);
+    return 0;
+}
+
+static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_init_in* req)
+{
+    struct fuse_init_out out;
+    size_t fuse_struct_size;
+
+    DLOG(INFO) << "[" << handler->token << "] INIT ver=" << req->major << "." << req->minor
+               << " maxread=" << req->max_readahead << " flags=" << std::hex << req->flags;
+
+    /* Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
+     * defined (fuse version 7.6). The structure is the same from 7.6 through
+     * 7.22. Beginning with 7.23, the structure increased in size and added
+     * new parameters.
+     */
+    if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
+        LOG(ERROR) << "Fuse kernel version mismatch: Kernel version "
+                   << req->major << "." << req->minor
+                   << ", Expected at least " << FUSE_KERNEL_VERSION << ".6";
+        return -1;
+    }
+
+    /* We limit ourselves to 15 because we don't handle BATCH_FORGET yet */
+    out.minor = MIN(req->minor, 15);
+    fuse_struct_size = sizeof(out);
+#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
+    /* FUSE_KERNEL_VERSION >= 23. */
+
+    /* Since we return minor version 15, the kernel does not accept the latest
+     * fuse_init_out size. We need to use FUSE_COMPAT_22_INIT_OUT_SIZE always.*/
+    fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
+#endif
+
+    out.major = FUSE_KERNEL_VERSION;
+    out.max_readahead = req->max_readahead;
+    out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
+    out.max_background = 32;
+    out.congestion_threshold = 32;
+    out.max_write = MAX_WRITE;
+    fuse_reply(fuse, hdr->unique, &out, fuse_struct_size);
+    return NO_STATUS;
+}
+
+static int handle_canonical_path(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    int len;
+
+    pthread_mutex_lock(&fuse->global->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            path, sizeof(path));
+    DLOG(INFO) << "[" << handler->token << "] CANONICAL_PATH @ " << std::hex << hdr->nodeid
+               << std::dec << " (" << (node ? node->name : "?") << ")";
+    pthread_mutex_unlock(&fuse->global->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
+        return -EACCES;
+    }
+    len = strlen(path);
+    if (len + 1 > PATH_MAX)
+        len = PATH_MAX - 1;
+    path[PATH_MAX - 1] = 0;
+    fuse_reply(fuse, hdr->unique, path, len + 1);
+    return NO_STATUS;
+}
+
+static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const void *data, size_t data_len)
+{
+    switch (hdr->opcode) {
+    case FUSE_LOOKUP: { /* bytez[] -> entry_out */
+        const char *name = static_cast<const char*>(data);
+        return handle_lookup(fuse, handler, hdr, name);
+    }
+
+    case FUSE_FORGET: {
+        const struct fuse_forget_in *req = static_cast<const struct fuse_forget_in*>(data);
+        return handle_forget(fuse, handler, hdr, req);
+    }
+
+    case FUSE_GETATTR: { /* getattr_in -> attr_out */
+        const struct fuse_getattr_in *req = static_cast<const struct fuse_getattr_in*>(data);
+        return handle_getattr(fuse, handler, hdr, req);
+    }
+
+    case FUSE_SETATTR: { /* setattr_in -> attr_out */
+        const struct fuse_setattr_in *req = static_cast<const struct fuse_setattr_in*>(data);
+        return handle_setattr(fuse, handler, hdr, req);
+    }
+
+//    case FUSE_READLINK:
+//    case FUSE_SYMLINK:
+    case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
+        const struct fuse_mknod_in *req = static_cast<const struct fuse_mknod_in*>(data);
+        const char *name = ((const char*) data) + sizeof(*req);
+        return handle_mknod(fuse, handler, hdr, req, name);
+    }
+
+    case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
+        const struct fuse_mkdir_in *req = static_cast<const struct fuse_mkdir_in*>(data);
+        const char *name = ((const char*) data) + sizeof(*req);
+        return handle_mkdir(fuse, handler, hdr, req, name);
+    }
+
+    case FUSE_UNLINK: { /* bytez[] -> */
+        const char *name = static_cast<const char*>(data);
+        return handle_unlink(fuse, handler, hdr, name);
+    }
+
+    case FUSE_RMDIR: { /* bytez[] -> */
+        const char *name = static_cast<const char*>(data);
+        return handle_rmdir(fuse, handler, hdr, name);
+    }
+
+    case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
+        const struct fuse_rename_in *req = static_cast<const struct fuse_rename_in*>(data);
+        const char *old_name = ((const char*) data) + sizeof(*req);
+        const char *new_name = old_name + strlen(old_name) + 1;
+        return handle_rename(fuse, handler, hdr, req, old_name, new_name);
+    }
+
+//    case FUSE_LINK:
+    case FUSE_OPEN: { /* open_in -> open_out */
+        const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
+        return handle_open(fuse, handler, hdr, req);
+    }
+
+    case FUSE_READ: { /* read_in -> byte[] */
+        const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
+        return handle_read(fuse, handler, hdr, req);
+    }
+
+    case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
+        const struct fuse_write_in *req = static_cast<const struct fuse_write_in*>(data);
+        const void* buffer = (const __u8*)data + sizeof(*req);
+        return handle_write(fuse, handler, hdr, req, buffer);
+    }
+
+    case FUSE_STATFS: { /* getattr_in -> attr_out */
+        return handle_statfs(fuse, handler, hdr);
+    }
+
+    case FUSE_RELEASE: { /* release_in -> */
+        const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
+        return handle_release(fuse, handler, hdr, req);
+    }
+
+    case FUSE_FSYNC:
+    case FUSE_FSYNCDIR: {
+        const struct fuse_fsync_in *req = static_cast<const struct fuse_fsync_in*>(data);
+        return handle_fsync(fuse, handler, hdr, req);
+    }
+
+//    case FUSE_SETXATTR:
+//    case FUSE_GETXATTR:
+//    case FUSE_LISTXATTR:
+//    case FUSE_REMOVEXATTR:
+    case FUSE_FLUSH: {
+        return handle_flush(fuse, handler, hdr);
+    }
+
+    case FUSE_OPENDIR: { /* open_in -> open_out */
+        const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
+        return handle_opendir(fuse, handler, hdr, req);
+    }
+
+    case FUSE_READDIR: {
+        const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
+        return handle_readdir(fuse, handler, hdr, req);
+    }
+
+    case FUSE_RELEASEDIR: { /* release_in -> */
+        const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
+        return handle_releasedir(fuse, handler, hdr, req);
+    }
+
+    case FUSE_INIT: { /* init_in -> init_out */
+        const struct fuse_init_in *req = static_cast<const struct fuse_init_in*>(data);
+        return handle_init(fuse, handler, hdr, req);
+    }
+
+    case FUSE_CANONICAL_PATH: { /* nodeid -> bytez[] */
+        return handle_canonical_path(fuse, handler, hdr);
+    }
+
+    default: {
+        DLOG(INFO) << "[" << handler->token << "] NOTIMPL op=" << hdr->opcode
+                   << "uniq=" << std::hex << hdr->unique << "nid=" << hdr->nodeid << std::dec;
+        return -ENOSYS;
+    }
+    }
+}
+
+void handle_fuse_requests(struct fuse_handler* handler)
+{
+    struct fuse* fuse = handler->fuse;
+    for (;;) {
+        ssize_t len = TEMP_FAILURE_RETRY(read(fuse->fd,
+                handler->request_buffer, sizeof(handler->request_buffer)));
+        if (len == -1) {
+            if (errno == ENODEV) {
+                LOG(ERROR) << "[" << handler->token << "] someone stole our marbles!";
+                exit(2);
+            }
+            PLOG(ERROR) << "[" << handler->token << "] handle_fuse_requests";
+            continue;
+        }
+
+        if (static_cast<size_t>(len) < sizeof(struct fuse_in_header)) {
+            LOG(ERROR) << "[" << handler->token << "] request too short: len=" << len;
+            continue;
+        }
+
+        const struct fuse_in_header* hdr =
+            reinterpret_cast<const struct fuse_in_header*>(handler->request_buffer);
+        if (hdr->len != static_cast<size_t>(len)) {
+            LOG(ERROR) << "[" << handler->token << "] malformed header: len=" << len
+                       << ", hdr->len=" << hdr->len;
+            continue;
+        }
+
+        const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
+        size_t data_len = len - sizeof(struct fuse_in_header);
+        __u64 unique = hdr->unique;
+        int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
+
+        /* We do not access the request again after this point because the underlying
+         * buffer storage may have been reused while processing the request. */
+
+        if (res != NO_STATUS) {
+            if (res) {
+                DLOG(INFO) << "[" << handler->token << "] ERROR " << res;
+            }
+            fuse_status(fuse, unique, res);
+        }
+    }
+}
diff --git a/sdcard/fuse.h b/sdcard/fuse.h
new file mode 100644
index 0000000..9ccd21d
--- /dev/null
+++ b/sdcard/fuse.h
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FUSE_H_
+#define FUSE_H_
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/fuse.h>
+#include <pthread.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/statfs.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include <map>
+#include <string>
+
+#include <android-base/logging.h>
+#include <cutils/fs.h>
+#include <cutils/multiuser.h>
+#include <packagelistparser/packagelistparser.h>
+
+#include <private/android_filesystem_config.h>
+
+#define FUSE_TRACE 0
+
+#if FUSE_TRACE
+static constexpr bool kEnableDLog = true;
+#else  // FUSE_TRACE == 0
+static constexpr bool kEnableDLog = false;
+#endif
+
+// Use same strategy as DCHECK().
+#define DLOG(x) \
+    if (kEnableDLog) LOG(x)
+
+/* Maximum number of bytes to write in one request. */
+#define MAX_WRITE (256 * 1024)
+
+/* Maximum number of bytes to read in one request. */
+#define MAX_READ (128 * 1024)
+
+/* Largest possible request.
+ * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
+ * the largest possible data payload. */
+#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
+
+namespace {
+struct CaseInsensitiveCompare {
+    bool operator()(const std::string& lhs, const std::string& rhs) const {
+        return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
+    }
+};
+}
+
+using AppIdMap = std::map<std::string, appid_t, CaseInsensitiveCompare>;
+
+/* Permission mode for a specific node. Controls how file permissions
+ * are derived for children nodes. */
+typedef enum {
+    /* Nothing special; this node should just inherit from its parent. */
+    PERM_INHERIT,
+    /* This node is one level above a normal root; used for legacy layouts
+     * which use the first level to represent user_id. */
+    PERM_PRE_ROOT,
+    /* This node is "/" */
+    PERM_ROOT,
+    /* This node is "/Android" */
+    PERM_ANDROID,
+    /* This node is "/Android/data" */
+    PERM_ANDROID_DATA,
+    /* This node is "/Android/obb" */
+    PERM_ANDROID_OBB,
+    /* This node is "/Android/media" */
+    PERM_ANDROID_MEDIA,
+} perm_t;
+
+struct handle {
+    int fd;
+};
+
+struct dirhandle {
+    DIR *d;
+};
+
+struct node {
+    __u32 refcount;
+    __u64 nid;
+    __u64 gen;
+    /*
+     * The inode number for this FUSE node. Note that this isn't stable across
+     * multiple invocations of the FUSE daemon.
+     */
+    __u32 ino;
+
+    /* State derived based on current position in hierarchy. */
+    perm_t perm;
+    userid_t userid;
+    uid_t uid;
+    bool under_android;
+
+    struct node *next;          /* per-dir sibling list */
+    struct node *child;         /* first contained file by this dir */
+    struct node *parent;        /* containing directory */
+
+    size_t namelen;
+    char *name;
+    /* If non-null, this is the real name of the file in the underlying storage.
+     * This may differ from the field "name" only by case.
+     * strlen(actual_name) will always equal strlen(name), so it is safe to use
+     * namelen for both fields.
+     */
+    char *actual_name;
+
+    /* If non-null, an exact underlying path that should be grafted into this
+     * position. Used to support things like OBB. */
+    char* graft_path;
+    size_t graft_pathlen;
+
+    bool deleted;
+};
+
+/* Global data for all FUSE mounts */
+struct fuse_global {
+    pthread_mutex_t lock;
+
+    uid_t uid;
+    gid_t gid;
+    bool multi_user;
+
+    char source_path[PATH_MAX];
+    char obb_path[PATH_MAX];
+
+    AppIdMap* package_to_appid;
+
+    __u64 next_generation;
+    struct node root;
+
+    /* Used to allocate unique inode numbers for fuse nodes. We use
+     * a simple counter based scheme where inode numbers from deleted
+     * nodes aren't reused. Note that inode allocations are not stable
+     * across multiple invocation of the sdcard daemon, but that shouldn't
+     * be a huge problem in practice.
+     *
+     * Note that we restrict inodes to 32 bit unsigned integers to prevent
+     * truncation on 32 bit processes when unsigned long long stat.st_ino is
+     * assigned to an unsigned long ino_t type in an LP32 process.
+     *
+     * Also note that fuse_attr and fuse_dirent inode values are 64 bits wide
+     * on both LP32 and LP64, but the fuse kernel code doesn't squash 64 bit
+     * inode numbers into 32 bit values on 64 bit kernels (see fuse_squash_ino
+     * in fs/fuse/inode.c).
+     *
+     * Accesses must be guarded by |lock|.
+     */
+    __u32 inode_ctr;
+
+    struct fuse* fuse_default;
+    struct fuse* fuse_read;
+    struct fuse* fuse_write;
+};
+
+/* Single FUSE mount */
+struct fuse {
+    struct fuse_global* global;
+
+    char dest_path[PATH_MAX];
+
+    int fd;
+
+    gid_t gid;
+    mode_t mask;
+};
+
+/* Private data used by a single FUSE handler */
+struct fuse_handler {
+    struct fuse* fuse;
+    int token;
+
+    /* To save memory, we never use the contents of the request buffer and the read
+     * buffer at the same time.  This allows us to share the underlying storage. */
+    union {
+        __u8 request_buffer[MAX_REQUEST_SIZE];
+        __u8 read_buffer[MAX_READ + PAGE_SIZE];
+    };
+};
+
+void handle_fuse_requests(struct fuse_handler* handler);
+void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent);
+
+#endif  /* FUSE_H_ */
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
deleted file mode 100644
index 13ebaf1..0000000
--- a/sdcard/sdcard.c
+++ /dev/null
@@ -1,2154 +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.
- */
-
-#define LOG_TAG "sdcard"
-
-#include <ctype.h>
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <linux/fuse.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/inotify.h>
-#include <sys/mount.h>
-#include <sys/param.h>
-#include <sys/resource.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include <cutils/fs.h>
-#include <cutils/hashmap.h>
-#include <cutils/log.h>
-#include <cutils/multiuser.h>
-#include <cutils/properties.h>
-#include <packagelistparser/packagelistparser.h>
-
-#include <private/android_filesystem_config.h>
-
-/* FUSE_CANONICAL_PATH is not currently upstreamed */
-#define FUSE_CANONICAL_PATH 2016
-
-/* README
- *
- * What is this?
- *
- * sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
- * directory permissions (all files are given fixed owner, group, and
- * permissions at creation, owner, group, and permissions are not
- * changeable, symlinks and hardlinks are not createable, etc.
- *
- * See usage() for command line options.
- *
- * It must be run as root, but will drop to requested UID/GID as soon as it
- * mounts a filesystem.  It will refuse to run if requested UID/GID are zero.
- *
- * Things I believe to be true:
- *
- * - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
- * CREAT) must bump that node's refcount
- * - don't forget that FORGET can forget multiple references (req->nlookup)
- * - if an op that returns a fuse_entry fails writing the reply to the
- * kernel, you must rollback the refcount to reflect the reference the
- * kernel did not actually acquire
- *
- * This daemon can also derive custom filesystem permissions based on directory
- * structure when requested. These custom permissions support several features:
- *
- * - Apps can access their own files in /Android/data/com.example/ without
- * requiring any additional GIDs.
- * - Separate permissions for protecting directories like Pictures and Music.
- * - Multi-user separation on the same physical device.
- */
-
-#define FUSE_TRACE 0
-
-#if FUSE_TRACE
-#define TRACE(x...) ALOGD(x)
-#else
-#define TRACE(x...) do {} while (0)
-#endif
-
-#define ERROR(x...) ALOGE(x)
-
-#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
-#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"
-
-#define FUSE_UNKNOWN_INO 0xffffffff
-
-/* Maximum number of bytes to write in one request. */
-#define MAX_WRITE (256 * 1024)
-
-/* Maximum number of bytes to read in one request. */
-#define MAX_READ (128 * 1024)
-
-/* Largest possible request.
- * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
- * the largest possible data payload. */
-#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
-
-/* Pseudo-error constant used to indicate that no fuse status is needed
- * or that a reply has already been written. */
-#define NO_STATUS 1
-
-/* Supplementary groups to execute with */
-static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
-
-/* Permission mode for a specific node. Controls how file permissions
- * are derived for children nodes. */
-typedef enum {
-    /* Nothing special; this node should just inherit from its parent. */
-    PERM_INHERIT,
-    /* This node is one level above a normal root; used for legacy layouts
-     * which use the first level to represent user_id. */
-    PERM_PRE_ROOT,
-    /* This node is "/" */
-    PERM_ROOT,
-    /* This node is "/Android" */
-    PERM_ANDROID,
-    /* This node is "/Android/data" */
-    PERM_ANDROID_DATA,
-    /* This node is "/Android/obb" */
-    PERM_ANDROID_OBB,
-    /* This node is "/Android/media" */
-    PERM_ANDROID_MEDIA,
-} perm_t;
-
-struct handle {
-    int fd;
-};
-
-struct dirhandle {
-    DIR *d;
-};
-
-struct node {
-    __u32 refcount;
-    __u64 nid;
-    __u64 gen;
-    /*
-     * The inode number for this FUSE node. Note that this isn't stable across
-     * multiple invocations of the FUSE daemon.
-     */
-    __u32 ino;
-
-    /* State derived based on current position in hierarchy. */
-    perm_t perm;
-    userid_t userid;
-    uid_t uid;
-    bool under_android;
-
-    struct node *next;          /* per-dir sibling list */
-    struct node *child;         /* first contained file by this dir */
-    struct node *parent;        /* containing directory */
-
-    size_t namelen;
-    char *name;
-    /* If non-null, this is the real name of the file in the underlying storage.
-     * This may differ from the field "name" only by case.
-     * strlen(actual_name) will always equal strlen(name), so it is safe to use
-     * namelen for both fields.
-     */
-    char *actual_name;
-
-    /* If non-null, an exact underlying path that should be grafted into this
-     * position. Used to support things like OBB. */
-    char* graft_path;
-    size_t graft_pathlen;
-
-    bool deleted;
-};
-
-static int str_hash(void *key) {
-    return hashmapHash(key, strlen(key));
-}
-
-/** Test if two string keys are equal ignoring case */
-static bool str_icase_equals(void *keyA, void *keyB) {
-    return strcasecmp(keyA, keyB) == 0;
-}
-
-/* Global data for all FUSE mounts */
-struct fuse_global {
-    pthread_mutex_t lock;
-
-    uid_t uid;
-    gid_t gid;
-    bool multi_user;
-
-    char source_path[PATH_MAX];
-    char obb_path[PATH_MAX];
-
-    Hashmap* package_to_appid;
-
-    __u64 next_generation;
-    struct node root;
-
-    /* Used to allocate unique inode numbers for fuse nodes. We use
-     * a simple counter based scheme where inode numbers from deleted
-     * nodes aren't reused. Note that inode allocations are not stable
-     * across multiple invocation of the sdcard daemon, but that shouldn't
-     * be a huge problem in practice.
-     *
-     * Note that we restrict inodes to 32 bit unsigned integers to prevent
-     * truncation on 32 bit processes when unsigned long long stat.st_ino is
-     * assigned to an unsigned long ino_t type in an LP32 process.
-     *
-     * Also note that fuse_attr and fuse_dirent inode values are 64 bits wide
-     * on both LP32 and LP64, but the fuse kernel code doesn't squash 64 bit
-     * inode numbers into 32 bit values on 64 bit kernels (see fuse_squash_ino
-     * in fs/fuse/inode.c).
-     *
-     * Accesses must be guarded by |lock|.
-     */
-    __u32 inode_ctr;
-
-    struct fuse* fuse_default;
-    struct fuse* fuse_read;
-    struct fuse* fuse_write;
-};
-
-/* Single FUSE mount */
-struct fuse {
-    struct fuse_global* global;
-
-    char dest_path[PATH_MAX];
-
-    int fd;
-
-    gid_t gid;
-    mode_t mask;
-};
-
-/* Private data used by a single FUSE handler */
-struct fuse_handler {
-    struct fuse* fuse;
-    int token;
-
-    /* To save memory, we never use the contents of the request buffer and the read
-     * buffer at the same time.  This allows us to share the underlying storage. */
-    union {
-        __u8 request_buffer[MAX_REQUEST_SIZE];
-        __u8 read_buffer[MAX_READ + PAGE_SIZE];
-    };
-};
-
-static inline void *id_to_ptr(__u64 nid)
-{
-    return (void *) (uintptr_t) nid;
-}
-
-static inline __u64 ptr_to_id(void *ptr)
-{
-    return (__u64) (uintptr_t) ptr;
-}
-
-static void acquire_node_locked(struct node* node)
-{
-    node->refcount++;
-    TRACE("ACQUIRE %p (%s) rc=%d\n", node, node->name, node->refcount);
-}
-
-static void remove_node_from_parent_locked(struct node* node);
-
-static void release_node_locked(struct node* node)
-{
-    TRACE("RELEASE %p (%s) rc=%d\n", node, node->name, node->refcount);
-    if (node->refcount > 0) {
-        node->refcount--;
-        if (!node->refcount) {
-            TRACE("DESTROY %p (%s)\n", node, node->name);
-            remove_node_from_parent_locked(node);
-
-                /* TODO: remove debugging - poison memory */
-            memset(node->name, 0xef, node->namelen);
-            free(node->name);
-            free(node->actual_name);
-            memset(node, 0xfc, sizeof(*node));
-            free(node);
-        }
-    } else {
-        ERROR("Zero refcnt %p\n", node);
-    }
-}
-
-static void add_node_to_parent_locked(struct node *node, struct node *parent) {
-    node->parent = parent;
-    node->next = parent->child;
-    parent->child = node;
-    acquire_node_locked(parent);
-}
-
-static void remove_node_from_parent_locked(struct node* node)
-{
-    if (node->parent) {
-        if (node->parent->child == node) {
-            node->parent->child = node->parent->child->next;
-        } else {
-            struct node *node2;
-            node2 = node->parent->child;
-            while (node2->next != node)
-                node2 = node2->next;
-            node2->next = node->next;
-        }
-        release_node_locked(node->parent);
-        node->parent = NULL;
-        node->next = NULL;
-    }
-}
-
-/* Gets the absolute path to a node into the provided buffer.
- *
- * Populates 'buf' with the path and returns the length of the path on success,
- * or returns -1 if the path is too long for the provided buffer.
- */
-static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
-    const char* name;
-    size_t namelen;
-    if (node->graft_path) {
-        name = node->graft_path;
-        namelen = node->graft_pathlen;
-    } else if (node->actual_name) {
-        name = node->actual_name;
-        namelen = node->namelen;
-    } else {
-        name = node->name;
-        namelen = node->namelen;
-    }
-
-    if (bufsize < namelen + 1) {
-        return -1;
-    }
-
-    ssize_t pathlen = 0;
-    if (node->parent && node->graft_path == NULL) {
-        pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
-        if (pathlen < 0) {
-            return -1;
-        }
-        buf[pathlen++] = '/';
-    }
-
-    memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
-    return pathlen + namelen;
-}
-
-/* Finds the absolute path of a file within a given directory.
- * Performs a case-insensitive search for the file and sets the buffer to the path
- * of the first matching file.  If 'search' is zero or if no match is found, sets
- * the buffer to the path that the file would have, assuming the name were case-sensitive.
- *
- * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
- * or returns NULL if the path is too long for the provided buffer.
- */
-static char* find_file_within(const char* path, const char* name,
-        char* buf, size_t bufsize, int search)
-{
-    size_t pathlen = strlen(path);
-    size_t namelen = strlen(name);
-    size_t childlen = pathlen + namelen + 1;
-    char* actual;
-
-    if (bufsize <= childlen) {
-        return NULL;
-    }
-
-    memcpy(buf, path, pathlen);
-    buf[pathlen] = '/';
-    actual = buf + pathlen + 1;
-    memcpy(actual, name, namelen + 1);
-
-    if (search && access(buf, F_OK)) {
-        struct dirent* entry;
-        DIR* dir = opendir(path);
-        if (!dir) {
-            ERROR("opendir %s failed: %s\n", path, strerror(errno));
-            return actual;
-        }
-        while ((entry = readdir(dir))) {
-            if (!strcasecmp(entry->d_name, name)) {
-                /* we have a match - replace the name, don't need to copy the null again */
-                memcpy(actual, entry->d_name, namelen);
-                break;
-            }
-        }
-        closedir(dir);
-    }
-    return actual;
-}
-
-static void attr_from_stat(struct fuse* fuse, struct fuse_attr *attr,
-        const struct stat *s, const struct node* node) {
-    attr->ino = node->ino;
-    attr->size = s->st_size;
-    attr->blocks = s->st_blocks;
-    attr->atime = s->st_atim.tv_sec;
-    attr->mtime = s->st_mtim.tv_sec;
-    attr->ctime = s->st_ctim.tv_sec;
-    attr->atimensec = s->st_atim.tv_nsec;
-    attr->mtimensec = s->st_mtim.tv_nsec;
-    attr->ctimensec = s->st_ctim.tv_nsec;
-    attr->mode = s->st_mode;
-    attr->nlink = s->st_nlink;
-
-    attr->uid = node->uid;
-
-    if (fuse->gid == AID_SDCARD_RW) {
-        /* As an optimization, certain trusted system components only run
-         * as owner but operate across all users. Since we're now handing
-         * out the sdcard_rw GID only to trusted apps, we're okay relaxing
-         * the user boundary enforcement for the default view. The UIDs
-         * assigned to app directories are still multiuser aware. */
-        attr->gid = AID_SDCARD_RW;
-    } else {
-        attr->gid = multiuser_get_uid(node->userid, fuse->gid);
-    }
-
-    int visible_mode = 0775 & ~fuse->mask;
-    if (node->perm == PERM_PRE_ROOT) {
-        /* Top of multi-user view should always be visible to ensure
-         * secondary users can traverse inside. */
-        visible_mode = 0711;
-    } else if (node->under_android) {
-        /* Block "other" access to Android directories, since only apps
-         * belonging to a specific user should be in there; we still
-         * leave +x open for the default view. */
-        if (fuse->gid == AID_SDCARD_RW) {
-            visible_mode = visible_mode & ~0006;
-        } else {
-            visible_mode = visible_mode & ~0007;
-        }
-    }
-    int owner_mode = s->st_mode & 0700;
-    int filtered_mode = visible_mode & (owner_mode | (owner_mode >> 3) | (owner_mode >> 6));
-    attr->mode = (attr->mode & S_IFMT) | filtered_mode;
-}
-
-static int touch(char* path, mode_t mode) {
-    int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW, mode);
-    if (fd == -1) {
-        if (errno == EEXIST) {
-            return 0;
-        } else {
-            ERROR("Failed to open(%s): %s\n", path, strerror(errno));
-            return -1;
-        }
-    }
-    close(fd);
-    return 0;
-}
-
-static void derive_permissions_locked(struct fuse* fuse, struct node *parent,
-        struct node *node) {
-    appid_t appid;
-
-    /* By default, each node inherits from its parent */
-    node->perm = PERM_INHERIT;
-    node->userid = parent->userid;
-    node->uid = parent->uid;
-    node->under_android = parent->under_android;
-
-    /* Derive custom permissions based on parent and current node */
-    switch (parent->perm) {
-    case PERM_INHERIT:
-        /* Already inherited above */
-        break;
-    case PERM_PRE_ROOT:
-        /* Legacy internal layout places users at top level */
-        node->perm = PERM_ROOT;
-        node->userid = strtoul(node->name, NULL, 10);
-        break;
-    case PERM_ROOT:
-        /* Assume masked off by default. */
-        if (!strcasecmp(node->name, "Android")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID;
-            node->under_android = true;
-        }
-        break;
-    case PERM_ANDROID:
-        if (!strcasecmp(node->name, "data")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_DATA;
-        } else if (!strcasecmp(node->name, "obb")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_OBB;
-            /* Single OBB directory is always shared */
-            node->graft_path = fuse->global->obb_path;
-            node->graft_pathlen = strlen(fuse->global->obb_path);
-        } else if (!strcasecmp(node->name, "media")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_MEDIA;
-        }
-        break;
-    case PERM_ANDROID_DATA:
-    case PERM_ANDROID_OBB:
-    case PERM_ANDROID_MEDIA:
-        appid = (appid_t) (uintptr_t) hashmapGet(fuse->global->package_to_appid, node->name);
-        if (appid != 0) {
-            node->uid = multiuser_get_uid(parent->userid, appid);
-        }
-        break;
-    }
-}
-
-static void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent) {
-    struct node *node;
-    for (node = parent->child; node; node = node->next) {
-        derive_permissions_locked(fuse, parent, node);
-        if (node->child) {
-            derive_permissions_recursive_locked(fuse, node);
-        }
-    }
-}
-
-/* Kernel has already enforced everything we returned through
- * derive_permissions_locked(), so this is used to lock down access
- * even further, such as enforcing that apps hold sdcard_rw. */
-static bool check_caller_access_to_name(struct fuse* fuse,
-        const struct fuse_in_header *hdr, const struct node* parent_node,
-        const char* name, int mode) {
-    /* Always block security-sensitive files at root */
-    if (parent_node && parent_node->perm == PERM_ROOT) {
-        if (!strcasecmp(name, "autorun.inf")
-                || !strcasecmp(name, ".android_secure")
-                || !strcasecmp(name, "android_secure")) {
-            return false;
-        }
-    }
-
-    /* Root always has access; access for any other UIDs should always
-     * be controlled through packages.list. */
-    if (hdr->uid == 0) {
-        return true;
-    }
-
-    /* No extra permissions to enforce */
-    return true;
-}
-
-static bool check_caller_access_to_node(struct fuse* fuse,
-        const struct fuse_in_header *hdr, const struct node* node, int mode) {
-    return check_caller_access_to_name(fuse, hdr, node->parent, node->name, mode);
-}
-
-struct node *create_node_locked(struct fuse* fuse,
-        struct node *parent, const char *name, const char* actual_name)
-{
-    struct node *node;
-    size_t namelen = strlen(name);
-
-    // Detect overflows in the inode counter. "4 billion nodes should be enough
-    // for everybody".
-    if (fuse->global->inode_ctr == 0) {
-        ERROR("No more inode numbers available");
-        return NULL;
-    }
-
-    node = calloc(1, sizeof(struct node));
-    if (!node) {
-        return NULL;
-    }
-    node->name = malloc(namelen + 1);
-    if (!node->name) {
-        free(node);
-        return NULL;
-    }
-    memcpy(node->name, name, namelen + 1);
-    if (strcmp(name, actual_name)) {
-        node->actual_name = malloc(namelen + 1);
-        if (!node->actual_name) {
-            free(node->name);
-            free(node);
-            return NULL;
-        }
-        memcpy(node->actual_name, actual_name, namelen + 1);
-    }
-    node->namelen = namelen;
-    node->nid = ptr_to_id(node);
-    node->ino = fuse->global->inode_ctr++;
-    node->gen = fuse->global->next_generation++;
-
-    node->deleted = false;
-
-    derive_permissions_locked(fuse, parent, node);
-    acquire_node_locked(node);
-    add_node_to_parent_locked(node, parent);
-    return node;
-}
-
-static int rename_node_locked(struct node *node, const char *name,
-        const char* actual_name)
-{
-    size_t namelen = strlen(name);
-    int need_actual_name = strcmp(name, actual_name);
-
-    /* make the storage bigger without actually changing the name
-     * in case an error occurs part way */
-    if (namelen > node->namelen) {
-        char* new_name = realloc(node->name, namelen + 1);
-        if (!new_name) {
-            return -ENOMEM;
-        }
-        node->name = new_name;
-        if (need_actual_name && node->actual_name) {
-            char* new_actual_name = realloc(node->actual_name, namelen + 1);
-            if (!new_actual_name) {
-                return -ENOMEM;
-            }
-            node->actual_name = new_actual_name;
-        }
-    }
-
-    /* update the name, taking care to allocate storage before overwriting the old name */
-    if (need_actual_name) {
-        if (!node->actual_name) {
-            node->actual_name = malloc(namelen + 1);
-            if (!node->actual_name) {
-                return -ENOMEM;
-            }
-        }
-        memcpy(node->actual_name, actual_name, namelen + 1);
-    } else {
-        free(node->actual_name);
-        node->actual_name = NULL;
-    }
-    memcpy(node->name, name, namelen + 1);
-    node->namelen = namelen;
-    return 0;
-}
-
-static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
-{
-    if (nid == FUSE_ROOT_ID) {
-        return &fuse->global->root;
-    } else {
-        return id_to_ptr(nid);
-    }
-}
-
-static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
-        char* buf, size_t bufsize)
-{
-    struct node* node = lookup_node_by_id_locked(fuse, nid);
-    if (node && get_node_path_locked(node, buf, bufsize) < 0) {
-        node = NULL;
-    }
-    return node;
-}
-
-static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
-{
-    for (node = node->child; node; node = node->next) {
-        /* use exact string comparison, nodes that differ by case
-         * must be considered distinct even if they refer to the same
-         * underlying file as otherwise operations such as "mv x x"
-         * will not work because the source and target nodes are the same. */
-        if (!strcmp(name, node->name) && !node->deleted) {
-            return node;
-        }
-    }
-    return 0;
-}
-
-static struct node* acquire_or_create_child_locked(
-        struct fuse* fuse, struct node* parent,
-        const char* name, const char* actual_name)
-{
-    struct node* child = lookup_child_by_name_locked(parent, name);
-    if (child) {
-        acquire_node_locked(child);
-    } else {
-        child = create_node_locked(fuse, parent, name, actual_name);
-    }
-    return child;
-}
-
-static void fuse_status(struct fuse *fuse, __u64 unique, int err)
-{
-    struct fuse_out_header hdr;
-    hdr.len = sizeof(hdr);
-    hdr.error = err;
-    hdr.unique = unique;
-    write(fuse->fd, &hdr, sizeof(hdr));
-}
-
-static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
-{
-    struct fuse_out_header hdr;
-    struct iovec vec[2];
-    int res;
-
-    hdr.len = len + sizeof(hdr);
-    hdr.error = 0;
-    hdr.unique = unique;
-
-    vec[0].iov_base = &hdr;
-    vec[0].iov_len = sizeof(hdr);
-    vec[1].iov_base = data;
-    vec[1].iov_len = len;
-
-    res = writev(fuse->fd, vec, 2);
-    if (res < 0) {
-        ERROR("*** REPLY FAILED *** %d\n", errno);
-    }
-}
-
-static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
-        struct node* parent, const char* name, const char* actual_name,
-        const char* path)
-{
-    struct node* node;
-    struct fuse_entry_out out;
-    struct stat s;
-
-    if (lstat(path, &s) < 0) {
-        return -errno;
-    }
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
-    if (!node) {
-        pthread_mutex_unlock(&fuse->global->lock);
-        return -ENOMEM;
-    }
-    memset(&out, 0, sizeof(out));
-    attr_from_stat(fuse, &out.attr, &s, node);
-    out.attr_valid = 10;
-    out.entry_valid = 10;
-    out.nodeid = node->nid;
-    out.generation = node->gen;
-    pthread_mutex_unlock(&fuse->global->lock);
-    fuse_reply(fuse, unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int fuse_reply_attr(struct fuse* fuse, __u64 unique, const struct node* node,
-        const char* path)
-{
-    struct fuse_attr_out out;
-    struct stat s;
-
-    if (lstat(path, &s) < 0) {
-        return -errno;
-    }
-    memset(&out, 0, sizeof(out));
-    attr_from_stat(fuse, &out.attr, &s, node);
-    out.attr_valid = 10;
-    fuse_reply(fuse, unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static void fuse_notify_delete(struct fuse* fuse, const __u64 parent,
-        const __u64 child, const char* name) {
-    struct fuse_out_header hdr;
-    struct fuse_notify_delete_out data;
-    struct iovec vec[3];
-    size_t namelen = strlen(name);
-    int res;
-
-    hdr.len = sizeof(hdr) + sizeof(data) + namelen + 1;
-    hdr.error = FUSE_NOTIFY_DELETE;
-    hdr.unique = 0;
-
-    data.parent = parent;
-    data.child = child;
-    data.namelen = namelen;
-    data.padding = 0;
-
-    vec[0].iov_base = &hdr;
-    vec[0].iov_len = sizeof(hdr);
-    vec[1].iov_base = &data;
-    vec[1].iov_len = sizeof(data);
-    vec[2].iov_base = (void*) name;
-    vec[2].iov_len = namelen + 1;
-
-    res = writev(fuse->fd, vec, 3);
-    /* Ignore ENOENT, since other views may not have seen the entry */
-    if (res < 0 && errno != ENOENT) {
-        ERROR("*** NOTIFY FAILED *** %d\n", errno);
-    }
-}
-
-static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    TRACE("[%d] LOOKUP %s @ %"PRIx64" (%s)\n", handler->token, name, hdr->nodeid,
-        parent_node ? parent_node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, R_OK)) {
-        return -EACCES;
-    }
-
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
-{
-    struct node* node;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_by_id_locked(fuse, hdr->nodeid);
-    TRACE("[%d] FORGET #%"PRIu64" @ %"PRIx64" (%s)\n", handler->token, req->nlookup,
-            hdr->nodeid, node ? node->name : "?");
-    if (node) {
-        __u64 n = req->nlookup;
-        while (n--) {
-            release_node_locked(node);
-        }
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    return NO_STATUS; /* no reply */
-}
-
-static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    TRACE("[%d] GETATTR flags=%x fh=%"PRIx64" @ %"PRIx64" (%s)\n", handler->token,
-            req->getattr_flags, req->fh, hdr->nodeid, node ? node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-
-    return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct timespec times[2];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    TRACE("[%d] SETATTR fh=%"PRIx64" valid=%x @ %"PRIx64" (%s)\n", handler->token,
-            req->fh, req->valid, hdr->nodeid, node ? node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-
-    if (!(req->valid & FATTR_FH) &&
-            !check_caller_access_to_node(fuse, hdr, node, W_OK)) {
-        return -EACCES;
-    }
-
-    /* XXX: incomplete implementation on purpose.
-     * chmod/chown should NEVER be implemented.*/
-
-    if ((req->valid & FATTR_SIZE) && truncate64(path, req->size) < 0) {
-        return -errno;
-    }
-
-    /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
-     * are both set, then set it to the current time.  Else, set it to the
-     * time specified in the request.  Same goes for mtime.  Use utimensat(2)
-     * as it allows ATIME and MTIME to be changed independently, and has
-     * nanosecond resolution which fuse also has.
-     */
-    if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
-        times[0].tv_nsec = UTIME_OMIT;
-        times[1].tv_nsec = UTIME_OMIT;
-        if (req->valid & FATTR_ATIME) {
-            if (req->valid & FATTR_ATIME_NOW) {
-              times[0].tv_nsec = UTIME_NOW;
-            } else {
-              times[0].tv_sec = req->atime;
-              times[0].tv_nsec = req->atimensec;
-            }
-        }
-        if (req->valid & FATTR_MTIME) {
-            if (req->valid & FATTR_MTIME_NOW) {
-              times[1].tv_nsec = UTIME_NOW;
-            } else {
-              times[1].tv_sec = req->mtime;
-              times[1].tv_nsec = req->mtimensec;
-            }
-        }
-        TRACE("[%d] Calling utimensat on %s with atime %ld, mtime=%ld\n",
-                handler->token, path, times[0].tv_sec, times[1].tv_sec);
-        if (utimensat(-1, path, times, 0) < 0) {
-            return -errno;
-        }
-    }
-    return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    TRACE("[%d] MKNOD %s 0%o @ %"PRIx64" (%s)\n", handler->token,
-            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    __u32 mode = (req->mode & (~0777)) | 0664;
-    if (mknod(child_path, mode, req->rdev) < 0) {
-        return -errno;
-    }
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    TRACE("[%d] MKDIR %s 0%o @ %"PRIx64" (%s)\n", handler->token,
-            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    __u32 mode = (req->mode & (~0777)) | 0775;
-    if (mkdir(child_path, mode) < 0) {
-        return -errno;
-    }
-
-    /* When creating /Android/data and /Android/obb, mark them as .nomedia */
-    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "data")) {
-        char nomedia[PATH_MAX];
-        snprintf(nomedia, PATH_MAX, "%s/.nomedia", child_path);
-        if (touch(nomedia, 0664) != 0) {
-            ERROR("Failed to touch(%s): %s\n", nomedia, strerror(errno));
-            return -ENOENT;
-        }
-    }
-    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "obb")) {
-        char nomedia[PATH_MAX];
-        snprintf(nomedia, PATH_MAX, "%s/.nomedia", fuse->global->obb_path);
-        if (touch(nomedia, 0664) != 0) {
-            ERROR("Failed to touch(%s): %s\n", nomedia, strerror(errno));
-            return -ENOENT;
-        }
-    }
-
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const char* name)
-{
-    struct node* parent_node;
-    struct node* child_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    TRACE("[%d] UNLINK %s @ %"PRIx64" (%s)\n", handler->token,
-            name, hdr->nodeid, parent_node ? parent_node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1)) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    if (unlink(child_path) < 0) {
-        return -errno;
-    }
-    pthread_mutex_lock(&fuse->global->lock);
-    child_node = lookup_child_by_name_locked(parent_node, name);
-    if (child_node) {
-        child_node->deleted = true;
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (parent_node && child_node) {
-        /* Tell all other views that node is gone */
-        TRACE("[%d] fuse_notify_delete parent=%"PRIx64", child=%"PRIx64", name=%s\n",
-                handler->token, (uint64_t) parent_node->nid, (uint64_t) child_node->nid, name);
-        if (fuse != fuse->global->fuse_default) {
-            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_read) {
-            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_write) {
-            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
-        }
-    }
-    return 0;
-}
-
-static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const char* name)
-{
-    struct node* child_node;
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    TRACE("[%d] RMDIR %s @ %"PRIx64" (%s)\n", handler->token,
-            name, hdr->nodeid, parent_node ? parent_node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1)) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    if (rmdir(child_path) < 0) {
-        return -errno;
-    }
-    pthread_mutex_lock(&fuse->global->lock);
-    child_node = lookup_child_by_name_locked(parent_node, name);
-    if (child_node) {
-        child_node->deleted = true;
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (parent_node && child_node) {
-        /* Tell all other views that node is gone */
-        TRACE("[%d] fuse_notify_delete parent=%"PRIx64", child=%"PRIx64", name=%s\n",
-                handler->token, (uint64_t) parent_node->nid, (uint64_t) child_node->nid, name);
-        if (fuse != fuse->global->fuse_default) {
-            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_read) {
-            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_write) {
-            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
-        }
-    }
-    return 0;
-}
-
-static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
-        const char* old_name, const char* new_name)
-{
-    struct node* old_parent_node;
-    struct node* new_parent_node;
-    struct node* child_node;
-    char old_parent_path[PATH_MAX];
-    char new_parent_path[PATH_MAX];
-    char old_child_path[PATH_MAX];
-    char new_child_path[PATH_MAX];
-    const char* new_actual_name;
-    int res;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            old_parent_path, sizeof(old_parent_path));
-    new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
-            new_parent_path, sizeof(new_parent_path));
-    TRACE("[%d] RENAME %s->%s @ %"PRIx64" (%s) -> %"PRIx64" (%s)\n", handler->token,
-            old_name, new_name,
-            hdr->nodeid, old_parent_node ? old_parent_node->name : "?",
-            req->newdir, new_parent_node ? new_parent_node->name : "?");
-    if (!old_parent_node || !new_parent_node) {
-        res = -ENOENT;
-        goto lookup_error;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, old_parent_node, old_name, W_OK)) {
-        res = -EACCES;
-        goto lookup_error;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, new_parent_node, new_name, W_OK)) {
-        res = -EACCES;
-        goto lookup_error;
-    }
-    child_node = lookup_child_by_name_locked(old_parent_node, old_name);
-    if (!child_node || get_node_path_locked(child_node,
-            old_child_path, sizeof(old_child_path)) < 0) {
-        res = -ENOENT;
-        goto lookup_error;
-    }
-    acquire_node_locked(child_node);
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    /* Special case for renaming a file where destination is same path
-     * differing only by case.  In this case we don't want to look for a case
-     * insensitive match.  This allows commands like "mv foo FOO" to work as expected.
-     */
-    int search = old_parent_node != new_parent_node
-            || strcasecmp(old_name, new_name);
-    if (!(new_actual_name = find_file_within(new_parent_path, new_name,
-            new_child_path, sizeof(new_child_path), search))) {
-        res = -ENOENT;
-        goto io_error;
-    }
-
-    TRACE("[%d] RENAME %s->%s\n", handler->token, old_child_path, new_child_path);
-    res = rename(old_child_path, new_child_path);
-    if (res < 0) {
-        res = -errno;
-        goto io_error;
-    }
-
-    pthread_mutex_lock(&fuse->global->lock);
-    res = rename_node_locked(child_node, new_name, new_actual_name);
-    if (!res) {
-        remove_node_from_parent_locked(child_node);
-        derive_permissions_locked(fuse, new_parent_node, child_node);
-        derive_permissions_recursive_locked(fuse, child_node);
-        add_node_to_parent_locked(child_node, new_parent_node);
-    }
-    goto done;
-
-io_error:
-    pthread_mutex_lock(&fuse->global->lock);
-done:
-    release_node_locked(child_node);
-lookup_error:
-    pthread_mutex_unlock(&fuse->global->lock);
-    return res;
-}
-
-static int open_flags_to_access_mode(int open_flags) {
-    if ((open_flags & O_ACCMODE) == O_RDONLY) {
-        return R_OK;
-    } else if ((open_flags & O_ACCMODE) == O_WRONLY) {
-        return W_OK;
-    } else {
-        /* Probably O_RDRW, but treat as default to be safe */
-        return R_OK | W_OK;
-    }
-}
-
-static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct fuse_open_out out;
-    struct handle *h;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    TRACE("[%d] OPEN 0%o @ %"PRIx64" (%s)\n", handler->token,
-            req->flags, hdr->nodeid, node ? node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node,
-            open_flags_to_access_mode(req->flags))) {
-        return -EACCES;
-    }
-    h = malloc(sizeof(*h));
-    if (!h) {
-        return -ENOMEM;
-    }
-    TRACE("[%d] OPEN %s\n", handler->token, path);
-    h->fd = open(path, req->flags);
-    if (h->fd < 0) {
-        free(h);
-        return -errno;
-    }
-    out.fh = ptr_to_id(h);
-    out.open_flags = 0;
-
-#ifdef FUSE_SHORTCIRCUIT
-    out.lower_fd = h->fd;
-#else
-    out.padding = 0;
-#endif
-
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
-    struct handle *h = id_to_ptr(req->fh);
-    __u64 unique = hdr->unique;
-    __u32 size = req->size;
-    __u64 offset = req->offset;
-    int res;
-    __u8 *read_buffer = (__u8 *) ((uintptr_t)(handler->read_buffer + PAGE_SIZE) & ~((uintptr_t)PAGE_SIZE-1));
-
-    /* Don't access any other fields of hdr or req beyond this point, the read buffer
-     * overlaps the request buffer and will clobber data in the request.  This
-     * saves us 128KB per request handler thread at the cost of this scary comment. */
-
-    TRACE("[%d] READ %p(%d) %u@%"PRIu64"\n", handler->token,
-            h, h->fd, size, (uint64_t) offset);
-    if (size > MAX_READ) {
-        return -EINVAL;
-    }
-    res = pread64(h->fd, read_buffer, size, offset);
-    if (res < 0) {
-        return -errno;
-    }
-    fuse_reply(fuse, unique, read_buffer, res);
-    return NO_STATUS;
-}
-
-static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_write_in* req,
-        const void* buffer)
-{
-    struct fuse_write_out out;
-    struct handle *h = id_to_ptr(req->fh);
-    int res;
-    __u8 aligned_buffer[req->size] __attribute__((__aligned__(PAGE_SIZE)));
-
-    if (req->flags & O_DIRECT) {
-        memcpy(aligned_buffer, buffer, req->size);
-        buffer = (const __u8*) aligned_buffer;
-    }
-
-    TRACE("[%d] WRITE %p(%d) %u@%"PRIu64"\n", handler->token,
-            h, h->fd, req->size, req->offset);
-    res = pwrite64(h->fd, buffer, req->size, req->offset);
-    if (res < 0) {
-        return -errno;
-    }
-    out.size = res;
-    out.padding = 0;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr)
-{
-    char path[PATH_MAX];
-    struct statfs stat;
-    struct fuse_statfs_out out;
-    int res;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    TRACE("[%d] STATFS\n", handler->token);
-    res = get_node_path_locked(&fuse->global->root, path, sizeof(path));
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (res < 0) {
-        return -ENOENT;
-    }
-    if (statfs(fuse->global->root.name, &stat) < 0) {
-        return -errno;
-    }
-    memset(&out, 0, sizeof(out));
-    out.st.blocks = stat.f_blocks;
-    out.st.bfree = stat.f_bfree;
-    out.st.bavail = stat.f_bavail;
-    out.st.files = stat.f_files;
-    out.st.ffree = stat.f_ffree;
-    out.st.bsize = stat.f_bsize;
-    out.st.namelen = stat.f_namelen;
-    out.st.frsize = stat.f_frsize;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
-    struct handle *h = id_to_ptr(req->fh);
-
-    TRACE("[%d] RELEASE %p(%d)\n", handler->token, h, h->fd);
-    close(h->fd);
-    free(h);
-    return 0;
-}
-
-static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
-{
-    bool is_dir = (hdr->opcode == FUSE_FSYNCDIR);
-    bool is_data_sync = req->fsync_flags & 1;
-
-    int fd = -1;
-    if (is_dir) {
-      struct dirhandle *dh = id_to_ptr(req->fh);
-      fd = dirfd(dh->d);
-    } else {
-      struct handle *h = id_to_ptr(req->fh);
-      fd = h->fd;
-    }
-
-    TRACE("[%d] %s %p(%d) is_data_sync=%d\n", handler->token,
-            is_dir ? "FSYNCDIR" : "FSYNC",
-            id_to_ptr(req->fh), fd, is_data_sync);
-    int res = is_data_sync ? fdatasync(fd) : fsync(fd);
-    if (res == -1) {
-        return -errno;
-    }
-    return 0;
-}
-
-static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr)
-{
-    TRACE("[%d] FLUSH\n", handler->token);
-    return 0;
-}
-
-static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct fuse_open_out out;
-    struct dirhandle *h;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    TRACE("[%d] OPENDIR @ %"PRIx64" (%s)\n", handler->token,
-            hdr->nodeid, node ? node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-    h = malloc(sizeof(*h));
-    if (!h) {
-        return -ENOMEM;
-    }
-    TRACE("[%d] OPENDIR %s\n", handler->token, path);
-    h->d = opendir(path);
-    if (!h->d) {
-        free(h);
-        return -errno;
-    }
-    out.fh = ptr_to_id(h);
-    out.open_flags = 0;
-
-#ifdef FUSE_SHORTCIRCUIT
-    out.lower_fd = -1;
-#else
-    out.padding = 0;
-#endif
-
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
-    char buffer[8192];
-    struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
-    struct dirent *de;
-    struct dirhandle *h = id_to_ptr(req->fh);
-
-    TRACE("[%d] READDIR %p\n", handler->token, h);
-    if (req->offset == 0) {
-        /* rewinddir() might have been called above us, so rewind here too */
-        TRACE("[%d] calling rewinddir()\n", handler->token);
-        rewinddir(h->d);
-    }
-    de = readdir(h->d);
-    if (!de) {
-        return 0;
-    }
-    fde->ino = FUSE_UNKNOWN_INO;
-    /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
-    fde->off = req->offset + 1;
-    fde->type = de->d_type;
-    fde->namelen = strlen(de->d_name);
-    memcpy(fde->name, de->d_name, fde->namelen + 1);
-    fuse_reply(fuse, hdr->unique, fde,
-            FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
-    return NO_STATUS;
-}
-
-static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
-    struct dirhandle *h = id_to_ptr(req->fh);
-
-    TRACE("[%d] RELEASEDIR %p\n", handler->token, h);
-    closedir(h->d);
-    free(h);
-    return 0;
-}
-
-static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_init_in* req)
-{
-    struct fuse_init_out out;
-    size_t fuse_struct_size;
-
-    TRACE("[%d] INIT ver=%d.%d maxread=%d flags=%x\n",
-            handler->token, req->major, req->minor, req->max_readahead, req->flags);
-
-    /* Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
-     * defined (fuse version 7.6). The structure is the same from 7.6 through
-     * 7.22. Beginning with 7.23, the structure increased in size and added
-     * new parameters.
-     */
-    if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
-        ERROR("Fuse kernel version mismatch: Kernel version %d.%d, Expected at least %d.6",
-              req->major, req->minor, FUSE_KERNEL_VERSION);
-        return -1;
-    }
-
-    /* We limit ourselves to 15 because we don't handle BATCH_FORGET yet */
-    out.minor = MIN(req->minor, 15);
-    fuse_struct_size = sizeof(out);
-#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
-    /* FUSE_KERNEL_VERSION >= 23. */
-
-    /* If the kernel only works on minor revs older than or equal to 22,
-     * then use the older structure size since this code only uses the 7.22
-     * version of the structure. */
-    if (req->minor <= 22) {
-        fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
-    }
-#endif
-
-    out.major = FUSE_KERNEL_VERSION;
-    out.max_readahead = req->max_readahead;
-    out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
-
-#ifdef FUSE_SHORTCIRCUIT
-    out.flags |= FUSE_SHORTCIRCUIT;
-#endif
-
-    out.max_background = 32;
-    out.congestion_threshold = 32;
-    out.max_write = MAX_WRITE;
-    fuse_reply(fuse, hdr->unique, &out, fuse_struct_size);
-    return NO_STATUS;
-}
-
-static int handle_canonical_path(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    int len;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            path, sizeof(path));
-    TRACE("[%d] CANONICAL_PATH @ %" PRIx64 " (%s)\n", handler->token, hdr->nodeid,
-        node ? node->name : "?");
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-    len = strlen(path);
-    if (len + 1 > PATH_MAX)
-        len = PATH_MAX - 1;
-    path[PATH_MAX - 1] = 0;
-    fuse_reply(fuse, hdr->unique, path, len + 1);
-    return NO_STATUS;
-}
-
-
-static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const void *data, size_t data_len)
-{
-    switch (hdr->opcode) {
-    case FUSE_LOOKUP: { /* bytez[] -> entry_out */
-        const char* name = data;
-        return handle_lookup(fuse, handler, hdr, name);
-    }
-
-    case FUSE_FORGET: {
-        const struct fuse_forget_in *req = data;
-        return handle_forget(fuse, handler, hdr, req);
-    }
-
-    case FUSE_GETATTR: { /* getattr_in -> attr_out */
-        const struct fuse_getattr_in *req = data;
-        return handle_getattr(fuse, handler, hdr, req);
-    }
-
-    case FUSE_SETATTR: { /* setattr_in -> attr_out */
-        const struct fuse_setattr_in *req = data;
-        return handle_setattr(fuse, handler, hdr, req);
-    }
-
-//    case FUSE_READLINK:
-//    case FUSE_SYMLINK:
-    case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
-        const struct fuse_mknod_in *req = data;
-        const char *name = ((const char*) data) + sizeof(*req);
-        return handle_mknod(fuse, handler, hdr, req, name);
-    }
-
-    case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
-        const struct fuse_mkdir_in *req = data;
-        const char *name = ((const char*) data) + sizeof(*req);
-        return handle_mkdir(fuse, handler, hdr, req, name);
-    }
-
-    case FUSE_UNLINK: { /* bytez[] -> */
-        const char* name = data;
-        return handle_unlink(fuse, handler, hdr, name);
-    }
-
-    case FUSE_RMDIR: { /* bytez[] -> */
-        const char* name = data;
-        return handle_rmdir(fuse, handler, hdr, name);
-    }
-
-    case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
-        const struct fuse_rename_in *req = data;
-        const char *old_name = ((const char*) data) + sizeof(*req);
-        const char *new_name = old_name + strlen(old_name) + 1;
-        return handle_rename(fuse, handler, hdr, req, old_name, new_name);
-    }
-
-//    case FUSE_LINK:
-    case FUSE_OPEN: { /* open_in -> open_out */
-        const struct fuse_open_in *req = data;
-        return handle_open(fuse, handler, hdr, req);
-    }
-
-    case FUSE_READ: { /* read_in -> byte[] */
-        const struct fuse_read_in *req = data;
-        return handle_read(fuse, handler, hdr, req);
-    }
-
-    case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
-        const struct fuse_write_in *req = data;
-        const void* buffer = (const __u8*)data + sizeof(*req);
-        return handle_write(fuse, handler, hdr, req, buffer);
-    }
-
-    case FUSE_STATFS: { /* getattr_in -> attr_out */
-        return handle_statfs(fuse, handler, hdr);
-    }
-
-    case FUSE_RELEASE: { /* release_in -> */
-        const struct fuse_release_in *req = data;
-        return handle_release(fuse, handler, hdr, req);
-    }
-
-    case FUSE_FSYNC:
-    case FUSE_FSYNCDIR: {
-        const struct fuse_fsync_in *req = data;
-        return handle_fsync(fuse, handler, hdr, req);
-    }
-
-//    case FUSE_SETXATTR:
-//    case FUSE_GETXATTR:
-//    case FUSE_LISTXATTR:
-//    case FUSE_REMOVEXATTR:
-    case FUSE_FLUSH: {
-        return handle_flush(fuse, handler, hdr);
-    }
-
-    case FUSE_OPENDIR: { /* open_in -> open_out */
-        const struct fuse_open_in *req = data;
-        return handle_opendir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_READDIR: {
-        const struct fuse_read_in *req = data;
-        return handle_readdir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_RELEASEDIR: { /* release_in -> */
-        const struct fuse_release_in *req = data;
-        return handle_releasedir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_INIT: { /* init_in -> init_out */
-        const struct fuse_init_in *req = data;
-        return handle_init(fuse, handler, hdr, req);
-    }
-
-    case FUSE_CANONICAL_PATH: { /* nodeid -> bytez[] */
-        return handle_canonical_path(fuse, handler, hdr);
-    }
-
-    default: {
-        TRACE("[%d] NOTIMPL op=%d uniq=%"PRIx64" nid=%"PRIx64"\n",
-                handler->token, hdr->opcode, hdr->unique, hdr->nodeid);
-        return -ENOSYS;
-    }
-    }
-}
-
-static void handle_fuse_requests(struct fuse_handler* handler)
-{
-    struct fuse* fuse = handler->fuse;
-    for (;;) {
-        ssize_t len = TEMP_FAILURE_RETRY(read(fuse->fd,
-                handler->request_buffer, sizeof(handler->request_buffer)));
-        if (len < 0) {
-            if (errno == ENODEV) {
-                ERROR("[%d] someone stole our marbles!\n", handler->token);
-                exit(2);
-            }
-            ERROR("[%d] handle_fuse_requests: errno=%d\n", handler->token, errno);
-            continue;
-        }
-
-        if ((size_t)len < sizeof(struct fuse_in_header)) {
-            ERROR("[%d] request too short: len=%zu\n", handler->token, (size_t)len);
-            continue;
-        }
-
-        const struct fuse_in_header *hdr = (void*)handler->request_buffer;
-        if (hdr->len != (size_t)len) {
-            ERROR("[%d] malformed header: len=%zu, hdr->len=%u\n",
-                    handler->token, (size_t)len, hdr->len);
-            continue;
-        }
-
-        const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
-        size_t data_len = len - sizeof(struct fuse_in_header);
-        __u64 unique = hdr->unique;
-        int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
-
-        /* We do not access the request again after this point because the underlying
-         * buffer storage may have been reused while processing the request. */
-
-        if (res != NO_STATUS) {
-            if (res) {
-                TRACE("[%d] ERROR %d\n", handler->token, res);
-            }
-            fuse_status(fuse, unique, res);
-        }
-    }
-}
-
-static void* start_handler(void* data)
-{
-    struct fuse_handler* handler = data;
-    handle_fuse_requests(handler);
-    return NULL;
-}
-
-static bool remove_str_to_int(void *key, void *value, void *context) {
-    Hashmap* map = context;
-    hashmapRemove(map, key);
-    free(key);
-    return true;
-}
-
-static bool package_parse_callback(pkg_info *info, void *userdata) {
-    struct fuse_global *global = (struct fuse_global *)userdata;
-
-    char* name = strdup(info->name);
-    hashmapPut(global->package_to_appid, name, (void*) (uintptr_t) info->uid);
-    packagelist_free(info);
-    return true;
-}
-
-static bool read_package_list(struct fuse_global* global) {
-    pthread_mutex_lock(&global->lock);
-
-    hashmapForEach(global->package_to_appid, remove_str_to_int, global->package_to_appid);
-
-    bool rc = packagelist_parse(package_parse_callback, global);
-    TRACE("read_package_list: found %zu packages\n",
-            hashmapSize(global->package_to_appid));
-
-    /* Regenerate ownership details using newly loaded mapping */
-    derive_permissions_recursive_locked(global->fuse_default, &global->root);
-
-    pthread_mutex_unlock(&global->lock);
-
-    return rc;
-}
-
-static void watch_package_list(struct fuse_global* global) {
-    struct inotify_event *event;
-    char event_buf[512];
-
-    int nfd = inotify_init();
-    if (nfd < 0) {
-        ERROR("inotify_init failed: %s\n", strerror(errno));
-        return;
-    }
-
-    bool active = false;
-    while (1) {
-        if (!active) {
-            int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
-            if (res == -1) {
-                if (errno == ENOENT || errno == EACCES) {
-                    /* Framework may not have created yet, sleep and retry */
-                    ERROR("missing \"%s\"; retrying\n", PACKAGES_LIST_FILE);
-                    sleep(3);
-                    continue;
-                } else {
-                    ERROR("inotify_add_watch failed: %s\n", strerror(errno));
-                    return;
-                }
-            }
-
-            /* Watch above will tell us about any future changes, so
-             * read the current state. */
-            if (read_package_list(global) == false) {
-                ERROR("read_package_list failed\n");
-                return;
-            }
-            active = true;
-        }
-
-        int event_pos = 0;
-        int res = read(nfd, event_buf, sizeof(event_buf));
-        if (res < (int) sizeof(*event)) {
-            if (errno == EINTR)
-                continue;
-            ERROR("failed to read inotify event: %s\n", strerror(errno));
-            return;
-        }
-
-        while (res >= (int) sizeof(*event)) {
-            int event_size;
-            event = (struct inotify_event *) (event_buf + event_pos);
-
-            TRACE("inotify event: %08x\n", event->mask);
-            if ((event->mask & IN_IGNORED) == IN_IGNORED) {
-                /* Previously watched file was deleted, probably due to move
-                 * that swapped in new data; re-arm the watch and read. */
-                active = false;
-            }
-
-            event_size = sizeof(*event) + event->len;
-            res -= event_size;
-            event_pos += event_size;
-        }
-    }
-}
-
-static int usage() {
-    ERROR("usage: sdcard [OPTIONS] <source_path> <label>\n"
-            "    -u: specify UID to run as\n"
-            "    -g: specify GID to run as\n"
-            "    -U: specify user ID that owns device\n"
-            "    -m: source_path is multi-user\n"
-            "    -w: runtime write mount has full write access\n"
-            "\n");
-    return 1;
-}
-
-static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
-    char opts[256];
-
-    fuse->fd = open("/dev/fuse", O_RDWR);
-    if (fuse->fd == -1) {
-        ERROR("failed to open fuse device: %s\n", strerror(errno));
-        return -1;
-    }
-
-    umount2(fuse->dest_path, MNT_DETACH);
-
-    snprintf(opts, sizeof(opts),
-            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
-            fuse->fd, fuse->global->uid, fuse->global->gid);
-    if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC |
-            MS_NOATIME, opts) != 0) {
-        ERROR("failed to mount fuse filesystem: %s\n", strerror(errno));
-        return -1;
-    }
-
-    fuse->gid = gid;
-    fuse->mask = mask;
-
-    return 0;
-}
-
-static void run(const char* source_path, const char* label, uid_t uid,
-        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
-    struct fuse_global global;
-    struct fuse fuse_default;
-    struct fuse fuse_read;
-    struct fuse fuse_write;
-    struct fuse_handler handler_default;
-    struct fuse_handler handler_read;
-    struct fuse_handler handler_write;
-    pthread_t thread_default;
-    pthread_t thread_read;
-    pthread_t thread_write;
-
-    memset(&global, 0, sizeof(global));
-    memset(&fuse_default, 0, sizeof(fuse_default));
-    memset(&fuse_read, 0, sizeof(fuse_read));
-    memset(&fuse_write, 0, sizeof(fuse_write));
-    memset(&handler_default, 0, sizeof(handler_default));
-    memset(&handler_read, 0, sizeof(handler_read));
-    memset(&handler_write, 0, sizeof(handler_write));
-
-    pthread_mutex_init(&global.lock, NULL);
-    global.package_to_appid = hashmapCreate(256, str_hash, str_icase_equals);
-    global.uid = uid;
-    global.gid = gid;
-    global.multi_user = multi_user;
-    global.next_generation = 0;
-    global.inode_ctr = 1;
-
-    memset(&global.root, 0, sizeof(global.root));
-    global.root.nid = FUSE_ROOT_ID; /* 1 */
-    global.root.refcount = 2;
-    global.root.namelen = strlen(source_path);
-    global.root.name = strdup(source_path);
-    global.root.userid = userid;
-    global.root.uid = AID_ROOT;
-    global.root.under_android = false;
-
-    strcpy(global.source_path, source_path);
-
-    if (multi_user) {
-        global.root.perm = PERM_PRE_ROOT;
-        snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
-    } else {
-        global.root.perm = PERM_ROOT;
-        snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
-    }
-
-    fuse_default.global = &global;
-    fuse_read.global = &global;
-    fuse_write.global = &global;
-
-    global.fuse_default = &fuse_default;
-    global.fuse_read = &fuse_read;
-    global.fuse_write = &fuse_write;
-
-    snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
-    snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
-    snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
-
-    handler_default.fuse = &fuse_default;
-    handler_read.fuse = &fuse_read;
-    handler_write.fuse = &fuse_write;
-
-    handler_default.token = 0;
-    handler_read.token = 1;
-    handler_write.token = 2;
-
-    umask(0);
-
-    if (multi_user) {
-        /* Multi-user storage is fully isolated per user, so "other"
-         * permissions are completely masked off. */
-        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
-                || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
-                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
-            ERROR("failed to fuse_setup\n");
-            exit(1);
-        }
-    } else {
-        /* Physical storage is readable by all users on device, but
-         * the Android directories are masked off to a single user
-         * deep inside attr_from_stat(). */
-        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
-                || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
-                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
-            ERROR("failed to fuse_setup\n");
-            exit(1);
-        }
-    }
-
-    /* Drop privs */
-    if (setgroups(sizeof(kGroups) / sizeof(kGroups[0]), kGroups) < 0) {
-        ERROR("cannot setgroups: %s\n", strerror(errno));
-        exit(1);
-    }
-    if (setgid(gid) < 0) {
-        ERROR("cannot setgid: %s\n", strerror(errno));
-        exit(1);
-    }
-    if (setuid(uid) < 0) {
-        ERROR("cannot setuid: %s\n", strerror(errno));
-        exit(1);
-    }
-
-    if (multi_user) {
-        fs_prepare_dir(global.obb_path, 0775, uid, gid);
-    }
-
-    if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
-            || pthread_create(&thread_read, NULL, start_handler, &handler_read)
-            || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
-        ERROR("failed to pthread_create\n");
-        exit(1);
-    }
-
-    watch_package_list(&global);
-    ERROR("terminated prematurely\n");
-    exit(1);
-}
-
-static int sdcardfs_setup(const char *source_path, const char *dest_path, uid_t fsuid,
-                        gid_t fsgid, bool multi_user, userid_t userid, gid_t gid, mode_t mask) {
-    char opts[256];
-
-    snprintf(opts, sizeof(opts),
-            "fsuid=%d,fsgid=%d,%smask=%d,userid=%d,gid=%d",
-            fsuid, fsgid, multi_user?"multiuser,":"", mask, userid, gid);
-
-    if (mount(source_path, dest_path, "sdcardfs",
-                        MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts) != 0) {
-        ERROR("failed to mount sdcardfs filesystem: %s\n", strerror(errno));
-        return -1;
-    }
-
-    return 0;
-}
-
-static void run_sdcardfs(const char* source_path, const char* label, uid_t uid,
-        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
-    char dest_path_default[PATH_MAX];
-    char dest_path_read[PATH_MAX];
-    char dest_path_write[PATH_MAX];
-    char obb_path[PATH_MAX];
-    snprintf(dest_path_default, PATH_MAX, "/mnt/runtime/default/%s", label);
-    snprintf(dest_path_read, PATH_MAX, "/mnt/runtime/read/%s", label);
-    snprintf(dest_path_write, PATH_MAX, "/mnt/runtime/write/%s", label);
-
-    umask(0);
-    if (multi_user) {
-        /* Multi-user storage is fully isolated per user, so "other"
-         * permissions are completely masked off. */
-        if (sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
-                                                      AID_SDCARD_RW, 0006)
-                || sdcardfs_setup(source_path, dest_path_read, uid, gid, multi_user, userid,
-                                                      AID_EVERYBODY, 0027)
-                || sdcardfs_setup(source_path, dest_path_write, uid, gid, multi_user, userid,
-                                                      AID_EVERYBODY, full_write ? 0007 : 0027)) {
-            ERROR("failed to fuse_setup\n");
-            exit(1);
-        }
-    } else {
-        /* Physical storage is readable by all users on device, but
-         * the Android directories are masked off to a single user
-         * deep inside attr_from_stat(). */
-        if (sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
-                                                      AID_SDCARD_RW, 0006)
-                || sdcardfs_setup(source_path, dest_path_read, uid, gid, multi_user, userid,
-                                                      AID_EVERYBODY, full_write ? 0027 : 0022)
-                || sdcardfs_setup(source_path, dest_path_write, uid, gid, multi_user, userid,
-                                                      AID_EVERYBODY, full_write ? 0007 : 0022)) {
-            ERROR("failed to fuse_setup\n");
-            exit(1);
-        }
-    }
-
-    /* Drop privs */
-    if (setgroups(sizeof(kGroups) / sizeof(kGroups[0]), kGroups) < 0) {
-        ERROR("cannot setgroups: %s\n", strerror(errno));
-        exit(1);
-    }
-    if (setgid(gid) < 0) {
-        ERROR("cannot setgid: %s\n", strerror(errno));
-        exit(1);
-    }
-    if (setuid(uid) < 0) {
-        ERROR("cannot setuid: %s\n", strerror(errno));
-        exit(1);
-    }
-
-    if (multi_user) {
-        snprintf(obb_path, sizeof(obb_path), "%s/obb", source_path);
-        fs_prepare_dir(&obb_path[0], 0775, uid, gid);
-    }
-
-    exit(0);
-}
-
-static bool supports_sdcardfs(void) {
-    FILE *fp;
-    char *buf = NULL;
-    size_t buflen = 0;
-
-    fp = fopen("/proc/filesystems", "r");
-    if (!fp) {
-        ERROR("Could not read /proc/filesystems, error: %s\n", strerror(errno));
-        return false;
-    }
-    while ((getline(&buf, &buflen, fp)) > 0) {
-        if (strstr(buf, "sdcardfs\n")) {
-            free(buf);
-            fclose(fp);
-            return true;
-        }
-    }
-    free(buf);
-    fclose(fp);
-    return false;
-}
-
-static bool should_use_sdcardfs(void) {
-    char property[PROPERTY_VALUE_MAX];
-
-    // Allow user to have a strong opinion about state
-    property_get(PROP_SDCARDFS_USER, property, "");
-    if (!strcmp(property, "force_on")) {
-        ALOGW("User explicitly enabled sdcardfs");
-        return supports_sdcardfs();
-    } else if (!strcmp(property, "force_off")) {
-        ALOGW("User explicitly disabled sdcardfs");
-        return false;
-    }
-
-    // Fall back to device opinion about state
-    if (property_get_bool(PROP_SDCARDFS_DEVICE, false)) {
-        ALOGW("Device explicitly enabled sdcardfs");
-        return supports_sdcardfs();
-    } else {
-        ALOGW("Device explicitly disabled sdcardfs");
-        return false;
-    }
-}
-
-int main(int argc, char **argv) {
-    const char *source_path = NULL;
-    const char *label = NULL;
-    uid_t uid = 0;
-    gid_t gid = 0;
-    userid_t userid = 0;
-    bool multi_user = false;
-    bool full_write = false;
-    int i;
-    struct rlimit rlim;
-    int fs_version;
-
-    int opt;
-    while ((opt = getopt(argc, argv, "u:g:U:mw")) != -1) {
-        switch (opt) {
-            case 'u':
-                uid = strtoul(optarg, NULL, 10);
-                break;
-            case 'g':
-                gid = strtoul(optarg, NULL, 10);
-                break;
-            case 'U':
-                userid = strtoul(optarg, NULL, 10);
-                break;
-            case 'm':
-                multi_user = true;
-                break;
-            case 'w':
-                full_write = true;
-                break;
-            case '?':
-            default:
-                return usage();
-        }
-    }
-
-    for (i = optind; i < argc; i++) {
-        char* arg = argv[i];
-        if (!source_path) {
-            source_path = arg;
-        } else if (!label) {
-            label = arg;
-        } else {
-            ERROR("too many arguments\n");
-            return usage();
-        }
-    }
-
-    if (!source_path) {
-        ERROR("no source path specified\n");
-        return usage();
-    }
-    if (!label) {
-        ERROR("no label specified\n");
-        return usage();
-    }
-    if (!uid || !gid) {
-        ERROR("uid and gid must be nonzero\n");
-        return usage();
-    }
-
-    rlim.rlim_cur = 8192;
-    rlim.rlim_max = 8192;
-    if (setrlimit(RLIMIT_NOFILE, &rlim)) {
-        ERROR("Error setting RLIMIT_NOFILE, errno = %d\n", errno);
-    }
-
-    while ((fs_read_atomic_int("/data/.layout_version", &fs_version) == -1) || (fs_version < 3)) {
-        ERROR("installd fs upgrade not yet complete. Waiting...\n");
-        sleep(1);
-    }
-
-    if (should_use_sdcardfs()) {
-        run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write);
-    } else {
-        run(source_path, label, uid, gid, userid, multi_user, full_write);
-    }
-    return 1;
-}
diff --git a/sdcard/sdcard.cpp b/sdcard/sdcard.cpp
new file mode 100644
index 0000000..c342cf8
--- /dev/null
+++ b/sdcard/sdcard.cpp
@@ -0,0 +1,520 @@
+// 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.
+
+#define LOG_TAG "sdcard"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/fuse.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/inotify.h>
+#include <sys/mount.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include <cutils/fs.h>
+#include <cutils/multiuser.h>
+#include <cutils/properties.h>
+
+#include <packagelistparser/packagelistparser.h>
+
+#include <libminijail.h>
+#include <scoped_minijail.h>
+
+#include <private/android_filesystem_config.h>
+
+// README
+//
+// What is this?
+//
+// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
+// directory permissions (all files are given fixed owner, group, and
+// permissions at creation, owner, group, and permissions are not
+// changeable, symlinks and hardlinks are not createable, etc.
+//
+// See usage() for command line options.
+//
+// It must be run as root, but will drop to requested UID/GID as soon as it
+// mounts a filesystem.  It will refuse to run if requested UID/GID are zero.
+//
+// Things I believe to be true:
+//
+// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
+// CREAT) must bump that node's refcount
+// - don't forget that FORGET can forget multiple references (req->nlookup)
+// - if an op that returns a fuse_entry fails writing the reply to the
+// kernel, you must rollback the refcount to reflect the reference the
+// kernel did not actually acquire
+//
+// This daemon can also derive custom filesystem permissions based on directory
+// structure when requested. These custom permissions support several features:
+//
+// - Apps can access their own files in /Android/data/com.example/ without
+// requiring any additional GIDs.
+// - Separate permissions for protecting directories like Pictures and Music.
+// - Multi-user separation on the same physical device.
+
+#include "fuse.h"
+
+#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
+#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"
+
+/* Supplementary groups to execute with. */
+static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
+
+static bool package_parse_callback(pkg_info *info, void *userdata) {
+    struct fuse_global *global = (struct fuse_global *)userdata;
+    bool res = global->package_to_appid->emplace(info->name, info->uid).second;
+    packagelist_free(info);
+    return res;
+}
+
+static bool read_package_list(struct fuse_global* global) {
+    pthread_mutex_lock(&global->lock);
+
+    global->package_to_appid->clear();
+    bool rc = packagelist_parse(package_parse_callback, global);
+    DLOG(INFO) << "read_package_list: found " << global->package_to_appid->size() << " packages";
+
+    // Regenerate ownership details using newly loaded mapping.
+    derive_permissions_recursive_locked(global->fuse_default, &global->root);
+
+    pthread_mutex_unlock(&global->lock);
+
+    return rc;
+}
+
+static void watch_package_list(struct fuse_global* global) {
+    struct inotify_event *event;
+    char event_buf[512];
+
+    int nfd = inotify_init();
+    if (nfd == -1) {
+        PLOG(ERROR) << "inotify_init failed";
+        return;
+    }
+
+    bool active = false;
+    while (1) {
+        if (!active) {
+            int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
+            if (res == -1) {
+                if (errno == ENOENT || errno == EACCES) {
+                    /* Framework may not have created the file yet, sleep and retry. */
+                    LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
+                    sleep(3);
+                    continue;
+                } else {
+                    PLOG(ERROR) << "inotify_add_watch failed";
+                    return;
+                }
+            }
+
+            /* Watch above will tell us about any future changes, so
+             * read the current state. */
+            if (read_package_list(global) == false) {
+                LOG(ERROR) << "read_package_list failed";
+                return;
+            }
+            active = true;
+        }
+
+        int event_pos = 0;
+        ssize_t res = TEMP_FAILURE_RETRY(read(nfd, event_buf, sizeof(event_buf)));
+        if (res == -1) {
+            PLOG(ERROR) << "failed to read inotify event";
+            return;
+        } else if (static_cast<size_t>(res) < sizeof(*event)) {
+            LOG(ERROR) << "failed to read inotify event: read " << res << " expected "
+                       << sizeof(event_buf);
+            return;
+        }
+
+        while (res >= static_cast<ssize_t>(sizeof(*event))) {
+            int event_size;
+            event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);
+
+            DLOG(INFO) << "inotify event: " << std::hex << event->mask << std::dec;
+            if ((event->mask & IN_IGNORED) == IN_IGNORED) {
+                /* Previously watched file was deleted, probably due to move
+                 * that swapped in new data; re-arm the watch and read. */
+                active = false;
+            }
+
+            event_size = sizeof(*event) + event->len;
+            res -= event_size;
+            event_pos += event_size;
+        }
+    }
+}
+
+static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
+    char opts[256];
+
+    fuse->fd = TEMP_FAILURE_RETRY(open("/dev/fuse", O_RDWR | O_CLOEXEC));
+    if (fuse->fd == -1) {
+        PLOG(ERROR) << "failed to open fuse device";
+        return -1;
+    }
+
+    umount2(fuse->dest_path, MNT_DETACH);
+
+    snprintf(opts, sizeof(opts),
+            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
+            fuse->fd, fuse->global->uid, fuse->global->gid);
+    if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME,
+              opts) == -1) {
+        PLOG(ERROR) << "failed to mount fuse filesystem";
+        return -1;
+    }
+
+    fuse->gid = gid;
+    fuse->mask = mask;
+
+    return 0;
+}
+
+static void drop_privs(uid_t uid, gid_t gid) {
+    ScopedMinijail j(minijail_new());
+    minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
+    minijail_change_gid(j.get(), gid);
+    minijail_change_uid(j.get(), uid);
+    /* minijail_enter() will abort if priv-dropping fails. */
+    minijail_enter(j.get());
+}
+
+static void* start_handler(void* data) {
+    struct fuse_handler* handler = static_cast<fuse_handler*>(data);
+    handle_fuse_requests(handler);
+    return NULL;
+}
+
+static void run(const char* source_path, const char* label, uid_t uid,
+        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
+    struct fuse_global global;
+    struct fuse fuse_default;
+    struct fuse fuse_read;
+    struct fuse fuse_write;
+    struct fuse_handler handler_default;
+    struct fuse_handler handler_read;
+    struct fuse_handler handler_write;
+    pthread_t thread_default;
+    pthread_t thread_read;
+    pthread_t thread_write;
+
+    memset(&global, 0, sizeof(global));
+    memset(&fuse_default, 0, sizeof(fuse_default));
+    memset(&fuse_read, 0, sizeof(fuse_read));
+    memset(&fuse_write, 0, sizeof(fuse_write));
+    memset(&handler_default, 0, sizeof(handler_default));
+    memset(&handler_read, 0, sizeof(handler_read));
+    memset(&handler_write, 0, sizeof(handler_write));
+
+    pthread_mutex_init(&global.lock, NULL);
+    global.package_to_appid = new AppIdMap;
+    global.uid = uid;
+    global.gid = gid;
+    global.multi_user = multi_user;
+    global.next_generation = 0;
+    global.inode_ctr = 1;
+
+    memset(&global.root, 0, sizeof(global.root));
+    global.root.nid = FUSE_ROOT_ID; /* 1 */
+    global.root.refcount = 2;
+    global.root.namelen = strlen(source_path);
+    global.root.name = strdup(source_path);
+    global.root.userid = userid;
+    global.root.uid = AID_ROOT;
+    global.root.under_android = false;
+
+    strcpy(global.source_path, source_path);
+
+    if (multi_user) {
+        global.root.perm = PERM_PRE_ROOT;
+        snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
+    } else {
+        global.root.perm = PERM_ROOT;
+        snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
+    }
+
+    fuse_default.global = &global;
+    fuse_read.global = &global;
+    fuse_write.global = &global;
+
+    global.fuse_default = &fuse_default;
+    global.fuse_read = &fuse_read;
+    global.fuse_write = &fuse_write;
+
+    snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
+    snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
+    snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
+
+    handler_default.fuse = &fuse_default;
+    handler_read.fuse = &fuse_read;
+    handler_write.fuse = &fuse_write;
+
+    handler_default.token = 0;
+    handler_read.token = 1;
+    handler_write.token = 2;
+
+    umask(0);
+
+    if (multi_user) {
+        /* Multi-user storage is fully isolated per user, so "other"
+         * permissions are completely masked off. */
+        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
+                || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
+                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
+            PLOG(FATAL) << "failed to fuse_setup";
+        }
+    } else {
+        /* Physical storage is readable by all users on device, but
+         * the Android directories are masked off to a single user
+         * deep inside attr_from_stat(). */
+        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
+                || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
+                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
+            PLOG(FATAL) << "failed to fuse_setup";
+        }
+    }
+
+    // Will abort if priv-dropping fails.
+    drop_privs(uid, gid);
+
+    if (multi_user) {
+        fs_prepare_dir(global.obb_path, 0775, uid, gid);
+    }
+
+    if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
+            || pthread_create(&thread_read, NULL, start_handler, &handler_read)
+            || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
+        LOG(FATAL) << "failed to pthread_create";
+    }
+
+    watch_package_list(&global);
+    LOG(FATAL) << "terminated prematurely";
+}
+
+static bool sdcardfs_setup(const std::string& source_path, const std::string& dest_path, uid_t fsuid,
+                        gid_t fsgid, bool multi_user, userid_t userid, gid_t gid, mode_t mask) {
+    std::string opts = android::base::StringPrintf("fsuid=%d,fsgid=%d,%smask=%d,userid=%d,gid=%d",
+            fsuid, fsgid, multi_user?"multiuser,":"", mask, userid, gid);
+
+    if (mount(source_path.c_str(), dest_path.c_str(), "sdcardfs",
+              MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) == -1) {
+        PLOG(ERROR) << "failed to mount sdcardfs filesystem";
+        return false;
+    }
+
+    return true;
+}
+
+static bool sdcardfs_setup_bind_remount(const std::string& source_path, const std::string& dest_path,
+                                        gid_t gid, mode_t mask) {
+    std::string opts = android::base::StringPrintf("mask=%d,gid=%d", mask, gid);
+
+    if (mount(source_path.c_str(), dest_path.c_str(), nullptr,
+            MS_BIND, nullptr) != 0) {
+        PLOG(ERROR) << "failed to bind mount sdcardfs filesystem";
+        return false;
+    }
+
+    if (mount(source_path.c_str(), dest_path.c_str(), "none",
+            MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) != 0) {
+        PLOG(ERROR) << "failed to mount sdcardfs filesystem";
+        if (umount2(dest_path.c_str(), MNT_DETACH))
+            PLOG(WARNING) << "Failed to unmount bind";
+        return false;
+    }
+
+    return true;
+}
+
+static void run_sdcardfs(const std::string& source_path, const std::string& label, uid_t uid,
+        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
+    std::string dest_path_default = "/mnt/runtime/default/" + label;
+    std::string dest_path_read = "/mnt/runtime/read/" + label;
+    std::string dest_path_write = "/mnt/runtime/write/" + label;
+
+    umask(0);
+    if (multi_user) {
+        // Multi-user storage is fully isolated per user, so "other"
+        // permissions are completely masked off.
+        if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
+                                                      AID_SDCARD_RW, 0006)
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read, AID_EVERYBODY, 0027)
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write,
+                                                      AID_EVERYBODY, full_write ? 0007 : 0027)) {
+            LOG(FATAL) << "failed to sdcardfs_setup";
+        }
+    } else {
+        // Physical storage is readable by all users on device, but
+        // the Android directories are masked off to a single user
+        // deep inside attr_from_stat().
+        if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
+                                                      AID_SDCARD_RW, 0006)
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read,
+                                                      AID_EVERYBODY, full_write ? 0027 : 0022)
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write,
+                                                      AID_EVERYBODY, full_write ? 0007 : 0022)) {
+            LOG(FATAL) << "failed to sdcardfs_setup";
+        }
+    }
+
+    // Will abort if priv-dropping fails.
+    drop_privs(uid, gid);
+
+    if (multi_user) {
+        std::string obb_path = source_path + "/obb";
+        fs_prepare_dir(obb_path.c_str(), 0775, uid, gid);
+    }
+
+    exit(0);
+}
+
+static bool supports_sdcardfs(void) {
+    std::string filesystems;
+    if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) {
+        PLOG(ERROR) << "Could not read /proc/filesystems";
+        return false;
+    }
+    for (const auto& fs : android::base::Split(filesystems, "\n")) {
+        if (fs.find("sdcardfs") != std::string::npos) return true;
+    }
+    return false;
+}
+
+static bool should_use_sdcardfs(void) {
+    char property[PROPERTY_VALUE_MAX];
+
+    // Allow user to have a strong opinion about state
+    property_get(PROP_SDCARDFS_USER, property, "");
+    if (!strcmp(property, "force_on")) {
+        LOG(WARNING) << "User explicitly enabled sdcardfs";
+        return supports_sdcardfs();
+    } else if (!strcmp(property, "force_off")) {
+        LOG(WARNING) << "User explicitly disabled sdcardfs";
+        return false;
+    }
+
+    // Fall back to device opinion about state
+    if (property_get_bool(PROP_SDCARDFS_DEVICE, true)) {
+        LOG(WARNING) << "Device explicitly enabled sdcardfs";
+        return supports_sdcardfs();
+    } else {
+        LOG(WARNING) << "Device explicitly disabled sdcardfs";
+        return false;
+    }
+}
+
+static int usage() {
+    LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
+               << "    -u: specify UID to run as"
+               << "    -g: specify GID to run as"
+               << "    -U: specify user ID that owns device"
+               << "    -m: source_path is multi-user"
+               << "    -w: runtime write mount has full write access";
+    return 1;
+}
+
+int main(int argc, char **argv) {
+    const char *source_path = NULL;
+    const char *label = NULL;
+    uid_t uid = 0;
+    gid_t gid = 0;
+    userid_t userid = 0;
+    bool multi_user = false;
+    bool full_write = false;
+    int i;
+    struct rlimit rlim;
+    int fs_version;
+
+    int opt;
+    while ((opt = getopt(argc, argv, "u:g:U:mw")) != -1) {
+        switch (opt) {
+            case 'u':
+                uid = strtoul(optarg, NULL, 10);
+                break;
+            case 'g':
+                gid = strtoul(optarg, NULL, 10);
+                break;
+            case 'U':
+                userid = strtoul(optarg, NULL, 10);
+                break;
+            case 'm':
+                multi_user = true;
+                break;
+            case 'w':
+                full_write = true;
+                break;
+            case '?':
+            default:
+                return usage();
+        }
+    }
+
+    for (i = optind; i < argc; i++) {
+        char* arg = argv[i];
+        if (!source_path) {
+            source_path = arg;
+        } else if (!label) {
+            label = arg;
+        } else {
+            LOG(ERROR) << "too many arguments";
+            return usage();
+        }
+    }
+
+    if (!source_path) {
+        LOG(ERROR) << "no source path specified";
+        return usage();
+    }
+    if (!label) {
+        LOG(ERROR) << "no label specified";
+        return usage();
+    }
+    if (!uid || !gid) {
+        LOG(ERROR) << "uid and gid must be nonzero";
+        return usage();
+    }
+
+    rlim.rlim_cur = 8192;
+    rlim.rlim_max = 8192;
+    if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) {
+        PLOG(ERROR) << "setting RLIMIT_NOFILE failed";
+    }
+
+    while ((fs_read_atomic_int("/data/.layout_version", &fs_version) == -1) || (fs_version < 3)) {
+        LOG(ERROR) << "installd fs upgrade not yet complete; waiting...";
+        sleep(1);
+    }
+
+    if (should_use_sdcardfs()) {
+        run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write);
+    } else {
+        run(source_path, label, uid, gid, userid, multi_user, full_write);
+    }
+    return 1;
+}
diff --git a/shell_and_utilities/Android.bp b/shell_and_utilities/Android.bp
new file mode 100644
index 0000000..4f4fc5d
--- /dev/null
+++ b/shell_and_utilities/Android.bp
@@ -0,0 +1,16 @@
+phony {
+    name: "shell_and_utilities",
+    required: [
+        "bzip2",
+        "grep",
+        "gzip",
+        "mkshrc",
+        "mkshrc_vendor",
+        "reboot",
+        "sh",
+        "sh_vendor",
+        "toolbox",
+        "toybox",
+        "toybox_vendor",
+    ],
+}
diff --git a/storaged/Android.mk b/storaged/Android.mk
new file mode 100644
index 0000000..5e6a3c0
--- /dev/null
+++ b/storaged/Android.mk
@@ -0,0 +1,45 @@
+# Copyright 2016 The Android Open Source Project
+
+LOCAL_PATH := $(call my-dir)
+
+LIBSTORAGED_SHARED_LIBRARIES := \
+    libbinder \
+    libbase \
+    libutils \
+    libcutils \
+    liblog \
+    libsysutils \
+    libpackagelistparser \
+    libbatteryservice \
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+    storaged.cpp \
+    storaged_info.cpp \
+    storaged_service.cpp \
+    storaged_utils.cpp \
+    storaged_uid_monitor.cpp \
+    EventLogTags.logtags
+
+LOCAL_MODULE := libstoraged
+LOCAL_CFLAGS := -Werror
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include external/googletest/googletest/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_SHARED_LIBRARIES := $(LIBSTORAGED_SHARED_LIBRARIES)
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := storaged
+LOCAL_INIT_RC := storaged.rc
+LOCAL_SRC_FILES := main.cpp
+# libstoraged is an internal static library, only main.cpp and storaged_test.cpp should be using it
+LOCAL_STATIC_LIBRARIES := libstoraged
+LOCAL_SHARED_LIBRARIES := $(LIBSTORAGED_SHARED_LIBRARIES)
+LOCAL_CFLAGS := -Wall -Werror -Wno-unused-parameter
+LOCAL_C_INCLUDES := external/googletest/googletest/include
+
+include $(BUILD_EXECUTABLE)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/storaged/EventLogTags.logtags b/storaged/EventLogTags.logtags
new file mode 100644
index 0000000..2e25d4a
--- /dev/null
+++ b/storaged/EventLogTags.logtags
@@ -0,0 +1,39 @@
+# The entries in this file map a sparse set of log tag numbers to tag names.
+# This is installed on the device, in /system/etc, and parsed by logcat.
+#
+# Tag numbers are decimal integers, from 0 to 2^31.  (Let's leave the
+# negative values alone for now.)
+#
+# Tag names are one or more ASCII letters and numbers or underscores, i.e.
+# "[A-Z][a-z][0-9]_".  Do not include spaces or punctuation (the former
+# impacts log readability, the latter makes regex searches more annoying).
+#
+# Tag numbers and names are separated by whitespace.  Blank lines and lines
+# starting with '#' are ignored.
+#
+# Optionally, after the tag names can be put a description for the value(s)
+# of the tag. Description are in the format
+#    (<name>|data type[|data unit])
+# Multiple values are separated by commas.
+#
+# The data type is a number from the following values:
+# 1: int
+# 2: long
+# 3: string
+# 4: list
+# 5: float
+#
+# The data unit is a number taken from the following list:
+# 1: Number of objects
+# 2: Number of bytes
+# 3: Number of milliseconds
+# 4: Number of allocations
+# 5: Id
+# 6: Percent
+# Default value for data of type int/long is 2 (bytes).
+#
+# TODO: generate ".java" and ".h" files with integer constants from this file.
+
+2732 storaged_disk_stats (type|3),(start_time|2|3),(end_time|2|3),(read_ios|2|1),(read_merges|2|1),(read_sectors|2|1),(read_ticks|2|3),(write_ios|2|1),(write_merges|2|1),(write_sectors|2|1),(write_ticks|2|3),(o_in_flight|2|1),(io_ticks|2|3),(io_in_queue|2|1)
+
+2733 storaged_emmc_info (mmc_ver|3),(eol|1),(lifetime_a|1),(lifetime_b|1)
\ No newline at end of file
diff --git a/storaged/README.properties b/storaged/README.properties
new file mode 100644
index 0000000..2d8397f
--- /dev/null
+++ b/storaged/README.properties
@@ -0,0 +1,5 @@
+ro.storaged.event.interval    # interval storaged scans for IO stats, in seconds
+ro.storaged.event.perf_check  # check for time spent in event loop, in microseconds
+ro.storaged.disk_stats_pub    # interval storaged publish disk stats, in seconds
+ro.storaged.uid_io.interval   # interval storaged checks Per UID IO usage, in seconds
+ro.storaged.uid_io.threshold  # Per UID IO usage limit, in bytes
diff --git a/storaged/include/storaged.h b/storaged/include/storaged.h
new file mode 100644
index 0000000..514798b
--- /dev/null
+++ b/storaged/include/storaged.h
@@ -0,0 +1,296 @@
+/*
+ * 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 _STORAGED_H_
+#define _STORAGED_H_
+
+#include <semaphore.h>
+#include <stdint.h>
+#include <time.h>
+
+#include <queue>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <batteryservice/IBatteryPropertiesListener.h>
+#include <batteryservice/IBatteryPropertiesRegistrar.h>
+
+#include "storaged_info.h"
+#include "storaged_uid_monitor.h"
+
+using namespace android;
+
+#define FRIEND_TEST(test_case_name, test_name) \
+friend class test_case_name##_##test_name##_Test
+
+/* For debug */
+#ifdef DEBUG
+#define debuginfo(fmt, ...) \
+ do {printf("%s():\t" fmt "\t[%s:%d]\n", __FUNCTION__, ##__VA_ARGS__, __FILE__, __LINE__);} \
+ while(0)
+#else
+#define debuginfo(...)
+#endif
+
+#define ARRAY_SIZE(x)   (sizeof(x) / sizeof((x)[0]))
+
+#define SECTOR_SIZE ( 512 )
+#define SEC_TO_MSEC ( 1000 )
+#define MSEC_TO_USEC ( 1000 )
+#define USEC_TO_NSEC ( 1000 )
+#define SEC_TO_USEC ( 1000000 )
+#define HOUR_TO_SEC ( 3600 )
+#define DAY_TO_SEC ( 3600 * 24 )
+
+// number of attributes diskstats has
+#define DISK_STATS_SIZE ( 11 )
+// maximum size limit of a stats file
+#define DISK_STATS_FILE_MAX_SIZE ( 256 )
+#define DISK_STATS_IO_IN_FLIGHT_IDX ( 8 )
+struct disk_stats {
+    /* It will be extremely unlikely for any of the following entries to overflow.
+     * For read_bytes(which will be greater than any of the following entries), it
+     * will take 27 years to overflow uint64_t at the reading rate of 20GB/s, which
+     * is the peak memory transfer rate for current memory.
+     * The diskstats entries (first 11) need to be at top in this structure _after_
+     * compiler's optimization.
+     */
+    uint64_t read_ios;       // number of read I/Os processed
+    uint64_t read_merges;    // number of read I/Os merged with in-queue I/Os
+    uint64_t read_sectors;   // number of sectors read
+    uint64_t read_ticks;     // total wait time for read requests
+    uint64_t write_ios;      // number of write I/Os processed
+    uint64_t write_merges;   // number of write I/Os merged with in-queue I/Os
+    uint64_t write_sectors;  // number of sectors written
+    uint64_t write_ticks;    // total wait time for write requests
+    uint64_t io_in_flight;   // number of I/Os currently in flight
+    uint64_t io_ticks;       // total time this block device has been active
+    uint64_t io_in_queue;    // total wait time for all requests
+
+    uint64_t start_time;     // monotonic time accounting starts
+    uint64_t end_time;       // monotonic time accounting ends
+    uint32_t counter;        // private counter for accumulate calculations
+    double   io_avg;         // average io_in_flight for accumulate calculations
+};
+
+
+
+struct disk_perf {
+    uint32_t read_perf;         // read speed (kbytes/s)
+    uint32_t read_ios;          // read I/Os per second
+    uint32_t write_perf;        // write speed (kbytes/s)
+    uint32_t write_ios;         // write I/Os per second
+    uint32_t queue;             // I/Os in queue
+};
+
+#define CMD_MAX_LEN ( 64 )
+struct task_info {
+    uint32_t pid;                   // task id
+    uint64_t rchar;                 // characters read
+    uint64_t wchar;                 // characters written
+    uint64_t syscr;                 // read syscalls
+    uint64_t syscw;                 // write syscalls
+    uint64_t read_bytes;            // bytes read (from storage layer)
+    uint64_t write_bytes;           // bytes written (to storage layer)
+    uint64_t cancelled_write_bytes; // cancelled write byte by truncate
+
+    uint64_t starttime;             // start time of task
+
+    char cmd[CMD_MAX_LEN];          // filename of the executable
+};
+
+class lock_t {
+    sem_t* mSem;
+public:
+    lock_t(sem_t* sem) {
+        mSem = sem;
+        sem_wait(mSem);
+    }
+    ~lock_t() {
+        sem_post(mSem);
+    }
+};
+
+class stream_stats {
+private:
+    double mSum;
+    double mSquareSum;
+    uint32_t mCnt;
+public:
+    stream_stats() : mSum(0), mSquareSum(0), mCnt(0) {};
+    ~stream_stats() {};
+    double get_mean() {
+        return mSum / mCnt;
+    }
+    double get_std() {
+        return sqrt(mSquareSum / mCnt - mSum * mSum / (mCnt * mCnt));
+    }
+    void add(uint32_t num) {
+        mSum += (double)num;
+        mSquareSum += (double)num * (double)num;
+        mCnt++;
+    }
+    void evict(uint32_t num) {
+        if (mSum < num || mSquareSum < (double)num * (double)num) return;
+        mSum -= (double)num;
+        mSquareSum -= (double)num * (double)num;
+        mCnt--;
+    }
+};
+
+#define MMC_DISK_STATS_PATH "/sys/block/mmcblk0/stat"
+#define SDA_DISK_STATS_PATH "/sys/block/sda/stat"
+#define EMMC_ECSD_PATH "/d/mmc0/mmc0:0001/ext_csd"
+#define UID_IO_STATS_PATH "/proc/uid_io/stats"
+
+class disk_stats_monitor {
+private:
+    FRIEND_TEST(storaged_test, disk_stats_monitor);
+    const char* DISK_STATS_PATH;
+    struct disk_stats mPrevious;
+    struct disk_stats mAccumulate;
+    bool mStall;
+    std::queue<struct disk_perf> mBuffer;
+    struct {
+        stream_stats read_perf;           // read speed (bytes/s)
+        stream_stats read_ios;            // read I/Os per second
+        stream_stats write_perf;          // write speed (bytes/s)
+        stream_stats write_ios;           // write I/O per second
+        stream_stats queue;               // I/Os in queue
+    } mStats;
+    bool mValid;
+    const uint32_t mWindow;
+    const double mSigma;
+    struct disk_perf mMean;
+    struct disk_perf mStd;
+
+    void update_mean();
+    void update_std();
+    void add(struct disk_perf* perf);
+    void evict(struct disk_perf* perf);
+    bool detect(struct disk_perf* perf);
+
+    void update(struct disk_stats* stats);
+
+public:
+    disk_stats_monitor(uint32_t window_size = 5, double sigma = 1.0) :
+            mStall(false),
+            mValid(false),
+            mWindow(window_size),
+            mSigma(sigma) {
+        memset(&mPrevious, 0, sizeof(mPrevious));
+        memset(&mMean, 0, sizeof(mMean));
+        memset(&mStd, 0, sizeof(mStd));
+
+        if (access(MMC_DISK_STATS_PATH, R_OK) >= 0) {
+            DISK_STATS_PATH = MMC_DISK_STATS_PATH;
+        } else {
+            DISK_STATS_PATH = SDA_DISK_STATS_PATH;
+        }
+    }
+    void update(void);
+};
+
+class disk_stats_publisher {
+private:
+    FRIEND_TEST(storaged_test, disk_stats_publisher);
+    const char* DISK_STATS_PATH;
+    struct disk_stats mAccumulate;
+    struct disk_stats mPrevious;
+public:
+    disk_stats_publisher(void) {
+        memset(&mAccumulate, 0, sizeof(struct disk_stats));
+        memset(&mPrevious, 0, sizeof(struct disk_stats));
+
+        if (access(MMC_DISK_STATS_PATH, R_OK) >= 0) {
+            DISK_STATS_PATH = MMC_DISK_STATS_PATH;
+        } else {
+            DISK_STATS_PATH = SDA_DISK_STATS_PATH;
+        }
+    }
+
+    ~disk_stats_publisher(void) {}
+    void publish(void);
+    void update(void);
+};
+
+// Periodic chores intervals in seconds
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT ( 60 )
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH ( 3600 )
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO ( 3600 )
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO_LIMIT (300)
+
+// UID IO threshold in bytes
+#define DEFAULT_PERIODIC_CHORES_UID_IO_THRESHOLD ( 1024 * 1024 * 1024ULL )
+
+struct storaged_config {
+    int periodic_chores_interval_unit;
+    int periodic_chores_interval_disk_stats_publish;
+    int periodic_chores_interval_uid_io;
+    bool proc_uid_io_available;      // whether uid_io is accessible
+    bool diskstats_available;   // whether diskstats is accessible
+    int event_time_check_usec;  // check how much cputime spent in event loop
+};
+
+class storaged_t : public BnBatteryPropertiesListener,
+                   public IBinder::DeathRecipient {
+private:
+    time_t mTimer;
+    storaged_config mConfig;
+    disk_stats_publisher mDiskStats;
+    disk_stats_monitor mDsm;
+    uid_monitor mUidm;
+    time_t mStarttime;
+    sp<IBatteryPropertiesRegistrar> battery_properties;
+public:
+    storaged_t(void);
+    ~storaged_t() {}
+    void event(void);
+    void event_checked(void);
+    void pause(void) {
+        sleep(mConfig.periodic_chores_interval_unit);
+    }
+
+    time_t get_starttime(void) {
+        return mStarttime;
+    }
+
+    std::unordered_map<uint32_t, struct uid_info> get_uids(void) {
+        return mUidm.get_uid_io_stats();
+    }
+    std::map<uint64_t, struct uid_records> get_uid_records(
+            double hours, uint64_t threshold, bool force_report) {
+        return mUidm.dump(hours, threshold, force_report);
+    }
+    void update_uid_io_interval(int interval) {
+        if (interval >= DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO_LIMIT) {
+            mConfig.periodic_chores_interval_uid_io = interval;
+        }
+    }
+
+    void init_battery_service();
+    virtual void batteryPropertiesChanged(struct BatteryProperties props);
+    void binderDied(const wp<IBinder>& who);
+};
+
+// Eventlog tag
+// The content must match the definition in EventLogTags.logtags
+#define EVENTLOGTAG_DISKSTATS ( 2732 )
+#define EVENTLOGTAG_EMMCINFO ( 2733 )
+#define EVENTLOGTAG_UID_IO_ALERT ( 2734 )
+
+#endif /* _STORAGED_H_ */
diff --git a/storaged/include/storaged_info.h b/storaged/include/storaged_info.h
new file mode 100644
index 0000000..913c814
--- /dev/null
+++ b/storaged/include/storaged_info.h
@@ -0,0 +1,65 @@
+/*
+ * 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 _STORAGED_INFO_H_
+#define _STORAGED_INFO_H_
+
+#include <string.h>
+
+#define FRIEND_TEST(test_case_name, test_name) \
+friend class test_case_name##_##test_name##_Test
+
+using namespace std;
+
+class storage_info_t {
+protected:
+    FRIEND_TEST(storaged_test, storage_info_t);
+    uint16_t eol;                   // pre-eol (end of life) information
+    uint16_t lifetime_a;            // device life time estimation (type A)
+    uint16_t lifetime_b;            // device life time estimation (type B)
+    string version;                 // version string
+    void publish();
+public:
+    storage_info_t() : eol(0), lifetime_a(0), lifetime_b(0) {}
+    virtual ~storage_info_t() {}
+    virtual bool report() = 0;
+};
+
+class emmc_info_t : public storage_info_t {
+private:
+    const string emmc_sysfs = "/sys/bus/mmc/devices/mmc0:0001/";
+    const string emmc_debugfs = "/d/mmc0/mmc0:0001/ext_csd";
+    const char* emmc_ver_str[9] = {
+        "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0", "5.1"
+    };
+public:
+    virtual ~emmc_info_t() {}
+    bool report();
+    bool report_sysfs();
+    bool report_debugfs();
+};
+
+class ufs_info_t : public storage_info_t {
+private:
+    const string health_file = "/sys/devices/soc/624000.ufshc/health";
+public:
+    virtual ~ufs_info_t() {}
+    bool report();
+};
+
+void report_storage_health();
+
+#endif /* _STORAGED_INFO_H_ */
diff --git a/storaged/include/storaged_service.h b/storaged/include/storaged_service.h
new file mode 100644
index 0000000..a8ddf4c
--- /dev/null
+++ b/storaged/include/storaged_service.h
@@ -0,0 +1,60 @@
+/*
+ * 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 _STORAGED_SERVICE_H_
+#define _STORAGED_SERVICE_H_
+
+#include <vector>
+
+#include <binder/IInterface.h>
+#include <binder/IBinder.h>
+
+#include "storaged.h"
+
+using namespace android;
+
+// Interface
+class IStoraged : public IInterface {
+public:
+    enum {
+        DUMPUIDS  = IBinder::FIRST_CALL_TRANSACTION,
+    };
+    // Request the service to run the test function
+    virtual std::vector<struct uid_info> dump_uids(const char* option) = 0;
+
+    DECLARE_META_INTERFACE(Storaged);
+};
+
+// Client
+class BpStoraged : public BpInterface<IStoraged> {
+public:
+    BpStoraged(const sp<IBinder>& impl) : BpInterface<IStoraged>(impl){};
+    virtual std::vector<struct uid_info> dump_uids(const char* option);
+};
+
+// Server
+class BnStoraged : public BnInterface<IStoraged> {
+    virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0);
+};
+
+class Storaged : public BnStoraged {
+    virtual std::vector<struct uid_info> dump_uids(const char* option);
+    virtual status_t dump(int fd, const Vector<String16>& args);
+};
+
+sp<IStoraged> get_storaged_service();
+
+#endif /* _STORAGED_SERVICE_H_ */
\ No newline at end of file
diff --git a/storaged/include/storaged_uid_monitor.h b/storaged/include/storaged_uid_monitor.h
new file mode 100644
index 0000000..901a872
--- /dev/null
+++ b/storaged/include/storaged_uid_monitor.h
@@ -0,0 +1,110 @@
+/*
+ * 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 _STORAGED_UID_MONITOR_H_
+#define _STORAGED_UID_MONITOR_H_
+
+#include <stdint.h>
+
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+enum uid_stat_t {
+    FOREGROUND = 0,
+    BACKGROUND = 1,
+    UID_STATS = 2
+};
+
+enum charger_stat_t {
+    CHARGER_OFF = 0,
+    CHARGER_ON = 1,
+    CHARGER_STATS = 2
+};
+
+enum io_type_t {
+    READ = 0,
+    WRITE = 1,
+    IO_TYPES = 2
+};
+
+struct uid_io_stats {
+    uint64_t rchar;                 // characters read
+    uint64_t wchar;                 // characters written
+    uint64_t read_bytes;            // bytes read (from storage layer)
+    uint64_t write_bytes;           // bytes written (to storage layer)
+    uint64_t fsync;                 // number of fsync syscalls
+};
+
+struct uid_info {
+    uint32_t uid;                   // user id
+    std::string name;               // package name
+    struct uid_io_stats io[UID_STATS];    // [0]:foreground [1]:background
+};
+
+struct uid_io_usage {
+    uint64_t bytes[IO_TYPES][UID_STATS][CHARGER_STATS];
+};
+
+struct uid_record {
+    std::string name;
+    struct uid_io_usage ios;
+};
+
+struct uid_records {
+    uint64_t start_ts;
+    std::vector<struct uid_record> entries;
+};
+
+class uid_monitor {
+private:
+    // last dump from /proc/uid_io/stats, uid -> uid_info
+    std::unordered_map<uint32_t, struct uid_info> last_uid_io_stats;
+    // current io usage for next report, app name -> uid_io_usage
+    std::unordered_map<std::string, struct uid_io_usage> curr_io_stats;
+    // io usage records, end timestamp -> {start timestamp, vector of records}
+    std::map<uint64_t, struct uid_records> records;
+    // charger ON/OFF
+    charger_stat_t charger_stat;
+    // protects curr_io_stats, last_uid_io_stats, records and charger_stat
+    sem_t um_lock;
+    // start time for IO records
+    uint64_t start_ts;
+
+    // reads from /proc/uid_io/stats
+    std::unordered_map<uint32_t, struct uid_info> get_uid_io_stats_locked();
+    // flushes curr_io_stats to records
+    void add_records_locked(uint64_t curr_ts);
+    // updates curr_io_stats and set last_uid_io_stats
+    void update_curr_io_stats_locked();
+
+public:
+    uid_monitor();
+    ~uid_monitor();
+    // called by storaged main thread
+    void init(charger_stat_t stat);
+    // called by storaged -u
+    std::unordered_map<uint32_t, struct uid_info> get_uid_io_stats();
+    // called by dumpsys
+    std::map<uint64_t, struct uid_records> dump(
+        double hours, uint64_t threshold, bool force_report);
+    // called by battery properties listener
+    void set_charger_state(charger_stat_t stat);
+    // called by storaged periodic_chore or dump with force_report
+    void report();
+};
+
+#endif /* _STORAGED_UID_MONITOR_H_ */
diff --git a/storaged/include/storaged_utils.h b/storaged/include/storaged_utils.h
new file mode 100644
index 0000000..2161c40
--- /dev/null
+++ b/storaged/include/storaged_utils.h
@@ -0,0 +1,44 @@
+/*
+ * 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 _STORAGED_UTILS_H_
+#define _STORAGED_UTILS_H_
+
+#include <stdint.h>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "storaged.h"
+
+// Diskstats
+bool parse_disk_stats(const char* disk_stats_path, struct disk_stats* stats);
+struct disk_perf get_disk_perf(struct disk_stats* stats);
+struct disk_stats get_inc_disk_stats(struct disk_stats* prev, struct disk_stats* curr);
+void add_disk_stats(struct disk_stats* src, struct disk_stats* dst);
+bool parse_emmc_ecsd(int ext_csd_fd, struct emmc_info* info);
+
+// UID I/O
+void sort_running_uids_info(std::vector<struct uid_info> &uids);
+
+// Logging
+void log_console_running_uids_info(std::vector<struct uid_info> uids);
+
+void log_debug_disk_perf(struct disk_perf* perf, const char* type);
+
+void log_event_disk_stats(struct disk_stats* stats, const char* type);
+void log_event_emmc_info(struct emmc_info* info_);
+#endif /* _STORAGED_UTILS_H_ */
diff --git a/storaged/main.cpp b/storaged/main.cpp
new file mode 100644
index 0000000..4d1e430
--- /dev/null
+++ b/storaged/main.cpp
@@ -0,0 +1,153 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storaged"
+#define KLOG_LEVEL 6
+
+#include <fcntl.h>
+#include <getopt.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <vector>
+
+#include <android-base/macros.h>
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include <cutils/android_get_control_file.h>
+#include <cutils/sched_policy.h>
+#include <private/android_filesystem_config.h>
+
+#include <storaged.h>
+#include <storaged_service.h>
+#include <storaged_utils.h>
+
+sp<storaged_t> storaged;
+
+// Function of storaged's main thread
+void* storaged_main(void* /* unused */) {
+    storaged = new storaged_t();
+
+    storaged->init_battery_service();
+
+    LOG_TO(SYSTEM, INFO) << "storaged: Start";
+
+    for (;;) {
+        storaged->event_checked();
+        storaged->pause();
+    }
+    return NULL;
+}
+
+static void help_message(void) {
+    printf("usage: storaged [OPTION]\n");
+    printf("  -u    --uid                   Dump uid I/O usage to stdout\n");
+    printf("  -s    --start                 Start storaged (default)\n");
+    fflush(stdout);
+}
+
+int main(int argc, char** argv) {
+    int flag_main_service = 0;
+    int flag_dump_uid = 0;
+    int opt;
+
+    for (;;) {
+        int opt_idx = 0;
+        static struct option long_options[] = {
+            {"start",       no_argument,        0, 's'},
+            {"kill",        no_argument,        0, 'k'},
+            {"uid",         no_argument,        0, 'u'},
+            {"help",        no_argument,        0, 'h'}
+        };
+        opt = getopt_long(argc, argv, ":skdhu0", long_options, &opt_idx);
+        if (opt == -1) {
+            break;
+        }
+
+        switch (opt) {
+        case 's':
+            flag_main_service = 1;
+            break;
+        case 'u':
+            flag_dump_uid = 1;
+            break;
+        case 'h':
+            help_message();
+            return 0;
+        case '?':
+        default:
+            fprintf(stderr, "no supported option\n");
+            help_message();
+            return -1;
+        }
+    }
+
+    if (argc == 1) {
+        flag_main_service = 1;
+    }
+
+    if (flag_main_service && flag_dump_uid) {
+        fprintf(stderr, "Invalid arguments. Option \"start\" and \"dump\" cannot be used together.\n");
+        help_message();
+        return -1;
+    }
+
+    if (flag_main_service) { // start main thread
+        report_storage_health();
+        // Start the main thread of storaged
+        pthread_t storaged_main_thread;
+        errno = pthread_create(&storaged_main_thread, NULL, storaged_main, NULL);
+        if (errno != 0) {
+            PLOG_TO(SYSTEM, ERROR) << "Failed to create main thread";
+            return -1;
+        }
+
+        defaultServiceManager()->addService(String16("storaged"), new Storaged());
+        android::ProcessState::self()->startThreadPool();
+        IPCThreadState::self()->joinThreadPool();
+        pthread_join(storaged_main_thread, NULL);
+
+        return 0;
+    }
+
+    if (flag_dump_uid) {
+        sp<IStoraged> storaged_service = get_storaged_service();
+        if (storaged_service == NULL) {
+            fprintf(stderr, "Cannot find storaged service.\nMaybe run storaged --start first?\n");
+            return -1;
+        }
+        std::vector<struct uid_info> res = storaged_service->dump_uids(NULL);
+
+        if (res.size() == 0) {
+            fprintf(stderr, "UID I/O is not readable in this version of kernel.\n");
+            return 0;
+        }
+
+        sort_running_uids_info(res);
+        log_console_running_uids_info(res);
+
+        return 0;
+    }
+
+    return 0;
+}
diff --git a/storaged/storaged.cpp b/storaged/storaged.cpp
new file mode 100644
index 0000000..54d429c
--- /dev/null
+++ b/storaged/storaged.cpp
@@ -0,0 +1,276 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storaged"
+
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <android-base/logging.h>
+#include <batteryservice/BatteryServiceConstants.h>
+#include <batteryservice/IBatteryPropertiesRegistrar.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <cutils/properties.h>
+#include <log/log.h>
+
+#include <storaged.h>
+#include <storaged_utils.h>
+
+/* disk_stats_publisher */
+void disk_stats_publisher::publish(void) {
+    // Logging
+    struct disk_perf perf = get_disk_perf(&mAccumulate);
+    log_debug_disk_perf(&perf, "regular");
+    log_event_disk_stats(&mAccumulate, "regular");
+    // Reset global structures
+    memset(&mAccumulate, 0, sizeof(struct disk_stats));
+}
+
+void disk_stats_publisher::update(void) {
+    struct disk_stats curr;
+    if (parse_disk_stats(DISK_STATS_PATH, &curr)) {
+        struct disk_stats inc = get_inc_disk_stats(&mPrevious, &curr);
+        add_disk_stats(&inc, &mAccumulate);
+#ifdef DEBUG
+//            log_kernel_disk_stats(&mPrevious, "prev stats");
+//            log_kernel_disk_stats(&curr, "curr stats");
+//            log_kernel_disk_stats(&inc, "inc stats");
+//            log_kernel_disk_stats(&mAccumulate, "accumulated stats");
+#endif
+        mPrevious = curr;
+    }
+}
+
+/* disk_stats_monitor */
+void disk_stats_monitor::update_mean() {
+    CHECK(mValid);
+    mMean.read_perf = (uint32_t)mStats.read_perf.get_mean();
+    mMean.read_ios = (uint32_t)mStats.read_ios.get_mean();
+    mMean.write_perf = (uint32_t)mStats.write_perf.get_mean();
+    mMean.write_ios = (uint32_t)mStats.write_ios.get_mean();
+    mMean.queue = (uint32_t)mStats.queue.get_mean();
+}
+
+void disk_stats_monitor::update_std() {
+    CHECK(mValid);
+    mStd.read_perf = (uint32_t)mStats.read_perf.get_std();
+    mStd.read_ios = (uint32_t)mStats.read_ios.get_std();
+    mStd.write_perf = (uint32_t)mStats.write_perf.get_std();
+    mStd.write_ios = (uint32_t)mStats.write_ios.get_std();
+    mStd.queue = (uint32_t)mStats.queue.get_std();
+}
+
+void disk_stats_monitor::add(struct disk_perf* perf) {
+    mStats.read_perf.add(perf->read_perf);
+    mStats.read_ios.add(perf->read_ios);
+    mStats.write_perf.add(perf->write_perf);
+    mStats.write_ios.add(perf->write_ios);
+    mStats.queue.add(perf->queue);
+}
+
+void disk_stats_monitor::evict(struct disk_perf* perf) {
+    mStats.read_perf.evict(perf->read_perf);
+    mStats.read_ios.evict(perf->read_ios);
+    mStats.write_perf.evict(perf->write_perf);
+    mStats.write_ios.evict(perf->write_ios);
+    mStats.queue.evict(perf->queue);
+}
+
+bool disk_stats_monitor::detect(struct disk_perf* perf) {
+    return ((double)perf->queue >= (double)mMean.queue + mSigma * (double)mStd.queue) &&
+            ((double)perf->read_perf < (double)mMean.read_perf - mSigma * (double)mStd.read_perf) &&
+            ((double)perf->write_perf < (double)mMean.write_perf - mSigma * (double)mStd.write_perf);
+}
+
+void disk_stats_monitor::update(struct disk_stats* stats) {
+    struct disk_stats inc = get_inc_disk_stats(&mPrevious, stats);
+    struct disk_perf perf = get_disk_perf(&inc);
+    // Update internal data structures
+    if (LIKELY(mValid)) {
+        CHECK_EQ(mBuffer.size(), mWindow);
+
+        if (UNLIKELY(detect(&perf))) {
+            mStall = true;
+            add_disk_stats(&inc, &mAccumulate);
+            log_debug_disk_perf(&mMean, "stalled_mean");
+            log_debug_disk_perf(&mStd, "stalled_std");
+        } else {
+            if (mStall) {
+                struct disk_perf acc_perf = get_disk_perf(&mAccumulate);
+                log_debug_disk_perf(&acc_perf, "stalled");
+                log_event_disk_stats(&mAccumulate, "stalled");
+                mStall = false;
+                memset(&mAccumulate, 0, sizeof(mAccumulate));
+            }
+        }
+
+        evict(&mBuffer.front());
+        mBuffer.pop();
+        add(&perf);
+        mBuffer.push(perf);
+
+        update_mean();
+        update_std();
+
+    } else { /* mValid == false */
+        CHECK_LT(mBuffer.size(), mWindow);
+        add(&perf);
+        mBuffer.push(perf);
+        if (mBuffer.size() == mWindow) {
+            mValid = true;
+            update_mean();
+            update_std();
+        }
+    }
+
+    mPrevious = *stats;
+}
+
+void disk_stats_monitor::update(void) {
+    struct disk_stats curr;
+    if (LIKELY(parse_disk_stats(DISK_STATS_PATH, &curr))) {
+        update(&curr);
+    }
+}
+
+static sp<IBatteryPropertiesRegistrar> get_battery_properties_service() {
+    sp<IServiceManager> sm = defaultServiceManager();
+    if (sm == NULL) return NULL;
+
+    sp<IBinder> binder = sm->getService(String16("batteryproperties"));
+    if (binder == NULL) return NULL;
+
+    sp<IBatteryPropertiesRegistrar> battery_properties =
+        interface_cast<IBatteryPropertiesRegistrar>(binder);
+
+    return battery_properties;
+}
+
+static inline charger_stat_t is_charger_on(int64_t prop) {
+    return (prop == BATTERY_STATUS_CHARGING || prop == BATTERY_STATUS_FULL) ?
+        CHARGER_ON : CHARGER_OFF;
+}
+
+void storaged_t::batteryPropertiesChanged(struct BatteryProperties props) {
+    mUidm.set_charger_state(is_charger_on(props.batteryStatus));
+}
+
+void storaged_t::init_battery_service() {
+    if (!mConfig.proc_uid_io_available)
+        return;
+
+    battery_properties = get_battery_properties_service();
+    if (battery_properties == NULL) {
+        LOG_TO(SYSTEM, WARNING) << "failed to find batteryproperties service";
+        return;
+    }
+
+    struct BatteryProperty val;
+    battery_properties->getProperty(BATTERY_PROP_BATTERY_STATUS, &val);
+    mUidm.init(is_charger_on(val.valueInt64));
+
+    // register listener after init uid_monitor
+    battery_properties->registerListener(this);
+    IInterface::asBinder(battery_properties)->linkToDeath(this);
+}
+
+void storaged_t::binderDied(const wp<IBinder>& who) {
+    if (battery_properties != NULL &&
+        IInterface::asBinder(battery_properties) == who) {
+        LOG_TO(SYSTEM, ERROR) << "batteryproperties service died, exiting";
+        IPCThreadState::self()->stopProcess();
+        exit(1);
+    } else {
+        LOG_TO(SYSTEM, ERROR) << "unknown service died";
+    }
+}
+
+/* storaged_t */
+storaged_t::storaged_t(void) {
+    if (access(MMC_DISK_STATS_PATH, R_OK) < 0 && access(SDA_DISK_STATS_PATH, R_OK) < 0) {
+        mConfig.diskstats_available = false;
+    } else {
+        mConfig.diskstats_available = true;
+    }
+
+    mConfig.proc_uid_io_available = (access(UID_IO_STATS_PATH, R_OK) == 0);
+
+    mConfig.periodic_chores_interval_unit =
+        property_get_int32("ro.storaged.event.interval", DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT);
+
+    mConfig.event_time_check_usec =
+        property_get_int32("ro.storaged.event.perf_check", 0);
+
+    mConfig.periodic_chores_interval_disk_stats_publish =
+        property_get_int32("ro.storaged.disk_stats_pub", DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH);
+
+    mConfig.periodic_chores_interval_uid_io =
+        property_get_int32("ro.storaged.uid_io.interval", DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO);
+
+    mStarttime = time(NULL);
+}
+
+void storaged_t::event(void) {
+    if (mConfig.diskstats_available) {
+        mDiskStats.update();
+        mDsm.update();
+        if (mTimer && (mTimer % mConfig.periodic_chores_interval_disk_stats_publish) == 0) {
+            mDiskStats.publish();
+        }
+    }
+
+    if (mConfig.proc_uid_io_available && mTimer &&
+            (mTimer % mConfig.periodic_chores_interval_uid_io) == 0) {
+         mUidm.report();
+    }
+
+    mTimer += mConfig.periodic_chores_interval_unit;
+}
+
+void storaged_t::event_checked(void) {
+    struct timespec start_ts, end_ts;
+    bool check_time = true;
+
+    if (mConfig.event_time_check_usec &&
+        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_ts) < 0) {
+        check_time = false;
+        static time_t state_a;
+        IF_ALOG_RATELIMIT_LOCAL(300, &state_a) {
+            PLOG_TO(SYSTEM, ERROR) << "clock_gettime() failed";
+        }
+    }
+
+    event();
+
+    if (mConfig.event_time_check_usec && check_time) {
+        if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_ts) < 0) {
+            static time_t state_b;
+            IF_ALOG_RATELIMIT_LOCAL(300, &state_b) {
+                PLOG_TO(SYSTEM, ERROR) << "clock_gettime() failed";
+            }
+            return;
+        }
+        int64_t cost = (end_ts.tv_sec - start_ts.tv_sec) * SEC_TO_USEC +
+                       (end_ts.tv_nsec - start_ts.tv_nsec) / USEC_TO_NSEC;
+        if (cost > mConfig.event_time_check_usec) {
+            LOG_TO(SYSTEM, ERROR)
+                << "event loop spent " << cost << " usec, threshold "
+                << mConfig.event_time_check_usec << " usec";
+        }
+    }
+}
diff --git a/storaged/storaged.rc b/storaged/storaged.rc
new file mode 100644
index 0000000..a24c7fb
--- /dev/null
+++ b/storaged/storaged.rc
@@ -0,0 +1,7 @@
+service storaged /system/bin/storaged
+    class main
+    priority 10
+    file /d/mmc0/mmc0:0001/ext_csd r
+    writepid /dev/cpuset/system-background/tasks
+    user root
+    group package_info
\ No newline at end of file
diff --git a/storaged/storaged_info.cpp b/storaged/storaged_info.cpp
new file mode 100644
index 0000000..434bd74
--- /dev/null
+++ b/storaged/storaged_info.cpp
@@ -0,0 +1,184 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storaged"
+
+#include <stdio.h>
+#include <string.h>
+
+#include <android-base/file.h>
+#include <android-base/parseint.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <log/log_event_list.h>
+
+#include "storaged.h"
+
+using namespace std;
+using namespace android::base;
+
+void report_storage_health()
+{
+    emmc_info_t mmc;
+    ufs_info_t ufs;
+
+    mmc.report();
+    ufs.report();
+}
+
+void storage_info_t::publish()
+{
+    android_log_event_list(EVENTLOGTAG_EMMCINFO)
+        << version << eol << lifetime_a << lifetime_b
+        << LOG_ID_EVENTS;
+}
+
+bool emmc_info_t::report()
+{
+    if (!report_sysfs() && !report_debugfs())
+        return false;
+
+    publish();
+    return true;
+}
+
+bool emmc_info_t::report_sysfs()
+{
+    string buffer;
+    uint16_t rev = 0;
+
+    if (!ReadFileToString(emmc_sysfs + "rev", &buffer)) {
+        return false;
+    }
+
+    if (sscanf(buffer.c_str(), "0x%hx", &rev) < 1 ||
+        rev < 7 || rev > ARRAY_SIZE(emmc_ver_str)) {
+        return false;
+    }
+
+    version = "emmc ";
+    version += emmc_ver_str[rev];
+
+    if (!ReadFileToString(emmc_sysfs + "pre_eol_info", &buffer)) {
+        return false;
+    }
+
+    if (sscanf(buffer.c_str(), "%hx", &eol) < 1 || eol == 0) {
+        return false;
+    }
+
+    if (!ReadFileToString(emmc_sysfs + "life_time", &buffer)) {
+        return false;
+    }
+
+    if (sscanf(buffer.c_str(), "0x%hx 0x%hx", &lifetime_a, &lifetime_b) < 2 ||
+        (lifetime_a == 0 && lifetime_b == 0)) {
+        return false;
+    }
+
+    return true;
+}
+
+const size_t EXT_CSD_FILE_MIN_SIZE = 1024;
+/* 2 characters in string for each byte */
+const size_t EXT_CSD_REV_IDX = 192 * 2;
+const size_t EXT_PRE_EOL_INFO_IDX = 267 * 2;
+const size_t EXT_DEVICE_LIFE_TIME_EST_A_IDX = 268 * 2;
+const size_t EXT_DEVICE_LIFE_TIME_EST_B_IDX = 269 * 2;
+
+bool emmc_info_t::report_debugfs()
+{
+    string buffer;
+    uint16_t rev = 0;
+
+    if (!ReadFileToString(emmc_debugfs, &buffer) ||
+        buffer.length() < (size_t)EXT_CSD_FILE_MIN_SIZE) {
+        return false;
+    }
+
+    string str = buffer.substr(EXT_CSD_REV_IDX, 2);
+    if (!ParseUint(str, &rev) ||
+        rev < 7 || rev > ARRAY_SIZE(emmc_ver_str)) {
+        return false;
+    }
+
+    version = "emmc ";
+    version += emmc_ver_str[rev];
+
+    str = buffer.substr(EXT_PRE_EOL_INFO_IDX, 2);
+    if (!ParseUint(str, &eol)) {
+        return false;
+    }
+
+    str = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_A_IDX, 2);
+    if (!ParseUint(str, &lifetime_a)) {
+        return false;
+    }
+
+    str = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_B_IDX, 2);
+    if (!ParseUint(str, &lifetime_b)) {
+        return false;
+    }
+
+    return true;
+}
+
+bool ufs_info_t::report()
+{
+    string buffer;
+    if (!ReadFileToString(health_file, &buffer)) {
+        return false;
+    }
+
+    vector<string> lines = Split(buffer, "\n");
+    if (lines.empty()) {
+        return false;
+    }
+
+    char rev[8];
+    if (sscanf(lines[0].c_str(), "ufs version: 0x%7s\n", rev) < 1) {
+        return false;
+    }
+
+    version = "ufs " + string(rev);
+
+    for (size_t i = 1; i < lines.size(); i++) {
+        char token[32];
+        uint16_t val;
+        int ret;
+        if ((ret = sscanf(lines[i].c_str(),
+                   "Health Descriptor[Byte offset 0x%*d]: %31s = 0x%hx",
+                   token, &val)) < 2) {
+            continue;
+        }
+
+        if (string(token) == "bPreEOLInfo") {
+            eol = val;
+        } else if (string(token) == "bDeviceLifeTimeEstA") {
+            lifetime_a = val;
+        } else if (string(token) == "bDeviceLifeTimeEstB") {
+            lifetime_b = val;
+        }
+    }
+
+    if (eol == 0 || (lifetime_a == 0 && lifetime_b == 0)) {
+        return false;
+    }
+
+    publish();
+    return true;
+}
+
diff --git a/storaged/storaged_service.cpp b/storaged/storaged_service.cpp
new file mode 100644
index 0000000..b1d3bfd
--- /dev/null
+++ b/storaged/storaged_service.cpp
@@ -0,0 +1,169 @@
+/*
+ * 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 <vector>
+
+#include <android-base/parseint.h>
+#include <android-base/parsedouble.h>
+#include <binder/IBinder.h>
+#include <binder/IInterface.h>
+
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/PermissionCache.h>
+#include <private/android_filesystem_config.h>
+
+#include <storaged.h>
+#include <storaged_service.h>
+
+using namespace android::base;
+
+extern sp<storaged_t> storaged;
+
+std::vector<struct uid_info> BpStoraged::dump_uids(const char* /*option*/) {
+    Parcel data, reply;
+    data.writeInterfaceToken(IStoraged::getInterfaceDescriptor());
+
+    remote()->transact(DUMPUIDS, data, &reply);
+
+    uint32_t res_size = reply.readInt32();
+    std::vector<struct uid_info> res(res_size);
+    for (auto&& uid : res) {
+        uid.uid = reply.readInt32();
+        uid.name = reply.readCString();
+        reply.read(&uid.io, sizeof(uid.io));
+    }
+    return res;
+}
+IMPLEMENT_META_INTERFACE(Storaged, "Storaged");
+
+status_t BnStoraged::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
+    switch(code) {
+        case DUMPUIDS: {
+                if (!data.checkInterface(this))
+                    return BAD_TYPE;
+                std::vector<struct uid_info> res = dump_uids(NULL);
+                reply->writeInt32(res.size());
+                for (auto uid : res) {
+                    reply->writeInt32(uid.uid);
+                    reply->writeCString(uid.name.c_str());
+                    reply->write(&uid.io, sizeof(uid.io));
+                }
+                return NO_ERROR;
+            }
+            break;
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+std::vector<struct uid_info> Storaged::dump_uids(const char* /* option */) {
+    std::vector<struct uid_info> uids_v;
+    std::unordered_map<uint32_t, struct uid_info> uids_m = storaged->get_uids();
+
+    for (const auto& it : uids_m) {
+        uids_v.push_back(it.second);
+    }
+    return uids_v;
+}
+
+status_t Storaged::dump(int fd, const Vector<String16>& args) {
+    IPCThreadState* self = IPCThreadState::self();
+    const int pid = self->getCallingPid();
+    const int uid = self->getCallingUid();
+    if ((uid != AID_SHELL) &&
+        !PermissionCache::checkPermission(
+                String16("android.permission.DUMP"), pid, uid)) {
+        return PERMISSION_DENIED;
+    }
+
+    double hours = 0;
+    int time_window = 0;
+    uint64_t threshold = 0;
+    bool force_report = false;
+    for (size_t i = 0; i < args.size(); i++) {
+        const auto& arg = args[i];
+        if (arg == String16("--hours")) {
+            if (++i >= args.size())
+                break;
+            if(!ParseDouble(String8(args[i]).c_str(), &hours))
+                return BAD_VALUE;
+            continue;
+        }
+        if (arg == String16("--time_window")) {
+            if (++i >= args.size())
+                break;
+            if(!ParseInt(String8(args[i]).c_str(), &time_window))
+                return BAD_VALUE;
+            continue;
+        }
+        if (arg == String16("--threshold")) {
+            if (++i >= args.size())
+                break;
+            if(!ParseUint(String8(args[i]).c_str(), &threshold))
+                return BAD_VALUE;
+            continue;
+        }
+        if (arg == String16("--force")) {
+            force_report = true;
+            continue;
+        }
+    }
+
+    uint64_t last_ts = 0;
+    const std::map<uint64_t, struct uid_records>& records =
+                storaged->get_uid_records(hours, threshold, force_report);
+    for (const auto& it : records) {
+        if (last_ts != it.second.start_ts) {
+            dprintf(fd, "%llu", (unsigned long long)it.second.start_ts);
+        }
+        dprintf(fd, ",%llu\n", (unsigned long long)it.first);
+        last_ts = it.first;
+
+        for (const auto& record : it.second.entries) {
+            dprintf(fd, "%s %ju %ju %ju %ju %ju %ju %ju %ju\n",
+                record.name.c_str(),
+                record.ios.bytes[READ][FOREGROUND][CHARGER_OFF],
+                record.ios.bytes[WRITE][FOREGROUND][CHARGER_OFF],
+                record.ios.bytes[READ][BACKGROUND][CHARGER_OFF],
+                record.ios.bytes[WRITE][BACKGROUND][CHARGER_OFF],
+                record.ios.bytes[READ][FOREGROUND][CHARGER_ON],
+                record.ios.bytes[WRITE][FOREGROUND][CHARGER_ON],
+                record.ios.bytes[READ][BACKGROUND][CHARGER_ON],
+                record.ios.bytes[WRITE][BACKGROUND][CHARGER_ON]);
+        }
+    }
+
+    if (time_window) {
+        storaged->update_uid_io_interval(time_window);
+    }
+
+    return NO_ERROR;
+}
+
+sp<IStoraged> get_storaged_service() {
+    sp<IServiceManager> sm = defaultServiceManager();
+    if (sm == NULL) return NULL;
+
+    sp<IBinder> binder = sm->getService(String16("storaged"));
+    if (binder == NULL) return NULL;
+
+    sp<IStoraged> storaged = interface_cast<IStoraged>(binder);
+
+    return storaged;
+}
diff --git a/storaged/storaged_uid_monitor.cpp b/storaged/storaged_uid_monitor.cpp
new file mode 100644
index 0000000..5bb98e1
--- /dev/null
+++ b/storaged/storaged_uid_monitor.cpp
@@ -0,0 +1,278 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storaged"
+
+#include <stdint.h>
+#include <time.h>
+
+#include <string>
+#include <unordered_map>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+#include <android-base/stringprintf.h>
+#include <log/log_event_list.h>
+#include <packagelistparser/packagelistparser.h>
+
+#include "storaged.h"
+#include "storaged_uid_monitor.h"
+
+using namespace android;
+using namespace android::base;
+
+static bool packagelist_parse_cb(pkg_info* info, void* userdata)
+{
+    std::unordered_map<uint32_t, struct uid_info>* uids =
+        reinterpret_cast<std::unordered_map<uint32_t, struct uid_info>*>(userdata);
+
+    if (uids->find(info->uid) != uids->end()) {
+        (*uids)[info->uid].name = info->name;
+    }
+
+    packagelist_free(info);
+    return true;
+}
+
+std::unordered_map<uint32_t, struct uid_info> uid_monitor::get_uid_io_stats()
+{
+    std::unique_ptr<lock_t> lock(new lock_t(&um_lock));
+    return get_uid_io_stats_locked();
+};
+
+std::unordered_map<uint32_t, struct uid_info> uid_monitor::get_uid_io_stats_locked()
+{
+    std::unordered_map<uint32_t, struct uid_info> uid_io_stats;
+    std::string buffer;
+    if (!ReadFileToString(UID_IO_STATS_PATH, &buffer)) {
+        PLOG_TO(SYSTEM, ERROR) << UID_IO_STATS_PATH << ": ReadFileToString failed";
+        return uid_io_stats;
+    }
+
+    std::vector<std::string> io_stats = Split(buffer, "\n");
+    struct uid_info u;
+    bool refresh_uid = false;
+
+    for (uint32_t i = 0; i < io_stats.size(); i++) {
+        if (io_stats[i].empty()) {
+            continue;
+        }
+        std::vector<std::string> fields = Split(io_stats[i], " ");
+        if (fields.size() < 11 ||
+            !ParseUint(fields[0],  &u.uid) ||
+            !ParseUint(fields[1],  &u.io[FOREGROUND].rchar) ||
+            !ParseUint(fields[2],  &u.io[FOREGROUND].wchar) ||
+            !ParseUint(fields[3],  &u.io[FOREGROUND].read_bytes) ||
+            !ParseUint(fields[4],  &u.io[FOREGROUND].write_bytes) ||
+            !ParseUint(fields[5],  &u.io[BACKGROUND].rchar) ||
+            !ParseUint(fields[6],  &u.io[BACKGROUND].wchar) ||
+            !ParseUint(fields[7],  &u.io[BACKGROUND].read_bytes) ||
+            !ParseUint(fields[8],  &u.io[BACKGROUND].write_bytes) ||
+            !ParseUint(fields[9],  &u.io[FOREGROUND].fsync) ||
+            !ParseUint(fields[10], &u.io[BACKGROUND].fsync)) {
+            LOG_TO(SYSTEM, WARNING) << "Invalid I/O stats: \""
+                                    << io_stats[i] << "\"";
+            continue;
+        }
+
+        if (last_uid_io_stats.find(u.uid) == last_uid_io_stats.end()) {
+            refresh_uid = true;
+            u.name = std::to_string(u.uid);
+        } else {
+            u.name = last_uid_io_stats[u.uid].name;
+        }
+        uid_io_stats[u.uid] = u;
+    }
+
+    if (refresh_uid) {
+        packagelist_parse(packagelist_parse_cb, &uid_io_stats);
+    }
+
+    return uid_io_stats;
+}
+
+static const int MAX_UID_RECORDS_SIZE = 1000 * 48; // 1000 uids in 48 hours
+
+static inline int records_size(
+    const std::map<uint64_t, struct uid_records>& curr_records)
+{
+    int count = 0;
+    for (auto const& it : curr_records) {
+        count += it.second.entries.size();
+    }
+    return count;
+}
+
+static struct uid_io_usage zero_io_usage;
+
+void uid_monitor::add_records_locked(uint64_t curr_ts)
+{
+    // remove records more than 5 days old
+    if (curr_ts > 5 * DAY_TO_SEC) {
+        auto it = records.lower_bound(curr_ts - 5 * DAY_TO_SEC);
+        records.erase(records.begin(), it);
+    }
+
+    struct uid_records new_records;
+    for (const auto& p : curr_io_stats) {
+        struct uid_record record = {};
+        record.name = p.first;
+        record.ios = p.second;
+        if (memcmp(&record.ios, &zero_io_usage, sizeof(struct uid_io_usage))) {
+            new_records.entries.push_back(record);
+        }
+    }
+
+    curr_io_stats.clear();
+    new_records.start_ts = start_ts;
+    start_ts = curr_ts;
+
+    if (new_records.entries.empty())
+      return;
+
+    // make some room for new records
+    int overflow = records_size(records) +
+        new_records.entries.size() - MAX_UID_RECORDS_SIZE;
+    while (overflow > 0 && records.size() > 0) {
+        auto del_it = records.begin();
+        overflow -= del_it->second.entries.size();
+        records.erase(records.begin());
+    }
+
+    records[curr_ts] = new_records;
+}
+
+std::map<uint64_t, struct uid_records> uid_monitor::dump(
+    double hours, uint64_t threshold, bool force_report)
+{
+    if (force_report) {
+        report();
+    }
+
+    std::unique_ptr<lock_t> lock(new lock_t(&um_lock));
+
+    std::map<uint64_t, struct uid_records> dump_records;
+    uint64_t first_ts = 0;
+
+    if (hours != 0) {
+        first_ts = time(NULL) - hours * HOUR_TO_SEC;
+    }
+
+    for (auto it = records.lower_bound(first_ts); it != records.end(); ++it) {
+        const std::vector<struct uid_record>& recs = it->second.entries;
+        struct uid_records filtered;
+
+        for (const auto& rec : recs) {
+            if (rec.ios.bytes[READ][FOREGROUND][CHARGER_ON] +
+                rec.ios.bytes[READ][FOREGROUND][CHARGER_OFF] +
+                rec.ios.bytes[READ][BACKGROUND][CHARGER_ON] +
+                rec.ios.bytes[READ][BACKGROUND][CHARGER_OFF] +
+                rec.ios.bytes[WRITE][FOREGROUND][CHARGER_ON] +
+                rec.ios.bytes[WRITE][FOREGROUND][CHARGER_OFF] +
+                rec.ios.bytes[WRITE][BACKGROUND][CHARGER_ON] +
+                rec.ios.bytes[WRITE][BACKGROUND][CHARGER_OFF] > threshold) {
+                filtered.entries.push_back(rec);
+            }
+        }
+
+        if (filtered.entries.empty())
+            continue;
+
+        filtered.start_ts = it->second.start_ts;
+        dump_records.insert(
+            std::pair<uint64_t, struct uid_records>(it->first, filtered));
+    }
+
+    return dump_records;
+}
+
+void uid_monitor::update_curr_io_stats_locked()
+{
+    std::unordered_map<uint32_t, struct uid_info> uid_io_stats =
+        get_uid_io_stats_locked();
+    if (uid_io_stats.empty()) {
+        return;
+    }
+
+    for (const auto& it : uid_io_stats) {
+        const struct uid_info& uid = it.second;
+
+        if (curr_io_stats.find(uid.name) == curr_io_stats.end()) {
+          curr_io_stats[uid.name] = {};
+        }
+
+        struct uid_io_usage& usage = curr_io_stats[uid.name];
+        int64_t fg_rd_delta = uid.io[FOREGROUND].read_bytes -
+            last_uid_io_stats[uid.uid].io[FOREGROUND].read_bytes;
+        int64_t bg_rd_delta = uid.io[BACKGROUND].read_bytes -
+            last_uid_io_stats[uid.uid].io[BACKGROUND].read_bytes;
+        int64_t fg_wr_delta = uid.io[FOREGROUND].write_bytes -
+            last_uid_io_stats[uid.uid].io[FOREGROUND].write_bytes;
+        int64_t bg_wr_delta = uid.io[BACKGROUND].write_bytes -
+            last_uid_io_stats[uid.uid].io[BACKGROUND].write_bytes;
+
+        usage.bytes[READ][FOREGROUND][charger_stat] +=
+            (fg_rd_delta < 0) ? uid.io[FOREGROUND].read_bytes : fg_rd_delta;
+        usage.bytes[READ][BACKGROUND][charger_stat] +=
+            (bg_rd_delta < 0) ? uid.io[BACKGROUND].read_bytes : bg_rd_delta;
+        usage.bytes[WRITE][FOREGROUND][charger_stat] +=
+            (fg_wr_delta < 0) ? uid.io[FOREGROUND].write_bytes : fg_wr_delta;
+        usage.bytes[WRITE][BACKGROUND][charger_stat] +=
+            (bg_wr_delta < 0) ? uid.io[BACKGROUND].write_bytes : bg_wr_delta;
+    }
+
+    last_uid_io_stats = uid_io_stats;
+}
+
+void uid_monitor::report()
+{
+    std::unique_ptr<lock_t> lock(new lock_t(&um_lock));
+
+    update_curr_io_stats_locked();
+    add_records_locked(time(NULL));
+}
+
+void uid_monitor::set_charger_state(charger_stat_t stat)
+{
+    std::unique_ptr<lock_t> lock(new lock_t(&um_lock));
+
+    if (charger_stat == stat) {
+        return;
+    }
+
+    update_curr_io_stats_locked();
+    charger_stat = stat;
+}
+
+void uid_monitor::init(charger_stat_t stat)
+{
+    charger_stat = stat;
+    start_ts = time(NULL);
+    last_uid_io_stats = get_uid_io_stats();
+}
+
+uid_monitor::uid_monitor()
+{
+    sem_init(&um_lock, 0, 1);
+}
+
+uid_monitor::~uid_monitor()
+{
+    sem_destroy(&um_lock);
+}
diff --git a/storaged/storaged_utils.cpp b/storaged/storaged_utils.cpp
new file mode 100644
index 0000000..74b7436
--- /dev/null
+++ b/storaged/storaged_utils.cpp
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storaged"
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/time.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <iomanip>
+#include <sstream>
+#include <string>
+#include <unordered_map>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <log/log_event_list.h>
+
+#include <storaged.h>
+#include <storaged_utils.h>
+
+bool parse_disk_stats(const char* disk_stats_path, struct disk_stats* stats) {
+    // Get time
+    struct timespec ts;
+    // Use monotonic to exclude suspend time so that we measure IO bytes/sec
+    // when system is running.
+    int ret = clock_gettime(CLOCK_MONOTONIC, &ts);
+    if (ret < 0) {
+        PLOG_TO(SYSTEM, ERROR) << "clock_gettime() failed";
+        return false;
+    }
+
+    std::string buffer;
+    if (!android::base::ReadFileToString(disk_stats_path, &buffer)) {
+        PLOG_TO(SYSTEM, ERROR) << disk_stats_path << ": ReadFileToString failed.";
+        return false;
+    }
+
+    // Regular diskstats entries
+    std::stringstream ss(buffer);
+    for (uint i = 0; i < DISK_STATS_SIZE; ++i) {
+        ss >> *((uint64_t*)stats + i);
+    }
+    // Other entries
+    stats->start_time = 0;
+    stats->end_time = (uint64_t)ts.tv_sec * SEC_TO_MSEC +
+        ts.tv_nsec / (MSEC_TO_USEC * USEC_TO_NSEC);
+    stats->counter = 1;
+    stats->io_avg = (double)stats->io_in_flight;
+    return true;
+}
+
+struct disk_perf get_disk_perf(struct disk_stats* stats) {
+    struct disk_perf perf;
+    memset(&perf, 0, sizeof(struct disk_perf));  // initialize
+
+    if (stats->io_ticks) {
+        if (stats->read_ticks) {
+            unsigned long long divisor = stats->read_ticks * stats->io_ticks;
+            perf.read_perf = ((unsigned long long)SECTOR_SIZE *
+                                        stats->read_sectors *
+                                        stats->io_in_queue +
+                                        (divisor >> 1)) /
+                                            divisor;
+            perf.read_ios = ((unsigned long long)SEC_TO_MSEC *
+                                        stats->read_ios *
+                                        stats->io_in_queue +
+                                        (divisor >> 1)) /
+                                            divisor;
+        }
+        if (stats->write_ticks) {
+            unsigned long long divisor = stats->write_ticks * stats->io_ticks;
+                        perf.write_perf = ((unsigned long long)SECTOR_SIZE *
+                                                    stats->write_sectors *
+                                                    stats->io_in_queue +
+                                                    (divisor >> 1)) /
+                                                        divisor;
+                        perf.write_ios = ((unsigned long long)SEC_TO_MSEC *
+                                                    stats->write_ios *
+                                                    stats->io_in_queue +
+                                                    (divisor >> 1)) /
+                                                        divisor;
+        }
+        perf.queue = (stats->io_in_queue + (stats->io_ticks >> 1)) /
+                                stats->io_ticks;
+    }
+    return perf;
+}
+
+struct disk_stats get_inc_disk_stats(struct disk_stats* prev, struct disk_stats* curr) {
+    struct disk_stats inc;
+    for (uint i = 0; i < DISK_STATS_SIZE; ++i) {
+        if (i == DISK_STATS_IO_IN_FLIGHT_IDX) {
+            continue;
+        }
+
+        *((uint64_t*)&inc + i) =
+                *((uint64_t*)curr + i) - *((uint64_t*)prev + i);
+    }
+    // io_in_flight is exception
+    inc.io_in_flight = curr->io_in_flight;
+
+    inc.start_time = prev->end_time;
+    inc.end_time = curr->end_time;
+    inc.io_avg = curr->io_avg;
+    inc.counter = 1;
+
+    return inc;
+}
+
+// Add src to dst
+void add_disk_stats(struct disk_stats* src, struct disk_stats* dst) {
+    if (dst->end_time != 0 && dst->end_time != src->start_time) {
+        LOG_TO(SYSTEM, WARNING) << "Two dis-continuous periods of diskstats"
+            << " are added. dst end with " << dst->end_time
+            << ", src start with " << src->start_time;
+    }
+
+    for (uint i = 0; i < DISK_STATS_SIZE; ++i) {
+        if (i == DISK_STATS_IO_IN_FLIGHT_IDX) {
+            continue;
+        }
+
+        *((uint64_t*)dst + i) += *((uint64_t*)src + i);
+    }
+
+    dst->io_in_flight = src->io_in_flight;
+    if (dst->counter + src->counter) {
+        dst->io_avg = ((dst->io_avg * dst->counter) + (src->io_avg * src->counter)) /
+                        (dst->counter + src->counter);
+    }
+    dst->counter += src->counter;
+    dst->end_time = src->end_time;
+    if (dst->start_time == 0) {
+        dst->start_time = src->start_time;
+    }
+}
+
+static bool cmp_uid_info(struct uid_info l, struct uid_info r) {
+    // Compare background I/O first.
+    for (int i = UID_STATS - 1; i >= 0; i--) {
+        uint64_t l_bytes = l.io[i].read_bytes + l.io[i].write_bytes;
+        uint64_t r_bytes = r.io[i].read_bytes + r.io[i].write_bytes;
+        uint64_t l_chars = l.io[i].rchar + l.io[i].wchar;
+        uint64_t r_chars = r.io[i].rchar + r.io[i].wchar;
+
+        if (l_bytes != r_bytes) {
+            return l_bytes > r_bytes;
+        }
+        if (l_chars != r_chars) {
+            return l_chars > r_chars;
+        }
+    }
+
+    return l.name < r.name;
+}
+
+void sort_running_uids_info(std::vector<struct uid_info> &uids) {
+    std::sort(uids.begin(), uids.end(), cmp_uid_info);
+}
+
+// Logging functions
+void log_console_running_uids_info(std::vector<struct uid_info> uids) {
+    printf("name/uid fg_rchar fg_wchar fg_rbytes fg_wbytes "
+           "bg_rchar bg_wchar bg_rbytes bg_wbytes fg_fsync bg_fsync\n");
+
+    for (const auto& uid : uids) {
+        printf("%s %ju %ju %ju %ju %ju %ju %ju %ju %ju %ju\n", uid.name.c_str(),
+            uid.io[0].rchar, uid.io[0].wchar, uid.io[0].read_bytes, uid.io[0].write_bytes,
+            uid.io[1].rchar, uid.io[1].wchar, uid.io[1].read_bytes, uid.io[1].write_bytes,
+            uid.io[0].fsync, uid.io[1].fsync);
+    }
+    fflush(stdout);
+}
+
+#if DEBUG
+void log_debug_disk_perf(struct disk_perf* perf, const char* type) {
+    // skip if the input structure are all zeros
+    if (perf == NULL) return;
+    struct disk_perf zero_cmp;
+    memset(&zero_cmp, 0, sizeof(zero_cmp));
+    if (memcmp(&zero_cmp, perf, sizeof(struct disk_perf)) == 0) return;
+
+    LOG_TO(SYSTEM, INFO) << "perf(ios) " << type
+              << " rd:" << perf->read_perf << "KB/s(" << perf->read_ios << "/s)"
+              << " wr:" << perf->write_perf << "KB/s(" << perf->write_ios << "/s)"
+              << " q:" << perf->queue;
+}
+#else
+void log_debug_disk_perf(struct disk_perf* /* perf */, const char* /* type */) {}
+#endif
+
+void log_event_disk_stats(struct disk_stats* stats, const char* type) {
+    // skip if the input structure are all zeros
+    if (stats == NULL) return;
+    struct disk_stats zero_cmp;
+    memset(&zero_cmp, 0, sizeof(zero_cmp));
+    // skip event logging diskstats when it is zero increment (all first 11 entries are zero)
+    if (memcmp(&zero_cmp, stats, sizeof(uint64_t) * DISK_STATS_SIZE) == 0) return;
+
+    android_log_event_list(EVENTLOGTAG_DISKSTATS)
+        << type << stats->start_time << stats->end_time
+        << stats->read_ios << stats->read_merges
+        << stats->read_sectors << stats->read_ticks
+        << stats->write_ios << stats->write_merges
+        << stats->write_sectors << stats->write_ticks
+        << (uint64_t)stats->io_avg << stats->io_ticks << stats->io_in_queue
+        << LOG_ID_EVENTS;
+}
+
diff --git a/storaged/tests/Android.mk b/storaged/tests/Android.mk
new file mode 100644
index 0000000..26d04b1
--- /dev/null
+++ b/storaged/tests/Android.mk
@@ -0,0 +1,45 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+test_module_prefix := storaged-
+test_tags := tests
+
+# -----------------------------------------------------------------------------
+# Unit tests.
+# -----------------------------------------------------------------------------
+
+test_c_flags := \
+    -fstack-protector-all \
+    -g \
+    -Wall -Wextra \
+    -Werror \
+    -fno-builtin \
+
+test_src_files := \
+    storaged_test.cpp \
+
+# Build tests for the logger. Run with:
+#   adb shell /data/nativetest/storaged-unit-tests/storaged-unit-tests
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(test_module_prefix)unit-tests
+LOCAL_MODULE_TAGS := $(test_tags)
+LOCAL_CFLAGS += $(test_c_flags)
+LOCAL_STATIC_LIBRARIES := libstoraged
+LOCAL_SHARED_LIBRARIES := libbase libcutils liblog libpackagelistparser
+LOCAL_SRC_FILES := $(test_src_files)
+include $(BUILD_NATIVE_TEST)
diff --git a/storaged/tests/storaged_test.cpp b/storaged/tests/storaged_test.cpp
new file mode 100644
index 0000000..b103ac1
--- /dev/null
+++ b/storaged/tests/storaged_test.cpp
@@ -0,0 +1,351 @@
+/*
+ * 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 <deque>
+#include <fcntl.h>
+#include <random>
+#include <string.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <gtest/gtest.h>
+
+#include <storaged.h>               // data structures
+#include <storaged_utils.h>         // functions to test
+
+#define MMC_DISK_STATS_PATH "/sys/block/mmcblk0/stat"
+#define SDA_DISK_STATS_PATH "/sys/block/sda/stat"
+
+static void pause(uint32_t sec) {
+    const char* path = "/cache/test";
+    int fd = open(path, O_WRONLY | O_CREAT, 0600);
+    ASSERT_LT(-1, fd);
+    char buffer[2048];
+    memset(buffer, 1, sizeof(buffer));
+    int loop_size = 100;
+    for (int i = 0; i < loop_size; ++i) {
+        ASSERT_EQ(2048, write(fd, buffer, sizeof(buffer)));
+    }
+    fsync(fd);
+    close(fd);
+
+    fd = open(path, O_RDONLY);
+    ASSERT_LT(-1, fd);
+    for (int i = 0; i < loop_size; ++i) {
+        ASSERT_EQ(2048, read(fd, buffer, sizeof(buffer)));
+    }
+    close(fd);
+
+    sleep(sec);
+}
+
+// the return values of the tested functions should be the expected ones
+const char* DISK_STATS_PATH;
+TEST(storaged_test, retvals) {
+    struct disk_stats stats;
+    memset(&stats, 0, sizeof(struct disk_stats));
+
+    if (access(MMC_DISK_STATS_PATH, R_OK) >= 0) {
+        DISK_STATS_PATH = MMC_DISK_STATS_PATH;
+    } else if (access(SDA_DISK_STATS_PATH, R_OK) >= 0) {
+        DISK_STATS_PATH = SDA_DISK_STATS_PATH;
+    } else {
+        return;
+    }
+
+    EXPECT_TRUE(parse_disk_stats(DISK_STATS_PATH, &stats));
+
+    struct disk_stats old_stats;
+    memset(&old_stats, 0, sizeof(struct disk_stats));
+    old_stats = stats;
+
+    const char wrong_path[] = "/this/is/wrong";
+    EXPECT_FALSE(parse_disk_stats(wrong_path, &stats));
+
+    // reading a wrong path should not damage the output structure
+    EXPECT_EQ(0, memcmp(&stats, &old_stats, sizeof(disk_stats)));
+}
+
+TEST(storaged_test, disk_stats) {
+    struct disk_stats stats;
+    memset(&stats, 0, sizeof(struct disk_stats));
+
+    ASSERT_TRUE(parse_disk_stats(DISK_STATS_PATH, &stats));
+
+    // every entry of stats (except io_in_flight) should all be greater than 0
+    for (uint i = 0; i < DISK_STATS_SIZE; ++i) {
+        if (i == 8) continue; // skip io_in_flight which can be 0
+        EXPECT_LT((uint64_t)0, *((uint64_t*)&stats + i));
+    }
+
+    // accumulation of the increments should be the same with the overall increment
+    struct disk_stats base, tmp, curr, acc, inc[5];
+    memset(&base, 0, sizeof(struct disk_stats));
+    memset(&tmp, 0, sizeof(struct disk_stats));
+    memset(&acc, 0, sizeof(struct disk_stats));
+
+    for (uint i = 0; i < 5; ++i) {
+        ASSERT_TRUE(parse_disk_stats(DISK_STATS_PATH, &curr));
+        if (i == 0) {
+            base = curr;
+            tmp = curr;
+            sleep(5);
+            continue;
+        }
+        inc[i] = get_inc_disk_stats(&tmp, &curr);
+        add_disk_stats(&inc[i], &acc);
+        tmp = curr;
+        pause(5);
+    }
+    struct disk_stats overall_inc;
+    memset(&overall_inc, 0, sizeof(disk_stats));
+    overall_inc= get_inc_disk_stats(&base, &curr);
+
+    for (uint i = 0; i < DISK_STATS_SIZE; ++i) {
+        if (i == 8) continue; // skip io_in_flight which can be 0
+        EXPECT_EQ(*((uint64_t*)&overall_inc + i), *((uint64_t*)&acc + i));
+    }
+}
+
+static double mean(std::deque<uint32_t> nums) {
+    double sum = 0.0;
+    for (uint32_t i : nums) {
+    sum += i;
+    }
+    return sum / nums.size();
+}
+
+static double standard_deviation(std::deque<uint32_t> nums) {
+    double sum = 0.0;
+    double avg = mean(nums);
+    for (uint32_t i : nums) {
+    sum += ((double)i - avg) * ((double)i - avg);
+    }
+    return sqrt(sum / nums.size());
+}
+
+TEST(storaged_test, stream_stats) {
+    // 100 random numbers
+    std::vector<uint32_t> data = {8147,9058,1270,9134,6324,975,2785,5469,9575,9649,1576,9706,9572,4854,8003,1419,4218,9157,7922,9595,6557,357,8491,9340,6787,7577,7431,3922,6555,1712,7060,318,2769,462,971,8235,6948,3171,9502,344,4387,3816,7655,7952,1869,4898,4456,6463,7094,7547,2760,6797,6551,1626,1190,4984,9597,3404,5853,2238,7513,2551,5060,6991,8909,9593,5472,1386,1493,2575,8407,2543,8143,2435,9293,3500,1966,2511,6160,4733,3517,8308,5853,5497,9172,2858,7572,7537,3804,5678,759,540,5308,7792,9340,1299,5688,4694,119,3371};
+    std::deque<uint32_t> test_data;
+    stream_stats sstats;
+    for (uint32_t i : data) {
+        test_data.push_back(i);
+        sstats.add(i);
+
+        EXPECT_EQ((int)standard_deviation(test_data), (int)sstats.get_std());
+        EXPECT_EQ((int)mean(test_data), (int)sstats.get_mean());
+    }
+
+    for (uint32_t i : data) {
+        test_data.pop_front();
+        sstats.evict(i);
+
+        EXPECT_EQ((int)standard_deviation(test_data), (int)sstats.get_std());
+        EXPECT_EQ((int)mean(test_data), (int)sstats.get_mean());
+    }
+
+    // some real data
+    std::vector<uint32_t> another_data = {113875,81620,103145,28327,86855,207414,96526,52567,28553,250311};
+    test_data.clear();
+    uint32_t window_size = 2;
+    uint32_t idx;
+    stream_stats sstats1;
+    for (idx = 0; idx < window_size; ++idx) {
+        test_data.push_back(another_data[idx]);
+        sstats1.add(another_data[idx]);
+    }
+    EXPECT_EQ((int)standard_deviation(test_data), (int)sstats1.get_std());
+    EXPECT_EQ((int)mean(test_data), (int)sstats1.get_mean());
+    for (;idx < another_data.size(); ++idx) {
+        test_data.pop_front();
+        sstats1.evict(another_data[idx - window_size]);
+        test_data.push_back(another_data[idx]);
+        sstats1.add(another_data[idx]);
+        EXPECT_EQ((int)standard_deviation(test_data), (int)sstats1.get_std());
+        EXPECT_EQ((int)mean(test_data), (int)sstats1.get_mean());
+    }
+}
+
+static struct disk_perf disk_perf_multiply(struct disk_perf perf, double mul) {
+    struct disk_perf retval;
+    retval.read_perf = (double)perf.read_perf * mul;
+    retval.read_ios = (double)perf.read_ios * mul;
+    retval.write_perf = (double)perf.write_perf * mul;
+    retval.write_ios = (double)perf.write_ios * mul;
+    retval.queue = (double)perf.queue * mul;
+
+    return retval;
+}
+
+static struct disk_stats disk_stats_add(struct disk_stats stats1, struct disk_stats stats2) {
+    struct disk_stats retval;
+    retval.read_ios = stats1.read_ios + stats2.read_ios;
+    retval.read_merges = stats1.read_merges + stats2.read_merges;
+    retval.read_sectors = stats1.read_sectors + stats2.read_sectors;
+    retval.read_ticks = stats1.read_ticks + stats2.read_ticks;
+    retval.write_ios = stats1.write_ios + stats2.write_ios;
+    retval.write_merges = stats1.write_merges + stats2.write_merges;
+    retval.write_sectors = stats1.write_sectors + stats2.write_sectors;
+    retval.write_ticks = stats1.write_ticks + stats2.write_ticks;
+    retval.io_in_flight = stats1.io_in_flight + stats2.io_in_flight;
+    retval.io_ticks = stats1.io_ticks + stats2.io_ticks;
+    retval.io_in_queue = stats1.io_in_queue + stats2.io_in_queue;
+    retval.end_time = stats1.end_time + stats2.end_time;
+
+    return retval;
+}
+
+TEST(storaged_test, disk_stats_monitor) {
+    // asserting that there is one file for diskstats
+    ASSERT_TRUE(access(MMC_DISK_STATS_PATH, R_OK) >= 0 || access(SDA_DISK_STATS_PATH, R_OK) >= 0);
+    // testing if detect() will return the right value
+    disk_stats_monitor dsm_detect;
+    // feed monitor with constant perf data for io perf baseline
+    // using constant perf is reasonable since the functionality of stream_stats
+    // has already been tested
+    struct disk_perf norm_perf = {
+        .read_perf = 10 * 1024,
+        .read_ios = 50,
+        .write_perf = 5 * 1024,
+        .write_ios = 25,
+        .queue = 5
+    };
+
+    std::random_device rd;
+    std::mt19937 gen(rd());
+    std::uniform_real_distribution<> rand(0.8, 1.2);
+
+    for (uint i = 0; i < dsm_detect.mWindow; ++i) {
+        struct disk_perf perf = disk_perf_multiply(norm_perf, rand(gen));
+
+        dsm_detect.add(&perf);
+        dsm_detect.mBuffer.push(perf);
+        EXPECT_EQ(dsm_detect.mBuffer.size(), (uint64_t)i + 1);
+    }
+
+    dsm_detect.mValid = true;
+    dsm_detect.update_mean();
+    dsm_detect.update_std();
+
+    for (double i = 0; i < 2 * dsm_detect.mSigma; i += 0.5) {
+        struct disk_perf test_perf;
+        struct disk_perf test_mean = dsm_detect.mMean;
+        struct disk_perf test_std = dsm_detect.mStd;
+
+        test_perf.read_perf = (double)test_mean.read_perf - i * test_std.read_perf;
+        test_perf.read_ios = (double)test_mean.read_ios - i * test_std.read_ios;
+        test_perf.write_perf = (double)test_mean.write_perf - i * test_std.write_perf;
+        test_perf.write_ios = (double)test_mean.write_ios - i * test_std.write_ios;
+        test_perf.queue = (double)test_mean.queue + i * test_std.queue;
+
+        EXPECT_EQ((i > dsm_detect.mSigma), dsm_detect.detect(&test_perf));
+    }
+
+    // testing if stalled disk_stats can be correctly accumulated in the monitor
+    disk_stats_monitor dsm_acc;
+    struct disk_stats norm_inc = {
+        .read_ios = 200,
+        .read_merges = 0,
+        .read_sectors = 200,
+        .read_ticks = 200,
+        .write_ios = 100,
+        .write_merges = 0,
+        .write_sectors = 100,
+        .write_ticks = 100,
+        .io_in_flight = 0,
+        .io_ticks = 600,
+        .io_in_queue = 300,
+        .start_time = 0,
+        .end_time = 100,
+        .counter = 0,
+        .io_avg = 0
+    };
+
+    struct disk_stats stall_inc = {
+        .read_ios = 200,
+        .read_merges = 0,
+        .read_sectors = 20,
+        .read_ticks = 200,
+        .write_ios = 100,
+        .write_merges = 0,
+        .write_sectors = 10,
+        .write_ticks = 100,
+        .io_in_flight = 0,
+        .io_ticks = 600,
+        .io_in_queue = 1200,
+        .start_time = 0,
+        .end_time = 100,
+        .counter = 0,
+        .io_avg = 0
+    };
+
+    struct disk_stats stats_base;
+    memset(&stats_base, 0, sizeof(stats_base));
+
+    int loop_size = 100;
+    for (int i = 0; i < loop_size; ++i) {
+        stats_base = disk_stats_add(stats_base, norm_inc);
+        dsm_acc.update(&stats_base);
+        EXPECT_EQ(dsm_acc.mValid, (uint32_t)(i + 1) >= dsm_acc.mWindow);
+        EXPECT_FALSE(dsm_acc.mStall);
+    }
+
+    stats_base = disk_stats_add(stats_base, stall_inc);
+    dsm_acc.update(&stats_base);
+    EXPECT_TRUE(dsm_acc.mValid);
+    EXPECT_TRUE(dsm_acc.mStall);
+
+    for (int i = 0; i < 10; ++i) {
+        stats_base = disk_stats_add(stats_base, norm_inc);
+        dsm_acc.update(&stats_base);
+        EXPECT_TRUE(dsm_acc.mValid);
+        EXPECT_FALSE(dsm_acc.mStall);
+    }
+}
+
+static void expect_increasing(struct disk_stats stats1, struct disk_stats stats2) {
+    EXPECT_LE(stats1.read_ios, stats2.read_ios);
+    EXPECT_LE(stats1.read_merges, stats2.read_merges);
+    EXPECT_LE(stats1.read_sectors, stats2.read_sectors);
+    EXPECT_LE(stats1.read_ticks, stats2.read_ticks);
+
+    EXPECT_LE(stats1.write_ios, stats2.write_ios);
+    EXPECT_LE(stats1.write_merges, stats2.write_merges);
+    EXPECT_LE(stats1.write_sectors, stats2.write_sectors);
+    EXPECT_LE(stats1.write_ticks, stats2.write_ticks);
+
+    EXPECT_LE(stats1.io_ticks, stats2.io_ticks);
+    EXPECT_LE(stats1.io_in_queue, stats2.io_in_queue);
+}
+
+#define TEST_LOOPS 20
+TEST(storaged_test, disk_stats_publisher) {
+    // asserting that there is one file for diskstats
+    ASSERT_TRUE(access(MMC_DISK_STATS_PATH, R_OK) >= 0 || access(SDA_DISK_STATS_PATH, R_OK) >= 0);
+    disk_stats_publisher dsp;
+    struct disk_stats prev;
+    memset(&prev, 0, sizeof(prev));
+
+    for (int i = 0; i < TEST_LOOPS; ++i) {
+        dsp.update();
+        expect_increasing(prev, dsp.mPrevious);
+        prev = dsp.mPrevious;
+        pause(10);
+    }
+}
+
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 9ade759..d6ead1a 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -3,7 +3,6 @@
 
 common_cflags := \
     -Werror -Wno-unused-parameter -Wno-unused-const-variable \
-    -I$(LOCAL_PATH)/upstream-netbsd/include/ \
     -include bsd-compatibility.h \
 
 
@@ -21,6 +20,7 @@
     upstream-netbsd/lib/libc/string/swab.c \
     upstream-netbsd/lib/libutil/raise_default_signal.c
 LOCAL_CFLAGS += $(common_cflags) -Dmain=dd_main -DNO_CONV
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_MODULE := libtoolbox_dd
 include $(BUILD_STATIC_LIBRARY)
 
@@ -32,31 +32,19 @@
 
 OUR_TOOLS := \
     getevent \
-    iftop \
-    ioctl \
-    log \
-    nandread \
     newfs_msdos \
-    ps \
-    prlimit \
-    sendevent \
-    start \
-    stop \
-    top \
 
 ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
 
 LOCAL_SRC_FILES := \
-    start_stop.cpp \
     toolbox.c \
     $(patsubst %,%.c,$(OUR_TOOLS)) \
 
 LOCAL_CFLAGS += $(common_cflags)
-LOCAL_CONLYFLAGS += -std=gnu99
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
-    libselinux \
 
 LOCAL_WHOLE_STATIC_LIBRARIES := $(patsubst %,libtoolbox_%,$(BSD_TOOLS))
 
@@ -72,7 +60,7 @@
 $(LOCAL_PATH)/toolbox.c: $(intermediates)/tools.h
 
 TOOLS_H := $(intermediates)/tools.h
-$(TOOLS_H): PRIVATE_TOOLS := $(ALL_TOOLS)
+$(TOOLS_H): PRIVATE_TOOLS := toolbox $(ALL_TOOLS)
 $(TOOLS_H): PRIVATE_CUSTOM_TOOL = echo "/* file generated automatically */" > $@ ; for t in $(PRIVATE_TOOLS) ; do echo "TOOL($$t)" >> $@ ; done
 $(TOOLS_H): $(LOCAL_PATH)/Android.mk
 $(TOOLS_H):
@@ -80,7 +68,7 @@
 
 $(LOCAL_PATH)/getevent.c: $(intermediates)/input.h-labels.h
 
-UAPI_INPUT_EVENT_CODES_H := bionic/libc/kernel/uapi/linux/input-event-codes.h
+UAPI_INPUT_EVENT_CODES_H := bionic/libc/kernel/uapi/linux/input.h bionic/libc/kernel/uapi/linux/input-event-codes.h
 INPUT_H_LABELS_H := $(intermediates)/input.h-labels.h
 $(INPUT_H_LABELS_H): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
 # The PRIVATE_CUSTOM_TOOL line uses = to evaluate the output path late.
@@ -93,14 +81,6 @@
 $(INPUT_H_LABELS_H):
 	$(transform-generated-source)
 
-# We only want 'r' on userdebug and eng builds.
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := r.c
-LOCAL_CFLAGS += $(common_cflags)
-LOCAL_MODULE := r
-LOCAL_MODULE_TAGS := debug
-include $(BUILD_EXECUTABLE)
-
 
 # We build BSD grep separately, so it can provide egrep and fgrep too.
 include $(CLEAR_VARS)
@@ -111,6 +91,7 @@
     upstream-netbsd/usr.bin/grep/queue.c \
     upstream-netbsd/usr.bin/grep/util.c
 LOCAL_CFLAGS += $(common_cflags)
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_MODULE := grep
 LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,egrep fgrep,ln -sf grep $(TARGET_OUT)/bin/$(t);)
 include $(BUILD_EXECUTABLE)
diff --git a/toolbox/bsd-compatibility.h b/toolbox/bsd-compatibility.h
index 434d370..7c3ddd4 100644
--- a/toolbox/bsd-compatibility.h
+++ b/toolbox/bsd-compatibility.h
@@ -43,7 +43,7 @@
 #define __type_fit(t, a) (0 == 0)
 
 // TODO: should this be in our <sys/cdefs.h>?
-#define __arraycount(a) (sizeof(a) / sizeof(a[0]))
+#define __arraycount(a) (sizeof(a) / sizeof((a)[0]))
 
 // This at least matches GNU dd(1) behavior.
 #define SIGINFO SIGUSR1
diff --git a/toolbox/generate-input.h-labels.py b/toolbox/generate-input.h-labels.py
index a2b9111..c0e9fce 100755
--- a/toolbox/generate-input.h-labels.py
+++ b/toolbox/generate-input.h-labels.py
@@ -38,39 +38,40 @@
 
 r = re.compile(r'#define\s+(\S+)\s+((?:0x)?\d+)')
 
-with open(sys.argv[1], 'r') as f:
-  for line in f:
-    m = r.match(line)
-    if m:
-      name = m.group(1)
-      if name.startswith("INPUT_PROP_"):
-        input_prop_list.append(name)
-      elif name.startswith("EV_"):
-        ev_list.append(name)
-      elif name.startswith("SYN_"):
-        syn_list.append(name)
-      elif name.startswith("KEY_") or name.startswith("BTN_"):
-        key_list.append(name)
-      elif name.startswith("REL_"):
-        rel_list.append(name)
-      elif name.startswith("ABS_"):
-        abs_list.append(name)
-      elif name.startswith("SW_"):
-        sw_list.append(name)
-      elif name.startswith("MSC_"):
-        msc_list.append(name)
-      elif name.startswith("LED_"):
-        led_list.append(name)
-      elif name.startswith("REP_"):
-        rep_list.append(name)
-      elif name.startswith("SND_"):
-        snd_list.append(name)
-      elif name.startswith("MT_TOOL_"):
-        mt_tool_list.append(name)
-      elif name.startswith("FF_STATUS_"):
-        ff_status_list.append(name)
-      elif name.startswith("FF_"):
-        ff_list.append(name)
+for arg in sys.argv[1:]:
+  with open(arg, 'r') as f:
+    for line in f:
+      m = r.match(line)
+      if m:
+        name = m.group(1)
+        if name.startswith("INPUT_PROP_"):
+          input_prop_list.append(name)
+        elif name.startswith("EV_"):
+          ev_list.append(name)
+        elif name.startswith("SYN_"):
+          syn_list.append(name)
+        elif name.startswith("KEY_") or name.startswith("BTN_"):
+          key_list.append(name)
+        elif name.startswith("REL_"):
+          rel_list.append(name)
+        elif name.startswith("ABS_"):
+          abs_list.append(name)
+        elif name.startswith("SW_"):
+          sw_list.append(name)
+        elif name.startswith("MSC_"):
+          msc_list.append(name)
+        elif name.startswith("LED_"):
+          led_list.append(name)
+        elif name.startswith("REP_"):
+          rep_list.append(name)
+        elif name.startswith("SND_"):
+          snd_list.append(name)
+        elif name.startswith("MT_TOOL_"):
+          mt_tool_list.append(name)
+        elif name.startswith("FF_STATUS_"):
+          ff_status_list.append(name)
+        elif name.startswith("FF_"):
+          ff_list.append(name)
 
 def Dump(struct_name, values):
   print('static struct label %s[] = {' % (struct_name))
diff --git a/toolbox/getevent.c b/toolbox/getevent.c
index 30053af..e6def6b 100644
--- a/toolbox/getevent.c
+++ b/toolbox/getevent.c
@@ -9,6 +9,7 @@
 #include <sys/limits.h>
 #include <sys/poll.h>
 #include <linux/input.h>
+#include <err.h>
 #include <errno.h>
 #include <unistd.h>
 
@@ -110,10 +111,8 @@
                 break;
             bits_size = res + 16;
             bits = realloc(bits, bits_size * 2);
-            if(bits == NULL) {
-                fprintf(stderr, "failed to allocate buffer of size %d\n", (int)bits_size);
-                return 1;
-            }
+            if(bits == NULL)
+                err(1, "failed to allocate buffer of size %d\n", (int)bits_size);
         }
         res2 = 0;
         switch(i) {
diff --git a/toolbox/iftop.c b/toolbox/iftop.c
deleted file mode 100644
index 800c0f0..0000000
--- a/toolbox/iftop.c
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <net/if.h>
-
-#define PROC_NET_DEV    "/proc/net/dev"
-
-#define MAX_IF           8   /* max interfaces we can handle */
-
-#ifndef PAGE_SIZE
-# define PAGE_SIZE 4096
-#endif
-
-#define _STR(s) #s
-#define STR(s) _STR(s)
-
-struct if_stats {
-    char name[IFNAMSIZ];
-
-    unsigned int mtu;
-
-    unsigned int rx_bytes;
-    unsigned int rx_packets;
-    unsigned int rx_errors;
-    unsigned int rx_dropped;
-
-    unsigned int tx_bytes;
-    unsigned int tx_packets;
-    unsigned int tx_errors;
-    unsigned int tx_dropped;
-};
-
-static int get_mtu(const char *if_name)
-{
-    struct ifreq ifr;
-    int s, ret;
-
-    s = socket(AF_INET, SOCK_DGRAM, 0);
-    if (s < 0) {
-        perror("socket");
-        exit(EXIT_FAILURE);
-    }
-
-    memset(&ifr, 0, sizeof(struct ifreq));
-    ifr.ifr_addr.sa_family = AF_INET;
-    strcpy(ifr.ifr_name, if_name);
-
-    ret = ioctl(s, SIOCGIFMTU, &ifr);
-    if (ret < 0) {
-        perror("ioctl");
-        exit(EXIT_FAILURE);
-    }
-
-    ret = close(s);
-    if (ret < 0) {
-        perror("close");
-        exit(EXIT_FAILURE);
-    }
-
-    return ifr.ifr_mtu;
-}
-
-static int get_interfaces(struct if_stats *ifs)
-{
-    char buf[PAGE_SIZE];
-    char *p;
-    int ret, nr, fd;
-
-    fd = open(PROC_NET_DEV, O_RDONLY);
-    if (fd < 0) {
-        perror("open");
-        exit(EXIT_FAILURE);
-    }
-
-    ret = read(fd, buf, sizeof(buf) - 1);
-    if (ret < 0) {
-        perror("read");
-        exit(EXIT_FAILURE);
-    } else if (!ret) {
-        fprintf(stderr, "reading " PROC_NET_DEV " returned premature EOF\n");
-        exit(EXIT_FAILURE);
-    }
-    buf[ret] = '\0';
-
-    /* skip down to the third line */
-    p = strchr(buf, '\n');
-    if (!p) {
-        fprintf(stderr, "parsing " PROC_NET_DEV " failed unexpectedly\n");
-        exit(EXIT_FAILURE);
-    }
-    p = strchr(p + 1, '\n');
-    if (!p) {
-        fprintf(stderr, "parsing " PROC_NET_DEV " failed unexpectedly\n");
-        exit(EXIT_FAILURE);
-    }
-    p += 1;
-
-    /*
-     * Key:
-     * if: (Rx) bytes packets errs drop fifo frame compressed multicast \
-     *     (Tx) bytes packets errs drop fifo colls carrier compressed
-     */
-    for (nr = 0; nr < MAX_IF; nr++) {
-        char *c;
-
-        ret = sscanf(p, "%" STR(IFNAMSIZ) "s", ifs->name);
-        if (ret != 1) {
-            fprintf(stderr, "parsing " PROC_NET_DEV " failed unexpectedly\n");
-            exit(EXIT_FAILURE);
-        }
-
-        /*
-         * This works around a bug in the proc file where large interface names
-         * or Rx byte counts eat the delimiter, breaking sscanf.
-         */
-        c = strchr(ifs->name, ':');
-        if (c)
-            *c = '\0';
-
-        p = strchr(p, ':') + 1;
-
-        ret = sscanf(p, "%u %u %u %u %*u %*u %*u %*u %u %u %u %u %*u %*u "
-                     "%*u %*u\n", &ifs->rx_bytes, &ifs->rx_packets,
-                     &ifs->rx_errors, &ifs->rx_dropped, &ifs->tx_bytes,
-                     &ifs->tx_packets, &ifs->tx_errors, &ifs->tx_dropped);
-        if (ret != 8) {
-            fprintf(stderr, "parsing " PROC_NET_DEV " failed unexpectedly\n");
-            exit(EXIT_FAILURE);
-        }
-
-        ifs->mtu = get_mtu(ifs->name);
-
-        p = strchr(p, '\n') + 1;
-        if (*p == '\0') {
-            nr++;
-            break;
-        }
-
-        ifs++;
-    }
-
-    ret = close(fd);
-    if (ret) {
-        perror("close");
-        exit(EXIT_FAILURE);
-    }
-
-    return nr;
-}
-
-static void print_header(void)
-{
-    printf("               Rx                              Tx\n");
-    printf("%-8s %-5s %-10s %-8s %-5s %-5s %-10s %-8s %-5s %-5s\n",
-           "name", "MTU", "bytes", "packets", "errs", "drpd", "bytes",
-           "packets", "errs", "drpd");
-}
-
-static int print_interfaces(struct if_stats *old, struct if_stats *new, int nr)
-{
-    int i = 0;
-
-    while (nr--) {
-        if (old->rx_packets || old->tx_packets) {
-            printf("%-8s %-5u %-10u %-8u %-5u %-5u %-10u %-8u %-5u %-5u\n",
-                   new->name, new->mtu,
-                   new->rx_bytes - old->rx_bytes,
-                   new->rx_packets - old->rx_packets,
-                   new->rx_errors - old->rx_errors,
-                   new->rx_dropped - old->rx_dropped,
-                   new->tx_bytes - old->tx_bytes,
-                   new->tx_packets - old->tx_packets,
-                   new->tx_errors - old->tx_errors,
-                   new->tx_dropped - old->tx_dropped);
-            i++;
-        }
-        old++;
-        new++;
-    }
-
-    return i;
-}
-
-static void usage(const char *cmd)
-{
-    fprintf(stderr, "usage: %s [ -r repeats] [ -d delay ]\n", cmd);
-}
-
-int iftop_main(int argc, char *argv[])
-{
-    struct if_stats ifs[2][MAX_IF];
-    int count = 0, header_interval = 22, delay = 1, i;
-    unsigned int toggle = 0;
-
-    for (i = 1; i < argc; i++) {
-        if (!strcmp(argv[i], "-d")) {
-            if (i >= argc - 1) {
-                fprintf(stderr, "Option -d requires an argument.\n");
-                exit(EXIT_FAILURE);
-            }
-            delay = atoi(argv[i++]);
-            if (!delay)
-                delay = 1;
-            continue;
-        }
-        if (!strcmp(argv[i], "-r")) {
-            if (i >= argc - 1) {
-                fprintf(stderr, "Option -r requires an argument.\n");
-                exit(EXIT_FAILURE);
-            }
-            header_interval = atoi(argv[i++]);
-            if (header_interval < MAX_IF)
-                header_interval = MAX_IF;
-            continue;
-        }
-        if (!strcmp(argv[i], "-h")) {
-            usage(argv[0]);
-            exit(EXIT_SUCCESS);
-        }
-        usage(argv[0]);
-        exit(EXIT_FAILURE);
-    }
-
-    get_interfaces(ifs[!toggle]);
-    if (header_interval)
-        print_header();
-    while (1) {
-        int nr;
-
-        sleep(delay);
-        nr = get_interfaces(ifs[toggle]);
-        if (header_interval && count + nr > header_interval) {
-            print_header();
-            count = 0;
-        }
-        count += print_interfaces(ifs[!toggle], ifs[toggle], nr);
-        toggle = !toggle;
-    }
-
-    return 0;
-}
diff --git a/toolbox/ioctl.c b/toolbox/ioctl.c
deleted file mode 100644
index 093e467..0000000
--- a/toolbox/ioctl.c
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <errno.h>
-#include <error.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-
-static void usage() {
-    fprintf(stderr, "%s [-l <length>] [-a <argsize>] [-rdh] <device> <ioctlnr>\n"
-            "  -l <length>   Length of io buffer\n"
-            "  -a <argsize>  Size of each argument (1-8)\n"
-            "  -r            Open device in read only mode\n"
-            "  -d            Direct argument (no iobuffer)\n"
-            "  -h            Print help\n", getprogname());
-    exit(1);
-}
-
-static int xstrtoi(const char* s, const char* what) {
-    char* endp;
-    errno = 0;
-    long result = strtol(s, &endp, 0);
-    if (errno != 0 || *endp != '\0') {
-        error(1, errno, "couldn't parse %s '%s'", what, s);
-    }
-    if (result > INT_MAX || result < INT_MIN) {
-        error(1, errno, "%s '%s' out of range", what, s);
-    }
-    return result;
-}
-
-int ioctl_main(int argc, char* argv[]) {
-    int read_only = 0;
-    int length = -1;
-    int arg_size = 4;
-    int direct_arg = 0;
-
-    void *ioctl_args = NULL;
-    uint8_t *ioctl_argp;
-    uint8_t *ioctl_argp_save = NULL;
-    int rem;
-
-    int c;
-    while ((c = getopt(argc, argv, "rdl:a:h")) != -1) {
-        switch (c) {
-        case 'r':
-            read_only = 1;
-            break;
-        case 'd':
-            direct_arg = 1;
-            break;
-        case 'l':
-            length = xstrtoi(optarg, "length");
-            break;
-        case 'a':
-            arg_size = xstrtoi(optarg, "argument size");
-            break;
-        case 'h':
-            usage();
-            break;
-        default:
-            error(1, 0, "invalid option -%c", optopt);
-        }
-    }
-
-    if (optind + 2 > argc) {
-        usage();
-    }
-
-    const char* device = argv[optind];
-    int fd;
-    if (strcmp(device, "-") == 0) {
-        fd = STDIN_FILENO;
-    } else {
-        fd = open(device, read_only ? O_RDONLY : (O_RDWR | O_SYNC));
-        if (fd == -1) {
-            error(1, errno, "cannot open %s", argv[optind]);
-        }
-    }
-    optind++;
-
-    // IOCTL(2) wants second parameter as a signed int.
-    // Let's let the user specify either negative numbers or large positive
-    // numbers, for the case where ioctl number is larger than INT_MAX.
-    errno = 0;
-    char* endp;
-    int ioctl_nr = UINT_MAX & strtoll(argv[optind], &endp, 0);
-    if (errno != 0 || *endp != '\0') {
-        error(1, errno, "couldn't parse ioctl number '%s'", argv[optind]);
-    }
-    optind++;
-
-    if(direct_arg) {
-        arg_size = 4;
-        length = 4;
-    }
-
-    if(length < 0) {
-        length = (argc - optind) * arg_size;
-    }
-    if(length) {
-        ioctl_args = calloc(1, length);
-
-        ioctl_argp_save = ioctl_argp = ioctl_args;
-        rem = length;
-        while (optind < argc) {
-            uint64_t tmp = strtoull(argv[optind], NULL, 0);
-            if (rem < arg_size) {
-                error(1, 0, "too many arguments");
-            }
-            memcpy(ioctl_argp, &tmp, arg_size);
-            ioctl_argp += arg_size;
-            rem -= arg_size;
-            optind++;
-        }
-    }
-    printf("sending ioctl 0x%x", ioctl_nr);
-    rem = length;
-    while(rem--) {
-        printf(" 0x%02x", *ioctl_argp_save++);
-    }
-    printf(" to %s\n", device);
-
-    int res;
-    if(direct_arg)
-        res = ioctl(fd, ioctl_nr, *(uint32_t*)ioctl_args);
-    else if(length)
-        res = ioctl(fd, ioctl_nr, ioctl_args);
-    else
-        res = ioctl(fd, ioctl_nr, 0);
-    if (res < 0) {
-        free(ioctl_args);
-        error(1, errno, "ioctl 0x%x failed (returned %d)", ioctl_nr, res);
-    }
-
-    if (length) {
-        printf("return buf:");
-        ioctl_argp = ioctl_args;
-        rem = length;
-        while(rem--) {
-            printf(" %02x", *ioctl_argp++);
-        }
-        printf("\n");
-    }
-    free(ioctl_args);
-    close(fd);
-    return 0;
-}
diff --git a/toolbox/log.c b/toolbox/log.c
deleted file mode 100644
index 2f020a8..0000000
--- a/toolbox/log.c
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <log/logd.h>
-#include <ctype.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <stdlib.h>
-#include <cutils/sockets.h>
-#include <unistd.h>
-
-/*
- * Note: also accepts 0-9 priorities
- * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
- */
-static android_LogPriority filterCharToPri (char c)
-{
-    android_LogPriority pri;
-
-    c = tolower(c);
-
-    if (c >= '0' && c <= '9') {
-        if (c >= ('0'+ANDROID_LOG_SILENT)) {
-            pri = ANDROID_LOG_VERBOSE;
-        } else {
-            pri = (android_LogPriority)(c - '0');
-        }
-    } else if (c == 'v') {
-        pri = ANDROID_LOG_VERBOSE;
-    } else if (c == 'd') {
-        pri = ANDROID_LOG_DEBUG;
-    } else if (c == 'i') {
-        pri = ANDROID_LOG_INFO;
-    } else if (c == 'w') {
-        pri = ANDROID_LOG_WARN;
-    } else if (c == 'e') {
-        pri = ANDROID_LOG_ERROR;
-    } else if (c == 'f') {
-        pri = ANDROID_LOG_FATAL;
-    } else if (c == 's') {
-        pri = ANDROID_LOG_SILENT;
-    } else if (c == '*') {
-        pri = ANDROID_LOG_DEFAULT;
-    } else {
-        pri = ANDROID_LOG_UNKNOWN;
-    }
-
-    return pri;
-}
-
-static int usage(const char *s)
-{
-    fprintf(stderr, "USAGE: %s [-p priorityChar] [-t tag] message\n", s);
-
-    fprintf(stderr, "\tpriorityChar should be one of:\n"
-                        "\t\tv,d,i,w,e\n");
-    exit(-1);
-}
-
-
-int log_main(int argc, char *argv[])
-{
-    android_LogPriority priority; 
-    const char *tag = "log";
-    char buffer[4096];
-    int i;
-
-    priority = ANDROID_LOG_INFO;
-
-    for (;;) {
-        int ret;
-
-        ret = getopt(argc, argv, "t:p:h");
-
-        if (ret < 0) {
-            break;
-        }
-
-        switch(ret) {
-            case 't':
-                tag = optarg;
-            break;
-            
-            case 'p':
-                priority = filterCharToPri(optarg[0]);
-                if (priority == ANDROID_LOG_UNKNOWN) {
-                    usage(argv[0]);                    
-                }
-            break;
-
-            case 'h':
-                usage(argv[0]);
-            break;
-        }
-    }
-
-    if (optind == argc) {
-        usage(argv[0]);
-    }
-
-    buffer[0] = '\0';
-    
-    for (i = optind ; i < argc ; i++) {
-        strlcat(buffer, argv[i], sizeof(buffer)-1);
-        strlcat(buffer, " ", sizeof(buffer)-1);
-    }
-
-    if(buffer[0] == 0) {
-        usage(argv[0]);
-    }
-
-    __android_log_print(priority, tag, "%s", buffer);
-
-    return 0;
-}
-
diff --git a/toolbox/nandread.c b/toolbox/nandread.c
deleted file mode 100644
index bd19942..0000000
--- a/toolbox/nandread.c
+++ /dev/null
@@ -1,287 +0,0 @@
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <mtd/mtd-user.h>
-#include <sys/ioctl.h>
-
-static int test_empty(const char *buf, size_t size)
-{
-    while(size--) {
-        if (*buf++ != (char) 0xff)
-            return 0;
-    }
-    return 1;
-}
-
-int nandread_main(int argc, char **argv)
-{
-    char *devname = NULL;
-    char *filename = NULL;
-    char *statusfilename = NULL;
-    char *statusext = ".stat";
-    int fd;
-    int outfd = -1;
-    FILE *statusfile = NULL;
-    int ret;
-    int verbose = 0;
-    void *buffer;
-    loff_t pos, opos, end, bpos;
-    loff_t start = 0, len = 0;
-    int c;
-    int i;
-    int empty_pages = 0;
-    int page_count = 0;
-    int bad_block;
-    int rawmode = 0;
-    uint32_t *oob_data;
-    uint8_t *oob_fixed;
-    size_t spare_size = 64;
-    struct mtd_info_user mtdinfo;
-    struct mtd_ecc_stats initial_ecc, last_ecc, ecc;
-    struct mtd_oob_buf oobbuf;
-    nand_ecclayout_t ecclayout;
-
-    do {
-        c = getopt(argc, argv, "d:f:s:S:L:Rhv");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'd':
-            devname = optarg;
-            break;
-        case 'f':
-            filename = optarg;
-            break;
-        case 's':
-            spare_size = atoi(optarg);
-            break;
-        case 'S':
-            start = strtoll(optarg, NULL, 0);
-            break;
-        case 'L':
-            len = strtoll(optarg, NULL, 0);
-            break;
-        case 'R':
-            rawmode = 1;
-            break;
-        case 'v':
-            verbose++;
-            break;
-        case 'h':
-            fprintf(stderr, "%s [-d <dev>] [-f file] [-s sparesize] [-vh]\n"
-                    "  -d <dev>   Read from <dev>\n"
-                    "  -f <file>  Write to <file>\n"
-                    "  -s <size>  Number of spare bytes in file (default 64)\n"
-                    "  -R         Raw mode\n"
-                    "  -S <start> Start offset (default 0)\n"
-                    "  -L <len>   Length (default 0)\n"
-                    "  -v         Print info\n"
-                    "  -h         Print help\n", argv[0]);
-            return -1;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if (optind < argc) {
-        fprintf(stderr, "%s: extra arguments\n", argv[0]);
-        return 1;
-    }
-    if (!devname) {
-        fprintf(stderr, "%s: specify device name\n", argv[0]);
-        return 1;
-    }
-
-    fd = open(devname, O_RDONLY);
-    if (fd < 0) {
-        fprintf(stderr, "cannot open %s, %s\n", devname, strerror(errno));
-        return 1;
-    }
-
-    if (filename) {
-        outfd = creat(filename, 0666);
-        if (outfd < 0) {
-            fprintf(stderr, "cannot open %s, %s\n", filename, strerror(errno));
-            return 1;
-        }
-        statusfilename = malloc(strlen(filename) + strlen(statusext) + 1);
-        strcpy(statusfilename, filename);
-        strcat(statusfilename, statusext);
-        statusfile = fopen(statusfilename, "w+");
-        if (!statusfile) {
-            fprintf(stderr, "cannot open %s, %s\n", statusfilename, strerror(errno));
-            return 1;
-        }
-    }
-
-    ret = ioctl(fd, MEMGETINFO, &mtdinfo);
-    if (ret) {
-        fprintf(stderr, "failed get mtd info for %s, %s\n",
-                devname, strerror(errno));
-        return 1;
-    }
-
-    if (verbose) {
-        printf("size: %u\n", mtdinfo.size);
-        printf("erase size: %u\n", mtdinfo.erasesize);
-        printf("write size: %u\n", mtdinfo.writesize);
-        printf("oob size: %u\n", mtdinfo.oobsize);
-    }
-
-    buffer = malloc(mtdinfo.writesize + mtdinfo.oobsize + spare_size);
-    if (!buffer) {
-        fprintf(stderr, "failed allocate readbuffer size %u\n",
-                mtdinfo.writesize + mtdinfo.oobsize);
-        return 1;
-    }
-
-    oobbuf.length = mtdinfo.oobsize;
-    oob_data = (uint32_t *)((uint8_t *)buffer + mtdinfo.writesize);
-    memset(oob_data, 0xff, mtdinfo.oobsize + spare_size);
-    oobbuf.ptr = (uint8_t *)oob_data + spare_size;
-
-    ret = ioctl(fd, ECCGETLAYOUT, &ecclayout);
-    if (ret) {
-        fprintf(stderr, "failed get ecc layout for %s, %s\n",
-                devname, strerror(errno));
-        return 1;
-    }
-    if (verbose) {
-        printf("ecc bytes: %u\n", ecclayout.eccbytes);
-        printf("oobavail: %u\n", ecclayout.oobavail);
-    }
-    if (ecclayout.oobavail > spare_size)
-        printf("oobavail, %d > image spare size, %zu\n", ecclayout.oobavail, spare_size);
-
-    ret = ioctl(fd, ECCGETSTATS, &initial_ecc);
-    if (ret) {
-        fprintf(stderr, "failed get ecc stats for %s, %s\n",
-                devname, strerror(errno));
-        return 1;
-    }
-    last_ecc = initial_ecc;
-
-    if (verbose) {
-        printf("initial ecc corrected: %u\n", initial_ecc.corrected);
-        printf("initial ecc failed: %u\n", initial_ecc.failed);
-        printf("initial ecc badblocks: %u\n", initial_ecc.badblocks);
-        printf("initial ecc bbtblocks: %u\n", initial_ecc.bbtblocks);
-    }
-
-    if (rawmode) {
-        rawmode = mtdinfo.oobsize;
-        ret = ioctl(fd, MTDFILEMODE, MTD_FILE_MODE_RAW);
-        if (ret) {
-            fprintf(stderr, "failed set raw mode for %s, %s\n",
-                    devname, strerror(errno));
-            return 1;
-        }
-    }
-
-    end = len ? (start + len) : mtdinfo.size;
-    for (pos = start, opos = 0; pos < end; pos += mtdinfo.writesize) {
-        bad_block = 0;
-        if (verbose > 3)
-            printf("reading at %" PRIx64 "\n", pos);
-        lseek64(fd, pos, SEEK_SET);
-        ret = read(fd, buffer, mtdinfo.writesize + rawmode);
-        if (ret < (int)mtdinfo.writesize) {
-            fprintf(stderr, "short read at %" PRIx64 ", %d\n", pos, ret);
-            bad_block = 2;
-        }
-        if (!rawmode) {
-            oobbuf.start = pos;
-            ret = ioctl(fd, MEMREADOOB, &oobbuf);
-            if (ret) {
-                fprintf(stderr, "failed to read oob data at %" PRIx64 ", %d\n", pos, ret);
-                bad_block = 2;
-            }
-        }
-        ret = ioctl(fd, ECCGETSTATS, &ecc);
-        if (ret) {
-            fprintf(stderr, "failed get ecc stats for %s, %s\n",
-                    devname, strerror(errno));
-            return 1;
-        }
-        bpos = pos / mtdinfo.erasesize * mtdinfo.erasesize;
-        ret = ioctl(fd, MEMGETBADBLOCK, &bpos);
-        if (ret && errno != EOPNOTSUPP) {
-            printf("badblock at %" PRIx64 "\n", pos);
-            bad_block = 1;
-        }
-        if (ecc.corrected != last_ecc.corrected)
-            printf("ecc corrected, %u, at %" PRIx64 "\n", ecc.corrected - last_ecc.corrected, pos);
-        if (ecc.failed != last_ecc.failed)
-            printf("ecc failed, %u, at %" PRIx64 "\n", ecc.failed - last_ecc.failed, pos);
-        if (ecc.badblocks != last_ecc.badblocks)
-            printf("ecc badblocks, %u, at %" PRIx64 "\n", ecc.badblocks - last_ecc.badblocks, pos);
-        if (ecc.bbtblocks != last_ecc.bbtblocks)
-            printf("ecc bbtblocks, %u, at %" PRIx64 "\n", ecc.bbtblocks - last_ecc.bbtblocks, pos);
-
-        if (!rawmode) {
-            oob_fixed = (uint8_t *)oob_data;
-            for (i = 0; i < MTD_MAX_OOBFREE_ENTRIES; i++) {
-                int len = ecclayout.oobfree[i].length;
-                if (oob_fixed + len > oobbuf.ptr)
-                    len = oobbuf.ptr - oob_fixed;
-                if (len) {
-                    memcpy(oob_fixed, oobbuf.ptr + ecclayout.oobfree[i].offset, len);
-                    oob_fixed += len;
-                }
-            }
-        }
-
-        if (outfd >= 0) {
-            ret = write(outfd, buffer, mtdinfo.writesize + spare_size);
-            if (ret < (int)(mtdinfo.writesize + spare_size)) {
-                fprintf(stderr, "short write at %" PRIx64 ", %d\n", pos, ret);
-                close(outfd);
-                outfd = -1;
-            }
-            if (ecc.corrected != last_ecc.corrected)
-                fprintf(statusfile, "%08" PRIx64 ": ecc corrected\n", opos);
-            if (ecc.failed != last_ecc.failed)
-                fprintf(statusfile, "%08" PRIx64 ": ecc failed\n", opos);
-            if (bad_block == 1)
-                fprintf(statusfile, "%08" PRIx64 ": badblock\n", opos);
-            if (bad_block == 2)
-                fprintf(statusfile, "%08" PRIx64 ": read error\n", opos);
-            opos += mtdinfo.writesize + spare_size;
-        }
-
-        last_ecc = ecc;
-        page_count++;
-        if (test_empty(buffer, mtdinfo.writesize + mtdinfo.oobsize + spare_size))
-            empty_pages++;
-        else if (verbose > 2 || (verbose > 1 && !(pos & (mtdinfo.erasesize - 1))))
-            printf("page at %" PRIx64 " (%d oobbytes): %08x %08x %08x %08x "
-                   "%08x %08x %08x %08x\n", pos, oobbuf.start,
-                   oob_data[0], oob_data[1], oob_data[2], oob_data[3],
-                   oob_data[4], oob_data[5], oob_data[6], oob_data[7]);
-    }
-
-    if (outfd >= 0) {
-        fprintf(statusfile, "read %d pages, %d empty\n", page_count, empty_pages);
-        fprintf(statusfile, "total ecc corrected, %u\n", ecc.corrected - initial_ecc.corrected);
-        fprintf(statusfile, "total ecc failed, %u\n", ecc.failed - initial_ecc.failed);
-        fprintf(statusfile, "total ecc badblocks, %u\n", ecc.badblocks - initial_ecc.badblocks);
-        fprintf(statusfile, "total ecc bbtblocks, %u\n", ecc.bbtblocks - initial_ecc.bbtblocks);
-    }
-    if (verbose) {
-        printf("total ecc corrected, %u\n", ecc.corrected - initial_ecc.corrected);
-        printf("total ecc failed, %u\n", ecc.failed - initial_ecc.failed);
-        printf("total ecc badblocks, %u\n", ecc.badblocks - initial_ecc.badblocks);
-        printf("total ecc bbtblocks, %u\n", ecc.bbtblocks - initial_ecc.bbtblocks);
-    }
-    printf("read %d pages, %d empty\n", page_count, empty_pages);
-
-    return 0;
-}
diff --git a/toolbox/newfs_msdos.c b/toolbox/newfs_msdos.c
index 5b98a01..d7047e2 100644
--- a/toolbox/newfs_msdos.c
+++ b/toolbox/newfs_msdos.c
@@ -695,7 +695,7 @@
                                                     (u_int)tm->tm_min));
                 mk4(bsx->volid, x);
                 mklabel(bsx->label, opt_L ? opt_L : "NO NAME");
-                sprintf(buf, "FAT%u", fat);
+                snprintf(buf, sizeof(buf), "FAT%u", fat);
                 setstr(bsx->type, buf, sizeof(bsx->type));
                 if (!opt_B) {
                     x1 += sizeof(struct bsx);
@@ -741,6 +741,7 @@
                 exit(1);
             }
         }
+        free(img);
     }
     return 0;
 }
diff --git a/toolbox/prlimit.c b/toolbox/prlimit.c
deleted file mode 100644
index 8cf202a..0000000
--- a/toolbox/prlimit.c
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2014, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/time.h>
-#include <sys/resource.h>
-
-static void
-usage(const char *s)
-{
-    fprintf(stderr, "usage: %s pid resource cur max\n", s);
-    exit(EXIT_FAILURE);
-}
-
-int prlimit_main(int argc, char *argv[])
-{
-    pid_t pid;
-    struct rlimit64 rl;
-    int resource;
-    int rc;
-
-    if (argc != 5)
-        usage(*argv);
-
-    if (sscanf(argv[1], "%d", &pid) != 1)
-        usage(*argv);
-
-    if (sscanf(argv[2], "%d", &resource) != 1)
-        usage(*argv);
-
-    if (sscanf(argv[3], "%llu", &rl.rlim_cur) != 1)
-        usage(*argv);
-
-    if (sscanf(argv[4], "%llu", &rl.rlim_max) != 1)
-        usage(*argv);
-
-    printf("setting resource %d of pid %d to [%llu,%llu]\n", resource, pid,
-            rl.rlim_cur, rl.rlim_max);
-    rc = prlimit64(pid, resource, &rl, NULL);
-    if (rc < 0) {
-        perror("prlimit");
-        exit(EXIT_FAILURE);
-    }
-
-    return 0;
-}
diff --git a/toolbox/ps.c b/toolbox/ps.c
deleted file mode 100644
index 7e70c71..0000000
--- a/toolbox/ps.c
+++ /dev/null
@@ -1,334 +0,0 @@
-#include <ctype.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/sched_policy.h>
-
-static char *nexttoksep(char **strp, char *sep)
-{
-    char *p = strsep(strp,sep);
-    return (p == 0) ? "" : p;
-}
-static char *nexttok(char **strp)
-{
-    return nexttoksep(strp, " ");
-}
-
-#define SHOW_PRIO 1
-#define SHOW_TIME 2
-#define SHOW_POLICY 4
-#define SHOW_CPU  8
-#define SHOW_MACLABEL 16
-#define SHOW_NUMERIC_UID 32
-#define SHOW_ABI 64
-
-#if __LP64__
-#define PC_WIDTH 10 /* Realistically, the top bits will be 0, so don't waste space. */
-#else
-#define PC_WIDTH (2*sizeof(uintptr_t))
-#endif
-
-static int display_flags = 0;
-static int ppid_filter = 0;
-
-static void print_exe_abi(int pid);
-
-static int ps_line(int pid, int tid)
-{
-    char statline[1024];
-    char cmdline[1024];
-    char macline[1024];
-    char user[32];
-    struct stat stats;
-    int r;
-    char *ptr, *name, *state;
-    int ppid;
-    unsigned rss, vss;
-    uintptr_t eip;
-    unsigned utime, stime;
-    int prio, nice, rtprio, sched, psr;
-    struct passwd *pw;
-
-    sprintf(statline, "/proc/%d", tid ? tid : pid);
-    stat(statline, &stats);
-
-    if(tid) {
-        sprintf(statline, "/proc/%d/task/%d/stat", pid, tid);
-        cmdline[0] = 0;
-        snprintf(macline, sizeof(macline), "/proc/%d/task/%d/attr/current", pid, tid);
-    } else {
-        sprintf(statline, "/proc/%d/stat", pid);
-        sprintf(cmdline, "/proc/%d/cmdline", pid);
-        snprintf(macline, sizeof(macline), "/proc/%d/attr/current", pid);
-        int fd = open(cmdline, O_RDONLY);
-        if(fd == 0) {
-            r = 0;
-        } else {
-            r = read(fd, cmdline, 1023);
-            close(fd);
-            if(r < 0) r = 0;
-        }
-        cmdline[r] = 0;
-    }
-
-    int fd = open(statline, O_RDONLY);
-    if(fd == 0) return -1;
-    r = read(fd, statline, 1023);
-    close(fd);
-    if(r < 0) return -1;
-    statline[r] = 0;
-
-    ptr = statline;
-    nexttok(&ptr); // skip pid
-    ptr++;          // skip "("
-
-    name = ptr;
-    ptr = strrchr(ptr, ')'); // Skip to *last* occurence of ')',
-    *ptr++ = '\0';           // and null-terminate name.
-
-    ptr++;          // skip " "
-    state = nexttok(&ptr);
-    ppid = atoi(nexttok(&ptr));
-    nexttok(&ptr); // pgrp
-    nexttok(&ptr); // sid
-    nexttok(&ptr); // tty
-    nexttok(&ptr); // tpgid
-    nexttok(&ptr); // flags
-    nexttok(&ptr); // minflt
-    nexttok(&ptr); // cminflt
-    nexttok(&ptr); // majflt
-    nexttok(&ptr); // cmajflt
-#if 1
-    utime = atoi(nexttok(&ptr));
-    stime = atoi(nexttok(&ptr));
-#else
-    nexttok(&ptr); // utime
-    nexttok(&ptr); // stime
-#endif
-    nexttok(&ptr); // cutime
-    nexttok(&ptr); // cstime
-    prio = atoi(nexttok(&ptr));
-    nice = atoi(nexttok(&ptr));
-    nexttok(&ptr); // threads
-    nexttok(&ptr); // itrealvalue
-    nexttok(&ptr); // starttime
-    vss = strtoul(nexttok(&ptr), 0, 10); // vsize
-    rss = strtoul(nexttok(&ptr), 0, 10); // rss
-    nexttok(&ptr); // rlim
-    nexttok(&ptr); // startcode
-    nexttok(&ptr); // endcode
-    nexttok(&ptr); // startstack
-    nexttok(&ptr); // kstkesp
-    eip = strtoul(nexttok(&ptr), 0, 10); // kstkeip
-    nexttok(&ptr); // signal
-    nexttok(&ptr); // blocked
-    nexttok(&ptr); // sigignore
-    nexttok(&ptr); // sigcatch
-    nexttok(&ptr); // wchan
-    nexttok(&ptr); // nswap
-    nexttok(&ptr); // cnswap
-    nexttok(&ptr); // exit signal
-    psr = atoi(nexttok(&ptr)); // processor
-    rtprio = atoi(nexttok(&ptr)); // rt_priority
-    sched = atoi(nexttok(&ptr)); // scheduling policy
-
-    nexttok(&ptr); // tty
-
-    if(tid != 0) {
-        ppid = pid;
-        pid = tid;
-    }
-
-    pw = getpwuid(stats.st_uid);
-    if(pw == 0 || (display_flags & SHOW_NUMERIC_UID)) {
-        sprintf(user,"%d",(int)stats.st_uid);
-    } else {
-        strcpy(user,pw->pw_name);
-    }
-
-    if(ppid_filter != 0 && ppid != ppid_filter) {
-        return 0;
-    }
-
-    if (display_flags & SHOW_MACLABEL) {
-        fd = open(macline, O_RDONLY);
-        strcpy(macline, "-");
-        if (fd >= 0) {
-            r = read(fd, macline, sizeof(macline)-1);
-            close(fd);
-            if (r > 0)
-                macline[r] = 0;
-        }
-        printf("%-30s ", macline);
-    }
-
-    printf("%-9s %-5d %-5d %-6d %-5d", user, pid, ppid, vss / 1024, rss * 4);
-    if (display_flags & SHOW_CPU)
-        printf(" %-2d", psr);
-    if (display_flags & SHOW_PRIO)
-        printf(" %-5d %-5d %-5d %-5d", prio, nice, rtprio, sched);
-    if (display_flags & SHOW_POLICY) {
-        SchedPolicy p;
-        if (get_sched_policy(pid, &p) < 0)
-            printf(" un ");
-        else
-            printf(" %.2s ", get_sched_policy_name(p));
-    }
-    char path[PATH_MAX];
-    snprintf(path, sizeof(path), "/proc/%d/wchan", pid);
-    char wchan[10];
-    fd = open(path, O_RDONLY);
-    ssize_t wchan_len = read(fd, wchan, sizeof(wchan));
-    if (wchan_len == -1) {
-        wchan[wchan_len = 0] = '\0';
-    }
-    close(fd);
-    printf(" %10.*s %0*" PRIxPTR " %s ", (int) wchan_len, wchan, (int) PC_WIDTH, eip, state);
-    if (display_flags & SHOW_ABI) {
-        print_exe_abi(pid);
-    }
-    printf("%s", cmdline[0] ? cmdline : name);
-    if(display_flags&SHOW_TIME)
-        printf(" (u:%d, s:%d)", utime, stime);
-
-    printf("\n");
-    return 0;
-}
-
-static void print_exe_abi(int pid)
-{
-    int fd, r;
-    char exeline[1024];
-
-    sprintf(exeline, "/proc/%d/exe", pid);
-    fd = open(exeline, O_RDONLY);
-    if(fd == 0) {
-        printf("    ");
-        return;
-    }
-    r = read(fd, exeline, 5 /* 4 byte ELFMAG + 1 byte EI_CLASS */);
-    close(fd);
-    if(r < 0) {
-        printf("    ");
-        return;
-    }
-    if (memcmp("\177ELF", exeline, 4) != 0) {
-        printf("??  ");
-        return;
-    }
-    switch (exeline[4]) {
-        case 1:
-            printf("32  ");
-            return;
-        case 2:
-            printf("64  ");
-            return;
-        default:
-            printf("??  ");
-            return;
-    }
-}
-
-void ps_threads(int pid)
-{
-    char tmp[128];
-    DIR *d;
-    struct dirent *de;
-
-    sprintf(tmp,"/proc/%d/task",pid);
-    d = opendir(tmp);
-    if(d == 0) return;
-
-    while((de = readdir(d)) != 0){
-        if(isdigit(de->d_name[0])){
-            int tid = atoi(de->d_name);
-            if(tid == pid) continue;
-            ps_line(pid, tid);
-        }
-    }
-    closedir(d);
-}
-
-int ps_main(int argc, char **argv)
-{
-    DIR *d;
-    struct dirent *de;
-    int pidfilter = 0;
-    int threads = 0;
-
-    while(argc > 1){
-        if(!strcmp(argv[1],"-t")) {
-            threads = 1;
-        } else if(!strcmp(argv[1],"-n")) {
-            display_flags |= SHOW_NUMERIC_UID;
-        } else if(!strcmp(argv[1],"-x")) {
-            display_flags |= SHOW_TIME;
-        } else if(!strcmp(argv[1], "-Z")) {
-            display_flags |= SHOW_MACLABEL;
-        } else if(!strcmp(argv[1],"-P")) {
-            display_flags |= SHOW_POLICY;
-        } else if(!strcmp(argv[1],"-p")) {
-            display_flags |= SHOW_PRIO;
-        } else if(!strcmp(argv[1],"-c")) {
-            display_flags |= SHOW_CPU;
-        } else if(!strcmp(argv[1],"--abi")) {
-            display_flags |= SHOW_ABI;
-        } else if(!strcmp(argv[1],"--ppid")) {
-            ppid_filter = atoi(argv[2]);
-            if (ppid_filter == 0) {
-                /* Bug 26554285: Use printf because some apps require at least
-                 * one line of output to stdout even for errors.
-                 */
-                printf("bad ppid '%s'\n", argv[2]);
-                return 1;
-            }
-            argc--;
-            argv++;
-        } else {
-            pidfilter = atoi(argv[1]);
-            if (pidfilter == 0) {
-                /* Bug 26554285: Use printf because some apps require at least
-                 * one line of output to stdout even for errors.
-                 */
-                printf("bad pid '%s'\n", argv[1]);
-                return 1;
-            }
-        }
-        argc--;
-        argv++;
-    }
-
-    if (display_flags & SHOW_MACLABEL) {
-        printf("LABEL                          ");
-    }
-    printf("USER      PID   PPID  VSIZE  RSS  %s%s %sWCHAN      %*s  %sNAME\n",
-           (display_flags&SHOW_CPU)?"CPU ":"",
-           (display_flags&SHOW_PRIO)?"PRIO  NICE  RTPRI SCHED ":"",
-           (display_flags&SHOW_POLICY)?"PCY " : "",
-           (int) PC_WIDTH, "PC",
-           (display_flags&SHOW_ABI)?"ABI " : "");
-
-    d = opendir("/proc");
-    if(d == 0) return -1;
-
-    while((de = readdir(d)) != 0){
-        if(isdigit(de->d_name[0])){
-            int pid = atoi(de->d_name);
-            if(!pidfilter || (pidfilter == pid)) {
-                ps_line(pid, 0);
-                if(threads) ps_threads(pid);
-            }
-        }
-    }
-    closedir(d);
-    return 0;
-}
-
diff --git a/toolbox/r.c b/toolbox/r.c
deleted file mode 100644
index b96cdb2..0000000
--- a/toolbox/r.c
+++ /dev/null
@@ -1,102 +0,0 @@
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#if __LP64__
-#define strtoptr strtoull
-#else
-#define strtoptr strtoul
-#endif
-
-static int usage()
-{
-    fprintf(stderr,"r [-b|-s] <address> [<value>]\n");
-    return -1;
-}
-
-int main(int argc, char *argv[])
-{
-    if(argc < 2) return usage();
-
-    int width = 4;
-    if(!strcmp(argv[1], "-b")) {
-        width = 1;
-        argc--;
-        argv++;
-    } else if(!strcmp(argv[1], "-s")) {
-        width = 2;
-        argc--;
-        argv++;
-    }
-
-    if(argc < 2) return usage();
-    uintptr_t addr = strtoptr(argv[1], 0, 16);
-
-    uintptr_t endaddr = 0;
-    char* end = strchr(argv[1], '-');
-    if (end)
-        endaddr = strtoptr(end + 1, 0, 16);
-
-    if (!endaddr)
-        endaddr = addr + width - 1;
-
-    if (endaddr <= addr) {
-        fprintf(stderr, "end address <= start address\n");
-        return -1;
-    }
-
-    bool set = false;
-    uint32_t value = 0;
-    if(argc > 2) {
-        set = true;
-        value = strtoul(argv[2], 0, 16);
-    }
-
-    int fd = open("/dev/mem", O_RDWR | O_SYNC);
-    if(fd < 0) {
-        fprintf(stderr,"cannot open /dev/mem\n");
-        return -1;
-    }
-
-    off64_t mmap_start = addr & ~(PAGE_SIZE - 1);
-    size_t mmap_size = endaddr - mmap_start + 1;
-    mmap_size = (mmap_size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
-
-    void* page = mmap64(0, mmap_size, PROT_READ | PROT_WRITE,
-                        MAP_SHARED, fd, mmap_start);
-
-    if(page == MAP_FAILED){
-        fprintf(stderr,"cannot mmap region\n");
-        return -1;
-    }
-
-    while (addr <= endaddr) {
-        switch(width){
-        case 4: {
-            uint32_t* x = (uint32_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %08x\n", addr, *x);
-            break;
-        }
-        case 2: {
-            uint16_t* x = (uint16_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %04x\n", addr, *x);
-            break;
-        }
-        case 1: {
-            uint8_t* x = (uint8_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %02x\n", addr, *x);
-            break;
-        }
-        }
-        addr += width;
-    }
-    return 0;
-}
diff --git a/toolbox/sendevent.c b/toolbox/sendevent.c
deleted file mode 100644
index 4d0ca17..0000000
--- a/toolbox/sendevent.c
+++ /dev/null
@@ -1,42 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/input.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-
-int sendevent_main(int argc, char *argv[])
-{
-    int fd;
-    ssize_t ret;
-    int version;
-    struct input_event event;
-
-    if(argc != 5) {
-        fprintf(stderr, "use: %s device type code value\n", argv[0]);
-        return 1;
-    }
-
-    fd = open(argv[1], O_RDWR);
-    if(fd < 0) {
-        fprintf(stderr, "could not open %s, %s\n", argv[optind], strerror(errno));
-        return 1;
-    }
-    if (ioctl(fd, EVIOCGVERSION, &version)) {
-        fprintf(stderr, "could not get driver version for %s, %s\n", argv[optind], strerror(errno));
-        return 1;
-    }
-    memset(&event, 0, sizeof(event));
-    event.type = atoi(argv[2]);
-    event.code = atoi(argv[3]);
-    event.value = atoi(argv[4]);
-    ret = write(fd, &event, sizeof(event));
-    if(ret < (ssize_t) sizeof(event)) {
-        fprintf(stderr, "write event failed, %s\n", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
diff --git a/toolbox/start.c b/toolbox/start.c
deleted file mode 100644
index cca5fef..0000000
--- a/toolbox/start.c
+++ /dev/null
@@ -1 +0,0 @@
-/* Needed by Android.mk. Actual code in start_stop.cpp. */
diff --git a/toolbox/start_stop.cpp b/toolbox/start_stop.cpp
deleted file mode 100644
index dc48c0c..0000000
--- a/toolbox/start_stop.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include <error.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <cutils/properties.h>
-
-static const char* services[] = {
-  "netd",
-  "surfaceflinger",
-  "zygote",
-  "zygote_secondary",
-};
-
-static int start_stop(bool start, int argc, char* argv[]) {
-  if (getuid() != 0) error(1, 0, "must be root");
-  const char* property = start ? "ctl.start" : "ctl.stop";
-  if (argc > 2) {
-    error(1, 0, "usage: %s [SERVICE]\n", argv[0]);
-  } else if (argc == 2) {
-    property_set(property, argv[1]);
-  } else {
-    if (start) {
-      for (size_t i = 0; i < sizeof(services)/sizeof(services[0]); ++i) {
-        property_set(property, services[i]);
-      }
-    } else {
-      for (int i = sizeof(services)/sizeof(services[0]) - 1; i >= 0; --i) {
-        property_set(property, services[i]);
-      }
-    }
-  }
-  return 0;
-}
-
-extern "C" int start_main(int argc, char* argv[]) {
-  return start_stop(true, argc, argv);
-}
-
-extern "C" int stop_main(int argc, char* argv[]) {
-  return start_stop(false, argc, argv);
-}
diff --git a/toolbox/stop.c b/toolbox/stop.c
deleted file mode 100644
index cca5fef..0000000
--- a/toolbox/stop.c
+++ /dev/null
@@ -1 +0,0 @@
-/* Needed by Android.mk. Actual code in start_stop.cpp. */
diff --git a/toolbox/toolbox.c b/toolbox/toolbox.c
index 915da44..b5a942c 100644
--- a/toolbox/toolbox.c
+++ b/toolbox/toolbox.c
@@ -4,29 +4,14 @@
 #include <string.h>
 #include <unistd.h>
 
-int main(int, char **);
-
-static int toolbox_main(int argc, char **argv)
-{
-    // "toolbox foo ..." is equivalent to "foo ..."
-    if (argc > 1) {
-        return main(argc - 1, argv + 1);
-    } else {
-        printf("Toolbox!\n");
-        return 0;
-    }
-}
-
 #define TOOL(name) int name##_main(int, char**);
 #include "tools.h"
 #undef TOOL
 
-static struct 
-{
-    const char *name;
+static struct {
+    const char* name;
     int (*func)(int, char**);
 } tools[] = {
-    { "toolbox", toolbox_main },
 #define TOOL(name) { #name, name##_main },
 #include "tools.h"
 #undef TOOL
@@ -40,33 +25,35 @@
     _exit(0);
 }
 
-int main(int argc, char **argv)
-{
-    int i;
-    char *name = argv[0];
-
+int main(int argc, char** argv) {
     // Let's assume that none of this code handles broken pipes. At least ls,
     // ps, and top were broken (though I'd previously added this fix locally
     // to top). We exit rather than use SIG_IGN because tools like top will
     // just keep on writing to nowhere forever if we don't stop them.
     signal(SIGPIPE, SIGPIPE_handler);
 
-    if((argc > 1) && (argv[1][0] == '@')) {
-        name = argv[1] + 1;
-        argc--;
-        argv++;
-    } else {
-        char *cmd = strrchr(argv[0], '/');
-        if (cmd)
-            name = cmd + 1;
-    }
+    char* cmd = strrchr(argv[0], '/');
+    char* name = cmd ? (cmd + 1) : argv[0];
 
-    for(i = 0; tools[i].name; i++){
-        if(!strcmp(tools[i].name, name)){
+    for (size_t i = 0; tools[i].name; i++) {
+        if (!strcmp(tools[i].name, name)) {
             return tools[i].func(argc, argv);
         }
     }
 
     printf("%s: no such tool\n", argv[0]);
-    return -1;
+    return 127;
+}
+
+int toolbox_main(int argc, char** argv) {
+    // "toolbox foo ..." is equivalent to "foo ..."
+    if (argc > 1) {
+        return main(argc - 1, argv + 1);
+    }
+
+    // Plain "toolbox" lists the tools.
+    for (size_t i = 1; tools[i].name; i++) {
+        printf("%s%c", tools[i].name, tools[i+1].name ? ' ' : '\n');
+    }
+    return 0;
 }
diff --git a/toolbox/top.c b/toolbox/top.c
deleted file mode 100644
index e70ea31..0000000
--- a/toolbox/top.c
+++ /dev/null
@@ -1,596 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <ctype.h>
-#include <dirent.h>
-#include <errno.h>
-#include <grp.h>
-#include <inttypes.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <cutils/sched_policy.h>
-
-struct cpu_info {
-    long unsigned utime, ntime, stime, itime;
-    long unsigned iowtime, irqtime, sirqtime;
-};
-
-#define PROC_NAME_LEN 64
-#define THREAD_NAME_LEN 32
-#define POLICY_NAME_LEN 4
-
-struct proc_info {
-    struct proc_info *next;
-    pid_t pid;
-    pid_t tid;
-    uid_t uid;
-    gid_t gid;
-    char name[PROC_NAME_LEN];
-    char tname[THREAD_NAME_LEN];
-    char state;
-    uint64_t utime;
-    uint64_t stime;
-    char pr[3];
-    long ni;
-    uint64_t delta_utime;
-    uint64_t delta_stime;
-    uint64_t delta_time;
-    uint64_t vss;
-    uint64_t rss;
-    int num_threads;
-    char policy[POLICY_NAME_LEN];
-};
-
-struct proc_list {
-    struct proc_info **array;
-    int size;
-};
-
-#define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
-
-#define INIT_PROCS 50
-#define THREAD_MULT 8
-static struct proc_info **old_procs, **new_procs;
-static int num_old_procs, num_new_procs;
-static struct proc_info *free_procs;
-static int num_used_procs, num_free_procs;
-
-static int max_procs, delay, iterations, threads;
-
-static struct cpu_info old_cpu, new_cpu;
-
-static struct proc_info *alloc_proc(void);
-static void free_proc(struct proc_info *proc);
-static void read_procs(void);
-static int read_stat(char *filename, struct proc_info *proc);
-static void read_policy(int pid, struct proc_info *proc);
-static void add_proc(int proc_num, struct proc_info *proc);
-static int read_cmdline(char *filename, struct proc_info *proc);
-static int read_status(char *filename, struct proc_info *proc);
-static void print_procs(void);
-static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
-static void free_old_procs(void);
-static int (*proc_cmp)(const void *a, const void *b);
-static int proc_cpu_cmp(const void *a, const void *b);
-static int proc_vss_cmp(const void *a, const void *b);
-static int proc_rss_cmp(const void *a, const void *b);
-static int proc_thr_cmp(const void *a, const void *b);
-static int numcmp(long long a, long long b);
-static void usage(char *cmd);
-
-int top_main(int argc, char *argv[]) {
-    num_used_procs = num_free_procs = 0;
-
-    max_procs = 0;
-    delay = 3;
-    iterations = -1;
-    proc_cmp = &proc_cpu_cmp;
-    for (int i = 1; i < argc; i++) {
-        if (!strcmp(argv[i], "-m")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -m expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            max_procs = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-n")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -n expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            iterations = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-d")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -d expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            delay = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-s")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -s expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            ++i;
-            if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
-            if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
-            if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
-            if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
-            fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
-            exit(EXIT_FAILURE);
-        }
-        if (!strcmp(argv[i], "-H") || !strcmp(argv[i], "-t")) { threads = 1; continue; }
-        if (!strcmp(argv[i], "-h")) {
-            usage(argv[0]);
-            exit(EXIT_SUCCESS);
-        }
-        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
-        usage(argv[0]);
-        exit(EXIT_FAILURE);
-    }
-
-    if (threads && proc_cmp == &proc_thr_cmp) {
-        fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
-        exit(EXIT_FAILURE);
-    }
-
-    free_procs = NULL;
-
-    num_new_procs = num_old_procs = 0;
-    new_procs = old_procs = NULL;
-
-    read_procs();
-
-    // Pause 250ms to get better data and avoid divide by zero later (http://b/32478213).
-    struct timespec ts = { .tv_sec = 0, .tv_nsec = 250000000 };
-    TEMP_FAILURE_RETRY(nanosleep(&ts, &ts));
-
-    while ((iterations == -1) || (iterations-- > 0)) {
-        old_procs = new_procs;
-        num_old_procs = num_new_procs;
-        memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
-        read_procs();
-        print_procs();
-        free_old_procs();
-        fflush(stdout);
-        if (iterations != 0) sleep(delay);
-    }
-
-    return 0;
-}
-
-static struct proc_info *alloc_proc(void) {
-    struct proc_info *proc;
-
-    if (free_procs) {
-        proc = free_procs;
-        free_procs = free_procs->next;
-        num_free_procs--;
-    } else {
-        proc = malloc(sizeof(*proc));
-        if (!proc) die("Could not allocate struct process_info.\n");
-    }
-
-    num_used_procs++;
-
-    return proc;
-}
-
-static void free_proc(struct proc_info *proc) {
-    proc->next = free_procs;
-    free_procs = proc;
-
-    num_used_procs--;
-    num_free_procs++;
-}
-
-#define MAX_LINE 256
-
-static void read_procs(void) {
-    DIR *proc_dir, *task_dir;
-    struct dirent *pid_dir, *tid_dir;
-    char filename[64];
-    FILE *file;
-    int proc_num;
-    struct proc_info *proc;
-    pid_t pid, tid;
-
-    int i;
-
-    proc_dir = opendir("/proc");
-    if (!proc_dir) die("Could not open /proc.\n");
-
-    new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
-    num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
-
-    file = fopen("/proc/stat", "r");
-    if (!file) die("Could not open /proc/stat.\n");
-    fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
-            &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
-    fclose(file);
-
-    proc_num = 0;
-    while ((pid_dir = readdir(proc_dir))) {
-        if (!isdigit(pid_dir->d_name[0]))
-            continue;
-
-        pid = atoi(pid_dir->d_name);
-
-        struct proc_info cur_proc;
-
-        if (!threads) {
-            proc = alloc_proc();
-
-            proc->pid = proc->tid = pid;
-
-            sprintf(filename, "/proc/%d/stat", pid);
-            read_stat(filename, proc);
-
-            sprintf(filename, "/proc/%d/cmdline", pid);
-            read_cmdline(filename, proc);
-
-            sprintf(filename, "/proc/%d/status", pid);
-            read_status(filename, proc);
-
-            read_policy(pid, proc);
-
-            proc->num_threads = 0;
-        } else {
-            sprintf(filename, "/proc/%d/cmdline", pid);
-            read_cmdline(filename, &cur_proc);
-
-            sprintf(filename, "/proc/%d/status", pid);
-            read_status(filename, &cur_proc);
-
-            proc = NULL;
-        }
-
-        sprintf(filename, "/proc/%d/task", pid);
-        task_dir = opendir(filename);
-        if (!task_dir) continue;
-
-        while ((tid_dir = readdir(task_dir))) {
-            if (!isdigit(tid_dir->d_name[0]))
-                continue;
-
-            if (threads) {
-                tid = atoi(tid_dir->d_name);
-
-                proc = alloc_proc();
-
-                proc->pid = pid; proc->tid = tid;
-
-                sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
-                read_stat(filename, proc);
-
-                read_policy(tid, proc);
-
-                strcpy(proc->name, cur_proc.name);
-                proc->uid = cur_proc.uid;
-                proc->gid = cur_proc.gid;
-
-                add_proc(proc_num++, proc);
-            } else {
-                proc->num_threads++;
-            }
-        }
-
-        closedir(task_dir);
-
-        if (!threads)
-            add_proc(proc_num++, proc);
-    }
-
-    for (i = proc_num; i < num_new_procs; i++)
-        new_procs[i] = NULL;
-
-    closedir(proc_dir);
-}
-
-static int read_stat(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char buf[MAX_LINE], *open_paren, *close_paren;
-
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    fgets(buf, MAX_LINE, file);
-    fclose(file);
-
-    /* Split at first '(' and last ')' to get process name. */
-    open_paren = strchr(buf, '(');
-    close_paren = strrchr(buf, ')');
-    if (!open_paren || !close_paren) return 1;
-
-    *open_paren = *close_paren = '\0';
-    strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
-    proc->tname[THREAD_NAME_LEN-1] = 0;
-
-    // Scan rest of string.
-    long pr;
-    sscanf(close_paren + 1,
-           " %c "
-           "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
-           "%" SCNu64 // utime %lu (14)
-           "%" SCNu64 // stime %lu (15)
-           "%*d %*d "
-           "%ld " // priority %ld (18)
-           "%ld " // nice %ld (19)
-           "%*d %*d %*d "
-           "%" SCNu64 // vsize %lu (23)
-           "%" SCNu64, // rss %ld (24)
-           &proc->state,
-           &proc->utime,
-           &proc->stime,
-           &pr,
-           &proc->ni,
-           &proc->vss,
-           &proc->rss);
-
-    // Translate the PR field.
-    if (pr < -9) strcpy(proc->pr, "RT");
-    else snprintf(proc->pr, sizeof(proc->pr), "%ld", pr);
-
-    return 0;
-}
-
-static void add_proc(int proc_num, struct proc_info *proc) {
-    int i;
-
-    if (proc_num >= num_new_procs) {
-        new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
-        if (!new_procs) die("Could not expand procs array.\n");
-        for (i = num_new_procs; i < 2 * num_new_procs; i++)
-            new_procs[i] = NULL;
-        num_new_procs = 2 * num_new_procs;
-    }
-    new_procs[proc_num] = proc;
-}
-
-static int read_cmdline(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char line[MAX_LINE];
-
-    line[0] = '\0';
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    fgets(line, MAX_LINE, file);
-    fclose(file);
-    if (strlen(line) > 0) {
-        strncpy(proc->name, line, PROC_NAME_LEN);
-        proc->name[PROC_NAME_LEN-1] = 0;
-    } else
-        proc->name[0] = 0;
-    return 0;
-}
-
-static void read_policy(int pid, struct proc_info *proc) {
-    SchedPolicy p;
-    if (get_sched_policy(pid, &p) < 0)
-        strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
-    else {
-        strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
-        proc->policy[2] = '\0';
-    }
-}
-
-static int read_status(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char line[MAX_LINE];
-    unsigned int uid, gid;
-
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    while (fgets(line, MAX_LINE, file)) {
-        sscanf(line, "Uid: %u", &uid);
-        sscanf(line, "Gid: %u", &gid);
-    }
-    fclose(file);
-    proc->uid = uid; proc->gid = gid;
-    return 0;
-}
-
-static void print_procs(void) {
-    static int call = 0;
-    int i;
-    struct proc_info *old_proc, *proc;
-    long unsigned total_delta_time;
-
-    for (i = 0; i < num_new_procs; i++) {
-        if (new_procs[i]) {
-            old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
-            if (old_proc) {
-                new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
-                new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
-            } else {
-                new_procs[i]->delta_utime = 0;
-                new_procs[i]->delta_stime = 0;
-            }
-            new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
-        }
-    }
-
-    total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
-                        + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
-                     - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
-                        + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
-
-    qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
-
-    if (call++ > 0) printf("\n\n\n");
-    printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
-            ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
-            ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
-            ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
-            ((new_cpu.irqtime + new_cpu.sirqtime)
-                    - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
-    printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
-            new_cpu.utime - old_cpu.utime,
-            new_cpu.ntime - old_cpu.ntime,
-            new_cpu.stime - old_cpu.stime,
-            new_cpu.itime - old_cpu.itime,
-            new_cpu.iowtime - old_cpu.iowtime,
-            new_cpu.irqtime - old_cpu.irqtime,
-            new_cpu.sirqtime - old_cpu.sirqtime,
-            total_delta_time);
-    printf("\n");
-    if (!threads)
-        printf("%5s %-8s %2s %3s %4s %1s %5s %7s %7s %3s %s\n", "PID", "USER", "PR", "NI", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "Name");
-    else
-        printf("%5s %5s %-8s %2s %3s %4s %1s %7s %7s %3s %-15s %s\n", "PID", "TID", "USER", "PR", "NI", "CPU%", "S", "VSS", "RSS", "PCY", "Thread", "Proc");
-
-    for (i = 0; i < num_new_procs; i++) {
-        proc = new_procs[i];
-
-        if (!proc || (max_procs && (i >= max_procs)))
-            break;
-        struct passwd* user = getpwuid(proc->uid);
-        char user_buf[20];
-        char* user_str;
-        if (user && user->pw_name) {
-            user_str = user->pw_name;
-        } else {
-            snprintf(user_buf, 20, "%d", proc->uid);
-            user_str = user_buf;
-        }
-        if (!threads) {
-            printf("%5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %5d %6" PRIu64 "K %6" PRIu64 "K %3s %s\n",
-                   proc->pid, user_str, proc->pr, proc->ni,
-                   proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
-                   proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
-                   proc->name[0] != 0 ? proc->name : proc->tname);
-        } else {
-            printf("%5d %5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %6" PRIu64 "K %6" PRIu64 "K %3s %-15s %s\n",
-                   proc->pid, proc->tid, user_str, proc->pr, proc->ni,
-                   proc->delta_time * 100 / total_delta_time, proc->state,
-                   proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
-                   proc->tname, proc->name);
-        }
-    }
-}
-
-static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
-    int i;
-
-    for (i = 0; i < num_old_procs; i++)
-        if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
-            return old_procs[i];
-
-    return NULL;
-}
-
-static void free_old_procs(void) {
-    int i;
-
-    for (i = 0; i < num_old_procs; i++)
-        if (old_procs[i])
-            free_proc(old_procs[i]);
-
-    free(old_procs);
-}
-
-static int proc_cpu_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->delta_time, pb->delta_time);
-}
-
-static int proc_vss_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->vss, pb->vss);
-}
-
-static int proc_rss_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->rss, pb->rss);
-}
-
-static int proc_thr_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->num_threads, pb->num_threads);
-}
-
-static int numcmp(long long a, long long b) {
-    if (a < b) return -1;
-    if (a > b) return 1;
-    return 0;
-}
-
-static void usage(char *cmd) {
-    fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
-                    "    -m num  Maximum number of processes to display.\n"
-                    "    -n num  Updates to show before exiting.\n"
-                    "    -d num  Seconds to wait between updates.\n"
-                    "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
-                    "    -H      Show threads instead of processes.\n"
-                    "    -h      Display this help screen.\n",
-        cmd);
-}
diff --git a/toolbox/upstream-netbsd/include/util.h b/toolbox/upstream-netbsd/include/util.h
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/toolbox/upstream-netbsd/include/util.h
diff --git a/trusty/gatekeeper/Android.mk b/trusty/gatekeeper/Android.mk
index 13e9a09..3982c8f 100644
--- a/trusty/gatekeeper/Android.mk
+++ b/trusty/gatekeeper/Android.mk
@@ -43,8 +43,4 @@
 
 LOCAL_MODULE_TAGS := optional
 
-# Symlink gatekeeper.trusty.so -> gatekeeper.<device>.so so libhardware can find it.
-LOCAL_POST_INSTALL_CMD = \
-    $(hide) ln -sf $(notdir $(LOCAL_INSTALLED_MODULE)) $(dir $(LOCAL_INSTALLED_MODULE))gatekeeper.$(TARGET_DEVICE).so
-
 include $(BUILD_SHARED_LIBRARY)
diff --git a/trusty/gatekeeper/trusty_gatekeeper.cpp b/trusty/gatekeeper/trusty_gatekeeper.cpp
index d24f44f..b3fbfa9 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.cpp
+++ b/trusty/gatekeeper/trusty_gatekeeper.cpp
@@ -14,18 +14,20 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "TrustyGateKeeper"
+
+#include <assert.h>
 #include <errno.h>
 #include <stdio.h>
-#include <assert.h>
+
 #include <type_traits>
 
+#include <log/log.h>
+
 #include "trusty_gatekeeper.h"
 #include "trusty_gatekeeper_ipc.h"
 #include "gatekeeper_ipc.h"
 
-#define LOG_TAG "TrustyGateKeeper"
-#include <cutils/log.h>
-
 namespace gatekeeper {
 
 const uint32_t SEND_BUF_SIZE = 8192;
diff --git a/trusty/gatekeeper/trusty_gatekeeper.h b/trusty/gatekeeper/trusty_gatekeeper.h
index 82108dc..2becc49 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.h
+++ b/trusty/gatekeeper/trusty_gatekeeper.h
@@ -27,7 +27,7 @@
 class TrustyGateKeeperDevice {
     public:
 
-    TrustyGateKeeperDevice(const hw_module_t* module);
+    explicit TrustyGateKeeperDevice(const hw_module_t* module);
     ~TrustyGateKeeperDevice();
 
     hw_device_t* hw_device();
diff --git a/trusty/gatekeeper/trusty_gatekeeper_ipc.c b/trusty/gatekeeper/trusty_gatekeeper_ipc.c
index a1c319e..f67944b 100644
--- a/trusty/gatekeeper/trusty_gatekeeper_ipc.c
+++ b/trusty/gatekeeper/trusty_gatekeeper_ipc.c
@@ -14,12 +14,15 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "TrustyGateKeeper"
+
 #include <errno.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
 
-#define LOG_TAG "TrustyGateKeeper"
-#include <cutils/log.h>
+#include <log/log.h>
 #include <trusty/tipc.h>
 
 #include "trusty_gatekeeper_ipc.h"
diff --git a/trusty/keymaster/Android.mk b/trusty/keymaster/Android.mk
new file mode 100644
index 0000000..0ebf52d
--- /dev/null
+++ b/trusty/keymaster/Android.mk
@@ -0,0 +1,67 @@
+#
+# 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.
+#
+
+# WARNING: Everything listed here will be built on ALL platforms,
+# including x86, the emulator, and the SDK.  Modules must be uniquely
+# named (liblights.panda), and must build everywhere, or limit themselves
+# to only building on ARM if they include assembly. Individual makefiles
+# are responsible for having their own logic, for fine-grained control.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+###
+# trusty_keymaster is a binary used only for on-device testing.  It
+# runs Trusty Keymaster through a basic set of operations with RSA
+# and ECDSA keys.
+###
+LOCAL_MODULE := trusty_keymaster_tipc
+LOCAL_SRC_FILES := \
+	trusty_keymaster_device.cpp \
+	trusty_keymaster_ipc.c \
+	trusty_keymaster_main.cpp
+LOCAL_SHARED_LIBRARIES := \
+	libcrypto \
+	libcutils \
+	libkeymaster1 \
+	libtrusty \
+	libkeymaster_messages \
+	liblog
+
+include $(BUILD_EXECUTABLE)
+
+###
+# keystore.trusty is the HAL used by keystore on Trusty devices.
+##
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := keystore.trusty
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := module.cpp \
+	trusty_keymaster_ipc.c \
+	trusty_keymaster_device.cpp
+LOCAL_CLFAGS = -fvisibility=hidden -Wall -Werror
+LOCAL_SHARED_LIBRARIES := \
+	libcrypto \
+	libkeymaster_messages \
+	libtrusty \
+	liblog \
+	libcutils
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/trusty/keymaster/Makefile b/trusty/keymaster/Makefile
new file mode 100644
index 0000000..f575381
--- /dev/null
+++ b/trusty/keymaster/Makefile
@@ -0,0 +1,199 @@
+#####
+# Local unit test Makefile
+#
+# This makefile builds and runs the trusty_keymaster unit tests locally on the development
+# machine, not on an Android device.
+#
+# To build and run these tests, one pre-requisite must be manually installed: BoringSSL.
+# This Makefile expects to find BoringSSL in a directory adjacent to $ANDROID_BUILD_TOP.
+# To get and build it, first install the Ninja build tool (e.g. apt-get install
+# ninja-build), then do:
+#
+# cd $ANDROID_BUILD_TOP/..
+# git clone https://boringssl.googlesource.com/boringssl
+# cd boringssl
+# mdkir build
+# cd build
+# cmake -GNinja ..
+# ninja
+#
+# Then return to $ANDROID_BUILD_TOP/system/keymaster and run "make".
+#####
+
+BASE=../../../..
+SUBS=system/core \
+	system/keymaster \
+	hardware/libhardware \
+	external/gtest
+GTEST=$(BASE)/external/gtest
+KM=$(BASE)/system/keymaster
+
+INCLUDES=$(foreach dir,$(SUBS),-I $(BASE)/$(dir)/include) \
+	-I $(BASE)/libnativehelper/include/nativehelper \
+	-I ../tipc/include \
+	-I $(BASE)/system/keymaster \
+	-I $(GTEST) \
+	-I$(BASE)/../boringssl/include
+
+ifdef USE_CLANG
+CC=/usr/bin/clang
+CXX=/usr/bin/clang
+CLANG_TEST_DEFINE=-DKEYMASTER_CLANG_TEST_BUILD
+COMPILER_SPECIFIC_ARGS=-std=c++11 $(CLANG_TEST_DEFINE)
+else
+COMPILER_SPECIFIC_ARGS=-std=c++0x -fprofile-arcs
+endif
+
+CPPFLAGS=$(INCLUDES) -g -O0 -MD
+CXXFLAGS=-Wall -Werror -Wno-unused -Winit-self -Wpointer-arith	-Wunused-parameter \
+	-Wmissing-declarations -ftest-coverage \
+	-Wno-deprecated-declarations -fno-exceptions -DKEYMASTER_NAME_TAGS \
+	$(COMPILER_SPECIFIC_ARGS)
+LDLIBS=-L$(BASE)/../boringssl/build/crypto -lcrypto -lpthread -lstdc++
+
+CPPSRCS=\
+	$(KM)/aead_mode_operation.cpp \
+	$(KM)/aes_key.cpp \
+	$(KM)/aes_operation.cpp \
+	$(KM)/android_keymaster.cpp \
+	$(KM)/android_keymaster_messages.cpp \
+	$(KM)/android_keymaster_messages_test.cpp \
+	$(KM)/android_keymaster_test.cpp \
+	$(KM)/android_keymaster_test_utils.cpp \
+	$(KM)/android_keymaster_utils.cpp \
+	$(KM)/asymmetric_key.cpp \
+	$(KM)/auth_encrypted_key_blob.cpp \
+	$(KM)/auth_encrypted_key_blob.cpp \
+	$(KM)/authorization_set.cpp \
+	$(KM)/authorization_set_test.cpp \
+	$(KM)/ec_key.cpp \
+	$(KM)/ec_keymaster0_key.cpp \
+	$(KM)/ecdsa_operation.cpp \
+	$(KM)/hmac_key.cpp \
+	$(KM)/hmac_operation.cpp \
+	$(KM)/integrity_assured_key_blob.cpp \
+	$(KM)/key.cpp \
+	$(KM)/key_blob_test.cpp \
+	$(KM)/keymaster0_engine.cpp \
+	$(KM)/logger.cpp \
+	$(KM)/ocb_utils.cpp \
+	$(KM)/openssl_err.cpp \
+	$(KM)/openssl_utils.cpp \
+	$(KM)/operation.cpp \
+	$(KM)/operation_table.cpp \
+	$(KM)/rsa_key.cpp \
+	$(KM)/rsa_keymaster0_key.cpp \
+	$(KM)/rsa_operation.cpp \
+	$(KM)/serializable.cpp \
+	$(KM)/soft_keymaster_context.cpp \
+	$(KM)/symmetric_key.cpp \
+	$(KM)/unencrypted_key_blob.cpp \
+	trusty_keymaster_device.cpp \
+	trusty_keymaster_device_test.cpp
+CCSRCS=$(GTEST)/src/gtest-all.cc
+CSRCS=ocb.c
+
+OBJS=$(CPPSRCS:.cpp=.o) $(CCSRCS:.cc=.o) $(CSRCS:.c=.o)
+DEPS=$(CPPSRCS:.cpp=.d) $(CCSRCS:.cc=.d) $(CSRCS:.c=.d)
+GCDA=$(CPPSRCS:.cpp=.gcda) $(CCSRCS:.cc=.gcda) $(CSRCS:.c=.gcda)
+GCNO=$(CPPSRCS:.cpp=.gcno) $(CCSRCS:.cc=.gcno) $(CSRCS:.c=.gcno)
+
+LINK.o=$(LINK.cc)
+
+BINARIES=trusty_keymaster_device_test
+
+ifdef TRUSTY
+BINARIES += trusty_keymaster_device_test
+endif # TRUSTY
+
+.PHONY: coverage memcheck massif clean run
+
+%.run: %
+	./$<
+	touch $@
+
+run: $(BINARIES:=.run)
+
+coverage: coverage.info
+	genhtml coverage.info --output-directory coverage
+
+coverage.info: run
+	lcov --capture --directory=. --output-file coverage.info
+
+%.coverage : %
+	$(MAKE) clean && $(MAKE) $<
+	./$<
+	lcov --capture --directory=. --output-file coverage.info
+	genhtml coverage.info --output-directory coverage
+
+#UNINIT_OPTS=--track-origins=yes
+UNINIT_OPTS=--undef-value-errors=no
+
+MEMCHECK_OPTS=--leak-check=full \
+	--show-reachable=yes \
+	--vgdb=full \
+	$(UNINIT_OPTS) \
+	--error-exitcode=1
+
+MASSIF_OPTS=--tool=massif \
+	--stacks=yes
+
+%.memcheck : %
+	valgrind $(MEMCHECK_OPTS) ./$< && \
+	touch $@
+
+%.massif : %
+	valgrind $(MASSIF_OPTS) --massif-out-file=$@ ./$<
+
+memcheck: $(BINARIES:=.memcheck)
+
+massif: $(BINARIES:=.massif)
+
+trusty_keymaster_device_test: trusty_keymaster_device_test.o \
+	trusty_keymaster_device.o \
+	$(KM)/aead_mode_operation.o \
+	$(KM)/aes_key.o \
+	$(KM)/aes_operation.o \
+	$(KM)/android_keymaster.o \
+	$(KM)/android_keymaster_messages.o \
+	$(KM)/android_keymaster_test_utils.o \
+	$(KM)/android_keymaster_utils.o \
+	$(KM)/asymmetric_key.o \
+	$(KM)/auth_encrypted_key_blob.o \
+	$(KM)/auth_encrypted_key_blob.o \
+	$(KM)/authorization_set.o \
+	$(KM)/ec_key.o \
+	$(KM)/ec_keymaster0_key.cpp \
+	$(KM)/ecdsa_operation.o \
+	$(KM)/hmac_key.o \
+	$(KM)/hmac_operation.o \
+	$(KM)/integrity_assured_key_blob.o \
+	$(KM)/key.o \
+	$(KM)/keymaster0_engine.o \
+	$(KM)/logger.o \
+	$(KM)/ocb.o \
+	$(KM)/ocb_utils.o \
+	$(KM)/openssl_err.o \
+	$(KM)/openssl_utils.o \
+	$(KM)/operation.o \
+	$(KM)/operation_table.o \
+	$(KM)/rsa_key.o \
+	$(KM)/rsa_keymaster0_key.o \
+	$(KM)/rsa_operation.o \
+	$(KM)/serializable.o \
+	$(KM)/soft_keymaster_context.o \
+	$(KM)/symmetric_key.o \
+	$(GTEST)/src/gtest-all.o
+
+$(GTEST)/src/gtest-all.o: CXXFLAGS:=$(subst -Wmissing-declarations,,$(CXXFLAGS))
+ocb.o: CFLAGS=$(CLANG_TEST_DEFINE)
+
+clean:
+	rm -f $(OBJS) $(DEPS) $(GCDA) $(GCNO) $(BINARIES) \
+		$(BINARIES:=.run) $(BINARIES:=.memcheck) $(BINARIES:=.massif) \
+		coverage.info
+	rm -rf coverage
+
+-include $(CPPSRCS:.cpp=.d)
+-include $(CCSRCS:.cc=.d)
+
diff --git a/trusty/keymaster/keymaster_ipc.h b/trusty/keymaster/keymaster_ipc.h
new file mode 100644
index 0000000..48fa53d
--- /dev/null
+++ b/trusty/keymaster/keymaster_ipc.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#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,
+
+    KM_GENERATE_KEY                 = (0 << KEYMASTER_REQ_SHIFT),
+    KM_BEGIN_OPERATION              = (1 << KEYMASTER_REQ_SHIFT),
+    KM_UPDATE_OPERATION             = (2 << KEYMASTER_REQ_SHIFT),
+    KM_FINISH_OPERATION             = (3 << KEYMASTER_REQ_SHIFT),
+    KM_ABORT_OPERATION              = (4 << KEYMASTER_REQ_SHIFT),
+    KM_IMPORT_KEY                   = (5 << KEYMASTER_REQ_SHIFT),
+    KM_EXPORT_KEY                   = (6 << KEYMASTER_REQ_SHIFT),
+    KM_GET_VERSION                  = (7 << KEYMASTER_REQ_SHIFT),
+    KM_ADD_RNG_ENTROPY              = (8 << KEYMASTER_REQ_SHIFT),
+    KM_GET_SUPPORTED_ALGORITHMS     = (9 << KEYMASTER_REQ_SHIFT),
+    KM_GET_SUPPORTED_BLOCK_MODES    = (10 << KEYMASTER_REQ_SHIFT),
+    KM_GET_SUPPORTED_PADDING_MODES  = (11 << KEYMASTER_REQ_SHIFT),
+    KM_GET_SUPPORTED_DIGESTS        = (12 << KEYMASTER_REQ_SHIFT),
+    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),
+};
+
+#ifdef __ANDROID__
+
+/**
+ * keymaster_message - Serial header for communicating with KM server
+ * @cmd: the command, one of keymaster_command.
+ * @payload: start of the serialized command specific payload
+ */
+struct keymaster_message {
+	uint32_t cmd;
+	uint8_t payload[0];
+};
+
+#endif
diff --git a/trusty/keymaster/module.cpp b/trusty/keymaster/module.cpp
new file mode 100644
index 0000000..81597d9
--- /dev/null
+++ b/trusty/keymaster/module.cpp
@@ -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.
+ */
+#include <errno.h>
+#include <string.h>
+
+#include <hardware/hardware.h>
+#include <hardware/keymaster0.h>
+
+#include "trusty_keymaster_device.h"
+
+using keymaster::TrustyKeymasterDevice;
+
+/*
+ * 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)
+        return -EINVAL;
+
+    TrustyKeymasterDevice* dev = new TrustyKeymasterDevice(module);
+    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.
+    return 0;
+}
+
+static struct hw_module_methods_t keystore_module_methods = {
+    .open = trusty_keymaster_open,
+};
+
+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 = {},
+        },
+};
diff --git a/trusty/keymaster/trusty_keymaster_device.cpp b/trusty/keymaster/trusty_keymaster_device.cpp
new file mode 100644
index 0000000..1368f88
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_device.cpp
@@ -0,0 +1,534 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "TrustyKeymaster"
+
+#include <assert.h>
+#include <openssl/evp.h>
+#include <openssl/x509.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <type_traits>
+
+#include <hardware/keymaster0.h>
+#include <keymaster/authorization_set.h>
+#include <log/log.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;
+
+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 -ECANCELED:
+        return KM_ERROR_OPERATION_CANCELLED;
+
+    case -ENODEV:
+        return KM_ERROR_UNIMPLEMENTED;
+
+    case -ENOMEM:
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+
+    case -EBUSY:
+        return KM_ERROR_SECURE_HW_BUSY;
+
+    case -EIO:
+        return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
+
+    case -EOVERFLOW:
+        return KM_ERROR_INVALID_INPUT_LENGTH;
+
+    default:
+        return KM_ERROR_UNKNOWN_ERROR;
+    }
+}
+
+TrustyKeymasterDevice::TrustyKeymasterDevice(const hw_module_t* module) {
+    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");
+    static_assert(offsetof(TrustyKeymasterDevice, device_.common) == 0,
+                  "common must be the first member of keymaster_device");
+
+    ALOGI("Creating device");
+    ALOGD("Device address: %p", this);
+
+    memset(&device_, 0, sizeof(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_.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;
+
+    int rc = trusty_keymaster_connect();
+    error_ = translate_error(rc);
+    if (rc < 0) {
+        ALOGE("failed to connect to keymaster (%d)", rc);
+        return;
+    }
+
+    GetVersionRequest version_request;
+    GetVersionResponse version_response;
+    error_ = Send(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;
+    }
+    message_version_ = MessageVersion(version_response.major_ver, version_response.minor_ver,
+                                      version_response.subminor_ver);
+    if (message_version_ < 0) {
+        // Can't translate version?  Keymaster implementation must be newer.
+        ALOGE("Keymaster version %d.%d.%d not supported.", version_response.major_ver,
+              version_response.minor_ver, version_response.subminor_ver);
+        error_ = KM_ERROR_VERSION_MISMATCH;
+    }
+}
+
+TrustyKeymasterDevice::~TrustyKeymasterDevice() {
+    trusty_keymaster_disconnect();
+}
+
+const uint64_t HUNDRED_YEARS = 1000LL * 60 * 60 * 24 * 365 * 100;
+
+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");
+
+    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;
+    }
+
+    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;
+    }
+
+    GenerateKeyResponse rsp(message_version_);
+    ALOGD("Sending generate request");
+    keymaster_error_t err = Send(req, &rsp);
+    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); }
+};
+
+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)
+        return error_;
+
+    if (!key)
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+
+    if (!key_blob || !key_blob_length)
+        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.SetKeyMaterial(key, key_length);
+    request.key_format = KM_KEY_FORMAT_PKCS8;
+    ImportKeyResponse response(message_version_);
+    err = Send(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);
+
+    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");
+        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;
+    }
+
+    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_;
+
+    ExportKeyRequest request(message_version_);
+    request.SetKeyMaterial(key_blob, key_blob_length);
+    request.key_format = KM_KEY_FORMAT_X509;
+    ExportKeyResponse response(message_version_);
+    keymaster_error_t err = Send(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);
+
+    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)
+        return error_;
+
+    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);
+    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;
+    }
+
+    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;
+    }
+
+    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)
+        return error_;
+
+    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;
+
+    BeginOperationResponse begin_response(message_version_);
+    err = Send(begin_request, &begin_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;
+
+    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;
+}
+
+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 */
+int TrustyKeymasterDevice::close_device(hw_device_t* dev) {
+    delete reinterpret_cast<TrustyKeymasterDevice*>(dev);
+    return 0;
+}
+
+/* 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);
+}
+
+/* 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);
+}
+
+/* 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);
+}
+
+/* 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);
+}
+
+/* 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::Send(uint32_t command, const Serializable& req,
+                                              KeymasterResponse* rsp) {
+    uint32_t req_size = req.SerializedSize();
+    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);
+
+    // Send it
+    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());
+    int rc = trusty_keymaster_call(command, send_buf, req_size, recv_buf, &rsp_size);
+    if (rc < 0) {
+        ALOGE("tipc error: %d\n", rc);
+        // TODO(swillden): Distinguish permanent from transient errors and set error_ appropriately.
+        return translate_error(rc);
+    } else {
+        ALOGV("Received %d byte response\n", rsp_size);
+    }
+
+    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;
+    } else if (rsp->error != KM_ERROR_OK) {
+        ALOGE("Response of size %d contained error code %d\n", (int)rsp_size, (int)rsp->error);
+        return rsp->error;
+    }
+    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
new file mode 100644
index 0000000..68cf40c
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_device.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
+#define EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
+
+#include <hardware/keymaster0.h>
+
+#include <keymaster/android_keymaster_messages.h>
+
+#include "keymaster_ipc.h"
+
+namespace keymaster {
+
+/**
+ * Software OpenSSL-based 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
+ * no data members which aren't standard layout), and device_ must be the first data member.
+ * Assertions in the constructor validate compliance with those constraints.
+ */
+class TrustyKeymasterDevice {
+  public:
+    /*
+     * These are the only symbols that will be exported by libtrustykeymaster.  All functionality
+     * can be reached via the function pointers in device_.
+     */
+    __attribute__((visibility("default"))) explicit TrustyKeymasterDevice(const hw_module_t* module);
+    __attribute__((visibility("default"))) hw_device_t* hw_device();
+
+    ~TrustyKeymasterDevice();
+
+    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);
+
+  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);
+
+    keymaster0_device_t device_;
+    keymaster_error_t error_;
+    int32_t message_version_;
+};
+
+}  // namespace keymaster
+
+#endif  // EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
diff --git a/trusty/keymaster/trusty_keymaster_device_test.cpp b/trusty/keymaster/trusty_keymaster_device_test.cpp
new file mode 100644
index 0000000..3bb5430
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_device_test.cpp
@@ -0,0 +1,562 @@
+/*
+ * 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.
+ */
+#include <algorithm>
+#include <fstream>
+
+#include <UniquePtr.h>
+#include <gtest/gtest.h>
+#include <openssl/engine.h>
+
+#include <hardware/keymaster0.h>
+
+#include <keymaster/android_keymaster.h>
+#include <keymaster/android_keymaster_messages.h>
+#include <keymaster/android_keymaster_utils.h>
+#include <keymaster/keymaster_tags.h>
+#include <keymaster/soft_keymaster_context.h>
+
+#include "android_keymaster_test_utils.h"
+#include "trusty_keymaster_device.h"
+#include "openssl_utils.h"
+
+using std::string;
+using std::ifstream;
+using std::istreambuf_iterator;
+
+static keymaster::AndroidKeymaster *impl_ =  nullptr;
+
+extern "C" {
+int __android_log_print();
+}
+
+int __android_log_print() {
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    int result = RUN_ALL_TESTS();
+    // Clean up stuff OpenSSL leaves around, so Valgrind doesn't complain.
+    CRYPTO_cleanup_all_ex_data();
+    ERR_free_strings();
+    return result;
+}
+
+int trusty_keymaster_connect() {
+    impl_ = new keymaster::AndroidKeymaster(new keymaster::SoftKeymasterContext(nullptr), 16);
+}
+
+void trusty_keymaster_disconnect() {
+    delete static_cast<keymaster::AndroidKeymaster*>(priv_);
+}
+
+template <typename Req, typename Rsp>
+static int fake_call(keymaster::AndroidKeymaster* device,
+                       void (keymaster::AndroidKeymaster::*method)(const Req&, Rsp*), void* in_buf,
+                       uint32_t in_size, void* out_buf, uint32_t* out_size) {
+    Req req;
+    const uint8_t* in = static_cast<uint8_t*>(in_buf);
+    req.Deserialize(&in, in + in_size);
+    Rsp rsp;
+    (device->*method)(req, &rsp);
+
+    *out_size = rsp.SerializedSize();
+    uint8_t* out = static_cast<uint8_t*>(out_buf);
+    rsp.Serialize(out, out + *out_size);
+    return 0;
+}
+
+int trusty_keymaster_call(uint32_t cmd, void* in_buf, uint32_t in_size, void* out_buf,
+                       uint32_t* out_size) {
+    switch (cmd) {
+    case KM_GENERATE_KEY:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::GenerateKey, in_buf, in_size,
+                           out_buf, out_size);
+    case KM_BEGIN_OPERATION:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::BeginOperation, in_buf, in_size,
+                           out_buf, out_size);
+    case KM_UPDATE_OPERATION:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::UpdateOperation, in_buf, in_size,
+                           out_buf, out_size);
+    case KM_FINISH_OPERATION:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::FinishOperation, in_buf, in_size,
+                           out_buf, out_size);
+    case KM_IMPORT_KEY:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::ImportKey, in_buf, in_size, out_buf,
+                           out_size);
+    case KM_EXPORT_KEY:
+        return fake_call(impl_, &keymaster::AndroidKeymaster::ExportKey, in_buf, in_size, out_buf,
+                           out_size);
+    }
+    return -EINVAL;
+
+}
+
+namespace keymaster {
+namespace test {
+
+class TrustyKeymasterTest : public testing::Test {
+  protected:
+    TrustyKeymasterTest() : device(NULL) {}
+
+    keymaster_rsa_keygen_params_t build_rsa_params() {
+        keymaster_rsa_keygen_params_t rsa_params;
+        rsa_params.public_exponent = 65537;
+        rsa_params.modulus_size = 2048;
+        return rsa_params;
+    }
+
+    uint8_t* build_message(size_t length) {
+        uint8_t* msg = new uint8_t[length];
+        memset(msg, 'a', length);
+        return msg;
+    }
+
+    size_t dsa_message_len(const keymaster_dsa_keygen_params_t& params) {
+        switch (params.key_size) {
+        case 256:
+        case 1024:
+            return 48;
+        case 2048:
+        case 4096:
+            return 72;
+        default:
+            // Oops.
+            return 0;
+        }
+    }
+
+    TrustyKeymasterDevice device;
+};
+
+class Malloc_Delete {
+  public:
+    Malloc_Delete(void* p) : p_(p) {}
+    ~Malloc_Delete() { free(p_); }
+
+  private:
+    void* p_;
+};
+
+typedef TrustyKeymasterTest KeyGenTest;
+TEST_F(KeyGenTest, RsaSuccess) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+}
+
+TEST_F(KeyGenTest, EcdsaSuccess) {
+    keymaster_ec_keygen_params_t ec_params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &ec_params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+}
+
+typedef TrustyKeymasterTest SigningTest;
+TEST_F(SigningTest, RsaSuccess) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(message_len, siglen);
+}
+
+TEST_F(SigningTest, RsaShortMessage) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8 - 1;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, device.sign_data(&sig_params, ptr, size, message.get(),
+                                                       message_len, &signature, &siglen));
+}
+
+TEST_F(SigningTest, RsaLongMessage) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8 + 1;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, device.sign_data(&sig_params, ptr, size, message.get(),
+                                                       message_len, &signature, &siglen));
+}
+
+TEST_F(SigningTest, EcdsaSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    uint8_t message[] = "12345678901234567890123456789012";
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
+                                            array_size(message) - 1, &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_GT(siglen, 69U);
+    EXPECT_LT(siglen, 73U);
+}
+
+TEST_F(SigningTest, EcdsaEmptyMessageSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    uint8_t message[] = "";
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
+                                            array_size(message) - 1, &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_GT(siglen, 69U);
+    EXPECT_LT(siglen, 73U);
+}
+
+TEST_F(SigningTest, EcdsaLargeMessageSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    size_t message_len = 1024 * 7;
+    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    // contents of message don't matter.
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_GT(siglen, 69U);
+    EXPECT_LT(siglen, 73U);
+}
+
+typedef TrustyKeymasterTest VerificationTest;
+TEST_F(VerificationTest, RsaSuccess) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message.get(), message_len,
+                                              signature, siglen));
+}
+
+TEST_F(VerificationTest, RsaBadSignature) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+
+    Malloc_Delete sig_deleter(signature);
+    signature[siglen / 2]++;
+    EXPECT_EQ(
+        KM_ERROR_VERIFICATION_FAILED,
+        device.verify_data(&sig_params, ptr, size, message.get(), message_len, signature, siglen));
+}
+
+TEST_F(VerificationTest, RsaBadMessage) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    message[0]++;
+    EXPECT_EQ(
+        KM_ERROR_VERIFICATION_FAILED,
+        device.verify_data(&sig_params, ptr, size, message.get(), message_len, signature, siglen));
+}
+
+TEST_F(VerificationTest, RsaShortMessage) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH,
+              device.verify_data(&sig_params, ptr, size, message.get(), message_len - 1, signature,
+                                 siglen));
+}
+
+TEST_F(VerificationTest, RsaLongMessage) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len + 1));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH,
+              device.verify_data(&sig_params, ptr, size, message.get(), message_len + 1, signature,
+                                 siglen));
+}
+
+TEST_F(VerificationTest, EcdsaSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    uint8_t message[] = "12345678901234567890123456789012";
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
+                                            array_size(message) - 1, &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message,
+                                              array_size(message) - 1, signature, siglen));
+}
+
+TEST_F(VerificationTest, EcdsaLargeMessageSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    size_t message_len = 1024 * 7;
+    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    // contents of message don't matter.
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message.get(), message_len,
+                                              signature, siglen));
+}
+
+static string read_file(const string& file_name) {
+    ifstream file_stream(file_name, std::ios::binary);
+    istreambuf_iterator<char> file_begin(file_stream);
+    istreambuf_iterator<char> file_end;
+    return string(file_begin, file_end);
+}
+
+typedef TrustyKeymasterTest ImportKeyTest;
+TEST_F(ImportKeyTest, RsaSuccess) {
+    string pk8_key = read_file("../../../../system/keymaster/rsa_privkey_pk8.der");
+    ASSERT_EQ(633U, pk8_key.size());
+
+    uint8_t* key = NULL;
+    size_t size;
+    ASSERT_EQ(KM_ERROR_OK, device.import_keypair(reinterpret_cast<const uint8_t*>(pk8_key.data()),
+                                                 pk8_key.size(), &key, &size));
+    Malloc_Delete key_deleter(key);
+
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_size = 1024 /* key size */ / 8;
+    UniquePtr<uint8_t[]> message(new uint8_t[message_size]);
+    memset(message.get(), 'a', message_size);
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message.get(), message_size,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message.get(), message_size,
+                                              signature, siglen));
+}
+
+TEST_F(ImportKeyTest, EcdsaSuccess) {
+    string pk8_key = read_file("../../../../system/keymaster/ec_privkey_pk8.der");
+    ASSERT_EQ(138U, pk8_key.size());
+
+    uint8_t* key = NULL;
+    size_t size;
+    ASSERT_EQ(KM_ERROR_OK, device.import_keypair(reinterpret_cast<const uint8_t*>(pk8_key.data()),
+                                                 pk8_key.size(), &key, &size));
+    Malloc_Delete key_deleter(key);
+
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    uint8_t message[] = "12345678901234567890123456789012";
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message,
+                                            array_size(message) - 1, &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message,
+                                              array_size(message) - 1, signature, siglen));
+}
+
+struct EVP_PKEY_CTX_Delete {
+    void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
+};
+
+static void VerifySignature(const uint8_t* key, size_t key_len, const uint8_t* signature,
+                            size_t signature_len, const uint8_t* message, size_t message_len) {
+    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(d2i_PUBKEY(NULL, &key, key_len));
+    ASSERT_TRUE(pkey.get() != NULL);
+    UniquePtr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
+    ASSERT_TRUE(ctx.get() != NULL);
+    ASSERT_EQ(1, EVP_PKEY_verify_init(ctx.get()));
+    if (EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA)
+        ASSERT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING));
+    EXPECT_EQ(1, EVP_PKEY_verify(ctx.get(), signature, signature_len, message, message_len));
+}
+
+typedef TrustyKeymasterTest ExportKeyTest;
+TEST_F(ExportKeyTest, RsaSuccess) {
+    keymaster_rsa_keygen_params_t params = build_rsa_params();
+    uint8_t* ptr = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(ptr);
+
+    uint8_t* exported;
+    size_t exported_size;
+    EXPECT_EQ(KM_ERROR_OK, device.get_keypair_public(ptr, size, &exported, &exported_size));
+    Malloc_Delete exported_deleter(exported);
+
+    // Sign a message so we can verify it with the exported pubkey.
+    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
+    size_t message_len = params.modulus_size / 8;
+    UniquePtr<uint8_t[]> message(build_message(message_len));
+    uint8_t* signature;
+    size_t siglen;
+    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
+                                            &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(message_len, siglen);
+    const uint8_t* tmp = exported;
+
+    VerifySignature(exported, exported_size, signature, siglen, message.get(), message_len);
+}
+
+typedef TrustyKeymasterTest ExportKeyTest;
+TEST_F(ExportKeyTest, EcdsaSuccess) {
+    keymaster_ec_keygen_params_t params = {256};
+    uint8_t* key = NULL;
+    size_t size;
+    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &key, &size));
+    EXPECT_GT(size, 0U);
+    Malloc_Delete key_deleter(key);
+
+    uint8_t* exported;
+    size_t exported_size;
+    EXPECT_EQ(KM_ERROR_OK, device.get_keypair_public(key, size, &exported, &exported_size));
+    Malloc_Delete exported_deleter(exported);
+
+    // Sign a message so we can verify it with the exported pubkey.
+    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
+    uint8_t message[] = "12345678901234567890123456789012";
+    uint8_t* signature;
+    size_t siglen;
+    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message,
+                                            array_size(message) - 1, &signature, &siglen));
+    Malloc_Delete sig_deleter(signature);
+    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message,
+                                              array_size(message) - 1, signature, siglen));
+
+    VerifySignature(exported, exported_size, signature, siglen, message, array_size(message) - 1);
+}
+
+}  // namespace test
+}  // namespace keymaster
diff --git a/trusty/keymaster/trusty_keymaster_ipc.c b/trusty/keymaster/trusty_keymaster_ipc.c
new file mode 100644
index 0000000..88546af
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_ipc.c
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "TrustyKeymaster"
+
+// TODO: make this generic in libtrusty
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <log/log.h>
+#include <trusty/tipc.h>
+
+#include "trusty_keymaster_ipc.h"
+#include "keymaster_ipc.h"
+
+#define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
+
+static int handle_ = 0;
+
+int trusty_keymaster_connect() {
+    int rc = tipc_connect(TRUSTY_DEVICE_NAME, KEYMASTER_PORT);
+    if (rc < 0) {
+        return rc;
+    }
+
+    handle_ = rc;
+    return 0;
+}
+
+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);
+    msg->cmd = cmd;
+    memcpy(msg->payload, in, in_size);
+
+    ssize_t rc = write(handle_, msg, msg_size);
+    free(msg);
+
+    if (rc < 0) {
+        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));
+        return -errno;
+    }
+
+    if ((size_t) rc < sizeof(struct keymaster_message)) {
+        ALOGE("invalid response size (%d)\n", (int) rc);
+        return -EINVAL;
+    }
+
+    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);
+    return rc;
+}
+
+void trusty_keymaster_disconnect() {
+    if (handle_ != 0) {
+        tipc_close(handle_);
+    }
+}
+
diff --git a/trusty/keymaster/trusty_keymaster_ipc.h b/trusty/keymaster/trusty_keymaster_ipc.h
new file mode 100644
index 0000000..9785247
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_ipc.h
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+__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);
+void trusty_keymaster_disconnect(void);
+
+__END_DECLS
diff --git a/trusty/keymaster/trusty_keymaster_main.cpp b/trusty/keymaster/trusty_keymaster_main.cpp
new file mode 100644
index 0000000..7ed880e
--- /dev/null
+++ b/trusty/keymaster/trusty_keymaster_main.cpp
@@ -0,0 +1,368 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+
+#include <openssl/evp.h>
+#include <openssl/x509.h>
+
+#include "trusty_keymaster_device.h"
+
+using keymaster::TrustyKeymasterDevice;
+
+unsigned char rsa_privkey_pk8_der[] = {
+    0x30, 0x82, 0x02, 0x75, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+    0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x02, 0x5f, 0x30, 0x82, 0x02, 0x5b, 0x02, 0x01,
+    0x00, 0x02, 0x81, 0x81, 0x00, 0xc6, 0x09, 0x54, 0x09, 0x04, 0x7d, 0x86, 0x34, 0x81, 0x2d, 0x5a,
+    0x21, 0x81, 0x76, 0xe4, 0x5c, 0x41, 0xd6, 0x0a, 0x75, 0xb1, 0x39, 0x01, 0xf2, 0x34, 0x22, 0x6c,
+    0xff, 0xe7, 0x76, 0x52, 0x1c, 0x5a, 0x77, 0xb9, 0xe3, 0x89, 0x41, 0x7b, 0x71, 0xc0, 0xb6, 0xa4,
+    0x4d, 0x13, 0xaf, 0xe4, 0xe4, 0xa2, 0x80, 0x5d, 0x46, 0xc9, 0xda, 0x29, 0x35, 0xad, 0xb1, 0xff,
+    0x0c, 0x1f, 0x24, 0xea, 0x06, 0xe6, 0x2b, 0x20, 0xd7, 0x76, 0x43, 0x0a, 0x4d, 0x43, 0x51, 0x57,
+    0x23, 0x3c, 0x6f, 0x91, 0x67, 0x83, 0xc3, 0x0e, 0x31, 0x0f, 0xcb, 0xd8, 0x9b, 0x85, 0xc2, 0xd5,
+    0x67, 0x71, 0x16, 0x97, 0x85, 0xac, 0x12, 0xbc, 0xa2, 0x44, 0xab, 0xda, 0x72, 0xbf, 0xb1, 0x9f,
+    0xc4, 0x4d, 0x27, 0xc8, 0x1e, 0x1d, 0x92, 0xde, 0x28, 0x4f, 0x40, 0x61, 0xed, 0xfd, 0x99, 0x28,
+    0x07, 0x45, 0xea, 0x6d, 0x25, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x81, 0x80, 0x1b, 0xe0, 0xf0,
+    0x4d, 0x9c, 0xae, 0x37, 0x18, 0x69, 0x1f, 0x03, 0x53, 0x38, 0x30, 0x8e, 0x91, 0x56, 0x4b, 0x55,
+    0x89, 0x9f, 0xfb, 0x50, 0x84, 0xd2, 0x46, 0x0e, 0x66, 0x30, 0x25, 0x7e, 0x05, 0xb3, 0xce, 0xab,
+    0x02, 0x97, 0x2d, 0xfa, 0xbc, 0xd6, 0xce, 0x5f, 0x6e, 0xe2, 0x58, 0x9e, 0xb6, 0x79, 0x11, 0xed,
+    0x0f, 0xac, 0x16, 0xe4, 0x3a, 0x44, 0x4b, 0x8c, 0x86, 0x1e, 0x54, 0x4a, 0x05, 0x93, 0x36, 0x57,
+    0x72, 0xf8, 0xba, 0xf6, 0xb2, 0x2f, 0xc9, 0xe3, 0xc5, 0xf1, 0x02, 0x4b, 0x06, 0x3a, 0xc0, 0x80,
+    0xa7, 0xb2, 0x23, 0x4c, 0xf8, 0xae, 0xe8, 0xf6, 0xc4, 0x7b, 0xbf, 0x4f, 0xd3, 0xac, 0xe7, 0x24,
+    0x02, 0x90, 0xbe, 0xf1, 0x6c, 0x0b, 0x3f, 0x7f, 0x3c, 0xdd, 0x64, 0xce, 0x3a, 0xb5, 0x91, 0x2c,
+    0xf6, 0xe3, 0x2f, 0x39, 0xab, 0x18, 0x83, 0x58, 0xaf, 0xcc, 0xcd, 0x80, 0x81, 0x02, 0x41, 0x00,
+    0xe4, 0xb4, 0x9e, 0xf5, 0x0f, 0x76, 0x5d, 0x3b, 0x24, 0xdd, 0xe0, 0x1a, 0xce, 0xaa, 0xf1, 0x30,
+    0xf2, 0xc7, 0x66, 0x70, 0xa9, 0x1a, 0x61, 0xae, 0x08, 0xaf, 0x49, 0x7b, 0x4a, 0x82, 0xbe, 0x6d,
+    0xee, 0x8f, 0xcd, 0xd5, 0xe3, 0xf7, 0xba, 0x1c, 0xfb, 0x1f, 0x0c, 0x92, 0x6b, 0x88, 0xf8, 0x8c,
+    0x92, 0xbf, 0xab, 0x13, 0x7f, 0xba, 0x22, 0x85, 0x22, 0x7b, 0x83, 0xc3, 0x42, 0xff, 0x7c, 0x55,
+    0x02, 0x41, 0x00, 0xdd, 0xab, 0xb5, 0x83, 0x9c, 0x4c, 0x7f, 0x6b, 0xf3, 0xd4, 0x18, 0x32, 0x31,
+    0xf0, 0x05, 0xb3, 0x1a, 0xa5, 0x8a, 0xff, 0xdd, 0xa5, 0xc7, 0x9e, 0x4c, 0xce, 0x21, 0x7f, 0x6b,
+    0xc9, 0x30, 0xdb, 0xe5, 0x63, 0xd4, 0x80, 0x70, 0x6c, 0x24, 0xe9, 0xeb, 0xfc, 0xab, 0x28, 0xa6,
+    0xcd, 0xef, 0xd3, 0x24, 0xb7, 0x7e, 0x1b, 0xf7, 0x25, 0x1b, 0x70, 0x90, 0x92, 0xc2, 0x4f, 0xf5,
+    0x01, 0xfd, 0x91, 0x02, 0x40, 0x23, 0xd4, 0x34, 0x0e, 0xda, 0x34, 0x45, 0xd8, 0xcd, 0x26, 0xc1,
+    0x44, 0x11, 0xda, 0x6f, 0xdc, 0xa6, 0x3c, 0x1c, 0xcd, 0x4b, 0x80, 0xa9, 0x8a, 0xd5, 0x2b, 0x78,
+    0xcc, 0x8a, 0xd8, 0xbe, 0xb2, 0x84, 0x2c, 0x1d, 0x28, 0x04, 0x05, 0xbc, 0x2f, 0x6c, 0x1b, 0xea,
+    0x21, 0x4a, 0x1d, 0x74, 0x2a, 0xb9, 0x96, 0xb3, 0x5b, 0x63, 0xa8, 0x2a, 0x5e, 0x47, 0x0f, 0xa8,
+    0x8d, 0xbf, 0x82, 0x3c, 0xdd, 0x02, 0x40, 0x1b, 0x7b, 0x57, 0x44, 0x9a, 0xd3, 0x0d, 0x15, 0x18,
+    0x24, 0x9a, 0x5f, 0x56, 0xbb, 0x98, 0x29, 0x4d, 0x4b, 0x6a, 0xc1, 0x2f, 0xfc, 0x86, 0x94, 0x04,
+    0x97, 0xa5, 0xa5, 0x83, 0x7a, 0x6c, 0xf9, 0x46, 0x26, 0x2b, 0x49, 0x45, 0x26, 0xd3, 0x28, 0xc1,
+    0x1e, 0x11, 0x26, 0x38, 0x0f, 0xde, 0x04, 0xc2, 0x4f, 0x91, 0x6d, 0xec, 0x25, 0x08, 0x92, 0xdb,
+    0x09, 0xa6, 0xd7, 0x7c, 0xdb, 0xa3, 0x51, 0x02, 0x40, 0x77, 0x62, 0xcd, 0x8f, 0x4d, 0x05, 0x0d,
+    0xa5, 0x6b, 0xd5, 0x91, 0xad, 0xb5, 0x15, 0xd2, 0x4d, 0x7c, 0xcd, 0x32, 0xcc, 0xa0, 0xd0, 0x5f,
+    0x86, 0x6d, 0x58, 0x35, 0x14, 0xbd, 0x73, 0x24, 0xd5, 0xf3, 0x36, 0x45, 0xe8, 0xed, 0x8b, 0x4a,
+    0x1c, 0xb3, 0xcc, 0x4a, 0x1d, 0x67, 0x98, 0x73, 0x99, 0xf2, 0xa0, 0x9f, 0x5b, 0x3f, 0xb6, 0x8c,
+    0x88, 0xd5, 0xe5, 0xd9, 0x0a, 0xc3, 0x34, 0x92, 0xd6};
+unsigned int rsa_privkey_pk8_der_len = 633;
+
+unsigned char dsa_privkey_pk8_der[] = {
+    0x30, 0x82, 0x01, 0x4b, 0x02, 0x01, 0x00, 0x30, 0x82, 0x01, 0x2b, 0x06, 0x07, 0x2a, 0x86, 0x48,
+    0xce, 0x38, 0x04, 0x01, 0x30, 0x82, 0x01, 0x1e, 0x02, 0x81, 0x81, 0x00, 0xa3, 0xf3, 0xe9, 0xb6,
+    0x7e, 0x7d, 0x88, 0xf6, 0xb7, 0xe5, 0xf5, 0x1f, 0x3b, 0xee, 0xac, 0xd7, 0xad, 0xbc, 0xc9, 0xd1,
+    0x5a, 0xf8, 0x88, 0xc4, 0xef, 0x6e, 0x3d, 0x74, 0x19, 0x74, 0xe7, 0xd8, 0xe0, 0x26, 0x44, 0x19,
+    0x86, 0xaf, 0x19, 0xdb, 0x05, 0xe9, 0x3b, 0x8b, 0x58, 0x58, 0xde, 0xe5, 0x4f, 0x48, 0x15, 0x01,
+    0xea, 0xe6, 0x83, 0x52, 0xd7, 0xc1, 0x21, 0xdf, 0xb9, 0xb8, 0x07, 0x66, 0x50, 0xfb, 0x3a, 0x0c,
+    0xb3, 0x85, 0xee, 0xbb, 0x04, 0x5f, 0xc2, 0x6d, 0x6d, 0x95, 0xfa, 0x11, 0x93, 0x1e, 0x59, 0x5b,
+    0xb1, 0x45, 0x8d, 0xe0, 0x3d, 0x73, 0xaa, 0xf2, 0x41, 0x14, 0x51, 0x07, 0x72, 0x3d, 0xa2, 0xf7,
+    0x58, 0xcd, 0x11, 0xa1, 0x32, 0xcf, 0xda, 0x42, 0xb7, 0xcc, 0x32, 0x80, 0xdb, 0x87, 0x82, 0xec,
+    0x42, 0xdb, 0x5a, 0x55, 0x24, 0x24, 0xa2, 0xd1, 0x55, 0x29, 0xad, 0xeb, 0x02, 0x15, 0x00, 0xeb,
+    0xea, 0x17, 0xd2, 0x09, 0xb3, 0xd7, 0x21, 0x9a, 0x21, 0x07, 0x82, 0x8f, 0xab, 0xfe, 0x88, 0x71,
+    0x68, 0xf7, 0xe3, 0x02, 0x81, 0x80, 0x19, 0x1c, 0x71, 0xfd, 0xe0, 0x03, 0x0c, 0x43, 0xd9, 0x0b,
+    0xf6, 0xcd, 0xd6, 0xa9, 0x70, 0xe7, 0x37, 0x86, 0x3a, 0x78, 0xe9, 0xa7, 0x47, 0xa7, 0x47, 0x06,
+    0x88, 0xb1, 0xaf, 0xd7, 0xf3, 0xf1, 0xa1, 0xd7, 0x00, 0x61, 0x28, 0x88, 0x31, 0x48, 0x60, 0xd8,
+    0x11, 0xef, 0xa5, 0x24, 0x1a, 0x81, 0xc4, 0x2a, 0xe2, 0xea, 0x0e, 0x36, 0xd2, 0xd2, 0x05, 0x84,
+    0x37, 0xcf, 0x32, 0x7d, 0x09, 0xe6, 0x0f, 0x8b, 0x0c, 0xc8, 0xc2, 0xa4, 0xb1, 0xdc, 0x80, 0xca,
+    0x68, 0xdf, 0xaf, 0xd2, 0x90, 0xc0, 0x37, 0x58, 0x54, 0x36, 0x8f, 0x49, 0xb8, 0x62, 0x75, 0x8b,
+    0x48, 0x47, 0xc0, 0xbe, 0xf7, 0x9a, 0x92, 0xa6, 0x68, 0x05, 0xda, 0x9d, 0xaf, 0x72, 0x9a, 0x67,
+    0xb3, 0xb4, 0x14, 0x03, 0xae, 0x4f, 0x4c, 0x76, 0xb9, 0xd8, 0x64, 0x0a, 0xba, 0x3b, 0xa8, 0x00,
+    0x60, 0x4d, 0xae, 0x81, 0xc3, 0xc5, 0x04, 0x17, 0x02, 0x15, 0x00, 0x81, 0x9d, 0xfd, 0x53, 0x0c,
+    0xc1, 0x8f, 0xbe, 0x8b, 0xea, 0x00, 0x26, 0x19, 0x29, 0x33, 0x91, 0x84, 0xbe, 0xad, 0x81};
+unsigned int dsa_privkey_pk8_der_len = 335;
+
+unsigned char ec_privkey_pk8_der[] = {
+    0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
+    0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02,
+    0x01, 0x01, 0x04, 0x20, 0x73, 0x7c, 0x2e, 0xcd, 0x7b, 0x8d, 0x19, 0x40, 0xbf, 0x29, 0x30, 0xaa,
+    0x9b, 0x4e, 0xd3, 0xff, 0x94, 0x1e, 0xed, 0x09, 0x36, 0x6b, 0xc0, 0x32, 0x99, 0x98, 0x64, 0x81,
+    0xf3, 0xa4, 0xd8, 0x59, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xbf, 0x85, 0xd7, 0x72, 0x0d, 0x07,
+    0xc2, 0x54, 0x61, 0x68, 0x3b, 0xc6, 0x48, 0xb4, 0x77, 0x8a, 0x9a, 0x14, 0xdd, 0x8a, 0x02, 0x4e,
+    0x3b, 0xdd, 0x8c, 0x7d, 0xdd, 0x9a, 0xb2, 0xb5, 0x28, 0xbb, 0xc7, 0xaa, 0x1b, 0x51, 0xf1, 0x4e,
+    0xbb, 0xbb, 0x0b, 0xd0, 0xce, 0x21, 0xbc, 0xc4, 0x1c, 0x6e, 0xb0, 0x00, 0x83, 0xcf, 0x33, 0x76,
+    0xd1, 0x1f, 0xd4, 0x49, 0x49, 0xe0, 0xb2, 0x18, 0x3b, 0xfe};
+unsigned int ec_privkey_pk8_der_len = 138;
+
+struct EVP_PKEY_Delete {
+    void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
+};
+
+struct EVP_PKEY_CTX_Delete {
+    void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
+};
+
+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);
+    if (error != KM_ERROR_OK) {
+        printf("Error importing key pair: %d\n\n", error);
+        return false;
+    }
+    UniquePtr<uint8_t[]> key_deleter(key);
+
+    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]);
+    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);
+        return false;
+    }
+    UniquePtr<uint8_t[]> signature_deleter(signature);
+
+    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);
+        return false;
+    }
+
+    printf("\n");
+    return true;
+}
+
+static bool test_rsa(TrustyKeymasterDevice* device) {
+    printf("============\n");
+    printf("= RSA Test =\n");
+    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);
+    if (error != KM_ERROR_OK) {
+        printf("Error generating RSA key pair: %d\n\n", error);
+        return false;
+    }
+    UniquePtr<uint8_t[]> deleter(key);
+
+    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]);
+    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);
+        return false;
+    }
+    UniquePtr<uint8_t[]> signature_deleter(signature);
+
+    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);
+        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);
+    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));
+    if (EVP_PKEY_verify_init(ctx.get()) != 1) {
+        printf("Error initializing openss EVP context\n");
+        return false;
+    }
+    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
+        printf("Exported key was the wrong type?!?\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");
+        return false;
+    } else {
+        printf("Verification succeeded\n");
+    }
+
+    printf("\n");
+    return true;
+}
+
+static bool test_import_ecdsa(TrustyKeymasterDevice* device) {
+    printf("=====================\n");
+    printf("= ECDSA Import Test =\n");
+    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);
+    if (error != KM_ERROR_OK) {
+        printf("Error importing key pair: %d\n\n", error);
+        return false;
+    }
+    UniquePtr<uint8_t[]> deleter(key);
+
+    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]);
+    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);
+        return false;
+    }
+    UniquePtr<uint8_t[]> signature_deleter(signature);
+
+    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);
+        return false;
+    }
+
+    printf("\n");
+    return true;
+}
+
+static bool test_ecdsa(TrustyKeymasterDevice* device) {
+    printf("==============\n");
+    printf("= ECDSA Test =\n");
+    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) {
+        printf("Error generating ECDSA key pair: %d\n\n", error);
+        return false;
+    }
+    UniquePtr<uint8_t[]> deleter(key);
+
+    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]);
+    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);
+        return false;
+    }
+    UniquePtr<uint8_t[]> signature_deleter(signature);
+
+    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);
+        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);
+    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));
+    if (EVP_PKEY_verify_init(ctx.get()) != 1) {
+        printf("Error initializing openss EVP context\n");
+        return false;
+    }
+    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
+        printf("Exported key was the wrong type?!?\n");
+        return false;
+    }
+
+    if (EVP_PKEY_verify(ctx.get(), signature, signature_len, message.get(), message_len) != 1) {
+        printf("Verification with exported pubkey failed.\n");
+        return false;
+    } else {
+        printf("Verification succeeded\n");
+    }
+
+    printf("\n");
+    return true;
+}
+
+int main(void) {
+
+    TrustyKeymasterDevice device(NULL);
+    if (device.session_error() != KM_ERROR_OK) {
+        printf("Failed to initialize Trusty session: %d\n", device.session_error());
+        return 1;
+    }
+    printf("Trusty session initialized\n");
+
+    bool success = true;
+    success &= test_rsa(&device);
+    success &= test_import_rsa(&device);
+    success &= test_ecdsa(&device);
+    success &= test_import_ecdsa(&device);
+
+    if (success) {
+        printf("\nTESTS PASSED!\n");
+    } else {
+        printf("\n!!!!TESTS FAILED!!!\n");
+    }
+
+    return success ? 0 : 1;
+}
diff --git a/trusty/libtrusty/tipc-test/tipc_test.c b/trusty/libtrusty/tipc-test/tipc_test.c
index 55d5ee6..1fb34c9 100644
--- a/trusty/libtrusty/tipc-test/tipc_test.c
+++ b/trusty/libtrusty/tipc-test/tipc_test.c
@@ -21,6 +21,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 #include <getopt.h>
+#include <sys/uio.h>
 
 #include <trusty/tipc.h>
 
@@ -80,6 +81,8 @@
 "   ta2ta-ipc    - execute TA to TA unittest\n"
 "   dev-uuid     - print device uuid\n"
 "   ta-access    - test ta-access flags\n"
+"   writev       - writev test\n"
+"   readv        - readv test\n"
 "\n"
 ;
 
@@ -93,7 +96,7 @@
 {
 	fprintf (stderr, usage, prog);
 	if (verbose)
-		fprintf (stderr, usage_long);
+		fprintf (stderr, "%s", usage_long);
 	exit(code);
 }
 
@@ -692,6 +695,171 @@
 }
 
 
+static int writev_test(uint repeat, uint msgsz, bool var)
+{
+	uint i;
+	ssize_t rc;
+	size_t  msg_len;
+	int  echo_fd = -1;
+	char tx0_buf[msgsz];
+	char tx1_buf[msgsz];
+	char rx_buf [msgsz];
+	struct iovec iovs[2]= {{tx0_buf, 0}, {tx1_buf, 0}};
+
+	if (!opt_silent) {
+		printf("%s: repeat %u: msgsz %u: variable %s\n",
+			__func__, repeat, msgsz, var ? "true" : "false");
+	}
+
+	echo_fd = tipc_connect(dev_name, echo_name);
+	if (echo_fd < 0) {
+		fprintf(stderr, "Failed to connect to service\n");
+		return echo_fd;
+	}
+
+	for (i = 0; i < repeat; i++) {
+
+		msg_len = msgsz;
+		if (opt_variable && msgsz) {
+			msg_len = rand() % msgsz;
+		}
+
+		iovs[0].iov_len = msg_len / 3;
+		iovs[1].iov_len = msg_len - iovs[0].iov_len;
+
+		memset(tx0_buf, i + 1, iovs[0].iov_len);
+		memset(tx1_buf, i + 2, iovs[1].iov_len);
+		memset(rx_buf,  i + 3, sizeof(rx_buf));
+
+		rc = writev(echo_fd, iovs, 2);
+		if (rc < 0) {
+			perror("writev_test: writev");
+			break;
+		}
+
+		if ((size_t)rc != msg_len) {
+			fprintf(stderr,
+				"%s: %s: data size mismatch (%zd vs. %zd)\n",
+				__func__, "writev", (size_t)rc, msg_len);
+			break;
+		}
+
+		rc = read(echo_fd, rx_buf, sizeof(rx_buf));
+		if (rc < 0) {
+			perror("writev_test: read");
+			break;
+		}
+
+		if ((size_t)rc != msg_len) {
+			fprintf(stderr,
+				"%s: %s: data size mismatch (%zd vs. %zd)\n",
+				__func__, "read", (size_t)rc, msg_len);
+			break;
+		}
+
+		if (memcmp(tx0_buf, rx_buf, iovs[0].iov_len)) {
+			fprintf(stderr, "%s: data mismatch: buf 0\n", __func__);
+			break;
+		}
+
+		if (memcmp(tx1_buf, rx_buf + iovs[0].iov_len, iovs[1].iov_len)) {
+			fprintf(stderr, "%s: data mismatch, buf 1\n", __func__);
+			break;
+		}
+	}
+
+	tipc_close(echo_fd);
+
+	if (!opt_silent) {
+		printf("%s: done\n",__func__);
+	}
+
+	return 0;
+}
+
+static int readv_test(uint repeat, uint msgsz, bool var)
+{
+	uint i;
+	ssize_t rc;
+	size_t  msg_len;
+	int  echo_fd = -1;
+	char tx_buf [msgsz];
+	char rx0_buf[msgsz];
+	char rx1_buf[msgsz];
+	struct iovec iovs[2]= {{rx0_buf, 0}, {rx1_buf, 0}};
+
+	if (!opt_silent) {
+		printf("%s: repeat %u: msgsz %u: variable %s\n",
+			__func__, repeat, msgsz, var ? "true" : "false");
+	}
+
+	echo_fd = tipc_connect(dev_name, echo_name);
+	if (echo_fd < 0) {
+		fprintf(stderr, "Failed to connect to service\n");
+		return echo_fd;
+	}
+
+	for (i = 0; i < repeat; i++) {
+
+		msg_len = msgsz;
+		if (opt_variable && msgsz) {
+			msg_len = rand() % msgsz;
+		}
+
+		iovs[0].iov_len = msg_len / 3;
+		iovs[1].iov_len = msg_len - iovs[0].iov_len;
+
+		memset(tx_buf,  i + 1, sizeof(tx_buf));
+		memset(rx0_buf, i + 2, iovs[0].iov_len);
+		memset(rx1_buf, i + 3, iovs[1].iov_len);
+
+		rc = write(echo_fd, tx_buf, msg_len);
+		if (rc < 0) {
+			perror("readv_test: write");
+			break;
+		}
+
+		if ((size_t)rc != msg_len) {
+			fprintf(stderr,
+				"%s: %s: data size mismatch (%zd vs. %zd)\n",
+				__func__, "write", (size_t)rc, msg_len);
+			break;
+		}
+
+		rc = readv(echo_fd, iovs, 2);
+		if (rc < 0) {
+			perror("readv_test: readv");
+			break;
+		}
+
+		if ((size_t)rc != msg_len) {
+			fprintf(stderr,
+				"%s: %s: data size mismatch (%zd vs. %zd)\n",
+				__func__, "write", (size_t)rc, msg_len);
+			break;
+		}
+
+		if (memcmp(rx0_buf, tx_buf, iovs[0].iov_len)) {
+			fprintf(stderr, "%s: data mismatch: buf 0\n", __func__);
+			break;
+		}
+
+		if (memcmp(rx1_buf, tx_buf + iovs[0].iov_len, iovs[1].iov_len)) {
+			fprintf(stderr, "%s: data mismatch, buf 1\n", __func__);
+			break;
+		}
+	}
+
+	tipc_close(echo_fd);
+
+	if (!opt_silent) {
+		printf("%s: done\n",__func__);
+	}
+
+	return 0;
+}
+
+
 int main(int argc, char **argv)
 {
 	int rc = 0;
@@ -735,6 +903,10 @@
 		rc = dev_uuid_test();
 	} else if (strcmp(test_name, "ta-access") == 0) {
 		rc = ta_access_test();
+	} else if (strcmp(test_name, "writev") == 0) {
+		rc = writev_test(opt_repeat, opt_msgsize, opt_variable);
+	} else if (strcmp(test_name, "readv") == 0) {
+		rc = readv_test(opt_repeat, opt_msgsize, opt_variable);
 	} else {
 		fprintf(stderr, "Unrecognized test name '%s'\n", test_name);
 		print_usage_and_exit(argv[0], EXIT_FAILURE, true);
diff --git a/trusty/libtrusty/trusty.c b/trusty/libtrusty/trusty.c
index b6897ce..a6238af 100644
--- a/trusty/libtrusty/trusty.c
+++ b/trusty/libtrusty/trusty.c
@@ -22,8 +22,10 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
 
-#include <cutils/log.h>
+#include <log/log.h>
 
 #include "tipc_ioctl.h"
 
diff --git a/trusty/nvram/Android.mk b/trusty/nvram/Android.mk
new file mode 100644
index 0000000..44e2212
--- /dev/null
+++ b/trusty/nvram/Android.mk
@@ -0,0 +1,43 @@
+#
+# 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+# nvram.trusty is the Trusty NVRAM HAL module.
+include $(CLEAR_VARS)
+LOCAL_MODULE := nvram.trusty
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := \
+	module.c \
+	trusty_nvram_device.cpp \
+	trusty_nvram_implementation.cpp
+LOCAL_MODULE_TAGS := optional
+LOCAL_CFLAGS := -Wall -Werror -Wextra -fvisibility=hidden
+LOCAL_STATIC_LIBRARIES := libnvram-hal
+LOCAL_SHARED_LIBRARIES := libtrusty libnvram-messages liblog
+include $(BUILD_SHARED_LIBRARY)
+
+# nvram-wipe is a helper tool for clearing NVRAM state.
+include $(CLEAR_VARS)
+LOCAL_MODULE := nvram-wipe
+LOCAL_SRC_FILES := \
+	nvram_wipe.cpp \
+	trusty_nvram_implementation.cpp
+LOCAL_MODULE_TAGS := optional
+LOCAL_CFLAGS := -Wall -Werror -Wextra -fvisibility=hidden
+LOCAL_STATIC_LIBRARIES := libnvram-hal
+LOCAL_SHARED_LIBRARIES := libtrusty libnvram-messages liblog
+include $(BUILD_EXECUTABLE)
diff --git a/trusty/nvram/module.c b/trusty/nvram/module.c
new file mode 100644
index 0000000..a2e64d3
--- /dev/null
+++ b/trusty/nvram/module.c
@@ -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 <hardware/nvram.h>
+
+// This function is defined in trusty_nvram_device.cpp.
+int trusty_nvram_open(const hw_module_t* module,
+                      const char* device_id,
+                      hw_device_t** device_ptr);
+
+static struct hw_module_methods_t nvram_module_methods = {
+    .open = trusty_nvram_open,
+};
+
+struct nvram_module HAL_MODULE_INFO_SYM
+    __attribute__((visibility("default"))) = {
+        .common = {.tag = HARDWARE_MODULE_TAG,
+                   .module_api_version = NVRAM_MODULE_API_VERSION_0_1,
+                   .hal_api_version = HARDWARE_HAL_API_VERSION,
+                   .id = NVRAM_HARDWARE_MODULE_ID,
+                   .name = "Trusty NVRAM HAL",
+                   .author = "The Android Open Source Project",
+                   .methods = &nvram_module_methods,
+                   .dso = 0,
+                   .reserved = {}},
+};
diff --git a/trusty/nvram/nvram_wipe.cpp b/trusty/nvram/nvram_wipe.cpp
new file mode 100644
index 0000000..d0f4fad
--- /dev/null
+++ b/trusty/nvram/nvram_wipe.cpp
@@ -0,0 +1,66 @@
+/*
+ * 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <nvram/messages/nvram_messages.h>
+
+#include "trusty_nvram_implementation.h"
+
+void usage(const char* program_name) {
+  fprintf(stderr, "Usage: %s [status|disable|wipe]\n", program_name);
+  exit(-1);
+}
+
+int main(int argc, char* argv[]) {
+  if (argc < 2) {
+    usage(argv[0]);
+  }
+
+  nvram::TrustyNvramImplementation nvram_proxy;
+  nvram::Request request;
+  nvram::Response response;
+
+  if (!strcmp(argv[1], "status")) {
+    request.payload.Activate<nvram::COMMAND_GET_INFO>();
+    nvram_proxy.Execute(request, &response);
+    const nvram::GetInfoResponse* get_info_response =
+        response.payload.get<nvram::COMMAND_GET_INFO>();
+    if (response.result == NV_RESULT_SUCCESS) {
+      int status = get_info_response && get_info_response->wipe_disabled;
+      printf("Wiping disabled: %d\n", status);
+      return status;
+    }
+  } else if (!strcmp(argv[1], "disable")) {
+    request.payload.Activate<nvram::COMMAND_DISABLE_WIPE>();
+    nvram_proxy.Execute(request, &response);
+  } else if (!strcmp(argv[1], "wipe")) {
+    request.payload.Activate<nvram::COMMAND_WIPE_STORAGE>();
+    nvram_proxy.Execute(request, &response);
+  } else {
+    usage(argv[0]);
+  }
+
+  if (response.result != NV_RESULT_SUCCESS) {
+    fprintf(stderr, "Command execution failure: %u\n", response.result);
+    return -1;
+  }
+
+  return 0;
+}
+
diff --git a/trusty/nvram/trusty_nvram_device.cpp b/trusty/nvram/trusty_nvram_device.cpp
new file mode 100644
index 0000000..2c50915
--- /dev/null
+++ b/trusty/nvram/trusty_nvram_device.cpp
@@ -0,0 +1,32 @@
+/*
+ * 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 <nvram/hal/nvram_device_adapter.h>
+
+#include "trusty_nvram_implementation.h"
+
+extern "C" int trusty_nvram_open(const hw_module_t* module,
+                                 const char* device_id,
+                                 hw_device_t** device_ptr) {
+  if (strcmp(NVRAM_HARDWARE_DEVICE_ID, device_id) != 0) {
+    return -EINVAL;
+  }
+
+  nvram::NvramDeviceAdapter* adapter = new nvram::NvramDeviceAdapter(
+      module, new nvram::TrustyNvramImplementation);
+  *device_ptr = adapter->as_device();
+  return 0;
+}
diff --git a/trusty/nvram/trusty_nvram_implementation.cpp b/trusty/nvram/trusty_nvram_implementation.cpp
new file mode 100644
index 0000000..9215c85
--- /dev/null
+++ b/trusty/nvram/trusty_nvram_implementation.cpp
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "TrustyNVRAM"
+
+#include "trusty_nvram_implementation.h"
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <hardware/nvram.h>
+#include <log/log.h>
+#include <trusty/tipc.h>
+
+#include <nvram/messages/blob.h>
+
+namespace nvram {
+namespace {
+
+// Character device to open for Trusty IPC connections.
+const char kTrustyDeviceName[] = "/dev/trusty-ipc-dev0";
+
+// App identifier of the NVRAM app.
+const char kTrustyNvramAppId[] = "com.android.trusty.nvram";
+
+}  // namespace
+
+TrustyNvramImplementation::~TrustyNvramImplementation() {
+  if (tipc_nvram_fd_ != -1) {
+    tipc_close(tipc_nvram_fd_);
+    tipc_nvram_fd_ = -1;
+  }
+}
+
+void TrustyNvramImplementation::Execute(const nvram::Request& request,
+                                        nvram::Response* response) {
+  if (!SendRequest(request, response)) {
+    response->result = NV_RESULT_INTERNAL_ERROR;
+  }
+}
+
+bool TrustyNvramImplementation::Connect() {
+  if (tipc_nvram_fd_ != -1) {
+    return true;
+  }
+
+  int rc = tipc_connect(kTrustyDeviceName, kTrustyNvramAppId);
+  if (rc < 0) {
+    ALOGE("Failed to connect to Trusty NVRAM app: %s\n", strerror(-rc));
+    return false;
+  }
+
+  tipc_nvram_fd_ = rc;
+  return true;
+}
+
+bool TrustyNvramImplementation::SendRequest(const nvram::Request& request,
+                                            nvram::Response* response) {
+  if (!Connect()) {
+    return false;
+  }
+
+  nvram::Blob request_buffer;
+  if (!nvram::Encode(request, &request_buffer)) {
+    ALOGE("Failed to encode NVRAM request.\n");
+    return false;
+  }
+
+  ssize_t rc =
+      write(tipc_nvram_fd_, request_buffer.data(), request_buffer.size());
+  if (rc < 0) {
+    ALOGE("Failed to send NVRAM request: %s\n", strerror(-rc));
+    return false;
+  }
+  if (static_cast<size_t>(rc) != request_buffer.size()) {
+    ALOGE("Failed to send full request buffer: %zd\n", rc);
+    return false;
+  }
+
+  rc = read(tipc_nvram_fd_, response_buffer_, sizeof(response_buffer_));
+  if (rc < 0) {
+    ALOGE("Failed to read NVRAM response: %s\n", strerror(-rc));
+    return false;
+  }
+
+  if (static_cast<size_t>(rc) >= sizeof(response_buffer_)) {
+    ALOGE("NVRAM response exceeds response buffer size.\n");
+    return false;
+  }
+
+  if (!nvram::Decode(response_buffer_, static_cast<size_t>(rc), response)) {
+    ALOGE("Failed to decode NVRAM response.\n");
+    return false;
+  }
+
+  return true;
+}
+
+}  // namespace nvram
diff --git a/trusty/nvram/trusty_nvram_implementation.h b/trusty/nvram/trusty_nvram_implementation.h
new file mode 100644
index 0000000..60758f7
--- /dev/null
+++ b/trusty/nvram/trusty_nvram_implementation.h
@@ -0,0 +1,59 @@
+/*
+ * 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 TRUSTY_NVRAM_TRUSTY_NVRAM_IMPLEMENTATION_H_
+#define TRUSTY_NVRAM_TRUSTY_NVRAM_IMPLEMENTATION_H_
+
+#include <stdint.h>
+
+#include <nvram/hal/nvram_device_adapter.h>
+#include <nvram/messages/nvram_messages.h>
+
+namespace nvram {
+
+// |TrustyNvramImplementation| proxies requests to the Trusty NVRAM app. It
+// serializes the request objects, sends it to the Trusty app and finally reads
+// back the result and decodes it.
+class TrustyNvramImplementation : public nvram::NvramImplementation {
+ public:
+  ~TrustyNvramImplementation() override;
+
+  void Execute(const nvram::Request& request,
+               nvram::Response* response) override;
+
+ private:
+  // Connects the IPC channel to the Trusty app if it is not already open.
+  // Returns true if the channel is open, false on errors.
+  bool Connect();
+
+  // Dispatches a command to the trust app. Returns true if successful (note
+  // that the response may still indicate an error on the Trusty side), false if
+  // there are any I/O or encoding/decoding errors.
+  bool SendRequest(const nvram::Request& request,
+                   nvram::Response* response);
+
+  // The file descriptor for the IPC connection to the Trusty app.
+  int tipc_nvram_fd_ = -1;
+
+  // Response buffer. This puts a hard size limit on the responses from the
+  // Trusty app. 4096 matches the maximum IPC message size currently supported
+  // by Trusty.
+  uint8_t response_buffer_[4096];
+};
+
+}  // namespace nvram
+
+#endif  // TRUSTY_NVRAM_TRUSTY_NVRAM_IMPLEMENTATION_H_
diff --git a/trusty/storage/interface/Android.mk b/trusty/storage/interface/Android.mk
new file mode 100644
index 0000000..15cb6f3
--- /dev/null
+++ b/trusty/storage/interface/Android.mk
@@ -0,0 +1,25 @@
+#
+# 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 := libtrustystorageinterface
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/trusty/storage/interface/include/trusty/interface/storage.h b/trusty/storage/interface/include/trusty/interface/storage.h
new file mode 100644
index 0000000..b196d88
--- /dev/null
+++ b/trusty/storage/interface/include/trusty/interface/storage.h
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2015-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.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+/*
+ * Storage port names
+ * @STORAGE_CLIENT_TD_PORT:     Port used by clients that require tamper and
+ *                              rollback detection.
+ * @STORAGE_CLIENT_TDEA_PORT:   Port used by clients that require storage before
+ *                              the non-secure os has booted.
+ * @STORAGE_CLIENT_TP_PORT:     Port used by clients that require tamper proof
+ *                              storage. Note that non-secure code can prevent
+                                read and write operations from succeeding, but
+                                it cannot modify on-disk data.
+ * @STORAGE_DISK_PROXY_PORT:    Port used by non-secure proxy server
+ */
+#define STORAGE_CLIENT_TD_PORT     "com.android.trusty.storage.client.td"
+#define STORAGE_CLIENT_TDEA_PORT   "com.android.trusty.storage.client.tdea"
+#define STORAGE_CLIENT_TP_PORT     "com.android.trusty.storage.client.tp"
+#define STORAGE_DISK_PROXY_PORT    "com.android.trusty.storage.proxy"
+
+enum storage_cmd {
+	STORAGE_REQ_SHIFT = 1,
+	STORAGE_RESP_BIT  = 1,
+
+	STORAGE_RESP_MSG_ERR   = STORAGE_RESP_BIT,
+
+	STORAGE_FILE_DELETE    = 1 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_OPEN      = 2 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_CLOSE     = 3 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_READ      = 4 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_WRITE     = 5 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_GET_SIZE  = 6 << STORAGE_REQ_SHIFT,
+	STORAGE_FILE_SET_SIZE  = 7 << STORAGE_REQ_SHIFT,
+
+	STORAGE_RPMB_SEND      = 8 << STORAGE_REQ_SHIFT,
+
+	/* transaction support */
+	STORAGE_END_TRANSACTION = 9 << STORAGE_REQ_SHIFT,
+};
+
+/**
+ * enum storage_err - error codes for storage protocol
+ * @STORAGE_NO_ERROR:           all OK
+ * @STORAGE_ERR_GENERIC:        unknown error. Can occur when there's an internal server
+ *                              error, e.g. the server runs out of memory or is in a bad state.
+ * @STORAGE_ERR_NOT_VALID:      input not valid. May occur if the arguments passed
+ *                              into the command are not valid, for example if the file handle
+ *                              passed in is not a valid one.
+ * @STORAGE_ERR_UNIMPLEMENTED:  the command passed in is not recognized
+ * @STORAGE_ERR_ACCESS:         the file is not accessible in the requested mode
+ * @STORAGE_ERR_NOT_FOUND:      the file was not found
+ * @STORAGE_ERR_EXIST           the file exists when it shouldn't as in with OPEN_CREATE | OPEN_EXCLUSIVE.
+ * @STORAGE_ERR_TRANSACT        returned by various operations to indicate that current transaction
+ *                              is in error state. Such state could be only cleared by sending
+ *                              STORAGE_END_TRANSACTION message.
+ */
+enum storage_err {
+	STORAGE_NO_ERROR          = 0,
+	STORAGE_ERR_GENERIC       = 1,
+	STORAGE_ERR_NOT_VALID     = 2,
+	STORAGE_ERR_UNIMPLEMENTED = 3,
+	STORAGE_ERR_ACCESS        = 4,
+	STORAGE_ERR_NOT_FOUND     = 5,
+	STORAGE_ERR_EXIST         = 6,
+	STORAGE_ERR_TRANSACT      = 7,
+};
+
+/**
+ * storage_delete_flag - flags for controlling delete semantics
+ */
+enum storage_file_delete_flag {
+	STORAGE_FILE_DELETE_MASK = 0,
+};
+
+/**
+ * storage_file_flag - Flags to control 'open' semantics.
+ * @STORAGE_FILE_OPEN_CREATE:           if this file does not exist, create it.
+ * @STORAGE_FILE_OPEN_CREATE_EXCLUSIVE: causes STORAGE_FILE_OPEN_CREATE to fail if the file
+ *                                      already exists. Only meaningful if used in combination
+ *                                      with STORAGE_FILE_OPEN_CREATE.
+ * @STORAGE_FILE_OPEN_TRUNCATE:         if this file already exists, discard existing content
+ *                                      and open it as a new file. No change in semantics if the
+ *                                      file does not exist.
+ * @STORAGE_FILE_OPEN_MASK:             mask for all open flags supported in current protocol.
+ *                                      All other bits must be set to 0.
+ */
+enum storage_file_open_flag {
+	STORAGE_FILE_OPEN_CREATE             = (1 << 0),
+	STORAGE_FILE_OPEN_CREATE_EXCLUSIVE   = (1 << 1),
+	STORAGE_FILE_OPEN_TRUNCATE           = (1 << 2),
+	STORAGE_FILE_OPEN_MASK               = STORAGE_FILE_OPEN_CREATE |
+					       STORAGE_FILE_OPEN_TRUNCATE |
+					       STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+};
+
+/**
+ * enum storage_msg_flag - protocol-level flags in struct storage_msg
+ * @STORAGE_MSG_FLAG_BATCH:             if set, command belongs to a batch transaction.
+ *                                      No response will be sent by the server until
+ *                                      it receives a command with this flag unset, at
+ *                                      which point a cummulative result for all messages
+ *                                      sent with STORAGE_MSG_FLAG_BATCH will be sent.
+ *                                      This is only supported by the non-secure disk proxy
+ *                                      server.
+ * @STORAGE_MSG_FLAG_PRE_COMMIT:        if set, indicates that server need to commit
+ *                                      pending changes before processing this message.
+ * @STORAGE_MSG_FLAG_POST_COMMIT:       if set, indicates that server need to commit
+ *                                      pending changes after processing this message.
+ * @STORAGE_MSG_FLAG_TRANSACT_COMPLETE: if set, indicates that server need to commit
+ *                                      current transaction after processing this message.
+ *                                      It is an alias for STORAGE_MSG_FLAG_POST_COMMIT.
+ */
+enum storage_msg_flag {
+	STORAGE_MSG_FLAG_BATCH = 0x1,
+	STORAGE_MSG_FLAG_PRE_COMMIT = 0x2,
+	STORAGE_MSG_FLAG_POST_COMMIT = 0x4,
+	STORAGE_MSG_FLAG_TRANSACT_COMPLETE = STORAGE_MSG_FLAG_POST_COMMIT,
+};
+
+/*
+ * The following declarations are the message-specific contents of
+ * the 'payload' element inside struct storage_msg.
+ */
+
+/**
+ * struct storage_file_delete_req - request format for STORAGE_FILE_DELETE
+ * @flags: currently unused, must be set to 0.
+ * @name:  the name of the file
+ */
+struct storage_file_delete_req {
+	uint32_t flags;
+	char name[0];
+};
+
+/**
+ * struct storage_file_open_req - request format for STORAGE_FILE_OPEN
+ * @flags: any of enum storage_file_flag or'ed together
+ * @name:  the name of the file
+ */
+struct storage_file_open_req {
+	uint32_t flags;
+	char     name[0];
+};
+
+/**
+ * struct storage_file_open_resp - response format for STORAGE_FILE_OPEN
+ * @handle: opaque handle to the opened file. Only present on success.
+ */
+struct storage_file_open_resp {
+	uint32_t handle;
+};
+
+/**
+ * struct storage_file_close_req - request format for STORAGE_FILE_CLOSE
+ * @handle: the handle for the file to close
+ */
+struct storage_file_close_req {
+	uint32_t handle;
+};
+
+/**
+ * struct storage_file_read_req - request format for STORAGE_FILE_READ
+ * @handle: the handle for the file from which to read
+ * @size:   the quantity of bytes to read from the file
+ * @offset: the offset in the file from whence to read
+ */
+struct storage_file_read_req {
+	uint32_t handle;
+	uint32_t size;
+	uint64_t offset;
+};
+
+/**
+ * struct storage_file_read_resp - response format for STORAGE_FILE_READ
+ * @data: beginning of data retrieved from file
+ */
+struct storage_file_read_resp {
+	uint8_t data[0];
+};
+
+/**
+ * struct storage_file_write_req - request format for STORAGE_FILE_WRITE
+ * @handle:     the handle for the file to write to
+ * @offset:     the offset in the file from whence to write
+ * @__reserved: unused, must be set to 0.
+ * @data:       beginning of the data to be written
+ */
+struct storage_file_write_req {
+	uint64_t offset;
+	uint32_t handle;
+	uint32_t __reserved;
+	uint8_t  data[0];
+};
+
+/**
+ * struct storage_file_get_size_req - request format for STORAGE_FILE_GET_SIZE
+ * @handle: handle for which the size is requested
+ */
+struct storage_file_get_size_req {
+	uint32_t handle;
+};
+
+/**
+ * struct storage_file_get_size_resp - response format for STORAGE_FILE_GET_SIZE
+ * @size:   the size of the file
+ */
+struct storage_file_get_size_resp {
+	uint64_t size;
+};
+
+/**
+ * struct storage_file_set_size_req - request format for STORAGE_FILE_SET_SIZE
+ * @handle: the file handle
+ * @size:   the desired size of the file
+ */
+struct storage_file_set_size_req {
+	uint64_t size;
+	uint32_t handle;
+};
+
+/**
+ * struct storage_rpmb_send_req - request format for STORAGE_RPMB_SEND
+ * @reliable_write_size:        size in bytes of reliable write region
+ * @write_size:                 size in bytes of write region
+ * @read_size:                  number of bytes to read for a read request
+ * @__reserved:                 unused, must be set to 0
+ * @payload:                    start of reliable write region, followed by
+ *                              write region.
+ *
+ * Only used in proxy<->server interface.
+ */
+struct storage_rpmb_send_req {
+	uint32_t reliable_write_size;
+	uint32_t write_size;
+	uint32_t read_size;
+	uint32_t __reserved;
+	uint8_t  payload[0];
+};
+
+/**
+ * struct storage_rpmb_send_resp: response type for STORAGE_RPMB_SEND
+ * @data: the data frames frames retrieved from the MMC.
+ */
+struct storage_rpmb_send_resp {
+	uint8_t data[0];
+};
+
+/**
+ * struct storage_msg - generic req/resp format for all storage commands
+ * @cmd:        one of enum storage_cmd
+ * @op_id:      client chosen operation identifier for an instance
+ *              of a command or atomic grouping of commands (transaction).
+ * @flags:      one or many of enum storage_msg_flag or'ed together.
+ * @size:       total size of the message including this header
+ * @result:     one of enum storage_err
+ * @__reserved: unused, must be set to 0.
+ * @payload:    beginning of command specific message format
+ */
+struct storage_msg {
+	uint32_t cmd;
+	uint32_t op_id;
+	uint32_t flags;
+	uint32_t size;
+	int32_t  result;
+	uint32_t __reserved;
+	uint8_t  payload[0];
+};
+
diff --git a/trusty/storage/lib/Android.mk b/trusty/storage/lib/Android.mk
new file mode 100644
index 0000000..7e0fc9d
--- /dev/null
+++ b/trusty/storage/lib/Android.mk
@@ -0,0 +1,37 @@
+#
+# 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 := libtrustystorage
+
+LOCAL_SRC_FILES := \
+	storage.c \
+
+LOCAL_CLFAGS = -fvisibility=hidden -Wall -Werror
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+
+LOCAL_STATIC_LIBRARIES := \
+	liblog \
+	libtrusty \
+	libtrustystorageinterface
+
+include $(BUILD_STATIC_LIBRARY)
+
diff --git a/trusty/storage/lib/include/trusty/lib/storage.h b/trusty/storage/lib/include/trusty/lib/storage.h
new file mode 100644
index 0000000..b8ddf67
--- /dev/null
+++ b/trusty/storage/lib/include/trusty/lib/storage.h
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <trusty/interface/storage.h>
+
+#define STORAGE_MAX_NAME_LENGTH_BYTES 159
+
+__BEGIN_DECLS
+
+typedef uint32_t storage_session_t;
+typedef uint64_t file_handle_t;
+typedef uint64_t storage_off_t;
+
+#define STORAGE_INVALID_SESSION ((storage_session_t)-1)
+
+/**
+ * storage_ops_flags - storage related operation flags
+ * @STORAGE_OP_COMPLETE: forces to commit current transaction
+ */
+enum storage_ops_flags {
+    STORAGE_OP_COMPLETE = 0x1,
+};
+
+/**
+ * storage_open_session() - Opens a storage session.
+ * @device:    device node for talking with Trusty
+ * @session_p: pointer to location in which to store session handle
+ *             in case of success.
+ *
+ * Return: 0 on success, or an error code < 0 on failure.
+ */
+int storage_open_session(const char *device, storage_session_t *session_p, const char *port);
+
+/**
+ * storage_close_session() - Closes the session.
+ * @session: the session to close
+ */
+void storage_close_session(storage_session_t session);
+
+/**
+ * storage_open_file() - Opens a file
+ * @session:  the storage_session_t returned from a call to storage_open_session
+ * @handle_p: pointer to location in which to store file handle in case of success
+ * @name:     a null-terminated string identifier of the file to open.
+ *            Cannot be more than STORAGE_MAX_NAME_LENGTH_BYTES in length.
+ * @flags:    A bitmask consisting any storage_file_flag value or'ed together:
+ * - STORAGE_FILE_OPEN_CREATE:           if this file does not exist, create it.
+ * - STORAGE_FILE_OPEN_CREATE_EXCLUSIVE: when specified, opening file with
+ *                                       STORAGE_OPEN_FILE_CREATE flag will
+ *                                       fail if the file already exists.
+ *                                       Only meaningful if used in combination
+ *                                       with STORAGE_FILE_OPEN_CREATE flag.
+ * - STORAGE_FILE_OPEN_TRUNCATE: if this file already exists, discard existing
+ *                               content and open it as a new file. No change
+ *                               in semantics if the  file does not exist.
+ * @opflags: a combination of @storage_op_flags
+ *
+ * Return: 0 on success, or an error code < 0 on failure.
+ */
+int storage_open_file(storage_session_t session, file_handle_t *handle_p,
+                      const char *name, uint32_t flags, uint32_t opflags);
+
+/**
+ * storage_close_file() - Closes a file.
+ * @handle: the file_handle_t retrieved from storage_open_file
+ */
+void storage_close_file(file_handle_t handle);
+
+/**
+ * storage_delete_file - Deletes a file.
+ * @session: the storage_session_t returned from a call to storage_open_session
+ * @name: the name of the file to delete
+ * @opflags: a combination of @storage_op_flags
+ *
+ * Return: 0 on success, or an error code < 0 on failure.
+ */
+int storage_delete_file(storage_session_t session, const char *name,
+                        uint32_t opflags);
+
+/**
+ * storage_read() - Reads a file at a given offset.
+ * @handle: the file_handle_t retrieved from storage_open_file
+ * @off: the start offset from whence to read in the file
+ * @buf: the buffer in which to write the data read
+ * @size: the size of buf and number of bytes to read
+ *
+ * Return: the number of bytes read on success, negative error code on failure
+ */
+ssize_t storage_read(file_handle_t handle,
+                     storage_off_t off, void *buf, size_t size);
+
+/**
+ * storage_write() - Writes to a file at a given offset. Grows the file if necessary.
+ * @handle: the file_handle_t retrieved from storage_open_file
+ * @off: the start offset from whence to write in the file
+ * @buf: the buffer containing the data to write
+ * @size: the size of buf and number of bytes to write
+ * @opflags: a combination of @storage_op_flags
+ *
+ * Return: the number of bytes written on success, negative error code on failure
+ */
+ssize_t storage_write(file_handle_t handle,
+                      storage_off_t off, const void *buf, size_t size,
+                      uint32_t opflags);
+
+/**
+ * storage_set_file_size() - Sets the size of the file.
+ * @handle: the file_handle_t retrieved from storage_open_file
+ * @off: the number of bytes to set as the new size of the file
+ * @opflags: a combination of @storage_op_flags
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int storage_set_file_size(file_handle_t handle, storage_off_t file_size,
+                          uint32_t opflags);
+
+/**
+ * storage_get_file_size() - Gets the size of the file.
+ * @session: the storage_session_t returned from a call to storage_open_session
+ * @handle: the file_handle_t retrieved from storage_open_file
+ * @size: pointer to storage_off_t in which to store the file size
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int storage_get_file_size(file_handle_t handle, storage_off_t *size);
+
+
+/**
+ * storage_end_transaction: End current transaction
+ * @session: the storage_session_t returned from a call to storage_open_session
+ * @complete: if true, commit current transaction, discard it otherwise
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int storage_end_transaction(storage_session_t session, bool complete);
+
+
+__END_DECLS
diff --git a/trusty/storage/lib/storage.c b/trusty/storage/lib/storage.c
new file mode 100644
index 0000000..915bc17
--- /dev/null
+++ b/trusty/storage/lib/storage.c
@@ -0,0 +1,311 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "trusty_storage_client"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/uio.h>
+
+#include <log/log.h>
+#include <trusty/tipc.h>
+#include <trusty/lib/storage.h>
+
+#define MAX_CHUNK_SIZE 4040
+
+static inline file_handle_t make_file_handle(storage_session_t s, uint32_t fid)
+{
+    return ((uint64_t)s << 32) | fid;
+}
+
+static inline storage_session_t _to_session(file_handle_t fh)
+{
+    return (storage_session_t)(fh >> 32);
+}
+
+static inline uint32_t _to_handle(file_handle_t fh)
+{
+    return (uint32_t) fh;
+}
+
+static inline uint32_t _to_msg_flags(uint32_t opflags)
+{
+    uint32_t msg_flags = 0;
+
+    if (opflags & STORAGE_OP_COMPLETE)
+        msg_flags |= STORAGE_MSG_FLAG_TRANSACT_COMPLETE;
+
+    return msg_flags;
+}
+
+static ssize_t check_response(struct storage_msg *msg, ssize_t res)
+{
+    if (res < 0)
+        return res;
+
+    if ((size_t)res < sizeof(*msg)) {
+        ALOGE("invalid msg length (%zd < %zd)\n", res, sizeof(*msg));
+        return -EIO;
+    }
+
+    ALOGV("cmd 0x%x: server returned %u\n", msg->cmd, msg->result);
+
+    switch(msg->result) {
+        case STORAGE_NO_ERROR:
+            return res - sizeof(*msg);
+
+        case STORAGE_ERR_NOT_FOUND:
+            return -ENOENT;
+
+        case STORAGE_ERR_EXIST:
+            return -EEXIST;
+
+        case STORAGE_ERR_NOT_VALID:
+            return -EINVAL;
+
+        case STORAGE_ERR_UNIMPLEMENTED:
+            ALOGE("cmd 0x%x: is unhandles command\n", msg->cmd);
+            return -EINVAL;
+
+        case STORAGE_ERR_ACCESS:
+             return -EACCES;
+
+        case STORAGE_ERR_TRANSACT:
+             return -EBUSY;
+
+        case STORAGE_ERR_GENERIC:
+            ALOGE("cmd 0x%x: internal server error\n", msg->cmd);
+            return -EIO;
+
+        default:
+            ALOGE("cmd 0x%x: unhandled server response %u\n",
+                   msg->cmd, msg->result);
+    }
+
+    return -EIO;
+}
+
+static ssize_t send_reqv(storage_session_t session,
+                         const struct iovec *tx_iovs, uint tx_iovcnt,
+                         const struct iovec *rx_iovs, uint rx_iovcnt)
+{
+    ssize_t rc;
+
+    rc = writev(session, tx_iovs, tx_iovcnt);
+    if (rc < 0) {
+        rc = -errno;
+        ALOGE("failed to send request: %s\n", strerror(errno));
+        return rc;
+    }
+
+    rc = readv(session, rx_iovs, rx_iovcnt);
+    if (rc < 0) {
+        rc = -errno;
+        ALOGE("failed to recv response: %s\n", strerror(errno));
+        return rc;
+    }
+
+    return rc;
+}
+
+int storage_open_session(const char *device, storage_session_t *session_p,
+                         const char *port)
+{
+    int rc = tipc_connect(device, port);
+    if (rc < 0)
+        return rc;
+    *session_p = (storage_session_t) rc;
+    return 0;
+}
+
+void storage_close_session(storage_session_t session)
+{
+    tipc_close(session);
+}
+
+
+int storage_open_file(storage_session_t session, file_handle_t *handle_p, const char *name,
+                      uint32_t flags, uint32_t opflags)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_OPEN, .flags = _to_msg_flags(opflags)};
+    struct storage_file_open_req req = { .flags = flags };
+    struct iovec tx[3] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}, {(void *)name, strlen(name)}};
+    struct storage_file_open_resp rsp = { 0 };
+    struct iovec rx[2] = {{&msg, sizeof(msg)}, {&rsp, sizeof(rsp)}};
+
+    ssize_t rc = send_reqv(session, tx, 3, rx, 2);
+    rc = check_response(&msg, rc);
+    if (rc < 0)
+        return rc;
+
+    if ((size_t)rc != sizeof(rsp)) {
+        ALOGE("%s: invalid response length (%zd != %zd)\n", __func__, rc, sizeof(rsp));
+        return -EIO;
+    }
+
+    *handle_p = make_file_handle(session, rsp.handle);
+    return 0;
+}
+
+void storage_close_file(file_handle_t fh)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_CLOSE };
+    struct storage_file_close_req req = { .handle = _to_handle(fh)};
+    struct iovec tx[2] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}};
+    struct iovec rx[1] = {{&msg, sizeof(msg)}};
+
+    ssize_t rc = send_reqv(_to_session(fh), tx, 2, rx, 1);
+    rc = check_response(&msg, rc);
+    if (rc < 0) {
+        ALOGE("close file failed (%d)\n", (int)rc);
+    }
+}
+
+int storage_delete_file(storage_session_t session, const char *name, uint32_t opflags)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_DELETE, .flags = _to_msg_flags(opflags)};
+    struct storage_file_delete_req req = { .flags = 0, };
+    struct iovec tx[3] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}, {(void *)name, strlen(name)}};
+    struct iovec rx[1] = {{&msg, sizeof(msg)}};
+
+    ssize_t rc = send_reqv(session, tx, 3, rx, 1);
+    return check_response(&msg, rc);
+}
+
+static int _read_chunk(file_handle_t fh, storage_off_t off, void *buf, size_t size)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_READ };
+    struct storage_file_read_req req = { .handle = _to_handle(fh), .size = size, .offset = off };
+    struct iovec tx[2] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}};
+    struct iovec rx[2] = {{&msg, sizeof(msg)}, {buf, size}};
+
+    ssize_t rc = send_reqv(_to_session(fh), tx, 2, rx, 2);
+    return check_response(&msg, rc);
+}
+
+ssize_t storage_read(file_handle_t fh, storage_off_t off, void *buf, size_t size)
+{
+    int rc;
+    size_t bytes_read = 0;
+    size_t chunk = MAX_CHUNK_SIZE;
+    uint8_t *ptr = buf;
+
+    while (size) {
+        if (chunk > size)
+            chunk = size;
+        rc = _read_chunk(fh, off, ptr, chunk);
+        if (rc < 0)
+            return rc;
+        if (rc == 0)
+            break;
+        off += rc;
+        ptr += rc;
+        bytes_read += rc;
+        size -= rc;
+    }
+    return bytes_read;
+}
+
+static int _write_req(file_handle_t fh, storage_off_t off,
+                      const void *buf, size_t size, uint32_t msg_flags)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_WRITE, .flags = msg_flags, };
+    struct storage_file_write_req req = { .handle = _to_handle(fh), .offset = off, };
+    struct iovec tx[3] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}, {(void *)buf, size}};
+    struct iovec rx[1] = {{&msg, sizeof(msg)}};
+
+    ssize_t rc = send_reqv(_to_session(fh), tx, 3, rx, 1);
+    rc = check_response(&msg, rc);
+    return rc < 0 ? rc : size;
+}
+
+ssize_t storage_write(file_handle_t fh, storage_off_t off,
+                      const void *buf, size_t size, uint32_t opflags)
+{
+    int rc;
+    size_t bytes_written = 0;
+    size_t chunk = MAX_CHUNK_SIZE;
+    const uint8_t *ptr = buf;
+    uint32_t msg_flags = _to_msg_flags(opflags & ~STORAGE_OP_COMPLETE);
+
+    while (size) {
+        if (chunk >= size) {
+            /* last chunk in sequence */
+            chunk = size;
+            msg_flags = _to_msg_flags(opflags);
+        }
+        rc = _write_req(fh, off, ptr, chunk, msg_flags);
+        if (rc < 0)
+            return rc;
+        if ((size_t)rc != chunk) {
+            ALOGE("got partial write (%d)\n", (int)rc);
+            return -EIO;
+        }
+        off += chunk;
+        ptr += chunk;
+        bytes_written += chunk;
+        size -= chunk;
+    }
+    return bytes_written;
+}
+
+int storage_set_file_size(file_handle_t fh, storage_off_t file_size, uint32_t opflags)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_SET_SIZE, .flags = _to_msg_flags(opflags)};
+    struct storage_file_set_size_req req = { .handle = _to_handle(fh), .size = file_size, };
+    struct iovec tx[2] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}};
+    struct iovec rx[1] = {{&msg, sizeof(msg)}};
+
+    ssize_t rc = send_reqv(_to_session(fh), tx, 2, rx, 1);
+    return check_response(&msg, rc);
+}
+
+int storage_get_file_size(file_handle_t fh, storage_off_t *size_p)
+{
+    struct storage_msg msg = { .cmd = STORAGE_FILE_GET_SIZE };
+    struct storage_file_get_size_req  req = { .handle = _to_handle(fh), };
+    struct iovec tx[2] = {{&msg, sizeof(msg)}, {&req, sizeof(req)}};
+    struct storage_file_get_size_resp rsp;
+    struct iovec rx[2] = {{&msg, sizeof(msg)}, {&rsp, sizeof(rsp)}};
+
+    ssize_t rc = send_reqv(_to_session(fh), tx, 2, rx, 2);
+    rc = check_response(&msg, rc);
+    if (rc < 0)
+        return rc;
+
+    if ((size_t)rc != sizeof(rsp)) {
+        ALOGE("%s: invalid response length (%zd != %zd)\n", __func__, rc, sizeof(rsp));
+        return -EIO;
+    }
+
+    *size_p = rsp.size;
+    return 0;
+}
+
+int storage_end_transaction(storage_session_t session, bool complete)
+{
+    struct storage_msg msg = {
+        .cmd = STORAGE_END_TRANSACTION,
+        .flags = complete ? STORAGE_MSG_FLAG_TRANSACT_COMPLETE : 0,
+    };
+    struct iovec iov = {&msg, sizeof(msg)};
+
+    ssize_t rc = send_reqv(session, &iov, 1, &iov, 1);
+    return check_response(&msg, rc);
+}
diff --git a/trusty/storage/proxy/Android.mk b/trusty/storage/proxy/Android.mk
new file mode 100644
index 0000000..745e302
--- /dev/null
+++ b/trusty/storage/proxy/Android.mk
@@ -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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := storageproxyd
+
+LOCAL_C_INCLUDES += bionic/libc/kernel/uapi
+
+LOCAL_SRC_FILES := \
+	ipc.c \
+	rpmb.c \
+	storage.c \
+	proxy.c
+
+LOCAL_CLFAGS = -Wall -Werror
+
+LOCAL_SHARED_LIBRARIES := \
+	liblog \
+
+LOCAL_STATIC_LIBRARIES := \
+	libtrustystorageinterface \
+	libtrusty
+
+include $(BUILD_EXECUTABLE)
+
diff --git a/trusty/storage/proxy/ipc.c b/trusty/storage/proxy/ipc.c
new file mode 100644
index 0000000..57cf600
--- /dev/null
+++ b/trusty/storage/proxy/ipc.c
@@ -0,0 +1,115 @@
+/*
+ * 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 <assert.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include <trusty/tipc.h>
+
+#include "ipc.h"
+#include "log.h"
+
+#define MAX_RECONNECT_RETRY_COUNT 5
+#define TRUSTY_RECONNECT_TIMEOUT_SEC 5
+
+static int tipc_fd = -1;
+
+int ipc_connect(const char *device, const char *port)
+{
+    int rc;
+    uint retry_cnt = 0;
+
+    assert(tipc_fd == -1);
+
+    while(true) {
+        rc = tipc_connect(device, port);
+        if (rc >= 0)
+            break;
+
+        ALOGE("failed (%d) to connect to storage server\n", rc);
+        if (++retry_cnt > MAX_RECONNECT_RETRY_COUNT) {
+            ALOGE("max number of reconnect retries (%d) has been reached\n",
+                   retry_cnt);
+            return -1;
+        }
+        sleep(TRUSTY_RECONNECT_TIMEOUT_SEC);
+    }
+    tipc_fd = rc;
+    return 0;
+}
+
+void ipc_disconnect(void)
+{
+    assert(tipc_fd >=  0);
+
+    tipc_close(tipc_fd);
+    tipc_fd = -1;
+}
+
+ssize_t ipc_get_msg(struct storage_msg *msg, void *req_buf, size_t req_buf_len)
+{
+    ssize_t rc;
+    struct iovec iovs[2] = {{msg, sizeof(*msg)}, {req_buf, req_buf_len}};
+
+    assert(tipc_fd >=  0);
+
+    rc = readv(tipc_fd, iovs, 2);
+    if (rc < 0) {
+        ALOGE("failed to read request: %s\n", strerror(errno));
+        return rc;
+    }
+
+   /* check for minimum size */
+   if ((size_t)rc < sizeof(*msg)) {
+       ALOGE("message is too short (%zu bytes received)\n", rc);
+       return -1;
+   }
+
+   /* check for message completeness */
+   if (msg->size != (uint32_t)rc) {
+       ALOGE("inconsistent message size [cmd=%d] (%u != %u)\n",
+             msg->cmd, msg->size, (uint32_t)rc);
+       return -1;
+   }
+
+   return rc - sizeof(*msg);
+}
+
+int ipc_respond(struct storage_msg *msg, void *out, size_t out_size)
+{
+    ssize_t rc;
+    struct iovec iovs[2] = {{msg, sizeof(*msg)}, {out, out_size}};
+
+    assert(tipc_fd >=  0);
+
+    msg->cmd |= STORAGE_RESP_BIT;
+
+    rc = writev(tipc_fd, iovs, out ? 2 : 1);
+    if (rc < 0) {
+        ALOGE("error sending response 0x%x: %s\n",
+              msg->cmd, strerror(errno));
+        return -1;
+    }
+
+    return 0;
+}
+
+
diff --git a/trusty/storage/proxy/ipc.h b/trusty/storage/proxy/ipc.h
new file mode 100644
index 0000000..2e366bb
--- /dev/null
+++ b/trusty/storage/proxy/ipc.h
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+#pragma once
+
+#include <stdint.h>
+#include <trusty/interface/storage.h>
+
+int ipc_connect(const char *device, const char *service_name);
+void ipc_disconnect(void);
+ssize_t ipc_get_msg(struct storage_msg *msg, void *req_buf, size_t req_buf_len);
+int ipc_respond(struct storage_msg *msg, void *out, size_t out_size);
diff --git a/trusty/storage/proxy/log.h b/trusty/storage/proxy/log.h
new file mode 100644
index 0000000..c81beab
--- /dev/null
+++ b/trusty/storage/proxy/log.h
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "storageproxyd"
+
+#include <log/log.h>
+
diff --git a/trusty/storage/proxy/proxy.c b/trusty/storage/proxy/proxy.c
new file mode 100644
index 0000000..d645ac0
--- /dev/null
+++ b/trusty/storage/proxy/proxy.c
@@ -0,0 +1,264 @@
+/*
+ * 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 <getopt.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <private/android_filesystem_config.h>
+
+#include "ipc.h"
+#include "log.h"
+#include "rpmb.h"
+#include "storage.h"
+
+#define REQ_BUFFER_SIZE 4096
+static uint8_t req_buffer[REQ_BUFFER_SIZE + 1];
+
+static const char *ss_data_root;
+static const char *trusty_devname;
+static const char *rpmb_devname;
+static const char *ss_srv_name = STORAGE_DISK_PROXY_PORT;
+
+static const char *_sopts = "hp:d:r:";
+static const struct option _lopts[] =  {
+    {"help",       no_argument,       NULL, 'h'},
+    {"trusty_dev", required_argument, NULL, 'd'},
+    {"data_path",  required_argument, NULL, 'p'},
+    {"rpmb_dev",   required_argument, NULL, 'r'},
+    {0, 0, 0, 0}
+};
+
+static void show_usage_and_exit(int code)
+{
+    ALOGE("usage: storageproxyd -d <trusty_dev> -p <data_path> -r <rpmb_dev>\n");
+    exit(code);
+}
+
+static int drop_privs(void)
+{
+    struct __user_cap_header_struct capheader;
+    struct __user_cap_data_struct capdata[2];
+
+    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
+        return -1;
+    }
+
+    /*
+     * ensure we're running as the system user
+     */
+    if (setgid(AID_SYSTEM) != 0) {
+        return -1;
+    }
+
+    if (setuid(AID_SYSTEM) != 0) {
+        return -1;
+    }
+
+    /*
+     * drop all capabilities except SYS_RAWIO
+     */
+    memset(&capheader, 0, sizeof(capheader));
+    memset(&capdata, 0, sizeof(capdata));
+    capheader.version = _LINUX_CAPABILITY_VERSION_3;
+    capheader.pid = 0;
+
+    capdata[CAP_TO_INDEX(CAP_SYS_RAWIO)].permitted = CAP_TO_MASK(CAP_SYS_RAWIO);
+    capdata[CAP_TO_INDEX(CAP_SYS_RAWIO)].effective = CAP_TO_MASK(CAP_SYS_RAWIO);
+
+    if (capset(&capheader, &capdata[0]) < 0) {
+        return -1;
+    }
+
+    /* no-execute for user, no access for group and other */
+    umask(S_IXUSR | S_IRWXG | S_IRWXO);
+
+    return 0;
+}
+
+static int handle_req(struct storage_msg *msg, const void *req, size_t req_len)
+{
+    int rc;
+
+    if ((msg->flags & STORAGE_MSG_FLAG_POST_COMMIT) &&
+        (msg->cmd != STORAGE_RPMB_SEND)) {
+        /*
+         * handling post commit messages on non rpmb commands are not
+         * implemented as there is no use case for this yet.
+         */
+        ALOGE("cmd 0x%x: post commit option is not implemented\n", msg->cmd);
+        msg->result = STORAGE_ERR_UNIMPLEMENTED;
+        return ipc_respond(msg, NULL, 0);
+    }
+
+    if (msg->flags & STORAGE_MSG_FLAG_PRE_COMMIT) {
+        rc = storage_sync_checkpoint();
+        if (rc < 0) {
+            msg->result = STORAGE_ERR_GENERIC;
+            return ipc_respond(msg, NULL, 0);
+        }
+    }
+
+    switch (msg->cmd) {
+    case STORAGE_FILE_DELETE:
+        rc = storage_file_delete(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_OPEN:
+        rc = storage_file_open(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_CLOSE:
+        rc = storage_file_close(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_WRITE:
+        rc = storage_file_write(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_READ:
+        rc = storage_file_read(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_GET_SIZE:
+        rc = storage_file_get_size(msg, req, req_len);
+        break;
+
+    case STORAGE_FILE_SET_SIZE:
+        rc = storage_file_set_size(msg, req, req_len);
+        break;
+
+    case STORAGE_RPMB_SEND:
+        rc = rpmb_send(msg, req, req_len);
+        break;
+
+    default:
+        ALOGE("unhandled command 0x%x\n", msg->cmd);
+        msg->result = STORAGE_ERR_UNIMPLEMENTED;
+        rc = 1;
+    }
+
+    if (rc > 0) {
+        /* still need to send response */
+        rc = ipc_respond(msg, NULL, 0);
+    }
+    return rc;
+}
+
+static int proxy_loop(void)
+{
+    ssize_t rc;
+    struct storage_msg msg;
+
+    /* enter main message handling loop */
+    while (true) {
+
+        /* get incoming message */
+        rc = ipc_get_msg(&msg, req_buffer, REQ_BUFFER_SIZE);
+        if (rc < 0)
+            return rc;
+
+        /* handle request */
+        req_buffer[rc] = 0; /* force zero termination */
+        rc = handle_req(&msg, req_buffer, rc);
+        if (rc)
+            return rc;
+    }
+
+    return 0;
+}
+
+static void parse_args(int argc, char *argv[])
+{
+    int opt;
+    int oidx = 0;
+
+    while ((opt = getopt_long(argc, argv, _sopts, _lopts, &oidx)) != -1) {
+        switch (opt) {
+
+        case 'd':
+            trusty_devname = strdup(optarg);
+            break;
+
+        case 'p':
+            ss_data_root = strdup(optarg);
+            break;
+
+        case 'r':
+            rpmb_devname = strdup(optarg);
+            break;
+
+        default:
+            ALOGE("unrecognized option (%c):\n", opt);
+            show_usage_and_exit(EXIT_FAILURE);
+        }
+    }
+
+    if (ss_data_root == NULL ||
+        trusty_devname == NULL ||
+        rpmb_devname == NULL) {
+        ALOGE("missing required argument(s)\n");
+        show_usage_and_exit(EXIT_FAILURE);
+    }
+
+    ALOGI("starting storageproxyd\n");
+    ALOGI("storage data root: %s\n", ss_data_root);
+    ALOGI("trusty dev: %s\n", trusty_devname);
+    ALOGI("rpmb dev: %s\n", rpmb_devname);
+}
+
+int main(int argc, char *argv[])
+{
+    int rc;
+    uint retry_cnt;
+
+    /* drop privileges */
+    if (drop_privs() < 0)
+        return EXIT_FAILURE;
+
+    /* parse arguments */
+    parse_args(argc, argv);
+
+    /* initialize secure storage directory */
+    rc = storage_init(ss_data_root);
+    if (rc < 0)
+        return EXIT_FAILURE;
+
+    /* open rpmb device */
+    rc = rpmb_open(rpmb_devname);
+    if (rc < 0)
+        return EXIT_FAILURE;
+
+    /* connect to Trusty secure storage server */
+    rc = ipc_connect(trusty_devname, ss_srv_name);
+    if (rc < 0)
+        return EXIT_FAILURE;
+
+    /* enter main loop */
+    rc = proxy_loop();
+    ALOGE("exiting proxy loop with status (%d)\n", rc);
+
+    ipc_disconnect();
+    rpmb_close();
+
+    return (rc < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/trusty/storage/proxy/rpmb.c b/trusty/storage/proxy/rpmb.c
new file mode 100644
index 0000000..9c79105
--- /dev/null
+++ b/trusty/storage/proxy/rpmb.c
@@ -0,0 +1,211 @@
+/*
+ * 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 <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include <linux/major.h>
+#include <linux/mmc/ioctl.h>
+
+#include "ipc.h"
+#include "log.h"
+#include "rpmb.h"
+#include "storage.h"
+
+#define MMC_READ_MULTIPLE_BLOCK 18
+#define MMC_WRITE_MULTIPLE_BLOCK 25
+#define MMC_RELIABLE_WRITE_FLAG (1 << 31)
+
+#define MMC_RSP_PRESENT (1 << 0)
+#define MMC_RSP_CRC (1 << 2)
+#define MMC_RSP_OPCODE (1 << 4)
+#define MMC_CMD_ADTC (1 << 5)
+#define MMC_RSP_SPI_S1 (1 << 7)
+#define MMC_RSP_R1 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE)
+#define MMC_RSP_SPI_R1 (MMC_RSP_SPI_S1)
+
+#define MMC_WRITE_FLAG_R 0
+#define MMC_WRITE_FLAG_W 1
+#define MMC_WRITE_FLAG_RELW (MMC_WRITE_FLAG_W | MMC_RELIABLE_WRITE_FLAG)
+
+#define MMC_BLOCK_SIZE 512
+
+static int rpmb_fd = -1;
+static uint8_t read_buf[4096];
+
+#ifdef RPMB_DEBUG
+
+static void print_buf(const char *prefix, const uint8_t *buf, size_t size)
+{
+    size_t i;
+
+    printf("%s @%p [%zu]", prefix, buf, size);
+    for (i = 0; i < size; i++) {
+        if (i && i % 32 == 0)
+            printf("\n%*s", (int) strlen(prefix), "");
+        printf(" %02x", buf[i]);
+    }
+    printf("\n");
+    fflush(stdout);
+}
+
+#endif
+
+
+int rpmb_send(struct storage_msg *msg, const void *r, size_t req_len)
+{
+    int rc;
+    struct {
+        struct mmc_ioc_multi_cmd multi;
+        struct mmc_ioc_cmd cmd_buf[3];
+    } mmc = {};
+    struct mmc_ioc_cmd *cmd = mmc.multi.cmds;
+    const struct storage_rpmb_send_req *req = r;
+
+    if (req_len < sizeof(*req)) {
+        ALOGW("malformed rpmb request: invalid length (%zu < %zu)\n",
+              req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    size_t expected_len =
+            sizeof(*req) + req->reliable_write_size + req->write_size;
+    if (req_len != expected_len) {
+        ALOGW("malformed rpmb request: invalid length (%zu != %zu)\n",
+              req_len, expected_len);
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    const uint8_t *write_buf = req->payload;
+    if (req->reliable_write_size) {
+        if ((req->reliable_write_size % MMC_BLOCK_SIZE) != 0) {
+            ALOGW("invalid reliable write size %u\n", req->reliable_write_size);
+            msg->result = STORAGE_ERR_NOT_VALID;
+            goto err_response;
+        }
+
+        cmd->write_flag = MMC_WRITE_FLAG_RELW;
+        cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
+        cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
+        cmd->blksz = MMC_BLOCK_SIZE;
+        cmd->blocks = req->reliable_write_size / MMC_BLOCK_SIZE;
+        mmc_ioc_cmd_set_data((*cmd), write_buf);
+#ifdef RPMB_DEBUG
+        ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
+        print_buf("request: ", write_buf, req->reliable_write_size);
+#endif
+        write_buf += req->reliable_write_size;
+        mmc.multi.num_of_cmds++;
+        cmd++;
+    }
+
+    if (req->write_size) {
+        if ((req->write_size % MMC_BLOCK_SIZE) != 0) {
+            ALOGW("invalid write size %u\n", req->write_size);
+            msg->result = STORAGE_ERR_NOT_VALID;
+            goto err_response;
+        }
+
+        cmd->write_flag = MMC_WRITE_FLAG_W;
+        cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
+        cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
+        cmd->blksz = MMC_BLOCK_SIZE;
+        cmd->blocks = req->write_size / MMC_BLOCK_SIZE;
+        mmc_ioc_cmd_set_data((*cmd), write_buf);
+#ifdef RPMB_DEBUG
+        ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
+        print_buf("request: ", write_buf, req->write_size);
+#endif
+        write_buf += req->write_size;
+        mmc.multi.num_of_cmds++;
+        cmd++;
+    }
+
+    if (req->read_size) {
+        if (req->read_size % MMC_BLOCK_SIZE != 0 ||
+            req->read_size > sizeof(read_buf)) {
+            ALOGE("%s: invalid read size %u\n", __func__, req->read_size);
+            msg->result = STORAGE_ERR_NOT_VALID;
+            goto err_response;
+        }
+
+        cmd->write_flag = MMC_WRITE_FLAG_R;
+        cmd->opcode = MMC_READ_MULTIPLE_BLOCK;
+        cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC,
+        cmd->blksz = MMC_BLOCK_SIZE;
+        cmd->blocks = req->read_size / MMC_BLOCK_SIZE;
+        mmc_ioc_cmd_set_data((*cmd), read_buf);
+#ifdef RPMB_DEBUG
+        ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
+#endif
+        mmc.multi.num_of_cmds++;
+        cmd++;
+    }
+
+    rc = ioctl(rpmb_fd, MMC_IOC_MULTI_CMD, &mmc.multi);
+    if (rc < 0) {
+        ALOGE("%s: mmc ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
+        msg->result = STORAGE_ERR_GENERIC;
+        goto err_response;
+    }
+#ifdef RPMB_DEBUG
+    if (req->read_size)
+        print_buf("response: ", read_buf, req->read_size);
+#endif
+
+    if (msg->flags & STORAGE_MSG_FLAG_POST_COMMIT) {
+        /*
+         * Nothing todo for post msg commit request as MMC_IOC_MULTI_CMD
+         * is fully synchronous in this implementation.
+         */
+    }
+
+    msg->result = STORAGE_NO_ERROR;
+    return ipc_respond(msg, read_buf, req->read_size);
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int rpmb_open(const char *rpmb_devname)
+{
+    int rc;
+
+    rc = open(rpmb_devname, O_RDWR, 0);
+    if (rc < 0) {
+        ALOGE("unable (%d) to open rpmb device '%s': %s\n",
+              errno, rpmb_devname, strerror(errno));
+        return rc;
+    }
+    rpmb_fd = rc;
+    return 0;
+}
+
+void rpmb_close(void)
+{
+    close(rpmb_fd);
+    rpmb_fd = -1;
+}
+
diff --git a/trusty/storage/proxy/rpmb.h b/trusty/storage/proxy/rpmb.h
new file mode 100644
index 0000000..85cff44
--- /dev/null
+++ b/trusty/storage/proxy/rpmb.h
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+#pragma once
+
+#include <stdint.h>
+#include <trusty/interface/storage.h>
+
+int rpmb_open(const char *rpmb_devname);
+int rpmb_send(struct storage_msg *msg, const void *r, size_t req_len);
+void rpmb_close(void);
diff --git a/trusty/storage/proxy/storage.c b/trusty/storage/proxy/storage.c
new file mode 100644
index 0000000..c61e89d
--- /dev/null
+++ b/trusty/storage/proxy/storage.c
@@ -0,0 +1,529 @@
+/*
+ * 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 <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "log.h"
+#include "ipc.h"
+#include "storage.h"
+
+#define FD_TBL_SIZE 64
+#define MAX_READ_SIZE 4096
+
+enum sync_state {
+    SS_UNUSED = -1,
+    SS_CLEAN =  0,
+    SS_DIRTY =  1,
+};
+
+static int ssdir_fd = -1;
+static const char *ssdir_name;
+
+static enum sync_state fs_state;
+static enum sync_state dir_state;
+static enum sync_state fd_state[FD_TBL_SIZE];
+
+static struct {
+   struct storage_file_read_resp hdr;
+   uint8_t data[MAX_READ_SIZE];
+}  read_rsp;
+
+static uint32_t insert_fd(int open_flags, int fd)
+{
+    uint32_t handle = fd;
+
+    if (open_flags & O_CREAT) {
+        dir_state = SS_DIRTY;
+    }
+
+    if (handle < FD_TBL_SIZE) {
+            fd_state[fd] = SS_CLEAN; /* fd clean */
+            if (open_flags & O_TRUNC) {
+                fd_state[fd] = SS_DIRTY;  /* set fd dirty */
+            }
+    } else {
+            ALOGW("%s: untracked fd %u\n", __func__, fd);
+            if (open_flags & (O_TRUNC | O_CREAT)) {
+                fs_state = SS_DIRTY;
+            }
+    }
+    return handle;
+}
+
+static int lookup_fd(uint32_t handle, bool dirty)
+{
+    if (dirty) {
+        if (handle < FD_TBL_SIZE) {
+            fd_state[handle] = SS_DIRTY;
+        } else {
+            fs_state = SS_DIRTY;
+        }
+    }
+    return handle;
+}
+
+static int remove_fd(uint32_t handle)
+{
+    if (handle < FD_TBL_SIZE) {
+        fd_state[handle] = SS_UNUSED; /* set to uninstalled */
+    }
+    return handle;
+}
+
+static enum storage_err translate_errno(int error)
+{
+    enum storage_err result;
+    switch (error) {
+    case 0:
+        result = STORAGE_NO_ERROR;
+        break;
+    case EBADF:
+    case EINVAL:
+    case ENOTDIR:
+    case EISDIR:
+    case ENAMETOOLONG:
+        result = STORAGE_ERR_NOT_VALID;
+        break;
+    case ENOENT:
+        result = STORAGE_ERR_NOT_FOUND;
+        break;
+    case EEXIST:
+        result = STORAGE_ERR_EXIST;
+        break;
+    case EPERM:
+    case EACCES:
+        result = STORAGE_ERR_ACCESS;
+        break;
+    default:
+        result = STORAGE_ERR_GENERIC;
+        break;
+    }
+
+    return result;
+}
+
+static ssize_t write_with_retry(int fd, const void *buf_, size_t size, off_t offset)
+{
+    ssize_t rc;
+    const uint8_t *buf = buf_;
+
+    while (size > 0) {
+        rc = TEMP_FAILURE_RETRY(pwrite(fd, buf, size, offset));
+        if (rc < 0)
+            return rc;
+        size -= rc;
+        buf += rc;
+        offset += rc;
+    }
+    return 0;
+}
+
+static ssize_t read_with_retry(int fd, void *buf_, size_t size, off_t offset)
+{
+    ssize_t rc;
+    size_t  rcnt = 0;
+    uint8_t *buf = buf_;
+
+    while (size > 0) {
+        rc = TEMP_FAILURE_RETRY(pread(fd, buf, size, offset));
+        if (rc < 0)
+            return rc;
+        if (rc == 0)
+            break;
+        size -= rc;
+        buf += rc;
+        offset += rc;
+        rcnt += rc;
+    }
+    return rcnt;
+}
+
+int storage_file_delete(struct storage_msg *msg,
+                        const void *r, size_t req_len)
+{
+    char *path = NULL;
+    const struct storage_file_delete_req *req = r;
+
+    if (req_len < sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd < %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    size_t fname_len = strlen(req->name);
+    if (fname_len != req_len - sizeof(*req)) {
+        ALOGE("%s: invalid filename length (%zd != %zd)\n",
+              __func__, fname_len, req_len - sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int rc = asprintf(&path, "%s/%s", ssdir_name, req->name);
+    if (rc < 0) {
+        ALOGE("%s: asprintf failed\n", __func__);
+        msg->result = STORAGE_ERR_GENERIC;
+        goto err_response;
+    }
+
+    dir_state = SS_DIRTY;
+    rc = unlink(path);
+    if (rc < 0) {
+        rc = errno;
+        if (errno == ENOENT) {
+            ALOGV("%s: error (%d) unlinking file '%s'\n",
+                  __func__, rc, path);
+        } else {
+            ALOGE("%s: error (%d) unlinking file '%s'\n",
+                  __func__, rc, path);
+        }
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    ALOGV("%s: \"%s\"\n", __func__, path);
+    msg->result = STORAGE_NO_ERROR;
+
+err_response:
+    if (path)
+        free(path);
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int storage_file_open(struct storage_msg *msg,
+                      const void *r, size_t req_len)
+{
+    char *path = NULL;
+    const struct storage_file_open_req *req = r;
+    struct storage_file_open_resp resp = {0};
+
+    if (req_len < sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd < %zd)\n",
+               __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    size_t fname_len = strlen(req->name);
+    if (fname_len != req_len - sizeof(*req)) {
+        ALOGE("%s: invalid filename length (%zd != %zd)\n",
+              __func__, fname_len, req_len - sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int rc = asprintf(&path, "%s/%s", ssdir_name, req->name);
+    if (rc < 0) {
+        ALOGE("%s: asprintf failed\n", __func__);
+        msg->result = STORAGE_ERR_GENERIC;
+        goto err_response;
+    }
+
+    int open_flags = O_RDWR;
+
+    if (req->flags & STORAGE_FILE_OPEN_TRUNCATE)
+        open_flags |= O_TRUNC;
+
+    if (req->flags & STORAGE_FILE_OPEN_CREATE) {
+        /* open or create */
+        if (req->flags & STORAGE_FILE_OPEN_CREATE_EXCLUSIVE) {
+            /* create exclusive */
+            open_flags |= O_CREAT | O_EXCL;
+            rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
+        } else {
+            /* try open first */
+            rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
+            if (rc == -1 && errno == ENOENT) {
+                /* then try open with O_CREATE */
+                open_flags |= O_CREAT;
+                rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
+            }
+
+        }
+    } else {
+        /* open an existing file */
+        rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
+    }
+
+    if (rc < 0) {
+        rc = errno;
+        if (errno == EEXIST || errno == ENOENT) {
+            ALOGV("%s: failed to open file \"%s\": %s\n",
+                  __func__, path, strerror(errno));
+        } else {
+            ALOGE("%s: failed to open file \"%s\": %s\n",
+                  __func__, path, strerror(errno));
+        }
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+    free(path);
+
+    /* at this point rc contains storage file fd */
+    msg->result = STORAGE_NO_ERROR;
+    resp.handle = insert_fd(open_flags, rc);
+    ALOGV("%s: \"%s\": fd = %u: handle = %d\n",
+          __func__, path, rc, resp.handle);
+
+    return ipc_respond(msg, &resp, sizeof(resp));
+
+err_response:
+    if (path)
+        free(path);
+    return ipc_respond(msg, NULL, 0);
+}
+
+int storage_file_close(struct storage_msg *msg,
+                       const void *r, size_t req_len)
+{
+    const struct storage_file_close_req *req = r;
+
+    if (req_len != sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd != %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int fd = remove_fd(req->handle);
+    ALOGV("%s: handle = %u: fd = %u\n", __func__, req->handle, fd);
+
+    int rc = fsync(fd);
+    if (rc < 0) {
+        rc = errno;
+        ALOGE("%s: fsync failed for fd=%u: %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    rc = close(fd);
+    if (rc < 0) {
+        rc = errno;
+        ALOGE("%s: close failed for fd=%u: %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    msg->result = STORAGE_NO_ERROR;
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int storage_file_write(struct storage_msg *msg,
+                       const void *r, size_t req_len)
+{
+    int rc;
+    const struct storage_file_write_req *req = r;
+
+    if (req_len < sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd < %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int fd = lookup_fd(req->handle, true);
+    if (write_with_retry(fd, &req->data[0], req_len - sizeof(*req),
+                         req->offset) < 0) {
+        rc = errno;
+        ALOGW("%s: error writing file (fd=%d): %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    msg->result = STORAGE_NO_ERROR;
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int storage_file_read(struct storage_msg *msg,
+                      const void *r, size_t req_len)
+{
+    int rc;
+    const struct storage_file_read_req *req = r;
+
+    if (req_len != sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd != %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    if (req->size > MAX_READ_SIZE) {
+        ALOGW("%s: request is too large (%zd > %zd) - refusing\n",
+              __func__, req->size, MAX_READ_SIZE);
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int fd = lookup_fd(req->handle, false);
+    ssize_t read_res = read_with_retry(fd, read_rsp.hdr.data, req->size,
+                                       (off_t)req->offset);
+    if (read_res < 0) {
+        rc = errno;
+        ALOGW("%s: error reading file (fd=%d): %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    msg->result = STORAGE_NO_ERROR;
+    return ipc_respond(msg, &read_rsp, read_res + sizeof(read_rsp.hdr));
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int storage_file_get_size(struct storage_msg *msg,
+                          const void *r, size_t req_len)
+{
+    const struct storage_file_get_size_req *req = r;
+    struct storage_file_get_size_resp resp = {0};
+
+    if (req_len != sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd != %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    struct stat stat;
+    int fd = lookup_fd(req->handle, false);
+    int rc = fstat(fd, &stat);
+    if (rc < 0) {
+        rc = errno;
+        ALOGE("%s: error stat'ing file (fd=%d): %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    resp.size = stat.st_size;
+    msg->result = STORAGE_NO_ERROR;
+    return ipc_respond(msg, &resp, sizeof(resp));
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+
+int storage_file_set_size(struct storage_msg *msg,
+                          const void *r, size_t req_len)
+{
+    const struct storage_file_set_size_req *req = r;
+
+    if (req_len != sizeof(*req)) {
+        ALOGE("%s: invalid request length (%zd != %zd)\n",
+              __func__, req_len, sizeof(*req));
+        msg->result = STORAGE_ERR_NOT_VALID;
+        goto err_response;
+    }
+
+    int fd = lookup_fd(req->handle, true);
+    int rc = TEMP_FAILURE_RETRY(ftruncate(fd, req->size));
+    if (rc < 0) {
+        rc = errno;
+        ALOGE("%s: error truncating file (fd=%d): %s\n",
+              __func__, fd, strerror(errno));
+        msg->result = translate_errno(rc);
+        goto err_response;
+    }
+
+    msg->result = STORAGE_NO_ERROR;
+
+err_response:
+    return ipc_respond(msg, NULL, 0);
+}
+
+int storage_init(const char *dirname)
+{
+    fs_state = SS_CLEAN;
+    dir_state = SS_CLEAN;
+    for (uint i = 0; i < FD_TBL_SIZE; i++) {
+        fd_state[i] = SS_UNUSED;  /* uninstalled */
+    }
+
+    ssdir_fd = open(dirname, O_RDONLY);
+    if (ssdir_fd < 0) {
+        ALOGE("failed to open ss root dir \"%s\": %s\n",
+               dirname, strerror(errno));
+        return -1;
+    }
+    ssdir_name = dirname;
+    return 0;
+}
+
+int storage_sync_checkpoint(void)
+{
+    int rc;
+
+    /* sync fd table and reset it to clean state first */
+    for (uint fd = 0; fd < FD_TBL_SIZE; fd++) {
+         if (fd_state[fd] == SS_DIRTY) {
+             if (fs_state == SS_CLEAN) {
+                 /* need to sync individual fd */
+                 rc = fsync(fd);
+                 if (rc < 0) {
+                     ALOGE("fsync for fd=%d failed: %s\n", fd, strerror(errno));
+                     return rc;
+                 }
+             }
+             fd_state[fd] = SS_CLEAN; /* set to clean */
+         }
+    }
+
+    /* check if we need to sync the directory */
+    if (dir_state == SS_DIRTY) {
+        if (fs_state == SS_CLEAN) {
+            rc = fsync(ssdir_fd);
+            if (rc < 0) {
+                ALOGE("fsync for ssdir failed: %s\n", strerror(errno));
+                return rc;
+            }
+        }
+        dir_state = SS_CLEAN;  /* set to clean */
+    }
+
+    /* check if we need to sync the whole fs */
+    if (fs_state == SS_DIRTY) {
+        rc = syscall(SYS_syncfs, ssdir_fd);
+        if (rc < 0) {
+            ALOGE("syncfs failed: %s\n", strerror(errno));
+            return rc;
+        }
+        fs_state = SS_CLEAN;
+    }
+
+    return 0;
+}
+
diff --git a/trusty/storage/proxy/storage.h b/trusty/storage/proxy/storage.h
new file mode 100644
index 0000000..5a670d4
--- /dev/null
+++ b/trusty/storage/proxy/storage.h
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+#pragma once
+
+#include <stdint.h>
+#include <trusty/interface/storage.h>
+
+int storage_file_delete(struct storage_msg *msg,
+                        const void *req, size_t req_len);
+
+int storage_file_open(struct storage_msg *msg,
+                      const void *req, size_t req_len);
+
+int storage_file_close(struct storage_msg *msg,
+                       const void *req, size_t req_len);
+
+int storage_file_write(struct storage_msg *msg,
+                       const void *req, size_t req_len);
+
+int storage_file_read(struct storage_msg *msg,
+                      const void *req, size_t req_len);
+
+int storage_file_get_size(struct storage_msg *msg,
+                          const void *req, size_t req_len);
+
+int storage_file_set_size(struct storage_msg *msg,
+                          const void *req, size_t req_len);
+
+int storage_init(const char *dirname);
+
+int storage_sync_checkpoint(void);
+
diff --git a/trusty/storage/tests/Android.mk b/trusty/storage/tests/Android.mk
new file mode 100644
index 0000000..71c904d
--- /dev/null
+++ b/trusty/storage/tests/Android.mk
@@ -0,0 +1,29 @@
+#
+# 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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := secure-storage-unit-test
+LOCAL_CFLAGS += -g -Wall -Werror -std=gnu++11 -Wno-missing-field-initializers
+LOCAL_STATIC_LIBRARIES := \
+	libtrustystorageinterface \
+	libtrustystorage \
+	libtrusty \
+	liblog
+LOCAL_SRC_FILES := main.cpp
+include $(BUILD_NATIVE_TEST)
+
diff --git a/trusty/storage/tests/main.cpp b/trusty/storage/tests/main.cpp
new file mode 100644
index 0000000..1fd6f8d
--- /dev/null
+++ b/trusty/storage/tests/main.cpp
@@ -0,0 +1,3040 @@
+/*
+ * 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 <assert.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <gtest/gtest.h>
+
+#include <trusty/lib/storage.h>
+
+#define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
+
+#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
+
+static inline bool is_32bit_aligned(size_t sz)
+{
+    return ((sz & 0x3) == 0);
+}
+
+static inline bool is_valid_size(size_t sz) {
+    return (sz > 0) && is_32bit_aligned(sz);
+}
+
+static bool is_valid_offset(storage_off_t off)
+{
+    return (off & 0x3) == 0ULL;
+}
+
+static void fill_pattern32(uint32_t *buf, size_t len, storage_off_t off)
+{
+    size_t cnt = len / sizeof(uint32_t);
+    uint32_t pattern = (uint32_t)(off / sizeof(uint32_t));
+    while (cnt--) {
+        *buf++ = pattern++;
+    }
+}
+
+static bool check_pattern32(const uint32_t *buf, size_t len, storage_off_t off)
+{
+    size_t cnt = len / sizeof(uint32_t);
+    uint32_t pattern = (uint32_t)(off / sizeof(uint32_t));
+    while (cnt--) {
+        if (*buf != pattern)
+            return false;
+        buf++;
+        pattern++;
+    }
+    return true;
+}
+
+static bool check_value32(const uint32_t *buf, size_t len, uint32_t val)
+{
+    size_t cnt = len / sizeof(uint32_t);
+    while (cnt--) {
+        if (*buf != val)
+            return false;
+        buf++;
+    }
+    return true;
+}
+
+using testing::TestWithParam;
+
+class StorageServiceTest : public virtual TestWithParam<const char *> {
+public:
+    StorageServiceTest() {}
+    virtual ~StorageServiceTest() {}
+
+    virtual void SetUp() {
+        port_ = GetParam();
+        test_buf_ = NULL;
+        aux_session_ = STORAGE_INVALID_SESSION;
+        int rc = storage_open_session(TRUSTY_DEVICE_NAME, &session_, port_);
+        ASSERT_EQ(0, rc);
+    }
+
+    virtual void TearDown() {
+        if (test_buf_) {
+            delete[] test_buf_;
+            test_buf_ = NULL;
+        }
+        storage_close_session(session_);
+
+        if (aux_session_ != STORAGE_INVALID_SESSION) {
+            storage_close_session(aux_session_);
+            aux_session_ = STORAGE_INVALID_SESSION;
+        }
+    }
+
+    void WriteReadAtOffsetHelper(file_handle_t handle, size_t blk, size_t cnt, bool complete);
+
+    void WriteZeroChunk(file_handle_t handle, storage_off_t off, size_t chunk_len, bool complete );
+    void WritePatternChunk(file_handle_t handle, storage_off_t off, size_t chunk_len, bool complete);
+    void WritePattern(file_handle_t handle, storage_off_t off, size_t data_len, size_t chunk_len, bool complete);
+
+    void ReadChunk(file_handle_t handle, storage_off_t off, size_t chunk_len,
+                   size_t head_len, size_t pattern_len, size_t tail_len);
+    void ReadPattern(file_handle_t handle, storage_off_t off, size_t data_len, size_t chunk_len);
+    void ReadPatternEOF(file_handle_t handle, storage_off_t off, size_t chunk_len, size_t exp_len);
+
+protected:
+    const char *port_;
+    uint32_t *test_buf_;
+    storage_session_t session_;
+    storage_session_t aux_session_;
+};
+
+INSTANTIATE_TEST_CASE_P(SS_TD_Tests, StorageServiceTest,   ::testing::Values(STORAGE_CLIENT_TD_PORT));
+INSTANTIATE_TEST_CASE_P(SS_TDEA_Tests, StorageServiceTest, ::testing::Values(STORAGE_CLIENT_TDEA_PORT));
+INSTANTIATE_TEST_CASE_P(SS_TP_Tests, StorageServiceTest,   ::testing::Values(STORAGE_CLIENT_TP_PORT));
+
+
+void StorageServiceTest::WriteZeroChunk(file_handle_t handle, storage_off_t off,
+                                       size_t chunk_len, bool complete)
+{
+    int rc;
+    uint32_t data_buf[chunk_len/sizeof(uint32_t)];
+
+    ASSERT_PRED1(is_valid_size, chunk_len);
+    ASSERT_PRED1(is_valid_offset, off);
+
+    memset(data_buf, 0, chunk_len);
+
+    rc = storage_write(handle, off, data_buf, sizeof(data_buf),
+                       complete ? STORAGE_OP_COMPLETE : 0);
+    ASSERT_EQ((int)chunk_len, rc);
+}
+
+void StorageServiceTest::WritePatternChunk(file_handle_t handle, storage_off_t off,
+                                           size_t chunk_len, bool complete)
+{
+    int rc;
+    uint32_t data_buf[chunk_len/sizeof(uint32_t)];
+
+    ASSERT_PRED1(is_valid_size, chunk_len);
+    ASSERT_PRED1(is_valid_offset, off);
+
+    fill_pattern32(data_buf, chunk_len, off);
+
+    rc = storage_write(handle, off, data_buf, sizeof(data_buf),
+                       complete ? STORAGE_OP_COMPLETE : 0);
+    ASSERT_EQ((int)chunk_len, rc);
+}
+
+void StorageServiceTest::WritePattern(file_handle_t handle, storage_off_t off,
+                                      size_t data_len, size_t chunk_len, bool complete)
+{
+    ASSERT_PRED1(is_valid_size, data_len);
+    ASSERT_PRED1(is_valid_size, chunk_len);
+
+    while (data_len) {
+        if (data_len < chunk_len)
+            chunk_len = data_len;
+        WritePatternChunk(handle, off, chunk_len, (chunk_len == data_len) && complete);
+        ASSERT_FALSE(HasFatalFailure());
+        off += chunk_len;
+        data_len -= chunk_len;
+    }
+}
+
+void StorageServiceTest::ReadChunk(file_handle_t handle,
+                                   storage_off_t off, size_t chunk_len,
+                                   size_t head_len, size_t pattern_len,
+                                   size_t tail_len)
+{
+    int rc;
+    uint32_t data_buf[chunk_len/sizeof(uint32_t)];
+    uint8_t *data_ptr = (uint8_t *)data_buf;
+
+    ASSERT_PRED1(is_valid_size, chunk_len);
+    ASSERT_PRED1(is_valid_offset, off);
+    ASSERT_EQ(head_len + pattern_len + tail_len, chunk_len);
+
+    rc = storage_read(handle, off, data_buf, chunk_len);
+    ASSERT_EQ((int)chunk_len, rc);
+
+    if (head_len) {
+        ASSERT_TRUE(check_value32((const uint32_t *)data_ptr, head_len, 0));
+        data_ptr += head_len;
+        off += head_len;
+    }
+
+    if (pattern_len) {
+        ASSERT_TRUE(check_pattern32((const uint32_t *)data_ptr, pattern_len, off));
+        data_ptr += pattern_len;
+    }
+
+    if (tail_len) {
+        ASSERT_TRUE(check_value32((const uint32_t *)data_ptr, tail_len, 0));
+    }
+}
+
+void StorageServiceTest::ReadPattern(file_handle_t handle, storage_off_t off,
+                                     size_t data_len, size_t chunk_len)
+{
+    int rc;
+    uint32_t data_buf[chunk_len/sizeof(uint32_t)];
+
+    ASSERT_PRED1(is_valid_size, chunk_len);
+    ASSERT_PRED1(is_valid_size, data_len);
+    ASSERT_PRED1(is_valid_offset, off);
+
+    while (data_len) {
+        if (chunk_len > data_len)
+            chunk_len = data_len;
+        rc = storage_read(handle, off, data_buf, sizeof(data_buf));
+        ASSERT_EQ((int)chunk_len, rc);
+        ASSERT_TRUE(check_pattern32(data_buf, chunk_len, off));
+        off += chunk_len;
+        data_len -= chunk_len;
+    }
+}
+
+void StorageServiceTest::ReadPatternEOF(file_handle_t handle, storage_off_t off,
+                                        size_t chunk_len, size_t exp_len)
+{
+    int rc;
+    size_t bytes_read = 0;
+    uint32_t data_buf[chunk_len/sizeof(uint32_t)];
+
+    ASSERT_PRED1(is_valid_size, chunk_len);
+    ASSERT_PRED1(is_32bit_aligned, exp_len);
+
+    while (true) {
+         rc = storage_read(handle, off, data_buf, sizeof(data_buf));
+         ASSERT_GE(rc, 0);
+         if (rc == 0)
+             break; // end of file reached
+         ASSERT_PRED1(is_valid_size, (size_t)rc);
+         ASSERT_TRUE(check_pattern32(data_buf, rc, off));
+         off += rc;
+         bytes_read += rc;
+    }
+    ASSERT_EQ(bytes_read, exp_len);
+}
+
+TEST_P(StorageServiceTest, CreateDelete) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "test_create_delete_file";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // one more time (expect -ENOENT only)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // create file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // try to create it again while it is still opened (expect -EEXIST)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EEXIST, rc);
+
+    // close it
+    storage_close_file(handle);
+
+    // try to create it again while it is closed (expect -EEXIST)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EEXIST, rc);
+
+    // delete file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // one more time (expect -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+}
+
+
+TEST_P(StorageServiceTest, DeleteOpened) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "delete_opened_test_file";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // one more time (expect -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // open/create file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // delete opened file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // one more time (expect -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // close file
+    storage_close_file(handle);
+
+    // one more time (expect -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+}
+
+
+TEST_P(StorageServiceTest, OpenNoCreate) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "test_open_no_create_file";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // open non-existing file (expect -ENOENT)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // create file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // open existing file (expect 0)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // close it
+    storage_close_file(handle);
+
+    // delete file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+}
+
+
+TEST_P(StorageServiceTest, OpenOrCreate) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "test_open_create_file";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // open/create a non-existing file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // open/create an existing file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // delete file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+}
+
+
+TEST_P(StorageServiceTest, OpenCreateDeleteCharset) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-abcdefghijklmnopqrstuvwxyz_01234.56789";
+
+    // open/create file (expect 0)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // open/create an existing file (expect 0)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // delete file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open again
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+}
+
+
+TEST_P(StorageServiceTest, WriteReadSequential) {
+    int rc;
+    size_t blk = 2048;
+    file_handle_t handle;
+    const char *fname = "test_write_read_sequential";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // create file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks (sequentially)
+    WritePattern(handle, 0, 32 * blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPattern(handle, 0, 32 * blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close file
+    storage_close_file(handle);
+
+    // open the same file again
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // read data back (sequentially) and check pattern again
+    ReadPattern(handle, 0, 32 * blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, OpenTruncate) {
+    int rc;
+    uint32_t val;
+    size_t blk = 2048;
+    file_handle_t handle;
+    const char *fname = "test_open_truncate";
+
+    // make sure test file does not exist (expect success or -ENOENT)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+
+    // create file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write some data and read it back
+    WritePatternChunk(handle, 0, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPattern(handle, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+     // close file
+    storage_close_file(handle);
+
+    // reopen with truncate
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_TRUNCATE, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    /* try to read data back (expect no data) */
+    rc = storage_read(handle, 0LL, &val, sizeof(val));
+    ASSERT_EQ(0, rc);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, OpenSame) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    file_handle_t handle3;
+    const char *fname = "test_open_same_file";
+
+    // open/create file (expect 0)
+    rc = storage_open_file(session_, &handle1, fname, STORAGE_FILE_OPEN_CREATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle1);
+
+    // open an existing file first time (expect 0)
+    rc = storage_open_file(session_, &handle1, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // open the same file second time (expect error)
+    rc = storage_open_file(session_, &handle2, fname, 0, 0);
+    ASSERT_NE(0, rc);
+
+    storage_close_file(handle1);
+
+    // delete file (expect 0)
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open deleted file (expect -ENOENT)
+    rc = storage_open_file(session_, &handle3, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+}
+
+
+TEST_P(StorageServiceTest, OpenMany) {
+    int rc;
+    file_handle_t handles[10];
+    char filename[10];
+    const char *fname_fmt = "mf%d";
+
+    // open or create a bunch of files (expect 0)
+    for (uint i = 0; i < ARRAY_SIZE(handles); ++i) {
+        snprintf(filename, sizeof(filename), fname_fmt, i);
+        rc = storage_open_file(session_, &handles[i], filename,
+                               STORAGE_FILE_OPEN_CREATE, STORAGE_OP_COMPLETE);
+        ASSERT_EQ(0, rc);
+    }
+
+    // check that all handles are different
+    for (uint i = 0; i < ARRAY_SIZE(handles)-1; i++) {
+        for (uint j = i+1; j < ARRAY_SIZE(handles); j++) {
+            ASSERT_NE(handles[i], handles[j]);
+        }
+    }
+
+    // close them all
+    for (uint i = 0; i < ARRAY_SIZE(handles); ++i) {
+        storage_close_file(handles[i]);
+    }
+
+    // open all files without CREATE flags (expect 0)
+    for (uint i = 0; i < ARRAY_SIZE(handles); ++i) {
+        snprintf(filename, sizeof(filename), fname_fmt, i);
+        rc = storage_open_file(session_, &handles[i], filename, 0, 0);
+        ASSERT_EQ(0, rc);
+    }
+
+    // check that all handles are different
+    for (uint i = 0; i < ARRAY_SIZE(handles)-1; i++) {
+        for (uint j = i+1; j < ARRAY_SIZE(handles); j++) {
+            ASSERT_NE(handles[i], handles[j]);
+        }
+    }
+
+    // close and remove all test files
+    for (uint i = 0; i < ARRAY_SIZE(handles); ++i) {
+        storage_close_file(handles[i]);
+        snprintf(filename, sizeof(filename), fname_fmt, i);
+        rc = storage_delete_file(session_, filename, STORAGE_OP_COMPLETE);
+        ASSERT_EQ(0, rc);
+    }
+}
+
+
+TEST_P(StorageServiceTest, ReadAtEOF) {
+    int rc;
+    uint32_t val;
+    size_t blk = 2048;
+    file_handle_t handle;
+    const char *fname = "test_read_eof";
+
+    // open/create/truncate file
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write block at offset 0
+    WritePatternChunk(handle, 0, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close file
+    storage_close_file(handle);
+
+    // open same file again
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // read the whole block back and check pattern again
+    ReadPattern(handle, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read at end of file (expected 0 bytes)
+    rc = storage_read(handle, blk, &val, sizeof(val));
+    ASSERT_EQ(0, rc);
+
+    // partial read at end of the file (expected partial data)
+    ReadPatternEOF(handle, blk/2, blk, blk/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read past end of file
+    rc = storage_read(handle, blk + 2, &val, sizeof(val));
+    ASSERT_EQ(-EINVAL, rc);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, GetFileSize) {
+    int rc;
+    size_t blk = 2048;
+    storage_off_t size;
+    file_handle_t handle;
+    const char *fname = "test_get_file_size";
+
+    // open/create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check file size (expect success and size == 0)
+    size = 1;
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, size);
+
+    // write block
+    WritePatternChunk(handle, 0, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check size
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ(blk, size);
+
+    // write another block
+    WritePatternChunk(handle, blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check size again
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ(blk*2, size);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, SetFileSize) {
+    int rc;
+    size_t blk = 2048;
+    storage_off_t size;
+    file_handle_t handle;
+    const char *fname = "test_set_file_size";
+
+    // open/create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check file size (expect success and size == 0)
+    size = 1;
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, size);
+
+    // write block
+    WritePatternChunk(handle, 0, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check size
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ(blk, size);
+
+    storage_close_file(handle);
+
+    // reopen normally
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check size again
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ(blk, size);
+
+    // set file size to half
+    rc = storage_set_file_size(handle, blk/2, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check size again (should be half of original size)
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ(blk/2, size);
+
+    // read data back
+    ReadPatternEOF(handle, 0, blk, blk/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // set file size to 0
+    rc = storage_set_file_size(handle, 0, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check size again (should be 0)
+    rc = storage_get_file_size(handle, &size);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0LL, size);
+
+    // try to read again
+    ReadPatternEOF(handle, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+void StorageServiceTest::WriteReadAtOffsetHelper(file_handle_t handle, size_t blk, size_t cnt, bool complete)
+{
+    storage_off_t off1 = blk;
+    storage_off_t off2 = blk * (cnt-1);
+
+    // write known pattern data at non-zero offset1
+    WritePatternChunk(handle, off1, blk, complete);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write known pattern data at non-zero offset2
+    WritePatternChunk(handle, off2, blk, complete);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read data back at offset1
+    ReadPattern(handle, off1, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read data back at offset2
+    ReadPattern(handle, off2, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read partially written data at end of file(expect to get data only, no padding)
+    ReadPatternEOF(handle, off2 + blk/2, blk, blk/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read data at offset 0 (expect success and zero data)
+    ReadChunk(handle, 0, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read data from gap (expect success and zero data)
+    ReadChunk(handle, off1 + blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read partially written data (start pointing within written data)
+    // (expect to get written data back and zeroes at the end)
+    ReadChunk(handle, off1 + blk/2, blk, 0, blk/2, blk/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read partially written data (start pointing withing unwritten data)
+    // expect to get zeroes at the beginning and proper data at the end
+    ReadChunk(handle, off1 - blk/2, blk, blk/2, blk/2, 0);
+    ASSERT_FALSE(HasFatalFailure());
+}
+
+
+TEST_P(StorageServiceTest, WriteReadAtOffset) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t blk_cnt = 32;
+    const char *fname = "test_write_at_offset";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with zeroes
+    for (uint i = 0; i < blk_cnt; i++) {
+        WriteZeroChunk(handle, i * blk, blk, true);
+        ASSERT_FALSE(HasFatalFailure());
+    }
+
+    WriteReadAtOffsetHelper(handle, blk, blk_cnt, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, WriteSparse) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "test_write_sparse";
+
+    // open/create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write value past en of file
+    uint32_t val = 0xDEADBEEF;
+    rc = storage_write(handle, 1, &val, sizeof(val), STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+// Persistent 32k
+
+TEST_P(StorageServiceTest, CreatePersistent32K) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t file_size = 32768;
+    const char *fname = "test_persistent_32K_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with pattern
+    WritePattern(handle, 0, file_size, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, ReadPersistent32k) {
+    int rc;
+    file_handle_t handle;
+    size_t exp_len = 32 * 1024;
+    const char *fname = "test_persistent_32K_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    ReadPatternEOF(handle, 0, 2048, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle, 0, 1024, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle, 0,  332, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, CleanUpPersistent32K) {
+    int rc;
+    const char *fname = "test_persistent_32K_file";
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+}
+
+// Persistent 1M
+TEST_P(StorageServiceTest, CreatePersistent1M_4040) {
+    int rc;
+    file_handle_t handle;
+    size_t file_size = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with pattern
+    WritePattern(handle, 0, file_size, 4040, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, CreatePersistent1M_2032) {
+    int rc;
+    file_handle_t handle;
+    size_t file_size = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with pattern
+    WritePattern(handle, 0, file_size, 2032, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+
+TEST_P(StorageServiceTest, CreatePersistent1M_496) {
+    int rc;
+    file_handle_t handle;
+    size_t file_size = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with pattern
+    WritePattern(handle, 0, file_size, 496, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, CreatePersistent1M_240) {
+    int rc;
+    file_handle_t handle;
+    size_t file_size = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write a bunch of blocks filled with pattern
+    WritePattern(handle, 0, file_size, 240, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, ReadPersistent1M_4040) {
+    int rc;
+    file_handle_t handle;
+    size_t exp_len = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    ReadPatternEOF(handle, 0, 4040, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, ReadPersistent1M_2032) {
+    int rc;
+    file_handle_t handle;
+    size_t exp_len = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    ReadPatternEOF(handle, 0, 2032, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, ReadPersistent1M_496) {
+    int rc;
+    file_handle_t handle;
+    size_t exp_len = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    ReadPatternEOF(handle, 0, 496, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, ReadPersistent1M_240) {
+    int rc;
+    file_handle_t handle;
+    size_t exp_len = 1024 * 1024;
+    const char *fname = "test_persistent_1M_file";
+
+    // create/truncate file.
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    ReadPatternEOF(handle, 0, 240, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close but do not delete file
+    storage_close_file(handle);
+}
+
+TEST_P(StorageServiceTest, CleanUpPersistent1M) {
+    int rc;
+    const char *fname = "test_persistent_1M_file";
+    rc = storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+    rc = (rc == -ENOENT) ? 0 : rc;
+    ASSERT_EQ(0, rc);
+}
+
+TEST_P(StorageServiceTest, WriteReadLong) {
+    int rc;
+    file_handle_t handle;
+    size_t wc = 10000;
+    const char *fname = "test_write_read_long";
+
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    test_buf_ = new uint32_t[wc];
+    fill_pattern32(test_buf_, wc * sizeof(uint32_t), 0);
+    rc = storage_write(handle, 0, test_buf_, wc * sizeof(uint32_t), STORAGE_OP_COMPLETE);
+    ASSERT_EQ((int)(wc * sizeof(uint32_t)), rc);
+
+    rc = storage_read(handle, 0, test_buf_, wc * sizeof(uint32_t));
+    ASSERT_EQ((int)(wc * sizeof(uint32_t)), rc);
+    ASSERT_TRUE(check_pattern32(test_buf_, wc * sizeof(uint32_t), 0));
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+// Negative tests
+
+TEST_P(StorageServiceTest, OpenInvalidFileName) {
+    int rc;
+    file_handle_t handle;
+    const char *fname1 = "";
+    const char *fname2 = "ffff$ffff";
+    const char *fname3 = "ffff\\ffff";
+    char max_name[STORAGE_MAX_NAME_LENGTH_BYTES+1];
+
+    rc = storage_open_file(session_, &handle, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    rc = storage_open_file(session_, &handle, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    rc = storage_open_file(session_, &handle, fname3,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    /* max name */
+    memset(max_name, 'a', sizeof(max_name));
+    max_name[sizeof(max_name)-1] = 0;
+
+    rc = storage_open_file(session_, &handle, max_name,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    max_name[sizeof(max_name)-2] = 0;
+    rc = storage_open_file(session_, &handle, max_name,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    storage_close_file(handle);
+    storage_delete_file(session_, max_name, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, BadFileHnadle) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle1;
+    const char *fname = "test_invalid_file_handle";
+
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    handle1 = handle + 1;
+
+    // write to invalid file handle
+    uint32_t val = 0xDEDBEEF;
+    rc = storage_write(handle1,  0, &val, sizeof(val), STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // read from invalid handle
+    rc = storage_read(handle1,  0, &val, sizeof(val));
+    ASSERT_EQ(-EINVAL, rc);
+
+    // set size
+    rc = storage_set_file_size(handle1,  0, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // get size
+    storage_off_t fsize = (storage_off_t)(-1);
+    rc = storage_get_file_size(handle1,  &fsize);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // close (there is no way to check errors here)
+    storage_close_file(handle1);
+
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, ClosedFileHnadle) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    const char *fname1 = "test_invalid_file_handle1";
+    const char *fname2 = "test_invalid_file_handle2";
+
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // close first file handle
+    storage_close_file(handle1);
+
+    // write to invalid file handle
+    uint32_t val = 0xDEDBEEF;
+    rc = storage_write(handle1,  0, &val, sizeof(val), STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // read from invalid handle
+    rc = storage_read(handle1,  0, &val, sizeof(val));
+    ASSERT_EQ(-EINVAL, rc);
+
+    // set size
+    rc = storage_set_file_size(handle1,  0, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // get size
+    storage_off_t fsize = (storage_off_t)(-1);
+    rc = storage_get_file_size(handle1,  &fsize);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // close (there is no way to check errors here)
+    storage_close_file(handle1);
+
+    // clean up
+    storage_close_file(handle2);
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_delete_file(session_, fname2, STORAGE_OP_COMPLETE);
+}
+
+// Transactions
+
+TEST_P(StorageServiceTest, TransactDiscardInactive) {
+    int rc;
+
+    // discard current transaction (there should not be any)
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // try it again
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+}
+
+TEST_P(StorageServiceTest, TransactCommitInactive) {
+    int rc;
+
+    // try to commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // try it again
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardWrite) {
+
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_write";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // write (without commit)
+    WritePattern(handle, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // cleanup
+    storage_close_file( handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactDiscardWriteAppend) {
+
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_write_append";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data with commit
+    WritePattern(handle, 0, exp_len/2, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write data without commit
+    WritePattern(handle, exp_len/2, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size (should be exp_len)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // discard transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size, it should be exp_len/2
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    // check file data
+    ReadPatternEOF(handle, 0, blk, exp_len/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardWriteRead) {
+
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_write_read";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // Fill with zeroes (with commit)
+    for (uint i = 0; i < 32; i++) {
+        WriteZeroChunk(handle, i * blk, blk, true);
+        ASSERT_FALSE(HasFatalFailure());
+    }
+
+    // check that test chunk is filled with zeroes
+    ReadChunk(handle, blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write test pattern (without commit)
+    WritePattern(handle, blk, blk, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back an check pattern
+    ReadChunk(handle, blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // read same chunk back (should be filled with zeros)
+    ReadChunk(handle, blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardWriteMany) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    size_t exp_len1 = 32 * 1024;
+    size_t exp_len2 = 31 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname1 = "test_transact_discard_write_file1";
+    const char *fname2 = "test_transact_discard_write_file2";
+
+    // open create truncate (with commit)
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate (with commit)
+    rc = storage_open_file(session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // file1: fill file with pattern (without commit)
+    WritePattern(handle1, 0, exp_len1, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // file2: fill file with pattern (without commit)
+    WritePattern(handle2, 0, exp_len2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size, it should be exp_len1
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len1, fsize);
+
+    // check file size, it should be exp_len2
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len2, fsize);
+
+    // commit transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size, it should be exp_len1
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // check file size, it should be exp_len2
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // check data
+    ReadPatternEOF(handle1, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle2, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_close_file(handle2);
+    storage_delete_file(session_, fname2, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardTruncate) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_truncate";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // close file
+    storage_close_file(handle);
+
+    // open truncate file (without commit)
+    rc = storage_open_file(session_, &handle, fname, STORAGE_FILE_OPEN_TRUNCATE, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be an oruginal size)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardSetSize) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_set_size";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // set file size to half of original (no commit)
+    rc = storage_set_file_size(handle,  (storage_off_t)exp_len/2, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    // set file size to 1/3 of original (no commit)
+    rc = storage_set_file_size(handle,  (storage_off_t)exp_len/3, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/3, fsize);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be an original size)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardDelete) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_delete";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close it
+    storage_close_file(handle);
+
+    // delete file (without commit)
+    rc = storage_delete_file(session_, fname, 0);
+    ASSERT_EQ(0, rc);
+
+    // try to open it (should fail)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // try to open it
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be an original size)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactDiscardDelete2) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_discard_delete";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // delete file (without commit)
+    rc = storage_delete_file(session_, fname, 0);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle);
+
+    // try to open it (should fail)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // try to open it
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be an original size)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactDiscardCreate) {
+    int rc;
+    file_handle_t handle;
+    const char *fname = "test_transact_discard_create_excl";
+
+    // delete test file just in case
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+
+    // create file (without commit)
+    rc = storage_open_file(session_, &handle, fname,
+                               STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                               0);
+    ASSERT_EQ(0, rc);
+
+    // abort current transaction
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactCommitWrites) {
+
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_commit_writes";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open the same file in aux session
+    rc = storage_open_file(aux_session_, &handle_aux, fname,  0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size, it should be 0
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // write data in primary session (without commit)
+    WritePattern(handle, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write more data in primary session (without commit)
+    WritePattern(handle, exp_len/2, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size in aux session, it should still be 0
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check file size of aux session, should fail
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // abort transaction in aux session to recover
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check file size in aux session, it should be exp_len
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // check file size in primary session, it should be exp_len
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // check data in primary session
+    ReadPatternEOF(handle, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check data in aux session
+    ReadPatternEOF(handle_aux, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactCommitWrites2) {
+
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_commit_writes2";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open the same file in separate session
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // discard transaction in aux_session
+    rc = storage_end_transaction(aux_session_,  false);
+    ASSERT_EQ(0, rc);
+
+    // Fill with zeroes (with commit)
+    for (uint i = 0; i < 8; i++) {
+        WriteZeroChunk(handle, i * blk, blk, true);
+        ASSERT_FALSE(HasFatalFailure());
+    }
+
+    // check that test chunks are filled with zeroes
+    ReadChunk(handle, blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadChunk(handle, 2 * blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write test pattern (without commit)
+    WritePattern(handle, blk, blk, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // write test pattern (without commit)
+    WritePattern(handle, 2 * blk, blk, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back and check pattern
+    ReadChunk(handle, blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadChunk(handle, 2 * blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // In aux session it still should be empty
+    ReadChunk(handle_aux, blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadChunk(handle_aux, 2 * blk, blk, blk, 0, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // read same chunks back in primary session
+    ReadChunk(handle, blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadChunk(handle, 2 * blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read same chunks back in aux session (should fail)
+    uint32_t val;
+    rc = storage_read(handle_aux, blk, &val, sizeof(val));
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_read(handle_aux, 2 * blk, &val, sizeof(val));
+    ASSERT_EQ(-EBUSY, rc);
+
+    // abort transaction in aux session
+    rc = storage_end_transaction(aux_session_,  false);
+    ASSERT_EQ(0, rc);
+
+    // read same chunk again in aux session
+    ReadChunk(handle_aux, blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadChunk(handle_aux, 2 * blk, blk, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactCommitSetSize) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_commit_set_size";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open the same file in separate session
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // same in aux session
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // set file size to half of original (no commit)
+    rc = storage_set_file_size(handle,  (storage_off_t)exp_len/2, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // set file size to 1/3 of original (no commit)
+    rc = storage_set_file_size(handle,  (storage_off_t)exp_len/3, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/3, fsize);
+
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be 1/3 of an original size)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/3, fsize);
+
+    // check file size from aux session
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // abort transaction in aux_session
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check again
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/3, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactCommitDelete) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    const char *fname = "test_transact_commit_delete";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close it
+    storage_close_file(handle);
+
+    // open the same file in separate session
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle_aux);
+
+    // delete file (without commit)
+    rc = storage_delete_file(session_, fname, 0);
+    ASSERT_EQ(0, rc);
+
+    // try to open it (should fail)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // open the same file in separate session (should be fine)
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+    storage_close_file(handle_aux);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // try to open it in primary session (still fails)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // open the same file in aux session (should also fail)
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+}
+
+
+TEST_P(StorageServiceTest, TransactCommitTruncate) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_commit_truncate";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // close file
+    storage_close_file(handle);
+
+    // check from different session
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // open truncate file (without commit)
+    rc = storage_open_file(session_, &handle, fname, STORAGE_FILE_OPEN_TRUNCATE, 0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check file size (should be 0)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // check file size in aux session (should be -EBUSY)
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // abort transaction in aux session
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // check again
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactCommitCreate) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_commit_create";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // delete test file just in case
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+
+    // check from aux session
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // create file (without commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           0);
+    ASSERT_EQ(0, rc);
+
+    // check file size
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // close file
+    storage_close_file(handle);
+
+    // check from aux session (should fail)
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check open from normal session
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // check open from aux session (should succeed)
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactCommitCreateMany) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    file_handle_t handle1_aux;
+    file_handle_t handle2_aux;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname1 = "test_transact_commit_create1";
+    const char *fname2 = "test_transact_commit_create2";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // delete test file just in case
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_delete_file(session_, fname2, STORAGE_OP_COMPLETE);
+
+    // create file (without commit)
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           0);
+    ASSERT_EQ(0, rc);
+
+    // create file (without commit)
+    rc = storage_open_file(session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           0);
+    ASSERT_EQ(0, rc);
+
+    // check file sizes
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // close files
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    // open files from aux session
+    rc = storage_open_file(aux_session_, &handle1_aux, fname1, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    rc = storage_open_file(aux_session_, &handle2_aux, fname2, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // open from primary session
+    rc = storage_open_file(session_, &handle1, fname1, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(session_, &handle2, fname2, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // open from aux session
+    rc = storage_open_file(aux_session_, &handle1_aux, fname1, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(aux_session_, &handle2_aux, fname2, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle1_aux);
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_close_file(handle2);
+    storage_close_file(handle2_aux);
+    storage_delete_file(session_, fname2, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactCommitWriteMany) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    file_handle_t handle1_aux;
+    file_handle_t handle2_aux;
+    size_t blk = 2048;
+    size_t exp_len1 = 32 * 1024;
+    size_t exp_len2 = 31 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname1 = "test_transact_commit_write_file1";
+    const char *fname2 = "test_transact_commit_write_file2";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate (with commit)
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate (with commit)
+    rc = storage_open_file(session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // open same files from aux session
+    rc = storage_open_file(aux_session_, &handle1_aux, fname1, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(aux_session_, &handle2_aux, fname2, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // file1: fill file with pattern (without commit)
+    WritePattern(handle1, 0, exp_len1, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // file2: fill file with pattern (without commit)
+    WritePattern(handle2, 0, exp_len2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size, it should be exp_len1
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len1, fsize);
+
+    // check file size, it should be exp_len2
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len2, fsize);
+
+    // check file sizes from aux session (should be 0)
+    rc = storage_get_file_size(handle1_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    rc = storage_get_file_size(handle2_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // commit transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check file size, it should be exp_len1
+    rc = storage_get_file_size(handle1, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len1, fsize);
+
+    // check file size, it should be exp_len2
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len2, fsize);
+
+    // check from aux session (should be -EBUSY)
+    rc = storage_get_file_size(handle1_aux, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // abort transaction in aux session
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // and check again
+    rc = storage_get_file_size(handle1_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len1, fsize);
+
+    rc = storage_get_file_size(handle2_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len2, fsize);
+
+    // check data
+    ReadPatternEOF(handle1, 0, blk, exp_len1);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle2, 0, blk, exp_len2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle1_aux, 0, blk, exp_len1);
+    ASSERT_FALSE(HasFatalFailure());
+
+    ReadPatternEOF(handle2_aux, 0, blk, exp_len2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle1_aux);
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_close_file(handle2);
+    storage_close_file(handle2_aux);
+    storage_delete_file(session_, fname2, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactCommitDeleteCreate) {
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle_aux;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_delete_create";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write data (with commit)
+    WritePattern(handle, 0, exp_len, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close it
+    storage_close_file(handle);
+
+    // delete file (without commit)
+    rc = storage_delete_file(session_, fname, 0);
+    ASSERT_EQ(0, rc);
+
+    // try to open it (should fail)
+    rc = storage_open_file(session_, &handle, fname, 0, 0);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // try to open it in aux session (should succeed)
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // create file with the same name (no commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_CREATE_EXCLUSIVE,
+                           0);
+    ASSERT_EQ(0, rc);
+
+    // write half of data (with commit)
+    WritePattern(handle, 0, exp_len/2, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check file size (should be half)
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    // commit transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check data from primary session
+    ReadPatternEOF(handle, 0, blk, exp_len/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // check from aux session (should fail)
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // abort trunsaction in aux session
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // and try again (should still fail)
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // close file and reopen it again
+    storage_close_file(handle_aux);
+    rc = storage_open_file(aux_session_, &handle_aux, fname, 0, 0);
+    ASSERT_EQ(0, rc);
+
+    // try it again (should succeed)
+    rc = storage_get_file_size(handle_aux, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    // check data
+    ReadPatternEOF(handle_aux, 0, blk, exp_len/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_close_file(handle_aux);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, TransactRewriteExistingTruncate) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    const char *fname = "test_transact_rewrite_existing_truncate";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // close it
+    storage_close_file(handle);
+
+    // up
+    for (uint i = 1; i < 32; i++) {
+        // open truncate (no commit)
+        rc = storage_open_file(session_, &handle, fname, STORAGE_FILE_OPEN_TRUNCATE, 0);
+        ASSERT_EQ(0, rc);
+
+        // write data (with commit)
+        WritePattern(handle, 0, i * blk, blk, true);
+        ASSERT_FALSE(HasFatalFailure());
+
+        // close
+        storage_close_file(handle);
+    }
+
+    // down
+    for (uint i = 1; i < 32; i++) {
+        // open truncate (no commit)
+        rc = storage_open_file(session_, &handle, fname, STORAGE_FILE_OPEN_TRUNCATE, 0);
+        ASSERT_EQ(0, rc);
+
+        // write data (with commit)
+        WritePattern(handle, 0, (32 - i) * blk, blk, true);
+        ASSERT_FALSE(HasFatalFailure());
+
+        // close
+        storage_close_file(handle);
+    }
+
+    // cleanup
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactRewriteExistingSetSize) {
+    int rc;
+    file_handle_t handle;
+    size_t blk = 2048;
+    const char *fname = "test_transact_rewrite_existing_set_size";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // close it
+    storage_close_file(handle);
+
+    // up
+    for (uint i = 1; i < 32; i++) {
+        // open truncate (no commit)
+        rc = storage_open_file(session_, &handle, fname, 0, 0);
+        ASSERT_EQ(0, rc);
+
+        // write data (with commit)
+        WritePattern(handle, 0, i * blk, blk, false);
+        ASSERT_FALSE(HasFatalFailure());
+
+        // update size (with commit)
+        rc = storage_set_file_size(handle, i * blk, STORAGE_OP_COMPLETE);
+        ASSERT_EQ(0, rc);
+
+        // close
+        storage_close_file(handle);
+    }
+
+    // down
+    for (uint i = 1; i < 32; i++) {
+        // open trancate (no commit)
+        rc = storage_open_file(session_, &handle, fname, 0, 0);
+        ASSERT_EQ(0, rc);
+
+        // write data (with commit)
+        WritePattern(handle, 0, (32 - i) * blk, blk, false);
+        ASSERT_FALSE(HasFatalFailure());
+
+        // update size (with commit)
+        rc = storage_set_file_size(handle, (32 - i) * blk, STORAGE_OP_COMPLETE);
+        ASSERT_EQ(0, rc);
+
+        // close
+        storage_close_file(handle);
+    }
+
+    // cleanup
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, TransactResumeAfterNonFatalError) {
+
+    int rc;
+    file_handle_t handle;
+    file_handle_t handle1;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_resume_writes";
+
+    // open create truncate file (with commit)
+    rc = storage_open_file(session_, &handle, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // write (without commit)
+    WritePattern(handle, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // issue some commands that should fail with non-fatal errors
+
+    // write past end of file
+    uint32_t val = 0xDEDBEEF;
+    rc = storage_write(handle,  exp_len/2 + 1, &val, sizeof(val), 0);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // read past end of file
+    rc = storage_read(handle, exp_len/2 + 1, &val, sizeof(val));
+    ASSERT_EQ(-EINVAL, rc);
+
+    // try to extend file past end of file
+    rc = storage_set_file_size(handle, exp_len/2 + 1, 0);
+    ASSERT_EQ(-EINVAL, rc);
+
+    // open non existing file
+    rc = storage_open_file(session_, &handle1, "foo",
+                           STORAGE_FILE_OPEN_TRUNCATE, STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // delete non-existing file
+    rc = storage_delete_file(session_, "foo", STORAGE_OP_COMPLETE);
+    ASSERT_EQ(-ENOENT, rc);
+
+    // then resume writinga (without commit)
+    WritePattern(handle, exp_len/2, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // commit current transaction
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // check file size, it should be exp_len
+    rc = storage_get_file_size(handle, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // check data
+    ReadPatternEOF(handle, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle);
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+// Transaction Collisions
+
+TEST_P(StorageServiceTest, Transact2_WriteNC) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    const char *fname1 = "test_transact_f1";
+    const char *fname2 = "test_transact_f2";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(aux_session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // session 1
+    WritePattern(handle1, 0, blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back
+    ReadPatternEOF(handle1, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // session 2
+    WritePattern(handle2, 0, blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back
+    ReadPatternEOF(handle2, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname1, STORAGE_OP_COMPLETE);
+    storage_delete_file(aux_session_, fname2, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, Transact2_DeleteNC) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    const char *fname1 = "test_transact_delete_f1";
+    const char *fname2 = "test_transact_delete_f2";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(session_, &handle1, fname1,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_open_file(aux_session_, &handle2, fname2,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // session 1
+    WritePattern(handle1, 0, blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back
+    ReadPatternEOF(handle1, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // session 2
+    WritePattern(handle2, 0, blk, blk, true);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // read it back
+    ReadPatternEOF(handle2, 0, blk, blk);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // close files and delete them
+    storage_close_file(handle1);
+    storage_delete_file(session_, fname1, 0);
+
+    storage_close_file(handle2);
+    storage_delete_file(aux_session_, fname2, 0);
+
+    // commit
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    rc = storage_end_transaction(aux_session_, true);
+    ASSERT_EQ(0, rc);
+}
+
+
+TEST_P(StorageServiceTest, Transact2_Write_Read) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_writeRead";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // S1: open create truncate file
+    rc = storage_open_file(session_, &handle1, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S2: open the same file
+    rc = storage_open_file(aux_session_, &handle2, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S1: write (no commit)
+    WritePattern(handle1, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: read it back
+    ReadPatternEOF(handle1, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S2: check file size, it should be 0
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // S2: read it back (should no data)
+    ReadPatternEOF(handle2, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: commit
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // S2: check file size, it should fail
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // S2: abort transaction
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // S2: check file size again, it should be exp_len
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // S2: read it again (should be exp_len)
+    ReadPatternEOF(handle2, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, Transact2_Write_Write_Commit_Commit) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    file_handle_t handle3;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_write_write_commit_commit";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // S1: open create truncate file
+    rc = storage_open_file(session_, &handle1, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S2: open the same file
+    rc = storage_open_file(aux_session_, &handle2, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S1: write (no commit)
+    WritePattern(handle1, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S2: write (no commit)
+    WritePattern(handle2, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: commit
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // S2: read/write/get/set size/delete (all should fail)
+    uint32_t val = 0;
+    rc = storage_read(handle2, 0, &val, sizeof(val));
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_write(handle2, 0, &val, sizeof(val), 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_set_file_size(handle2,  fsize, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_delete_file(aux_session_, fname, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_open_file(aux_session_, &handle3, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // S2: commit (should fail, and failed state should be cleared)
+    rc = storage_end_transaction(aux_session_, true);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // S2: check file size, it should be exp_len
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // S2: read it again (should be exp_len)
+    ReadPatternEOF(handle2, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, Transact2_Write_Write_Commit_Discard) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    file_handle_t handle3;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_write_write_commit_discard";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // S1: open create truncate file
+    rc = storage_open_file(session_, &handle1, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S2: open the same file
+    rc = storage_open_file(aux_session_, &handle2, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S1: write (no commit)
+    WritePattern(handle1, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S2: write (no commit)
+    WritePattern(handle2, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: commit
+    rc = storage_end_transaction(session_, true);
+    ASSERT_EQ(0, rc);
+
+    // S2: read/write/get/set size/delete (all should fail)
+    uint32_t val = 0;
+    rc = storage_read(handle2, 0, &val, sizeof(val));
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_write(handle2, 0, &val, sizeof(val), 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_set_file_size(handle2,  fsize, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_delete_file(aux_session_, fname, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    rc = storage_open_file(aux_session_, &handle3, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE, 0);
+    ASSERT_EQ(-EBUSY, rc);
+
+    // S2: discard (should fail, and failed state should be cleared)
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // S2: check file size, it should be exp_len
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len, fsize);
+
+    // S2: read it again (should be exp_len)
+    ReadPatternEOF(handle2, 0, blk, exp_len);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+TEST_P(StorageServiceTest, Transact2_Write_Write_Discard_Commit) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_write_write_discard_commit";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // S1: open create truncate file
+    rc = storage_open_file(session_, &handle1, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S2: open the same file
+    rc = storage_open_file(aux_session_, &handle2, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S1: write (no commit)
+    WritePattern(handle1, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S2: write (no commit)
+    WritePattern(handle2, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: discard
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // S2: commit (should succeed)
+    rc = storage_end_transaction(aux_session_, true);
+    ASSERT_EQ(0, rc);
+
+    // S2: check file size, it should be exp_len
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)exp_len/2, fsize);
+
+    // S2: read it again (should be exp_len)
+    ReadPatternEOF(handle2, 0, blk, exp_len/2);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
+
+TEST_P(StorageServiceTest, Transact2_Write_Write_Discard_Discard) {
+    int rc;
+    file_handle_t handle1;
+    file_handle_t handle2;
+    size_t blk = 2048;
+    size_t exp_len = 32 * 1024;
+    storage_off_t fsize = (storage_off_t)(-1);
+    const char *fname = "test_transact_write_write_discard_Discard";
+
+    // open second session
+    rc = storage_open_session(TRUSTY_DEVICE_NAME, &aux_session_, port_);
+    ASSERT_EQ(0, rc);
+
+    // S1: open create truncate file
+    rc = storage_open_file(session_, &handle1, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S2: open the same file
+    rc = storage_open_file(aux_session_, &handle2, fname,
+                           STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE,
+                           STORAGE_OP_COMPLETE);
+    ASSERT_EQ(0, rc);
+
+    // S1: write (no commit)
+    WritePattern(handle1, 0, exp_len, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S2: write (no commit)
+    WritePattern(handle2, 0, exp_len/2, blk, false);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // S1: discard
+    rc = storage_end_transaction(session_, false);
+    ASSERT_EQ(0, rc);
+
+    // S2: discard
+    rc = storage_end_transaction(aux_session_, false);
+    ASSERT_EQ(0, rc);
+
+    // S2: check file size, it should be 0
+    rc = storage_get_file_size(handle2, &fsize);
+    ASSERT_EQ(0, rc);
+    ASSERT_EQ((storage_off_t)0, fsize);
+
+    // S2: read it again (should be 0)
+    ReadPatternEOF(handle2, 0, blk, 0);
+    ASSERT_FALSE(HasFatalFailure());
+
+    // cleanup
+    storage_close_file(handle1);
+    storage_close_file(handle2);
+
+    storage_delete_file(session_, fname, STORAGE_OP_COMPLETE);
+}
+
diff --git a/trusty/trusty-base.mk b/trusty/trusty-base.mk
new file mode 100644
index 0000000..9c3a7df
--- /dev/null
+++ b/trusty/trusty-base.mk
@@ -0,0 +1,28 @@
+#
+# 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.
+#
+
+#
+# This makefile should be included by devices that use Trusty TEE
+# to pull in the baseline set of Trusty specific modules.
+#
+
+PRODUCT_PACKAGES += \
+	keystore.trusty \
+	gatekeeper.trusty
+
+PRODUCT_PROPERTY_OVERRIDES += \
+	ro.hardware.keystore=trusty \
+	ro.hardware.gatekeeper=trusty
diff --git a/trusty/trusty-storage.mk b/trusty/trusty-storage.mk
new file mode 100644
index 0000000..3f26316
--- /dev/null
+++ b/trusty/trusty-storage.mk
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+PRODUCT_PACKAGES += \
+	storageproxyd \
diff --git a/tzdatacheck/Android.bp b/tzdatacheck/Android.bp
new file mode 100644
index 0000000..00ad141
--- /dev/null
+++ b/tzdatacheck/Android.bp
@@ -0,0 +1,14 @@
+// ========================================================
+// Executable
+// ========================================================
+cc_binary {
+    name: "tzdatacheck",
+    host_supported: true,
+    srcs: ["tzdatacheck.cpp"],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+    ],
+    cflags: ["-Werror"],
+}
diff --git a/tzdatacheck/Android.mk b/tzdatacheck/Android.mk
deleted file mode 100644
index 0e25f7d..0000000
--- a/tzdatacheck/Android.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# ========================================================
-# Executable
-# ========================================================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= tzdatacheck.cpp
-LOCAL_MODULE := tzdatacheck
-LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
-LOCAL_CFLAGS := -Werror
-include $(BUILD_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= tzdatacheck.cpp
-LOCAL_MODULE := tzdatacheck
-LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
-LOCAL_CFLAGS := -Werror
-include $(BUILD_HOST_EXECUTABLE)
-
diff --git a/tzdatacheck/tzdatacheck.cpp b/tzdatacheck/tzdatacheck.cpp
index c1ab2ac..8fcd17f 100644
--- a/tzdatacheck/tzdatacheck.cpp
+++ b/tzdatacheck/tzdatacheck.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <ctype.h>
 #include <errno.h>
 #include <ftw.h>
 #include <libgen.h>
@@ -29,47 +30,139 @@
 
 #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";
+
+// distro_version is an ASCII file consisting of 17 bytes in the form: AAA.BBB|CCCCC|DDD
+// AAA.BBB is the major/minor version of the distro format (e.g. 001.001),
+// CCCCC is the rules version (e.g. 2016g)
+// DDD is the android revision for this rules version to allow for distro corrections (e.g. 001)
+// We only need the first 13 to determine if it is suitable for the device.
+static const int DISTRO_VERSION_LENGTH = 13;
+
+// The major version of the distro format supported by this code as a null-terminated char[].
+// See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
+static const char SUPPORTED_DISTRO_MAJOR_VERSION[] = "001";
+
+// The length of the distro format major version excluding the \0
+static const size_t SUPPORTED_DISTRO_MAJOR_VERSION_LEN = sizeof(SUPPORTED_DISTRO_MAJOR_VERSION) - 1;
+
+// The minor version of the distro format supported by this code as a null-terminated char[].
+// See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
+static const char SUPPORTED_DISTRO_MINOR_VERSION[] = "001";
+
+// The length of the distro format minor version excluding the \0
+static const size_t SUPPORTED_DISTRO_MINOR_VERSION_LEN = sizeof(SUPPORTED_DISTRO_MINOR_VERSION) - 1;
+
+// The length of the distro format version. e.g. 001.001
+static const size_t SUPPORTED_DISTRO_VERSION_LEN =
+        SUPPORTED_DISTRO_MAJOR_VERSION_LEN + SUPPORTED_DISTRO_MINOR_VERSION_LEN + 1;
+
+// The length of the IANA rules version bytes. e.g. 2016a
+static const size_t RULES_VERSION_LEN = 5;
+
+// Distro version bytes are: AAA.BBB|CCCCC - the rules version is CCCCC
+static const size_t DISTRO_VERSION_RULES_IDX = 8;
+
+// See also libcore.tzdata.shared2.TimeZoneDistro.
 static const char* TZDATA_FILENAME = "/tzdata";
+
 // tzdata file header (as much as we need for the version):
 // byte[11] tzdata_version  -- e.g. "tzdata2012f"
 static const int TZ_HEADER_LENGTH = 11;
 
+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"
-            "Compares the headers of two tzdata files. If the one in SYSTEM_TZ_DIR is the\n"
-            "same or a higher version than the one in DATA_TZ_DIR the DATA_TZ_DIR is renamed\n"
-            "and then deleted.\n";
+            "Checks whether any timezone update distro in DATA_TZ_DIR is compatible with the\n"
+            "current Android release and better than or the same as base system timezone rules in\n"
+            "SYSTEM_TZ_DIR. If the timezone rules in SYSTEM_TZ_DIR are a higher version than the\n"
+            "one in DATA_TZ_DIR the DATA_TZ_DIR is renamed and then deleted.\n";
     exit(1);
 }
 
 /*
- * Opens a file and fills headerBytes with the first byteCount bytes from the file. It is a fatal
- * error if the file is too small or cannot be opened. If the file does not exist false is returned.
+ * Opens a file and fills buffer with the first byteCount bytes from the file.
+ * If the file does not exist or cannot be opened or is too short then false is returned.
  * If the bytes were read successfully then true is returned.
  */
-static bool readHeader(const std::string& tzDataFileName, char* headerBytes, size_t byteCount) {
-    FILE* tzDataFile = fopen(tzDataFileName.c_str(), "r");
-    if (tzDataFile == nullptr) {
-        if (errno == ENOENT) {
-            return false;
-        } else {
-            PLOG(FATAL) << "Error opening tzdata file " << tzDataFileName;
+static bool readBytes(const std::string& fileName, char* buffer, size_t byteCount) {
+    FILE* file = fopen(fileName.c_str(), "r");
+    if (file == nullptr) {
+        if (errno != ENOENT) {
+            PLOG(WARNING) << "Error opening file " << fileName;
         }
+        return false;
     }
-    size_t bytesRead = fread(headerBytes, 1, byteCount, tzDataFile);
+    size_t bytesRead = fread(buffer, 1, byteCount, file);
+    fclose(file);
     if (bytesRead != byteCount) {
-        LOG(FATAL) << tzDataFileName << " is too small. " << byteCount << " bytes required";
+        LOG(WARNING) << fileName << " is too small. " << byteCount << " bytes required";
+        return false;
     }
-    fclose(tzDataFile);
     return true;
 }
 
-/* Checks the contents of headerBytes. It is a fatal error if it not a tzdata header. */
-static void checkValidHeader(const std::string& fileName, char* headerBytes) {
+/*
+ * Checks the contents of headerBytes. Returns true if it is valid (starts with "tzdata"), false
+ * otherwise.
+ */
+static bool checkValidTzDataHeader(const std::string& fileName, const char* headerBytes) {
     if (strncmp("tzdata", headerBytes, 6) != 0) {
-        LOG(FATAL) << fileName << " does not start with the expected bytes (tzdata)";
+        LOG(WARNING) << fileName << " does not start with the expected bytes (tzdata)";
+        return false;
     }
+    return true;
+}
+
+static bool checkDigits(const char* buffer, const size_t count, size_t* i) {
+    for (size_t j = 0; j < count; j++) {
+      char toCheck = buffer[(*i)++];
+      if (!isdigit(toCheck)) {
+        return false;
+      }
+    }
+    return true;
+}
+
+static bool checkValidDistroVersion(const char* buffer) {
+    // See DISTRO_VERSION_LENGTH comments above for a description of the format.
+    size_t i = 0;
+    if (!checkDigits(buffer, 3, &i)) {
+      return false;
+    }
+    if (buffer[i++] != '.') {
+      return false;
+    }
+    if (!checkDigits(buffer, 3, &i)) {
+      return false;
+    }
+    if (buffer[i++] != '|') {
+      return false;
+    }
+    if (!checkDigits(buffer, 4, &i)) {
+      return false;
+    }
+    // Ignore the last character. It is assumed to be a letter but we don't check because it's not
+    // obvious what would happen at 'z'.
+    return true;
 }
 
 /* Return the parent directory of dirName. */
@@ -103,9 +196,48 @@
     return 0;
 }
 
+enum PathStatus { ERR, NONE, IS_DIR, IS_REG, UNKNOWN };
+
+static PathStatus checkPath(const std::string& path) {
+    struct stat buf;
+    if (stat(path.c_str(), &buf) != 0) {
+        if (errno != ENOENT) {
+            PLOG(WARNING) << "Unable to stat " << path;
+            return ERR;
+        }
+        return NONE;
+    }
+    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;
+}
+
 /*
  * Deletes dirToDelete and returns true if it is successful in removing or moving the directory out
- * of the way. If dirToDelete does not exist this function does nothing and returns true.
+ * of the way. If dirToDelete does not exist this function does nothing and returns true. If
+ * dirToDelete is not a directory or cannot be accessed this method returns false.
  *
  * During deletion, this function first renames the directory to a temporary name. If the temporary
  * directory cannot be created, or the directory cannot be renamed, false is returned. After the
@@ -114,23 +246,18 @@
  */
 static bool deleteDir(const std::string& dirToDelete) {
     // Check whether the dir exists.
-    struct stat buf;
-    if (stat(dirToDelete.c_str(), &buf) == 0) {
-      if (!S_ISDIR(buf.st_mode)) {
-        LOG(WARNING) << dirToDelete << " is not a directory";
+    int pathStatus = checkPath(dirToDelete);
+    if (pathStatus == NONE) {
+        LOG(INFO) << "Path " << dirToDelete << " does not exist";
+        return true;
+    }
+    if (pathStatus != IS_DIR) {
+        LOG(WARNING) << "Path " << dirToDelete << " failed to stat() or is not a directory.";
         return false;
-      }
-    } else {
-      if (errno == ENOENT) {
-          PLOG(INFO) << "Directory does not exist: " << dirToDelete;
-          return true;
-      } else {
-          PLOG(WARNING) << "Unable to stat " << dirToDelete;
-          return false;
-      }
     }
 
     // First, rename dirToDelete.
+
     std::string tempDirNameTemplate = getParentDir(dirToDelete);
     tempDirNameTemplate += "/tempXXXXXX";
 
@@ -142,7 +269,7 @@
         return false;
     }
 
-    // Rename dirToDelete to tempDirName.
+    // Rename dirToDelete to tempDirName (replacing the empty tempDirName directory created above).
     int rc = rename(dirToDelete.c_str(), &tempDirName[0]);
     if (rc == -1) {
         PLOG(WARNING) << "Unable to rename directory from " << dirToDelete << " to "
@@ -151,6 +278,7 @@
     }
 
     // Recursively delete contents of tempDirName.
+
     rc = nftw(&tempDirName[0], deleteFn, 10 /* openFiles */,
             FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
     if (rc == -1) {
@@ -160,9 +288,172 @@
 }
 
 /*
+ * Deletes the ConfigInstaller metadata directory.
+ * TODO(nfuller). http://b/31008728 Remove this when ConfigInstaller is no longer used.
+ */
+static void deleteConfigUpdaterMetadataDir(const char* dataZoneInfoDir) {
+    // Delete the update metadata
+    std::string dataUpdatesDirName(dataZoneInfoDir);
+    dataUpdatesDirName += "/updates";
+    LOG(INFO) << "Removing: " << dataUpdatesDirName;
+    if (!deleteDir(dataUpdatesDirName)) {
+        LOG(WARNING) << "Deletion of install metadata " << dataUpdatesDirName
+                << " was not successful";
+    }
+}
+
+/*
+ * Deletes the timezone update distro directory.
+ */
+static void deleteUpdateDistroDir(const std::string& distroDirName) {
+    LOG(INFO) << "Removing: " << distroDirName;
+    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
- * version in /data along with any update metadata.
+ * version in /data.
  *
  * Note: This code is related to code in com.android.server.updates.TzDataInstallReceiver. The
  * paths for the metadata and current timezone data must match.
@@ -175,62 +466,136 @@
 int main(int argc, char* argv[]) {
     if (argc != 3) {
         usage();
+        return 1;
     }
 
     const char* systemZoneInfoDir = argv[1];
     const char* dataZoneInfoDir = argv[2];
 
+    std::string dataStagedDirName(dataZoneInfoDir);
+    dataStagedDirName += STAGED_DIR_NAME;
+
     std::string dataCurrentDirName(dataZoneInfoDir);
-    dataCurrentDirName += "/current";
-    std::string dataTzDataFileName(dataCurrentDirName);
-    dataTzDataFileName += TZDATA_FILENAME;
+    dataCurrentDirName += CURRENT_DIR_NAME;
 
-    std::vector<char> dataTzDataHeader;
-    dataTzDataHeader.reserve(TZ_HEADER_LENGTH);
+    // 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);
 
-    bool dataFileExists = readHeader(dataTzDataFileName, dataTzDataHeader.data(), TZ_HEADER_LENGTH);
-    if (!dataFileExists) {
-        LOG(INFO) << "tzdata file " << dataTzDataFileName << " does not exist. No action required.";
+    // 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;
     }
-    checkValidHeader(dataTzDataFileName, dataTzDataHeader.data());
 
+    // 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.
+    if (dataCurrentDirStatus != IS_DIR) {
+        LOG(WARNING) << "Current distro dir " << dataCurrentDirName
+                << " could not be accessed or is not a directory. result=" << dataCurrentDirStatus;
+        return 2;
+    }
+
+    // Check the installed distro version.
+    std::string distroVersionFileName(dataCurrentDirName);
+    distroVersionFileName += DISTRO_VERSION_FILENAME;
+    std::vector<char> distroVersion;
+    distroVersion.reserve(DISTRO_VERSION_LENGTH);
+    bool distroVersionReadOk =
+            readBytes(distroVersionFileName, distroVersion.data(), DISTRO_VERSION_LENGTH);
+    if (!distroVersionReadOk) {
+        LOG(WARNING) << "distro version file " << distroVersionFileName
+                << " does not exist or is too short. Deleting distro dir.";
+        // Implies the contents of the data partition is corrupt in some way. Try to clean up.
+        deleteConfigUpdaterMetadataDir(dataZoneInfoDir);
+        deleteUpdateDistroDir(dataCurrentDirName);
+        return 3;
+    }
+
+    if (!checkValidDistroVersion(distroVersion.data())) {
+        LOG(WARNING) << "distro version file " << distroVersionFileName
+                << " is not valid. Deleting distro dir.";
+        // Implies the contents of the data partition is corrupt in some way. Try to clean up.
+        deleteConfigUpdaterMetadataDir(dataZoneInfoDir);
+        deleteUpdateDistroDir(dataCurrentDirName);
+        return 4;
+    }
+
+    std::string actualDistroVersion =
+            std::string(distroVersion.data(), SUPPORTED_DISTRO_VERSION_LEN);
+    // Check the first 3 bytes of the distro version: these are the major version (e.g. 001).
+    // It must match the one we support exactly to be ok.
+    if (strncmp(
+            &distroVersion[0],
+            SUPPORTED_DISTRO_MAJOR_VERSION,
+            SUPPORTED_DISTRO_MAJOR_VERSION_LEN) != 0) {
+
+        LOG(INFO) << "distro version file " << distroVersionFileName
+                << " major version is not the required version " << SUPPORTED_DISTRO_MAJOR_VERSION
+                << ", was \"" << actualDistroVersion << "\". Deleting distro dir.";
+        // This implies there has been an OTA and the installed distro is not compatible with the
+        // new version of Android. Remove the installed distro.
+        deleteConfigUpdaterMetadataDir(dataZoneInfoDir);
+        deleteUpdateDistroDir(dataCurrentDirName);
+        return 5;
+    }
+
+    // Check the last 3 bytes of the distro version: these are the minor version (e.g. 001).
+    // If the version in the distro is < the minor version required by this device it cannot be
+    // used.
+    if (strncmp(
+            &distroVersion[4],
+            SUPPORTED_DISTRO_MINOR_VERSION,
+            SUPPORTED_DISTRO_MINOR_VERSION_LEN) < 0) {
+
+        LOG(INFO) << "distro version file " << distroVersionFileName
+                << " minor version is not the required version " << SUPPORTED_DISTRO_MINOR_VERSION
+                << ", was \"" << actualDistroVersion << "\". Deleting distro dir.";
+        // This implies there has been an OTA and the installed distro is not compatible with the
+        // new version of Android. Remove the installed distro.
+        deleteConfigUpdaterMetadataDir(dataZoneInfoDir);
+        deleteUpdateDistroDir(dataCurrentDirName);
+        return 5;
+    }
+
+    // Read the system rules version out of the /system tzdata file.
     std::string systemTzDataFileName(systemZoneInfoDir);
     systemTzDataFileName += TZDATA_FILENAME;
     std::vector<char> systemTzDataHeader;
     systemTzDataHeader.reserve(TZ_HEADER_LENGTH);
     bool systemFileExists =
-            readHeader(systemTzDataFileName, systemTzDataHeader.data(), TZ_HEADER_LENGTH);
+            readBytes(systemTzDataFileName, systemTzDataHeader.data(), TZ_HEADER_LENGTH);
     if (!systemFileExists) {
-        LOG(FATAL) << systemTzDataFileName << " does not exist or could not be opened";
+        // Implies the contents of the system partition is corrupt in some way. Nothing we can do.
+        LOG(WARNING) << systemTzDataFileName << " does not exist or could not be opened";
+        return 6;
     }
-    checkValidHeader(systemTzDataFileName, systemTzDataHeader.data());
-
-    if (strncmp(&systemTzDataHeader[0], &dataTzDataHeader[0], TZ_HEADER_LENGTH) < 0) {
-        LOG(INFO) << "tzdata file " << dataTzDataFileName << " is the newer than "
-                << systemTzDataFileName << ". No action required.";
-    } else {
-        // We have detected the case this tool is intended to prevent. Go fix it.
-        LOG(INFO) << "tzdata file " << dataTzDataFileName << " is the same as or older than "
-                << systemTzDataFileName << "; fixing...";
-
-        // Delete the update metadata
-        std::string dataUpdatesDirName(dataZoneInfoDir);
-        dataUpdatesDirName += "/updates";
-        LOG(INFO) << "Removing: " << dataUpdatesDirName;
-        bool deleted = deleteDir(dataUpdatesDirName);
-        if (!deleted) {
-            LOG(WARNING) << "Deletion of install metadata " << dataUpdatesDirName
-                    << " was not successful";
-        }
-
-        // Delete the TZ data
-        LOG(INFO) << "Removing: " << dataCurrentDirName;
-        deleted = deleteDir(dataCurrentDirName);
-        if (!deleted) {
-            LOG(WARNING) << "Deletion of tzdata " << dataCurrentDirName << " was not successful";
-        }
+    if (!checkValidTzDataHeader(systemTzDataFileName, systemTzDataHeader.data())) {
+        // Implies the contents of the system partition is corrupt in some way. Nothing we can do.
+        LOG(WARNING) << systemTzDataFileName << " does not have a valid header.";
+        return 7;
     }
 
+    // Compare the distro rules version against the system rules version.
+    if (strncmp(
+            &systemTzDataHeader[TZ_DATA_HEADER_PREFIX_LEN],
+            &distroVersion[DISTRO_VERSION_RULES_IDX],
+            RULES_VERSION_LEN) <= 0) {
+        LOG(INFO) << "Found an installed distro but it is valid. No action taken.";
+        // Implies there is an installed update, but it is good.
+        return 0;
+    }
+
+    // Implies there has been an OTA and the system version of the timezone rules is now newer
+    // than the version installed in /data. Remove the installed distro.
+    LOG(INFO) << "timezone distro in " << dataCurrentDirName << " is older than data in "
+            << systemTzDataFileName << "; fixing...";
+
+    deleteConfigUpdaterMetadataDir(dataZoneInfoDir);
+    deleteUpdateDistroDir(dataCurrentDirName);
     return 0;
 }