Merge "Only allow system to write to existing input nodes."
diff --git a/adb/Android.mk b/adb/Android.mk
index 2f5a2ee..b444afa 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -81,17 +81,21 @@
 
 LIBADB_darwin_SRC_FILES := \
     sysdeps_unix.cpp \
-    usb_osx.cpp \
+    client/usb_dispatch.cpp \
+    client/usb_libusb.cpp \
+    client/usb_osx.cpp \
 
 LIBADB_linux_SRC_FILES := \
     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 \
@@ -99,13 +103,26 @@
 
 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) \
     adbd_auth.cpp \
     jdwp_service.cpp \
-    usb_linux_client.cpp \
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
 
@@ -113,6 +130,8 @@
 # this to take effect), this adds the includes to our path.
 LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase
 
+LOCAL_WHOLE_STATIC_LIBRARIES := libadbd_usb
+
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
@@ -135,6 +154,8 @@
 # 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
+LOCAL_STATIC_LIBRARIES_linux := libusb
+LOCAL_STATIC_LIBRARIES_darwin := libusb
 
 LOCAL_C_INCLUDES_windows := development/host/windows/usb/api/
 LOCAL_MULTILIB := first
@@ -154,7 +175,7 @@
     shell_service_test.cpp \
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
-LOCAL_STATIC_LIBRARIES := libadbd libcrypto_utils libcrypto
+LOCAL_STATIC_LIBRARIES := libadbd libcrypto_utils libcrypto libusb
 LOCAL_SHARED_LIBRARIES := liblog libbase libcutils
 include $(BUILD_NATIVE_TEST)
 
@@ -204,10 +225,13 @@
     libdiagnose_usb \
     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
 
@@ -221,7 +245,7 @@
 
 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
@@ -272,6 +296,9 @@
 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
@@ -346,3 +373,5 @@
     libdebuggerd_handler \
 
 include $(BUILD_EXECUTABLE)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 3cd50ba..ece143c 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -40,6 +40,7 @@
 #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>
 
@@ -1047,7 +1048,7 @@
         // may not read the OKAY sent above.
         adb_shutdown(reply_fd);
 
-        exit(0);
+        android::base::quick_exit(0);
     }
 
 #if ADB_HOST
diff --git a/adb/adb.h b/adb/adb.h
index 7db3b15..6a38f18 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -28,6 +28,7 @@
 #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;
@@ -54,7 +55,6 @@
 #define ADB_SERVER_VERSION 38
 
 class atransport;
-struct usb_handle;
 
 struct amessage {
     uint32_t command;     /* command identifier constant      */
@@ -195,18 +195,6 @@
 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 usb_class, int usb_subclass, int usb_protocol);
-#endif
-
 ConnectionState connection_state(atransport *t);
 
 extern const char* adb_device_banner;
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 5a3b401..7afa616 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -313,3 +313,15 @@
 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 16317e0..2b59034 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -21,6 +21,8 @@
 
 #include <android-base/macros.h>
 
+int usage(const char*, ...);
+
 void close_stdin();
 
 bool getcwd(std::string* cwd);
diff --git a/adb/bugreport.cpp b/adb/bugreport.cpp
index 9b59d05..b7e76a6 100644
--- a/adb/bugreport.cpp
+++ b/adb/bugreport.cpp
@@ -182,11 +182,8 @@
     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;
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index d583516..97a54fd 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -28,6 +28,7 @@
 #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"
@@ -86,7 +87,7 @@
 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
@@ -108,6 +109,10 @@
     }
 
     SetConsoleCtrlHandler(ctrlc_handler, TRUE);
+#else
+    signal(SIGINT, [](int) {
+        android::base::quick_exit(0);
+    });
 #endif
 
     init_transport_registration();
diff --git a/adb/client/usb_dispatch.cpp b/adb/client/usb_dispatch.cpp
new file mode 100644
index 0000000..f02dccf
--- /dev/null
+++ b/adb/client/usb_dispatch.cpp
@@ -0,0 +1,55 @@
+/*
+ * 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"
+
+static bool should_use_libusb() {
+    static bool enable = getenv("ADB_LIBUSB") && strcmp(getenv("ADB_LIBUSB"), "1") == 0;
+    return enable;
+}
+
+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/usb_linux.cpp b/adb/client/usb_linux.cpp
similarity index 99%
rename from adb/usb_linux.cpp
rename to adb/client/usb_linux.cpp
index e7f1338..13b7674 100644
--- a/adb/usb_linux.cpp
+++ b/adb/client/usb_linux.cpp
@@ -46,6 +46,7 @@
 
 #include "adb.h"
 #include "transport.h"
+#include "usb.h"
 
 using namespace std::chrono_literals;
 using namespace std::literals;
@@ -53,7 +54,8 @@
 /* usb scan debugging is waaaay too verbose */
 #define DBGX(x...)
 
-struct usb_handle {
+namespace native {
+struct usb_handle : public ::usb_handle {
     ~usb_handle() {
       if (fd != -1) unix_close(fd);
     }
@@ -595,3 +597,4 @@
         fatal_errno("cannot create device_poll thread");
     }
 }
+} // namespace native
diff --git a/adb/usb_osx.cpp b/adb/client/usb_osx.cpp
similarity index 98%
rename from adb/usb_osx.cpp
rename to adb/client/usb_osx.cpp
index e541f6e..d4fc7c0 100644
--- a/adb/usb_osx.cpp
+++ b/adb/client/usb_osx.cpp
@@ -44,6 +44,7 @@
 
 using namespace std::chrono_literals;
 
+namespace native {
 struct usb_handle
 {
     UInt8 bulkIn;
@@ -298,7 +299,8 @@
         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);
+        register_usb_transport(reinterpret_cast<::usb_handle*>(handle_p), serial, devpath.c_str(),
+                               1);
     }
 }
 
@@ -558,3 +560,4 @@
     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
     usb_kick_locked(handle);
 }
+} // namespace native
diff --git a/adb/usb_windows.cpp b/adb/client/usb_windows.cpp
similarity index 100%
rename from adb/usb_windows.cpp
rename to adb/client/usb_windows.cpp
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 2befa0c..3b2df2e 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -231,11 +231,6 @@
     // clang-format on
 }
 
-int usage() {
-    help();
-    return 1;
-}
-
 #if defined(_WIN32)
 
 // Implemented in sysdeps_win32.cpp.
@@ -1235,7 +1230,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);
@@ -1443,19 +1438,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++;
@@ -1465,13 +1460,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++;
@@ -1484,7 +1479,7 @@
             gListenAll = 1;
         } else if (!strncmp(argv[0], "-H", 2)) {
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage();
+                if (argc < 2) return usage("-H requires an argument");
                 server_host_str = argv[1];
                 argc--;
                 argv++;
@@ -1493,7 +1488,7 @@
             }
         } 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++;
@@ -1501,7 +1496,7 @@
                 server_port_str = argv[0] + 2;
             }
         } else if (!strcmp(argv[0], "-L")) {
-            if (argc < 2) return usage();
+            if (argc < 2) return usage("-L requires an argument");
             server_socket_str = argv[1];
             argc--;
             argv++;
@@ -1566,7 +1561,7 @@
         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_socket_str, ack_reply_fd);
         } else {
@@ -1579,7 +1574,8 @@
     }
 
     if (argc == 0) {
-        return usage();
+        help();
+        return 1;
     }
 
     /* handle wait-for-* prefix */
@@ -1696,7 +1692,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 {
@@ -1730,7 +1726,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;
@@ -1750,24 +1746,24 @@
 
         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();
+            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();
+            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];
             }
@@ -1796,7 +1792,7 @@
     }
     /* 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")) {
@@ -1805,7 +1801,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")) {
@@ -1814,22 +1810,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);
         }
@@ -1852,12 +1848,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");
@@ -1909,7 +1905,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]);
@@ -1926,11 +1922,11 @@
 
 
     /* "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;
     }
@@ -1961,12 +1957,12 @@
                 std::string err;
                 return adb_query_command("host:reconnect-offline");
             } else {
-                return usage();
+                return usage("usage: adb reconnect [device|offline]");
             }
         }
     }
 
-    usage();
+    usage("unknown command %s", argv[0]);
     return 1;
 }
 
diff --git a/adb/usb_linux_client.cpp b/adb/daemon/usb.cpp
similarity index 93%
rename from adb/usb_linux_client.cpp
rename to adb/daemon/usb.cpp
index a21a193..a35c210 100644
--- a/adb/usb_linux_client.cpp
+++ b/adb/daemon/usb.cpp
@@ -40,13 +40,14 @@
 #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
+#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
@@ -55,31 +56,11 @@
 // 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)
+#define cpu_to_le16(x) htole16(x)
+#define cpu_to_le32(x) htole32(x)
 
 static int dummy_fd = -1;
 
-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 */
-};
-
 struct func_desc {
     struct usb_interface_descriptor intf;
     struct usb_endpoint_descriptor_no_audio source;
@@ -223,7 +204,6 @@
     .Reserved = cpu_to_le32(0),
 };
 
-
 #define STR_INTERFACE_ "ADB Interface"
 
 static const struct {
@@ -245,7 +225,7 @@
     },
 };
 
-static bool init_functionfs(struct usb_handle* h) {
+bool init_functionfs(struct usb_handle* h) {
     ssize_t ret;
     struct desc_v1 v1_descriptor;
     struct desc_v2 v2_descriptor;
diff --git a/adb/daemon/usb.h b/adb/daemon/usb.h
new file mode 100644
index 0000000..1d85405
--- /dev/null
+++ b/adb/daemon/usb.h
@@ -0,0 +1,50 @@
+#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>
+
+// 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
+
+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 */
+};
+
+bool init_functionfs(struct usb_handle* h);
diff --git a/adb/transport_usb.cpp b/adb/transport_usb.cpp
index d054601..3d6cc99 100644
--- a/adb/transport_usb.cpp
+++ b/adb/transport_usb.cpp
@@ -93,9 +93,7 @@
     t->usb = h;
 }
 
-#if ADB_HOST
 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);
 }
-#endif
diff --git a/adb/usb.h b/adb/usb.h
new file mode 100644
index 0000000..879bacc
--- /dev/null
+++ b/adb/usb.h
@@ -0,0 +1,57 @@
+/*
+ * 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);
diff --git a/adf/libadf/Android.bp b/adf/libadf/Android.bp
index 2b5461e..1a81a49 100644
--- a/adf/libadf/Android.bp
+++ b/adf/libadf/Android.bp
@@ -19,3 +19,5 @@
     local_include_dirs: ["include"],
     export_include_dirs: ["include"],
 }
+
+subdirs = ["tests"]
diff --git a/adf/libadf/include/video/adf.h b/adf/libadf/include/video/adf.h
new file mode 100644
index 0000000..77203a5
--- /dev/null
+++ b/adf/libadf/include/video/adf.h
@@ -0,0 +1,180 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   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,
+};
+struct adf_set_event {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u8 type;
+  __u8 enabled;
+};
+struct adf_event {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u8 type;
+  __u32 length;
+};
+struct adf_vsync_event {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  struct adf_event base;
+  __aligned_u64 timestamp;
+};
+struct adf_hotplug_event {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  struct adf_event base;
+  __u8 connected;
+};
+#define ADF_MAX_PLANES 4
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_buffer_config {
+  __u32 overlay_engine;
+  __u32 w;
+  __u32 h;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 format;
+  __s32 fd[ADF_MAX_PLANES];
+  __u32 offset[ADF_MAX_PLANES];
+  __u32 pitch[ADF_MAX_PLANES];
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u8 n_planes;
+  __s32 acquire_fence;
+};
+#define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct adf_post_config {
+  size_t n_interfaces;
+  __u32 __user * interfaces;
+  size_t n_bufs;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  struct adf_buffer_config __user * bufs;
+  size_t custom_data_size;
+  void __user * custom_data;
+  __s32 complete_fence;
+/* 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;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u16 h;
+  __u32 format;
+  __s32 fd;
+  __u32 offset;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __u32 pitch;
+};
+struct adf_simple_post_config {
+  struct adf_buffer_config buf;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+  __s32 complete_fence;
+};
+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)
+#endif
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..c5d2e62
--- /dev/null
+++ b/adf/libadf/original-kernel-headers/video/adf.h
@@ -0,0 +1,321 @@
+/*
+ * 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,
+};
+
+/**
+ * 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
+ *
+ * @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;
+};
+#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
+ *
+ * @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_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)
+
+#endif /* _UAPI_VIDEO_ADF_H_ */
diff --git a/adf/libadf/tests/adf_test.cpp b/adf/libadf/tests/adf_test.cpp
index 01b2785..eaa9342 100644
--- a/adf/libadf/tests/adf_test.cpp
+++ b/adf/libadf/tests/adf_test.cpp
@@ -149,11 +149,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,
diff --git a/base/logging.cpp b/base/logging.cpp
index cbc3c8a..6357b4b 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -118,27 +118,32 @@
 namespace android {
 namespace base {
 
-static auto& logging_lock = *new std::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 auto& gAborter = *new AbortFunction(DefaultAborter);
+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>();
-
-static const char* ProgramInvocationName() {
-  if (gProgramInvocationName == nullptr) {
-    gProgramInvocationName.reset(new std::string(getprogname()));
-  }
-
-  return gProgramInvocationName->c_str();
-}
 
 #if defined(__linux__)
 void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
@@ -198,7 +203,7 @@
   static_assert(arraysize(log_characters) - 1 == FATAL + 1,
                 "Mismatch in size of log_characters and values in LogSeverity");
   char severity_char = log_characters[severity];
-  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
+  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
           severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
 }
 
@@ -262,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");
@@ -307,13 +313,13 @@
 }
 
 void SetLogger(LogFunction&& logger) {
-  std::lock_guard<std::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(logging_lock);
-  gAborter = std::move(aborter);
+  std::lock_guard<std::mutex> lock(LoggingLock());
+  Aborter() = std::move(aborter);
 }
 
 static const char* GetFileBasename(const char* file) {
@@ -403,7 +409,7 @@
 
   {
     // Do the actual logging with the lock held.
-    std::lock_guard<std::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());
@@ -424,7 +430,7 @@
 
   // Abort if necessary.
   if (data_->GetSeverity() == FATAL) {
-    gAborter(msg.c_str());
+    Aborter()(msg.c_str());
   }
 }
 
@@ -434,8 +440,8 @@
 
 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);
 }
 
 LogSeverity GetMinimumLogSeverity() {
diff --git a/base/logging_test.cpp b/base/logging_test.cpp
index 2d9c2ba..adb041b 100644
--- a/base/logging_test.cpp
+++ b/base/logging_test.cpp
@@ -594,3 +594,7 @@
 
   EXPECT_EQ(CountLineAborter::newline_count, 1U + 1U);  // +1 for final '\n'.
 }
+
+__attribute__((constructor)) void TestLoggingInConstructor() {
+  LOG(ERROR) << "foobar";
+}
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index 483c01d..c85667e 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -28,10 +28,12 @@
 #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 "boot_event_record_store.h"
@@ -212,14 +214,33 @@
     BootEventRecordStore* boot_event_store, const char* property) {
   std::string value = GetProperty(property);
 
-  int32_t time_in_ns;
-  if (android::base::ParseInt(value, &time_in_ns)) {
-    static constexpr int32_t kNanosecondsPerMillisecond = 1e6;
-    int32_t time_in_ms = static_cast<int32_t>(time_in_ns / kNanosecondsPerMillisecond);
+  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");
+
+  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)) {
+      boot_event_store->AddBootEventWithValue(
+          "boottime.bootloader." + stageName, time_ms);
+    }
+  }
+}
+
 // 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() {
@@ -273,6 +294,8 @@
   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
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index ca8bea2..b072412 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -12,19 +12,19 @@
     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/debuggerd/Android.bp b/debuggerd/Android.bp
index 6dc6675..ca881aa 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -195,3 +195,7 @@
 
     init_rc: ["tombstoned/tombstoned.rc"]
 }
+
+subdirs = [
+    "crasher",
+]
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 831150b..2889356 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -18,10 +18,12 @@
 #include <dirent.h>
 #include <fcntl.h>
 #include <stdlib.h>
-#include <syscall.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>
@@ -36,7 +38,7 @@
 #include <android-base/stringprintf.h>
 #include <android-base/unique_fd.h>
 #include <cutils/sockets.h>
-#include <log/logger.h>
+#include <log/log.h>
 #include <procinfo/process.h>
 #include <selinux/selinux.h>
 
@@ -51,26 +53,33 @@
 using android::base::unique_fd;
 using android::base::StringPrintf;
 
-static bool pid_contains_tid(pid_t pid, pid_t tid) {
-  std::string task_path = StringPrintf("/proc/%d/task/%d", pid, tid);
-  return access(task_path.c_str(), F_OK) == 0;
+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_attach_thread(pid_t pid, pid_t tid, std::string* error) {
-  if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) {
+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, tid)) {
+  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 %d", tid, pid);
+    *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;
 }
 
@@ -160,11 +169,15 @@
   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) {
-  LOG(ERROR) << 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) {
@@ -177,10 +190,27 @@
 
   dprintf(output_fd.get(), "crash_dump failed to dump process %d: %s\n", target, abort_msg);
 
-  // Don't dump ourselves.
   _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";
+  }
+}
+
 static void check_process(int proc_fd, pid_t expected_pid) {
   android::procinfo::ProcessInfo proc_info;
   if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
@@ -203,6 +233,11 @@
     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 != 2) {
     return 1;
   }
@@ -243,10 +278,13 @@
     exit(0);
   }
 
+  // Die if we take too long.
+  alarm(20);
+
   check_process(target_proc_fd, target);
 
   std::string attach_error;
-  if (!ptrace_attach_thread(target, main_tid, &attach_error)) {
+  if (!ptrace_seize_thread(target_proc_fd, main_tid, &attach_error)) {
     LOG(FATAL) << attach_error;
   }
 
@@ -267,13 +305,14 @@
   } 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 PTRACE_ATTACHed
-  // and has the signal that triggered things queued. Send PTRACE_CONT, and
-  // then wait for the signal.
+  // 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);
@@ -286,6 +325,7 @@
   }
 
   int signo = siginfo.si_signo;
+  bool fatal_signal = signo != DEBUGGER_SIGNAL;
   bool backtrace = false;
   uintptr_t abort_address = 0;
 
@@ -301,18 +341,16 @@
 
   // Now that we have the signal that kicked things off, attach all of the
   // sibling threads, and then proceed.
-  bool fatal_signal = signo != DEBUGGER_SIGNAL;
-  int resume_signal = fatal_signal ? signo : 0;
-  std::set<pid_t> siblings;
   std::set<pid_t> attached_siblings;
-  if (resume_signal == 0) {
+  {
+    std::set<pid_t> siblings;
     if (!android::procinfo::GetProcessTids(target, &siblings)) {
       PLOG(FATAL) << "failed to get process siblings";
     }
     siblings.erase(main_tid);
 
     for (pid_t sibling_tid : siblings) {
-      if (!ptrace_attach_thread(target, sibling_tid, &attach_error)) {
+      if (!ptrace_seize_thread(target_proc_fd, sibling_tid, &attach_error)) {
         LOG(WARNING) << attach_error;
       } else {
         attached_siblings.insert(sibling_tid);
@@ -320,58 +358,66 @@
     }
   }
 
+  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;
+  if (!backtrace) {
+    populate_open_files_list(target, &open_files);
+  }
+
+  // Drop our capabilities now that we've attached to the threads we care about.
+  drop_capabilities();
+
   check_process(target_proc_fd, target);
 
   // TODO: Use seccomp to lock ourselves down.
 
-  std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
   std::string amfd_data;
 
   if (backtrace) {
     dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
   } else {
-    // Collect the list of open files.
-    OpenFilesList open_files;
-    populate_open_files_list(target, &open_files);
-
     engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
                       attached_siblings, 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 (wait_for_gdb) {
+  if (!fatal_signal || siginfo.si_code == SI_USER) {
     // Don't wait_for_gdb when the process didn't actually crash.
-    if (!fatal_signal) {
-      wait_for_gdb = false;
-    } else {
-      // 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);
-    }
+    wait_for_gdb = false;
   }
 
-  for (pid_t tid : attached_siblings) {
-    // Don't send the signal to sibling threads.
-    if (ptrace(PTRACE_DETACH, tid, 0, wait_for_gdb ? SIGSTOP : 0) != 0) {
-      PLOG(ERROR) << "ptrace detach from " << tid << " failed";
+  // 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 (ptrace(PTRACE_DETACH, main_tid, 0, wait_for_gdb ? SIGSTOP : resume_signal)) {
-    PLOG(ERROR) << "ptrace detach from main thread " << main_tid << " failed";
+    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) {
-    if (tgkill(target, main_tid, resume_signal) != 0) {
-      PLOG(ERROR) << "failed to resend signal to process " << target;
-    }
+    // 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) {
@@ -380,7 +426,7 @@
 
   // Close stdout before we notify tombstoned of completion.
   close(STDOUT_FILENO);
-  if (!tombstoned_notify_completion(tombstoned_socket.get())) {
+  if (tombstoned_connected && !tombstoned_notify_completion(tombstoned_socket.get())) {
     LOG(ERROR) << "failed to notify tombstoned of completion";
   }
 
diff --git a/debuggerd/crasher/Android.bp b/debuggerd/crasher/Android.bp
new file mode 100644
index 0000000..4727894
--- /dev/null
+++ b/debuggerd/crasher/Android.bp
@@ -0,0 +1,81 @@
+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",
+    ],
+    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",
+    ],
+    multilib: {
+        lib32: {
+            stem: "static_crasher",
+        },
+        lib64: {
+            stem: "static_crasher64",
+        },
+    },
+}
diff --git a/debuggerd/crasher/Android.mk b/debuggerd/crasher/Android.mk
deleted file mode 100644
index b8b786b..0000000
--- a/debuggerd/crasher/Android.mk
+++ /dev/null
@@ -1,66 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-crasher_cppflags := \
-    -std=gnu++14 \
-    -W \
-    -Wall \
-    -Wextra \
-    -Wunused \
-    -Werror \
-    -O0 \
-    -fstack-protector-all \
-    -Wno-free-nonheap-object \
-    -Wno-date-time
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := crasher.cpp
-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_CPPFLAGS := $(crasher_cppflags)
-LOCAL_SHARED_LIBRARIES := libbase liblog
-
-# 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)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := crasher.cpp
-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_CPPFLAGS := $(crasher_cppflags) -DSTATIC_CRASHER
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_SHARED_LIBRARIES := libbase liblog
-
-# 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 := static_crasher
-LOCAL_MODULE_STEM_32 := static_crasher
-LOCAL_MODULE_STEM_64 := static_crasher64
-LOCAL_MULTILIB := both
-
-LOCAL_STATIC_LIBRARIES := libdebuggerd_handler libbase liblog
-
-include $(BUILD_EXECUTABLE)
diff --git a/debuggerd/crasher/crasher.cpp b/debuggerd/crasher/crasher.cpp
index 288f116..64a38dd 100644
--- a/debuggerd/crasher/crasher.cpp
+++ b/debuggerd/crasher/crasher.cpp
@@ -36,6 +36,19 @@
 #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.
@@ -142,22 +155,36 @@
     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, "  nostack               crash with a NULL stack pointer\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");
@@ -235,6 +262,20 @@
                                                  MAP_SHARED | MAP_ANONYMOUS, -1, 0));
         munmap(map, sizeof(int));
         map[0] = '8';
+    } else if (!strcasecmp(arg, "seccomp")) {
+        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 {
         return usage();
     }
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 3208230..0c5d3cf 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -71,7 +71,7 @@
   std::thread redirect_thread = spawn_redirect_thread(std::move(piperead));
   bool backtrace = argc == 3;
   if (!debuggerd_trigger_dump(pid, std::move(pipewrite),
-                              backtrace ? kDebuggerdBacktrace : kDebuggerdBacktrace, 0)) {
+                              backtrace ? kDebuggerdBacktrace : kDebuggerdTombstone, 0)) {
     redirect_thread.join();
     errx(1, "failed to dump process %d", pid);
   }
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index f51b5f2..002e940 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -17,6 +17,7 @@
 #include <err.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <sys/prctl.h>
 #include <sys/types.h>
 
 #include <chrono>
@@ -39,10 +40,10 @@
 using android::base::unique_fd;
 
 #if defined(__LP64__)
-#define CRASHER_PATH  "/system/xbin/crasher64"
+#define CRASHER_PATH  "/system/bin/crasher64"
 #define ARCH_SUFFIX "64"
 #else
-#define CRASHER_PATH "/system/xbin/crasher"
+#define CRASHER_PATH "/system/bin/crasher"
 #define ARCH_SUFFIX ""
 #endif
 
@@ -90,6 +91,7 @@
   // 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);
   void StartCrasher(const std::string& crash_type);
   void FinishCrasher();
   void AssertDeath(int signo);
@@ -166,9 +168,8 @@
   }
 }
 
-void CrasherTest::StartCrasher(const std::string& crash_type) {
-  std::string type = "wait-" + crash_type;
-
+void CrasherTest::StartProcess(std::function<void()> function) {
+  unique_fd read_pipe;
   unique_fd crasher_read_pipe;
   if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
     FAIL() << "failed to create pipe: " << strerror(errno);
@@ -182,11 +183,19 @@
     dup2(crasher_read_pipe.get(), STDIN_FILENO);
     dup2(devnull.get(), STDOUT_FILENO);
     dup2(devnull.get(), STDERR_FILENO);
-    execl(CRASHER_PATH, CRASHER_PATH, type.c_str(), nullptr);
-    err(1, "exec failed");
+    function();
+    _exit(0);
   }
 }
 
+void CrasherTest::StartCrasher(const std::string& crash_type) {
+  std::string type = "wait-" + crash_type;
+  StartProcess([type]() {
+    execl(CRASHER_PATH, CRASHER_PATH, type.c_str(), nullptr);
+    exit(errno);
+  });
+}
+
 void CrasherTest::FinishCrasher() {
   if (crasher_pipe == -1) {
     FAIL() << "crasher pipe uninitialized";
@@ -207,7 +216,9 @@
     FAIL() << "failed to wait for crasher: " << strerror(errno);
   }
 
-  if (!WIFSIGNALED(status)) {
+  if (WIFEXITED(status)) {
+    FAIL() << "crasher failed to exec: " << strerror(WEXITSTATUS(status));
+  } else if (!WIFSIGNALED(status)) {
     FAIL() << "crasher didn't terminate via a signal";
   }
   ASSERT_EQ(signo, WTERMSIG(status));
@@ -340,24 +351,15 @@
   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";
   }
 
   StartCrasher("abort");
-  ASSERT_EQ(0, kill(crasher_pid, SIGABRT)) << strerror(errno);
-
-  std::this_thread::sleep_for(500ms);
-
-  int status;
-  ASSERT_EQ(crasher_pid, (TIMEOUT(1, waitpid(crasher_pid, &status, WUNTRACED))));
-  ASSERT_TRUE(WIFSTOPPED(status));
-  ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
-
-  ASSERT_EQ(0, kill(crasher_pid, SIGCONT)) << strerror(errno);
-
-  AssertDeath(SIGABRT);
+  ASSERT_EQ(0, kill(crasher_pid, SIGSEGV)) << strerror(errno);
+  AssertDeath(SIGSEGV);
 }
 
 TEST_F(CrasherTest, backtrace) {
@@ -388,3 +390,20 @@
   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) {
+  StartProcess([]() {
+    prctl(PR_SET_DUMPABLE, 0);
+    volatile char* null = static_cast<char*>(nullptr);
+    *null = '\0';
+  });
+  AssertDeath(SIGSEGV);
+}
+
+TEST_F(CrasherTest, PR_SET_DUMPABLE_0_raise) {
+  StartProcess([]() {
+    prctl(PR_SET_DUMPABLE, 0);
+    raise(SIGUSR1);
+  });
+  AssertDeath(SIGUSR1);
+}
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 6033a6b..38a7be3 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -31,6 +31,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <linux/futex.h>
 #include <pthread.h>
 #include <sched.h>
 #include <signal.h>
@@ -38,6 +39,7 @@
 #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>
@@ -46,6 +48,7 @@
 #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
@@ -61,12 +64,26 @@
 
 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.
-#define fatal(...)                                             \
-  do {                                                         \
-    __libc_format_log(ANDROID_LOG_FATAL, "libc", __VA_ARGS__); \
-    _exit(1);                                                  \
-  } while (0)
+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];
+  vsnprintf(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
@@ -78,6 +95,21 @@
  * 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_FATAL, "libc", "Requested dump for tid %d (%s)", gettid(),
+                      thread_name);
+    return;
+  }
+
   const char* signal_name = "???";
   bool has_address = false;
   switch (signum) {
@@ -113,15 +145,6 @@
       break;
   }
 
-  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;
-  }
-
   // "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"
@@ -133,6 +156,7 @@
       __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);
 }
@@ -151,8 +175,7 @@
 }
 
 struct debugger_thread_info {
-  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
-  bool crash_dump_started = false;
+  bool crash_dump_started;
   pid_t crashing_tid;
   pid_t pseudothread_tid;
   int signal_number;
@@ -181,11 +204,11 @@
 
   int pipefds[2];
   if (pipe(pipefds) != 0) {
-    fatal("failed to create pipe");
+    fatal_errno("failed to create pipe");
   }
 
   // Don't use fork(2) to avoid calling pthread_atfork handlers.
-  int forkpid = clone(nullptr, nullptr, SIGCHLD, nullptr);
+  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));
@@ -194,11 +217,16 @@
     close(pipefds[0]);
     close(pipefds[1]);
 
+    // Set all of the ambient capability bits we can, so that crash_dump can ptrace us.
+    for (unsigned long i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) != -1; ++i) {
+      prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0);
+    }
+
     char buf[10];
     snprintf(buf, sizeof(buf), "%d", thread_info->crashing_tid);
     execl(CRASH_DUMP_PATH, CRASH_DUMP_NAME, buf, nullptr);
 
-    fatal("exec failed: %s", strerror(errno));
+    fatal_errno("exec failed");
   } else {
     close(pipefds[1]);
     char buf[4];
@@ -220,24 +248,53 @@
     close(pipefds[0]);
 
     // Don't leave a zombie child.
-    siginfo_t child_siginfo;
-    if (TEMP_FAILURE_RETRY(waitid(P_PID, forkpid, &child_siginfo, WEXITED)) != 0) {
+    int status;
+    if (TEMP_FAILURE_RETRY(waitpid(forkpid, &status, __WCLONE)) == -1 && errno != ECHILD) {
       __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;
     }
   }
 
-  pthread_mutex_unlock(&thread_info->mutex);
+  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");
+    }
+  }
+
+  if (info->si_signo == DEBUGGER_SIGNAL) {
+    pthread_mutex_unlock(&crash_mutex);
+  }
+}
+
 // 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*) {
-  // Mutex to prevent multiple crashing threads from trying to talk
-  // to debuggerd at the same time.
-  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));
@@ -250,59 +307,10 @@
     info = nullptr;
   }
 
-  log_signal_summary(signal_number, info);
-  if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) == 0) {
-    // process has disabled core dumps and PTRACE_ATTACH, and does not want to be dumped.
-    // Honor that intention by not connecting to debuggerd and asking it to dump our internal state.
-    __libc_format_log(ANDROID_LOG_INFO, "libc",
-                      "Suppressing debuggerd output because prctl(PR_GET_DUMPABLE)==0");
-
-    pthread_mutex_unlock(&crash_mutex);
-    return;
-  }
-
-  void* abort_message = nullptr;
-  if (g_callbacks.get_abort_message) {
-    abort_message = g_callbacks.get_abort_message();
-  }
-
-  debugger_thread_info thread_info = {
-    .crashing_tid = gettid(),
-    .signal_number = signal_number,
-    .info = info
-  };
-  pthread_mutex_lock(&thread_info.mutex);
-
-  // 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,
-                          &thread_info, nullptr, nullptr, &thread_info.pseudothread_tid);
-  if (child_pid == -1) {
-    fatal("failed to spawn debuggerd dispatch thread: %s", strerror(errno));
-  }
-
-  // Wait for the child to finish and unlock the mutex.
-  // This relies on bionic behavior that isn't guaranteed by the standard.
-  pthread_mutex_lock(&thread_info.mutex);
-
-  // 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);
-  }
-
-  // We need to return from the signal handler so that debuggerd can dump the
-  // thread that crashed, but returning here does not guarantee that the signal
-  // will be thrown again, even for SIGSEGV and friends, since the signal could
-  // have been sent manually. Resend the signal with rt_tgsigqueueinfo(2) to
-  // preserve the SA_SIGINFO contents.
-  struct siginfo si;
+  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();
@@ -314,23 +322,59 @@
     // check to allow all si_code values in calls coming from inside the house.
   }
 
+  log_signal_summary(signal_number, info);
+
+  if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
+    // The process has NO_NEW_PRIVS enabled, so we can't transition to the crash_dump context.
+    __libc_format_log(ANDROID_LOG_INFO, "libc",
+                      "Suppressing debuggerd output because prctl(PR_GET_NO_NEW_PRIVS)==1");
+    resend_signal(info, false);
+    return;
+  }
+
+  void* abort_message = nullptr;
+  if (g_callbacks.get_abort_message) {
+    abort_message = g_callbacks.get_abort_message();
+  }
   // Populate si_value with the abort message address, if found.
   if (abort_message) {
     info->si_value.sival_ptr = abort_message;
   }
 
-  // Only resend the signal if we know that either crash_dump has ptraced us or
-  // the signal was fatal.
-  if (thread_info.crash_dump_started || signal_number != DEBUGGER_SIGNAL) {
-    int rc = syscall(SYS_rt_tgsigqueueinfo, getpid(), gettid(), signal_number, info);
-    if (rc != 0) {
-      fatal("failed to resend signal during crash: %s", strerror(errno));
-    }
+  debugger_thread_info thread_info = {
+    .crash_dump_started = false,
+    .pseudothread_tid = -1,
+    .crashing_tid = gettid(),
+    .signal_number = signal_number,
+    .info = info
+  };
+
+  // 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");
   }
 
-  if (signal_number == DEBUGGER_SIGNAL) {
-    pthread_mutex_unlock(&crash_mutex);
+  // 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);
+
+  // 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);
 }
 
 void debuggerd_init(debuggerd_callbacks_t* callbacks) {
@@ -341,12 +385,12 @@
   void* thread_stack_allocation =
     mmap(nullptr, PAGE_SIZE * 3, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
   if (thread_stack_allocation == MAP_FAILED) {
-    fatal("failed to allocate debuggerd thread stack");
+    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("failed to mprotect debuggerd thread stack");
+    fatal_errno("failed to mprotect debuggerd thread stack");
   }
 
   // Stack grows negatively, set it to the last byte in the page...
@@ -363,15 +407,5 @@
 
   // Use the alternate signal stack if available so we can catch stack overflows.
   action.sa_flags |= SA_ONSTACK;
-
-  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(SIGTRAP, &action, nullptr);
-  sigaction(DEBUGGER_SIGNAL, &action, nullptr);
+  debuggerd_register_handlers(&action);
 }
diff --git a/debuggerd/include/debuggerd/handler.h b/debuggerd/include/debuggerd/handler.h
index 302f4c2..7196e0a 100644
--- a/debuggerd/include/debuggerd/handler.h
+++ b/debuggerd/include/debuggerd/handler.h
@@ -39,4 +39,18 @@
 // 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/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index 01e9cf6..ac2c0b6 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -49,6 +49,8 @@
 #include "open_files_list.h"
 #include "tombstone.h"
 
+using android::base::StringPrintf;
+
 #define STACK_WORDS 16
 
 #define MAX_TOMBSTONES  10
@@ -74,7 +76,7 @@
 }
 
 static const char* get_signame(int sig) {
-  switch(sig) {
+  switch (sig) {
     case SIGABRT: return "SIGABRT";
     case SIGBUS: return "SIGBUS";
     case SIGFPE: return "SIGFPE";
@@ -195,6 +197,29 @@
   _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 system call %d", si.si_syscall);
+  }
+
+  if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
+}
+
 static void dump_signal_info(log_t* log, pid_t tid) {
   siginfo_t si;
   memset(&si, 0, sizeof(si));
@@ -212,6 +237,8 @@
 
   _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_thread_info(log_t* log, pid_t pid, pid_t tid) {
@@ -262,11 +289,11 @@
     line = "    ";
     if (i == 0 && label >= 0) {
       // Print the label once.
-      line += android::base::StringPrintf("#%02d  ", label);
+      line += StringPrintf("#%02d  ", label);
     } else {
       line += "     ";
     }
-    line += android::base::StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, stack_data[i]);
+    line += StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, stack_data[i]);
 
     backtrace_map_t map;
     backtrace->FillInMap(stack_data[i], &map);
@@ -277,7 +304,7 @@
       if (!func_name.empty()) {
         line += " (" + func_name;
         if (offset) {
-          line += android::base::StringPrintf("+%" PRIuPTR, offset);
+          line += StringPrintf("+%" PRIuPTR, offset);
         }
         line += ')';
       }
@@ -336,11 +363,11 @@
 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));
+  addr_str = StringPrintf("%08x'%08x",
+                          static_cast<uint32_t>(addr >> 32),
+                          static_cast<uint32_t>(addr & 0xffffffff));
 #else
-  addr_str = android::base::StringPrintf("%08x", addr);
+  addr_str = StringPrintf("%08x", addr);
 #endif
   return addr_str;
 }
@@ -426,8 +453,7 @@
     } else {
       line += '-';
     }
-    line += android::base::StringPrintf("  %8" PRIxPTR "  %8" PRIxPTR,
-                                        it->offset, it->end - it->start);
+    line += StringPrintf("  %8" PRIxPTR "  %8" PRIxPTR, it->offset, it->end - it->start);
     bool space_needed = true;
     if (it->name.length() > 0) {
       space_needed = false;
@@ -441,7 +467,7 @@
       if (space_needed) {
         line += ' ';
       }
-      line += android::base::StringPrintf(" (load base 0x%" PRIxPTR ")", it->load_base);
+      line += StringPrintf(" (load base 0x%" PRIxPTR ")", it->load_base);
     }
     _LOG(log, logtype::MAPS, "%s\n", line.c_str());
   }
diff --git a/debuggerd/tombstoned/tombstoned.cpp b/debuggerd/tombstoned/tombstoned.cpp
index 63e3dbd..8705ece 100644
--- a/debuggerd/tombstoned/tombstoned.cpp
+++ b/debuggerd/tombstoned/tombstoned.cpp
@@ -85,7 +85,13 @@
     std::string path = android::base::StringPrintf("%stombstone_%02zu", kTombstoneDirectory, i);
     struct stat st;
     if (stat(path.c_str(), &st) != 0) {
-      PLOG(ERROR) << "failed to stat " << path;
+      if (errno == ENOENT) {
+        oldest_tombstone = i;
+        break;
+      } else {
+        PLOG(ERROR) << "failed to stat " << path;
+        continue;
+      }
     }
 
     if (st.st_mtime < oldest_time) {
diff --git a/debuggerd/tombstoned/tombstoned.rc b/debuggerd/tombstoned/tombstoned.rc
index eaae9c4..b8345ca 100644
--- a/debuggerd/tombstoned/tombstoned.rc
+++ b/debuggerd/tombstoned/tombstoned.rc
@@ -2,6 +2,9 @@
     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/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 3f8bc8f..e7f1a07 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -358,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"
@@ -1397,6 +1397,7 @@
     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;
@@ -1647,6 +1648,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);
@@ -1807,6 +1812,9 @@
     } 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/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/fs_mgr/Android.mk b/fs_mgr/Android.mk
index 8d5b51b..956c702 100644
--- a/fs_mgr/Android.mk
+++ b/fs_mgr/Android.mk
@@ -11,18 +11,21 @@
     libcrypto \
     libext4_utils \
     libsquashfs_utils \
-    libselinux
+    libselinux \
+    libavb
 
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
 LOCAL_SANITIZE := integer
 LOCAL_SRC_FILES:= \
-    fs_mgr.c \
+    fs_mgr.cpp \
     fs_mgr_dm_ioctl.cpp \
-    fs_mgr_format.c \
-    fs_mgr_fstab.c \
-    fs_mgr_slotselect.c \
-    fs_mgr_verity.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
 LOCAL_C_INCLUDES := \
     $(LOCAL_PATH)/include \
     system/vold \
@@ -45,7 +48,7 @@
 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
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.cpp
similarity index 74%
rename from fs_mgr/fs_mgr.c
rename to fs_mgr/fs_mgr.cpp
index e699b71..be84e8a 100644
--- a/fs_mgr/fs_mgr.c
+++ b/fs_mgr/fs_mgr.cpp
@@ -31,6 +31,7 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <android-base/unique_fd.h>
 #include <cutils/android_reboot.h>
 #include <cutils/partition_utils.h>
 #include <cutils/properties.h>
@@ -46,6 +47,7 @@
 #include <private/android_logger.h>
 
 #include "fs_mgr_priv.h"
+#include "fs_mgr_priv_avb.h"
 #include "fs_mgr_priv_verity.h"
 
 #define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
@@ -74,7 +76,7 @@
 
     ret = clock_gettime(CLOCK_MONOTONIC, &ts);
     if (ret < 0) {
-        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
+        PERROR << "clock_gettime(CLOCK_MONOTONIC) failed";
         return 0;
     }
 
@@ -93,13 +95,13 @@
     return ret;
 }
 
-static void check_fs(char *blk_device, char *fs_type, char *target)
+static void check_fs(const 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[] = {
+    const char *e2fsck_argv[] = {
         E2FSCK_BIN,
 #ifndef TARGET_USES_MKE2FS // "-f" only for old ext4 generation tool
         "-f",
@@ -129,8 +131,8 @@
             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));
+        PINFO << __FUNCTION__ << "(): mount(" << blk_device <<  "," << target
+              << "," << fs_type << ")=" << ret;
         if (!ret) {
             int i;
             for (i = 0; i < 5; i++) {
@@ -138,10 +140,12 @@
                 // Should we try rebooting if all attempts fail?
                 int result = umount(target);
                 if (result == 0) {
-                    INFO("%s(): unmount(%s) succeeded\n", __func__, target);
+                    LINFO << __FUNCTION__ << "(): unmount(" << target
+                          << ") succeeded";
                     break;
                 }
-                ERROR("%s(): umount(%s)=%d: %s\n", __func__, target, result, strerror(errno));
+                PERROR << __FUNCTION__ << "(): umount(" << target << ")="
+                       << result;
                 sleep(1);
             }
         }
@@ -151,34 +155,39 @@
          * (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);
+            LINFO << "Not running " << E2FSCK_BIN << " on " << blk_device
+                  << " (executable not in system image)";
         } else {
-            INFO("Running %s on %s\n", E2FSCK_BIN, blk_device);
+            LINFO << "Running " << E2FSCK_BIN << " on " << blk_device;
 
-            ret = android_fork_execvp_ext(ARRAY_SIZE(e2fsck_argv), e2fsck_argv,
+            ret = android_fork_execvp_ext(ARRAY_SIZE(e2fsck_argv),
+                                          const_cast<char **>(e2fsck_argv),
                                           &status, true, LOG_KLOG | LOG_FILE,
-                                          true, FSCK_LOG_FILE, NULL, 0);
+                                          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 */
-                ERROR("Failed trying to run %s\n", E2FSCK_BIN);
+                LERROR << "Failed trying to run " << E2FSCK_BIN;
             }
         }
     } else if (!strcmp(fs_type, "f2fs")) {
-            char *f2fs_fsck_argv[] = {
+            const char *f2fs_fsck_argv[] = {
                     F2FS_FSCK_BIN,
                     "-a",
                     blk_device
             };
-        INFO("Running %s -a %s\n", F2FS_FSCK_BIN, blk_device);
+        LINFO << "Running " << F2FS_FSCK_BIN << " -a " << blk_device;
 
-        ret = android_fork_execvp_ext(ARRAY_SIZE(f2fs_fsck_argv), f2fs_fsck_argv,
+        ret = android_fork_execvp_ext(ARRAY_SIZE(f2fs_fsck_argv),
+                                      const_cast<char **>(f2fs_fsck_argv),
                                       &status, true, LOG_KLOG | LOG_FILE,
-                                      true, FSCK_LOG_FILE, NULL, 0);
+                                      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 */
-            ERROR("Failed trying to run %s\n", F2FS_FSCK_BIN);
+            LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
         }
     }
 
@@ -224,20 +233,21 @@
          * Detect these and skip reserve blocks.
          */
         if (access(TUNE2FS_BIN, X_OK)) {
-            ERROR("Not running %s on %s (executable not in system image)\n",
-                  TUNE2FS_BIN, blk_device);
+            LERROR << "Not running " << TUNE2FS_BIN << " on "
+                   << blk_device << " (executable not in system image)";
         } else {
-            char* arg1 = NULL;
-            char* arg2 = NULL;
+            const char* arg1 = nullptr;
+            const char* arg2 = nullptr;
             int status = 0;
             int ret = 0;
-            int fd = TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC));
+            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) {
-                    ERROR("Can't read '%s' super block: %s\n", blk_device, strerror(errno));
-                    goto out;
+                    PERROR << "Can't read '" << blk_device << "' super block";
+                    return force_check;
                 }
 
                 int has_quota = (sb.s_feature_ro_compat
@@ -245,38 +255,37 @@
                 int want_quota = fs_mgr_is_quota(rec) != 0;
 
                 if (has_quota == want_quota) {
-                    INFO("Requested quota status is match on %s\n", blk_device);
-                    goto out;
+                    LINFO << "Requested quota status is match on " << blk_device;
+                    return force_check;
                 } else if (want_quota) {
-                    INFO("Enabling quota on %s\n", blk_device);
+                    LINFO << "Enabling quota on " << blk_device;
                     arg1 = "-Oquota";
                     arg2 = "-Qusrquota,grpquota";
                     force_check = 1;
                 } else {
-                    INFO("Disabling quota on %s\n", blk_device);
+                    LINFO << "Disabling quota on " << blk_device;
                     arg1 = "-Q^usrquota,^grpquota";
                     arg2 = "-O^quota";
                 }
             } else {
-                ERROR("Failed to open '%s': %s\n", blk_device, strerror(errno));
+                PERROR << "Failed to open '" << blk_device << "'";
                 return force_check;
             }
 
-            char *tune2fs_argv[] = {
+            const char *tune2fs_argv[] = {
                 TUNE2FS_BIN,
                 arg1,
                 arg2,
                 blk_device,
             };
-            ret = android_fork_execvp_ext(ARRAY_SIZE(tune2fs_argv), tune2fs_argv,
+            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 */
-                ERROR("Failed trying to run %s\n", TUNE2FS_BIN);
+                LERROR << "Failed trying to run " << TUNE2FS_BIN;
             }
-      out:
-            close(fd);
         }
     }
     return force_check;
@@ -291,56 +300,57 @@
          * Detect these and skip reserve blocks.
          */
         if (access(TUNE2FS_BIN, X_OK)) {
-            ERROR("Not running %s on %s (executable not in system image)\n",
-                  TUNE2FS_BIN, blk_device);
+            LERROR << "Not running " << TUNE2FS_BIN << " on "
+                   << blk_device << " (executable not in system image)";
         } else {
-            INFO("Running %s on %s\n", TUNE2FS_BIN, blk_device);
+            LINFO << "Running " << TUNE2FS_BIN << " on " << blk_device;
 
             int status = 0;
             int ret = 0;
             unsigned long reserved_blocks = 0;
-            int fd = TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC));
+            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) {
-                    ERROR("Can't read '%s' super block: %s\n", blk_device, strerror(errno));
-                    goto out;
+                    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) {
-                    WARNING("Reserved blocks %lu is too large\n", reserved_blocks);
+                    LWARNING << "Reserved blocks " << reserved_blocks
+                             << " is too large";
                     reserved_blocks = reserved_threshold;
                 }
 
                 if (ext4_r_blocks_count(&sb) == reserved_blocks) {
-                    INFO("Have reserved same blocks\n");
-                    goto out;
+                    LINFO << "Have reserved same blocks";
+                    return;
                 }
             } else {
-                ERROR("Failed to open '%s': %s\n", blk_device, strerror(errno));
+                PERROR << "Failed to open '" << blk_device << "'";
                 return;
             }
 
             char buf[16] = {0};
             snprintf(buf, sizeof (buf), "-r %lu", reserved_blocks);
-            char *tune2fs_argv[] = {
+            const char *tune2fs_argv[] = {
                 TUNE2FS_BIN,
                 buf,
                 blk_device,
             };
 
-            ret = android_fork_execvp_ext(ARRAY_SIZE(tune2fs_argv), tune2fs_argv,
+            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 */
-                ERROR("Failed trying to run %s\n", TUNE2FS_BIN);
+                LERROR << "Failed trying to run " << TUNE2FS_BIN;
             }
-      out:
-            close(fd);
         }
     }
 }
@@ -399,7 +409,8 @@
     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);
+    LINFO << __FUNCTION__ << "(source=" << source << ",target="
+          << target << ",type=" << rec->fs_type << ")=" << ret;
     if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
         fs_mgr_set_blk_ro(source);
     }
@@ -481,8 +492,11 @@
              * 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);
+                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;
             }
 
@@ -503,9 +517,11 @@
                 *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);
+                    LERROR << __FUNCTION__ << "(): Mounted "
+                           << fstab->recs[i].blk_device << " on "
+                           << fstab->recs[i].mount_point << " with fs_type="
+                           << fstab->recs[i].fs_type << " instead of "
+                           << fstab->recs[start_idx].fs_type;
                 }
             } else {
                 /* back up errno for crypto decisions */
@@ -540,14 +556,14 @@
     label_len = strlen(label);
 
     if (label_len > 16) {
-        ERROR("FS label is longer than allowed by filesystem\n");
+        LERROR << "FS label is longer than allowed by filesystem";
         goto out;
     }
 
 
     blockdir = opendir("/dev/block");
     if (!blockdir) {
-        ERROR("couldn't open /dev/block\n");
+        LERROR << "couldn't open /dev/block";
         goto out;
     }
 
@@ -561,7 +577,7 @@
 
         fd = openat(dirfd(blockdir), ent->d_name, O_RDONLY);
         if (fd < 0) {
-            ERROR("Cannot open block device /dev/block/%s\n", ent->d_name);
+            LERROR << "Cannot open block device /dev/block/" << ent->d_name;
             goto out;
         }
 
@@ -576,7 +592,7 @@
 
         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);
+            LINFO << "/dev/block/" << ent->d_name << " not ext{234}";
             continue;
         }
 
@@ -584,11 +600,12 @@
             char *new_blk_device;
 
             if (asprintf(&new_blk_device, "/dev/block/%s", ent->d_name) < 0) {
-                ERROR("Could not allocate block device string\n");
+                LERROR << "Could not allocate block device string";
                 goto out;
             }
 
-            INFO("resolved label %s to %s\n", rec->blk_device, new_blk_device);
+            LINFO << "resolved label " << rec->blk_device << " to "
+                  << new_blk_device;
 
             free(rec->blk_device);
             rec->blk_device = new_blk_device;
@@ -631,13 +648,13 @@
         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));
+            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
-        INFO("%s is file encrypted\n", rec->mount_point);
+        // 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;
@@ -670,11 +687,17 @@
     int mret = -1;
     int mount_errno = 0;
     int attempted_idx = -1;
+    int avb_ret = FS_MGR_SETUP_AVB_FAIL;
 
     if (!fstab) {
         return -1;
     }
 
+    if (fs_mgr_is_avb_used() &&
+        (avb_ret = fs_mgr_load_vbmeta_images(fstab)) == FS_MGR_SETUP_AVB_FAIL) {
+        return -1;
+    }
+
     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)) ||
@@ -704,7 +727,7 @@
             !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");
+                LERROR << "Could not translate label to block device";
                 continue;
             }
         }
@@ -713,15 +736,31 @@
             wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
         }
 
-        if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) {
+        if (fs_mgr_is_avb_used() && (fstab->recs[i].fs_mgr_flags & MF_AVB)) {
+            /* If HASHTREE_DISABLED is set (cf. 'adb disable-verity'), we
+             * should set up the device without using dm-verity.
+             * The actual mounting still take place in the following
+             * mount_with_alternatives().
+             */
+            if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
+                LINFO << "AVB HASHTREE disabled";
+            } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
+                       FS_MGR_SETUP_AVB_SUCCESS) {
+                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) && device_is_secure()) {
             int rc = fs_mgr_setup_verity(&fstab->recs[i], true);
             if (__android_log_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
-                INFO("Verity disabled");
+                LINFO << "Verity disabled";
             } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
-                ERROR("Could not set up verified partition, skipping!\n");
+                LERROR << "Could not set up verified partition, skipping!";
                 continue;
             }
         }
+
         int last_idx_inspected;
         int top_idx = i;
 
@@ -741,7 +780,7 @@
             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");
+                    LERROR << "Only one encryptable/encrypted partition supported";
                 }
                 encryptable = status;
             }
@@ -759,19 +798,21 @@
              * 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);
+            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) {
-                    INFO("%s(): also wipe %s\n", __func__, fstab->recs[top_idx].key_loc);
+                    LINFO << __FUNCTION__ << "(): also wipe "
+                          << 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));
+                    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)) {
@@ -782,7 +823,8 @@
                 i = top_idx - 1;
                 continue;
             } else {
-                ERROR("%s(): Format failed. Suggest recovery...\n", __func__);
+                LERROR << __FUNCTION__ << "(): Format failed. "
+                       << "Suggest recovery...";
                 encryptable = FS_MGR_MNTALL_DEV_NEEDS_RECOVERY;
                 continue;
             }
@@ -790,18 +832,22 @@
         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);
+                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
                  */
-                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);
+                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;
@@ -810,21 +856,25 @@
             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));
+                PERROR << "Ignoring failure to mount an un-encryptable or wiped partition on"
+                       << fstab->recs[attempted_idx].blk_device << " at "
+                       << fstab->recs[attempted_idx].mount_point << " options: "
+                       << fstab->recs[attempted_idx].fs_options;
             } 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));
+                PERROR << "Failed to mount an un-encryptable or wiped partition on"
+                       << fstab->recs[attempted_idx].blk_device << " at "
+                       << fstab->recs[attempted_idx].mount_point << " options: "
+                       << fstab->recs[attempted_idx].fs_options;
                 ++error_count;
             }
             continue;
         }
     }
 
+    if (fs_mgr_is_avb_used()) {
+        fs_mgr_unload_vbmeta_images();
+    }
+
     if (error_count) {
         return -1;
     } else {
@@ -845,11 +895,17 @@
     int mount_errors = 0;
     int first_mount_errno = 0;
     char *m;
+    int avb_ret = FS_MGR_SETUP_AVB_FAIL;
 
     if (!fstab) {
         return ret;
     }
 
+    if (fs_mgr_is_avb_used() &&
+        (avb_ret = fs_mgr_load_vbmeta_images(fstab)) == FS_MGR_SETUP_AVB_FAIL) {
+        return ret;
+    }
+
     for (i = 0; i < fstab->num_entries; i++) {
         if (!fs_match(fstab->recs[i].mount_point, n_name)) {
             continue;
@@ -860,8 +916,8 @@
         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);
+            LERROR << "Cannot mount filesystem of type "
+                   << fstab->recs[i].fs_type << " on " << n_blk_device;
             goto out;
         }
 
@@ -882,12 +938,27 @@
             do_reserved_size(n_blk_device, fstab->recs[i].fs_type, &fstab->recs[i]);
         }
 
-        if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) {
+        if (fs_mgr_is_avb_used() && (fstab->recs[i].fs_mgr_flags & MF_AVB)) {
+            /* If HASHTREE_DISABLED is set (cf. 'adb disable-verity'), we
+             * should set up the device without using dm-verity.
+             * The actual mounting still take place in the following
+             * mount_with_alternatives().
+             */
+            if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
+                LINFO << "AVB HASHTREE disabled";
+            } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
+                       FS_MGR_SETUP_AVB_SUCCESS) {
+                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) && device_is_secure()) {
             int rc = fs_mgr_setup_verity(&fstab->recs[i], true);
             if (__android_log_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
-                INFO("Verity disabled");
+                LINFO << "Verity disabled";
             } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) {
-                ERROR("Could not set up verified partition, skipping!\n");
+                LERROR << "Could not set up verified partition, skipping!";
                 continue;
             }
         }
@@ -908,8 +979,8 @@
         }
     }
     if (mount_errors) {
-        ERROR("Cannot mount filesystem on %s at %s. error: %s\n",
-            n_blk_device, m, strerror(first_mount_errno));
+        PERROR << "Cannot mount filesystem on " << n_blk_device
+               << " at " << m;
         if (first_mount_errno == EBUSY) {
             ret = FS_MGR_DOMNT_BUSY;
         } else {
@@ -917,10 +988,14 @@
         }
     } 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);
+        LERROR << "Cannot find mount point " << fstab->recs[i].mount_point
+               << " in fstab";
     }
 
 out:
+    if (fs_mgr_is_avb_used()) {
+        fs_mgr_unload_vbmeta_images();
+    }
     return ret;
 }
 
@@ -935,7 +1010,7 @@
     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);
+        LERROR << "Cannot mount tmpfs filesystem at " << n_name;
         return -1;
     }
 
@@ -954,7 +1029,8 @@
 
     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);
+            LERROR << "Cannot unmount filesystem at "
+                   << fstab->recs[i].mount_point;
             ret = -1;
         }
         i++;
@@ -973,9 +1049,9 @@
     int err = 0;
     int ret = 0;
     int status;
-    char *mkswap_argv[2] = {
+    const char *mkswap_argv[2] = {
         MKSWAP_BIN,
-        NULL
+        nullptr
     };
 
     if (!fstab) {
@@ -1000,7 +1076,8 @@
             if (fstab->recs[i].max_comp_streams >= 0) {
                zram_mcs_fp = fopen(ZRAM_CONF_MCS, "r+");
               if (zram_mcs_fp == NULL) {
-                ERROR("Unable to open zram conf comp device %s\n", ZRAM_CONF_MCS);
+                LERROR << "Unable to open zram conf comp device "
+                       << ZRAM_CONF_MCS;
                 ret = -1;
                 continue;
               }
@@ -1010,7 +1087,7 @@
 
             zram_fp = fopen(ZRAM_CONF_DEV, "r+");
             if (zram_fp == NULL) {
-                ERROR("Unable to open zram conf device %s\n", ZRAM_CONF_DEV);
+                LERROR << "Unable to open zram conf device " << ZRAM_CONF_DEV;
                 ret = -1;
                 continue;
             }
@@ -1024,11 +1101,12 @@
 
         /* Initialize the swap area */
         mkswap_argv[1] = fstab->recs[i].blk_device;
-        err = android_fork_execvp_ext(ARRAY_SIZE(mkswap_argv), mkswap_argv,
+        err = android_fork_execvp_ext(ARRAY_SIZE(mkswap_argv),
+                                      const_cast<char **>(mkswap_argv),
                                       &status, true, LOG_KLOG, false, NULL,
                                       NULL, 0);
         if (err) {
-            ERROR("mkswap failed for %s\n", fstab->recs[i].blk_device);
+            LERROR << "mkswap failed for " << fstab->recs[i].blk_device;
             ret = -1;
             continue;
         }
@@ -1044,7 +1122,7 @@
         }
         err = swapon(fstab->recs[i].blk_device, flags);
         if (err) {
-            ERROR("swapon failed for %s\n", fstab->recs[i].blk_device);
+            LERROR << "swapon failed for " << fstab->recs[i].blk_device;
             ret = -1;
         }
     }
@@ -1101,7 +1179,7 @@
     if ((fstab_rec->fs_mgr_flags & MF_VERIFY) && device_is_secure()) {
         int rc = fs_mgr_setup_verity(fstab_rec, false);
         if (__android_log_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) {
-            INFO("Verity disabled");
+            LINFO << "Verity disabled";
             return FS_MGR_EARLY_SETUP_VERITY_NO_VERITY;
         } else if (rc == FS_MGR_SETUP_VERITY_SUCCESS) {
             return FS_MGR_EARLY_SETUP_VERITY_SUCCESS;
@@ -1109,7 +1187,7 @@
             return FS_MGR_EARLY_SETUP_VERITY_FAIL;
         }
     } else if (device_is_secure()) {
-        ERROR("Verity must be enabled for early mounted partitions on secured devices.\n");
+        LERROR << "Verity must be enabled for early mounted partitions on secured devices";
         return FS_MGR_EARLY_SETUP_VERITY_FAIL;
     }
     return FS_MGR_EARLY_SETUP_VERITY_NO_VERITY;
diff --git a/fs_mgr/fs_mgr_avb.cpp b/fs_mgr/fs_mgr_avb.cpp
new file mode 100644
index 0000000..70140d8
--- /dev/null
+++ b/fs_mgr/fs_mgr_avb.cpp
@@ -0,0 +1,642 @@
+/*
+ * 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 <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/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_avb_ops.h"
+#include "fs_mgr_priv.h"
+#include "fs_mgr_priv_avb.h"
+#include "fs_mgr_priv_dm_ioctl.h"
+#include "fs_mgr_priv_sha.h"
+
+/* 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
+
+AvbSlotVerifyData *fs_mgr_avb_verify_data = nullptr;
+AvbOps *fs_mgr_avb_ops = nullptr;
+
+enum HashAlgorithm {
+    kInvalid = 0,
+    kSHA256 = 1,
+    kSHA512 = 2,
+};
+
+struct androidboot_vbmeta {
+    HashAlgorithm hash_alg;
+    uint8_t digest[SHA512_DIGEST_LENGTH];
+    size_t vbmeta_size;
+    bool allow_verification_error;
+};
+
+androidboot_vbmeta fs_mgr_vbmeta_prop;
+
+static inline bool nibble_value(const char &c, uint8_t *value)
+{
+    FS_MGR_CHECK(value != nullptr);
+
+    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;
+}
+
+static bool load_vbmeta_prop(androidboot_vbmeta *vbmeta_prop)
+{
+    FS_MGR_CHECK(vbmeta_prop != nullptr);
+
+    std::string cmdline;
+    android::base::ReadFileToString("/proc/cmdline", &cmdline);
+
+    std::string hash_alg;
+    std::string digest;
+
+    for (const auto &entry :
+         android::base::Split(android::base::Trim(cmdline), " ")) {
+        std::vector<std::string> pieces = android::base::Split(entry, "=");
+        const std::string &key = pieces[0];
+        const std::string &value = pieces[1];
+
+        if (key == "androidboot.vbmeta.device_state") {
+            vbmeta_prop->allow_verification_error = (value == "unlocked");
+        } else if (key == "androidboot.vbmeta.hash_alg") {
+            hash_alg = value;
+        } else if (key == "androidboot.vbmeta.size") {
+            if (!android::base::ParseUint(value.c_str(),
+                                          &vbmeta_prop->vbmeta_size)) {
+                return false;
+            }
+        } 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;
+        vbmeta_prop->hash_alg = kSHA256;
+    } else if (hash_alg == "sha512") {
+        expected_digest_size = SHA512_DIGEST_LENGTH * 2;
+        vbmeta_prop->hash_alg = kSHA512;
+    } else {
+        LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
+        return false;
+    }
+
+    // Reads digest.
+    if (digest.size() != expected_digest_size) {
+        LERROR << "Unexpected digest size: " << digest.size() << " (expected: "
+               << expected_digest_size << ")";
+        return false;
+    }
+
+    if (!hex_to_bytes(vbmeta_prop->digest, sizeof(vbmeta_prop->digest),
+                      digest)) {
+        LERROR << "Hash digest contains non-hexidecimal character: "
+               << digest.c_str();
+        return false;
+    }
+
+    return true;
+}
+
+template <typename Hasher>
+static std::pair<size_t, bool> verify_vbmeta_digest(
+    const AvbSlotVerifyData &verify_data, const androidboot_vbmeta &vbmeta_prop)
+{
+    size_t total_size = 0;
+    Hasher hasher;
+    for (size_t n = 0; n < verify_data.num_vbmeta_images; n++) {
+        hasher.update(verify_data.vbmeta_images[n].vbmeta_data,
+                      verify_data.vbmeta_images[n].vbmeta_size);
+        total_size += verify_data.vbmeta_images[n].vbmeta_size;
+    }
+
+    bool matched = (memcmp(hasher.finalize(), vbmeta_prop.digest,
+                           Hasher::DIGEST_SIZE) == 0);
+
+    return std::make_pair(total_size, matched);
+}
+
+static bool verify_vbmeta_images(const AvbSlotVerifyData &verify_data,
+                                 const androidboot_vbmeta &vbmeta_prop)
+{
+    if (verify_data.num_vbmeta_images == 0) {
+        LERROR << "No vbmeta images";
+        return false;
+    }
+
+    size_t total_size = 0;
+    bool digest_matched = false;
+
+    if (vbmeta_prop.hash_alg == kSHA256) {
+        std::tie(total_size, digest_matched) =
+            verify_vbmeta_digest<SHA256Hasher>(verify_data, vbmeta_prop);
+    } else if (vbmeta_prop.hash_alg == kSHA512) {
+        std::tie(total_size, digest_matched) =
+            verify_vbmeta_digest<SHA512Hasher>(verify_data, vbmeta_prop);
+    }
+
+    if (total_size != vbmeta_prop.vbmeta_size) {
+        LERROR << "total vbmeta size mismatch: " << total_size
+               << " (expected: " << vbmeta_prop.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)
+{
+    // 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);
+
+    // TODO(bowgotsai): support verified all partition at boot.
+    // Updates fstab_rec->blk_device to verity device name.
+    free(fstab_entry->blk_device);
+    fstab_entry->blk_device = strdup(verity_blk_name.c_str());
+
+    // Makes sure we've set everything up properly.
+    if (fs_mgr_test_access(verity_blk_name.c_str()) < 0) {
+        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 either in /vbmeta or in
+        // the same partition for verity setup.
+        std::string vbmeta_partition_name(
+            verify_data.vbmeta_images[i].partition_name);
+        if (vbmeta_partition_name != "vbmeta" &&
+            vbmeta_partition_name != partition_name) {
+            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;
+}
+
+static inline bool polling_vbmeta_blk_device(struct fstab *fstab)
+{
+    // It needs the block device symlink: fstab_rec->blk_device to read
+    // /vbmeta partition. However, the symlink created by ueventd might
+    // not be ready at this point. Use test_access() to poll it before
+    // trying to read the partition.
+    struct fstab_rec *fstab_entry =
+        fs_mgr_get_entry_for_mount_point(fstab, "/vbmeta");
+
+    // Makes sure /vbmeta block device is ready to access.
+    if (fs_mgr_test_access(fstab_entry->blk_device) < 0) {
+        return false;
+    }
+    return true;
+}
+
+static bool init_is_avb_used()
+{
+    // When AVB is used, boot loader should set androidboot.vbmeta.{hash_alg,
+    // size, digest} in kernel cmdline. They will then be imported by init
+    // process to system properties: ro.boot.vbmeta.{hash_alg, size, digest}.
+    //
+    // Checks hash_alg as an indicator for whether AVB is used.
+    // We don't have to parse and check all of them here. The check will
+    // be done in fs_mgr_load_vbmeta_images() and FS_MGR_SETUP_AVB_FAIL will
+    // be returned when there is an error.
+
+    std::string hash_alg =
+        android::base::GetProperty("ro.boot.vbmeta.hash_alg", "");
+
+    if (hash_alg == "sha256" || hash_alg == "sha512") {
+        return true;
+    }
+
+    return false;
+}
+
+bool fs_mgr_is_avb_used()
+{
+    static bool result = init_is_avb_used();
+    return result;
+}
+
+int fs_mgr_load_vbmeta_images(struct fstab *fstab)
+{
+    FS_MGR_CHECK(fstab != nullptr);
+
+    if (!polling_vbmeta_blk_device(fstab)) {
+        LERROR << "Failed to find block device of /vbmeta";
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    // Gets the expected hash value of vbmeta images from
+    // kernel cmdline.
+    if (!load_vbmeta_prop(&fs_mgr_vbmeta_prop)) {
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    fs_mgr_avb_ops = fs_mgr_dummy_avb_ops_new(fstab);
+    if (fs_mgr_avb_ops == nullptr) {
+        LERROR << "Failed to allocate dummy avb_ops";
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    // Invokes avb_slot_verify() to load and verify all vbmeta images.
+    // Sets requested_partitions to nullptr as it's to copy the contents
+    // of HASH partitions into fs_mgr_avb_verify_data, which is not required as
+    // fs_mgr only deals with HASHTREE partitions.
+    const char *requested_partitions[] = {nullptr};
+    const char *ab_suffix =
+        android::base::GetProperty("ro.boot.slot_suffix", "").c_str();
+    AvbSlotVerifyResult verify_result = avb_slot_verify(
+        fs_mgr_avb_ops, requested_partitions, ab_suffix,
+        fs_mgr_vbmeta_prop.allow_verification_error, &fs_mgr_avb_verify_data);
+
+    // Only allow two verify results:
+    //   - AVB_SLOT_VERIFY_RESULT_OK.
+    //   - AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION (for UNLOCKED state).
+    if (verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION) {
+        if (!fs_mgr_vbmeta_prop.allow_verification_error) {
+            LERROR << "ERROR_VERIFICATION isn't allowed";
+            goto fail;
+        }
+    } else if (verify_result != AVB_SLOT_VERIFY_RESULT_OK) {
+        LERROR << "avb_slot_verify failed, result: " << verify_result;
+        goto fail;
+    }
+
+    // Verifies vbmeta images against the digest passed from bootloader.
+    if (!verify_vbmeta_images(*fs_mgr_avb_verify_data, fs_mgr_vbmeta_prop)) {
+        LERROR << "verify_vbmeta_images failed";
+        goto fail;
+    } else {
+        // Checks whether FLAGS_HASHTREE_DISABLED is set.
+        AvbVBMetaImageHeader vbmeta_header;
+        avb_vbmeta_image_header_to_host_byte_order(
+            (AvbVBMetaImageHeader *)fs_mgr_avb_verify_data->vbmeta_images[0]
+                .vbmeta_data,
+            &vbmeta_header);
+
+        bool hashtree_disabled = ((AvbVBMetaImageFlags)vbmeta_header.flags &
+                                  AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED);
+        if (hashtree_disabled) {
+            return FS_MGR_SETUP_AVB_HASHTREE_DISABLED;
+        }
+    }
+
+    if (verify_result == AVB_SLOT_VERIFY_RESULT_OK) {
+        return FS_MGR_SETUP_AVB_SUCCESS;
+    }
+
+fail:
+    fs_mgr_unload_vbmeta_images();
+    return FS_MGR_SETUP_AVB_FAIL;
+}
+
+void fs_mgr_unload_vbmeta_images()
+{
+    if (fs_mgr_avb_verify_data != nullptr) {
+        avb_slot_verify_data_free(fs_mgr_avb_verify_data);
+    }
+
+    if (fs_mgr_avb_ops != nullptr) {
+        fs_mgr_dummy_avb_ops_free(fs_mgr_avb_ops);
+    }
+}
+
+int fs_mgr_setup_avb(struct fstab_rec *fstab_entry)
+{
+    if (!fstab_entry || !fs_mgr_avb_verify_data ||
+        fs_mgr_avb_verify_data->num_vbmeta_images < 1) {
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    std::string partition_name(basename(fstab_entry->mount_point));
+    if (!avb_validate_utf8((const uint8_t *)partition_name.c_str(),
+                           partition_name.length())) {
+        LERROR << "Partition name: " << partition_name.c_str()
+               << " is not valid UTF-8.";
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    AvbHashtreeDescriptor hashtree_descriptor;
+    std::string salt;
+    std::string root_digest;
+    if (!get_hashtree_descriptor(partition_name, *fs_mgr_avb_verify_data,
+                                 &hashtree_descriptor, &salt, &root_digest)) {
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    // Converts HASHTREE descriptor to verity_table_params.
+    if (!hashtree_dm_verity_setup(fstab_entry, hashtree_descriptor, salt,
+                                  root_digest)) {
+        return FS_MGR_SETUP_AVB_FAIL;
+    }
+
+    return FS_MGR_SETUP_AVB_SUCCESS;
+}
diff --git a/fs_mgr/fs_mgr_avb_ops.cpp b/fs_mgr/fs_mgr_avb_ops.cpp
new file mode 100644
index 0000000..7683166
--- /dev/null
+++ b/fs_mgr/fs_mgr_avb_ops.cpp
@@ -0,0 +1,206 @@
+/*
+ * 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 <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_avb_ops.h"
+#include "fs_mgr_priv.h"
+
+static struct fstab *fs_mgr_fstab = nullptr;
+
+static AvbIOResult read_from_partition(AvbOps *ops ATTRIBUTE_UNUSED,
+                                       const char *partition,
+                                       int64_t offset,
+                                       size_t num_bytes,
+                                       void *buffer,
+                                       size_t *out_num_read)
+{
+    // The input |partition| name is with ab_suffix, e.g. system_a.
+    // Slot suffix (e.g. _a) will be appended to the device file path
+    // for partitions having 'slotselect' optin in fstab file, but it
+    // won't be appended to the mount point.
+    //
+    // In AVB, we can assume that there's an entry for the /misc mount
+    // point and use that to get the device file for the misc partition.
+    // From there we'll assume that a by-name scheme is used
+    // so we can just replace the trailing "misc" by the given
+    // |partition|, e.g.
+    //
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/system_a
+
+    struct fstab_rec *fstab_entry =
+        fs_mgr_get_entry_for_mount_point(fs_mgr_fstab, "/misc");
+
+    if (fstab_entry == nullptr) {
+        LERROR << "Partition (" << partition << ") not found in fstab";
+        return AVB_IO_RESULT_ERROR_IO;
+    }
+
+    std::string partition_name(partition);
+    std::string path(fstab_entry->blk_device);
+    // Replaces the last field of device file if it's not misc.
+    if (!android::base::StartsWith(partition_name, "misc")) {
+        size_t end_slash = path.find_last_of("/");
+        std::string by_name_prefix(path.substr(0, end_slash + 1));
+        path = by_name_prefix + partition_name;
+    }
+
+    android::base::unique_fd fd(
+        TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
+
+    if (fd < 0) {
+        PERROR << "Failed to open " << path.c_str();
+        return AVB_IO_RESULT_ERROR_IO;
+    }
+
+    // If offset is negative, interprets its absolute value as the
+    //  number of bytes from the end of the partition.
+    if (offset < 0) {
+        off64_t total_size = lseek64(fd, 0, SEEK_END);
+        if (total_size == -1) {
+            LERROR << "Failed to lseek64 to end of the partition";
+            return AVB_IO_RESULT_ERROR_IO;
+        }
+        offset = total_size + offset;
+        // Repositions the offset to the beginning.
+        if (lseek64(fd, 0, SEEK_SET) == -1) {
+            LERROR << "Failed to lseek64 to the beginning of the partition";
+            return AVB_IO_RESULT_ERROR_IO;
+        }
+    }
+
+    // On Linux, we never get partial reads from block devices (except
+    // for EOF).
+    ssize_t num_read =
+        TEMP_FAILURE_RETRY(pread64(fd, buffer, num_bytes, offset));
+
+    if (num_read < 0 || (size_t)num_read != num_bytes) {
+        PERROR << "Failed to read " << num_bytes << " bytes from "
+               << path.c_str() << " offset " << offset;
+        return AVB_IO_RESULT_ERROR_IO;
+    }
+
+    if (out_num_read != nullptr) {
+        *out_num_read = num_read;
+    }
+
+    return AVB_IO_RESULT_OK;
+}
+
+static AvbIOResult 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;
+}
+
+AvbOps *fs_mgr_dummy_avb_ops_new(struct fstab *fstab)
+{
+    AvbOps *ops;
+
+    // Assigns the fstab to the static variable for later use.
+    fs_mgr_fstab = fstab;
+
+    ops = (AvbOps *)calloc(1, sizeof(AvbOps));
+    if (ops == nullptr) {
+        LERROR << "Error allocating memory for AvbOps";
+        return nullptr;
+    }
+
+    // We only need these operations since that's all what is being used
+    // by the avb_slot_verify(); Most of them are dummy operations because
+    // they're only required in bootloader but not required in user-space.
+    ops->read_from_partition = read_from_partition;
+    ops->read_rollback_index = dummy_read_rollback_index;
+    ops->validate_vbmeta_public_key = dummy_validate_vbmeta_public_key;
+    ops->read_is_device_unlocked = dummy_read_is_device_unlocked;
+    ops->get_unique_guid_for_partition = dummy_get_unique_guid_for_partition;
+
+    return ops;
+}
+
+void fs_mgr_dummy_avb_ops_free(AvbOps *ops)
+{
+    free(ops);
+}
diff --git a/fs_mgr/fs_mgr_avb_ops.h b/fs_mgr/fs_mgr_avb_ops.h
new file mode 100644
index 0000000..9f99be8
--- /dev/null
+++ b/fs_mgr/fs_mgr_avb_ops.h
@@ -0,0 +1,59 @@
+/*
+ * 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_AVB_OPS_H
+#define __CORE_FS_MGR_AVB_OPS_H
+
+#include <libavb/libavb.h>
+
+#include "fs_mgr.h"
+
+__BEGIN_DECLS
+
+/* Allocates a "dummy" AvbOps instance solely for use in user-space.
+ * Returns nullptr on OOM.
+ *
+ * It mainly provides read_from_partitions() for user-space to get
+ * AvbSlotVerifyData.vbmeta_images[] and the caller MUST check their
+ * integrity against the androidboot.vbmeta.{hash_alg, size, digest}
+ * values from /proc/cmdline, e.g. verify_vbmeta_images()
+ * in fs_mgr_avb.cpp.
+ *
+ * Other I/O operations are only required in boot loader so we set
+ * them as dummy operations here.
+ *  - Will allow any public key for signing.
+ *  - returns 0 for any rollback index location.
+ *  - returns device is unlocked regardless of the actual state.
+ *  - returns a dummy guid for any partition.
+ *
+ * Frees with fs_mgr_dummy_avb_ops_free().
+ */
+AvbOps *fs_mgr_dummy_avb_ops_new(struct fstab *fstab);
+
+/* Frees an AvbOps instance previously allocated with fs_mgr_avb_ops_new(). */
+void fs_mgr_dummy_avb_ops_free(AvbOps *ops);
+
+__END_DECLS
+
+#endif /* __CORE_FS_MGR_AVB_OPS_H */
diff --git a/fs_mgr/fs_mgr_dm_ioctl.cpp b/fs_mgr/fs_mgr_dm_ioctl.cpp
index 75ce621..6012a39 100644
--- a/fs_mgr/fs_mgr_dm_ioctl.cpp
+++ b/fs_mgr/fs_mgr_dm_ioctl.cpp
@@ -45,7 +45,7 @@
 {
     fs_mgr_verity_ioctl_init(io, name, 1);
     if (ioctl(fd, DM_DEV_CREATE, io)) {
-        ERROR("Error creating device mapping (%s)", strerror(errno));
+        PERROR << "Error creating device mapping";
         return false;
     }
     return true;
@@ -57,7 +57,7 @@
 {
     fs_mgr_verity_ioctl_init(io, name, 0);
     if (ioctl(fd, DM_DEV_REMOVE, io)) {
-        ERROR("Error removing device mapping (%s)", strerror(errno));
+        PERROR << "Error removing device mapping";
         return false;
     }
     return true;
@@ -68,11 +68,11 @@
                                    int fd,
                                    std::string *out_dev_name)
 {
-    CHECK(out_dev_name != nullptr);
+    FS_MGR_CHECK(out_dev_name != nullptr);
 
     fs_mgr_verity_ioctl_init(io, name, 0);
     if (ioctl(fd, DM_DEV_STATUS, io)) {
-        ERROR("Error fetching verity device number (%s)", strerror(errno));
+        PERROR << "Error fetching verity device number";
         return false;
     }
 
@@ -88,7 +88,7 @@
 {
     fs_mgr_verity_ioctl_init(io, name, 0);
     if (ioctl(fd, DM_DEV_SUSPEND, io)) {
-        ERROR("Error activating verity device (%s)", strerror(errno));
+        PERROR << "Error activating verity device";
         return false;
     }
     return true;
diff --git a/fs_mgr/fs_mgr_format.c b/fs_mgr/fs_mgr_format.cpp
similarity index 83%
rename from fs_mgr/fs_mgr_format.c
rename to fs_mgr/fs_mgr_format.cpp
index 7c3b1ed..5705f93 100644
--- a/fs_mgr/fs_mgr_format.c
+++ b/fs_mgr/fs_mgr_format.cpp
@@ -34,8 +34,10 @@
 #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)
 {
@@ -43,12 +45,12 @@
     int fd, rc = 0;
 
     if ((fd = open(fs_blkdev, O_WRONLY)) < 0) {
-        ERROR("Cannot open block device.  %s\n", strerror(errno));
+        PERROR << "Cannot open block device";
         return -1;
     }
 
     if ((ioctl(fd, BLKGETSIZE64, &dev_sz)) == -1) {
-        ERROR("Cannot get block device size.  %s\n", strerror(errno));
+        PERROR << "Cannot get block device size";
         close(fd);
         return -1;
     }
@@ -56,7 +58,7 @@
     struct selabel_handle *sehandle = selinux_android_file_context_handle();
     if (!sehandle) {
         /* libselinux logs specific error */
-        ERROR("Cannot initialize android file_contexts");
+        LERROR << "Cannot initialize android file_contexts";
         close(fd);
         return -1;
     }
@@ -71,7 +73,7 @@
     /* 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) {
-        ERROR("make_ext4fs returned %d.\n", rc);
+        LERROR << "make_ext4fs returned " << rc;
     }
     close(fd);
 
@@ -104,19 +106,19 @@
     for(;;) {
         pid_t p = waitpid(pid, &rc, 0);
         if (p != pid) {
-            ERROR("Error waiting for child process - %d\n", p);
+            LERROR << "Error waiting for child process - " << p;
             rc = -1;
             break;
         }
         if (WIFEXITED(rc)) {
             rc = WEXITSTATUS(rc);
-            INFO("%s done, status %d\n", args[0], rc);
+            LINFO << args[0] << " done, status " << rc;
             if (rc) {
                 rc = -1;
             }
             break;
         }
-        ERROR("Still waiting for %s...\n", args[0]);
+        LERROR << "Still waiting for " << args[0] << "...";
     }
 
     return rc;
@@ -126,14 +128,15 @@
 {
     int rc = -EINVAL;
 
-    ERROR("%s: Format %s as '%s'.\n", __func__, fstab->blk_device, fstab->fs_type);
+    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 {
-        ERROR("File system type '%s' is not supported\n", fstab->fs_type);
+        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.cpp
similarity index 88%
rename from fs_mgr/fs_mgr_fstab.c
rename to fs_mgr/fs_mgr_fstab.cpp
index 41fb746..48ddf29 100644
--- a/fs_mgr/fs_mgr_fstab.c
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -35,6 +35,8 @@
     unsigned int zram_size;
     uint64_t reserved_size;
     unsigned int file_encryption_mode;
+    unsigned int erase_blk_size;
+    unsigned int logical_blk_size;
 };
 
 struct flag_list {
@@ -77,6 +79,7 @@
     { "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 },
@@ -85,6 +88,8 @@
     { "latemount",          MF_LATEMOUNT },
     { "reservedsize=",      MF_RESERVEDSIZE },
     { "quota",              MF_QUOTA },
+    { "eraseblk=",          MF_ERASEBLKSIZE },
+    { "logicalblk=",        MF_LOGICALBLKSIZE },
     { "defaults",           0 },
     { 0,                    0 },
 };
@@ -191,7 +196,7 @@
                         }
                     }
                     if (flag_vals->file_encryption_mode == 0) {
-                        ERROR("Unknown file encryption mode: %s\n", mode);
+                        LERROR << "Unknown file encryption mode: " << mode;
                     }
                 } else if ((fl[i].flag == MF_LENGTH) && flag_vals) {
                     /* The length flag is followed by an = and the
@@ -221,7 +226,7 @@
                             flag_vals->partnum = strtol(part_start, NULL, 0);
                         }
                     } else {
-                        ERROR("Warning: voldmanaged= flag malformed\n");
+                        LERROR << "Warning: voldmanaged= flag malformed";
                     }
                 } else if ((fl[i].flag == MF_SWAPPRIO) && flag_vals) {
                     flag_vals->swap_prio = strtoll(strchr(p, '=') + 1, NULL, 0);
@@ -239,6 +244,22 @@
                      * 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;
             }
@@ -255,7 +276,7 @@
                 /* fs_options was not passed in, so if the flag is unknown
                  * it's an error.
                  */
-                ERROR("Warning: unknown flag %s\n", p);
+                LERROR << "Warning: unknown flag " << p;
             }
         }
         p = strtok_r(NULL, ",", &savep);
@@ -300,14 +321,15 @@
     }
 
     if (!entries) {
-        ERROR("No entries found in fstab\n");
+        LERROR << "No entries found in fstab";
         goto err;
     }
 
     /* Allocate and init the fstab structure */
-    fstab = calloc(1, sizeof(struct fstab));
+    fstab = static_cast<struct fstab *>(calloc(1, sizeof(struct fstab)));
     fstab->num_entries = entries;
-    fstab->recs = calloc(fstab->num_entries, sizeof(struct fstab_rec));
+    fstab->recs = static_cast<struct fstab_rec *>(
+        calloc(fstab->num_entries, sizeof(struct fstab_rec)));
 
     fseek(fstab_file, 0, SEEK_SET);
 
@@ -332,30 +354,30 @@
          * between the two reads.
          */
         if (cnt >= entries) {
-            ERROR("Tried to process more entries than counted\n");
+            LERROR << "Tried to process more entries than counted";
             break;
         }
 
         if (!(p = strtok_r(line, delim, &save_ptr))) {
-            ERROR("Error parsing mount source\n");
+            LERROR << "Error parsing mount source";
             goto err;
         }
         fstab->recs[cnt].blk_device = strdup(p);
 
         if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing mount_point\n");
+            LERROR << "Error parsing mount_point";
             goto err;
         }
         fstab->recs[cnt].mount_point = strdup(p);
 
         if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing fs_type\n");
+            LERROR << "Error parsing fs_type";
             goto err;
         }
         fstab->recs[cnt].fs_type = strdup(p);
 
         if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing mount_flags\n");
+            LERROR << "Error parsing mount_flags";
             goto err;
         }
         tmp_fs_options[0] = '\0';
@@ -370,7 +392,7 @@
         }
 
         if (!(p = strtok_r(NULL, delim, &save_ptr))) {
-            ERROR("Error parsing fs_mgr_options\n");
+            LERROR << "Error parsing fs_mgr_options";
             goto err;
         }
         fstab->recs[cnt].fs_mgr_flags = parse_flags(p, fs_mgr_flags,
@@ -385,11 +407,13 @@
         fstab->recs[cnt].zram_size = flag_vals.zram_size;
         fstab->recs[cnt].reserved_size = flag_vals.reserved_size;
         fstab->recs[cnt].file_encryption_mode = flag_vals.file_encryption_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) != 0) {
-        ERROR("Error updating for slotselect\n");
+        LERROR << "Error updating for slotselect";
         goto err;
     }
     free(line);
@@ -409,7 +433,7 @@
 
     fstab_file = fopen(fstab_path, "r");
     if (!fstab_file) {
-        ERROR("Cannot open file %s\n", fstab_path);
+        LERROR << "Cannot open file " << fstab_path;
         return NULL;
     }
     fstab = fs_mgr_read_fstab_file(fstab_file);
diff --git a/fs_mgr/fs_mgr_main.c b/fs_mgr/fs_mgr_main.cpp
similarity index 88%
rename from fs_mgr/fs_mgr_main.c
rename to fs_mgr/fs_mgr_main.cpp
index 4bfe202..f3919d9 100644
--- a/fs_mgr/fs_mgr_main.c
+++ b/fs_mgr/fs_mgr_main.cpp
@@ -14,8 +14,6 @@
  * limitations under the License.
  */
 
-#define _GNU_SOURCE
-
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
@@ -25,11 +23,12 @@
 #warning "libgen.h must not be included"
 #endif
 
-char *me = "";
+char *me = nullptr;
 
 static void usage(void)
 {
-    ERROR("%s: usage: %s <-a | -n mnt_point blk_dev | -u> <fstab_file>\n", me, me);
+    LERROR << me << ": usage: " << me
+           << " <-a | -n mnt_point blk_dev | -u> <fstab_file>";
     exit(1);
 }
 
@@ -90,7 +89,9 @@
     const char *fstab_file=NULL;
     struct fstab *fstab=NULL;
 
-    klog_set_level(6);
+    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);
 
@@ -106,7 +107,7 @@
     } else if (u_flag) {
         return fs_mgr_unmount_all(fstab);
     } else {
-        ERROR("%s: Internal error, unknown option\n", me);
+        LERROR << me << ": Internal error, unknown option";
         exit(1);
     }
 
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
index 7f917d9..79c27c4 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -17,14 +17,30 @@
 #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>
 
-__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
+
+__BEGIN_DECLS
 
 #define CRYPTO_TMPFS_OPTIONS "size=256m,mode=0771,uid=1000,gid=1000"
 
@@ -89,6 +105,9 @@
 #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
 
diff --git a/fs_mgr/fs_mgr_priv_avb.h b/fs_mgr/fs_mgr_priv_avb.h
new file mode 100644
index 0000000..6d0171c
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_avb.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __CORE_FS_MGR_PRIV_AVB_H
+#define __CORE_FS_MGR_PRIV_AVB_H
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+#include "fs_mgr.h"
+
+__BEGIN_DECLS
+
+#define FS_MGR_SETUP_AVB_HASHTREE_DISABLED (-2)
+#define FS_MGR_SETUP_AVB_FAIL (-1)
+#define FS_MGR_SETUP_AVB_SUCCESS 0
+
+bool fs_mgr_is_avb_used();
+
+/* Gets AVB metadata through external/avb/libavb for all partitions:
+ * AvbSlotVerifyData.vbmeta_images[] and checks their integrity
+ * against the androidboot.vbmeta.{hash_alg, size, digest} values
+ * from /proc/cmdline.
+ *
+ * Return values:
+ *   - FS_MGR_SETUP_AVB_SUCCESS: the metadata cab be trusted.
+ *   - FS_MGR_SETUP_AVB_FAIL: any error when reading and verifying the
+ *     metadata, e.g. I/O error, digest value mismatch, size mismatch.
+ *   - FS_MGR_SETUP_AVB_HASHTREE_DISABLED: to support the existing
+ *     'adb disable-verity' feature in Android. It's very helpful for
+ *     developers to make the filesystem writable to allow replacing
+ *     binaries on the device.
+ */
+int fs_mgr_load_vbmeta_images(struct fstab *fstab);
+
+void fs_mgr_unload_vbmeta_images();
+
+int fs_mgr_setup_avb(struct fstab_rec *fstab_entry);
+
+__END_DECLS
+
+#endif /* __CORE_FS_MGR_PRIV_AVB_H */
diff --git a/fs_mgr/fs_mgr_priv_sha.h b/fs_mgr/fs_mgr_priv_sha.h
new file mode 100644
index 0000000..1abc273
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_sha.h
@@ -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.
+ */
+
+#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 void *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_slotselect.c b/fs_mgr/fs_mgr_slotselect.cpp
similarity index 90%
rename from fs_mgr/fs_mgr_slotselect.c
rename to fs_mgr/fs_mgr_slotselect.cpp
index 0f59115..94b43e4 100644
--- a/fs_mgr/fs_mgr_slotselect.c
+++ b/fs_mgr/fs_mgr_slotselect.cpp
@@ -48,9 +48,8 @@
         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));
+                PERROR << "Error opening misc partition '"
+                       << fstab->recs[n].blk_device << "'";
                 return -1;
             } else {
                 break;
@@ -59,7 +58,7 @@
     }
 
     if (misc_fd == -1) {
-        ERROR("Error finding misc partition\n");
+        LERROR << "Error finding misc partition";
         return -1;
     }
 
@@ -67,7 +66,7 @@
     // 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));
+        PERROR << "Error reading bootloader_message";
         close(misc_fd);
         return -1;
     }
@@ -98,11 +97,11 @@
     // 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);
+        LINFO << "Using slot suffix '" << out_suffix << "' from misc";
         return 0;
     }
 
-    ERROR("Error determining slot_suffix\n");
+    LERROR << "Error determining slot_suffix";
 
     return -1;
 }
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index e368a82..1ec4540 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -94,12 +94,12 @@
 
     FILE* f = fopen(path, "r");
     if (!f) {
-        ERROR("Can't open '%s'\n", path);
+        LERROR << "Can't open " << path;
         return NULL;
     }
 
     if (!fread(key_data, sizeof(key_data), 1, f)) {
-        ERROR("Could not read key!\n");
+        LERROR << "Could not read key!";
         fclose(f);
         return NULL;
     }
@@ -108,7 +108,7 @@
 
     RSA* key = NULL;
     if (!android_pubkey_decode(key_data, sizeof(key_data), &key)) {
-        ERROR("Could not parse key!\n");
+        LERROR << "Could not parse key!";
         return NULL;
     }
 
@@ -128,14 +128,14 @@
     // 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(NID_sha256, hash_buf, sizeof(hash_buf), signature,
                     signature_size, key)) {
-        ERROR("Couldn't verify table\n");
+        LERROR << "Couldn't verify table";
         goto out;
     }
 
@@ -227,7 +227,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;
     }
 
@@ -246,7 +246,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;
     }
 
@@ -277,20 +277,20 @@
     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;
     }
 
@@ -309,13 +309,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;
     }
 
@@ -326,14 +326,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;
     }
 
@@ -405,14 +403,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;
     }
 
@@ -421,13 +419,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;
@@ -452,14 +450,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;
         }
@@ -483,13 +480,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;
     }
 
@@ -512,13 +509,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;
     }
 
@@ -530,13 +527,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;
     }
 
@@ -558,15 +555,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;
@@ -590,15 +586,13 @@
 
     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;
     }
 
@@ -606,7 +600,7 @@
 
     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;
     }
 
@@ -618,14 +612,14 @@
     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;
     }
 
@@ -635,8 +629,8 @@
         /* 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;
         }
     }
@@ -654,7 +648,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;
     }
 
@@ -720,7 +714,7 @@
     fstab = fs_mgr_read_fstab(fstab_filename);
 
     if (!fstab) {
-        ERROR("Failed to read %s\n", fstab_filename);
+        LERROR << "Failed to read " << fstab_filename;
         goto out;
     }
 
@@ -776,7 +770,7 @@
     fd = TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC));
 
     if (fd == -1) {
-        ERROR("Error opening device mapper (%s)\n", strerror(errno));
+        PERROR << "Error opening device mapper";
         goto out;
     }
 
@@ -789,7 +783,7 @@
     fstab = fs_mgr_read_fstab(fstab_filename);
 
     if (!fstab) {
-        ERROR("Failed to read %s\n", fstab_filename);
+        LERROR << "Failed to read " << fstab_filename;
         goto out;
     }
 
@@ -810,8 +804,8 @@
             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.c_str(), strerror(errno));
+                PERROR << "Failed to query DM_TABLE_STATUS for "
+                       << mount_point.c_str();
                 continue;
             }
         }
@@ -881,22 +875,20 @@
 
     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 << "'";
         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
@@ -910,19 +902,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 (!fs_mgr_create_verity_device(io, mount_point, fd)) {
-        ERROR("Couldn't create verity device!\n");
+        LERROR << "Couldn't create verity device!";
         goto out;
     }
 
     // get the name of the device file
     if (!fs_mgr_get_verity_device_name(io, mount_point, fd, &verity_blk_name)) {
-        ERROR("Couldn't get verity device number!\n");
+        LERROR << "Couldn't get verity device number!";
         goto out;
     }
 
@@ -957,8 +949,8 @@
         }
     }
 
-    INFO("Enabling dm-verity for %s (mode %d)\n",
-         mount_point.c_str(), 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
@@ -973,7 +965,7 @@
 
     if (params.ecc.valid) {
         // kernel may not support error correction, try without
-        INFO("Disabling error correction for %s\n", mount_point.c_str());
+        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,
@@ -990,7 +982,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.c_str());
+        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,
@@ -999,7 +991,7 @@
         }
     }
 
-    ERROR("Failed to load verity table for %s\n", mount_point.c_str());
+    LERROR << "Failed to load verity table for " << mount_point.c_str();
     goto out;
 
 loaded:
@@ -1015,10 +1007,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);
+        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;
         }
     }
@@ -1028,7 +1021,7 @@
         free(fstab->blk_device);
         fstab->blk_device = strdup(verity_blk_name.c_str());
     } else if (!fs_mgr_destroy_verity_device(io, mount_point, fd)) {
-        ERROR("Failed to remove verity device %s\n", mount_point.c_str());
+        LERROR << "Failed to remove verity device " << mount_point.c_str();
         goto out;
     }
 
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index ef7fdd3..d959798 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -77,6 +77,8 @@
     unsigned int zram_size;
     uint64_t reserved_size;
     unsigned int file_encryption_mode;
+    unsigned int erase_blk_size;
+    unsigned int logical_blk_size;
 };
 
 // Callback function for verity status
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index 4d72a1a..86b6287 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -304,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");
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 369a022..4007203 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -348,6 +348,7 @@
 
 status_t BatteryMonitor::getProperty(int id, struct BatteryProperty *val) {
     status_t ret = BAD_VALUE;
+    std::string buf;
 
     val->valueInt64 = LONG_MIN;
 
@@ -400,6 +401,15 @@
         }
         break;
 
+    case BATTERY_PROP_BATTERY_STATUS:
+        if (mAlwaysPluggedDevice) {
+            val->valueInt64 = BATTERY_STATUS_CHARGING;
+        } else {
+            val->valueInt64 = getChargeStatus();
+        }
+        ret = NO_ERROR;
+        break;
+
     default:
         break;
     }
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index ec3de34..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>
 
@@ -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/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/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/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/log.h b/include/log/log.h
deleted file mode 100644
index ece9ea6..0000000
--- a/include/log/log.h
+++ /dev/null
@@ -1,871 +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.
- */
-
-#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/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
-
-/* --------------------------------------------------------------------- */
-
-/*
- * 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
-
-/*
- * 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
-    ;
-
-/*
- * 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
-
-/* --------------------------------------------------------------------- */
-
-/*
- * 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
-
-/* --------------------------------------------------------------------- */
-
-/*
- * 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
-
-#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
-
-/* --------------------------------------------------------------------- */
-
-/*
- * 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
-
-/* 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);
-    }
-    log_time(uint32_t sec, uint32_t nsec)
-    {
-        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__
-    log_time(clockid_t id)
-    {
-        timespec T;
-        clock_gettime(id, &T);
-        tv_sec = static_cast<uint32_t>(T.tv_sec);
-        tv_nsec = static_cast<uint32_t>(T.tv_nsec);
-    }
-#endif
-    log_time(const char* T)
-    {
-        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
-
-/*
- * 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)
-
-#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
-#define ANDROID_LOG_NONBLOCK O_NONBLOCK
-#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 __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__ */
-
-/*
- * 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);
-
-/* --------------------------------------------------------------------- */
-
-#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/include/log/logd.h b/include/log/logd.h
deleted file mode 100644
index 0e0248e..0000000
--- a/include/log/logd.h
+++ /dev/null
@@ -1 +0,0 @@
-#include <log/log.h>
diff --git a/include/log/logger.h b/include/log/logger.h
deleted file mode 100644
index 0e0248e..0000000
--- a/include/log/logger.h
+++ /dev/null
@@ -1 +0,0 @@
-#include <log/log.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/system/graphics-base.h b/include/system/graphics-base.h
index 150301a..2aac2d8 100644
--- a/include/system/graphics-base.h
+++ b/include/system/graphics-base.h
@@ -14,6 +14,7 @@
     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
@@ -99,6 +100,7 @@
     HAL_DATASPACE_BT2020_LINEAR = 138805248, // ((STANDARD_BT2020 | TRANSFER_LINEAR) | RANGE_FULL)
     HAL_DATASPACE_BT2020 = 147193856, // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_FULL)
     HAL_DATASPACE_DEPTH = 4096, // 0x1000
+    HAL_DATASPACE_SENSOR = 4097, // 0x1001
 } android_dataspace_t;
 
 typedef enum {
@@ -111,6 +113,7 @@
     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 {
diff --git a/include/system/graphics.h b/include/system/graphics.h
index 449b8c7..1a99187 100644
--- a/include/system/graphics.h
+++ b/include/system/graphics.h
@@ -237,6 +237,26 @@
 #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
diff --git a/include/system/window.h b/include/system/window.h
index 236de8d..26ea96a 100644
--- a/include/system/window.h
+++ b/include/system/window.h
@@ -355,6 +355,7 @@
     NATIVE_WINDOW_SET_AUTO_REFRESH          = 22,
     NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS   = 23,
     NATIVE_WINDOW_GET_FRAME_TIMESTAMPS      = 24,
+    NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION= 25,
 };
 
 /* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
@@ -1039,6 +1040,14 @@
             outDisplayRetireTime, outDequeueReadyTime, outReleaseTime);
 }
 
+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);
+}
+
 
 __END_DECLS
 
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/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/init/Android.mk b/init/Android.mk
index 35e6f4f..9e61fb2 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -70,7 +70,6 @@
     init.cpp \
     keychords.cpp \
     property_service.cpp \
-    seccomp.cpp \
     signal_handler.cpp \
     ueventd.cpp \
     ueventd_parser.cpp \
@@ -97,7 +96,6 @@
     libbase \
     libc \
     libselinux \
-    libseccomp_policy \
     liblog \
     libcrypto_utils \
     libcrypto \
@@ -107,6 +105,7 @@
     libz \
     libprocessgroup \
     libnl \
+    libavb
 
 # Create symlinks.
 LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
diff --git a/init/README.md b/init/README.md
index cef0dbc..c76a33b 100644
--- a/init/README.md
+++ b/init/README.md
@@ -298,7 +298,8 @@
 > 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.
+  finishes. _seclabel_ can be a - to denote default. Properties are expanded
+  within _argument_.
 
 `export <name> <value>`
 > Set the environment variable _name_ equal to _value_ in the
@@ -412,6 +413,11 @@
   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,
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 1186e9d..8ab5e30 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -265,10 +265,14 @@
     if (!svc) {
         return -1;
     }
-    if (!svc->Start()) {
+    if (!start_waiting_for_exec()) {
         return -1;
     }
-    waiting_for_exec = true;
+    if (!svc->Start()) {
+        stop_waiting_for_exec();
+        ServiceManager::GetInstance().RemoveService(*svc);
+        return -1;
+    }
     return 0;
 }
 
@@ -700,6 +704,9 @@
     } else if (strncmp(command, "reboot", 6) == 0) {
         cmd = ANDROID_RB_RESTART2;
         len = 6;
+    } else if (strncmp(command, "thermal-shutdown", 16) == 0) {
+        cmd = ANDROID_RB_THERMOFF;
+        len = 16;
     } else {
         LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
         return -EINVAL;
@@ -1003,6 +1010,29 @@
     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;
+}
+
 /*
  * Callback to make a directory from the ext4 code
  */
@@ -1074,6 +1104,7 @@
         {"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}},
     };
     return builtin_functions;
diff --git a/init/init.cpp b/init/init.cpp
index ddc707f..43f601f 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -62,7 +62,6 @@
 #include "keychords.h"
 #include "log.h"
 #include "property_service.h"
-#include "seccomp.h"
 #include "service.h"
 #include "signal_handler.h"
 #include "ueventd.h"
@@ -83,10 +82,14 @@
 
 const char *ENV[32];
 
-bool waiting_for_exec = false;
+static std::unique_ptr<Timer> waiting_for_exec(nullptr);
 
 static int epoll_fd = -1;
 
+static std::unique_ptr<Timer> waiting_for_prop(nullptr);
+static std::string wait_prop_name;
+static std::string wait_prop_value;
+
 void register_epoll_handler(int fd, void (*fn)()) {
     epoll_event ev;
     ev.events = EPOLLIN;
@@ -128,10 +131,52 @@
     return -1;
 }
 
+bool start_waiting_for_exec()
+{
+    if (waiting_for_exec) {
+        return false;
+    }
+    waiting_for_exec.reset(new Timer());
+    return true;
+}
+
+void stop_waiting_for_exec()
+{
+    if (waiting_for_exec) {
+        LOG(INFO) << "Wait for exec took " << *waiting_for_exec;
+        waiting_for_exec.reset();
+    }
+}
+
+bool start_waiting_for_property(const char *name, const char *value)
+{
+    if (waiting_for_prop) {
+        return false;
+    }
+    if (property_get(name) != value) {
+        // 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 char *name, const char *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()
@@ -178,7 +223,7 @@
         panic();
     }
 
-    property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ns()).c_str());
+    property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ms()).c_str());
     return 0;
 }
 
@@ -576,7 +621,7 @@
         }
 
         // 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_ns()).c_str(), 1);
+        setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ms()).c_str(), 1);
     } else {
         selinux_init_all_handles();
     }
@@ -757,8 +802,9 @@
 
         setenv("INIT_SECOND_STAGE", "true", 1);
 
-        uint64_t start_ns = start_time.time_since_epoch().count();
-        setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ns).c_str(), 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, nullptr };
@@ -792,12 +838,6 @@
 
         // Now set up SELinux for second stage.
         selinux_initialize(false);
-
-        // Install system-wide seccomp filter
-        if (!set_seccomp_filter()) {
-            LOG(ERROR) << "Failed to set seccomp policy";
-            security_failure();
-        }
     }
 
     // These directories were necessarily created before initial policy load
@@ -810,7 +850,8 @@
     restorecon("/dev/random");
     restorecon("/dev/urandom");
     restorecon("/dev/__properties__");
-    restorecon("/property_contexts");
+    restorecon("/plat_property_contexts");
+    restorecon("/nonplat_property_contexts");
     restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
     restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
     restorecon("/dev/device-mapper");
@@ -835,7 +876,12 @@
     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 = property_get("ro.boot.init_rc");
+    if (bootscript.empty()) {
+        parser.ParseConfig("/init.rc");
+    } else {
+        parser.ParseConfig(bootscript);
+    }
 
     ActionManager& am = ActionManager::GetInstance();
 
@@ -869,7 +915,7 @@
     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
 
     while (true) {
-        if (!waiting_for_exec) {
+        if (!(waiting_for_exec || waiting_for_prop)) {
             am.ExecuteOneCommand();
             restart_processes();
         }
diff --git a/init/init.h b/init/init.h
index cfb3139..3768c02 100644
--- a/init/init.h
+++ b/init/init.h
@@ -23,7 +23,6 @@
 class Service;
 
 extern const char *ENV[32];
-extern bool waiting_for_exec;
 extern std::string default_console;
 extern struct selabel_handle *sehandle;
 extern struct selabel_handle *sehandle_prop;
@@ -36,4 +35,10 @@
 
 int add_environment(const char* key, const char* val);
 
+bool start_waiting_for_exec();
+
+void stop_waiting_for_exec();
+
+bool start_waiting_for_property(const char *name, const char *value);
+
 #endif  /* _INIT_INIT_H */
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 72fcb5b..ce197ee 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -27,6 +27,7 @@
 #include <sys/poll.h>
 
 #include <memory>
+#include <vector>
 
 #include <cutils/misc.h>
 #include <cutils/sockets.h>
@@ -48,6 +49,7 @@
 
 #include <fs_mgr.h>
 #include <android-base/file.h>
+#include <android-base/strings.h>
 #include "bootimg.h"
 
 #include "property_service.h"
@@ -70,30 +72,30 @@
     }
 }
 
-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)
@@ -142,11 +144,9 @@
     }
 }
 
-bool is_legal_property_name(const std::string &name)
-{
+bool is_legal_property_name(const std::string& name) {
     size_t namelen = name.size();
 
-    if (namelen >= PROP_NAME_MAX) return false;
     if (namelen < 1) return false;
     if (name[0] == '.') return false;
     if (name[namelen - 1] == '.') return false;
@@ -169,60 +169,219 @@
     return true;
 }
 
-int property_set(const char* name, const char* value) {
-    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)) {
         LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: bad name";
-        return -1;
+        return PROP_ERROR_INVALID_NAME;
     }
+
     if (valuelen >= PROP_VALUE_MAX) {
         LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
                    << "value too long";
-        return -1;
+        return PROP_ERROR_INVALID_VALUE;
     }
 
-    if (strcmp("selinux.restorecon_recursive", name) == 0 && valuelen > 0) {
-        if (restorecon(value, SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
+    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 (!strncmp(name, "ro.", 3)) {
+        if (android::base::StartsWith(name, "ro.")) {
             LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
                        << "property already set";
-            return -1;
+            return PROP_ERROR_READ_ONLY_PROPERTY;
         }
 
-        __system_property_update(pi, value, valuelen);
+        __system_property_update(pi, value.c_str(), valuelen);
     } else {
-        int rc = __system_property_add(name, strlen(name), value, valuelen);
+        int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
         if (rc < 0) {
             LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
                        << "__system_property_add failed";
-            return rc;
+            return PROP_ERROR_SET_FAILED;
         }
     }
 
     // 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 && strncmp("persist.", name, strlen("persist.")) == 0) {
-        write_persistent_property(name, value);
+    if (persistent_properties_loaded && android::base::StartsWith(name, "persist.")) {
+        write_persistent_property(name.c_str(), value.c_str());
     }
-    property_changed(name, value);
-    return 0;
+    property_changed(name.c_str(), value.c_str());
+    return PROP_SUCCESS;
 }
 
-static void handle_property_set_fd()
-{
-    prop_msg msg;
-    int r;
-    char * source_ctx = NULL;
+class SocketConnection {
+ public:
+  SocketConnection(int socket, const struct ucred& cred)
+      : socket_(socket), cred_(cred) {}
 
-    int s = accept(property_set_fd, nullptr, nullptr);
+  ~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;
+    }
+
+    if (len == 0) {
+      *value = "";
+      return true;
+    }
+
+    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];
+    ufds[0].fd = socket_;
+    ufds[0].events = POLLIN;
+    ufds[0].revents = 0;
+    while (*timeout_ms > 0) {
+      Timer timer;
+      int nr = poll(ufds, 1, *timeout_ms);
+      uint64_t millis = timer.duration_ms();
+      *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
+
+      if (nr > 0) {
+        return true;
+      }
+
+      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;
     }
@@ -236,72 +395,50 @@
         return;
     }
 
-    static constexpr int timeout_ms = 2 * 1000;  /* Default 2 sec timeout for caller to send property. */
-    struct pollfd ufds[1];
-    ufds[0].fd = s;
-    ufds[0].events = POLLIN;
-    ufds[0].revents = 0;
-    int nr = TEMP_FAILURE_RETRY(poll(ufds, 1, timeout_ms));
-    if (nr == 0) {
-        LOG(ERROR) << "sys_prop: timeout waiting for uid " << cr.uid << " to send property message.";
-        close(s);
-        return;
-    } else if (nr < 0) {
-        PLOG(ERROR) << "sys_prop: error waiting for uid " << cr.uid << " to send property message";
-        close(s);
+    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;
     }
 
-    r = TEMP_FAILURE_RETRY(recv(s, &msg, sizeof(msg), MSG_DONTWAIT));
-    if(r != sizeof(prop_msg)) {
-        PLOG(ERROR) << "sys_prop: mis-match msg size received: " << r << " expected: " << sizeof(prop_msg);
-        close(s);
-        return;
-    }
+    switch(cmd) {
+    case PROP_MSG_SETPROP: {
+        char prop_name[PROP_NAME_MAX];
+        char prop_value[PROP_VALUE_MAX];
 
-    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)) {
-            LOG(ERROR) << "sys_prop: illegal property name \"" << msg.name << "\"";
-            close(s);
-            return;
+        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;
         }
 
-        getpeercon(s, &source_ctx);
+        prop_name[PROP_NAME_MAX-1] = 0;
+        prop_value[PROP_VALUE_MAX-1] = 0;
 
-        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 {
-                LOG(ERROR) << "sys_prop: Unable to " << (msg.name + 4)
-                           << " service ctl [" << msg.value << "]"
-                           << " uid:" << cr.uid
-                           << " gid:" << cr.gid
-                           << " pid:" << cr.pid;
-            }
-        } else {
-            if (check_mac_perms(msg.name, source_ctx, &cr)) {
-                property_set((char*) msg.name, (char*) msg.value);
-            } else {
-                LOG(ERROR) << "sys_prop: permission denied uid:" << cr.uid << " name:" << 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);
+        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);
+        socket.SendUint32(PROP_ERROR_INVALID_CMD);
         break;
     }
 }
@@ -438,16 +575,16 @@
 }
 
 void property_load_boot_defaults() {
-    load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT, NULL);
-    load_properties_from_file(PROP_PATH_ODM_DEFAULT, NULL);
-    load_properties_from_file(PROP_PATH_VENDOR_DEFAULT, NULL);
+    load_properties_from_file("/default.prop", NULL);
+    load_properties_from_file("/odm/default.prop", NULL);
+    load_properties_from_file("/vendor/default.prop", NULL);
 }
 
 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);
         }
     }
 }
@@ -502,14 +639,16 @@
 }
 
 void load_system_props() {
-    load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
-    load_properties_from_file(PROP_PATH_ODM_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) {
diff --git a/init/property_service.h b/init/property_service.h
index e3a2acb..5d59473 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -27,14 +27,14 @@
     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);
+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);
 std::string property_get(const char* name);
-extern int property_set(const char *name, const char *value);
-extern bool is_legal_property_name(const std::string &name);
+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/seccomp.cpp b/init/seccomp.cpp
deleted file mode 100644
index d9f2f79..0000000
--- a/init/seccomp.cpp
+++ /dev/null
@@ -1,213 +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 "seccomp.h"
-
-#include <vector>
-
-#include <sys/prctl.h>
-
-#include <linux/unistd.h>
-#include <linux/audit.h>
-#include <linux/filter.h>
-#include <linux/seccomp.h>
-
-#include "log.h"
-#include "seccomp_policy.h"
-
-#define syscall_nr (offsetof(struct seccomp_data, nr))
-#define arch_nr (offsetof(struct seccomp_data, arch))
-
-#if   defined __arm__
-#define AUDIT_ARCH_NR AUDIT_ARCH_ARM
-#elif defined __aarch64__
-#define AUDIT_ARCH_NR AUDIT_ARCH_AARCH64
-#define AUDIT_ARCH_NR32 AUDIT_ARCH_ARM
-#elif defined __i386__
-#define AUDIT_ARCH_NR AUDIT_ARCH_I386
-#elif defined __x86_64__
-#define AUDIT_ARCH_NR AUDIT_ARCH_X86_64
-#define AUDIT_ARCH_NR32 AUDIT_ARCH_I386
-#elif defined __mips64__
-#define AUDIT_ARCH_NR AUDIT_ARCH_MIPS64
-#define AUDIT_ARCH_NR32 AUDIT_ARCH_MIPS
-#elif defined __mips__ && !defined __mips64__
-#define AUDIT_ARCH_NR AUDIT_ARCH_MIPS
-#else
-#error "Could not determine AUDIT_ARCH_NR for this architecture"
-#endif
-
-typedef std::vector<sock_filter> filter;
-
-// We want to keep the below inline functions for debugging and future
-// development even though they are not used currently.
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wunused-function"
-
-static inline void Kill(filter& f) {
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL));
-}
-
-static inline void Trap(filter& f) {
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRAP));
-}
-
-static inline void Error(filter& f, __u16 retcode) {
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO + retcode));
-}
-
-inline static void Trace(filter& f) {
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE));
-}
-
-inline static void Allow(filter& f) {
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW));
-}
-
-inline static void AllowSyscall(filter& f, __u32 num) {
-    f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, num, 0, 1));
-    f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW));
-}
-
-inline static void ExamineSyscall(filter& f) {
-    f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_nr));
-}
-
-#ifdef AUDIT_ARCH_NR32
-inline static int SetValidateArchitectureJumpTarget(size_t offset, filter& f) {
-    auto jump_length = f.size() - offset - 1;
-    auto u8_jump_length = (__u8) jump_length;
-    if (u8_jump_length != jump_length) {
-        LOG(ERROR) << "Can't set jump greater than 255 - actual jump is " << jump_length;
-        return -1;
-    }
-    f[offset] = BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_NR32, u8_jump_length, 0);
-    return 0;
-}
-#endif
-
-inline static size_t ValidateArchitectureAndJumpIfNeeded(filter& f) {
-    f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, arch_nr));
-
-#ifdef AUDIT_ARCH_NR32
-    f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_NR, 2, 0));
-    f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_NR32, 1, 0));
-    Kill(f);
-    return f.size() - 2;
-#else
-    f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_NR, 1, 0));
-    Kill(f);
-    return 0;
-#endif
-}
-
-#pragma clang diagnostic pop
-
-static bool install_filter(filter const& f) {
-    struct sock_fprog prog = {
-        (unsigned short) f.size(),
-        (struct sock_filter*) &f[0],
-    };
-
-    if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0) {
-        PLOG(ERROR) << "SECCOMP: Could not set seccomp filter";
-        return false;
-    }
-
-    LOG(INFO) << "SECCOMP: Global filter installed";
-    return true;
-}
-
-bool set_seccomp_filter() {
-    filter f;
-
-    // Note that for mixed 64/32 bit architectures, ValidateArchitecture inserts a
-    // jump that must be changed to point to the start of the 32-bit policy
-    // 32 bit syscalls will not hit the policy between here and the call to SetJump
-#ifdef AUDIT_ARCH_NR32
-    auto offset_to_32bit_filter =
-#endif
-        ValidateArchitectureAndJumpIfNeeded(f);
-
-    // Native filter
-    ExamineSyscall(f);
-
-#ifdef __aarch64__
-    // Syscalls needed to boot Android
-    AllowSyscall(f, __NR_pivot_root);
-    AllowSyscall(f, __NR_ioprio_get);
-    AllowSyscall(f, __NR_ioprio_set);
-    AllowSyscall(f, __NR_gettid);
-    AllowSyscall(f, __NR_futex);
-    AllowSyscall(f, __NR_clone);
-    AllowSyscall(f, __NR_rt_sigreturn);
-    AllowSyscall(f, __NR_rt_tgsigqueueinfo);
-    AllowSyscall(f, __NR_add_key);
-    AllowSyscall(f, __NR_request_key);
-    AllowSyscall(f, __NR_keyctl);
-    AllowSyscall(f, __NR_restart_syscall);
-    AllowSyscall(f, __NR_getrandom);
-
-    // Needed for performance tools
-    AllowSyscall(f, __NR_perf_event_open);
-
-    // Needed for treble
-    AllowSyscall(f, __NR_finit_module);
-
-    // Needed for trusty
-    AllowSyscall(f, __NR_syncfs);
-
-     // arm64-only filter - autogenerated from bionic syscall usage
-    for (size_t i = 0; i < arm64_filter_size; ++i)
-        f.push_back(arm64_filter[i]);
-#else
-    // Generic policy
-    Allow(f);
-#endif
-
-#ifdef AUDIT_ARCH_NR32
-    if (SetValidateArchitectureJumpTarget(offset_to_32bit_filter, f) != 0)
-        return -1;
-
-    // 32-bit filter for 64-bit platforms
-    ExamineSyscall(f);
-
-#ifdef __aarch64__
-    // Syscalls needed to boot android
-    AllowSyscall(f, 120); // __NR_clone
-    AllowSyscall(f, 240); // __NR_futex
-    AllowSyscall(f, 119); // __NR_sigreturn
-    AllowSyscall(f, 173); // __NR_rt_sigreturn
-    AllowSyscall(f, 363); // __NR_rt_tgsigqueueinfo
-    AllowSyscall(f, 224); // __NR_gettid
-
-    // Syscalls needed to run Chrome
-    AllowSyscall(f, 383); // __NR_seccomp - needed to start Chrome
-    AllowSyscall(f, 384); // __NR_getrandom - needed to start Chrome
-
-    // Syscalls needed to run GFXBenchmark
-    AllowSyscall(f, 190); // __NR_vfork
-
-    // arm32-on-arm64 only filter - autogenerated from bionic syscall usage
-    for (size_t i = 0; i < arm_filter_size; ++i)
-        f.push_back(arm_filter[i]);
-#else
-    // Generic policy
-    Allow(f);
-#endif
-#endif
-    return install_filter(f);
-}
diff --git a/init/service.cpp b/init/service.cpp
index 0f7f62f..e186f27 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -997,7 +997,7 @@
     }
 
     if (svc->Reap()) {
-        waiting_for_exec = false;
+        stop_waiting_for_exec();
         RemoveService(*svc);
     }
 
diff --git a/init/util.h b/init/util.h
index 009413d..5c38dc3 100644
--- a/init/util.h
+++ b/init/util.h
@@ -55,8 +55,8 @@
     return std::chrono::duration_cast<double_duration>(boot_clock::now() - start_).count();
   }
 
-  int64_t duration_ns() const {
-    return (boot_clock::now() - start_).count();
+  int64_t duration_ms() const {
+    return std::chrono::duration_cast<std::chrono::milliseconds>(boot_clock::now() - start_).count();
   }
 
  private:
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index b96e3ae..8ba7452 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -30,6 +30,23 @@
     "str_parms.c",
 ]
 
+cc_library_headers {
+    name: "libcutils_vndk_headers",
+    host_supported: true,
+    export_include_dirs: ["include_vndk"],
+}
+
+cc_library_headers {
+    name: "libcutils_headers",
+    host_supported: true,
+    export_include_dirs: ["include"],
+    target: {
+       windows: {
+          enabled: true,
+       },
+    },
+}
+
 cc_library {
     name: "libcutils",
     host_supported: true,
@@ -51,6 +68,7 @@
         "threads.c",
     ],
 
+
     target: {
         host: {
             srcs: ["dlmalloc_stubs.c"],
@@ -80,11 +98,14 @@
                 "ashmem-dev.c",
                 "klog.cpp",
                 "partition_utils.c",
-                "properties.c",
+                "properties.cpp",
                 "qtaguid.c",
                 "trace-dev.c",
                 "uevent.c",
             ],
+            sanitize: {
+                misc_undefined: ["integer"],
+            },
         },
 
         android_arm: {
@@ -117,6 +138,9 @@
     },
 
     shared_libs: ["liblog"],
+    header_libs: ["libcutils_headers"],
+    export_header_lib_headers: ["libcutils_headers"],
+
     product_variables: {
         cpusets: {
             cflags: ["-DUSE_CPUSETS"],
@@ -132,9 +156,6 @@
     ],
 
     clang: true,
-    sanitize: {
-        misc_undefined: ["integer"],
-    },
 }
 
 subdirs = ["tests"]
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index 159a9d4..06026d1 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -189,11 +189,56 @@
     free_entries(&ro_entries);
 }
 
+static void save_reboot_reason(int cmd, const char *arg)
+{
+    FILE *fp;
+    const char *reason = NULL;
+
+    fp = fopen(LAST_REBOOT_REASON_FILE, "w");
+    if (fp == NULL) {
+        KLOG_WARNING(TAG, "Error creating " LAST_REBOOT_REASON_FILE
+                     ": %s\n", strerror(errno));
+        return;
+    }
+    switch (cmd) {
+        case ANDROID_RB_RESTART:
+            reason = "restart";
+            break;
+
+        case ANDROID_RB_POWEROFF:
+            reason = "power-off";
+            break;
+
+        case ANDROID_RB_RESTART2:
+            reason = arg && strlen(arg) ? arg : "restart";
+            break;
+
+        case ANDROID_RB_THERMOFF:
+            reason = "thermal-shutdown";
+            break;
+
+        default:
+            fprintf(fp,"0x%08X\n", cmd);
+            break;
+    }
+
+    if (reason) {
+        if (fprintf(fp, "%s\n", reason) < 0) {
+             KLOG_WARNING(TAG, "Error writing " LAST_REBOOT_REASON_FILE
+                          ": %s\n", strerror(errno));
+        }
+    }
+
+    fclose(fp);
+}
+
 int android_reboot_with_callback(
     int cmd, int flags __unused, const char *arg,
     void (*cb_on_remount)(const struct mntent*))
 {
     int ret;
+
+    save_reboot_reason(cmd, arg);
     remount_ro(cb_on_remount);
     switch (cmd) {
         case ANDROID_RB_RESTART:
@@ -209,6 +254,10 @@
                            LINUX_REBOOT_CMD_RESTART2, arg);
             break;
 
+        case ANDROID_RB_THERMOFF:
+            ret = reboot(RB_POWER_OFF);
+            break;
+
         default:
             ret = -1;
     }
diff --git a/libcutils/fs.c b/libcutils/fs.c
index 488fdfc..b253b1c 100644
--- a/libcutils/fs.c
+++ b/libcutils/fs.c
@@ -80,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/include/cutils/android_get_control_file.h b/libcutils/include/cutils/android_get_control_file.h
similarity index 100%
rename from include/cutils/android_get_control_file.h
rename to libcutils/include/cutils/android_get_control_file.h
diff --git a/include/cutils/android_reboot.h b/libcutils/include/cutils/android_reboot.h
similarity index 87%
rename from include/cutils/android_reboot.h
rename to libcutils/include/cutils/android_reboot.h
index a3861a0..2e3b429 100644
--- a/include/cutils/android_reboot.h
+++ b/libcutils/include/cutils/android_reboot.h
@@ -25,10 +25,14 @@
 #define ANDROID_RB_RESTART  0xDEAD0001
 #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"
+
 int android_reboot(int cmd, int flags, const char *arg);
 int android_reboot_with_callback(
     int cmd, int flags, const char *arg,
diff --git a/include/cutils/ashmem.h b/libcutils/include/cutils/ashmem.h
similarity index 100%
rename from include/cutils/ashmem.h
rename to libcutils/include/cutils/ashmem.h
diff --git a/include/cutils/atomic.h b/libcutils/include/cutils/atomic.h
similarity index 100%
rename from include/cutils/atomic.h
rename to libcutils/include/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/include/cutils/klog.h b/libcutils/include/cutils/klog.h
similarity index 97%
rename from include/cutils/klog.h
rename to libcutils/include/cutils/klog.h
index e7cd300..5ae6216 100644
--- a/include/cutils/klog.h
+++ b/libcutils/include/cutils/klog.h
@@ -23,7 +23,6 @@
 
 __BEGIN_DECLS
 
-int  klog_get_level(void);
 void klog_set_level(int level);
 
 void klog_write(int level, const char *fmt, ...)
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/include/cutils/multiuser.h b/libcutils/include/cutils/multiuser.h
similarity index 100%
rename from include/cutils/multiuser.h
rename to libcutils/include/cutils/multiuser.h
diff --git a/include/cutils/native_handle.h b/libcutils/include/cutils/native_handle.h
similarity index 100%
rename from include/cutils/native_handle.h
rename to libcutils/include/cutils/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/include/cutils/properties.h b/libcutils/include/cutils/properties.h
similarity index 100%
rename from include/cutils/properties.h
rename to libcutils/include/cutils/properties.h
diff --git a/include/cutils/qtaguid.h b/libcutils/include/cutils/qtaguid.h
similarity index 100%
rename from include/cutils/qtaguid.h
rename to libcutils/include/cutils/qtaguid.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/include/cutils/sched_policy.h b/libcutils/include/cutils/sched_policy.h
similarity index 100%
rename from include/cutils/sched_policy.h
rename to libcutils/include/cutils/sched_policy.h
diff --git a/include/cutils/sockets.h b/libcutils/include/cutils/sockets.h
similarity index 100%
rename from include/cutils/sockets.h
rename to libcutils/include/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/include/cutils/trace.h b/libcutils/include/cutils/trace.h
similarity index 100%
rename from include/cutils/trace.h
rename to libcutils/include/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_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/init/seccomp.h b/libcutils/include_vndk/cutils/log.h
similarity index 64%
copy from init/seccomp.h
copy to libcutils/include_vndk/cutils/log.h
index cda7a89..ae74024 100644
--- a/init/seccomp.h
+++ b/libcutils/include_vndk/cutils/log.h
@@ -1,5 +1,6 @@
+/*Special log.h file for VNDK linking modules*/
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * 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.
@@ -12,11 +13,9 @@
  * WITHOUT 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 SECCOMP_H
-#define SECCOMP_H
-
-bool set_seccomp_filter();
-
-#endif
+*/
+#ifndef _LIBS_CUTIL_LOG_H
+#define _LIBS_CUTIL_LOG_H
+#warning "Deprecated: don't include cutils/log.h, use either android/log.h or log/log.h"
+#include <log/log.h>
+#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/klog.cpp b/libcutils/klog.cpp
index 15adf6b..d301276 100644
--- a/libcutils/klog.cpp
+++ b/libcutils/klog.cpp
@@ -29,10 +29,6 @@
 
 static int klog_level = KLOG_INFO_LEVEL;
 
-int klog_get_level(void) {
-    return klog_level;
-}
-
 void klog_set_level(int level) {
     klog_level = level;
 }
diff --git a/libcutils/properties.c b/libcutils/properties.cpp
similarity index 85%
rename from libcutils/properties.c
rename to libcutils/properties.cpp
index bdbddd0..43ad574 100644
--- a/libcutils/properties.c
+++ b/libcutils/properties.cpp
@@ -112,9 +112,7 @@
 }
 
 int property_get(const char *key, char *value, const char *default_value) {
-    int len;
-
-    len = __system_property_get(key, value);
+    int len = __system_property_get(key, value);
     if (len > 0) {
         return len;
     }
@@ -126,21 +124,21 @@
     return len;
 }
 
-struct property_list_callback_data {
-    void (*propfn)(const char *key, const char *value, void *cookie);
-    void *cookie;
+struct callback_data {
+    void (*callback)(const char* name, 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);
+static void trampoline(void* raw_data, const char* name, const char* value) {
+    callback_data* data = reinterpret_cast<callback_data*>(raw_data);
+    data->callback(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};
+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/liblog/Android.bp b/liblog/Android.bp
index bbe7d79..310dbf4 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -15,13 +15,17 @@
 //
 
 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",
-    "logger_lock.c",
     "log_ratelimit.cpp",
+    "logger_lock.c",
+    "logger_name.c",
+    "logger_read.c",
+    "logger_write.c",
+    "logprint.c",
 ]
 liblog_host_sources = [
     "fake_log_device.c",
@@ -29,15 +33,12 @@
 ]
 liblog_target_sources = [
     "event_tag_map.cpp",
-    "config_read.c",
     "log_time.cpp",
     "properties.c",
-    "logprint.c",
     "pmsg_reader.c",
     "pmsg_writer.c",
     "logd_reader.c",
     "logd_writer.c",
-    "logger_read.c",
 ]
 
 // Shared and static library for host and device
@@ -57,7 +58,7 @@
             srcs: liblog_target_sources,
             // AddressSanitizer runtime library depends on liblog.
             sanitize: {
-                never: true,
+                address: false,
             },
         },
         android_arm: {
@@ -79,6 +80,8 @@
         },
     },
 
+    export_include_dirs: ["include"],
+
     cflags: [
         "-Werror",
         "-fvisibility=hidden",
@@ -95,22 +98,19 @@
     compile_multilib: "both",
 }
 
-// system/core/android/log.h needs some work before it can be included in the
-// NDK. It defines a *lot* of macros that previously were usable names in NDK
-// sources that used android/log.h. As an example, the following file defines
-// LOG_TAG as a variable, but the variable name gets macro replaced if we use
-// the current android/log.h.
-// https://android.googlesource.com/platform/external/deqp/+/4adc1515f867b26c19c2f7498e9de93a230a234d/framework/platform/android/tcuTestLogParserJNI.cpp#41
-//
-// For now, we keep a copy of the old NDK android/log.h in legacy-ndk-includes.
 ndk_headers {
     name: "liblog_headers",
-    from: "legacy-ndk-includes",
+    from: "include/android",
     to: "android",
-    srcs: ["legacy-ndk-includes/log.h"],
+    srcs: ["include/android/log.h"],
     license: "NOTICE",
 }
 
+cc_library_headers {
+    name: "liblog_vndk_headers",
+    export_include_dirs: ["include_vndk"],
+}
+
 ndk_library {
     name: "liblog.ndk",
     symbol_file: "liblog.map.txt",
diff --git a/liblog/README b/liblog/README
index 610338c..40a39ad 100644
--- a/liblog/README
+++ b/liblog/README
@@ -108,6 +108,11 @@
 
        int android_log_destroy(android_log_context *ctx)
 
+       #include <log/log_frontend.h>
+
+       int android_set_log_frontend(int frontend_flag)
+       int android_get_log_frontend()
+
        Link with -llog
 
 DESCRIPTION
@@ -162,6 +167,13 @@
        when  opening  the  sub-log.    It  is  recommended  to  open  the  log
        ANDROID_LOG_RDONLY in these cases.
 
+       android_set_log_frontend() selects frontend 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_frontend()   and
+       android_get_log_frontend()  return  the  current  frontend mask,   or a
+       negative errno for any problems.
+
 ERRORS
        If messages fail, a negative error code will be returned to the caller.
 
@@ -194,4 +206,4 @@
 
 
 
-                                  17 Oct 2016                        LIBLOG(3)
+                                  08 Feb 2017                        LIBLOG(3)
diff --git a/liblog/config_read.c b/liblog/config_read.c
index 1f54152..b9a281b 100644
--- a/liblog/config_read.c
+++ b/liblog/config_read.c
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <log/log_frontend.h>
+
 #include "config_read.h"
 #include "logger.h"
 
@@ -52,11 +54,35 @@
 }
 
 LIBLOG_HIDDEN void __android_log_config_read() {
-#if (FAKE_LOG_DEVICE == 0)
-    extern struct android_log_transport_read logdLoggerRead;
-    extern struct android_log_transport_read pmsgLoggerRead;
+    if (__android_log_frontend & LOGGER_LOCAL) {
+        extern struct android_log_transport_read localLoggerRead;
 
-    __android_log_add_transport(&__android_log_transport_read, &logdLoggerRead);
-    __android_log_add_transport(&__android_log_persist_read, &pmsgLoggerRead);
+        __android_log_add_transport(&__android_log_transport_read,
+                                    &localLoggerRead);
+    }
+
+#if (FAKE_LOG_DEVICE == 0)
+    if ((__android_log_frontend == LOGGER_DEFAULT) ||
+        (__android_log_frontend & 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 49a3b75..892e80d 100644
--- a/liblog/config_read.h
+++ b/liblog/config_read.h
@@ -28,22 +28,31 @@
 
 #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)); \
+                                 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))    \
+                                 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),    \
+                                 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((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..583dcff 100644
--- a/liblog/config_write.c
+++ b/liblog/config_write.c
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <log/log_frontend.h>
+
 #include "config_write.h"
 #include "logger.h"
 
@@ -52,15 +54,42 @@
 }
 
 LIBLOG_HIDDEN void __android_log_config_write() {
+    if (__android_log_frontend & LOGGER_LOCAL) {
+        extern struct android_log_transport_write localLoggerWrite;
+
+        __android_log_add_transport(&__android_log_transport_write,
+                                    &localLoggerWrite);
+    }
+
+    if ((__android_log_frontend == LOGGER_DEFAULT) ||
+        (__android_log_frontend & LOGGER_LOGD)) {
 #if (FAKE_LOG_DEVICE == 0)
-    extern struct android_log_transport_write logdLoggerWrite;
-    extern struct android_log_transport_write pmsgLoggerWrite;
+        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_persist_write, &pmsgLoggerWrite);
+        __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;
+        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
+    }
+}
+
+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 3b01a9a..8825411 100644
--- a/liblog/config_write.h
+++ b/liblog/config_write.h
@@ -29,21 +29,30 @@
 #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((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))  \
+                                 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), \
+         ((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_tag_map.cpp b/liblog/event_tag_map.cpp
index 1155422..1f08eb4 100644
--- a/liblog/event_tag_map.cpp
+++ b/liblog/event_tag_map.cpp
@@ -19,6 +19,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -26,22 +27,69 @@
 
 #include <experimental/string_view>
 #include <functional>
+#include <string>
 #include <unordered_map>
 
 #include <log/event_tag_map.h>
+#include <utils/FastStrcmp.h>
+#include <utils/RWLock.h>
+#include <private/android_logger.h>
 
 #include "log_portability.h"
+#include "logd_reader.h"
 
 #define OUT_TAG "EventTagMap"
 
-typedef std::experimental::string_view MapString;
+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 _LIBCPP_TYPE_VIS_ONLY std::hash<TagFmt>
+template <> struct std::hash<TagFmt>
         : public std::unary_function<const TagFmt&, size_t> {
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(const TagFmt& __t) const _NOEXCEPT {
+    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.:
@@ -54,57 +102,125 @@
 
 // Map
 struct EventTagMap {
+#   define NUM_MAPS 2
     // memory-mapped source file; we get strings from here
-    void*  mapAddr;
-    size_t mapLen;
+    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() : mapAddr(NULL), mapLen(0) { }
+    EventTagMap() {
+        memset(mapAddr, 0, sizeof(mapAddr));
+        memset(mapLen, 0, sizeof(mapLen));
+    }
 
     ~EventTagMap() {
         Idx2TagFmt.clear();
-        if (mapAddr) {
-            munmap(mapAddr, mapLen);
-            mapAddr = 0;
+        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) {
-    std::unordered_map<uint32_t, TagFmt>::const_iterator it;
-    it = Idx2TagFmt.find(tag);
-    if (it != Idx2TagFmt.end()) {
-        if (verbose) {
-            fprintf(stderr,
-                    OUT_TAG ": duplicate tag entries %" PRIu32
-                        ":%.*s:%.*s and %" PRIu32 ":%.*s:%.*s)\n",
-                    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());
+    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));
         }
-        return false;
     }
 
-    Idx2TagFmt.emplace(std::make_pair(tag, tagfmt));
-    return true;
+    {
+        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
@@ -158,6 +274,19 @@
         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);
@@ -165,24 +294,33 @@
     *pData = cp;
 
     if (map->emplaceUnique(tagIndex, TagFmt(std::make_pair(
-            MapString(tag, tagLen), MapString(fmt, fmtLen))), true)) {
+            MapString(tag, tagLen), MapString(fmt, fmtLen))), verbose)) {
         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) {
-    char* cp = static_cast<char*>(map->mapAddr);
-    size_t len = map->mapLen;
+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 missing EOL on last line\n");
+        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;
     }
@@ -200,7 +338,9 @@
             } else if (isdigit(*cp)) {
                 // looks like a tag; scan it out
                 if (scanTagLine(map, &cp, lineNum) != 0) {
-                    return -1;
+                    if (!which || (errno != EMLINK)) {
+                        return -1;
+                    }
                 }
                 lineNum++;      // we eat the '\n'
                 // leave lineStart==true
@@ -227,57 +367,87 @@
 // 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) {
-    int save_errno;
+    EventTagMap* newTagMap;
+    off_t end[NUM_MAPS];
+    int save_errno, fd[NUM_MAPS];
+    size_t which;
 
-    const char* tagfile = fileName ? fileName : EVENT_TAG_MAP_FILE;
-    int fd = open(tagfile, O_RDONLY | O_CLOEXEC);
-    if (fd < 0) {
+    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;
-        fprintf(stderr, OUT_TAG ": unable to open map '%s': %s\n",
-                tagfile, strerror(save_errno));
-        errno = save_errno;
-        return NULL;
-    }
-    off_t end = lseek(fd, 0L, SEEK_END);
-    save_errno = errno;
-    (void)lseek(fd, 0L, SEEK_SET);
-    if (end < 0) {
-        fprintf(stderr, OUT_TAG ": unable to seek map '%s' %s\n",
-                tagfile, strerror(save_errno));
-        close(fd);
-        errno = save_errno;
-        return NULL;
+        (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
     }
 
-    EventTagMap* newTagMap = new EventTagMap;
+    newTagMap = new EventTagMap;
     if (newTagMap == NULL) {
         save_errno = errno;
-        close(fd);
-        errno = save_errno;
-        return NULL;
+        goto fail_close;
     }
 
-    newTagMap->mapAddr = mmap(NULL, end, PROT_READ | PROT_WRITE,
-                              MAP_PRIVATE, fd, 0);
-    save_errno = errno;
-    close(fd);
-    fd = -1;
-    if ((newTagMap->mapAddr == MAP_FAILED) || (newTagMap->mapAddr == NULL)) {
-        fprintf(stderr, OUT_TAG ": mmap(%s) failed: %s\n",
-                tagfile, strerror(save_errno));
-        delete newTagMap;
-        errno = save_errno;
-        return NULL;
+    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;
+            }
+        }
     }
 
-    newTagMap->mapLen = end;
-
-    if (parseMapLines(newTagMap) != 0) {
-        delete newTagMap;
-        return NULL;
+    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.
@@ -321,3 +491,75 @@
     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 4939221..1d7a157 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -612,7 +612,12 @@
 
 bail:
     unlock();
-    return vector[0].iov_len + vector[1].iov_len + vector[2].iov_len;
+    int len = 0;
+    for (i = 0; i < count; ++i) {
+       len += vector[i].iov_len;
+    }
+    return len;
+
 error:
     unlock();
     return -1;
@@ -715,6 +720,12 @@
     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)
diff --git a/liblog/fake_writer.c b/liblog/fake_writer.c
index dab8bc5..2350673 100644
--- a/liblog/fake_writer.c
+++ b/liblog/fake_writer.c
@@ -46,9 +46,19 @@
     int i;
 
     for (i = 0; i < LOG_ID_MAX; i++) {
-        char buf[sizeof("/dev/log_security")];
+        /*
+         * 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;
+        }
         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;
 }
@@ -66,16 +76,28 @@
                       struct iovec *vec, size_t nr)
 {
     ssize_t ret;
-    int logFd;
+    size_t i;
+    int logFd, len;
 
     if (/*(int)log_id >= 0 &&*/ (int)log_id >= (int)LOG_ID_MAX) {
-        return -EBADF;
+        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;
     }
 
     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/legacy-ndk-includes/log.h b/liblog/include/android/log.h
similarity index 72%
rename from liblog/legacy-ndk-includes/log.h
rename to liblog/include/android/log.h
index d40d6fa..9f198fe 100644
--- a/liblog/legacy-ndk-includes/log.h
+++ b/liblog/include/android/log.h
@@ -91,14 +91,22 @@
 /*
  * Send a simple string to the log.
  */
-int __android_log_write(int prio, const char *tag, const char *text);
+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, ...)
+int __android_log_print(int prio, const char* tag,  const char* fmt, ...)
 #if defined(__GNUC__)
-    __attribute__((__format__(printf, 3, 4)))
+#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
     ;
 
@@ -106,18 +114,38 @@
  * 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);
+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 SIGTRAP the process to have a chance
- * to inspect it, if a debugger is attached. This uses the FATAL priority.
+ * 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, ...)    
+void __android_log_assert(const char* cond, const char* tag,
+                          const char* fmt, ...)
 #if defined(__GNUC__)
-    __attribute__((__noreturn__))
-    __attribute__((__format__(printf, 3, 4)))
+    __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
     ;
 
diff --git a/include/log/event_tag_map.h b/liblog/include/log/event_tag_map.h
similarity index 90%
rename from include/log/event_tag_map.h
rename to liblog/include/log/event_tag_map.h
index 22e62ec..e57e47b 100644
--- a/include/log/event_tag_map.h
+++ b/liblog/include/log/event_tag_map.h
@@ -58,6 +58,12 @@
 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
diff --git a/liblog/include/log/log.h b/liblog/include/log/log.h
new file mode 100644
index 0000000..db22211
--- /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/include/log/log_event_list.h b/liblog/include/log/log_event_list.h
similarity index 100%
rename from include/log/log_event_list.h
rename to liblog/include/log/log_event_list.h
diff --git a/liblog/include/log/log_frontend.h b/liblog/include/log/log_frontend.h
new file mode 100644
index 0000000..9527779
--- /dev/null
+++ b/liblog/include/log/log_frontend.h
@@ -0,0 +1,34 @@
+/*
+**
+** 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_FRONTEND_H
+#define _LIBS_LOG_FRONTEND_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Logging frontends, bit mask to select features. Function returns selection.
+ */
+#define LOGGER_DEFAULT 0x0
+#define LOGGER_LOGD    0x1
+#define LOGGER_KERNEL  0x2 /* Reserved/Deprecated */
+#define LOGGER_NULL    0x4 /* Does not release resources of other selections */
+#define LOGGER_LOCAL   0x8 /* logs sent to local memory */
+
+/* Both return the selected frontend flag mask, or negative errno */
+int android_set_log_frontend(int frontend_flag);
+int android_get_log_frontend();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_FRONTEND_H */
diff --git a/liblog/include/log/log_id.h b/liblog/include/log/log_id.h
new file mode 100644
index 0000000..3078e4e
--- /dev/null
+++ b/liblog/include/log/log_id.h
@@ -0,0 +1,63 @@
+/*
+ * 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/include/android/log.h b/liblog/include/log/log_main.h
similarity index 70%
rename from include/android/log.h
rename to liblog/include/log/log_main.h
index 5673357..f45397a 100644
--- a/include/android/log.h
+++ b/liblog/include/log/log_main.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009 The Android Open Source Project
+ * 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.
@@ -14,88 +14,16 @@
  * limitations under the License.
  */
 
-#ifndef _ANDROID_LOG_H
-#define _ANDROID_LOG_H
+#ifndef _LIBS_LOG_LOG_MAIN_H
+#define _LIBS_LOG_LOG_MAIN_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>
+#include <android/log.h>
 
 #ifdef __cplusplus
 extern "C" {
 #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
-
-/*
- * LOG_TAG is the local tag used for the following simplified
- * logging macros.  You must set this preprocessor definition,
- * or more tenuously supply a variable definition, before using
- * the macros.
- */
-
-/*
  * 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
@@ -111,52 +39,32 @@
 #endif
 #endif
 
-/*
- * Android log priority values, in ascending priority order.
- */
-#ifndef __android_LogPriority_defined
-#define __android_LogPriority_defined
-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;
-#endif
+/* --------------------------------------------------------------------- */
 
 /*
- * Send a simple string to the log.
+ * 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
  */
-int __android_log_write(int prio, const char* tag, const char* text);
+#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)
 
-/*
- * 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
-    ;
-
 #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.
  */
@@ -166,28 +74,6 @@
 #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
-    ;
-
-#define android_vprintLog(prio, cond, tag, ...) \
-    __android_log_vprint(prio, tag, __VA_ARGS__)
-
-/*
  * Log macro that allows you to pass in a varargs ("args" is a va_list).
  */
 #ifndef LOG_PRI_VA
@@ -195,25 +81,7 @@
     android_vprintLog(priority, NULL, tag, fmt, args)
 #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
-    ;
+/* --------------------------------------------------------------------- */
 
 /* 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
@@ -524,4 +392,4 @@
 }
 #endif
 
-#endif /* _ANDROID_LOG_H */
+#endif /* _LIBS_LOG_LOG_MAIN_H */
diff --git a/liblog/include/log/log_radio.h b/liblog/include/log/log_radio.h
new file mode 100644
index 0000000..430e522
--- /dev/null
+++ b/liblog/include/log/log_radio.h
@@ -0,0 +1,129 @@
+/*
+ * 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..6a44b56
--- /dev/null
+++ b/liblog/include/log/log_read.h
@@ -0,0 +1,295 @@
+/*
+ * 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..394a106
--- /dev/null
+++ b/liblog/include/log/log_system.h
@@ -0,0 +1,127 @@
+/*
+ * 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..900dc1b
--- /dev/null
+++ b/liblog/include/log/log_time.h
@@ -0,0 +1,196 @@
+/*
+ * 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);
+    }
+    log_time(uint32_t sec, uint32_t nsec)
+    {
+        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__
+    log_time(clockid_t id)
+    {
+        timespec T;
+        clock_gettime(id, &T);
+        tv_sec = static_cast<uint32_t>(T.tv_sec);
+        tv_nsec = static_cast<uint32_t>(T.tv_nsec);
+    }
+#endif
+    log_time(const char* T)
+    {
+        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/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/include/log/logprint.h b/liblog/include/log/logprint.h
similarity index 95%
rename from include/log/logprint.h
rename to liblog/include/log/logprint.h
index 3509e7f..5b99c3c 100644
--- a/include/log/logprint.h
+++ b/liblog/include/log/logprint.h
@@ -42,11 +42,13 @@
     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_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;
diff --git a/include/log/uio.h b/liblog/include/log/uio.h
similarity index 100%
rename from include/log/uio.h
rename to liblog/include/log/uio.h
diff --git a/include/private/android_logger.h b/liblog/include/private/android_logger.h
similarity index 100%
rename from include/private/android_logger.h
rename to liblog/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_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/local_logger.c b/liblog/local_logger.c
new file mode 100644
index 0000000..d504342
--- /dev/null
+++ b/liblog/local_logger.c
@@ -0,0 +1,556 @@
+/*
+ * 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 <sched.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <log/uio.h>
+
+#include <cutils/list.h> /* template, no library dependency */
+#include <log/log_frontend.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.private = 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_frontend == 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/logd_reader.c b/liblog/logd_reader.c
index 99d7fea..ccc7da8 100644
--- a/liblog/logd_reader.c
+++ b/liblog/logd_reader.c
@@ -37,6 +37,7 @@
 
 #include "config_read.h"
 #include "log_portability.h"
+#include "logd_reader.h"
 #include "logger.h"
 
 /* branchless on many architectures. */
@@ -324,6 +325,11 @@
     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) {
diff --git a/init/seccomp.h b/liblog/logd_reader.h
similarity index 71%
copy from init/seccomp.h
copy to liblog/logd_reader.h
index cda7a89..04c2cf2 100644
--- a/init/seccomp.h
+++ b/liblog/logd_reader.h
@@ -14,9 +14,17 @@
  * limitations under the License.
  */
 
-#ifndef SECCOMP_H
-#define SECCOMP_H
+#ifndef _LIBLOG_LOGD_READER_H__
+#define _LIBLOG_LOGD_READER_H__
 
-bool set_seccomp_filter();
+#include <unistd.h>
 
-#endif
+#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/logger.h b/liblog/logger.h
index 50d1cb4..d94cd14 100644
--- a/liblog/logger.h
+++ b/liblog/logger.h
@@ -39,14 +39,16 @@
 
 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,22 +57,23 @@
 
 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);
+  /* 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 */
+  /* 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);
 
@@ -96,6 +99,7 @@
 };
 
 struct android_log_logger_list {
+  struct listnode node;
   struct listnode logger;
   struct listnode transport;
   int mode;
@@ -117,9 +121,9 @@
   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 */
+  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 */
@@ -143,6 +147,41 @@
          (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)
@@ -157,6 +196,8 @@
 LIBLOG_HIDDEN int __android_log_trylock();
 LIBLOG_HIDDEN void __android_log_unlock();
 
+LIBLOG_HIDDEN int __android_log_frontend;
+
 __END_DECLS
 
 #endif /* _LIBLOG_LOGGER_H__ */
diff --git a/liblog/logger_read.c b/liblog/logger_read.c
index c3cb7ad..7e50a23 100644
--- a/liblog/logger_read.c
+++ b/liblog/logger_read.c
@@ -228,6 +228,13 @@
     LOGGER_LIST_FUNCTION(logger_list, -ENODEV, setPrune, buf, len);
 }
 
+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
+
 LIBLOG_ABI_PUBLIC struct logger_list *android_logger_list_alloc(
         int mode,
         unsigned int tail,
@@ -246,6 +253,10 @@
     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;
 }
 
@@ -267,6 +278,10 @@
     logger_list->start = start;
     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;
 }
 
@@ -502,6 +517,10 @@
         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 =
diff --git a/liblog/logger_write.c b/liblog/logger_write.c
index 1a2d506..e149e68 100644
--- a/liblog/logger_write.c
+++ b/liblog/logger_write.c
@@ -25,9 +25,11 @@
 #endif
 
 #include <log/event_tag_map.h>
+#include <log/log_frontend.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"
@@ -170,6 +172,8 @@
         }
     }
 
+    __android_log_config_write_close();
+
 #if defined(__ANDROID__)
     /*
      * Additional risk here somewhat mitigated by immediately unlock flushing
@@ -343,7 +347,7 @@
             }
         }
         /* tag must be nul terminated */
-        if (strnlen(tag, len) >= len) {
+        if (tag && strnlen(tag, len) >= len) {
             tag = NULL;
         }
 
@@ -514,6 +518,14 @@
             strcpy(buf, "Unspecified assertion failed");
     }
 
+    // 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 */
@@ -610,3 +622,87 @@
 
     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_frontend;
+
+LIBLOG_ABI_PUBLIC int android_set_log_frontend(int frontend_flag)
+{
+    int retval;
+
+    if (frontend_flag < 0) {
+        return -EINVAL;
+    }
+
+    retval = LOGGER_NULL;
+
+    __android_log_lock();
+
+    if (frontend_flag & LOGGER_NULL) {
+        write_to_log = __write_to_log_null;
+
+        __android_log_unlock();
+
+        return retval;
+    }
+
+    __android_log_frontend &= LOGGER_LOCAL | LOGGER_LOGD;
+
+    frontend_flag &= LOGGER_LOCAL | LOGGER_LOGD;
+
+    if (__android_log_frontend != frontend_flag) {
+        __android_log_frontend = frontend_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_frontend;
+
+    __android_log_unlock();
+
+    return retval;
+}
+
+LIBLOG_ABI_PUBLIC int android_get_log_frontend()
+{
+    int ret = LOGGER_DEFAULT;
+
+    __android_log_lock();
+    if (write_to_log == __write_to_log_null) {
+        ret = LOGGER_NULL;
+    } else {
+        __android_log_frontend &= LOGGER_LOCAL | LOGGER_LOGD;
+        ret = __android_log_frontend;
+        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 da80e36..e61850d 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -16,13 +16,20 @@
 */
 
 #define _GNU_SOURCE /* for asprintf */
+#ifndef __MINGW32__
+#define HAVE_STRSEP
+#endif
 
-#include <arpa/inet.h>
+//#ifndef __MINGW32__
+//#include <arpa/inet.h>
+//#endif
 #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>
@@ -40,6 +47,10 @@
 #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;
@@ -52,6 +63,7 @@
     AndroidLogPrintFormat format;
     bool colored_output;
     bool usec_time_output;
+    bool nsec_time_output;
     bool printable_output;
     bool year_output;
     bool zone_output;
@@ -210,11 +222,16 @@
     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;
@@ -258,6 +275,9 @@
     case FORMAT_MODIFIER_TIME_USEC:
         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;
@@ -309,6 +329,7 @@
     else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
     else if (strcmp(formatString, "colour") == 0) format = FORMAT_MODIFIER_COLOR;
     else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
+    else if (strcmp(formatString, "nsec") == 0) format = FORMAT_MODIFIER_TIME_NSEC;
     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;
@@ -316,6 +337,7 @@
     else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
     else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
     else if (strcmp(formatString, "descriptive") == 0) format = FORMAT_MODIFIER_DESCRIPT;
+#ifndef __MINGW32__
     else {
         extern char *tzname[2];
         static const char gmt[] = "GMT";
@@ -347,6 +369,7 @@
         }
         free(cp);
     }
+#endif
 
     return format;
 }
@@ -405,7 +428,7 @@
 
 /*
  * 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);
@@ -427,6 +450,27 @@
     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
@@ -438,7 +482,6 @@
  * Assumes single threaded execution
  *
  */
-
 LIBLOG_ABI_PUBLIC int android_log_addFilterString(
         AndroidLogFormat *p_format,
         const char *filterString)
@@ -722,6 +765,7 @@
             }
         }
     }
+    outCount = 0;
     lval = 0;
     switch (type) {
     case EVENT_TYPE_INT:
@@ -947,7 +991,7 @@
 LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
         struct logger_entry *buf,
         AndroidLogEntry *entry,
-        const EventTagMap *map,
+        const EventTagMap *map __unused,
         char *messageBuf, int messageBufLen)
 {
     size_t inCount;
@@ -989,11 +1033,12 @@
     inCount -= 4;
 
     entry->tagLen = 0;
+    entry->tag = NULL;
+#ifdef __ANDROID__
     if (map != NULL) {
         entry->tag = android_lookupEventTag_len(map, &entry->tagLen, tagIndex);
-    } else {
-        entry->tag = NULL;
     }
+#endif
 
     /*
      * If we don't have a map, or didn't find the tag number in the map,
@@ -1018,9 +1063,11 @@
      */
     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 */
@@ -1244,6 +1291,7 @@
     return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
 }
 
+#ifdef __ANDROID__
 static void convertMonotonic(struct timespec *result,
                              const AndroidLogEntry *entry)
 {
@@ -1476,6 +1524,7 @@
     result->tv_nsec = entry->tv_nsec;
     subTimespec(result, result, &convert);
 }
+#endif
 
 /**
  * Formats a log message into a buffer
@@ -1496,7 +1545,8 @@
     struct tm tmBuf;
 #endif
     struct tm* ptm;
-    char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
+    /* 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;
@@ -1522,6 +1572,7 @@
      */
     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) {
@@ -1531,6 +1582,7 @@
             nsec = time.tv_nsec;
         }
     }
+#endif
     if (now < 0) {
         nsec = NS_PER_SEC - nsec;
     }
@@ -1550,7 +1602,10 @@
                  ptm);
     }
     len = strlen(timeBuf);
-    if (p_format->usec_time_output) {
+    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 {
@@ -1581,13 +1636,18 @@
              * 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 {
+            } else
+#endif
+            {
                  // Not worth parsing package list, names all longer than 5
                  snprintf(uid, sizeof(uid), "%5d:", entry->uid);
             }
diff --git a/liblog/pmsg_writer.c b/liblog/pmsg_writer.c
index c1c068e..5e4ff98 100644
--- a/liblog/pmsg_writer.c
+++ b/liblog/pmsg_writer.c
@@ -285,6 +285,7 @@
                 __android_log_unlock();
             } else if (pmsgOpen() < 0) {
                 __android_log_unlock();
+                free(cp);
                 return -EBADF;
             }
         }
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index ec5a99b..cfea452 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -55,7 +55,13 @@
     -fno-builtin \
 
 test_src_files := \
-    liblog_test.cpp
+    liblog_test_default.cpp \
+    liblog_test_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),)
@@ -106,6 +112,7 @@
 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/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 5420f68..dac84eb 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -15,6 +15,8 @@
  */
 
 #include <fcntl.h>
+#include <inttypes.h>
+#include <poll.h>
 #include <sys/endian.h>
 #include <sys/socket.h>
 #include <sys/types.h>
@@ -22,8 +24,10 @@
 
 #include <unordered_set>
 
+#include <android-base/file.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
+#include <log/log_frontend.h>
 #include <private/android_logger.h>
 
 #include "benchmark.h"
@@ -77,10 +81,29 @@
 }
 BENCHMARK(BM_log_maximum);
 
+static void set_log_null() {
+    android_set_log_frontend(LOGGER_NULL);
+}
+
+static void set_log_default() {
+    android_set_log_frontend(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) {
@@ -465,19 +488,94 @@
 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) {
+/* helper function */
+static void test_print(const char *fmt, ...) {
+    va_list ap;
+    char buf[1024];
+
+    va_start(ap, fmt);
+    vsnprintf(buf, sizeof(buf), fmt, ap);
+    va_end(ap);
+}
+
+#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();
-       usleep(1000);
+       logd_yield();
     }
 }
-BENCHMARK(BM_log_overhead);
+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*/)
 {
@@ -695,7 +793,7 @@
 
 // Keep maps around for multiple iterations
 static std::unordered_set<uint32_t> set;
-static const EventTagMap* map;
+static EventTagMap* map;
 
 static bool prechargeEventMap() {
     if (map) return true;
@@ -785,3 +883,142 @@
     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 ec0352e..bc0ea4c 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -19,6 +19,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
+#include <pthread.h>
 #include <semaphore.h>
 #include <signal.h>
 #include <stdio.h>
@@ -36,9 +37,32 @@
 #include <gtest/gtest.h>
 #include <log/logprint.h>
 #include <log/log_event_list.h>
+#include <log/log_frontend.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
+#ifndef TEST_PREFIX
+#ifdef __ANDROID__ // make sure we always run code if compiled for android
+#define TEST_PREFIX
+#endif
+#endif
+
+#if (!defined(USING_LOGGER_DEFAULT) || !defined(USING_LOGGER_LOCAL))
+#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
+
 // 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
@@ -54,46 +78,10 @@
           || (_rc == -EAGAIN));    \
     _rc; })
 
-TEST(liblog, __android_log_buf_print) {
-#ifdef __ANDROID__
-    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);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-}
-
-TEST(liblog, __android_log_buf_write) {
-#ifdef __ANDROID__
-    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);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-}
-
 TEST(liblog, __android_log_btwrite) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
+#endif
     int intBuf = 0xDEADBEEF;
     EXPECT_LT(0, __android_log_btwrite(0,
                                       EVENT_TYPE_INT,
@@ -108,50 +96,10 @@
                                       EVENT_TYPE_STRING,
                                       Buf, sizeof(Buf) - 1));
     usleep(1000);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
 }
 
-#ifdef __ANDROID__
-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);
-}
-#endif
-
-#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)) {
-#ifdef __ANDROID__
-    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);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-}
-
-#ifdef __ANDROID__
-std::string popenToString(std::string command) {
+#if (defined(__ANDROID__) && !defined(USING_LOGGER_LOCAL))
+static std::string popenToString(std::string command) {
     std::string ret;
 
     FILE* fp = popen(command.c_str(), "r");
@@ -215,11 +163,11 @@
     return false;
 }
 
-bool tested__android_log_close;
+static bool tested__android_log_close;
 #endif
 
 TEST(liblog, __android_log_btwrite__android_logger_list_read) {
-#ifdef __ANDROID__
+#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -227,9 +175,10 @@
     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)));
+#ifndef USING_LOGGER_LOCAL
+    // Check that we can close and reopen the logger
     bool pmsgActiveAfter__android_log_btwrite;
     bool logdwActiveAfter__android_log_btwrite;
     if (getuid() == AID_ROOT) {
@@ -248,15 +197,18 @@
         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)));
+#ifndef USING_LOGGER_LOCAL
     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;
@@ -299,15 +251,92 @@
 #endif
 }
 
-#ifdef __ANDROID__
-static inline int32_t get4LE(const char* src)
-{
+// 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_frontend) {
+#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
+#ifdef TEST_PREFIX
+    TEST_PREFIX
+#endif
+
+    int logger = android_get_log_frontend();
+    EXPECT_NE(LOGGER_NULL, logger);
+
+    EXPECT_EQ(LOGGER_NULL, android_set_log_frontend(LOGGER_NULL));
+    EXPECT_EQ(LOGGER_NULL, android_get_log_frontend());
+
+    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);
+    ASSERT_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;
+        }
+
+        ASSERT_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, android_set_log_frontend(logger));
+    EXPECT_EQ(logger, android_get_log_frontend());
+
+    // 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.
+    EXPECT_EQ(0, count);
+    // 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.
+#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 __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -315,7 +344,11 @@
     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
 
     ASSERT_LT(0, __android_log_bswrite(0, message));
     size_t num_lines = 1, size = 0, length = 0, total = 0;
@@ -381,8 +414,11 @@
                 &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
             EXPECT_EQ((length == total) ? 0 : -1, processBinaryLogBuffer);
             if (processBinaryLogBuffer == 0) {
+                size_t line_overhead = 20;
+                if (pid > 99999) ++line_overhead;
+                if (pid > 999999) ++line_overhead;
                 fflush(stderr);
-                EXPECT_EQ((int)((20 * num_lines) + size),
+                EXPECT_EQ((int)((line_overhead * num_lines) + size),
                     android_log_printLogLine(logformat, fileno(stderr), &entry));
             }
             android_log_format_free(logformat);
@@ -419,7 +455,8 @@
 }
 
 static void buf_write_test(const char *message) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -428,7 +465,11 @@
         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));
@@ -476,8 +517,11 @@
                                                             &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)(((11 + sizeof(tag)) * num_lines) + size),
+            EXPECT_EQ((int)(((line_overhead + sizeof(tag)) * num_lines) + size),
                 android_log_printLogLine(logformat, fileno(stderr), &entry));
         }
         android_log_format_free(logformat);
@@ -504,7 +548,8 @@
     buf_write_test("\n Hello World \n");
 }
 
-#ifdef __ANDROID__
+#ifndef USING_LOGGER_LOCAL // requires blocking reader functionality
+#ifdef TEST_PREFIX
 static unsigned signaled;
 static log_time signal_time;
 
@@ -566,7 +611,8 @@
 #endif
 
 TEST(liblog, android_logger_list_read__cpu_signal) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     struct logger_list *logger_list;
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
@@ -658,7 +704,7 @@
 #endif
 }
 
-#ifdef __ANDROID__
+#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
@@ -692,7 +738,7 @@
     return NULL;
 }
 
-int start_thread()
+static int start_thread()
 {
     sem_init(&thread_trigger, 0, 0);
 
@@ -724,7 +770,8 @@
 #endif
 
 TEST(liblog, android_logger_list_read__cpu_thread) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     struct logger_list *logger_list;
     unsigned long long v = 0xDEADBEAFA55A0000ULL;
 
@@ -816,8 +863,9 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOGGER_LOCAL
 
-#ifdef __ANDROID__
+#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)
@@ -954,7 +1002,8 @@
 takes his leave.";
 
 TEST(liblog, max_payload) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     pid_t pid = getpid();
     char tag[sizeof(max_payload_tag)];
     memcpy(tag, max_payload_tag, sizeof(tag));
@@ -1018,7 +1067,8 @@
 }
 
 TEST(liblog, __android_log_buf_print__maxtag) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
+    TEST_PREFIX
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -1026,7 +1076,11 @@
     ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
         LOG_ID_MAIN, 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_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
                                          max_payload_buf, max_payload_buf));
@@ -1078,7 +1132,8 @@
 }
 
 TEST(liblog, too_big_payload) {
-#ifdef __ANDROID__
+#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)];
@@ -1132,6 +1187,12 @@
     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";
@@ -1139,17 +1200,29 @@
 }
 
 TEST(liblog, dual_reader) {
-#ifdef __ANDROID__
-    struct logger_list *logger_list1;
+#ifdef TEST_PREFIX
+    TEST_PREFIX
 
-    // >25 messages due to liblog.__android_log_buf_print__concurrentXX above.
+    static const int num = 25;
+
+    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);
+
+    struct logger_list *logger_list1;
     ASSERT_TRUE(NULL != (logger_list1 = android_logger_list_open(
-        LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 25, 0)));
+        LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, num, 0)));
 
     struct logger_list *logger_list2;
 
     if (NULL == (logger_list2 = android_logger_list_open(
-            LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 15, 0))) {
+            LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, num - 10, 0))) {
         android_logger_list_close(logger_list1);
         ASSERT_TRUE(NULL != logger_list2);
     }
@@ -1182,63 +1255,20 @@
     android_logger_list_close(logger_list1);
     android_logger_list_close(logger_list2);
 
-    EXPECT_EQ(25, count1);
-    EXPECT_EQ(15, count2);
+    EXPECT_EQ(num, count1);
+    EXPECT_EQ(num - 10, count2);
 #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! */
-            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));
-    }
-
-    android_logger_list_close(logger_list);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-}
-
-#ifdef __ANDROID__
+#ifndef USING_LOGGER_LOCAL // 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));
 }
-#endif
 
 TEST(liblog, filterRule) {
-#ifdef __ANDROID__
     static const char tag[] = "random";
 
     AndroidLogFormat *p_format = android_log_format_new();
@@ -1300,11 +1330,10 @@
 #endif
 
     android_log_format_free(p_format);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
 }
+#endif // !USING_LOGGER_LOCAL
 
+#ifndef USING_LOGGER_LOCAL // Do not retest property handling
 TEST(liblog, is_loggable) {
 #ifdef __ANDROID__
     static const char tag[] = "is_loggable";
@@ -1603,8 +1632,13 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOGGER_LOCAL
 
-#ifdef __ANDROID__
+// 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.
+#ifndef USING_LOGGER_LOCAL
+#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);
@@ -1646,10 +1680,11 @@
         testing::AssertionSuccess() :
         (testing::AssertionFailure() << message);
 }
-#endif
+#endif // TEST_PREFIX
 
 TEST(liblog, enoent) {
-#ifdef __ANDROID__
+#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(1, count_matching_ts(ts));
@@ -1703,9 +1738,12 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOCAL_LOGGER
 
 // 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
+#ifndef USING_LOGGER_LOCAL
 TEST(liblog, __security) {
 #ifdef __ANDROID__
     static const char persist_key[] = "persist.logd.security";
@@ -1891,15 +1929,19 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOGGER_LOCAL
 
-#ifdef __ANDROID__
+#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)));
 
@@ -1913,8 +1955,6 @@
 
     sleep(2);
 
-    count = 0;
-
     for (;;) {
         log_msg log_msg;
         if (android_logger_list_read(logger_list, &log_msg) <= 0) {
@@ -1954,7 +1994,7 @@
         ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
         eventData++;
 
-        int subtag_len = strlen(SUBTAG);
+        unsigned subtag_len = strlen(SUBTAG);
         if (subtag_len > 32) subtag_len = 32;
         ASSERT_EQ(subtag_len, get4LE(eventData));
         eventData += 4;
@@ -1968,7 +2008,7 @@
         ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
         eventData++;
 
-        ASSERT_EQ(UID, get4LE(eventData));
+        ASSERT_EQ(UID, (int)get4LE(eventData));
         eventData += 4;
 
         // Element #3: string type for data
@@ -1998,7 +2038,7 @@
 #endif
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteWithInfoLog_helper(
             123456781,
@@ -2014,7 +2054,7 @@
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteWithInfoLog_helper(
             123456782,
@@ -2030,7 +2070,7 @@
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteWithInfoLog_helper(
             123456783,
@@ -2046,7 +2086,7 @@
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteWithInfoLog_helper(
             123456784,
@@ -2069,12 +2109,15 @@
     buf_write_test(max_payload_buf);
 }
 
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
 static void android_errorWriteLog_helper(int TAG, const char *SUBTAG, 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)));
 
@@ -2087,8 +2130,6 @@
 
     sleep(2);
 
-    count = 0;
-
     for (;;) {
         log_msg log_msg;
         if (android_logger_list_read(logger_list, &log_msg) <= 0) {
@@ -2126,7 +2167,7 @@
         ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
         eventData++;
 
-        ASSERT_EQ((int) strlen(SUBTAG), get4LE(eventData));
+        ASSERT_EQ(strlen(SUBTAG), get4LE(eventData));
         eventData +=4;
 
         if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
@@ -2140,7 +2181,7 @@
 #endif
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteLog_helper(123456785, "test-subtag", count);
     EXPECT_EQ(1, count);
@@ -2150,7 +2191,7 @@
 }
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     int count;
     android_errorWriteLog_helper(123456786, NULL, count);
     EXPECT_EQ(0, count);
@@ -2159,7 +2200,8 @@
 #endif
 }
 
-#ifdef __ANDROID__
+// 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) ||
@@ -2167,8 +2209,8 @@
             (type == EVENT_TYPE_FLOAT));
 }
 
-int android_log_buffer_to_string(const char *msg, size_t len,
-                                 char *strOut, size_t 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;
@@ -2318,7 +2360,9 @@
 
     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;
 
@@ -2574,6 +2618,7 @@
 }
 
 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();
@@ -2581,7 +2626,11 @@
     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
 
     size_t expected_len;
     const char *expected_string = (*fn)(1005, expected_len);
@@ -2622,18 +2671,23 @@
             &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(20 + (int)strlen(expected_string), printLogLine);
+            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/[%d]", get4LE(eventData));
+            snprintf(msgBuf, sizeof(msgBuf),
+                     "I/[%" PRIu32 "]", get4LE(eventData));
             print_barrier();
             fprintf(stderr, "%-10s(%5u): ", msgBuf, pid);
             memset(msgBuf, 0, sizeof(msgBuf));
@@ -2656,7 +2710,7 @@
 #endif
 
 TEST(liblog, create_android_logger_int32) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_int32);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2664,7 +2718,7 @@
 }
 
 TEST(liblog, create_android_logger_int64) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_int64);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2672,7 +2726,7 @@
 }
 
 TEST(liblog, create_android_logger_list_int64) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_list_int64);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2680,7 +2734,7 @@
 }
 
 TEST(liblog, create_android_logger_simple_automagic_list) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_simple_automagic_list);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2688,7 +2742,7 @@
 }
 
 TEST(liblog, create_android_logger_list_empty) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_list_empty);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2696,7 +2750,7 @@
 }
 
 TEST(liblog, create_android_logger_complex_nested_list) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_complex_nested_list);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2704,7 +2758,7 @@
 }
 
 TEST(liblog, create_android_logger_7_level_prefix) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_7_level_prefix);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2712,7 +2766,7 @@
 }
 
 TEST(liblog, create_android_logger_7_level_suffix) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_7_level_suffix);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2720,7 +2774,7 @@
 }
 
 TEST(liblog, create_android_logger_android_log_error_write) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_android_log_error_write);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2728,15 +2782,15 @@
 }
 
 TEST(liblog, create_android_logger_android_log_error_write_null) {
-#ifdef __ANDROID__
+#ifdef TEST_PREFIX
     create_android_logger(event_test_android_log_error_write_null);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
 
+#ifndef USING_LOGGER_LOCAL // Do not retest logger list handling
 TEST(liblog, create_android_logger_overflow) {
-#ifdef __ANDROID__
     android_log_context ctx;
 
     EXPECT_TRUE(NULL != (ctx = create_android_logger(1005)));
@@ -2761,13 +2815,9 @@
     EXPECT_GT(0, android_log_write_list_begin(ctx));
     EXPECT_LE(0, android_log_destroy(&ctx));
     ASSERT_TRUE(NULL == ctx);
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
 }
 
 TEST(liblog, android_log_write_list_buffer) {
-#ifdef __ANDROID__
     __android_log_event_list ctx(1005);
     ctx << 1005 << "tag_def" << "(tag|1),(name|3),(format|3)";
     std::string buffer(ctx);
@@ -2778,11 +2828,10 @@
     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)]");
-#else
-    GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
 }
+#endif // !USING_LOGGER_LOCAL
 
+#ifndef USING_LOGGER_LOCAL // Do not retest pmsg functionality
 #ifdef __ANDROID__
 static const char __pmsg_file[] =
         "/data/william-shakespeare/MuchAdoAboutNothing.txt";
@@ -2845,8 +2894,8 @@
 }
 
 #ifdef __ANDROID__
-ssize_t __pmsg_fn(log_id_t logId, char prio, const char *filename,
-                  const char *buf, size_t len, void *arg) {
+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);
@@ -2908,7 +2957,9 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOGGER_LOCAL
 
+#ifndef USING_LOGGER_LOCAL // 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,
@@ -2991,7 +3042,7 @@
     EXPECT_TRUE(IsOk(private_ok, content));
     EXPECT_TRUE(IsOk(anonymous_ok, content));
 }
-#endif
+#endif // __ANDROID__
 
 TEST(liblog, event_log_tags) {
 #ifdef __ANDROID__
@@ -3012,7 +3063,9 @@
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif // !USING_LOGGER_LOCAL
 
+#ifndef USING_LOGGER_LOCAL // Do not retest ratelimit
 TEST(liblog, __android_log_ratelimit) {
     time_t state = 0;
 
@@ -3044,3 +3097,22 @@
     }
     // Do not test default seconds, to allow liblog to tune freely
 }
+#endif // !USING_LOGGER_LOCAL
+
+#ifndef USING_LOGGER_LOCAL // 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_LOCAL
diff --git a/liblog/tests/liblog_test_default.cpp b/liblog/tests/liblog_test_default.cpp
new file mode 100644
index 0000000..079ba07
--- /dev/null
+++ b/liblog/tests/liblog_test_default.cpp
@@ -0,0 +1,5 @@
+#ifdef __ANDROID__
+#include <log/log_frontend.h>
+#define TEST_PREFIX android_set_log_frontend(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..5f7f645
--- /dev/null
+++ b/liblog/tests/liblog_test_local.cpp
@@ -0,0 +1,4 @@
+#include <log/log_frontend.h>
+#define liblog liblog_local
+#define TEST_PREFIX android_set_log_frontend(LOGGER_LOCAL);
+#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..b8223f1
--- /dev/null
+++ b/liblog/tests/log_id_test.cpp
@@ -0,0 +1,107 @@
+/*
+ * 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..ecba777
--- /dev/null
+++ b/liblog/tests/log_radio_test.cpp
@@ -0,0 +1,117 @@
+/*
+ * 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..2e02407
--- /dev/null
+++ b/liblog/tests/log_read_test.cpp
@@ -0,0 +1,118 @@
+/*
+ * 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/log.h> // minimal logging API
+#include <android-base/stringprintf.h>
+#include <gtest/gtest.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! */
+            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));
+    }
+
+    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..40e3a63
--- /dev/null
+++ b/liblog/tests/log_system_test.cpp
@@ -0,0 +1,117 @@
+/*
+ * 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..59655ba
--- /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/libmemtrack/memtrack.cpp b/libmemtrack/memtrack.cpp
index 8adc8fc..e83f181 100644
--- a/libmemtrack/memtrack.cpp
+++ b/libmemtrack/memtrack.cpp
@@ -44,7 +44,7 @@
 
 //TODO(b/31632518)
 static android::sp<IMemtrack> get_instance() {
-    static android::sp<IMemtrack> module = IMemtrack::getService("memtrack");
+    static android::sp<IMemtrack> module = IMemtrack::getService();
     if (module == nullptr) {
         ALOGE("Couldn't load memtrack module");
     }
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index d7b5cb5..2f23c2c 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -246,7 +246,9 @@
     // 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, ':');
diff --git a/libsync/tests/sync_test.cpp b/libsync/tests/sync_test.cpp
index ff8a300..401aaee 100644
--- a/libsync/tests/sync_test.cpp
+++ b/libsync/tests/sync_test.cpp
@@ -536,7 +536,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++) {
@@ -549,12 +549,12 @@
         // 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.
diff --git a/libsysutils/Android.mk b/libsysutils/Android.mk
index 7bf53e3..330d6cb 100644
--- a/libsysutils/Android.mk
+++ b/libsysutils/Android.mk
@@ -21,5 +21,7 @@
         liblog \
         libnl
 
+LOCAL_EXPORT_C_INCLUDE_DIRS := system/core/libsysutils/include
+
 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/libunwindstack/Android.bp b/libunwindstack/Android.bp
new file mode 100644
index 0000000..9bb1304
--- /dev/null
+++ b/libunwindstack/Android.bp
@@ -0,0 +1,132 @@
+//
+// 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,
+        },
+    },
+}
+
+cc_defaults {
+    name: "libunwindstack_common",
+    defaults: ["libunwindstack_flags"],
+
+    srcs: [
+        "ArmExidx.cpp",
+        "Memory.cpp",
+        "Log.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/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",
+    ],
+
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+
+    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",
+    ],
+}
diff --git a/libunwindstack/ArmExidx.cpp b/libunwindstack/ArmExidx.cpp
new file mode 100644
index 0000000..3b78918
--- /dev/null
+++ b/libunwindstack/ArmExidx.cpp
@@ -0,0 +1,680 @@
+/*
+ * 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"
+
+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];
+  }
+  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;
+    }
+  }
+  if (!(*regs_)[ARM_REG_PC]) {
+    (*regs_)[ARM_REG_PC] = (*regs_)[ARM_REG_LR];
+  }
+  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() {
+  while (Decode());
+  return status_ == ARM_STATUS_FINISH;
+}
diff --git a/libunwindstack/ArmExidx.h b/libunwindstack/ArmExidx.h
new file mode 100644
index 0000000..a92caef
--- /dev/null
+++ b/libunwindstack/ArmExidx.h
@@ -0,0 +1,103 @@
+/*
+ * 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>
+
+#include "Memory.h"
+#include "Regs.h"
+
+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(Regs32* 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_; }
+
+  Regs32* regs() { return regs_; }
+
+  uint32_t cfa() { return cfa_; }
+  void set_cfa(uint32_t cfa) { cfa_ = cfa; }
+
+  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);
+
+  Regs32* 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;
+};
+
+#endif  // _LIBUNWINDSTACK_ARM_EXIDX_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/init/seccomp.h b/libunwindstack/Log.h
similarity index 75%
rename from init/seccomp.h
rename to libunwindstack/Log.h
index cda7a89..2d01aa8 100644
--- a/init/seccomp.h
+++ b/libunwindstack/Log.h
@@ -14,9 +14,12 @@
  * limitations under the License.
  */
 
-#ifndef SECCOMP_H
-#define SECCOMP_H
+#ifndef _LIBUNWINDSTACK_LOG_H
+#define _LIBUNWINDSTACK_LOG_H
 
-bool set_seccomp_filter();
+#include <stdint.h>
 
-#endif
+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..db84271
--- /dev/null
+++ b/libunwindstack/Machine.h
@@ -0,0 +1,135 @@
+/*
+ * 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>
+
+class Regs;
+
+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/Memory.cpp b/libunwindstack/Memory.cpp
new file mode 100644
index 0000000..336e4fe
--- /dev/null
+++ b/libunwindstack/Memory.cpp
@@ -0,0 +1,180 @@
+/*
+ * 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;
+}
+
+MemoryFileAtOffset::~MemoryFileAtOffset() {
+  if (data_) {
+    munmap(&data_[-offset_], size_ + offset_);
+    data_ = nullptr;
+  }
+}
+
+bool MemoryFileAtOffset::Init(const std::string& file, uint64_t offset) {
+  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;
+  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) {
+  // 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..5ab031d
--- /dev/null
+++ b/libunwindstack/Memory.h
@@ -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.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_H
+#define _LIBUNWINDSTACK_MEMORY_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/unique_fd.h>
+
+constexpr bool kMemoryStatsEnabled = true;
+
+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 MemoryFileAtOffset : public Memory {
+ public:
+  MemoryFileAtOffset() = default;
+  virtual ~MemoryFileAtOffset();
+
+  bool Init(const std::string& file, uint64_t offset);
+
+  bool Read(uint64_t addr, void* dst, size_t size) override;
+
+ 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.h b/libunwindstack/Regs.h
new file mode 100644
index 0000000..2766c6f
--- /dev/null
+++ b/libunwindstack/Regs.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_REGS_H
+#define _LIBUNWINDSTACK_REGS_H
+
+#include <stdint.h>
+
+#include <vector>
+
+class Regs {
+ public:
+  Regs(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
+      : pc_reg_(pc_reg), sp_reg_(sp_reg), total_regs_(total_regs) {
+  }
+  virtual ~Regs() = default;
+
+  uint16_t pc_reg() { return pc_reg_; }
+  uint16_t sp_reg() { return sp_reg_; }
+  uint16_t total_regs() { return total_regs_; }
+
+  virtual void* raw_data() = 0;
+  virtual uint64_t pc() = 0;
+  virtual uint64_t sp() = 0;
+
+ protected:
+  uint16_t pc_reg_;
+  uint16_t sp_reg_;
+  uint16_t total_regs_;
+};
+
+template <typename AddressType>
+class RegsTmpl : public Regs {
+ public:
+  RegsTmpl(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
+      : Regs(pc_reg, sp_reg, total_regs), regs_(total_regs) {}
+  virtual ~RegsTmpl() = default;
+
+  uint64_t pc() override { return regs_[pc_reg_]; }
+  uint64_t sp() override { return regs_[sp_reg_]; }
+
+  inline AddressType& operator[](size_t reg) { return regs_[reg]; }
+
+  void* raw_data() override { return regs_.data(); }
+
+ private:
+  std::vector<AddressType> regs_;
+};
+
+class Regs32 : public RegsTmpl<uint32_t> {
+ public:
+  Regs32(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
+      : RegsTmpl(pc_reg, sp_reg, total_regs) {}
+  virtual ~Regs32() = default;
+};
+
+class Regs64 : public RegsTmpl<uint64_t> {
+ public:
+  Regs64(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
+      : RegsTmpl(pc_reg, sp_reg, total_regs) {}
+  virtual ~Regs64() = default;
+};
+
+#endif  // _LIBUNWINDSTACK_REGS_H
diff --git a/libunwindstack/tests/ArmExidxDecodeTest.cpp b/libunwindstack/tests/ArmExidxDecodeTest.cpp
new file mode 100644
index 0000000..9ea917a
--- /dev/null
+++ b/libunwindstack/tests/ArmExidxDecodeTest.cpp
@@ -0,0 +1,992 @@
+/*
+ * 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 "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_;
+    }
+
+    regs32_.reset(new Regs32(0, 1, 32));
+    for (size_t i = 0; i < 32; i++) {
+      (*regs32_)[i] = 0;
+    }
+
+    exidx_.reset(new ArmExidx(regs32_.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<Regs32> regs32_;
+  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_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_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_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_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_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_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(0x80);
+  data_->push_back(0x01);
+  process_memory_.SetData(0x10000, 0x10);
+  ASSERT_TRUE(exidx_->Decode());
+  ASSERT_EQ("", GetFakeLogBuf());
+  if (log_) {
+    ASSERT_EQ("4 unwind pop {r4}\n", GetFakeLogPrint());
+  } else {
+    ASSERT_EQ("", GetFakeLogPrint());
+  }
+  ASSERT_EQ(0x10004U, exidx_->cfa());
+  ASSERT_EQ(0x10U, (*exidx_->regs())[4]);
+
+  ResetLogs();
+  data_->push_back(0x8f);
+  data_->push_back(0xff);
+  for (size_t i = 0; i < 12; i++) {
+    process_memory_.SetData(0x10004 + i * 4, i + 0x20);
+  }
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10034, 0x11);
+  process_memory_.SetData(0x10038, 0x22);
+  process_memory_.SetData(0x1003c, 0x33);
+  ASSERT_TRUE(exidx_->Decode());
+  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++) {
+    (*regs32_)[i] = i + 1;
+  }
+
+  data_->push_back(0x90);
+  ASSERT_TRUE(exidx_->Decode());
+  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_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_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_.SetData(0x10000, 0x14);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10004, 0x20);
+  process_memory_.SetData(0x10008, 0x30);
+  process_memory_.SetData(0x1000c, 0x40);
+  process_memory_.SetData(0x10010, 0x50);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10014, 0x41);
+  process_memory_.SetData(0x10018, 0x51);
+  process_memory_.SetData(0x1001c, 0x61);
+  process_memory_.SetData(0x10020, 0x71);
+  process_memory_.SetData(0x10024, 0x81);
+  process_memory_.SetData(0x10028, 0x91);
+  process_memory_.SetData(0x1002c, 0xa1);
+  process_memory_.SetData(0x10030, 0xb1);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10000, 0x12);
+  process_memory_.SetData(0x10004, 0x22);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10008, 0x1);
+  process_memory_.SetData(0x1000c, 0x2);
+  process_memory_.SetData(0x10010, 0x3);
+  process_memory_.SetData(0x10014, 0x4);
+  process_memory_.SetData(0x10018, 0x5);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x1001c, 0x1a);
+  process_memory_.SetData(0x10020, 0x2a);
+  process_memory_.SetData(0x10024, 0x3a);
+  process_memory_.SetData(0x10028, 0x4a);
+  process_memory_.SetData(0x1002c, 0x5a);
+  process_memory_.SetData(0x10030, 0x6a);
+  process_memory_.SetData(0x10034, 0x7a);
+  process_memory_.SetData(0x10038, 0x8a);
+  process_memory_.SetData(0x1003c, 0x9a);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10000, 0x45);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x10004, 0x23);
+  process_memory_.SetData(0x10008, 0x24);
+  ASSERT_TRUE(exidx_->Decode());
+  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_.SetData(0x1000c, 0x65);
+  process_memory_.SetData(0x10010, 0x54);
+  process_memory_.SetData(0x10014, 0x43);
+  process_memory_.SetData(0x10018, 0x32);
+  ASSERT_TRUE(exidx_->Decode());
+  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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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;
+      }
+    }
+  }
+}
+
+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..021765a
--- /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_.SetData(0x1000, 0x7fff2340);
+  elf_memory_.SetData(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_.SetData(0x4000, 0x7ffa3000);
+  elf_memory_.SetData(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_.SetData(0x534, 0x7ffa3000);
+  elf_memory_.SetData(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_.SetData(0x4000, 0x7ffa3000);
+
+  uint32_t compact_value = 0x80a8b0b0;
+  for (size_t i = 1; i < 16; i++) {
+    elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x8201f3f4);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x8103f3f4);
+  elf_memory_.SetData(0x6238, 0x10203040);
+  elf_memory_.SetData(0x623c, 0x50607080);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData(0x5004, 0x1230);
+  elf_memory_.SetData(0x6234, 0x832132b0);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+
+  elf_memory_.Clear();
+  elf_memory_.SetData(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData(0x5004, 0x1230);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x7ffa1e48);
+  elf_memory_.SetData(0x5004, 0x7fffb1e0);
+  elf_memory_.SetData(0x1e4, 0x842132b0);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, second_read_not_compact) {
+  elf_memory_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x1);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x2);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x3);
+  elf_memory_.SetData(0x6238, 0x01112233);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x3);
+  elf_memory_.SetData(0x6238, 0x05112233);
+  elf_memory_.SetData(0x623c, 0x01020304);
+  elf_memory_.SetData(0x6240, 0x05060708);
+  elf_memory_.SetData(0x6244, 0x090a0b0c);
+  elf_memory_.SetData(0x6248, 0x0d0e0f10);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x100);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData(0x5004, 0x100);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData(0x5104, 0x1);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+
+  elf_memory_.SetData(0x5108, 0x01010203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, malformed) {
+  elf_memory_.SetData(0x5000, 0x100);
+  elf_memory_.SetData(0x5004, 0x100);
+  elf_memory_.SetData(0x5104, 0x1);
+  elf_memory_.SetData(0x5108, 0x06010203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
+
+  elf_memory_.Clear();
+  elf_memory_.SetData(0x5000, 0x100);
+  elf_memory_.SetData(0x5004, 0x100);
+  elf_memory_.SetData(0x5104, 0x1);
+  elf_memory_.SetData(0x5108, 0x81060203);
+  ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
+  ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
+}
+
+TEST_F(ArmExidxExtractTest, cant_unwind_log) {
+  elf_memory_.SetData(0x1000, 0x7fff2340);
+  elf_memory_.SetData(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_.SetData(0x4000, 0x7ffa3000);
+  elf_memory_.SetData(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_.SetData(0x5000, 0x1234);
+  elf_memory_.SetData(0x5004, 0x00001230);
+  elf_memory_.SetData(0x6234, 0x2);
+  elf_memory_.SetData(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/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/init/seccomp.h b/libunwindstack/tests/LogFake.h
similarity index 66%
copy from init/seccomp.h
copy to libunwindstack/tests/LogFake.h
index cda7a89..006d393 100644
--- a/init/seccomp.h
+++ b/libunwindstack/tests/LogFake.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * 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.
@@ -14,9 +14,13 @@
  * limitations under the License.
  */
 
-#ifndef SECCOMP_H
-#define SECCOMP_H
+#ifndef _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
+#define _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
 
-bool set_seccomp_filter();
+#include <string>
 
-#endif
+void ResetLogs();
+std::string GetFakeLogBuf();
+std::string GetFakeLogPrint();
+
+#endif  // _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
diff --git a/libunwindstack/tests/MapsTest.cpp b/libunwindstack/tests/MapsTest.cpp
new file mode 100644
index 0000000..216873f
--- /dev/null
+++ b/libunwindstack/tests/MapsTest.cpp
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sys/mman.h>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "Maps.h"
+
+#include "LogFake.h"
+
+class MapsTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+  }
+};
+
+TEST_F(MapsTest, parse_permissions) {
+  MapsBuffer maps("1000-2000 ---- 00000000 00:00 0\n"
+                  "2000-3000 r--- 00000000 00:00 0\n"
+                  "3000-4000 -w-- 00000000 00:00 0\n"
+                  "4000-5000 --x- 00000000 00:00 0\n"
+                  "5000-6000 rwx- 00000000 00:00 0\n");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(5U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(PROT_NONE, it->flags);
+  ASSERT_EQ(0x1000U, it->start);
+  ASSERT_EQ(0x2000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_READ, it->flags);
+  ASSERT_EQ(0x2000U, it->start);
+  ASSERT_EQ(0x3000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_WRITE, it->flags);
+  ASSERT_EQ(0x3000U, it->start);
+  ASSERT_EQ(0x4000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_EXEC, it->flags);
+  ASSERT_EQ(0x4000U, it->start);
+  ASSERT_EQ(0x5000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, it->flags);
+  ASSERT_EQ(0x5000U, it->start);
+  ASSERT_EQ(0x6000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST_F(MapsTest, parse_name) {
+  MapsBuffer maps("720b29b000-720b29e000 rw-p 00000000 00:00 0\n"
+                  "720b29e000-720b29f000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
+                  "720b29f000-720b2a0000 rw-p 00000000 00:00 0");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(3U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ("", it->name);
+  ASSERT_EQ(0x720b29b000U, it->start);
+  ASSERT_EQ(0x720b29e000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ASSERT_EQ(0x720b29e000U, it->start);
+  ASSERT_EQ(0x720b29f000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ("", it->name);
+  ASSERT_EQ(0x720b29f000U, it->start);
+  ASSERT_EQ(0x720b2a0000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST_F(MapsTest, parse_offset) {
+  MapsBuffer maps("a000-e000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
+                  "e000-f000 rw-p 00a12345 00:00 0 /system/lib/fake.so\n");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(2U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(0xa000U, it->start);
+  ASSERT_EQ(0xe000U, it->end);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(0xa12345U, it->offset);
+  ASSERT_EQ(0xe000U, it->start);
+  ASSERT_EQ(0xf000U, it->end);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(maps.end(), it);
+}
+
+TEST_F(MapsTest, file_smoke) {
+  TemporaryFile tf;
+  ASSERT_TRUE(tf.fd != -1);
+
+  ASSERT_TRUE(android::base::WriteStringToFile(
+      "720b29b000-720b29e000 r-xp a0000000 00:00 0   /fake.so\n"
+      "720b2b0000-720b2e0000 r-xp b0000000 00:00 0   /fake2.so\n"
+      "720b2e0000-720b2f0000 r-xp c0000000 00:00 0   /fake3.so\n",
+      tf.path, 0660, getuid(), getgid()));
+
+  MapsFile maps(tf.path);
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(3U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(0x720b29b000U, it->start);
+  ASSERT_EQ(0x720b29e000U, it->end);
+  ASSERT_EQ(0xa0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(0x720b2b0000U, it->start);
+  ASSERT_EQ(0x720b2e0000U, it->end);
+  ASSERT_EQ(0xb0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake2.so", it->name);
+  ++it;
+  ASSERT_EQ(0x720b2e0000U, it->start);
+  ASSERT_EQ(0x720b2f0000U, it->end);
+  ASSERT_EQ(0xc0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake3.so", it->name);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST_F(MapsTest, find) {
+  MapsBuffer maps("1000-2000 r--p 00000010 00:00 0 /system/lib/fake1.so\n"
+                  "3000-4000 -w-p 00000020 00:00 0 /system/lib/fake2.so\n"
+                  "6000-8000 --xp 00000030 00:00 0 /system/lib/fake3.so\n"
+                  "a000-b000 rw-p 00000040 00:00 0 /system/lib/fake4.so\n"
+                  "e000-f000 rwxp 00000050 00:00 0 /system/lib/fake5.so\n");
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(5U, maps.Total());
+
+  ASSERT_TRUE(maps.Find(0x500) == nullptr);
+  ASSERT_TRUE(maps.Find(0x2000) == nullptr);
+  ASSERT_TRUE(maps.Find(0x5010) == nullptr);
+  ASSERT_TRUE(maps.Find(0x9a00) == nullptr);
+  ASSERT_TRUE(maps.Find(0xf000) == nullptr);
+  ASSERT_TRUE(maps.Find(0xf010) == nullptr);
+
+  MapInfo* info = maps.Find(0x1000);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x1000U, info->start);
+  ASSERT_EQ(0x2000U, info->end);
+  ASSERT_EQ(0x10U, info->offset);
+  ASSERT_EQ(PROT_READ, info->flags);
+  ASSERT_EQ("/system/lib/fake1.so", info->name);
+
+  info = maps.Find(0x3020);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x3000U, info->start);
+  ASSERT_EQ(0x4000U, info->end);
+  ASSERT_EQ(0x20U, info->offset);
+  ASSERT_EQ(PROT_WRITE, info->flags);
+  ASSERT_EQ("/system/lib/fake2.so", info->name);
+
+  info = maps.Find(0x6020);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x6000U, info->start);
+  ASSERT_EQ(0x8000U, info->end);
+  ASSERT_EQ(0x30U, info->offset);
+  ASSERT_EQ(PROT_EXEC, info->flags);
+  ASSERT_EQ("/system/lib/fake3.so", info->name);
+
+  info = maps.Find(0xafff);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0xa000U, info->start);
+  ASSERT_EQ(0xb000U, info->end);
+  ASSERT_EQ(0x40U, info->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, info->flags);
+  ASSERT_EQ("/system/lib/fake4.so", info->name);
+
+  info = maps.Find(0xe500);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0xe000U, info->start);
+  ASSERT_EQ(0xf000U, info->end);
+  ASSERT_EQ(0x50U, info->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, info->flags);
+  ASSERT_EQ("/system/lib/fake5.so", info->name);
+}
diff --git a/libunwindstack/tests/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..4f898fa
--- /dev/null
+++ b/libunwindstack/tests/MemoryFake.h
@@ -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.
+ */
+
+#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 SetData(uint64_t addr, uint32_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..ebc6118
--- /dev/null
+++ b/libunwindstack/tests/MemoryFileTest.cpp
@@ -0,0 +1,167 @@
+/*
+ * 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"
+
+#include "LogFake.h"
+
+class MemoryFileTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    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));
+}
diff --git a/libunwindstack/tests/MemoryLocalTest.cpp b/libunwindstack/tests/MemoryLocalTest.cpp
new file mode 100644
index 0000000..49ece9d
--- /dev/null
+++ b/libunwindstack/tests/MemoryLocalTest.cpp
@@ -0,0 +1,84 @@
+/*
+ * 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 "LogFake.h"
+
+class MemoryLocalTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+  }
+};
+
+TEST_F(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_F(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_F(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..fcae3a4
--- /dev/null
+++ b/libunwindstack/tests/MemoryRangeTest.cpp
@@ -0,0 +1,101 @@
+/*
+ * 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 "LogFake.h"
+#include "MemoryFake.h"
+
+class MemoryRangeTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    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..49244a5
--- /dev/null
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -0,0 +1,156 @@
+/*
+ * 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"
+
+#include "LogFake.h"
+
+class MemoryRemoteTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+  }
+
+  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..f9e8b0e
--- /dev/null
+++ b/libunwindstack/tests/RegsTest.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 <stdint.h>
+
+#include <gtest/gtest.h>
+
+#include "Regs.h"
+
+class RegsTest : public ::testing::Test {};
+
+TEST_F(RegsTest, regs32) {
+  Regs32 regs32(10, 20, 30);
+
+  ASSERT_EQ(10U, regs32.pc_reg());
+  ASSERT_EQ(20U, regs32.sp_reg());
+  ASSERT_EQ(30U, regs32.total_regs());
+
+  uint32_t* raw = reinterpret_cast<uint32_t*>(regs32.raw_data());
+  for (size_t i = 0; i < 30; i++) {
+    raw[i] = 0xf0000000 + i;
+  }
+
+  ASSERT_EQ(0xf000000aU, regs32.pc());
+  ASSERT_EQ(0xf0000014U, regs32.sp());
+
+  ASSERT_EQ(0xf0000001U, regs32[1]);
+  regs32[1] = 10;
+  ASSERT_EQ(10U, regs32[1]);
+
+  ASSERT_EQ(0xf000001dU, regs32[29]);
+}
+
+TEST_F(RegsTest, regs64) {
+  Regs64 regs64(10, 20, 30);
+
+  ASSERT_EQ(10U, regs64.pc_reg());
+  ASSERT_EQ(20U, regs64.sp_reg());
+  ASSERT_EQ(30U, regs64.total_regs());
+
+  uint64_t* raw = reinterpret_cast<uint64_t*>(regs64.raw_data());
+  for (size_t i = 0; i < 30; i++) {
+    raw[i] = 0xf123456780000000UL + i;
+  }
+
+  ASSERT_EQ(0xf12345678000000aUL, regs64.pc());
+  ASSERT_EQ(0xf123456780000014UL, regs64.sp());
+
+  ASSERT_EQ(0xf123456780000008U, regs64[8]);
+  regs64[8] = 10;
+  ASSERT_EQ(10U, regs64[8]);
+
+  ASSERT_EQ(0xf12345678000001dU, regs64[29]);
+}
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 217b8c3..0c777b1 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -12,6 +12,17 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+cc_library_headers {
+    name: "libutils_headers",
+    host_supported: true,
+    export_include_dirs: ["include"],
+    target: {
+        windows: {
+           enabled: true,
+      },
+    },
+}
+
 cc_library {
     name: "libutils",
     host_supported: true,
@@ -42,6 +53,8 @@
 
     cflags: ["-Werror"],
     include_dirs: ["external/safe-iop/include"],
+    header_libs: ["libutils_headers"],
+    export_header_lib_headers: ["libutils_headers"],
 
     arch: {
         mips: {
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/BlobCache.h b/libutils/include/utils/BlobCache.h
similarity index 100%
rename from include/utils/BlobCache.h
rename to libutils/include/utils/BlobCache.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/include/utils/Compat.h b/libutils/include/utils/Compat.h
similarity index 100%
rename from include/utils/Compat.h
rename to libutils/include/utils/Compat.h
diff --git a/include/utils/Condition.h b/libutils/include/utils/Condition.h
similarity index 100%
rename from include/utils/Condition.h
rename to libutils/include/utils/Condition.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/include/utils/FastStrcmp.h b/libutils/include/utils/FastStrcmp.h
similarity index 100%
rename from include/utils/FastStrcmp.h
rename to libutils/include/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/include/utils/Flattenable.h b/libutils/include/utils/Flattenable.h
similarity index 100%
rename from include/utils/Flattenable.h
rename to libutils/include/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/include/utils/KeyedVector.h b/libutils/include/utils/KeyedVector.h
similarity index 100%
rename from include/utils/KeyedVector.h
rename to libutils/include/utils/KeyedVector.h
diff --git a/include/utils/LinearTransform.h b/libutils/include/utils/LinearTransform.h
similarity index 100%
rename from include/utils/LinearTransform.h
rename to libutils/include/utils/LinearTransform.h
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/include/utils/Log.h b/libutils/include/utils/Log.h
similarity index 100%
rename from include/utils/Log.h
rename to libutils/include/utils/Log.h
diff --git a/include/utils/Looper.h b/libutils/include/utils/Looper.h
similarity index 100%
rename from include/utils/Looper.h
rename to libutils/include/utils/Looper.h
diff --git a/include/utils/LruCache.h b/libutils/include/utils/LruCache.h
similarity index 100%
rename from include/utils/LruCache.h
rename to libutils/include/utils/LruCache.h
diff --git a/include/utils/Mutex.h b/libutils/include/utils/Mutex.h
similarity index 100%
rename from include/utils/Mutex.h
rename to libutils/include/utils/Mutex.h
diff --git a/include/utils/NativeHandle.h b/libutils/include/utils/NativeHandle.h
similarity index 100%
rename from include/utils/NativeHandle.h
rename to libutils/include/utils/NativeHandle.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/include/utils/RWLock.h b/libutils/include/utils/RWLock.h
similarity index 100%
rename from include/utils/RWLock.h
rename to libutils/include/utils/RWLock.h
diff --git a/include/utils/RefBase.h b/libutils/include/utils/RefBase.h
similarity index 100%
rename from include/utils/RefBase.h
rename to libutils/include/utils/RefBase.h
diff --git a/include/utils/Singleton.h b/libutils/include/utils/Singleton.h
similarity index 100%
rename from include/utils/Singleton.h
rename to libutils/include/utils/Singleton.h
diff --git a/include/utils/SortedVector.h b/libutils/include/utils/SortedVector.h
similarity index 100%
rename from include/utils/SortedVector.h
rename to libutils/include/utils/SortedVector.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/include/utils/String16.h b/libutils/include/utils/String16.h
similarity index 100%
rename from include/utils/String16.h
rename to libutils/include/utils/String16.h
diff --git a/include/utils/String8.h b/libutils/include/utils/String8.h
similarity index 100%
rename from include/utils/String8.h
rename to libutils/include/utils/String8.h
diff --git a/include/utils/StrongPointer.h b/libutils/include/utils/StrongPointer.h
similarity index 100%
rename from include/utils/StrongPointer.h
rename to libutils/include/utils/StrongPointer.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/include/utils/Thread.h b/libutils/include/utils/Thread.h
similarity index 100%
rename from include/utils/Thread.h
rename to libutils/include/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/include/utils/Trace.h b/libutils/include/utils/Trace.h
similarity index 100%
rename from include/utils/Trace.h
rename to libutils/include/utils/Trace.h
diff --git a/include/utils/TypeHelpers.h b/libutils/include/utils/TypeHelpers.h
similarity index 100%
rename from include/utils/TypeHelpers.h
rename to libutils/include/utils/TypeHelpers.h
diff --git a/include/utils/Unicode.h b/libutils/include/utils/Unicode.h
similarity index 100%
rename from include/utils/Unicode.h
rename to libutils/include/utils/Unicode.h
diff --git a/include/utils/Vector.h b/libutils/include/utils/Vector.h
similarity index 100%
rename from include/utils/Vector.h
rename to libutils/include/utils/Vector.h
diff --git a/include/utils/VectorImpl.h b/libutils/include/utils/VectorImpl.h
similarity index 100%
rename from include/utils/VectorImpl.h
rename to libutils/include/utils/VectorImpl.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/tests/Vector_test.cpp b/libutils/tests/Vector_test.cpp
index 671200f..e074a92 100644
--- a/libutils/tests/Vector_test.cpp
+++ b/libutils/tests/Vector_test.cpp
@@ -74,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) {
@@ -95,20 +92,13 @@
   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) {
@@ -116,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/logcat/logcat.cpp b/logcat/logcat.cpp
index c204a16..4a171fd 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -298,6 +298,8 @@
                     "                  and individually flagged modifying adverbs can be added:\n"
                     "                    color descriptive epoch monotonic printable uid\n"
                     "                    usec UTC year zone\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"
@@ -581,24 +583,36 @@
 
 } /* 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)) {
+       return;
+    }
+    *current = name;
+}
 
 int main(int argc, char **argv)
 {
     using namespace android;
     int err;
     int hasSetLogFormat = 0;
-    int clearLog = 0;
-    int getLogSize = 0;
+    bool clearLog = false;
+    bool allSelected = false;
+    bool getLogSize = false;
+    bool getPruneList = false;
+    bool printStatistics = false;
+    bool printDividers = false;
     unsigned long setLogSize = 0;
-    int getPruneList = 0;
     char *setPruneList = NULL;
     char *setId = NULL;
-    int printStatistics = 0;
     int mode = ANDROID_LOG_RDONLY;
     const char *forceFilters = NULL;
     log_device_t* devices = NULL;
     log_device_t* dev;
-    bool printDividers = false;
     struct logger_list *logger_list;
     size_t tail_lines = 0;
     log_time tail_time(log_time::EPOCH);
@@ -710,7 +724,7 @@
             break;
 
             case 'c':
-                clearLog = 1;
+                clearLog = true;
                 mode |= ANDROID_LOG_WRONLY;
             break;
 
@@ -771,7 +785,7 @@
 
             case 'g':
                 if (!optarg) {
-                    getLogSize = 1;
+                    getLogSize = true;
                     break;
                 }
                 // FALLTHRU
@@ -813,7 +827,7 @@
 
             case 'p':
                 if (!optarg) {
-                    getPruneList = 1;
+                    getPruneList = true;
                     break;
                 }
                 // FALLTHRU
@@ -830,6 +844,7 @@
                                   (1 << LOG_ID_SYSTEM) |
                                   (1 << LOG_ID_CRASH);
                     } else if (strcmp(optarg, "all") == 0) {
+                        allSelected = true;
                         idMask = (unsigned)-1;
                     } else {
                         log_id_t log_id = android_name_to_log_id(optarg);
@@ -839,6 +854,7 @@
                             logcat_panic(HELP_TRUE,
                                          "unknown buffer %s\n", optarg);
                         }
+                        if (log_id == LOG_ID_SECURITY) allSelected = false;
                         idMask |= (1 << log_id);
                     }
                     optarg = NULL;
@@ -992,7 +1008,7 @@
                 break;
 
             case 'S':
-                printStatistics = 1;
+                printStatistics = true;
                 break;
 
             case ':':
@@ -1114,7 +1130,7 @@
         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;
         }
@@ -1136,7 +1152,7 @@
 
                     if (file.length() == 0) {
                         perror("while clearing log files");
-                        clearFail = clearFail ?: dev->device;
+                        reportErrorName(&clearFail, dev->device, allSelected);
                         break;
                     }
 
@@ -1144,17 +1160,17 @@
 
                     if (err < 0 && errno != ENOENT && clearFail == NULL) {
                         perror("while clearing log files");
-                        clearFail = dev->device;
+                        reportErrorName(&clearFail, dev->device, allSelected);
                     }
                 }
             } 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);
             }
         }
 
@@ -1163,7 +1179,7 @@
             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,
diff --git a/logcat/tests/Android.mk b/logcat/tests/Android.mk
index 99c2e0a..cb8b061 100644
--- a/logcat/tests/Android.mk
+++ b/logcat/tests/Android.mk
@@ -55,6 +55,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
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index 725d76e..081bf92 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -23,10 +23,12 @@
 #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/log_event_list.h>
@@ -53,6 +55,11 @@
 TEST(logcat, buckets) {
     FILE *fp;
 
+#undef LOG_TAG
+#define LOG_TAG "inject"
+    RLOGE("logcat.buckets");
+    sleep(1);
+
     ASSERT_TRUE(NULL != (fp = popen(
       "logcat -b radio -b events -b system -b main -d 2>/dev/null",
       "r")));
@@ -100,6 +107,32 @@
     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) {
@@ -107,35 +140,40 @@
         return;
     }
 
-    FILE *fp;
+    int count;
+    int tries = 3; // in case run too soon after system start or buffer clear
 
-    char needle[32];
-    time_t now;
-    time(&now);
-    struct tm *ptm;
+    do {
+        FILE *fp;
+
+        char needle[32];
+        time_t now;
+        time(&now);
+        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
-    strftime(needle, sizeof(needle), "[ %Y-", ptm);
+        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 = popen(
+          "logcat -v long -v year -b all -t 3 2>/dev/null",
+          "r")));
 
-    char buffer[BIG_BUFFER];
+        char buffer[BIG_BUFFER];
 
-    int count = 0;
+        count = 0;
 
-    while (fgets(buffer, sizeof(buffer), fp)) {
-        if (!strncmp(buffer, needle, strlen(needle))) {
-            ++count;
+        while (fgets(buffer, sizeof(buffer), fp)) {
+            if (!strncmp(buffer, needle, strlen(needle))) {
+                ++count;
+            }
         }
-    }
+        pclose(fp);
 
-    pclose(fp);
+    } while ((count < 3) && --tries && inject(3 - count));
 
     ASSERT_EQ(3, count);
 }
@@ -164,7 +202,8 @@
         if (!ep) {
             continue;
         }
-        ep -= 7;
+        static const size_t pid_field_width = 7;
+        ep -= pid_field_width;
         *ep = '\0';
         return cp;
     }
@@ -178,7 +217,7 @@
         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 {
@@ -195,12 +234,14 @@
         while (fgetLongTime(buffer, sizeof(buffer), fp)) {
             if (strstr(buffer, " -0700") || strstr(buffer, " -0800")) {
                 ++count;
+            } else {
+                fprintf(stderr, "ts=\"%s\"\n", buffer + 2);
             }
         }
 
         pclose(fp);
 
-    } while ((count < 3) && --tries && (sleep(1), true));
+    } while ((count < 3) && --tries && inject(3 - count));
 
     ASSERT_EQ(3, count);
 }
@@ -228,15 +269,16 @@
 }
 
 void do_tail(int num) {
-    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;
 
+    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);
+                 "logcat -v long -b all -t %d 2>/dev/null", num);
 
         FILE *fp;
         ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
@@ -249,7 +291,7 @@
 
         pclose(fp);
 
-    } while ((count < num) && --tries && (sleep(1), true));
+    } while ((count < num) && --tries && inject(num - count));
 
     ASSERT_EQ(num, count);
 }
@@ -272,56 +314,117 @@
 
 TEST(logcat, tail_time) {
     FILE *fp;
-
-    ASSERT_TRUE(NULL != (fp = popen("logcat -v long -b all -t 10 2>&1", "r")));
-
+    int count;
     char buffer[BIG_BUFFER];
     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;
-    int count = 0;
+    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 {
+        ASSERT_TRUE(NULL != (fp = popen("logcat"
+                                        " -v long"
+                                        " -v nsec"
+                                        " -b all"
+                                        " -t 10"
+                                        " 2>&1", "r")));
+        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);
+        pclose(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);
+    snprintf(buffer, sizeof(buffer), "logcat"
+                                     " -v long"
+                                     " -v nsec"
+                                     " -b all"
+                                     " -t '%s'"
+                                     " 2>&1",
+                                     first_timestamp);
     ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
 
     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);
 
+    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);
 }
@@ -704,7 +807,7 @@
     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 -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);
@@ -726,9 +829,15 @@
     }
     char *line = NULL;
     char *last_line = NULL; // this line is allowed to stutter, one-line overlap
-    char *second_last_line = NULL;
+    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;
@@ -746,6 +855,7 @@
     if (!second_last_line) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
         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
@@ -755,6 +865,8 @@
     if (ret) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
         EXPECT_FALSE(IsFalse(system(command), command));
+        free(second_last_line);
+        free(first_line);
         return;
     }
     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
@@ -762,6 +874,8 @@
     if (!dir) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
         EXPECT_FALSE(IsFalse(system(command), command));
+        free(second_last_line);
+        free(first_line);
         return;
     }
     struct dirent *entry;
@@ -791,13 +905,18 @@
     }
     if (count > 1) {
         char *brk = strpbrk(second_last_line, "\r\n");
-        if (!brk) {
-            brk = second_last_line + strlen(second_last_line);
-        }
-        fprintf(stderr, "\"%.*s\" occured %u times\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);
+        }
     }
     free(second_last_line);
+    free(first_line);
 
     snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
     EXPECT_FALSE(IsFalse(system(command), command));
@@ -1412,3 +1531,22 @@
         EXPECT_TRUE(End_to_End(sync.tagStr, ""));
     }
 }
+
+static bool reportedSecurity(const char* command) {
+    FILE* fp = popen(command, "r");
+    if (!fp) return true;
+
+    std::string ret;
+    bool val = android::base::ReadFdToString(fileno(fp), &ret);
+    pclose(fp);
+
+    if (!val) return true;
+    return std::string::npos != ret.find("'security'");
+}
+
+TEST(logcat, security) {
+    EXPECT_FALSE(reportedSecurity("logcat -b all -g 2>&1"));
+    EXPECT_TRUE(reportedSecurity("logcat -b security -g 2>&1"));
+    EXPECT_TRUE(reportedSecurity("logcat -b security -c 2>&1"));
+    EXPECT_TRUE(reportedSecurity("logcat -b security -G 256K 2>&1"));
+}
diff --git a/logd/Android.mk b/logd/Android.mk
index 2da9782..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 := \
@@ -38,12 +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 -DCHATTY_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 52c6742..74e0ea5 100644
--- a/logd/CommandListener.cpp
+++ b/logd/CommandListener.cpp
@@ -15,6 +15,7 @@
  */
 
 #include <arpa/inet.h>
+#include <ctype.h>
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -47,6 +48,7 @@
     registerCmd(new GetStatisticsCmd(buf));
     registerCmd(new SetPruneListCmd(buf));
     registerCmd(new GetPruneListCmd(buf));
+    registerCmd(new GetEventTagCmd(buf));
     registerCmd(new ReinitCmd());
     registerCmd(new ExitCmd(this));
 }
@@ -284,6 +286,41 @@
     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;
+    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;
+        }
+    }
+
+    cli->sendMsg(package_string(mBuf.formatGetEventTag(uid,
+                                                       name, format)).c_str());
+
+    return 0;
+}
+
 CommandListener::ReinitCmd::ReinitCmd() : LogCommand("reinit") {
 }
 
diff --git a/logd/CommandListener.h b/logd/CommandListener.h
index 5d50177..39de03b 100644
--- a/logd/CommandListener.h
+++ b/logd/CommandListener.h
@@ -61,6 +61,7 @@
     LogBufferCmd(GetStatistics);
     LogBufferCmd(GetPruneList);
     LogBufferCmd(SetPruneList);
+    LogBufferCmd(GetEventTag);
 
 #define LogCmd(name)                                             \
     class name##Cmd : public LogCommand {                        \
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index cc65d47..7613c1e 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -199,15 +199,13 @@
     if (log_id != LOG_ID_SECURITY) {
         int prio = ANDROID_LOG_INFO;
         const char *tag = NULL;
-        size_t len = 0;
         if (log_id == LOG_ID_EVENTS) {
-            tag = android::tagToName(&len, elem->getTag());
+            tag = tagToName(elem->getTag());
         } else {
             prio = *msg;
             tag = msg + 1;
-            len = strlen(tag);
         }
-        if (!__android_log_is_loggable_len(prio, tag, len, ANDROID_LOG_VERBOSE)) {
+        if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
             // Log traffic received to total
             pthread_mutex_lock(&mLogElementsLock);
             stats.add(elem);
@@ -1100,6 +1098,10 @@
         }
     }
 
+    // Help detect if the valid message before is from the same source so
+    // we can differentiate chatty filter types.
+    pid_t lastTid[LOG_ID_MAX] = { 0 };
+
     for (; it != mLogElements.end(); ++it) {
         LogBufferElement *element = *it;
 
@@ -1126,10 +1128,19 @@
             }
         }
 
+        bool sameTid = lastTid[element->getLogId()] == element->getTid();
+        // Dropped (chatty) immediately following a valid log from the
+        // same source in the same log buffer indicates we have a
+        // multiple identical squash.  chatty that differs source
+        // is due to spam filter.  chatty to chatty of different
+        // source is also due to spam filter.
+        lastTid[element->getLogId()] = (element->getDropped() && !sameTid) ?
+                0 : element->getTid();
+
         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;
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index 932d55f..da63e12 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -27,6 +27,7 @@
 #include <sysutils/SocketClient.h>
 
 #include "LogBufferElement.h"
+#include "LogTags.h"
 #include "LogTimes.h"
 #include "LogStatistics.h"
 #include "LogWhiteBlackList.h"
@@ -99,6 +100,8 @@
 
     bool monotonic;
 
+    LogTags tags;
+
     LogBufferElement* lastLoggedElements[LOG_ID_MAX];
     LogBufferElement* droppedElements[LOG_ID_MAX];
     void log(LogBufferElement* elem);
@@ -133,6 +136,12 @@
     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);
+    }
+    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); }
diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp
index 5e37a30..a651fd4 100644
--- a/logd/LogBufferElement.cpp
+++ b/logd/LogBufferElement.cpp
@@ -113,8 +113,8 @@
 }
 
 // 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_len(ANDROID_LOG_INFO,
@@ -123,7 +123,7 @@
         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);
     parent->unlock();
@@ -165,8 +165,9 @@
         }
     }
     // 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 : "",
+                          commName ? commName : "", type,
                           mDropped, (mDropped > 1) ? "s" : "");
 
     size_t hdrLen;
@@ -198,7 +199,7 @@
     }
 
     snprintf(buffer + hdrLen, len + 1, format_uid, mUid, name ? name : "",
-             commName ? commName : "",
+             commName ? commName : "", type,
              mDropped, (mDropped > 1) ? "s" : "");
     free(const_cast<char *>(name));
     free(const_cast<char *>(commName));
@@ -206,8 +207,8 @@
     return retval;
 }
 
-uint64_t LogBufferElement::flushTo(SocketClient *reader, LogBuffer *parent,
-                                   bool privileged) {
+uint64_t LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent,
+                                   bool privileged, bool lastSame) {
     struct logger_entry_v4 entry;
 
     memset(&entry, 0, sizeof(struct logger_entry_v4));
@@ -229,7 +230,7 @@
     char *buffer = NULL;
 
     if (!mMsg) {
-        entry.len = populateDroppedMessage(buffer, parent);
+        entry.len = populateDroppedMessage(buffer, parent, lastSame);
         if (!entry.len) {
             return mSequence;
         }
diff --git a/logd/LogBufferElement.h b/logd/LogBufferElement.h
index f8ffacd..bd98b9c 100644
--- a/logd/LogBufferElement.h
+++ b/logd/LogBufferElement.h
@@ -53,8 +53,9 @@
     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,
@@ -86,7 +87,8 @@
     log_time getRealTime(void) const { return mRealTime; }
 
     static const uint64_t FLUSH_ERROR;
-    uint64_t flushTo(SocketClient *writer, LogBuffer *parent, bool privileged);
+    uint64_t flushTo(SocketClient* writer, LogBuffer* parent,
+                     bool privileged, bool lastSame);
 };
 
 #endif
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 273150e..7e0a6b7 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -452,12 +452,11 @@
         name = android::base::StringPrintf("%7u/%u",
                                            getKey(), uid);
     }
-    size_t len = 0;
-    const char *nameTmp = getName(len);
+    const char *nameTmp = getName();
     if (nameTmp) {
         name += android::base::StringPrintf(
-            "%*s%.*s", (int)std::max(14 - name.length(), (size_t)1),
-            "", (int)len, nameTmp);
+            "%*s%s", (int)std::max(14 - name.length(), (size_t)1),
+            "", nameTmp);
     }
 
     std::string size = android::base::StringPrintf("%zu",
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 7acef6d..777dc33 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -413,7 +413,7 @@
     const uint32_t&getKey() const { return tag; }
     const pid_t&getPid() const { return pid; }
     const uid_t&getUid() const { return uid; }
-    const char*getName(size_t &len) const { return android::tagToName(&len, tag); }
+    const char*getName() const { return android::tagToName(tag); }
 
     inline void add(LogBufferElement *element) {
         if (uid != element->getUid()) {
diff --git a/logd/LogTags.cpp b/logd/LogTags.cpp
new file mode 100644
index 0000000..a109592
--- /dev/null
+++ b/logd/LogTags.cpp
@@ -0,0 +1,884 @@
+/*
+ * 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 <private/android_filesystem_config.h>
+#include <private/android_logger.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::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..37a6d96
--- /dev/null
+++ b/logd/LogTags.h
@@ -0,0 +1,118 @@
+/*
+ * 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 <unordered_map>
+#include <unordered_set>
+#include <string>
+
+#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;
+    // 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/LogUtils.h b/logd/LogUtils.h
index 70f24e4..f044b27 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -39,8 +39,9 @@
 char *pidToName(pid_t pid);
 char *tidToName(pid_t tid);
 
-// Furnished in main.cpp. Thread safe.
-const char *tagToName(size_t *len, uint32_t tag);
+// Furnished in LogTags.cpp. Thread safe.
+const char *tagToName(uint32_t tag);
+void ReReadEventLogTags();
 
 // Furnished by LogKlog.cpp.
 const char* strnstr(const char* s, size_t len, const char* needle);
diff --git a/logd/event.logtags b/logd/event.logtags
index 0d24df0..39063a9 100644
--- a/logd/event.logtags
+++ b/logd/event.logtags
@@ -35,3 +35,4 @@
 
 1003  auditd (avc|3)
 1004  chatty (dropped|3)
+1005  tag_def (tag|1),(name|3),(format|3)
diff --git a/logd/logd.rc b/logd/logd.rc
index 54349dd..ee89b83 100644
--- a/logd/logd.rc
+++ b/logd/logd.rc
@@ -14,3 +14,10 @@
     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 5878f15..2551f2e 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -244,7 +244,7 @@
     // 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.
+    (void)setuid(AID_LOGD);   // access to everything logd, eg /data/misc/logd
 
     while (reinit_running && !sem_wait(&reinit) && reinit_running) {
 
@@ -271,6 +271,7 @@
             logBuf->init();
             logBuf->initPrune(NULL);
         }
+        android::ReReadEventLogTags();
     }
 
     return NULL;
@@ -304,24 +305,6 @@
     sem_post(&reinit);
 }
 
-// tagToName converts an events tag into a name
-const char *android::tagToName(size_t *len, uint32_t tag) {
-    static const EventTagMap *map;
-
-    if (!map) {
-        sem_wait(&sem_name);
-        if (!map) {
-            map = android_openEventTagMap(NULL);
-        }
-        sem_post(&sem_name);
-        if (!map) {
-            if (len) len = 0;
-            return NULL;
-        }
-    }
-    return android_lookupEventTag_len(map, len, tag);
-}
-
 static void readDmesg(LogAudit *al, LogKlog *kl) {
     if (!al && !kl) {
         return;
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 13a7922..adf583b 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -39,12 +39,8 @@
 #include "../libaudit.h" // pickup AUDIT_RATE_LIMIT_*
 #include "../LogReader.h" // pickup LOGD_SNDTIMEO
 
-/*
- * returns statistics
- */
-static void my_android_logger_get_statistics(char *buf, size_t len)
+static void send_to_control(char* buf, size_t len)
 {
-    snprintf(buf, len, "getStatistics 0 1 2 3 4");
     int sock = socket_local_client("logd",
                                    ANDROID_SOCKET_NAMESPACE_RESERVED,
                                    SOCK_STREAM);
@@ -52,7 +48,7 @@
         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;
@@ -74,6 +70,15 @@
     }
 }
 
+/*
+ * 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);
+}
+
 static void alloc_statistics(char **buffer, size_t *length)
 {
     size_t len = 8192;
@@ -816,6 +821,44 @@
     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_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);
@@ -853,11 +896,13 @@
 
     int expected_count = (count < 2) ? count : 2;
     int expected_chatty_count = (count <= 2) ? 0 : 1;
-    int expected_expire_count = (count < 2) ? 0 : (count - 2);
+    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 (;;) {
@@ -887,11 +932,16 @@
             ++chatty_count;
             // int len = get4LE(eventData + 4 + 1);
             log_msg.buf[LOGGER_ENTRY_MAX_LEN] = '\0';
-            const char *cp = strstr(eventData + 4 + 1 + 4, " expire ");
-            if (!cp) continue;
-            unsigned val = 0;
-            sscanf(cp, " expire %u lines", &val);
-            expire_count += val;
+            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;
+            }
         }
     }
 
@@ -900,6 +950,7 @@
     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);
 }
 
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 1ae43fb..c300c1c 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -360,9 +360,6 @@
     start vold
     installkey /data
 
-    # start tombstoned to record early-boot crashes.
-    start tombstoned
-
     # Start bootcharting as soon as possible after the data partition is
     # mounted to collect more data.
     mkdir /data/bootchart 0755 shell shell
@@ -486,7 +483,7 @@
     # 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
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index 7084355..66e7750 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -13,7 +13,7 @@
     onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
 
-service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload
+service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
     class main
     priority -20
     user root
diff --git a/storaged/Android.mk b/storaged/Android.mk
index db97040..5abfb7a 100644
--- a/storaged/Android.mk
+++ b/storaged/Android.mk
@@ -2,20 +2,31 @@
 
 LOCAL_PATH := $(call my-dir)
 
-LIBSTORAGED_SHARED_LIBRARIES := libbinder libbase libutils libcutils liblog libsysutils libcap
+LIBSTORAGED_SHARED_LIBRARIES := \
+    libbinder \
+    libbase \
+    libutils \
+    libcutils \
+    liblog \
+    libsysutils \
+    libcap \
+    libpackagelistparser \
+    libbatteryservice \
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := storaged.cpp \
-                  storaged_service.cpp \
-                  storaged_utils.cpp \
-                  EventLogTags.logtags
+LOCAL_SRC_FILES := \
+    storaged.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)
diff --git a/storaged/EventLogTags.logtags b/storaged/EventLogTags.logtags
index ee92dd1..2e25d4a 100644
--- a/storaged/EventLogTags.logtags
+++ b/storaged/EventLogTags.logtags
@@ -36,4 +36,4 @@
 
 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)
+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..70e6026
--- /dev/null
+++ b/storaged/README.properties
@@ -0,0 +1,6 @@
+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.emmc_info_pub     # interval storaged publish emmc info, 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
index 521cc9e..7e5048f 100644
--- a/storaged/include/storaged.h
+++ b/storaged/include/storaged.h
@@ -17,13 +17,21 @@
 #ifndef _STORAGED_H_
 #define _STORAGED_H_
 
-#include <queue>
 #include <semaphore.h>
 #include <stdint.h>
+#include <time.h>
+
+#include <queue>
 #include <string>
 #include <unordered_map>
 #include <vector>
 
+#include <batteryservice/IBatteryPropertiesListener.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
 
@@ -36,6 +44,14 @@
 #define debuginfo(...)
 #endif
 
+#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
@@ -113,28 +129,6 @@
     }
 };
 
-class tasks_t {
-private:
-    FRIEND_TEST(storaged_test, tasks_t);
-    sem_t mSem;
-    // hashmap for all running tasks w/ pid as key
-    std::unordered_map<uint32_t, struct task_info> mRunning;
-    // hashmap for all tasks that have been killed (categorized by cmd) w/ cmd as key
-    std::unordered_map<std::string, struct task_info> mOld;
-    std::unordered_map<std::uint32_t, struct task_info> get_running_tasks();
-public:
-    tasks_t() {
-        sem_init(&mSem, 0, 1); // TODO: constructor don't have a return value, what if sem_init fails
-    }
-
-    ~tasks_t() {
-        sem_destroy(&mSem);
-    }
-
-    void update_running_tasks(void);
-    std::vector<struct task_info> get_tasks(void);
-};
-
 class stream_stats {
 private:
     double mSum;
@@ -165,6 +159,8 @@
 #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);
@@ -260,51 +256,39 @@
 #define DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT ( 60 )
 #define DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH ( 3600 )
 #define DEFAULT_PERIODIC_CHORES_INTERVAL_EMMC_INFO_PUBLISH ( 86400 )
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO ( 3600 )
+
+// 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_emmc_info_publish;
-    bool proc_taskio_readable;  // are /proc/[pid]/{io, comm, cmdline, stat} all readable
+    int periodic_chores_interval_uid_io;
+    bool proc_uid_io_available;      // whether uid_io is accessible
     bool emmc_available;        // whether eMMC est_csd file is readable
     bool diskstats_available;   // whether diskstats is accessible
+    int event_time_check_usec;  // check how much cputime spent in event loop
 };
 
-class storaged_t {
+class storaged_t : public BnBatteryPropertiesListener {
 private:
     time_t mTimer;
     storaged_config mConfig;
     disk_stats_publisher mDiskStats;
     disk_stats_monitor mDsm;
     emmc_info_t mEmmcInfo;
-    tasks_t mTasks;
+    uid_monitor mUidm;
     time_t mStarttime;
 public:
     storaged_t(void);
     ~storaged_t() {}
     void event(void);
+    void event_checked(void);
     void pause(void) {
         sleep(mConfig.periodic_chores_interval_unit);
     }
-    void set_unit_interval(int unit) {
-        mConfig.periodic_chores_interval_unit = unit;
-    }
-    void set_diskstats_interval(int disk_stats) {
-        mConfig.periodic_chores_interval_disk_stats_publish = disk_stats;
-    }
-    void set_emmc_interval(int emmc_info) {
-        mConfig.periodic_chores_interval_emmc_info_publish = emmc_info;
-    }
-    std::vector<struct task_info> get_tasks(void) {
-        // There could be a race when get_tasks() and the main thread is updating at the same time
-        // While update_running_tasks() is updating the critical sections at the end of the function
-        // all together atomically, the final state of task_t can only be either the main thread's
-        // update or this update. Since the race can only occur when both threads are updating
-        // "simultaneously", either final state is acceptable.
-        mTasks.update_running_tasks();
-        return mTasks.get_tasks();
-    }
-
     void set_privileged_fds(int fd_emmc) {
         mEmmcInfo.set_emmc_fd(fd_emmc);
     }
@@ -312,11 +296,22 @@
     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, std::vector<struct uid_record>> get_uid_records(int hours) {
+        return mUidm.dump(hours);
+    }
+
+    void init_battery_service();
+    virtual void batteryPropertiesChanged(struct BatteryProperties props);
 };
 
 // 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_service.h b/storaged/include/storaged_service.h
index 64a9c81..a8ddf4c 100644
--- a/storaged/include/storaged_service.h
+++ b/storaged/include/storaged_service.h
@@ -30,10 +30,10 @@
 class IStoraged : public IInterface {
 public:
     enum {
-        DUMPTASKS = IBinder::FIRST_CALL_TRANSACTION,
+        DUMPUIDS  = IBinder::FIRST_CALL_TRANSACTION,
     };
     // Request the service to run the test function
-    virtual std::vector<struct task_info> dump_tasks(const char* option) = 0;
+    virtual std::vector<struct uid_info> dump_uids(const char* option) = 0;
 
     DECLARE_META_INTERFACE(Storaged);
 };
@@ -42,7 +42,7 @@
 class BpStoraged : public BpInterface<IStoraged> {
 public:
     BpStoraged(const sp<IBinder>& impl) : BpInterface<IStoraged>(impl){};
-    virtual std::vector<struct task_info> dump_tasks(const char* option);
+    virtual std::vector<struct uid_info> dump_uids(const char* option);
 };
 
 // Server
@@ -51,7 +51,8 @@
 };
 
 class Storaged : public BnStoraged {
-    virtual std::vector<struct task_info> dump_tasks(const char* option);
+    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();
diff --git a/storaged/include/storaged_uid_monitor.h b/storaged/include/storaged_uid_monitor.h
new file mode 100644
index 0000000..07e6daa
--- /dev/null
+++ b/storaged/include/storaged_uid_monitor.h
@@ -0,0 +1,101 @@
+/*
+ * 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)
+};
+
+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;
+};
+
+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, timestamp -> vector of events
+    std::map<uint64_t, std::vector<struct uid_record>> 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;
+
+    // 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, std::vector<struct uid_record>> dump(int hours);
+    // called by battery properties listener
+    void set_charger_state(charger_stat_t stat);
+    // called by storaged periodic_chore
+    void report();
+};
+
+#endif /* _STORAGED_UID_MONITOR_H_ */
diff --git a/storaged/include/storaged_utils.h b/storaged/include/storaged_utils.h
index 83538c2..2161c40 100644
--- a/storaged/include/storaged_utils.h
+++ b/storaged/include/storaged_utils.h
@@ -31,15 +31,14 @@
 void add_disk_stats(struct disk_stats* src, struct disk_stats* dst);
 bool parse_emmc_ecsd(int ext_csd_fd, struct emmc_info* info);
 
-// Task I/O
-bool parse_task_info(uint32_t pid, struct task_info* info);
-void sort_running_tasks_info(std::vector<struct task_info> &tasks);
+// UID I/O
+void sort_running_uids_info(std::vector<struct uid_info> &uids);
 
 // Logging
-void log_console_running_tasks_info(std::vector<struct task_info> tasks);
+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_ */
\ No newline at end of file
+#endif /* _STORAGED_UTILS_H_ */
diff --git a/storaged/main.cpp b/storaged/main.cpp
index 0cb0f5f..1103df2 100644
--- a/storaged/main.cpp
+++ b/storaged/main.cpp
@@ -61,8 +61,7 @@
     if (cap_clear(caps.get()) < 0) return -1;
     cap_value_t cap_value[] = {
         CAP_SETGID,
-        CAP_SETUID,
-        CAP_SYS_PTRACE // allow access to proc/<pid>/io as non-root user
+        CAP_SETUID
     };
     if (cap_set_flag(caps.get(), CAP_PERMITTED,
                      arraysize(cap_value), cap_value,
@@ -73,10 +72,6 @@
     if (cap_set_proc(caps.get()) < 0)
         return -1;
 
-    gid_t groups[] = { AID_READPROC };
-
-    if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) == -1) return -1;
-
     if (setgid(AID_SYSTEM) != 0) return -1;
 
     if (setuid(AID_SYSTEM) != 0) return -1;
@@ -93,10 +88,12 @@
 void* storaged_main(void* s) {
     storaged_t* storaged = (storaged_t*)s;
 
+    storaged->init_battery_service();
+
     LOG_TO(SYSTEM, INFO) << "storaged: Start";
 
     for (;;) {
-        storaged->event();
+        storaged->event_checked();
         storaged->pause();
     }
     return NULL;
@@ -104,24 +101,14 @@
 
 static void help_message(void) {
     printf("usage: storaged [OPTION]\n");
-    printf("  -d    --dump                  Dump task I/O usage to stdout\n");
+    printf("  -u    --uid                   Dump uid I/O usage to stdout\n");
     printf("  -s    --start                 Start storaged (default)\n");
-    printf("        --emmc=INTERVAL         Set publish interval of emmc lifetime information (in days)\n");
-    printf("        --diskstats=INTERVAL    Set publish interval of diskstats (in hours)\n");
-    printf("        --unit=INTERVAL         Set storaged's refresh interval (in seconds)\n");
     fflush(stdout);
 }
 
-#define HOUR_TO_SEC ( 3600 )
-#define DAY_TO_SEC ( 3600 * 24 )
-
 int main(int argc, char** argv) {
     int flag_main_service = 0;
-    int flag_dump_task = 0;
-    int flag_config = 0;
-    int unit_interval = DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT;
-    int diskstats_interval = DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH;
-    int emmc_interval = DEFAULT_PERIODIC_CHORES_INTERVAL_EMMC_INFO_PUBLISH;
+    int flag_dump_uid = 0;
     int fd_emmc = -1;
     int opt;
 
@@ -130,62 +117,20 @@
         static struct option long_options[] = {
             {"start",       no_argument,        0, 's'},
             {"kill",        no_argument,        0, 'k'},
-            {"dump",        no_argument,        0, 'd'},
-            {"help",        no_argument,        0, 'h'},
-            {"unit",        required_argument,  0,  0 },
-            {"diskstats",   required_argument,  0,  0 },
-            {"emmc",        required_argument,  0,  0 }
+            {"uid",         no_argument,        0, 'u'},
+            {"help",        no_argument,        0, 'h'}
         };
-        opt = getopt_long(argc, argv, ":skdh0", long_options, &opt_idx);
+        opt = getopt_long(argc, argv, ":skdhu0", long_options, &opt_idx);
         if (opt == -1) {
             break;
         }
 
         switch (opt) {
-        case 0:
-            printf("option %s", long_options[opt_idx].name);
-            if (optarg) {
-                printf(" with arg %s", optarg);
-                if (strcmp(long_options[opt_idx].name, "unit") == 0) {
-                    unit_interval = atoi(optarg);
-                    if (unit_interval == 0) {
-                        fprintf(stderr, "Invalid argument. Option %s requires an integer argument greater than 0.\n",
-                                long_options[opt_idx].name);
-                        help_message();
-                        return -1;
-                    }
-                } else if (strcmp(long_options[opt_idx].name, "diskstats") == 0) {
-                    diskstats_interval = atoi(optarg) * HOUR_TO_SEC;
-                    if (diskstats_interval == 0) {
-                        fprintf(stderr, "Invalid argument. Option %s requires an integer argument greater than 0.\n",
-                                long_options[opt_idx].name);
-                        help_message();
-                        return -1;
-                    }
-
-                } else if (strcmp(long_options[opt_idx].name, "emmc") == 0) {
-                    emmc_interval = atoi(optarg) * DAY_TO_SEC;
-                    if (diskstats_interval == 0) {
-                        fprintf(stderr, "Invalid argument. Option %s requires an integer argument greater than 0.\n",
-                                long_options[opt_idx].name);
-                        help_message();
-                        return -1;
-                    }
-                }
-                flag_config = 1;
-            } else {
-                fprintf(stderr, "Invalid argument. Option %s requires an argument.\n",
-                        long_options[opt_idx].name);
-                help_message();
-                return -1;
-            }
-            printf("\n");
-            break;
         case 's':
             flag_main_service = 1;
             break;
-        case 'd':
-            flag_dump_task = 1;
+        case 'u':
+            flag_dump_uid = 1;
             break;
         case 'h':
             help_message();
@@ -202,18 +147,12 @@
         flag_main_service = 1;
     }
 
-    if (flag_main_service && flag_dump_task) {
+    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_config && flag_dump_task) {
-        fprintf(stderr, "Invalid arguments. Cannot set configs in \'dump\' option.\n");
-        help_message();
-        return -1;
-    }
-
     if (flag_main_service) { // start main thread
         static const char mmc0_ext_csd[] = "/d/mmc0/mmc0:0001/ext_csd";
         fd_emmc = android_get_control_file(mmc0_ext_csd);
@@ -226,12 +165,6 @@
 
         storaged.set_privileged_fds(fd_emmc);
 
-        if (flag_config) {
-            storaged.set_unit_interval(unit_interval);
-            storaged.set_diskstats_interval(diskstats_interval);
-            storaged.set_emmc_interval(emmc_interval);
-        }
-
         // Start the main thread of storaged
         pthread_t storaged_main_thread;
         errno = pthread_create(&storaged_main_thread, NULL, storaged_main, &storaged);
@@ -250,30 +183,21 @@
         return 0;
     }
 
-    if (flag_dump_task) {
+    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 task_info> res = storaged_service->dump_tasks(NULL);
+        std::vector<struct uid_info> res = storaged_service->dump_uids(NULL);
 
         if (res.size() == 0) {
-            fprintf(stderr, "Task I/O is not readable in this version of kernel.\n");
+            fprintf(stderr, "UID I/O is not readable in this version of kernel.\n");
             return 0;
         }
 
-        time_t starttime = storaged.get_starttime();
-
-        if (starttime == (time_t)-1) {
-            fprintf(stderr, "Unknown start time\n");
-        } else {
-            char* time_str = ctime(&starttime);
-            printf("Application I/O was collected by storaged since %s", time_str);
-        }
-
-        sort_running_tasks_info(res);
-        log_console_running_tasks_info(res);
+        sort_running_uids_info(res);
+        log_console_running_uids_info(res);
 
         return 0;
     }
diff --git a/storaged/storaged.cpp b/storaged/storaged.cpp
index 8f7ce62..2f02074 100644
--- a/storaged/storaged.cpp
+++ b/storaged/storaged.cpp
@@ -21,6 +21,11 @@
 #include <unistd.h>
 
 #include <android-base/logging.h>
+#include <batteryservice/BatteryServiceConstants.h>
+#include <batteryservice/IBatteryPropertiesRegistrar.h>
+#include <binder/IServiceManager.h>
+#include <cutils/properties.h>
+#include <log/log.h>
 
 #include <storaged.h>
 #include <storaged_utils.h>
@@ -155,6 +160,43 @@
     }
 }
 
+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() {
+    sp<IBatteryPropertiesRegistrar> 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);
+}
+
 /* storaged_t */
 storaged_t::storaged_t(void) {
     mConfig.emmc_available = (access(EMMC_ECSD_PATH, R_OK) >= 0);
@@ -165,18 +207,22 @@
         mConfig.diskstats_available = true;
     }
 
-    mConfig.proc_taskio_readable = true;
-    const char* test_paths[] = {"/proc/1/io", "/proc/1/comm", "/proc/1/cmdline", "/proc/1/stat"};
-    for (uint i = 0; i < sizeof(test_paths) / sizeof(const char*); ++i) {
-        if (access(test_paths[i], R_OK) < 0) {
-            mConfig.proc_taskio_readable = false;
-            break;
-        }
-    }
+    mConfig.proc_uid_io_available = (access(UID_IO_STATS_PATH, R_OK) == 0);
 
-    mConfig.periodic_chores_interval_unit = DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT;
-    mConfig.periodic_chores_interval_disk_stats_publish = DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH;
-    mConfig.periodic_chores_interval_emmc_info_publish = DEFAULT_PERIODIC_CHORES_INTERVAL_EMMC_INFO_PUBLISH;
+    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_emmc_info_publish =
+        property_get_int32("ro.storaged.emmc_info_pub", DEFAULT_PERIODIC_CHORES_INTERVAL_EMMC_INFO_PUBLISH);
+
+    mConfig.periodic_chores_interval_uid_io =
+        property_get_int32("ro.storaged.uid_io.interval", DEFAULT_PERIODIC_CHORES_INTERVAL_UID_IO);
 
     mStarttime = time(NULL);
 }
@@ -190,15 +236,49 @@
         }
     }
 
-    if (mConfig.proc_taskio_readable) {
-        mTasks.update_running_tasks();
-    }
-
     if (mConfig.emmc_available && mTimer &&
             (mTimer % mConfig.periodic_chores_interval_emmc_info_publish) == 0) {
         mEmmcInfo.update();
         mEmmcInfo.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
index a8fa5a7..53fdb85 100644
--- a/storaged/storaged.rc
+++ b/storaged/storaged.rc
@@ -1,5 +1,4 @@
 service storaged /system/bin/storaged
     class main
     file /d/mmc0/mmc0:0001/ext_csd r
-    group root readproc
     writepid /dev/cpuset/system-background/tasks
diff --git a/storaged/storaged_service.cpp b/storaged/storaged_service.cpp
index aa38ceb..6635431 100644
--- a/storaged/storaged_service.cpp
+++ b/storaged/storaged_service.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <stdint.h>
+
 #include <vector>
 
 #include <binder/IBinder.h>
@@ -21,38 +23,42 @@
 
 #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>
 
 extern storaged_t storaged;
 
-std::vector<struct task_info> BpStoraged::dump_tasks(const char* /*option*/) {
+std::vector<struct uid_info> BpStoraged::dump_uids(const char* /*option*/) {
     Parcel data, reply;
     data.writeInterfaceToken(IStoraged::getInterfaceDescriptor());
 
-    remote()->transact(DUMPTASKS, data, &reply);
+    remote()->transact(DUMPUIDS, data, &reply);
 
     uint32_t res_size = reply.readInt32();
-    std::vector<struct task_info> res(res_size);
-    for (auto&& task : res) {
-        reply.read(&task, sizeof(task));
+    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) {
-    data.checkInterface(this);
-
     switch(code) {
-        case DUMPTASKS: {
-                std::vector<struct task_info> res = dump_tasks(NULL);
-
+        case DUMPUIDS: {
+                if (!data.checkInterface(this))
+                    return BAD_TYPE;
+                std::vector<struct uid_info> res = dump_uids(NULL);
                 reply->writeInt32(res.size());
-                for (auto task : res) {
-                    reply->write(&task, sizeof(task));
+                for (auto uid : res) {
+                    reply->writeInt32(uid.uid);
+                    reply->writeCString(uid.name.c_str());
+                    reply->write(&uid.io, sizeof(uid.io));
                 }
                 return NO_ERROR;
             }
@@ -61,8 +67,56 @@
             return BBinder::onTransact(code, data, reply, flags);
     }
 }
-std::vector<struct task_info> Storaged::dump_tasks(const char* /* option */) {
-    return storaged.get_tasks();
+
+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;
+    }
+
+    int hours = 0;
+    for (size_t i = 0; i < args.size(); i++) {
+        const auto& arg = args[i];
+        if (arg == String16("--hours")) {
+            if (++i >= args.size())
+                break;
+            hours = stoi(String16::std_string(args[i]));
+            continue;
+        }
+    }
+
+    const std::map<uint64_t, std::vector<struct uid_record>>& records =
+                storaged.get_uid_records(hours);
+    for (const auto& it : records) {
+        dprintf(fd, "%llu\n", (unsigned long long)it.first);
+        for (const auto& record : it.second) {
+            dprintf(fd, "%s %llu %llu %llu %llu %llu %llu %llu %llu\n",
+                record.name.c_str(),
+                (unsigned long long)record.ios.bytes[READ][FOREGROUND][CHARGER_OFF],
+                (unsigned long long)record.ios.bytes[WRITE][FOREGROUND][CHARGER_OFF],
+                (unsigned long long)record.ios.bytes[READ][BACKGROUND][CHARGER_OFF],
+                (unsigned long long)record.ios.bytes[WRITE][BACKGROUND][CHARGER_OFF],
+                (unsigned long long)record.ios.bytes[READ][FOREGROUND][CHARGER_ON],
+                (unsigned long long)record.ios.bytes[WRITE][FOREGROUND][CHARGER_ON],
+                (unsigned long long)record.ios.bytes[READ][BACKGROUND][CHARGER_ON],
+                (unsigned long long)record.ios.bytes[WRITE][BACKGROUND][CHARGER_ON]);
+        }
+    }
+    return NO_ERROR;
 }
 
 sp<IStoraged> get_storaged_service() {
@@ -75,4 +129,4 @@
     sp<IStoraged> storaged = interface_cast<IStoraged>(binder);
 
     return storaged;
-}
\ No newline at end of file
+}
diff --git a/storaged/storaged_uid_monitor.cpp b/storaged/storaged_uid_monitor.cpp
new file mode 100644
index 0000000..b46d09a
--- /dev/null
+++ b/storaged/storaged_uid_monitor.cpp
@@ -0,0 +1,235 @@
+/*
+ * 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 <sstream>
+#include <unordered_map>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.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 (!android::base::ReadFileToString(UID_IO_STATS_PATH, &buffer)) {
+        PLOG_TO(SYSTEM, ERROR) << UID_IO_STATS_PATH << ": ReadFileToString failed";
+        return uid_io_stats;
+    }
+
+    std::stringstream ss(buffer);
+    struct uid_info u;
+    bool refresh_uid = false;
+
+    while (ss >> u.uid) {
+        ss >> u.io[FOREGROUND].rchar >> u.io[FOREGROUND].wchar
+           >> u.io[FOREGROUND].read_bytes >> u.io[FOREGROUND].write_bytes
+           >> u.io[BACKGROUND].rchar >> u.io[BACKGROUND].wchar
+           >> u.io[BACKGROUND].read_bytes >> u.io[BACKGROUND].write_bytes;
+
+        if (!ss.good()) {
+            ss.clear(std::ios_base::badbit);
+            break;
+        }
+
+        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 (!ss.eof() || ss.bad()) {
+        uid_io_stats.clear();
+        LOG_TO(SYSTEM, ERROR) << "read UID IO stats failed";
+    }
+
+    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, std::vector<struct uid_record>>& records)
+{
+    int count = 0;
+    for (auto const& it : records) {
+        count += it.second.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);
+    }
+
+    std::vector<struct uid_record> 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.push_back(record);
+        }
+    }
+
+    curr_io_stats.clear();
+
+    if (new_records.empty())
+      return;
+
+    // make some room for new records
+    int overflow = records_size(records) +
+        new_records.size() - MAX_UID_RECORDS_SIZE;
+    while (overflow > 0 && records.size() > 0) {
+        overflow -= records[0].size();
+        records.erase(records.begin());
+    }
+
+    records[curr_ts].insert(records[curr_ts].end(),
+        new_records.begin(), new_records.end());
+}
+
+std::map<uint64_t, std::vector<struct uid_record>> uid_monitor::dump(int hours)
+{
+    std::unique_ptr<lock_t> lock(new lock_t(&um_lock));
+
+    std::map<uint64_t, std::vector<struct uid_record>> dump_records;
+    uint64_t first_ts = 0;
+
+    if (hours != 0) {
+        first_ts = time(NULL) - (uint64_t)hours * HOUR_TO_SEC;
+    }
+
+    dump_records.insert(records.lower_bound(first_ts), records.end());
+
+    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];
+        usage.bytes[READ][FOREGROUND][charger_stat] +=
+            uid.io[FOREGROUND].read_bytes -
+            last_uid_io_stats[uid.uid].io[FOREGROUND].read_bytes;
+        usage.bytes[READ][BACKGROUND][charger_stat] +=
+            uid.io[BACKGROUND].read_bytes -
+            last_uid_io_stats[uid.uid].io[BACKGROUND].read_bytes;
+        usage.bytes[WRITE][FOREGROUND][charger_stat] +=
+            uid.io[FOREGROUND].write_bytes -
+            last_uid_io_stats[uid.uid].io[FOREGROUND].write_bytes;
+        usage.bytes[WRITE][BACKGROUND][charger_stat] +=
+            uid.io[BACKGROUND].write_bytes -
+            last_uid_io_stats[uid.uid].io[BACKGROUND].write_bytes;;
+    }
+
+    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;
+    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
index c845ac4..1ef89af 100644
--- a/storaged/storaged_utils.cpp
+++ b/storaged/storaged_utils.cpp
@@ -41,11 +41,6 @@
 #include <storaged.h>
 #include <storaged_utils.h>
 
-#define SECTOR_SIZE ( 512 )
-#define SEC_TO_MSEC ( 1000 )
-#define MSEC_TO_USEC ( 1000 )
-#define USEC_TO_NSEC ( 1000 )
-
 bool parse_disk_stats(const char* disk_stats_path, struct disk_stats* stats) {
     // Get time
     struct timespec ts;
@@ -250,187 +245,50 @@
     return true;
 }
 
-#define PROC_DIR "/proc/"
-#define PROC_STAT_STARTTIME_IDX ( 22 ) // This index is 1 based according to the linux proc man page
-bool parse_task_info(uint32_t pid, struct task_info* info) {
-    std::string buffer;
-    std::string pid_str = std::to_string(pid);
-    info->pid = pid;
+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;
 
-    // Get task I/O
-    std::string task_io_path = android::base::StringPrintf(PROC_DIR "%s/io", pid_str.c_str());
-    if (!android::base::ReadFileToString(task_io_path, &buffer)) return false;
-
-    std::stringstream ss(buffer);
-    std::string title;
-
-    ss >> title >> info->rchar
-       >> title >> info->wchar
-       >> title >> info->syscr
-       >> title >> info->syscw
-       >> title >> info->read_bytes
-       >> title >> info->write_bytes
-       >> title >> info->cancelled_write_bytes;
-    ss.clear();
-
-    // Get cmd string
-    std::string task_cmdline_path = android::base::StringPrintf(PROC_DIR "%u/cmdline", pid);
-    if (!android::base::ReadFileToString(task_cmdline_path, &buffer)) return false;
-    strlcpy(info->cmd, android::base::Trim(buffer).c_str(), sizeof(info->cmd));
-
-    if (info->cmd[0] == '\0') {
-        std::string task_comm_path = android::base::StringPrintf(PROC_DIR "%u/comm", pid);
-        if (!android::base::ReadFileToString(task_comm_path, &buffer)) return false;
-        strlcpy(info->cmd, android::base::Trim(buffer).c_str(), sizeof(info->cmd));
-    }
-
-    // Get task start time
-    std::string task_stat_path = android::base::StringPrintf(PROC_DIR "%u/stat", pid);
-    if (!android::base::ReadFileToString(task_stat_path, &buffer)) return false;
-
-    std::vector<std::string> stat_parts = android::base::Split(buffer, " ");
-    info->starttime = atoll(stat_parts[PROC_STAT_STARTTIME_IDX - 1].c_str());
-
-    return true;
-}
-
-static bool is_pid(char* d_name) {
-    if (!d_name || d_name[0] == '\0') return false;
-    char* c = d_name;
-    while (*c) {
-        if (!isdigit(*c)) return false;
-        ++c;
-    }
-    return true;
-}
-
-static bool cmp_task_info(struct task_info i, struct task_info j) {
-    if (i.write_bytes + i.read_bytes != j.write_bytes + j.read_bytes) {
-        return i.write_bytes + i.read_bytes > j.write_bytes + j.read_bytes;
-    }
-    if (i.wchar + i.rchar != j.wchar + j.rchar) {
-        return i.wchar + i.rchar > j.wchar + j.rchar;
-    }
-    if (i.syscw + i.syscr != j.syscw + j.syscr) {
-        return i.syscw + i.syscr > j.syscw + j.syscr;
-    }
-
-    return strcmp(i.cmd, j.cmd) < 0;
-}
-
-std::unordered_map<uint32_t, struct task_info> tasks_t::get_running_tasks() {
-    std::unordered_map<uint32_t, struct task_info> retval;
-    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(PROC_DIR), closedir);
-    CHECK(dir != NULL);
-    struct dirent* dp;
-
-    for (;;) {
-        if ((dp = readdir(dir.get())) == NULL) break;
-        if (!is_pid(dp->d_name)) continue;
-
-        uint32_t pid = atol(dp->d_name);
-        struct task_info info;
-        if (parse_task_info(pid, &info)) {
-            retval[pid] = info;
+        if (l_bytes != r_bytes) {
+            return l_bytes > r_bytes;
         }
-    }
-    return retval;
-}
-
-static void add_task_info(struct task_info* src, struct task_info* dst) {
-    CHECK(strcmp(src->cmd, dst->cmd) == 0);
-
-    dst->pid = 0;
-    dst->rchar += src->rchar;
-    dst->wchar += src->wchar;
-    dst->syscr += src->syscr;
-    dst->syscw += src->syscw;
-    dst->read_bytes += src->read_bytes;
-    dst->write_bytes += src->write_bytes;
-    dst->cancelled_write_bytes += src->cancelled_write_bytes;
-    dst->starttime = 0;
-}
-
-void tasks_t::update_running_tasks(void) {
-    std::unordered_map<uint32_t, struct task_info> tasks_latest = get_running_tasks();
-    std::unordered_map<std::string, struct task_info> tasks_old = mOld;
-
-    for (auto t : mRunning) {
-        uint32_t pid = t.first;
-        // old task on mRunning still exist on tasks_latest
-        if (tasks_latest.find(pid) != tasks_latest.end() &&
-                tasks_latest[pid].starttime == t.second.starttime) {
-            continue;
-        } else {
-            // This branch will handle 2 cases:
-            // - Task get killed between the 2 samplings
-            // - Task get killed and its pid is reused
-            std::string cmd = t.second.cmd;
-            struct task_info info = t.second;
-
-            if (tasks_old.find(cmd) == tasks_old.end()) {
-                tasks_old[cmd] = info;
-            } else {
-                add_task_info(&info, &tasks_old[cmd]);
-            }
-        }
-    }
-    {   // update critical area
-        // this is really fast!
-        std::unique_ptr<lock_t> lock(new lock_t(&mSem));
-        mRunning = tasks_latest;
-        mOld = tasks_old;
-    }
-
-}
-
-std::vector<struct task_info> tasks_t::get_tasks(void) {
-    std::unique_ptr<lock_t> lock(new lock_t(&mSem));
-    std::unordered_map<std::string, struct task_info> tasks_map = mOld;
-
-    for (auto i : mRunning) {
-        std::string cmd = i.second.cmd;
-        if (tasks_map.find(cmd) == tasks_map.end()) {
-            tasks_map[cmd] = i.second;
-        } else {
-            add_task_info(&i.second, &tasks_map[cmd]);
+        if (l_chars != r_chars) {
+            return l_chars > r_chars;
         }
     }
 
-    std::vector<struct task_info> retval(tasks_map.size());
-    int idx = 0;
-    for (auto i : tasks_map) {
-        retval[idx++]  = i.second;
-    }
-
-    return retval;
+    return l.name < r.name;
 }
 
-void sort_running_tasks_info(std::vector<struct task_info> &tasks) {
-    std::sort(tasks.begin(), tasks.end(), cmp_task_info);
+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_tasks_info(std::vector<struct task_info> tasks) {
+// Logging functions
+void log_console_running_uids_info(std::vector<struct uid_info> uids) {
 // Sample Output:
-//       Application           Read          Write           Read          Write           Read          Write      Cancelled
-//              Name     Characters     Characters       Syscalls       Syscalls          Bytes          Bytes     Writebytes
-//        ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------
-//          zygote64       37688308        3388467           7607           4363      314519552        5373952           8192
-//     system_server       95874193        2216913          74613          52257      213078016        7237632          16384
-//            zygote         506279        1726194            921            263      128114688        1765376              0
-//  /vendor/bin/qcks       75415632       75154382          21672          25036       63627264       29974528       10485760
-//             /init       86658523        5107871          82113           8633       91015168        1245184              0
+//                                       Application        FG Read       FG Write        FG Read       FG Write        BG Read       BG Write        BG Read       BG Write
+//                                          NAME/UID     Characters     Characters          Bytes          Bytes     Characters     Characters          Bytes          Bytes
+//                                        ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------
+//                      com.google.android.gsf.login              0              0              0              0       57195097        5137089      176386048        6512640
+//           com.google.android.googlequicksearchbox              0              0              0              0        4196821       12123468       34295808       13225984
+//                                              1037           4572            537              0              0         131352        5145643       34263040        5144576
+//                        com.google.android.youtube           2182             70              0              0       63969383         482939       38731776         466944
 
     // Title
-    printf("                                       Application           Read          Write           Read          Write           Read          Write      Cancelled\n"
-           "                                              Name     Characters     Characters       Syscalls       Syscalls          Bytes          Bytes     Writebytes\n"
-           "                                        ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------\n");
+    printf("Per-UID I/O stats\n");
+    printf("                                       Application        FG Read       FG Write        FG Read       FG Write        BG Read       BG Write        BG Read       BG Write\n"
+           "                                          NAME/UID     Characters     Characters          Bytes          Bytes     Characters     Characters          Bytes          Bytes\n"
+           "                                        ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------     ----------\n");
 
-    for (struct task_info task : tasks) {
-        printf("%50s%15ju%15ju%15ju%15ju%15ju%15ju%15ju\n",
-            task.cmd, task.rchar, task.wchar, task.syscr, task.syscw,
-            task.read_bytes, task.write_bytes, task.cancelled_write_bytes);
+    for (const auto& uid : uids) {
+        printf("%50s%15ju%15ju%15ju%15ju%15ju%15ju%15ju%15ju\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);
     }
     fflush(stdout);
 }
diff --git a/storaged/tests/Android.mk b/storaged/tests/Android.mk
index 4a0e45c..26d04b1 100644
--- a/storaged/tests/Android.mk
+++ b/storaged/tests/Android.mk
@@ -40,6 +40,6 @@
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
 LOCAL_STATIC_LIBRARIES := libstoraged
-LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
+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
index 99b21ac..9e03c50 100644
--- a/storaged/tests/storaged_test.cpp
+++ b/storaged/tests/storaged_test.cpp
@@ -30,11 +30,10 @@
 #define MMC_DISK_STATS_PATH "/sys/block/mmcblk0/stat"
 #define SDA_DISK_STATS_PATH "/sys/block/sda/stat"
 #define EMMC_EXT_CSD_PATH "/d/mmc0/mmc0:0001/ext_csd"
-#define INIT_TASK_IO_PATH "/proc/1/io"
 
 static void pause(uint32_t sec) {
     const char* path = "/cache/test";
-    int fd = open(path, O_WRONLY | O_CREAT);
+    int fd = open(path, O_WRONLY | O_CREAT, 0600);
     ASSERT_LT(-1, fd);
     char buffer[2048];
     memset(buffer, 1, sizeof(buffer));
@@ -144,46 +143,6 @@
     }
 }
 
-TEST(storaged_test, task_info) {
-    // parse_task_info should read something other than 0 from /proc/1/*
-    struct task_info task_info;
-    memset(&task_info, 0, sizeof(task_info));
-
-    if (!parse_task_info(1, &task_info)) return;
-
-    EXPECT_EQ((uint32_t)1, task_info.pid);
-    EXPECT_LT((uint64_t)0, task_info.rchar);
-    EXPECT_LT((uint64_t)0, task_info.wchar);
-    EXPECT_LT((uint64_t)0, task_info.syscr);
-    EXPECT_LT((uint64_t)0, task_info.syscw);
-    EXPECT_LT((uint64_t)0, task_info.read_bytes);
-    EXPECT_LT((uint64_t)0, task_info.write_bytes);
-    // cancelled_write_bytes of init could be 0, there is no need to test
-    EXPECT_LE((uint64_t)0, task_info.starttime);
-    EXPECT_NE((char*)NULL, strstr(task_info.cmd, "init"));
-
-    // Entries in /proc/1/io should be increasing through time
-    struct task_info task_old, task_new;
-    memset(&task_old, 0, sizeof(task_old));
-    memset(&task_new, 0, sizeof(task_new));
-
-    // parse_task_info should succeed at this point
-    ASSERT_TRUE(parse_task_info(1, &task_old));
-    sleep(1);
-    ASSERT_TRUE(parse_task_info(1, &task_new));
-
-    EXPECT_EQ(task_old.pid, task_new.pid);
-    EXPECT_LE(task_old.rchar, task_new.rchar);
-    EXPECT_LE(task_old.wchar, task_new.wchar);
-    EXPECT_LE(task_old.syscr, task_new.syscr);
-    EXPECT_LE(task_old.syscw, task_new.syscw);
-    EXPECT_LE(task_old.read_bytes, task_new.read_bytes);
-    EXPECT_LE(task_old.write_bytes, task_new.write_bytes);
-    EXPECT_LE(task_old.cancelled_write_bytes, task_new.cancelled_write_bytes);
-    EXPECT_EQ(task_old.starttime, task_new.starttime);
-    EXPECT_EQ(0, strcmp(task_old.cmd, task_new.cmd));
-}
-
 static double mean(std::deque<uint32_t> nums) {
     double sum = 0.0;
     for (uint32_t i : nums) {
@@ -244,179 +203,6 @@
     }
 }
 
-static void expect_increasing(struct task_info told, struct task_info tnew) {
-    ASSERT_EQ(told.pid, tnew.pid);
-    ASSERT_EQ(told.starttime, tnew.starttime);
-    ASSERT_EQ(strcmp(told.cmd, tnew.cmd), 0);
-
-    EXPECT_LE(told.rchar, tnew.rchar);
-    EXPECT_LE(told.wchar, tnew.wchar);
-    EXPECT_LE(told.syscr, tnew.syscr);
-    EXPECT_LE(told.syscw, tnew.syscw);
-    EXPECT_LE(told.read_bytes, tnew.read_bytes);
-    EXPECT_LE(told.write_bytes, tnew.write_bytes);
-    EXPECT_LE(told.cancelled_write_bytes, tnew.cancelled_write_bytes);
-}
-
-static void expect_equal(struct task_info told, struct task_info tnew) {
-    ASSERT_EQ(told.pid, tnew.pid);
-    ASSERT_EQ(told.starttime, tnew.starttime);
-    ASSERT_EQ(strcmp(told.cmd, tnew.cmd), 0);
-
-    EXPECT_EQ(told.rchar, tnew.rchar);
-    EXPECT_EQ(told.wchar, tnew.wchar);
-    EXPECT_EQ(told.syscr, tnew.syscr);
-    EXPECT_EQ(told.syscw, tnew.syscw);
-    EXPECT_EQ(told.read_bytes, tnew.read_bytes);
-    EXPECT_EQ(told.write_bytes, tnew.write_bytes);
-    EXPECT_EQ(told.cancelled_write_bytes, tnew.cancelled_write_bytes);
-}
-
-static std::set<uint32_t> find_overlap(std::unordered_map<uint32_t, struct task_info> t1,
-                                       std::unordered_map<uint32_t, struct task_info> t2) {
-    std::set<uint32_t> retval;
-    for (auto i : t1) {
-        if (t2.find(i.first) != t2.end()) {
-            retval.insert(i.first);
-        }
-    }
-
-    return retval;
-}
-
-static std::set<std::string> find_overlap(std::unordered_map<std::string, struct task_info> t1,
-                                          std::unordered_map<std::string, struct task_info> t2) {
-    std::set<std::string> retval;
-    for (auto i : t1) {
-        if (t2.find(i.first) != t2.end()) {
-            retval.insert(i.first);
-        }
-    }
-
-    return retval;
-}
-
-static bool cmp_app_name(struct task_info i, struct task_info j) {
-    return strcmp(i.cmd, j.cmd) > 0;
-}
-
-static void expect_match(std::vector<struct task_info> v1, std::vector<struct task_info> v2) {
-    ASSERT_EQ(v1.size(), v2.size());
-    std::sort(v1.begin(), v1.end(), cmp_app_name);
-    std::sort(v2.begin(), v2.end(), cmp_app_name);
-
-    for (uint i = 0; i < v1.size(); ++i) {
-        expect_equal(v1[i], v2[i]);
-    }
-}
-
-static void add_task_info(struct task_info* src, struct task_info* dst) {
-    ASSERT_EQ(0, strcmp(src->cmd, dst->cmd));
-
-    dst->pid = 0;
-    dst->rchar += src->rchar;
-    dst->wchar += src->wchar;
-    dst->syscr += src->syscr;
-    dst->syscw += src->syscw;
-    dst->read_bytes += src->read_bytes;
-    dst->write_bytes += src->write_bytes;
-    dst->cancelled_write_bytes += src->cancelled_write_bytes;
-    dst->starttime = 0;
-}
-
-static std::vector<struct task_info>
-categorize_tasks(std::unordered_map<uint32_t, struct task_info> tasks) {
-    std::unordered_map<std::string, struct task_info> tasks_cmd;
-    for (auto i : tasks) {
-        std::string cmd = i.second.cmd;
-        if (tasks_cmd.find(cmd) == tasks_cmd.end()) {
-            tasks_cmd[cmd] = i.second;
-        } else {
-            add_task_info(&i.second, &tasks_cmd[cmd]);
-        }
-    }
-
-    std::vector<struct task_info> retval(tasks_cmd.size());
-    int cnt = 0;
-    for (auto i : tasks_cmd) {
-        retval[cnt++] = i.second;
-    }
-
-    return retval;
-}
-
-#define TEST_LOOPS 20
-TEST(storaged_test, tasks_t) {
-    // pass this test if /proc/[pid]/io is not readable
-    const char* test_paths[] = {"/proc/1/io", "/proc/1/comm", "/proc/1/cmdline", "/proc/1/stat"};
-    for (uint i = 0; i < sizeof(test_paths) / sizeof(const char*); ++i) {
-        if (access(test_paths[i], R_OK) < 0) return;
-    }
-
-    tasks_t tasks;
-    EXPECT_EQ((uint32_t)0, tasks.mRunning.size());
-    EXPECT_EQ((uint32_t)0, tasks.mOld.size());
-
-    tasks.update_running_tasks();
-
-    std::unordered_map<uint32_t, struct task_info> prev_running = tasks.mRunning;
-    std::unordered_map<std::string, struct task_info> prev_old = tasks.mOld;
-
-    // hashmap maintaining
-    std::unordered_map<uint32_t, struct task_info> tasks_pid = tasks.mRunning;
-
-    // get_running_tasks() should return something other than a null map
-    std::unordered_map<uint32_t, struct task_info> test = tasks.get_running_tasks();
-    EXPECT_LE((uint32_t)1, test.size());
-
-    for (int i = 0; i < TEST_LOOPS; ++i) {
-        tasks.update_running_tasks();
-
-        std::set<uint32_t> overlap_running = find_overlap(prev_running, tasks.mRunning);
-        std::set<std::string> overlap_old = find_overlap(prev_old, tasks.mOld);
-
-        // overlap_running should capture init(pid == 1), since init never get killed
-        EXPECT_LE((uint32_t)1, overlap_running.size());
-        EXPECT_NE(overlap_running.find((uint32_t)1), overlap_running.end());
-        // overlap_old should never capture init, since init never get killed
-        EXPECT_EQ(overlap_old.find("init"), overlap_old.end());
-
-        // overlapping entries in previous and current running-tasks map should have increasing contents
-        for (uint32_t i : overlap_running) {
-            expect_increasing(prev_running[i], tasks.mRunning[i]);
-        }
-
-        // overlapping entries in previous and current killed-tasks map should have increasing contents
-        // and the map size should also be increasing
-        for (std::string i : overlap_old) {
-            expect_increasing(prev_old[i], tasks.mOld[i]);
-        }
-        EXPECT_LE(prev_old.size(), tasks.mRunning.size());
-
-        // update app name & tasks_pid
-        for (auto i : tasks.mRunning) {
-            // test will fail if the pid got wrapped
-            if (tasks_pid.find(i.first) != tasks_pid.end()) {
-                expect_increasing(tasks_pid[i.first], i.second);
-                tasks_pid[i.first] = i.second;
-            } else {
-                tasks_pid[i.first] = i.second;
-            }
-        }
-
-        // get maintained tasks
-        std::vector<struct task_info> test_tasks = categorize_tasks(tasks_pid);
-        std::vector<struct task_info> real_tasks = tasks.get_tasks();
-
-        expect_match(test_tasks, real_tasks);
-
-        prev_running = tasks.mRunning;
-        prev_old = tasks.mOld;
-
-        pause(5);
-    }
-}
-
 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;
@@ -569,6 +355,7 @@
     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);