Merge "storaged: fix check_time logic"
diff --git a/adb/Android.mk b/adb/Android.mk
index 41cb735..b444afa 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -81,10 +81,14 @@
 
 LIBADB_darwin_SRC_FILES := \
     sysdeps_unix.cpp \
+    client/usb_dispatch.cpp \
+    client/usb_libusb.cpp \
     client/usb_osx.cpp \
 
 LIBADB_linux_SRC_FILES := \
     sysdeps_unix.cpp \
+    client/usb_dispatch.cpp \
+    client/usb_libusb.cpp \
     client/usb_linux.cpp \
 
 LIBADB_windows_SRC_FILES := \
@@ -150,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
@@ -169,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)
 
@@ -219,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
 
@@ -236,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
@@ -287,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
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/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..597e66e
--- /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(INFO) << "using libusb backend";
+        libusb::usb_init();
+    } else {
+        LOG(INFO) << "using native backend";
+        native::usb_init();
+    }
+}
+
+int usb_write(usb_handle* h, const void* data, int len) {
+    return should_use_libusb()
+               ? libusb::usb_write(reinterpret_cast<libusb::usb_handle*>(h), data, len)
+               : native::usb_write(reinterpret_cast<native::usb_handle*>(h), data, len);
+}
+
+int usb_read(usb_handle* h, void* data, int len) {
+    return should_use_libusb()
+               ? libusb::usb_read(reinterpret_cast<libusb::usb_handle*>(h), data, len)
+               : native::usb_read(reinterpret_cast<native::usb_handle*>(h), data, len);
+}
+
+int usb_close(usb_handle* h) {
+    return should_use_libusb() ? libusb::usb_close(reinterpret_cast<libusb::usb_handle*>(h))
+                               : native::usb_close(reinterpret_cast<native::usb_handle*>(h));
+}
+
+void usb_kick(usb_handle* h) {
+    should_use_libusb() ? libusb::usb_kick(reinterpret_cast<libusb::usb_handle*>(h))
+                        : native::usb_kick(reinterpret_cast<native::usb_handle*>(h));
+}
diff --git a/adb/client/usb_libusb.cpp b/adb/client/usb_libusb.cpp
new file mode 100644
index 0000000..7adb262
--- /dev/null
+++ b/adb/client/usb_libusb.cpp
@@ -0,0 +1,519 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "usb.h"
+
+#include "sysdeps.h"
+
+#include <stdint.h>
+
+#include <atomic>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <unordered_map>
+
+#include <libusb/libusb.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/quick_exit.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "adb.h"
+#include "transport.h"
+#include "usb.h"
+
+using namespace std::literals;
+
+using android::base::StringPrintf;
+
+// RAII wrappers for libusb.
+struct ConfigDescriptorDeleter {
+    void operator()(libusb_config_descriptor* desc) {
+        libusb_free_config_descriptor(desc);
+    }
+};
+
+using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
+
+struct DeviceHandleDeleter {
+    void operator()(libusb_device_handle* h) {
+        libusb_close(h);
+    }
+};
+
+using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
+
+struct transfer_info {
+    transfer_info(const char* name, uint16_t zero_mask) :
+        name(name),
+        transfer(libusb_alloc_transfer(0)),
+        zero_mask(zero_mask)
+    {
+    }
+
+    ~transfer_info() {
+        libusb_free_transfer(transfer);
+    }
+
+    const char* name;
+    libusb_transfer* transfer;
+    bool transfer_complete;
+    std::condition_variable cv;
+    std::mutex mutex;
+    uint16_t zero_mask;
+
+    void Notify() {
+        LOG(DEBUG) << "notifying " << name << " transfer complete";
+        transfer_complete = true;
+        cv.notify_one();
+    }
+};
+
+namespace libusb {
+struct usb_handle : public ::usb_handle {
+    usb_handle(const std::string& device_address, const std::string& serial,
+               unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in,
+               uint8_t bulk_out, size_t zero_mask)
+        : device_address(device_address),
+          serial(serial),
+          closing(false),
+          device_handle(device_handle.release()),
+          read("read", zero_mask),
+          write("write", zero_mask),
+          interface(interface),
+          bulk_in(bulk_in),
+          bulk_out(bulk_out) {
+    }
+
+    ~usb_handle() {
+        Close();
+    }
+
+    void Close() {
+        std::unique_lock<std::mutex> lock(device_handle_mutex);
+        // Cancelling transfers will trigger more Closes, so make sure this only happens once.
+        if (closing) {
+            return;
+        }
+        closing = true;
+
+        // Make sure that no new transfers come in.
+        libusb_device_handle* handle = device_handle;
+        if (!handle) {
+            return;
+        }
+
+        device_handle = nullptr;
+
+        // Cancel already dispatched transfers.
+        libusb_cancel_transfer(read.transfer);
+        libusb_cancel_transfer(write.transfer);
+
+        libusb_release_interface(handle, interface);
+        libusb_close(handle);
+    }
+
+    std::string device_address;
+    std::string serial;
+
+    std::atomic<bool> closing;
+    std::mutex device_handle_mutex;
+    libusb_device_handle* device_handle;
+
+    transfer_info read;
+    transfer_info write;
+
+    uint8_t interface;
+    uint8_t bulk_in;
+    uint8_t bulk_out;
+};
+
+static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
+static auto& usb_handles_mutex = *new std::mutex();
+
+static std::thread* device_poll_thread = nullptr;
+static std::atomic<bool> terminate_device_poll_thread(false);
+
+static std::string get_device_address(libusb_device* device) {
+    return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
+                        libusb_get_device_address(device));
+}
+
+static bool endpoint_is_output(uint8_t endpoint) {
+    return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
+}
+
+static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length, uint16_t zero_mask) {
+    return endpoint_is_output(endpoint) && write_length != 0 && zero_mask != 0 &&
+           (write_length & zero_mask) == 0;
+}
+
+static void poll_for_devices() {
+    libusb_device** list;
+    adb_thread_setname("device poll");
+    while (!terminate_device_poll_thread) {
+        const ssize_t device_count = libusb_get_device_list(nullptr, &list);
+
+        LOG(VERBOSE) << "found " << device_count << " attached devices";
+
+        for (ssize_t i = 0; i < device_count; ++i) {
+            libusb_device* device = list[i];
+            std::string device_address = get_device_address(device);
+            std::string device_serial;
+
+            // Figure out if we want to open the device.
+            libusb_device_descriptor device_desc;
+            int rc = libusb_get_device_descriptor(device, &device_desc);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to get device descriptor for device at " << device_address
+                             << ": " << libusb_error_name(rc);
+            }
+
+            if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
+                // Assume that all Android devices have the device class set to per interface.
+                // TODO: Is this assumption valid?
+                LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
+                continue;
+            }
+
+            libusb_config_descriptor* config_raw;
+            rc = libusb_get_active_config_descriptor(device, &config_raw);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to get active config descriptor for device at "
+                             << device_address << ": " << libusb_error_name(rc);
+                continue;
+            }
+            const unique_config_descriptor config(config_raw);
+
+            // Use size_t for interface_num so <iostream>s don't mangle it.
+            size_t interface_num;
+            uint16_t zero_mask;
+            uint8_t bulk_in = 0, bulk_out = 0;
+            bool found_adb = false;
+
+            for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
+                const libusb_interface& interface = config->interface[interface_num];
+                if (interface.num_altsetting != 1) {
+                    // Assume that interfaces with alternate settings aren't adb interfaces.
+                    // TODO: Is this assumption valid?
+                    LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
+                                 << device_address << " (interface " << interface_num << ")";
+                    continue;
+                }
+
+                const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
+                if (!is_adb_interface(interface_desc.bInterfaceClass,
+                                      interface_desc.bInterfaceSubClass,
+                                      interface_desc.bInterfaceProtocol)) {
+                    LOG(VERBOSE) << "skipping non-adb interface at " << device_address
+                                 << " (interface " << interface_num << ")";
+                    continue;
+                }
+
+                LOG(VERBOSE) << "found potential adb interface at " << device_address
+                             << " (interface " << interface_num << ")";
+
+                bool found_in = false;
+                bool found_out = false;
+                for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
+                     ++endpoint_num) {
+                    const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
+                    const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
+                    const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
+
+                    const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
+
+                    if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
+                        continue;
+                    }
+
+                    if (endpoint_is_output(endpoint_addr) && !found_out) {
+                        found_out = true;
+                        bulk_out = endpoint_addr;
+                        zero_mask = endpoint_desc.wMaxPacketSize - 1;
+                    } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
+                        found_in = true;
+                        bulk_in = endpoint_addr;
+                    }
+                }
+
+                if (found_in && found_out) {
+                    found_adb = true;
+                    break;
+                } else {
+                    LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
+                                 << "(interface " << interface_num << "): missing bulk endpoints "
+                                 << "(found_in = " << found_in << ", found_out = " << found_out
+                                 << ")";
+                }
+            }
+
+            if (!found_adb) {
+                LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
+                continue;
+            }
+
+            {
+                std::unique_lock<std::mutex> lock(usb_handles_mutex);
+                if (usb_handles.find(device_address) != usb_handles.end()) {
+                    LOG(VERBOSE) << "device at " << device_address
+                                 << " has already been registered, skipping";
+                    continue;
+                }
+            }
+
+            libusb_device_handle* handle_raw;
+            rc = libusb_open(list[i], &handle_raw);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to open usb device at " << device_address << ": "
+                             << libusb_error_name(rc);
+                continue;
+            }
+
+            unique_device_handle handle(handle_raw);
+            LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
+                       << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
+
+            device_serial.resize(255);
+            rc = libusb_get_string_descriptor_ascii(
+                handle_raw, device_desc.iSerialNumber,
+                reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length());
+            if (rc == 0) {
+                LOG(WARNING) << "received empty serial from device at " << device_address;
+                continue;
+            } else if (rc < 0) {
+                LOG(WARNING) << "failed to get serial from device at " << device_address
+                             << libusb_error_name(rc);
+                continue;
+            }
+            device_serial.resize(rc);
+
+            // Try to reset the device.
+            rc = libusb_reset_device(handle_raw);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to reset opened device '" << device_serial
+                             << "': " << libusb_error_name(rc);
+                continue;
+            }
+
+            // WARNING: this isn't released via RAII.
+            rc = libusb_claim_interface(handle.get(), interface_num);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
+                             << libusb_error_name(rc);
+                continue;
+            }
+
+            for (uint8_t endpoint : {bulk_in, bulk_out}) {
+                rc = libusb_clear_halt(handle.get(), endpoint);
+                if (rc != 0) {
+                    LOG(WARNING) << "failed to clear halt on device '" << device_serial
+                                 << "' endpoint 0x" << std::hex << endpoint << ": "
+                                 << libusb_error_name(rc);
+                    libusb_release_interface(handle.get(), interface_num);
+                    continue;
+                }
+            }
+
+            auto result =
+                std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
+                                             interface_num, bulk_in, bulk_out, zero_mask);
+            usb_handle* usb_handle_raw = result.get();
+
+            {
+                std::unique_lock<std::mutex> lock(usb_handles_mutex);
+                usb_handles[device_address] = std::move(result);
+            }
+
+            register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1);
+
+            LOG(INFO) << "registered new usb device '" << device_serial << "'";
+        }
+        libusb_free_device_list(list, 1);
+
+        std::this_thread::sleep_for(500ms);
+    }
+}
+
+void usb_init() {
+    LOG(DEBUG) << "initializing libusb...";
+    int rc = libusb_init(nullptr);
+    if (rc != 0) {
+        LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
+    }
+
+    // Spawn a thread for libusb_handle_events.
+    std::thread([]() {
+        adb_thread_setname("libusb");
+        while (true) {
+            libusb_handle_events(nullptr);
+        }
+    }).detach();
+
+    // Spawn a thread to do device enumeration.
+    // TODO: Use libusb_hotplug_* instead?
+    device_poll_thread = new std::thread(poll_for_devices);
+    android::base::at_quick_exit([]() {
+        terminate_device_poll_thread = true;
+        std::unique_lock<std::mutex> lock(usb_handles_mutex);
+        for (auto& it : usb_handles) {
+            it.second->Close();
+        }
+        lock.unlock();
+        device_poll_thread->join();
+    });
+}
+
+// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
+static int perform_usb_transfer(usb_handle* h, transfer_info* info,
+                                std::unique_lock<std::mutex> device_lock) {
+    libusb_transfer* transfer = info->transfer;
+
+    transfer->user_data = info;
+    transfer->callback = [](libusb_transfer* transfer) {
+        transfer_info* info = static_cast<transfer_info*>(transfer->user_data);
+
+        LOG(DEBUG) << info->name << " transfer callback entered";
+
+        // Make sure that the original submitter has made it to the condition_variable wait.
+        std::unique_lock<std::mutex> lock(info->mutex);
+
+        LOG(DEBUG) << info->name << " callback successfully acquired lock";
+
+        if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+            LOG(WARNING) << info->name
+                         << " transfer failed: " << libusb_error_name(transfer->status);
+            info->Notify();
+            return;
+        }
+
+        if (transfer->actual_length != transfer->length) {
+            LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
+            transfer->length -= transfer->actual_length;
+            transfer->buffer += transfer->actual_length;
+            int rc = libusb_submit_transfer(transfer);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to submit " << info->name
+                             << " transfer: " << libusb_error_name(rc);
+                transfer->status = LIBUSB_TRANSFER_ERROR;
+                info->Notify();
+            }
+            return;
+        }
+
+        if (should_perform_zero_transfer(transfer->endpoint, transfer->length, info->zero_mask)) {
+            LOG(DEBUG) << "submitting zero-length write";
+            transfer->length = 0;
+            int rc = libusb_submit_transfer(transfer);
+            if (rc != 0) {
+                LOG(WARNING) << "failed to submit zero-length write: " << libusb_error_name(rc);
+                transfer->status = LIBUSB_TRANSFER_ERROR;
+                info->Notify();
+            }
+            return;
+        }
+
+        LOG(VERBOSE) << info->name << "transfer fully complete";
+        info->Notify();
+    };
+
+    LOG(DEBUG) << "locking " << info->name << " transfer_info mutex";
+    std::unique_lock<std::mutex> lock(info->mutex);
+    info->transfer_complete = false;
+    LOG(DEBUG) << "submitting " << info->name << " transfer";
+    int rc = libusb_submit_transfer(transfer);
+    if (rc != 0) {
+        LOG(WARNING) << "failed to submit " << info->name << " transfer: " << libusb_error_name(rc);
+        errno = EIO;
+        return -1;
+    }
+
+    LOG(DEBUG) << info->name << " transfer successfully submitted";
+    device_lock.unlock();
+    info->cv.wait(lock, [info]() { return info->transfer_complete; });
+    if (transfer->status != 0) {
+        errno = EIO;
+        return -1;
+    }
+
+    return 0;
+}
+
+int usb_write(usb_handle* h, const void* d, int len) {
+    LOG(DEBUG) << "usb_write of length " << len;
+
+    std::unique_lock<std::mutex> lock(h->device_handle_mutex);
+    if (!h->device_handle) {
+        errno = EIO;
+        return -1;
+    }
+
+    transfer_info* info = &h->write;
+    info->transfer->dev_handle = h->device_handle;
+    info->transfer->flags = 0;
+    info->transfer->endpoint = h->bulk_out;
+    info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
+    info->transfer->length = len;
+    info->transfer->buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(d));
+    info->transfer->num_iso_packets = 0;
+
+    int rc = perform_usb_transfer(h, info, std::move(lock));
+    LOG(DEBUG) << "usb_write(" << len << ") = " << rc;
+    return rc;
+}
+
+int usb_read(usb_handle* h, void* d, int len) {
+    LOG(DEBUG) << "usb_read of length " << len;
+
+    std::unique_lock<std::mutex> lock(h->device_handle_mutex);
+    if (!h->device_handle) {
+        errno = EIO;
+        return -1;
+    }
+
+    transfer_info* info = &h->read;
+    info->transfer->dev_handle = h->device_handle;
+    info->transfer->flags = 0;
+    info->transfer->endpoint = h->bulk_in;
+    info->transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
+    info->transfer->length = len;
+    info->transfer->buffer = reinterpret_cast<unsigned char*>(d);
+    info->transfer->num_iso_packets = 0;
+
+    int rc = perform_usb_transfer(h, info, std::move(lock));
+    LOG(DEBUG) << "usb_read(" << len << ") = " << rc;
+    return rc;
+}
+
+int usb_close(usb_handle* h) {
+    std::unique_lock<std::mutex> lock(usb_handles_mutex);
+    auto it = usb_handles.find(h->device_address);
+    if (it == usb_handles.end()) {
+        LOG(FATAL) << "attempted to close unregistered usb_handle for '" << h->serial << "'";
+    }
+    usb_handles.erase(h->device_address);
+    return 0;
+}
+
+void usb_kick(usb_handle* h) {
+    h->Close();
+}
+} // namespace libusb
diff --git a/adb/client/usb_linux.cpp b/adb/client/usb_linux.cpp
index e7f1338..13b7674 100644
--- a/adb/client/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/client/usb_osx.cpp b/adb/client/usb_osx.cpp
index e541f6e..d4fc7c0 100644
--- a/adb/client/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/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/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index c009869..501d089 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -297,13 +297,6 @@
   }
 
   log_signal_summary(signal_number, info);
-  if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) == 0) {
-    // The process has disabled core dumps and PTRACE_ATTACH, and does not want to be dumped.
-    __libc_format_log(ANDROID_LOG_INFO, "libc",
-                      "Suppressing debuggerd output because prctl(PR_GET_DUMPABLE)==0");
-    resend_signal(info, false);
-    return;
-  }
 
   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.
diff --git a/fastboot/usb_osx.cpp b/fastboot/usb_osx.cpp
index ee5d575..032ae31 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);
 
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 207f42b..be84e8a 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -76,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;
     }
 
@@ -131,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++) {
@@ -140,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);
             }
         }
@@ -153,10 +155,10 @@
          * (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),
                                           const_cast<char **>(e2fsck_argv),
@@ -167,7 +169,7 @@
 
             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")) {
@@ -176,7 +178,7 @@
                     "-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),
                                       const_cast<char **>(f2fs_fsck_argv),
@@ -185,7 +187,7 @@
                                       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;
         }
     }
 
@@ -231,8 +233,8 @@
          * 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 {
             const char* arg1 = nullptr;
             const char* arg2 = nullptr;
@@ -244,7 +246,7 @@
                 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));
+                    PERROR << "Can't read '" << blk_device << "' super block";
                     return force_check;
                 }
 
@@ -253,20 +255,20 @@
                 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);
+                    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;
             }
 
@@ -282,7 +284,7 @@
                                           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;
             }
         }
     }
@@ -298,10 +300,10 @@
          * 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;
@@ -312,22 +314,23 @@
                 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));
+                    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");
+                    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;
             }
 
@@ -346,7 +349,7 @@
 
             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;
             }
         }
     }
@@ -406,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);
     }
@@ -488,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;
             }
 
@@ -510,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 */
@@ -547,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;
     }
 
@@ -568,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;
         }
 
@@ -583,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;
         }
 
@@ -591,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;
@@ -638,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;
@@ -717,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;
             }
         }
@@ -733,20 +743,20 @@
              * mount_with_alternatives().
              */
             if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
-                INFO("AVB HASHTREE disabled\n");
+                LINFO << "AVB HASHTREE disabled";
             } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
                        FS_MGR_SETUP_AVB_SUCCESS) {
-                ERROR("Failed to set up AVB on partition: %s, skipping!\n",
-                      fstab->recs[i].mount_point);
+                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;
             }
         }
@@ -770,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;
             }
@@ -788,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)) {
@@ -811,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;
             }
@@ -819,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;
@@ -839,15 +856,15 @@
             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;
@@ -899,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;
         }
 
@@ -928,20 +945,20 @@
              * mount_with_alternatives().
              */
             if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
-                INFO("AVB HASHTREE disabled\n");
+                LINFO << "AVB HASHTREE disabled";
             } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
                        FS_MGR_SETUP_AVB_SUCCESS) {
-                ERROR("Failed to set up AVB on partition: %s, skipping!\n",
-                      fstab->recs[i].mount_point);
+                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;
             }
         }
@@ -962,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 {
@@ -971,7 +988,8 @@
         }
     } 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:
@@ -992,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;
     }
 
@@ -1011,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++;
@@ -1057,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;
               }
@@ -1067,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;
             }
@@ -1086,7 +1106,7 @@
                                       &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;
         }
@@ -1102,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;
         }
     }
@@ -1159,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;
@@ -1167,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
index 51632cf..70140d8 100644
--- a/fs_mgr/fs_mgr_avb.cpp
+++ b/fs_mgr/fs_mgr_avb.cpp
@@ -209,21 +209,21 @@
         expected_digest_size = SHA512_DIGEST_LENGTH * 2;
         vbmeta_prop->hash_alg = kSHA512;
     } else {
-        ERROR("Unknown hash algorithm: %s\n", hash_alg.c_str());
+        LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
         return false;
     }
 
     // Reads digest.
     if (digest.size() != expected_digest_size) {
-        ERROR("Unexpected digest size: %zu (expected %zu)\n", 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)) {
-        ERROR("Hash digest contains non-hexidecimal character: %s\n",
-              digest.c_str());
+        LERROR << "Hash digest contains non-hexidecimal character: "
+               << digest.c_str();
         return false;
     }
 
@@ -252,7 +252,7 @@
                                  const androidboot_vbmeta &vbmeta_prop)
 {
     if (verify_data.num_vbmeta_images == 0) {
-        ERROR("No vbmeta images\n");
+        LERROR << "No vbmeta images";
         return false;
     }
 
@@ -268,13 +268,13 @@
     }
 
     if (total_size != vbmeta_prop.vbmeta_size) {
-        ERROR("total vbmeta size mismatch: %zu (expected: %zu)\n", total_size,
-              vbmeta_prop.vbmeta_size);
+        LERROR << "total vbmeta size mismatch: " << total_size
+               << " (expected: " << vbmeta_prop.vbmeta_size << ")";
         return false;
     }
 
     if (!digest_matched) {
-        ERROR("vbmeta digest mismatch\n");
+        LERROR << "vbmeta digest mismatch";
         return false;
     }
 
@@ -326,11 +326,11 @@
     }
 
     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;
     }
 
-    INFO("loading verity table: '%s'", verity_params);
+    LINFO << "Loading verity table: '" << verity_params << "'";
 
     // Sets ext target boundary.
     verity_params += strlen(verity_params) + 1;
@@ -339,7 +339,7 @@
 
     // Sends 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 false;
     }
 
@@ -354,7 +354,7 @@
     // Gets the device mapper fd.
     android::base::unique_fd fd(open("/dev/device-mapper", O_RDWR));
     if (fd < 0) {
-        ERROR("Error opening device mapper (%s)\n", strerror(errno));
+        PERROR << "Error opening device mapper";
         return false;
     }
 
@@ -363,14 +363,14 @@
     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)) {
-        ERROR("Couldn't create verity device!\n");
+        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)) {
-        ERROR("Couldn't get verity device number!\n");
+        LERROR << "Couldn't get verity device number!";
         return false;
     }
 
@@ -378,7 +378,7 @@
     if (!hashtree_load_verity_table(io, mount_point, fd,
                                     std::string(fstab_entry->blk_device),
                                     hashtree_desc, salt, root_digest)) {
-        ERROR("Couldn't load verity table!\n");
+        LERROR << "Couldn't load verity table!";
         return false;
     }
 
@@ -432,16 +432,16 @@
             verify_data.vbmeta_images[i].partition_name);
         if (vbmeta_partition_name != "vbmeta" &&
             vbmeta_partition_name != partition_name) {
-            WARNING("Skip vbmeta image at %s for partition: %s\n",
-                    verify_data.vbmeta_images[i].partition_name,
-                    partition_name.c_str());
+            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)) {
-                WARNING("Descriptor is invalid.\n");
+                LWARNING << "Descriptor[" << j << "] is invalid";
                 continue;
             }
             if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) {
@@ -468,7 +468,7 @@
     }
 
     if (!found) {
-        ERROR("Partition descriptor not found: %s\n", partition_name.c_str());
+        LERROR << "Partition descriptor not found: " << partition_name.c_str();
         return false;
     }
 
@@ -530,7 +530,7 @@
     FS_MGR_CHECK(fstab != nullptr);
 
     if (!polling_vbmeta_blk_device(fstab)) {
-        ERROR("Failed to find block device of /vbmeta\n");
+        LERROR << "Failed to find block device of /vbmeta";
         return FS_MGR_SETUP_AVB_FAIL;
     }
 
@@ -542,7 +542,7 @@
 
     fs_mgr_avb_ops = fs_mgr_dummy_avb_ops_new(fstab);
     if (fs_mgr_avb_ops == nullptr) {
-        ERROR("Failed to allocate dummy avb_ops\n");
+        LERROR << "Failed to allocate dummy avb_ops";
         return FS_MGR_SETUP_AVB_FAIL;
     }
 
@@ -562,17 +562,17 @@
     //   - 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) {
-            ERROR("ERROR_VERIFICATION isn't allowed\n");
+            LERROR << "ERROR_VERIFICATION isn't allowed";
             goto fail;
         }
     } else if (verify_result != AVB_SLOT_VERIFY_RESULT_OK) {
-        ERROR("avb_slot_verify failed, result: %d\n", verify_result);
+        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)) {
-        ERROR("verify_vbmeta_images failed\n");
+        LERROR << "verify_vbmeta_images failed";
         goto fail;
     } else {
         // Checks whether FLAGS_HASHTREE_DISABLED is set.
@@ -619,8 +619,8 @@
     std::string partition_name(basename(fstab_entry->mount_point));
     if (!avb_validate_utf8((const uint8_t *)partition_name.c_str(),
                            partition_name.length())) {
-        ERROR("Partition name: %s is not valid UTF-8.\n",
-              partition_name.c_str());
+        LERROR << "Partition name: " << partition_name.c_str()
+               << " is not valid UTF-8.";
         return FS_MGR_SETUP_AVB_FAIL;
     }
 
diff --git a/fs_mgr/fs_mgr_avb_ops.cpp b/fs_mgr/fs_mgr_avb_ops.cpp
index f3030eb..7683166 100644
--- a/fs_mgr/fs_mgr_avb_ops.cpp
+++ b/fs_mgr/fs_mgr_avb_ops.cpp
@@ -66,7 +66,7 @@
         fs_mgr_get_entry_for_mount_point(fs_mgr_fstab, "/misc");
 
     if (fstab_entry == nullptr) {
-        ERROR("Partition (%s) not found in fstab\n", partition);
+        LERROR << "Partition (" << partition << ") not found in fstab";
         return AVB_IO_RESULT_ERROR_IO;
     }
 
@@ -83,7 +83,7 @@
         TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
 
     if (fd < 0) {
-        ERROR("Failed to open %s (%s)\n", path.c_str(), strerror(errno));
+        PERROR << "Failed to open " << path.c_str();
         return AVB_IO_RESULT_ERROR_IO;
     }
 
@@ -92,13 +92,13 @@
     if (offset < 0) {
         off64_t total_size = lseek64(fd, 0, SEEK_END);
         if (total_size == -1) {
-            ERROR("Failed to lseek64 to end of the partition\n");
+            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) {
-            ERROR("Failed to lseek64 to the beginning of the partition\n");
+            LERROR << "Failed to lseek64 to the beginning of the partition";
             return AVB_IO_RESULT_ERROR_IO;
         }
     }
@@ -109,8 +109,8 @@
         TEMP_FAILURE_RETRY(pread64(fd, buffer, num_bytes, offset));
 
     if (num_read < 0 || (size_t)num_read != num_bytes) {
-        ERROR("Failed to read %zu bytes from %s offset %" PRId64 " (%s)\n",
-              num_bytes, path.c_str(), offset, strerror(errno));
+        PERROR << "Failed to read " << num_bytes << " bytes from "
+               << path.c_str() << " offset " << offset;
         return AVB_IO_RESULT_ERROR_IO;
     }
 
@@ -184,7 +184,7 @@
 
     ops = (AvbOps *)calloc(1, sizeof(AvbOps));
     if (ops == nullptr) {
-        ERROR("Error allocating memory for AvbOps.\n");
+        LERROR << "Error allocating memory for AvbOps";
         return nullptr;
     }
 
diff --git a/fs_mgr/fs_mgr_dm_ioctl.cpp b/fs_mgr/fs_mgr_dm_ioctl.cpp
index 939657e..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;
@@ -72,7 +72,7 @@
 
     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.cpp b/fs_mgr/fs_mgr_format.cpp
index 45298b3..5705f93 100644
--- a/fs_mgr/fs_mgr_format.cpp
+++ b/fs_mgr/fs_mgr_format.cpp
@@ -45,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;
     }
@@ -58,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;
     }
@@ -73,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);
 
@@ -106,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;
@@ -128,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.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 23059df..48ddf29 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -196,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
@@ -226,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);
@@ -276,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);
@@ -321,7 +321,7 @@
     }
 
     if (!entries) {
-        ERROR("No entries found in fstab\n");
+        LERROR << "No entries found in fstab";
         goto err;
     }
 
@@ -354,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';
@@ -392,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,
@@ -413,7 +413,7 @@
     }
     /* 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);
@@ -433,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.cpp b/fs_mgr/fs_mgr_main.cpp
index f2901f3..f3919d9 100644
--- a/fs_mgr/fs_mgr_main.cpp
+++ b/fs_mgr/fs_mgr_main.cpp
@@ -27,7 +27,8 @@
 
 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);
 }
 
@@ -88,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);
 
@@ -104,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 0a27c7a..79c27c4 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -17,11 +17,9 @@
 #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>
 
-#ifdef __cplusplus
-#include <android-base/logging.h>
 /* 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.
@@ -29,14 +27,21 @@
  * indicate the check happens in fs_mgr.
  */
 #define FS_MGR_CHECK(x) CHECK(x) << "in libfs_mgr "
-#endif
+
+#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 INFO(x...)    KLOG_INFO("fs_mgr", x)
-#define WARNING(x...) KLOG_WARNING("fs_mgr", x)
-#define ERROR(x...)   KLOG_ERROR("fs_mgr", x)
-
 #define CRYPTO_TMPFS_OPTIONS "size=256m,mode=0771,uid=1000,gid=1000"
 
 #define WAIT_TIMEOUT 20
diff --git a/fs_mgr/fs_mgr_slotselect.cpp b/fs_mgr/fs_mgr_slotselect.cpp
index 0f59115..94b43e4 100644
--- a/fs_mgr/fs_mgr_slotselect.cpp
+++ 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 f6a14da..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,11 +277,11 @@
     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;
@@ -290,7 +290,7 @@
 
     // 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/include/android b/include/android
deleted file mode 120000
index 4872393..0000000
--- a/include/android
+++ /dev/null
@@ -1 +0,0 @@
-../liblog/include/android
\ No newline at end of file
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/system/graphics-base.h b/include/system/graphics-base.h
index 32b077a..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 {
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 15a9a55..26ea96a 100644
--- a/include/system/window.h
+++ b/include/system/window.h
@@ -356,7 +356,6 @@
     NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS   = 23,
     NATIVE_WINDOW_GET_FRAME_TIMESTAMPS      = 24,
     NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION= 25,
-    NATIVE_WINDOW_GET_REFRESH_CYCLE_PERIOD  = 26,
 };
 
 /* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
@@ -1049,14 +1048,6 @@
             outRefreshDuration);
 }
 
-static inline int native_window_get_refresh_cycle_period(
-        struct ANativeWindow* window,
-        int64_t* outMinRefreshDuration, int64_t* outMaxRefreshDuration)
-{
-    return window->perform(window, NATIVE_WINDOW_GET_REFRESH_CYCLE_PERIOD,
-            outMinRefreshDuration, outMaxRefreshDuration);
-}
-
 
 __END_DECLS
 
diff --git a/init/init.cpp b/init/init.cpp
index e7772e7..850a904 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -811,7 +811,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");
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 7e11ff0..ce197ee 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -575,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);
         }
     }
 }
@@ -639,10 +639,10 @@
 }
 
 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();
 }
 
diff --git a/init/seccomp.cpp b/init/seccomp.cpp
index d632302..6c85217 100644
--- a/init/seccomp.cpp
+++ b/init/seccomp.cpp
@@ -208,10 +208,20 @@
     AllowSyscall(f, 190); // __NR_vfork
 
     // Needed for strace
-    AllowSyscall(f, 238);  // __NR_tkill
+    AllowSyscall(f, 238); // __NR_tkill
 
     // Needed for kernel to restart syscalls
-    AllowSyscall(f, 0);  // __NR_restart_syscall
+    AllowSyscall(f, 0);   // __NR_restart_syscall
+
+    // Needed for debugging 32-bit Chrome
+    AllowSyscall(f, 42);  // __NR_pipe
+
+    // b/34732712
+    AllowSyscall(f, 364); // __NR_perf_event_open
+
+    // b/34651972
+    AllowSyscall(f, 33);  // __NR_access
+    AllowSyscall(f, 195); // __NR_stat64
 
     // arm32-on-arm64 only filter - autogenerated from bionic syscall usage
     for (size_t i = 0; i < arm_filter_size; ++i)
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index f6c0f0e..cf266dc 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -98,7 +98,7 @@
                 "ashmem-dev.c",
                 "klog.cpp",
                 "partition_utils.c",
-                "properties.c",
+                "properties.cpp",
                 "qtaguid.c",
                 "trace-dev.c",
                 "uevent.c",
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 dce316d..747fcc8 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -97,19 +97,11 @@
     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",
 }
 
diff --git a/liblog/event_tag_map.cpp b/liblog/event_tag_map.cpp
index 1155422..c53ea2c 100644
--- a/liblog/event_tag_map.cpp
+++ b/liblog/event_tag_map.cpp
@@ -38,10 +38,9 @@
 
 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.:
diff --git a/liblog/include/log/log.h b/liblog/include/log/log.h
index 6a7450c..db22211 100644
--- a/liblog/include/log/log.h
+++ b/liblog/include/log/log.h
@@ -31,6 +31,9 @@
 #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
@@ -76,90 +79,6 @@
 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
 #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
-
 /* --------------------------------------------------------------------- */
 
 /*
@@ -227,424 +146,6 @@
         (void) __android_log_bswrite(_tag, _value);
 #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
-
-/* 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
diff --git a/liblog/include/log/log_read.h b/liblog/include/log/log_read.h
new file mode 100644
index 0000000..5b5eebc
--- /dev/null
+++ b/liblog/include/log/log_read.h
@@ -0,0 +1,291 @@
+/*
+ * 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
+#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 __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..8c1ec96
--- /dev/null
+++ b/liblog/include/log/log_system.h
@@ -0,0 +1,123 @@
+/*
+ * 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
+
+/*
+ * 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_vndk/log/log.h b/liblog/include_vndk/log/log.h
index 1e3556c..f93b377 100644
--- a/liblog/include_vndk/log/log.h
+++ b/liblog/include_vndk/log/log.h
@@ -7,6 +7,8 @@
 #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
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/legacy-ndk-includes/log.h b/liblog/legacy-ndk-includes/log.h
deleted file mode 100644
index d40d6fa..0000000
--- a/liblog/legacy-ndk-includes/log.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROID_LOG_H
-#define _ANDROID_LOG_H
-
-/******************************************************************
- *
- * IMPORTANT NOTICE:
- *
- *   This file is part of Android's set of stable system headers
- *   exposed by the Android NDK (Native Development Kit) since
- *   platform release 1.5
- *
- *   Third-party source AND binary code relies on the definitions
- *   here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
- *
- *   - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
- *   - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
- *   - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
- *   - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
- */
-
-/*
- * Support routines to send messages to the Android in-kernel log buffer,
- * which can later be accessed through the 'logcat' utility.
- *
- * Each log message must have
- *   - a priority
- *   - a log tag
- *   - some text
- *
- * The tag normally corresponds to the component that emits the log message,
- * and should be reasonably small.
- *
- * Log message text may be truncated to less than an implementation-specific
- * limit (e.g. 1023 characters max).
- *
- * Note that a newline character ("\n") will be appended automatically to your
- * log message, if not already there. It is not possible to send several messages
- * and have them appear on a single line in logcat.
- *
- * PLEASE USE LOGS WITH MODERATION:
- *
- *  - Sending log messages eats CPU and slow down your application and the
- *    system.
- *
- *  - The circular log buffer is pretty small (<64KB), sending many messages
- *    might push off other important log messages from the rest of the system.
- *
- *  - In release builds, only send log messages to account for exceptional
- *    conditions.
- *
- * NOTE: These functions MUST be implemented by /system/lib/liblog.so
- */
-
-#include <stdarg.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Android log priority values, in ascending priority order.
- */
-typedef enum android_LogPriority {
-    ANDROID_LOG_UNKNOWN = 0,
-    ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
-    ANDROID_LOG_VERBOSE,
-    ANDROID_LOG_DEBUG,
-    ANDROID_LOG_INFO,
-    ANDROID_LOG_WARN,
-    ANDROID_LOG_ERROR,
-    ANDROID_LOG_FATAL,
-    ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
-} android_LogPriority;
-
-/*
- * Send a simple string to the log.
- */
-int __android_log_write(int prio, const char *tag, const char *text);
-
-/*
- * Send a formatted string to the log, used like printf(fmt,...)
- */
-int __android_log_print(int prio, const char *tag,  const char *fmt, ...)
-#if defined(__GNUC__)
-    __attribute__((__format__(printf, 3, 4)))
-#endif
-    ;
-
-/*
- * A variant of __android_log_print() that takes a va_list to list
- * additional parameters.
- */
-int __android_log_vprint(int prio, const char *tag,
-                         const char *fmt, va_list ap);
-
-/*
- * Log an assertion failure and SIGTRAP 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__))
-    __attribute__((__format__(printf, 3, 4)))
-#endif
-    ;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _ANDROID_LOG_H */
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index 1a685df..097befc 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -57,7 +57,10 @@
 test_src_files := \
     liblog_test.cpp \
     log_id_test.cpp \
-    log_radio_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),)
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index d03c6d1..8b9f0f0 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -1115,47 +1115,6 @@
 #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__
 static bool checkPriForTag(AndroidLogFormat *p_format, const char *tag, android_LogPriority pri) {
     return android_log_shouldPrintLine(p_format, tag, pri)
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..b62832e
--- /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) {
+#ifdef __ANDROID__
+    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);
+
+    // 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 nothing.\n";
+#endif
+}
diff --git a/liblog/tests/log_time_test.cpp b/liblog/tests/log_time_test.cpp
new file mode 100644
index 0000000..f2601b6
--- /dev/null
+++ b/liblog/tests/log_time_test.cpp
@@ -0,0 +1,43 @@
+/*
+ * 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 __ANDROID__
+
+#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);
+
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
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/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/libunwindstack/Log.h b/libunwindstack/Log.h
new file mode 100644
index 0000000..2d01aa8
--- /dev/null
+++ b/libunwindstack/Log.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_LOG_H
+#define _LIBUNWINDSTACK_LOG_H
+
+#include <stdint.h>
+
+void log_to_stdout(bool enable);
+void log(uint8_t indent, const char* format, ...);
+
+#endif  // _LIBUNWINDSTACK_LOG_H
diff --git a/libunwindstack/Machine.h b/libunwindstack/Machine.h
new file mode 100644
index 0000000..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/libunwindstack/tests/LogFake.h b/libunwindstack/tests/LogFake.h
new file mode 100644
index 0000000..006d393
--- /dev/null
+++ b/libunwindstack/tests/LogFake.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
+#define _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
+
+#include <string>
+
+void ResetLogs();
+std::string GetFakeLogBuf();
+std::string GetFakeLogPrint();
+
+#endif  // _LIBUNWINDSTACK_TESTS_LOG_FAKE_H
diff --git a/libunwindstack/tests/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/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index cc65d47..820ff64 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -1100,6 +1100,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 +1130,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/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/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 13a7922..2a6cdc8 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -853,11 +853,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 +889,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 +907,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);
 }