Merge "Replace "GL" naming with "GPU"."
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
index 6d77f4b..ac05d4c 100644
--- a/adb/daemon/usb.cpp
+++ b/adb/daemon/usb.cpp
@@ -64,7 +64,7 @@
 
 #define FUNCTIONFS_ENDPOINT_ALLOC       _IOR('g', 231, __u32)
 
-static constexpr size_t ENDPOINT_ALLOC_RETRIES = 10;
+static constexpr size_t ENDPOINT_ALLOC_RETRIES = 2;
 
 static int dummy_fd = -1;
 
diff --git a/adb/shell_service.cpp b/adb/shell_service.cpp
index 4975fab..d4f334b 100644
--- a/adb/shell_service.cpp
+++ b/adb/shell_service.cpp
@@ -320,6 +320,10 @@
         parent_error_sfd.reset(-1);
         close_on_exec(child_error_sfd);
 
+        // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
+        // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
+        signal(SIGPIPE, SIG_DFL);
+
         if (command_.empty()) {
             execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
         } else {
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index a7354a7..a4cc5f2 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -225,7 +225,12 @@
 void RecordBootloaderTimings(BootEventRecordStore* boot_event_store) {
   // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN'.
   std::string value = GetProperty("ro.boot.boottime");
+  if (value.empty()) {
+    // ro.boot.boottime is not reported on all devices.
+    return;
+  }
 
+  int32_t total_time = 0;
   auto stages = android::base::Split(value, ",");
   for (auto const &stageTiming : stages) {
     // |stageTiming| is of the form 'stage:time'.
@@ -235,10 +240,13 @@
     std::string stageName = stageTimingValues[0];
     int32_t time_ms;
     if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
+      total_time += time_ms;
       boot_event_store->AddBootEventWithValue(
           "boottime.bootloader." + stageName, time_ms);
     }
   }
+
+  boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
 }
 
 // Records several metrics related to the time it takes to boot the device,
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index ca881aa..8d2ea68 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -12,14 +12,48 @@
 }
 
 cc_library_static {
-    name: "libdebuggerd_handler",
+    name: "libdebuggerd_handler_core",
     defaults: ["debuggerd_defaults"],
     srcs: ["handler/debuggerd_handler.cpp"],
 
     // libdebuggerd_handler gets async signal safe logging via libc_logging,
     // which defines its interface in bionic private headers.
     include_dirs: ["bionic/libc"],
-    static_libs: ["libc_logging"],
+    whole_static_libs: [
+        "libc_logging",
+        "libdebuggerd",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+cc_library_static {
+    name: "libdebuggerd_handler",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["handler/debuggerd_fallback_nop.cpp"],
+
+    whole_static_libs: [
+        "libdebuggerd_handler_core",
+    ],
+
+    export_include_dirs: ["include"],
+}
+
+cc_library_static {
+    name: "libdebuggerd_handler_fallback",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["handler/debuggerd_fallback.cpp"],
+
+    // libdebuggerd_handler gets async signal safe logging via libc_logging,
+    // which defines its interface in bionic private headers.
+    include_dirs: ["bionic/libc"],
+    static_libs: [
+        "libdebuggerd",
+        "libbacktrace",
+        "libunwind",
+        "liblzma",
+        "libcutils",
+    ],
 
     export_include_dirs: ["include"],
 }
@@ -39,7 +73,7 @@
     export_include_dirs: ["include"],
 }
 
-cc_library {
+cc_library_static {
     name: "libdebuggerd",
     defaults: ["debuggerd_defaults"],
 
@@ -75,8 +109,10 @@
     local_include_dirs: ["libdebuggerd/include"],
     export_include_dirs: ["libdebuggerd/include"],
 
-    shared_libs: [
+    static_libs: [
         "libbacktrace",
+        "libunwind",
+        "liblzma",
         "libbase",
         "libcutils",
         "liblog",
@@ -150,10 +186,14 @@
         },
     },
 
+    static_libs: [
+        "libdebuggerd",
+        "libcutils",
+    ],
+
     shared_libs: [
         "libbacktrace",
         "libbase",
-        "libdebuggerd",
         "liblog",
         "libprocinfo",
         "libselinux",
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 0ca90c3..0e15472 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -155,6 +155,14 @@
     return false;
   }
 
+  // Make the fd O_APPEND so that our output is guaranteed to be at the end of a file.
+  // (This also makes selinux rules consistent, because selinux distinguishes between writing to
+  // a regular fd, and writing to an fd with O_APPEND).
+  int flags = fcntl(tmp_output_fd.get(), F_GETFL);
+  if (fcntl(tmp_output_fd.get(), F_SETFL, flags | O_APPEND) != 0) {
+    PLOG(WARNING) << "failed to set output fd flags";
+  }
+
   *tombstoned_socket = std::move(sockfd);
   *output_fd = std::move(tmp_output_fd);
   return true;
@@ -211,17 +219,6 @@
   }
 }
 
-static void check_process(int proc_fd, pid_t expected_pid) {
-  android::procinfo::ProcessInfo proc_info;
-  if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
-    LOG(FATAL) << "failed to fetch process info";
-  }
-
-  if (proc_info.pid != expected_pid) {
-    LOG(FATAL) << "pid mismatch: expected " << expected_pid << ", actual " << proc_info.ppid;
-  }
-}
-
 int main(int argc, char** argv) {
   pid_t target = getppid();
   bool tombstoned_connected = false;
@@ -254,7 +251,7 @@
   }
 
   if (!android::base::ParseInt(argv[2], &pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
-    LOG(FATAL) << "invalid pseudothread tid: " << argv[1];
+    LOG(FATAL) << "invalid pseudothread tid: " << argv[2];
   }
 
   android::procinfo::ProcessInfo target_info;
@@ -274,6 +271,11 @@
     PLOG(FATAL) << "failed to open " << target_proc_path;
   }
 
+  // Make sure our parent didn't die.
+  if (getppid() != target) {
+    PLOG(FATAL) << "parent died";
+  }
+
   // Reparent ourselves to init, so that the signal handler can waitpid on the
   // original process to avoid leaving a zombie for non-fatal dumps.
   pid_t forkpid = fork();
@@ -286,8 +288,6 @@
   // Die if we take too long.
   alarm(20);
 
-  check_process(target_proc_fd, target);
-
   std::string attach_error;
 
   // Seize the main thread.
@@ -329,7 +329,6 @@
 
   // Drop our capabilities now that we've attached to the threads we care about.
   drop_capabilities();
-  check_process(target_proc_fd, target);
 
   LOG(INFO) << "obtaining output fd from tombstoned";
   tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
@@ -387,8 +386,8 @@
   if (backtrace) {
     dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
   } else {
-    engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
-                      attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
+    engrave_tombstone(output_fd.get(), backtrace_map.get(), &open_files, target, main_tid,
+                      &attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
   }
 
   // We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
diff --git a/debuggerd/crasher/crasher.cpp b/debuggerd/crasher/crasher.cpp
index cd45bbb..1c01e3e 100644
--- a/debuggerd/crasher/crasher.cpp
+++ b/debuggerd/crasher/crasher.cpp
@@ -189,6 +189,7 @@
     fprintf(stderr, "  fprintf-NULL          pass a null pointer to fprintf\n");
     fprintf(stderr, "  readdir-NULL          pass a null pointer to readdir\n");
     fprintf(stderr, "  strlen-NULL           pass a null pointer to strlen\n");
+    fprintf(stderr, "  pthread_join-NULL     pass a null pointer to pthread_join\n");
     fprintf(stderr, "\n");
     fprintf(stderr, "  no_new_privs          set PR_SET_NO_NEW_PRIVS and then abort\n");
     fprintf(stderr, "\n");
@@ -258,6 +259,8 @@
         readdir_null();
     } else if (!strcasecmp(arg, "strlen-NULL")) {
         return strlen_null();
+    } else if (!strcasecmp(arg, "pthread_join-NULL")) {
+        return pthread_join(0, nullptr);
     } else if (!strcasecmp(arg, "heap-usage")) {
         abuse_heap();
     } else if (!strcasecmp(arg, "SIGSEGV-unmapped")) {
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
new file mode 100644
index 0000000..77ad6ac
--- /dev/null
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stddef.h>
+#include <sys/ucontext.h>
+#include <unistd.h>
+
+#include "tombstone.h"
+
+extern "C" void __linker_use_fallback_allocator();
+
+extern "C" bool debuggerd_fallback(ucontext_t* ucontext, siginfo_t* siginfo, void* abort_message) {
+  // This is incredibly sketchy to do inside of a signal handler, especially when libbacktrace
+  // uses the C++ standard library throughout, but this code runs in the linker, so we'll be using
+  // the linker's malloc instead of the libc one. Switch it out for a replacement, just in case.
+  //
+  // This isn't the default method of dumping because it can fail in cases such as memory space
+  // exhaustion.
+  __linker_use_fallback_allocator();
+  engrave_tombstone_ucontext(-1, getpid(), gettid(), reinterpret_cast<uintptr_t>(abort_message),
+                             siginfo, ucontext);
+  return true;
+}
diff --git a/debuggerd/handler/debuggerd_fallback_nop.cpp b/debuggerd/handler/debuggerd_fallback_nop.cpp
new file mode 100644
index 0000000..9b3053f
--- /dev/null
+++ b/debuggerd/handler/debuggerd_fallback_nop.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stddef.h>
+#include <sys/ucontext.h>
+#include <unistd.h>
+
+extern "C" bool debuggerd_fallback(ucontext_t*, siginfo_t*, void*) {
+  return false;
+}
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index a5de83a..67c26e2 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -62,6 +62,8 @@
 
 #define CRASH_DUMP_PATH "/system/bin/" CRASH_DUMP_NAME
 
+extern "C" bool debuggerd_fallback(ucontext_t*, siginfo_t*, void*);
+
 static debuggerd_callbacks_t g_callbacks;
 
 // Mutex to ensure only one crashing thread dumps itself.
@@ -81,7 +83,7 @@
   va_start(args, fmt);
 
   char buf[4096];
-  vsnprintf(buf, sizeof(buf), fmt, args);
+  __libc_format_buffer_va_list(buf, sizeof(buf), fmt, args);
   fatal("%s: %s", buf, strerror(err));
 }
 
@@ -200,7 +202,7 @@
   uint64_t capmask = capdata[0].inheritable;
   capmask |= static_cast<uint64_t>(capdata[1].inheritable) << 32;
   for (unsigned long i = 0; i < 64; ++i) {
-    if (capmask & (1 << i)) {
+    if (capmask & (1ULL << i)) {
       if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) != 0) {
         __libc_format_log(ANDROID_LOG_ERROR, "libc", "failed to raise ambient capability %lu: %s",
                           i, strerror(errno));
@@ -256,8 +258,9 @@
 
     char main_tid[10];
     char pseudothread_tid[10];
-    snprintf(main_tid, sizeof(main_tid), "%d", thread_info->crashing_tid);
-    snprintf(pseudothread_tid, sizeof(pseudothread_tid), "%d", thread_info->pseudothread_tid);
+    __libc_format_buffer(main_tid, sizeof(main_tid), "%d", thread_info->crashing_tid);
+    __libc_format_buffer(pseudothread_tid, sizeof(pseudothread_tid), "%d", thread_info->pseudothread_tid);
+
     execl(CRASH_DUMP_PATH, CRASH_DUMP_NAME, main_tid, pseudothread_tid, nullptr);
 
     fatal_errno("exec failed");
@@ -328,7 +331,7 @@
 
 // Handler that does crash dumping by forking and doing the processing in the child.
 // Do this by ptracing the relevant thread, and then execing debuggerd to do the actual dump.
-static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void*) {
+static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void* context) {
   int ret = pthread_mutex_lock(&crash_mutex);
   if (ret != 0) {
     __libc_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
@@ -358,18 +361,22 @@
 
   log_signal_summary(signal_number, info);
 
-  if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
-    // The process has NO_NEW_PRIVS enabled, so we can't transition to the crash_dump context.
-    __libc_format_log(ANDROID_LOG_INFO, "libc",
-                      "Suppressing debuggerd output because prctl(PR_GET_NO_NEW_PRIVS)==1");
-    resend_signal(info, false);
-    return;
-  }
-
   void* abort_message = nullptr;
   if (g_callbacks.get_abort_message) {
     abort_message = g_callbacks.get_abort_message();
   }
+
+  if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
+    ucontext_t* ucontext = static_cast<ucontext_t*>(context);
+    if (signal_number == DEBUGGER_SIGNAL || !debuggerd_fallback(ucontext, info, abort_message)) {
+      // The process has NO_NEW_PRIVS enabled, so we can't transition to the crash_dump context.
+      __libc_format_log(ANDROID_LOG_INFO, "libc",
+                        "Suppressing debuggerd output because prctl(PR_GET_NO_NEW_PRIVS)==1");
+    }
+    resend_signal(info, false);
+    return;
+  }
+
   // Populate si_value with the abort message address, if found.
   if (abort_message) {
     info->si_value.sival_ptr = abort_message;
diff --git a/debuggerd/libdebuggerd/include/tombstone.h b/debuggerd/libdebuggerd/include/tombstone.h
index 4ff24af..aed71de 100644
--- a/debuggerd/libdebuggerd/include/tombstone.h
+++ b/debuggerd/libdebuggerd/include/tombstone.h
@@ -35,8 +35,11 @@
 
 /* Creates a tombstone file and writes the crash dump to it. */
 void engrave_tombstone(int tombstone_fd, BacktraceMap* map,
-                       const OpenFilesList& open_files, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, uintptr_t abort_msg_address,
+                       const OpenFilesList* open_files, pid_t pid, pid_t tid,
+                       const std::set<pid_t>* siblings, uintptr_t abort_msg_address,
                        std::string* amfd_data);
 
+void engrave_tombstone_ucontext(int tombstone_fd, pid_t pid, pid_t tid, uintptr_t abort_msg_address,
+                                siginfo_t* siginfo, ucontext_t* ucontext);
+
 #endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index ac2c0b6..3166bfc 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -220,14 +220,8 @@
   if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
 }
 
-static void dump_signal_info(log_t* log, pid_t tid) {
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) == -1) {
-    ALOGE("cannot get siginfo: %s\n", strerror(errno));
-    return;
-  }
-
+static void dump_signal_info(log_t* log, const siginfo_t* siginfo) {
+  const siginfo_t& si = *siginfo;
   char addr_desc[32]; // ", fault addr 0x1234"
   if (signal_has_si_addr(si.si_signo, si.si_code)) {
     snprintf(addr_desc, sizeof(addr_desc), "%p", si.si_addr);
@@ -241,6 +235,17 @@
   dump_probable_cause(log, si);
 }
 
+static void dump_signal_info(log_t* log, pid_t tid) {
+  siginfo_t si;
+  memset(&si, 0, sizeof(si));
+  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) == -1) {
+    ALOGE("cannot get siginfo: %s\n", strerror(errno));
+    return;
+  }
+
+  dump_signal_info(log, &si);
+}
+
 static void dump_thread_info(log_t* log, pid_t pid, pid_t tid) {
   char path[64];
   char threadnamebuf[1024];
@@ -649,8 +654,8 @@
 
 // Dumps all information about the specified pid to the tombstone.
 static void dump_crash(log_t* log, BacktraceMap* map,
-                       const OpenFilesList& open_files, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, uintptr_t abort_msg_address) {
+                       const OpenFilesList* open_files, pid_t pid, pid_t tid,
+                       const std::set<pid_t>* siblings, uintptr_t abort_msg_address) {
   // don't copy log messages to tombstone unless this is a dev device
   char value[PROPERTY_VALUE_MAX];
   property_get("ro.debuggable", value, "0");
@@ -664,14 +669,16 @@
     dump_logs(log, pid, 5);
   }
 
-  if (!siblings.empty()) {
-    for (pid_t sibling : siblings) {
+  if (siblings && !siblings->empty()) {
+    for (pid_t sibling : *siblings) {
       dump_thread(log, pid, sibling, map, 0, false);
     }
   }
 
-  _LOG(log, logtype::OPEN_FILES, "\nopen files:\n");
-  dump_open_files_list_to_log(open_files, log, "    ");
+  if (open_files) {
+    _LOG(log, logtype::OPEN_FILES, "\nopen files:\n");
+    dump_open_files_list_to_log(*open_files, log, "    ");
+  }
 
   if (want_logs) {
     dump_logs(log, pid, 0);
@@ -732,19 +739,34 @@
 }
 
 void engrave_tombstone(int tombstone_fd, BacktraceMap* map,
-                       const OpenFilesList& open_files, pid_t pid, pid_t tid,
-                       const std::set<pid_t>& siblings, uintptr_t abort_msg_address,
+                       const OpenFilesList* open_files, pid_t pid, pid_t tid,
+                       const std::set<pid_t>* siblings, uintptr_t abort_msg_address,
                        std::string* amfd_data) {
   log_t log;
   log.current_tid = tid;
   log.crashed_tid = tid;
-
-  if (tombstone_fd < 0) {
-    ALOGE("debuggerd: skipping tombstone write, nothing to do.\n");
-    return;
-  }
-
   log.tfd = tombstone_fd;
   log.amfd_data = amfd_data;
   dump_crash(&log, map, open_files, pid, tid, siblings, abort_msg_address);
 }
+
+void engrave_tombstone_ucontext(int tombstone_fd, pid_t pid, pid_t tid, uintptr_t abort_msg_address,
+                                siginfo_t* siginfo, ucontext_t* ucontext) {
+  log_t log;
+  log.current_tid = tid;
+  log.crashed_tid = tid;
+  log.tfd = tombstone_fd;
+  log.amfd_data = nullptr;
+
+  dump_thread_info(&log, pid, tid);
+  dump_signal_info(&log, siginfo);
+
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
+  dump_abort_message(backtrace.get(), &log, abort_msg_address);
+  // TODO: Dump registers from the ucontext.
+  if (backtrace->Unwind(0, ucontext)) {
+    dump_backtrace_and_stack(backtrace.get(), &log);
+  } else {
+    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
+  }
+}
diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk
index 4369e5a..6939428 100644
--- a/fs_mgr/Android.mk
+++ b/fs_mgr/Android.mk
@@ -29,8 +29,7 @@
 LOCAL_C_INCLUDES := \
     $(LOCAL_PATH)/include \
     system/vold \
-    system/extras/ext4_utils \
-    bootable/recovery
+    system/extras/ext4_utils
 LOCAL_MODULE:= libfs_mgr
 LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
diff --git a/fs_mgr/fs_mgr_slotselect.cpp b/fs_mgr/fs_mgr_slotselect.cpp
index e957f6b..b30417f 100644
--- a/fs_mgr/fs_mgr_slotselect.cpp
+++ b/fs_mgr/fs_mgr_slotselect.cpp
@@ -33,53 +33,6 @@
 #include "fs_mgr.h"
 #include "fs_mgr_priv.h"
 
-#include "bootloader.h"
-
-// Copies slot_suffix from misc into |out_suffix|. Returns 0 on
-// success, -1 on error or if there is no non-empty slot_suffix.
-static int get_active_slot_suffix_from_misc(struct fstab *fstab,
-                                            char *out_suffix,
-                                            size_t suffix_len)
-{
-    int n;
-    int misc_fd;
-    ssize_t num_read;
-    struct bootloader_message_ab msg;
-
-    misc_fd = -1;
-    for (n = 0; n < fstab->num_entries; n++) {
-        if (strcmp(fstab->recs[n].mount_point, "/misc") == 0) {
-            misc_fd = open(fstab->recs[n].blk_device, O_RDONLY);
-            if (misc_fd == -1) {
-                PERROR << "Error opening misc partition '"
-                       << fstab->recs[n].blk_device << "'";
-                return -1;
-            } else {
-                break;
-            }
-        }
-    }
-
-    if (misc_fd == -1) {
-        LERROR << "Error finding misc partition";
-        return -1;
-    }
-
-    num_read = TEMP_FAILURE_RETRY(read(misc_fd, &msg, sizeof(msg)));
-    // Linux will never return partial reads when reading from block
-    // devices so no need to worry about them.
-    if (num_read != sizeof(msg)) {
-        PERROR << "Error reading bootloader_message";
-        close(misc_fd);
-        return -1;
-    }
-    close(misc_fd);
-    if (msg.slot_suffix[0] == '\0')
-        return -1;
-    strncpy(out_suffix, msg.slot_suffix, suffix_len);
-    return 0;
-}
-
 // finds slot_suffix in androidboot.slot_suffix kernel command line argument
 // or in the device tree node at /firmware/android/slot_suffix property
 static int get_active_slot_suffix_from_kernel(char *out_suffix,
@@ -123,11 +76,10 @@
     return -1;
 }
 
-// Gets slot_suffix from either the kernel cmdline / device tree / firmware
-// or the misc partition. Sets |out_suffix| on success and returns 0. Returns
-// -1 if slot_suffix could not be determined.
-static int get_active_slot_suffix(struct fstab *fstab, char *out_suffix,
-                                  size_t suffix_len)
+// Gets slot_suffix from either the kernel cmdline / device tree.  Sets
+// |out_suffix| on success and returns 0. Returns -1 if slot_suffix could not
+// be determined.
+static int get_active_slot_suffix(char *out_suffix, size_t suffix_len)
 {
     char propbuf[PROPERTY_VALUE_MAX];
 
@@ -140,22 +92,14 @@
         return 0;
     }
 
-    // if the property is not set, we are either being invoked too early
-    // or the slot suffix in mentioned in the misc partition. If its
-    // "too early", try to find the slotsuffix ourselves in the kernel command
-    // line or the device tree
+    // if the property is not set, we are probably being invoked early during
+    // boot.  Try to find the slotsuffix ourselves in the kernel command line
+    // or the device tree
     if (get_active_slot_suffix_from_kernel(out_suffix, suffix_len) == 0) {
         LINFO << "Using slot suffix '" << out_suffix << "' from kernel";
         return 0;
     }
 
-    // If we couldn't get the suffix from the kernel cmdline, try the
-    // the misc partition.
-    if (get_active_slot_suffix_from_misc(fstab, out_suffix, suffix_len) == 0) {
-        LINFO << "Using slot suffix '" << out_suffix << "' from misc";
-        return 0;
-    }
-
     LERROR << "Error determining slot_suffix";
 
     return -1;
@@ -174,8 +118,7 @@
 
             if (!got_suffix) {
                 memset(suffix, '\0', sizeof(suffix));
-                if (get_active_slot_suffix(fstab, suffix,
-                                           sizeof(suffix) - 1) != 0) {
+                if (get_active_slot_suffix(suffix, sizeof(suffix) - 1) != 0) {
                   return -1;
                 }
                 got_suffix = 1;
diff --git a/init/init.cpp b/init/init.cpp
index 9c1e23b..7f7eb2f 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -47,6 +47,7 @@
 #include <cutils/iosched_policy.h>
 #include <cutils/list.h>
 #include <cutils/sockets.h>
+#include <libavb/libavb.h>
 #include <private/android_filesystem_config.h>
 
 #include <fstream>
@@ -959,6 +960,9 @@
         property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
         property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
 
+        // Set libavb version for Framework-only OTA match in Treble build.
+        property_set("ro.boot.init.avb_version", std::to_string(AVB_MAJOR_VERSION).c_str());
+
         // Clean up our environment.
         unsetenv("INIT_SECOND_STAGE");
         unsetenv("INIT_STARTED_AT");
diff --git a/libutils/RefBase.cpp b/libutils/RefBase.cpp
index 1f8395b..4252ba6 100644
--- a/libutils/RefBase.cpp
+++ b/libutils/RefBase.cpp
@@ -22,7 +22,6 @@
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <typeinfo>
 #include <unistd.h>
 
 #include <utils/RefBase.h>
diff --git a/libutils/primes.py b/libutils/primes.py
deleted file mode 100755
index e161dd8..0000000
--- a/libutils/primes.py
+++ /dev/null
@@ -1,47 +0,0 @@
-#!/usr/bin/env python2.6
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-#
-# Generates a table of prime numbers for use in BasicHashtable.cpp.
-#
-# Each prime is chosen such that it is a little more than twice as large as
-# the previous prime in the table.  This makes it easier to choose a new
-# hashtable size when the underlying array is grown by as nominal factor
-# of two each time.
-#
-
-def is_odd_prime(n):
-  limit = (n - 1) / 2
-  d = 3
-  while d <= limit:
-    if n % d == 0:
-      return False
-    d += 2
-  return True
-
-print "static size_t PRIMES[] = {"
-
-n = 5
-max = 2**31 - 1
-while n < max:
-  print "    %d," % (n)
-  n = n * 2 + 1
-  while not is_odd_prime(n):
-    n += 2
-
-print "    0,"
-print "};"
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 7613c1e..e03731b 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -183,7 +183,8 @@
     lenr -= avcr - msgr;
     if (lenl != lenr) return DIFFERENT;
     if (fastcmp<memcmp>(avcl + strlen(avc),
-                        avcr + strlen(avc), lenl)) return DIFFERENT;
+                        avcr + strlen(avc),
+                        lenl - strlen(avc))) return DIFFERENT;
     return SAME;
 }
 
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index 36bb443..09db7b0 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -13,7 +13,7 @@
     onrestart restart wificond
     writepid /dev/cpuset/foreground/tasks
 
-service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
+service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload
     class main
     priority -20
     user root
diff --git a/storaged/storaged_uid_monitor.cpp b/storaged/storaged_uid_monitor.cpp
index 3b893b5..49d0d48 100644
--- a/storaged/storaged_uid_monitor.cpp
+++ b/storaged/storaged_uid_monitor.cpp
@@ -204,18 +204,23 @@
         }
 
         struct uid_io_usage& usage = curr_io_stats[uid.name];
-        usage.bytes[READ][FOREGROUND][charger_stat] +=
-            uid.io[FOREGROUND].read_bytes -
+        int64_t fg_rd_delta = uid.io[FOREGROUND].read_bytes -
             last_uid_io_stats[uid.uid].io[FOREGROUND].read_bytes;
-        usage.bytes[READ][BACKGROUND][charger_stat] +=
-            uid.io[BACKGROUND].read_bytes -
+        int64_t bg_rd_delta = uid.io[BACKGROUND].read_bytes -
             last_uid_io_stats[uid.uid].io[BACKGROUND].read_bytes;
-        usage.bytes[WRITE][FOREGROUND][charger_stat] +=
-            uid.io[FOREGROUND].write_bytes -
+        int64_t fg_wr_delta = uid.io[FOREGROUND].write_bytes -
             last_uid_io_stats[uid.uid].io[FOREGROUND].write_bytes;
+        int64_t bg_wr_delta = uid.io[BACKGROUND].write_bytes -
+            last_uid_io_stats[uid.uid].io[BACKGROUND].write_bytes;
+
+        usage.bytes[READ][FOREGROUND][charger_stat] +=
+            (fg_rd_delta < 0) ? uid.io[FOREGROUND].read_bytes : fg_rd_delta;
+        usage.bytes[READ][BACKGROUND][charger_stat] +=
+            (bg_rd_delta < 0) ? uid.io[BACKGROUND].read_bytes : bg_rd_delta;
+        usage.bytes[WRITE][FOREGROUND][charger_stat] +=
+            (fg_wr_delta < 0) ? uid.io[FOREGROUND].write_bytes : fg_wr_delta;
         usage.bytes[WRITE][BACKGROUND][charger_stat] +=
-            uid.io[BACKGROUND].write_bytes -
-            last_uid_io_stats[uid.uid].io[BACKGROUND].write_bytes;;
+            (bg_wr_delta < 0) ? uid.io[BACKGROUND].write_bytes : bg_wr_delta;
     }
 
     last_uid_io_stats = uid_io_stats;