adb: move adb_strerror to sysdeps/win32/errno.cpp.
am: 4fba3d2638

Change-Id: Ibdfa8ebbcfee5baf459f82fd13e1a0e8167c5053
diff --git a/adb/adb_client.cpp b/adb/adb_client.cpp
index 0b1ba32..ef52189 100644
--- a/adb/adb_client.cpp
+++ b/adb/adb_client.cpp
@@ -46,21 +46,11 @@
 
 static const char* __adb_server_socket_spec;
 
-void adb_set_transport(TransportType type, const char* serial)
-{
+void adb_set_transport(TransportType type, const char* serial) {
     __adb_transport = type;
     __adb_serial = serial;
 }
 
-void adb_get_transport(TransportType* type, const char** serial) {
-    if (type) {
-        *type = __adb_transport;
-    }
-    if (serial) {
-        *serial = __adb_serial;
-    }
-}
-
 void adb_set_socket_spec(const char* socket_spec) {
     if (__adb_server_socket_spec) {
         LOG(FATAL) << "attempted to reinitialize adb_server_socket_spec " << socket_spec << " (was " << __adb_server_socket_spec << ")";
diff --git a/adb/adb_client.h b/adb/adb_client.h
index d35d705..d07c1e9 100644
--- a/adb/adb_client.h
+++ b/adb/adb_client.h
@@ -40,9 +40,6 @@
 // Set the preferred transport to connect to.
 void adb_set_transport(TransportType type, const char* _Nullable serial);
 
-// Get the preferred transport to connect to.
-void adb_get_transport(TransportType* _Nullable type, const char* _Nullable* _Nullable serial);
-
 // Set the socket specification for the adb server.
 // This function can only be called once, and the argument must live to the end of the process.
 void adb_set_socket_spec(const char* _Nonnull socket_spec);
diff --git a/adb/bugreport.cpp b/adb/bugreport.cpp
index 143c62a..9b59d05 100644
--- a/adb/bugreport.cpp
+++ b/adb/bugreport.cpp
@@ -21,7 +21,6 @@
 #include <string>
 #include <vector>
 
-#include <android-base/parseint.h>
 #include <android-base/strings.h>
 
 #include "sysdeps.h"
@@ -144,11 +143,9 @@
             //
             size_t idx1 = line.rfind(BUGZ_PROGRESS_PREFIX) + strlen(BUGZ_PROGRESS_PREFIX);
             size_t idx2 = line.rfind(BUGZ_PROGRESS_SEPARATOR);
-            int progress, total;
-            if (android::base::ParseInt(line.substr(idx1, (idx2 - idx1)), &progress) &&
-                android::base::ParseInt(line.substr(idx2 + 1), &total)) {
-                br_->UpdateProgress(line_message_, progress, total);
-            }
+            int progress = std::stoi(line.substr(idx1, (idx2 - idx1)));
+            int total = std::stoi(line.substr(idx2 + 1));
+            br_->UpdateProgress(line_message_, progress, total);
         } else {
             invalid_lines_.push_back(line);
         }
diff --git a/base/Android.bp b/base/Android.bp
index e6ad15b..b9a6e0b 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -49,6 +49,11 @@
             srcs: ["errors_unix.cpp"],
             cppflags: ["-Wexit-time-destructors"],
         },
+        linux_bionic: {
+            srcs: ["errors_unix.cpp"],
+            cppflags: ["-Wexit-time-destructors"],
+            enabled: true,
+        },
         linux: {
             srcs: ["errors_unix.cpp"],
             cppflags: ["-Wexit-time-destructors"],
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index ba8f81c..c96e996 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -11,13 +11,8 @@
 on post-fs-data && property:init.svc.bootanim=running
     exec - root root -- /system/bin/bootstat -r post_decrypt_time_elapsed
 
-# The first marker, boot animation stopped, is considered the point at which
-# the user may interact with the device, so it is a good proxy for the boot
-# complete signal.
-#
-# The second marker ensures an encrypted device is decrypted before logging
-# boot time data.
-on property:init.svc.bootanim=stopped && property:vold.decrypt=trigger_restart_framework
+# Record boot complete metrics.
+on property:sys.boot_completed=1
     # Record boot_complete and related stats (decryption, etc).
     exec - root root -- /system/bin/bootstat --record_boot_complete
 
diff --git a/debuggerd/Android.mk b/debuggerd/Android.mk
index 155b309..607745d 100644
--- a/debuggerd/Android.mk
+++ b/debuggerd/Android.mk
@@ -18,6 +18,7 @@
     debuggerd.cpp \
     elf_utils.cpp \
     getevent.cpp \
+    open_files_list.cpp \
     signal_sender.cpp \
     tombstone.cpp \
     utility.cpp \
@@ -108,9 +109,11 @@
 
 debuggerd_test_src_files := \
     utility.cpp \
+    open_files_list.cpp \
     test/dump_memory_test.cpp \
     test/elf_fake.cpp \
     test/log_fake.cpp \
+    test/open_files_list_test.cpp \
     test/property_fake.cpp \
     test/ptrace_fake.cpp \
     test/tombstone_test.cpp \
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 5ae66db..9b82f64 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -55,6 +55,7 @@
 
 #include "backtrace.h"
 #include "getevent.h"
+#include "open_files_list.h"
 #include "signal_sender.h"
 #include "tombstone.h"
 #include "utility.h"
@@ -184,6 +185,16 @@
    return allowed;
 }
 
+static bool pid_contains_tid(pid_t pid, pid_t tid) {
+  char task_path[PATH_MAX];
+  if (snprintf(task_path, PATH_MAX, "/proc/%d/task/%d", pid, tid) >= PATH_MAX) {
+    ALOGE("debuggerd: task path overflow (pid = %d, tid = %d)\n", pid, tid);
+    exit(1);
+  }
+
+  return access(task_path, F_OK) == 0;
+}
+
 static int read_request(int fd, debugger_request_t* out_request) {
   ucred cr;
   socklen_t len = sizeof(cr);
@@ -226,16 +237,13 @@
 
   if (msg.action == DEBUGGER_ACTION_CRASH) {
     // Ensure that the tid reported by the crashing process is valid.
-    char buf[64];
-    struct stat s;
-    snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid);
-    if (stat(buf, &s)) {
-      ALOGE("tid %d does not exist in pid %d. ignoring debug request\n",
-          out_request->tid, out_request->pid);
+    // This check needs to happen again after ptracing the requested thread to prevent a race.
+    if (!pid_contains_tid(out_request->pid, out_request->tid)) {
+      ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid,
+            out_request->pid);
       return -1;
     }
-  } else if (cr.uid == 0
-            || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
+  } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
     // Only root or system can ask us to attach to any process and dump it explicitly.
     // However, system is only allowed to collect backtraces but cannot dump tombstones.
     status = get_process_info(out_request->tid, &out_request->pid,
@@ -412,10 +420,31 @@
 }
 #endif
 
-static void ptrace_siblings(pid_t pid, pid_t main_tid, pid_t ignore_tid, std::set<pid_t>& tids) {
-  char task_path[64];
+// Attach to a thread, and verify that it's still a member of the given process
+static bool ptrace_attach_thread(pid_t pid, pid_t tid) {
+  if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) {
+    return false;
+  }
 
-  snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
+  // Make sure that the task we attached to is actually part of the pid we're dumping.
+  if (!pid_contains_tid(pid, tid)) {
+    if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
+      ALOGE("debuggerd: failed to detach from thread '%d'", tid);
+      exit(1);
+    }
+    return false;
+  }
+
+  return true;
+}
+
+static void ptrace_siblings(pid_t pid, pid_t main_tid, pid_t ignore_tid, std::set<pid_t>& tids) {
+  char task_path[PATH_MAX];
+
+  if (snprintf(task_path, PATH_MAX, "/proc/%d/task", pid) >= PATH_MAX) {
+    ALOGE("debuggerd: task path overflow (pid = %d)\n", pid);
+    abort();
+  }
 
   std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
 
@@ -442,7 +471,7 @@
       continue;
     }
 
-    if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) {
+    if (!ptrace_attach_thread(pid, tid)) {
       ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
       continue;
     }
@@ -452,7 +481,8 @@
 }
 
 static bool perform_dump(const debugger_request_t& request, int fd, int tombstone_fd,
-                         BacktraceMap* backtrace_map, const std::set<pid_t>& siblings,
+                         BacktraceMap* backtrace_map, const OpenFilesList& open_files,
+                         const std::set<pid_t>& siblings,
                          int* crash_signal, std::string* amfd_data) {
   if (TEMP_FAILURE_RETRY(write(fd, "\0", 1)) != 1) {
     ALOGE("debuggerd: failed to respond to client: %s\n", strerror(errno));
@@ -471,7 +501,8 @@
       case SIGSTOP:
         if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
           ALOGV("debuggerd: stopped -- dumping to tombstone");
-          engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings,
+          engrave_tombstone(tombstone_fd, backtrace_map, open_files,
+                            request.pid, request.tid, siblings,
                             request.abort_msg_address, amfd_data);
         } else if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE) {
           ALOGV("debuggerd: stopped -- dumping to fd");
@@ -498,7 +529,8 @@
       case SIGTRAP:
         ALOGV("stopped -- fatal signal\n");
         *crash_signal = signal;
-        engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings,
+        engrave_tombstone(tombstone_fd, backtrace_map, open_files,
+                          request.pid, request.tid, siblings,
                           request.abort_msg_address, amfd_data);
         break;
 
@@ -568,11 +600,33 @@
   // debugger_signal_handler().
 
   // Attach to the target process.
-  if (ptrace(PTRACE_ATTACH, request.tid, 0, 0) != 0) {
+  if (!ptrace_attach_thread(request.pid, request.tid)) {
     ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno));
     exit(1);
   }
 
+  // DEBUGGER_ACTION_CRASH requests can come from arbitrary processes and the tid field in the
+  // request is sent from the other side. If an attacker can cause a process to be spawned with the
+  // pid of their process, they could trick debuggerd into dumping that process by exiting after
+  // sending the request. Validate the trusted request.uid/gid to defend against this.
+  if (request.action == DEBUGGER_ACTION_CRASH) {
+    pid_t pid;
+    uid_t uid;
+    gid_t gid;
+    if (get_process_info(request.tid, &pid, &uid, &gid) != 0) {
+      ALOGE("debuggerd: failed to get process info for tid '%d'", request.tid);
+      exit(1);
+    }
+
+    if (pid != request.pid || uid != request.uid || gid != request.gid) {
+      ALOGE(
+        "debuggerd: attached task %d does not match request: "
+        "expected pid=%d,uid=%d,gid=%d, actual pid=%d,uid=%d,gid=%d",
+        request.tid, request.pid, request.uid, request.gid, pid, uid, gid);
+      exit(1);
+    }
+  }
+
   // Don't attach to the sibling threads if we want to attach gdb.
   // Supposedly, it makes the process less reliable.
   bool attach_gdb = should_attach_gdb(request);
@@ -593,6 +647,10 @@
   // Generate the backtrace map before dropping privileges.
   std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid));
 
+  // Collect the list of open files before dropping privileges.
+  OpenFilesList open_files;
+  populate_open_files_list(request.pid, &open_files);
+
   int amfd = -1;
   std::unique_ptr<std::string> amfd_data;
   if (request.action == DEBUGGER_ACTION_CRASH) {
@@ -610,8 +668,8 @@
   }
 
   int crash_signal = SIGKILL;
-  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings,
-                           &crash_signal, amfd_data.get());
+  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), open_files,
+                           siblings, &crash_signal, amfd_data.get());
   if (succeeded) {
     if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
       if (!tombstone_path.empty()) {
diff --git a/debuggerd/open_files_list.cpp b/debuggerd/open_files_list.cpp
new file mode 100644
index 0000000..5ef2abc
--- /dev/null
+++ b/debuggerd/open_files_list.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include <dirent.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android/log.h>
+
+#include "open_files_list.h"
+
+#include "utility.h"
+
+void populate_open_files_list(pid_t pid, OpenFilesList* list) {
+  std::string fd_dir_name = "/proc/" + std::to_string(pid) + "/fd";
+  std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(fd_dir_name.c_str()), closedir);
+  if (dir == nullptr) {
+    ALOGE("failed to open directory %s: %s", fd_dir_name.c_str(), strerror(errno));
+    return;
+  }
+
+  struct dirent* de;
+  while ((de = readdir(dir.get())) != nullptr) {
+    if (*de->d_name == '.') {
+      continue;
+    }
+
+    int fd = atoi(de->d_name);
+    std::string path = fd_dir_name + "/" + std::string(de->d_name);
+    std::string target;
+    if (android::base::Readlink(path, &target)) {
+      list->emplace_back(fd, target);
+    } else {
+      ALOGE("failed to readlink %s: %s", path.c_str(), strerror(errno));
+      list->emplace_back(fd, "???");
+    }
+  }
+}
+
+void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix) {
+  for (auto& file : files) {
+    _LOG(log, logtype::OPEN_FILES, "%sfd %i: %s\n", prefix, file.first, file.second.c_str());
+  }
+}
+
diff --git a/debuggerd/open_files_list.h b/debuggerd/open_files_list.h
new file mode 100644
index 0000000..b37228d
--- /dev/null
+++ b/debuggerd/open_files_list.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _DEBUGGERD_OPEN_FILES_LIST_H
+#define _DEBUGGERD_OPEN_FILES_LIST_H
+
+#include <sys/types.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "utility.h"
+
+typedef std::vector<std::pair<int, std::string>> OpenFilesList;
+
+/* Populates the given list with open files for the given process. */
+void populate_open_files_list(pid_t pid, OpenFilesList* list);
+
+/* Dumps the open files list to the log. */
+void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix);
+
+#endif // _DEBUGGERD_OPEN_FILES_LIST_H
diff --git a/debuggerd/test/open_files_list_test.cpp b/debuggerd/test/open_files_list_test.cpp
new file mode 100644
index 0000000..85e0695
--- /dev/null
+++ b/debuggerd/test/open_files_list_test.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <gtest/gtest.h>
+
+#include "android-base/test_utils.h"
+
+#include "open_files_list.h"
+
+// Check that we can produce a list of open files for the current process, and
+// that it includes a known open file.
+TEST(OpenFilesListTest, BasicTest) {
+  // Open a temporary file that we can check for in the list of open files.
+  TemporaryFile tf;
+
+  // Get the list of open files for this process.
+  OpenFilesList list;
+  populate_open_files_list(getpid(), &list);
+
+  // Verify our open file is in the list.
+  bool found = false;
+  for (auto&  file : list) {
+    if (file.first == tf.fd) {
+      EXPECT_EQ(file.second, std::string(tf.path));
+      found = true;
+      break;
+    }
+  }
+  EXPECT_TRUE(found);
+}
diff --git a/debuggerd/tombstone.cpp b/debuggerd/tombstone.cpp
index b9fbe07..e76edb9 100644
--- a/debuggerd/tombstone.cpp
+++ b/debuggerd/tombstone.cpp
@@ -46,6 +46,7 @@
 #include "backtrace.h"
 #include "elf_utils.h"
 #include "machine.h"
+#include "open_files_list.h"
 #include "tombstone.h"
 
 #define STACK_WORDS 16
@@ -620,7 +621,8 @@
 }
 
 // Dumps all information about the specified pid to the tombstone.
-static void dump_crash(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid,
+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) {
   // don't copy log messages to tombstone unless this is a dev device
   bool want_logs = __android_log_is_debuggable();
@@ -639,6 +641,9 @@
     }
   }
 
+  _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);
   }
@@ -697,7 +702,8 @@
   return fd;
 }
 
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map, pid_t pid, pid_t tid,
+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,
                        std::string* amfd_data) {
   log_t log;
@@ -711,5 +717,5 @@
 
   log.tfd = tombstone_fd;
   log.amfd_data = amfd_data;
-  dump_crash(&log, map, pid, tid, siblings, abort_msg_address);
+  dump_crash(&log, map, open_files, pid, tid, siblings, abort_msg_address);
 }
diff --git a/debuggerd/tombstone.h b/debuggerd/tombstone.h
index e1c39c5..126f804 100644
--- a/debuggerd/tombstone.h
+++ b/debuggerd/tombstone.h
@@ -32,7 +32,8 @@
 int open_tombstone(std::string* path);
 
 /* Creates a tombstone file and writes the crash dump to it. */
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map, pid_t pid, pid_t tid,
+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,
                        std::string* amfd_data);
 
diff --git a/debuggerd/utility.h b/debuggerd/utility.h
index d820f0f..f7a3f73 100644
--- a/debuggerd/utility.h
+++ b/debuggerd/utility.h
@@ -70,7 +70,8 @@
   MAPS,
   MEMORY,
   STACK,
-  LOGS
+  LOGS,
+  OPEN_FILES
 };
 
 // Log information onto the tombstone.
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c
index e0d46d3..740720b 100644
--- a/fs_mgr/fs_mgr.c
+++ b/fs_mgr/fs_mgr.c
@@ -242,7 +242,7 @@
     return ret;
 }
 
-static int fs_match(const char *in1, const char *in2)
+static int fs_match(char *in1, char *in2)
 {
     char *n1;
     char *n2;
@@ -652,7 +652,7 @@
  * If multiple fstab entries are to be mounted on "n_name", it will try to mount each one
  * in turn, and stop on 1st success, or no more match.
  */
-int fs_mgr_do_mount(struct fstab *fstab, const char *n_name, char *n_blk_device,
+int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device,
                     char *tmp_mount_point)
 {
     int i = 0;
diff --git a/fs_mgr/fs_mgr_fstab.c b/fs_mgr/fs_mgr_fstab.c
index b219b38..0bc8bef 100644
--- a/fs_mgr/fs_mgr_fstab.c
+++ b/fs_mgr/fs_mgr_fstab.c
@@ -33,11 +33,12 @@
     int swap_prio;
     int max_comp_streams;
     unsigned int zram_size;
+    unsigned int file_encryption_mode;
 };
 
 struct flag_list {
     const char *name;
-    unsigned flag;
+    unsigned int flag;
 };
 
 static struct flag_list mount_flags[] = {
@@ -64,7 +65,7 @@
     { "check",       MF_CHECK },
     { "encryptable=",MF_CRYPT },
     { "forceencrypt=",MF_FORCECRYPT },
-    { "fileencryption",MF_FILEENCRYPTION },
+    { "fileencryption=",MF_FILEENCRYPTION },
     { "forcefdeorfbe=",MF_FORCEFDEORFBE },
     { "nonremovable",MF_NONREMOVABLE },
     { "voldmanaged=",MF_VOLDMANAGED},
@@ -84,6 +85,15 @@
     { 0,             0 },
 };
 
+#define EM_SOFTWARE 1
+#define EM_ICE      2
+
+static struct flag_list encryption_modes[] = {
+    {"software", EM_SOFTWARE},
+    {"ice", EM_ICE},
+    {0, 0}
+};
+
 static uint64_t calculate_zram_size(unsigned int percentage)
 {
     uint64_t total;
@@ -150,6 +160,21 @@
                      * location of the keys.  Get it and return it.
                      */
                     flag_vals->key_loc = strdup(strchr(p, '=') + 1);
+                    flag_vals->file_encryption_mode = EM_SOFTWARE;
+                } else if ((fl[i].flag == MF_FILEENCRYPTION) && flag_vals) {
+                    /* The fileencryption flag is followed by an = and the
+                     * type of the encryption.  Get it and return it.
+                     */
+                    const struct flag_list *j;
+                    const char *mode = strchr(p, '=') + 1;
+                    for (j = encryption_modes; j->name; ++j) {
+                        if (!strcmp(mode, j->name)) {
+                            flag_vals->file_encryption_mode = j->flag;
+                        }
+                    }
+                    if (flag_vals->file_encryption_mode == 0) {
+                        ERROR("Unknown file encryption mode: %s\n", mode);
+                    }
                 } else if ((fl[i].flag == MF_LENGTH) && flag_vals) {
                     /* The length flag is followed by an = and the
                      * size of the partition.  Get it and return it.
@@ -335,6 +360,7 @@
         fstab->recs[cnt].swap_prio = flag_vals.swap_prio;
         fstab->recs[cnt].max_comp_streams = flag_vals.max_comp_streams;
         fstab->recs[cnt].zram_size = flag_vals.zram_size;
+        fstab->recs[cnt].file_encryption_mode = flag_vals.file_encryption_mode;
         cnt++;
     }
     /* If an A/B partition, modify block device to be the real block device */
@@ -493,6 +519,17 @@
     return fstab->fs_mgr_flags & MF_FILEENCRYPTION;
 }
 
+const char* fs_mgr_get_file_encryption_mode(const struct fstab_rec *fstab)
+{
+    const struct flag_list *j;
+    for (j = encryption_modes; j->name; ++j) {
+        if (fstab->file_encryption_mode == j->flag) {
+            return j->name;
+        }
+    }
+    return NULL;
+}
+
 int fs_mgr_is_convertible_to_fbe(const struct fstab_rec *fstab)
 {
     return fstab->fs_mgr_flags & MF_FORCEFDEORFBE;
diff --git a/fs_mgr/fs_mgr_main.c b/fs_mgr/fs_mgr_main.c
index 4bfe202..33a7496 100644
--- a/fs_mgr/fs_mgr_main.c
+++ b/fs_mgr/fs_mgr_main.c
@@ -14,17 +14,12 @@
  * limitations under the License.
  */
 
-#define _GNU_SOURCE
-
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#include <libgen.h>
 #include "fs_mgr_priv.h"
 
-#ifdef _LIBGEN_H
-#warning "libgen.h must not be included"
-#endif
-
 char *me = "";
 
 static void usage(void)
@@ -37,10 +32,10 @@
  * and exit the program, do not return to the caller.
  * Return the number of argv[] entries consumed.
  */
-static void parse_options(int argc, char * const argv[], int *a_flag, int *u_flag, int *n_flag,
-                     const char **n_name, const char **n_blk_dev)
+static void parse_options(int argc, char *argv[], int *a_flag, int *u_flag, int *n_flag,
+                     char **n_name, char **n_blk_dev)
 {
-    me = basename(argv[0]);
+    me = basename(strdup(argv[0]));
 
     if (argc <= 1) {
         usage();
@@ -80,14 +75,14 @@
     return;
 }
 
-int main(int argc, char * const argv[])
+int main(int argc, char *argv[])
 {
     int a_flag=0;
     int u_flag=0;
     int n_flag=0;
-    const char *n_name=NULL;
-    const char *n_blk_dev=NULL;
-    const char *fstab_file=NULL;
+    char *n_name=NULL;
+    char *n_blk_dev=NULL;
+    char *fstab_file=NULL;
     struct fstab *fstab=NULL;
 
     klog_set_level(6);
@@ -102,7 +97,7 @@
     if (a_flag) {
         return fs_mgr_mount_all(fstab, MOUNT_MODE_DEFAULT);
     } else if (n_flag) {
-        return fs_mgr_do_mount(fstab, n_name, (char *)n_blk_dev, 0);
+        return fs_mgr_do_mount(fstab, n_name, n_blk_dev, 0);
     } else if (u_flag) {
         return fs_mgr_unmount_all(fstab);
     } else {
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index 67104cc..031b042 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -181,7 +181,7 @@
     return -1;
 }
 
-static void verity_ioctl_init(struct dm_ioctl *io, char *name, unsigned flags)
+static void verity_ioctl_init(struct dm_ioctl *io, const char *name, unsigned flags)
 {
     memset(io, 0, DM_BUF_SIZE);
     io->data_size = DM_BUF_SIZE;
@@ -784,8 +784,9 @@
 int fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback)
 {
     alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
+    bool system_root = false;
     char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
-    char *mount_point;
+    const char *mount_point;
     char propbuf[PROPERTY_VALUE_MAX];
     char *status;
     int fd = -1;
@@ -813,6 +814,9 @@
     property_get("ro.hardware", propbuf, "");
     snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
 
+    property_get("ro.build.system_root_image", propbuf, "");
+    system_root = !strcmp(propbuf, "true");
+
     fstab = fs_mgr_read_fstab(fstab_filename);
 
     if (!fstab) {
@@ -825,7 +829,12 @@
             continue;
         }
 
-        mount_point = basename(fstab->recs[i].mount_point);
+        if (system_root && !strcmp(fstab->recs[i].mount_point, "/")) {
+            mount_point = "system";
+        } else {
+            mount_point = basename(fstab->recs[i].mount_point);
+        }
+
         verity_ioctl_init(io, mount_point, 0);
 
         if (ioctl(fd, DM_TABLE_STATUS, io)) {
@@ -836,7 +845,9 @@
 
         status = &buffer[io->data_start + sizeof(struct dm_target_spec)];
 
-        callback(&fstab->recs[i], mount_point, mode, *status);
+        if (*status == 'C' || *status == 'V') {
+            callback(&fstab->recs[i], mount_point, mode, *status);
+        }
     }
 
     rc = 0;
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index 37df8f8..9323069 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -75,6 +75,7 @@
     int swap_prio;
     int max_comp_streams;
     unsigned int zram_size;
+    unsigned int file_encryption_mode;
 };
 
 // Callback function for verity status
@@ -96,7 +97,8 @@
 
 #define FS_MGR_DOMNT_FAILED (-1)
 #define FS_MGR_DOMNT_BUSY (-2)
-int fs_mgr_do_mount(struct fstab *fstab, const char *n_name, char *n_blk_device,
+
+int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device,
                     char *tmp_mount_point);
 int fs_mgr_do_tmpfs_mount(char *n_name);
 int fs_mgr_unmount_all(struct fstab *fstab);
@@ -113,6 +115,7 @@
 int fs_mgr_is_verified(const struct fstab_rec *fstab);
 int fs_mgr_is_encryptable(const struct fstab_rec *fstab);
 int fs_mgr_is_file_encrypted(const struct fstab_rec *fstab);
+const char* fs_mgr_get_file_encryption_mode(const struct fstab_rec *fstab);
 int fs_mgr_is_convertible_to_fbe(const struct fstab_rec *fstab);
 int fs_mgr_is_noemulatedsd(const struct fstab_rec *fstab);
 int fs_mgr_is_notrim(struct fstab_rec *fstab);
diff --git a/healthd/Android.mk b/healthd/Android.mk
index deebed5..7c5e35b 100644
--- a/healthd/Android.mk
+++ b/healthd/Android.mk
@@ -21,6 +21,36 @@
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
+LOCAL_SRC_FILES := \
+    healthd_mode_android.cpp \
+    healthd_mode_charger.cpp \
+    AnimationParser.cpp \
+    BatteryPropertiesRegistrar.cpp \
+
+LOCAL_MODULE := libhealthd_internal
+LOCAL_C_INCLUDES := bootable/recovery
+LOCAL_EXPORT_C_INCLUDE_DIRS := \
+    $(LOCAL_PATH) \
+    $(LOCAL_PATH)/include \
+
+LOCAL_STATIC_LIBRARIES := \
+    libbatterymonitor \
+    libbatteryservice \
+    libbinder \
+    libminui \
+    libpng \
+    libz \
+    libutils \
+    libbase \
+    libcutils \
+    liblog \
+    libm \
+    libc \
+
+include $(BUILD_STATIC_LIBRARY)
+
+
+include $(CLEAR_VARS)
 
 ifeq ($(strip $(BOARD_CHARGER_NO_UI)),true)
 LOCAL_CHARGER_NO_UI := true
@@ -32,7 +62,7 @@
 LOCAL_SRC_FILES := \
 	healthd.cpp \
 	healthd_mode_android.cpp \
-	BatteryPropertiesRegistrar.cpp
+	BatteryPropertiesRegistrar.cpp \
 
 ifneq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
 LOCAL_SRC_FILES += healthd_mode_charger.cpp
@@ -60,13 +90,28 @@
 
 LOCAL_C_INCLUDES := bootable/recovery $(LOCAL_PATH)/include
 
-LOCAL_STATIC_LIBRARIES := libbatterymonitor libbatteryservice libbinder libbase
+LOCAL_STATIC_LIBRARIES := \
+    libhealthd_internal \
+    libbatterymonitor \
+    libbatteryservice \
+    libbinder \
+    libbase \
 
 ifneq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
-LOCAL_STATIC_LIBRARIES += libminui libpng libz
+LOCAL_STATIC_LIBRARIES += \
+   libminui \
+   libpng \
+   libz \
+
 endif
 
-LOCAL_STATIC_LIBRARIES += libutils libcutils liblog libm libc
+
+LOCAL_STATIC_LIBRARIES += \
+    libutils \
+    libcutils \
+    liblog \
+    libm \
+    libc \
 
 ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
 LOCAL_STATIC_LIBRARIES += libsuspend
@@ -84,7 +129,7 @@
 ifneq ($(strip $(LOCAL_CHARGER_NO_UI)),true)
 define _add-charger-image
 include $$(CLEAR_VARS)
-LOCAL_MODULE := system_core_charger_$(notdir $(1))
+LOCAL_MODULE := system_core_charger_res_images_$(notdir $(1))
 LOCAL_MODULE_STEM := $(notdir $(1))
 _img_modules += $$(LOCAL_MODULE)
 LOCAL_SRC_FILES := $1
diff --git a/healthd/AnimationParser.cpp b/healthd/AnimationParser.cpp
new file mode 100644
index 0000000..864038b
--- /dev/null
+++ b/healthd/AnimationParser.cpp
@@ -0,0 +1,141 @@
+/*
+ * 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 "AnimationParser.h"
+
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include <cutils/klog.h>
+
+#include "animation.h"
+
+#define LOGE(x...) do { KLOG_ERROR("charger", x); } while (0)
+#define LOGW(x...) do { KLOG_WARNING("charger", x); } while (0)
+#define LOGV(x...) do { KLOG_DEBUG("charger", x); } while (0)
+
+namespace android {
+
+// Lines consisting of only whitespace or whitespace followed by '#' can be ignored.
+bool can_ignore_line(const char* str) {
+    for (int i = 0; str[i] != '\0' && str[i] != '#'; i++) {
+        if (!isspace(str[i])) return false;
+    }
+    return true;
+}
+
+bool remove_prefix(const std::string& line, const char* prefix, const char** rest) {
+    const char* str = line.c_str();
+    int start;
+    char c;
+
+    std::string format = base::StringPrintf(" %s%%n%%c", prefix);
+    if (sscanf(str, format.c_str(), &start, &c) != 1) {
+        return false;
+    }
+
+    *rest = &str[start];
+    return true;
+}
+
+bool parse_text_field(const char* in, animation::text_field* field) {
+    int* x = &field->pos_x;
+    int* y = &field->pos_y;
+    int* r = &field->color_r;
+    int* g = &field->color_g;
+    int* b = &field->color_b;
+    int* a = &field->color_a;
+
+    int start = 0, end = 0;
+
+    if (sscanf(in, "c c %d %d %d %d %n%*s%n", r, g, b, a, &start, &end) == 4) {
+        *x = CENTER_VAL;
+        *y = CENTER_VAL;
+    } else if (sscanf(in, "c %d %d %d %d %d %n%*s%n", y, r, g, b, a, &start, &end) == 5) {
+        *x = CENTER_VAL;
+    } else if (sscanf(in, "%d c %d %d %d %d %n%*s%n", x, r, g, b, a, &start, &end) == 5) {
+        *y = CENTER_VAL;
+    } else if (sscanf(in, "%d %d %d %d %d %d %n%*s%n", x, y, r, g, b, a, &start, &end) != 6) {
+        return false;
+    }
+
+    if (end == 0) return false;
+
+    field->font_file.assign(&in[start], end - start);
+
+    return true;
+}
+
+bool parse_animation_desc(const std::string& content, animation* anim) {
+    static constexpr const char* animation_prefix = "animation: ";
+    static constexpr const char* fail_prefix = "fail: ";
+    static constexpr const char* clock_prefix = "clock_display: ";
+    static constexpr const char* percent_prefix = "percent_display: ";
+    static constexpr const char* frame_prefix = "frame: ";
+
+    std::vector<animation::frame> frames;
+
+    for (const auto& line : base::Split(content, "\n")) {
+        animation::frame frame;
+        const char* rest;
+
+        if (can_ignore_line(line.c_str())) {
+            continue;
+        } else if (remove_prefix(line, animation_prefix, &rest)) {
+            int start = 0, end = 0;
+            if (sscanf(rest, "%d %d %n%*s%n", &anim->num_cycles, &anim->first_frame_repeats,
+                    &start, &end) != 2 ||
+                end == 0) {
+                LOGE("Bad animation format: %s\n", line.c_str());
+                return false;
+            } else {
+                anim->animation_file.assign(&rest[start], end - start);
+            }
+        } else if (remove_prefix(line, fail_prefix, &rest)) {
+            anim->fail_file.assign(rest);
+        } else if (remove_prefix(line, clock_prefix, &rest)) {
+            if (!parse_text_field(rest, &anim->text_clock)) {
+                LOGE("Bad clock_display format: %s\n", line.c_str());
+                return false;
+            }
+        } else if (remove_prefix(line, percent_prefix, &rest)) {
+            if (!parse_text_field(rest, &anim->text_percent)) {
+                LOGE("Bad percent_display format: %s\n", line.c_str());
+                return false;
+            }
+        } else if (sscanf(line.c_str(), " frame: %d %d %d",
+                &frame.disp_time, &frame.min_level, &frame.max_level) == 3) {
+            frames.push_back(std::move(frame));
+        } else {
+            LOGE("Malformed animation description line: %s\n", line.c_str());
+            return false;
+        }
+    }
+
+    if (anim->animation_file.empty() || frames.empty()) {
+        LOGE("Bad animation description. Provide the 'animation: ' line and at least one 'frame: ' "
+             "line.\n");
+        return false;
+    }
+
+    anim->num_frames = frames.size();
+    anim->frames = new animation::frame[frames.size()];
+    std::copy(frames.begin(), frames.end(), anim->frames);
+
+    return true;
+}
+
+}  // namespace android
diff --git a/healthd/AnimationParser.h b/healthd/AnimationParser.h
new file mode 100644
index 0000000..bc00845
--- /dev/null
+++ b/healthd/AnimationParser.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HEALTHD_ANIMATION_PARSER_H
+#define HEALTHD_ANIMATION_PARSER_H
+
+#include "animation.h"
+
+namespace android {
+
+bool parse_animation_desc(const std::string& content, animation* anim);
+
+bool can_ignore_line(const char* str);
+bool remove_prefix(const std::string& str, const char* prefix, const char** rest);
+bool parse_text_field(const char* in, animation::text_field* field);
+}  // namespace android
+
+#endif // HEALTHD_ANIMATION_PARSER_H
diff --git a/healthd/animation.h b/healthd/animation.h
new file mode 100644
index 0000000..562b689
--- /dev/null
+++ b/healthd/animation.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HEALTHD_ANIMATION_H
+#define HEALTHD_ANIMATION_H
+
+#include <inttypes.h>
+#include <string>
+
+struct GRSurface;
+struct GRFont;
+
+namespace android {
+
+#define CENTER_VAL INT_MAX
+
+struct animation {
+    struct frame {
+        int disp_time;
+        int min_level;
+        int max_level;
+
+        GRSurface* surface;
+    };
+
+    struct text_field {
+        std::string font_file;
+        int pos_x;
+        int pos_y;
+        int color_r;
+        int color_g;
+        int color_b;
+        int color_a;
+
+        GRFont* font;
+    };
+
+    std::string animation_file;
+    std::string fail_file;
+
+    text_field text_clock;
+    text_field text_percent;
+
+    bool run;
+
+    frame* frames;
+    int cur_frame;
+    int num_frames;
+    int first_frame_repeats;  // Number of times to repeat the first frame in the current cycle
+
+    int cur_cycle;
+    int num_cycles;  // Number of cycles to complete before blanking the screen
+
+    int cur_level;  // current battery level being animated (0-100)
+    int cur_status;  // current battery status - see BatteryService.h for BATTERY_STATUS_*
+};
+
+}
+
+#endif // HEALTHD_ANIMATION_H
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index 857bcb2..36c4664 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -30,6 +30,9 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+
 #include <sys/socket.h>
 #include <linux/netlink.h>
 
@@ -44,10 +47,14 @@
 #include <suspend/autosuspend.h>
 #endif
 
+#include "animation.h"
+#include "AnimationParser.h"
 #include "minui/minui.h"
 
 #include <healthd/healthd.h>
 
+using namespace android;
+
 char *locale;
 
 #ifndef max
@@ -67,8 +74,6 @@
 #define POWER_ON_KEY_TIME       (2 * MSEC_PER_SEC)
 #define UNPLUGGED_SHUTDOWN_TIME (10 * MSEC_PER_SEC)
 
-#define BATTERY_FULL_THRESH     95
-
 #define LAST_KMSG_PATH          "/proc/last_kmsg"
 #define LAST_KMSG_PSTORE_PATH   "/sys/fs/pstore/console-ramoops"
 #define LAST_KMSG_MAX_SZ        (32 * 1024)
@@ -77,34 +82,14 @@
 #define LOGW(x...) do { KLOG_WARNING("charger", x); } while (0)
 #define LOGV(x...) do { KLOG_DEBUG("charger", x); } while (0)
 
+static constexpr const char* animation_desc_path = "/res/values/charger/animation.txt";
+
 struct key_state {
     bool pending;
     bool down;
     int64_t timestamp;
 };
 
-struct frame {
-    int disp_time;
-    int min_capacity;
-    bool level_only;
-
-    GRSurface* surface;
-};
-
-struct animation {
-    bool run;
-
-    struct frame *frames;
-    int cur_frame;
-    int num_frames;
-
-    int cur_cycle;
-    int num_cycles;
-
-    /* current capacity being animated */
-    int capacity;
-};
-
 struct charger {
     bool have_battery_state;
     bool charger_connected;
@@ -119,54 +104,83 @@
     int boot_min_cap;
 };
 
-static struct frame batt_anim_frames[] = {
+static const struct animation BASE_ANIMATION = {
+    .text_clock = {
+        .pos_x = 0,
+        .pos_y = 0,
+
+        .color_r = 255,
+        .color_g = 255,
+        .color_b = 255,
+        .color_a = 255,
+
+        .font = nullptr,
+    },
+    .text_percent = {
+        .pos_x = 0,
+        .pos_y = 0,
+
+        .color_r = 255,
+        .color_g = 255,
+        .color_b = 255,
+        .color_a = 255,
+    },
+
+    .run = false,
+
+    .frames = nullptr,
+    .cur_frame = 0,
+    .num_frames = 0,
+    .first_frame_repeats = 2,
+
+    .cur_cycle = 0,
+    .num_cycles = 3,
+
+    .cur_level = 0,
+    .cur_status = BATTERY_STATUS_UNKNOWN,
+};
+
+
+static struct animation::frame default_animation_frames[] = {
     {
         .disp_time = 750,
-        .min_capacity = 0,
-        .level_only = false,
+        .min_level = 0,
+        .max_level = 19,
         .surface = NULL,
     },
     {
         .disp_time = 750,
-        .min_capacity = 20,
-        .level_only = false,
+        .min_level = 0,
+        .max_level = 39,
         .surface = NULL,
     },
     {
         .disp_time = 750,
-        .min_capacity = 40,
-        .level_only = false,
+        .min_level = 0,
+        .max_level = 59,
         .surface = NULL,
     },
     {
         .disp_time = 750,
-        .min_capacity = 60,
-        .level_only = false,
+        .min_level = 0,
+        .max_level = 79,
         .surface = NULL,
     },
     {
         .disp_time = 750,
-        .min_capacity = 80,
-        .level_only = true,
+        .min_level = 80,
+        .max_level = 95,
         .surface = NULL,
     },
     {
         .disp_time = 750,
-        .min_capacity = BATTERY_FULL_THRESH,
-        .level_only = false,
+        .min_level = 0,
+        .max_level = 100,
         .surface = NULL,
     },
 };
 
-static struct animation battery_animation = {
-    .run = false,
-    .frames = batt_anim_frames,
-    .cur_frame = 0,
-    .num_frames = ARRAY_SIZE(batt_anim_frames),
-    .cur_cycle = 0,
-    .num_cycles = 3,
-    .capacity = 0,
-};
+static struct animation battery_animation = BASE_ANIMATION;
 
 static struct charger charger_state;
 static struct healthd_config *healthd_config;
@@ -273,8 +287,79 @@
     gr_color(0xa4, 0xc6, 0x39, 255);
 }
 
+// Negative x or y coordinates position the text away from the opposite edge that positive ones do.
+void determine_xy(const animation::text_field& field, const int length, int* x, int* y)
+{
+    *x = field.pos_x;
+    *y = field.pos_y;
+
+    int str_len_px = length * field.font->char_width;
+    if (field.pos_x == CENTER_VAL) {
+        *x = (gr_fb_width() - str_len_px) / 2;
+    } else if (field.pos_x >= 0) {
+        *x = field.pos_x;
+    } else {  // position from max edge
+        *x = gr_fb_width() + field.pos_x - str_len_px;
+    }
+
+    if (field.pos_y == CENTER_VAL) {
+        *y = (gr_fb_height() - field.font->char_height) / 2;
+    } else if (field.pos_y >= 0) {
+        *y = field.pos_y;
+    } else {  // position from max edge
+        *y = gr_fb_height() + field.pos_y - field.font->char_height;
+    }
+}
+
+static void draw_clock(const animation& anim)
+{
+    static constexpr char CLOCK_FORMAT[] = "%H:%M";
+    static constexpr int CLOCK_LENGTH = 6;
+
+    const animation::text_field& field = anim.text_clock;
+
+    if (field.font == nullptr || field.font->char_width == 0 || field.font->char_height == 0) return;
+
+    time_t rawtime;
+    time(&rawtime);
+    struct tm* time_info = localtime(&rawtime);
+
+    char clock_str[CLOCK_LENGTH];
+    size_t length = strftime(clock_str, CLOCK_LENGTH, CLOCK_FORMAT, time_info);
+    if (length != CLOCK_LENGTH - 1) {
+        LOGE("Could not format time\n");
+        return;
+    }
+
+    int x, y;
+    determine_xy(field, length, &x, &y);
+
+    LOGV("drawing clock %s %d %d\n", clock_str, x, y);
+    gr_color(field.color_r, field.color_g, field.color_b, field.color_a);
+    gr_text(field.font, x, y, clock_str, false);
+}
+
+static void draw_percent(const animation& anim)
+{
+    if (anim.cur_level <= 0 || anim.cur_status != BATTERY_STATUS_CHARGING) return;
+
+    const animation::text_field& field = anim.text_percent;
+    if (field.font == nullptr || field.font->char_width == 0 || field.font->char_height == 0) {
+        return;
+    }
+
+    std::string str = base::StringPrintf("%d%%", anim.cur_level);
+
+    int x, y;
+    determine_xy(field, str.size(), &x, &y);
+
+    LOGV("drawing percent %s %d %d\n", str.c_str(), x, y);
+    gr_color(field.color_r, field.color_g, field.color_b, field.color_a);
+    gr_text(field.font, x, y, str.c_str(), false);
+}
+
 /* returns the last y-offset of where the surface ends */
-static int draw_surface_centered(struct charger* /*charger*/, GRSurface* surface)
+static int draw_surface_centered(GRSurface* surface)
 {
     int w;
     int h;
@@ -295,7 +380,7 @@
 {
     int y;
     if (charger->surf_unknown) {
-        draw_surface_centered(charger, charger->surf_unknown);
+        draw_surface_centered(charger->surf_unknown);
     } else {
         android_green();
         y = draw_text("Charging!", -1, -1);
@@ -303,17 +388,19 @@
     }
 }
 
-static void draw_battery(struct charger *charger)
+static void draw_battery(const struct charger* charger)
 {
-    struct animation *batt_anim = charger->batt_anim;
-    struct frame *frame = &batt_anim->frames[batt_anim->cur_frame];
+    const struct animation& anim = *charger->batt_anim;
+    const struct animation::frame& frame = anim.frames[anim.cur_frame];
 
-    if (batt_anim->num_frames != 0) {
-        draw_surface_centered(charger, frame->surface);
+    if (anim.num_frames != 0) {
+        draw_surface_centered(frame.surface);
         LOGV("drawing frame #%d min_cap=%d time=%d\n",
-             batt_anim->cur_frame, frame->min_capacity,
-             frame->disp_time);
+             anim.cur_frame, frame.min_level,
+             frame.disp_time);
     }
+    draw_clock(anim);
+    draw_percent(anim);
 }
 
 static void redraw_screen(struct charger *charger)
@@ -323,7 +410,7 @@
     clear_screen();
 
     /* try to display *something* */
-    if (batt_anim->capacity < 0 || batt_anim->num_frames == 0)
+    if (batt_anim->cur_level < 0 || batt_anim->num_frames == 0)
         draw_unknown(charger);
     else
         draw_battery(charger);
@@ -342,16 +429,33 @@
     anim->run = false;
 }
 
+static void init_status_display(struct animation* anim)
+{
+    int res;
+
+    if (!anim->text_clock.font_file.empty()) {
+        if ((res =
+                gr_init_font(anim->text_clock.font_file.c_str(), &anim->text_clock.font)) < 0) {
+            LOGE("Could not load time font (%d)\n", res);
+        }
+    }
+
+    if (!anim->text_percent.font_file.empty()) {
+        if ((res =
+                gr_init_font(anim->text_percent.font_file.c_str(), &anim->text_percent.font)) < 0) {
+            LOGE("Could not load percent font (%d)\n", res);
+        }
+    }
+}
+
 static void update_screen_state(struct charger *charger, int64_t now)
 {
     struct animation *batt_anim = charger->batt_anim;
     int disp_time;
 
-    if (!batt_anim->run || now < charger->next_screen_transition)
-        return;
+    if (!batt_anim->run || now < charger->next_screen_transition) return;
 
     if (!minui_inited) {
-
         if (healthd_config && healthd_config->screen_on) {
             if (!healthd_config->screen_on(batt_prop)) {
                 LOGV("[%" PRId64 "] leave screen off\n", now);
@@ -365,6 +469,7 @@
 
         gr_init();
         gr_font_size(gr_sys_font(), &char_width, &char_height);
+        init_status_display(batt_anim);
 
 #ifndef CHARGER_DISABLE_INIT_BLANK
         gr_fb_blank(true);
@@ -373,7 +478,7 @@
     }
 
     /* animation is over, blank screen and leave */
-    if (batt_anim->cur_cycle == batt_anim->num_cycles) {
+    if (batt_anim->num_cycles > 0 && batt_anim->cur_cycle == batt_anim->num_cycles) {
         reset_animation(batt_anim);
         charger->next_screen_transition = -1;
         gr_fb_blank(true);
@@ -389,21 +494,24 @@
     if (batt_anim->cur_frame == 0) {
 
         LOGV("[%" PRId64 "] animation starting\n", now);
-        if (batt_prop && batt_prop->batteryLevel >= 0 && batt_anim->num_frames != 0) {
-            int i;
+        if (batt_prop) {
+            batt_anim->cur_level = batt_prop->batteryLevel;
+            batt_anim->cur_status = batt_prop->batteryStatus;
+            if (batt_prop->batteryLevel >= 0 && batt_anim->num_frames != 0) {
+                /* find first frame given current battery level */
+                for (int i = 0; i < batt_anim->num_frames; i++) {
+                    if (batt_anim->cur_level >= batt_anim->frames[i].min_level &&
+                        batt_anim->cur_level <= batt_anim->frames[i].max_level) {
+                        batt_anim->cur_frame = i;
+                        break;
+                    }
+                }
 
-            /* find first frame given current capacity */
-            for (i = 1; i < batt_anim->num_frames; i++) {
-                if (batt_prop->batteryLevel < batt_anim->frames[i].min_capacity)
-                    break;
+                // repeat the first frame first_frame_repeats times
+                disp_time = batt_anim->frames[batt_anim->cur_frame].disp_time *
+                    batt_anim->first_frame_repeats;
             }
-            batt_anim->cur_frame = i - 1;
-
-            /* show the first frame for twice as long */
-            disp_time = batt_anim->frames[batt_anim->cur_frame].disp_time * 2;
         }
-        if (batt_prop)
-            batt_anim->capacity = batt_prop->batteryLevel;
     }
 
     /* unblank the screen  on first cycle */
@@ -416,8 +524,8 @@
     /* if we don't have anim frames, we only have one image, so just bump
      * the cycle counter and exit
      */
-    if (batt_anim->num_frames == 0 || batt_anim->capacity < 0) {
-        LOGV("[%" PRId64 "] animation missing or unknown battery status\n", now);
+    if (batt_anim->num_frames == 0 || batt_anim->cur_level < 0) {
+        LOGW("[%" PRId64 "] animation missing or unknown battery status\n", now);
         charger->next_screen_transition = now + BATTERY_UNKNOWN_TIME;
         batt_anim->cur_cycle++;
         return;
@@ -432,12 +540,11 @@
     if (charger->charger_connected) {
         batt_anim->cur_frame++;
 
-        /* if the frame is used for level-only, that is only show it when it's
-         * the current level, skip it during the animation.
-         */
         while (batt_anim->cur_frame < batt_anim->num_frames &&
-               batt_anim->frames[batt_anim->cur_frame].level_only)
+               (batt_anim->cur_level < batt_anim->frames[batt_anim->cur_frame].min_level ||
+                batt_anim->cur_level > batt_anim->frames[batt_anim->cur_frame].max_level)) {
             batt_anim->cur_frame++;
+        }
         if (batt_anim->cur_frame >= batt_anim->num_frames) {
             batt_anim->cur_cycle++;
             batt_anim->cur_frame = 0;
@@ -521,7 +628,7 @@
                     LOGW("[%" PRId64 "] booting from charger mode\n", now);
                     property_set("sys.boot_from_charger_mode", "1");
                 } else {
-                    if (charger->batt_anim->capacity >= charger->boot_min_cap) {
+                    if (charger->batt_anim->cur_level >= charger->boot_min_cap) {
                         LOGW("[%" PRId64 "] rebooting\n", now);
                         android_reboot(ANDROID_RB_RESTART, 0, 0);
                     } else {
@@ -672,6 +779,52 @@
         ev_dispatch();
 }
 
+animation* init_animation()
+{
+    bool parse_success;
+
+    std::string content;
+    if (base::ReadFileToString(animation_desc_path, &content)) {
+        parse_success = parse_animation_desc(content, &battery_animation);
+    } else {
+        LOGW("Could not open animation description at %s\n", animation_desc_path);
+        parse_success = false;
+    }
+
+    if (!parse_success) {
+        LOGW("Could not parse animation description. Using default animation.\n");
+        battery_animation = BASE_ANIMATION;
+        battery_animation.animation_file.assign("charger/battery_scale");
+        battery_animation.frames = default_animation_frames;
+        battery_animation.num_frames = ARRAY_SIZE(default_animation_frames);
+    }
+    if (battery_animation.fail_file.empty()) {
+        battery_animation.fail_file.assign("charger/battery_fail");
+    }
+
+    LOGV("Animation Description:\n");
+    LOGV("  animation: %d %d '%s' (%d)\n",
+        battery_animation.num_cycles, battery_animation.first_frame_repeats,
+        battery_animation.animation_file.c_str(), battery_animation.num_frames);
+    LOGV("  fail_file: '%s'\n", battery_animation.fail_file.c_str());
+    LOGV("  clock: %d %d %d %d %d %d '%s'\n",
+        battery_animation.text_clock.pos_x, battery_animation.text_clock.pos_y,
+        battery_animation.text_clock.color_r, battery_animation.text_clock.color_g,
+        battery_animation.text_clock.color_b, battery_animation.text_clock.color_a,
+        battery_animation.text_clock.font_file.c_str());
+    LOGV("  percent: %d %d %d %d %d %d '%s'\n",
+        battery_animation.text_percent.pos_x, battery_animation.text_percent.pos_y,
+        battery_animation.text_percent.color_r, battery_animation.text_percent.color_g,
+        battery_animation.text_percent.color_b, battery_animation.text_percent.color_a,
+        battery_animation.text_percent.font_file.c_str());
+    for (int i = 0; i < battery_animation.num_frames; i++) {
+        LOGV("  frame %.2d: %d %d %d\n", i, battery_animation.frames[i].disp_time,
+            battery_animation.frames[i].min_level, battery_animation.frames[i].max_level);
+    }
+
+    return &battery_animation;
+}
+
 void healthd_mode_charger_init(struct healthd_config* config)
 {
     int ret;
@@ -689,35 +842,39 @@
         healthd_register_event(epollfd, charger_event_handler);
     }
 
-    ret = res_create_display_surface("charger/battery_fail", &charger->surf_unknown);
-    if (ret < 0) {
-        LOGE("Cannot load battery_fail image\n");
-        charger->surf_unknown = NULL;
-    }
+    struct animation* anim = init_animation();
+    charger->batt_anim = anim;
 
-    charger->batt_anim = &battery_animation;
+    ret = res_create_display_surface(anim->fail_file.c_str(), &charger->surf_unknown);
+    if (ret < 0) {
+        LOGE("Cannot load custom battery_fail image. Reverting to built in.\n");
+        ret = res_create_display_surface("charger/battery_fail", &charger->surf_unknown);
+        if (ret < 0) {
+            LOGE("Cannot load built in battery_fail image\n");
+            charger->surf_unknown = NULL;
+        }
+    }
 
     GRSurface** scale_frames;
     int scale_count;
     int scale_fps;  // Not in use (charger/battery_scale doesn't have FPS text
                     // chunk). We are using hard-coded frame.disp_time instead.
-    ret = res_create_multi_display_surface("charger/battery_scale", &scale_count, &scale_fps,
-                                           &scale_frames);
+    ret = res_create_multi_display_surface(anim->animation_file.c_str(),
+        &scale_count, &scale_fps, &scale_frames);
     if (ret < 0) {
         LOGE("Cannot load battery_scale image\n");
-        charger->batt_anim->num_frames = 0;
-        charger->batt_anim->num_cycles = 1;
-    } else if (scale_count != charger->batt_anim->num_frames) {
+        anim->num_frames = 0;
+        anim->num_cycles = 1;
+    } else if (scale_count != anim->num_frames) {
         LOGE("battery_scale image has unexpected frame count (%d, expected %d)\n",
-             scale_count, charger->batt_anim->num_frames);
-        charger->batt_anim->num_frames = 0;
-        charger->batt_anim->num_cycles = 1;
+             scale_count, anim->num_frames);
+        anim->num_frames = 0;
+        anim->num_cycles = 1;
     } else {
-        for (i = 0; i < charger->batt_anim->num_frames; i++) {
-            charger->batt_anim->frames[i].surface = scale_frames[i];
+        for (i = 0; i < anim->num_frames; i++) {
+            anim->frames[i].surface = scale_frames[i];
         }
     }
-
     ev_sync_key_state(set_key_callback, charger);
 
     charger->next_screen_transition = -1;
diff --git a/healthd/tests/Android.mk b/healthd/tests/Android.mk
new file mode 100644
index 0000000..87e8862
--- /dev/null
+++ b/healthd/tests/Android.mk
@@ -0,0 +1,21 @@
+# Copyright 2016 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+    AnimationParser_test.cpp \
+
+LOCAL_MODULE := healthd_test
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_STATIC_LIBRARIES := \
+	libhealthd_internal \
+
+LOCAL_SHARED_LIBRARIES := \
+	liblog \
+	libbase \
+	libcutils \
+
+include $(BUILD_NATIVE_TEST)
diff --git a/healthd/tests/AnimationParser_test.cpp b/healthd/tests/AnimationParser_test.cpp
new file mode 100644
index 0000000..2fc3185
--- /dev/null
+++ b/healthd/tests/AnimationParser_test.cpp
@@ -0,0 +1,192 @@
+/*
+ * 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 "AnimationParser.h"
+
+#include <gtest/gtest.h>
+
+using namespace android;
+
+TEST(AnimationParserTest, Test_can_ignore_line) {
+    EXPECT_TRUE(can_ignore_line(""));
+    EXPECT_TRUE(can_ignore_line("     "));
+    EXPECT_TRUE(can_ignore_line("#"));
+    EXPECT_TRUE(can_ignore_line("   # comment"));
+
+    EXPECT_FALSE(can_ignore_line("text"));
+    EXPECT_FALSE(can_ignore_line("text # comment"));
+    EXPECT_FALSE(can_ignore_line("     text"));
+    EXPECT_FALSE(can_ignore_line("     text # comment"));
+}
+
+TEST(AnimationParserTest, Test_remove_prefix) {
+    static const char TEST_STRING[] = "abcdef";
+    const char* rest = nullptr;
+    EXPECT_FALSE(remove_prefix(TEST_STRING, "def", &rest));
+    // Ignore strings that only consist of the prefix
+    EXPECT_FALSE(remove_prefix(TEST_STRING, TEST_STRING, &rest));
+
+    EXPECT_TRUE(remove_prefix(TEST_STRING, "abc", &rest));
+    EXPECT_STREQ("def", rest);
+
+    EXPECT_TRUE(remove_prefix("  abcdef", "abc", &rest));
+    EXPECT_STREQ("def", rest);
+}
+
+TEST(AnimationParserTest, Test_parse_text_field) {
+    static const char TEST_FILE_NAME[] = "font_file";
+    static const int TEST_X = 3;
+    static const int TEST_Y = 6;
+    static const int TEST_R = 1;
+    static const int TEST_G = 2;
+    static const int TEST_B = 4;
+    static const int TEST_A = 8;
+
+    static const char TEST_XCENT_YCENT[] = "c c 1 2 4 8  font_file ";
+    static const char TEST_XCENT_YVAL[]  = "c 6 1 2 4 8  font_file ";
+    static const char TEST_XVAL_YCENT[]  = "3 c 1 2 4 8  font_file ";
+    static const char TEST_XVAL_YVAL[]   = "3 6 1 2 4 8  font_file ";
+    static const char TEST_BAD_MISSING[] = "c c 1 2 4 font_file";
+    static const char TEST_BAD_NO_FILE[] = "c c 1 2 4 8";
+
+    animation::text_field out;
+
+    EXPECT_TRUE(parse_text_field(TEST_XCENT_YCENT, &out));
+    EXPECT_EQ(CENTER_VAL, out.pos_x);
+    EXPECT_EQ(CENTER_VAL, out.pos_y);
+    EXPECT_EQ(TEST_R, out.color_r);
+    EXPECT_EQ(TEST_G, out.color_g);
+    EXPECT_EQ(TEST_B, out.color_b);
+    EXPECT_EQ(TEST_A, out.color_a);
+    EXPECT_STREQ(TEST_FILE_NAME, out.font_file.c_str());
+
+    EXPECT_TRUE(parse_text_field(TEST_XCENT_YVAL, &out));
+    EXPECT_EQ(CENTER_VAL, out.pos_x);
+    EXPECT_EQ(TEST_Y, out.pos_y);
+    EXPECT_EQ(TEST_R, out.color_r);
+    EXPECT_EQ(TEST_G, out.color_g);
+    EXPECT_EQ(TEST_B, out.color_b);
+    EXPECT_EQ(TEST_A, out.color_a);
+    EXPECT_STREQ(TEST_FILE_NAME, out.font_file.c_str());
+
+    EXPECT_TRUE(parse_text_field(TEST_XVAL_YCENT, &out));
+    EXPECT_EQ(TEST_X, out.pos_x);
+    EXPECT_EQ(CENTER_VAL, out.pos_y);
+    EXPECT_EQ(TEST_R, out.color_r);
+    EXPECT_EQ(TEST_G, out.color_g);
+    EXPECT_EQ(TEST_B, out.color_b);
+    EXPECT_EQ(TEST_A, out.color_a);
+    EXPECT_STREQ(TEST_FILE_NAME, out.font_file.c_str());
+
+    EXPECT_TRUE(parse_text_field(TEST_XVAL_YVAL, &out));
+    EXPECT_EQ(TEST_X, out.pos_x);
+    EXPECT_EQ(TEST_Y, out.pos_y);
+    EXPECT_EQ(TEST_R, out.color_r);
+    EXPECT_EQ(TEST_G, out.color_g);
+    EXPECT_EQ(TEST_B, out.color_b);
+    EXPECT_EQ(TEST_A, out.color_a);
+    EXPECT_STREQ(TEST_FILE_NAME, out.font_file.c_str());
+
+    EXPECT_FALSE(parse_text_field(TEST_BAD_MISSING, &out));
+    EXPECT_FALSE(parse_text_field(TEST_BAD_NO_FILE, &out));
+}
+
+TEST(AnimationParserTest, Test_parse_animation_desc_basic) {
+    static const char TEST_ANIMATION[] = R"desc(
+        # Basic animation
+        animation: 5 1 test/animation_file
+        frame: 1000 0 100
+    )desc";
+    animation anim;
+
+    EXPECT_TRUE(parse_animation_desc(TEST_ANIMATION, &anim));
+}
+
+TEST(AnimationParserTest, Test_parse_animation_desc_bad_no_animation_line) {
+    static const char TEST_ANIMATION[] = R"desc(
+        # Bad animation
+        frame: 1000 90  10
+    )desc";
+    animation anim;
+
+    EXPECT_FALSE(parse_animation_desc(TEST_ANIMATION, &anim));
+}
+
+TEST(AnimationParserTest, Test_parse_animation_desc_bad_no_frame) {
+    static const char TEST_ANIMATION[] = R"desc(
+        # Bad animation
+        animation: 5 1 test/animation_file
+    )desc";
+    animation anim;
+
+    EXPECT_FALSE(parse_animation_desc(TEST_ANIMATION, &anim));
+}
+
+TEST(AnimationParserTest, Test_parse_animation_desc_bad_animation_line_format) {
+    static const char TEST_ANIMATION[] = R"desc(
+        # Bad animation
+        animation: 5 1
+        frame: 1000 90  10
+    )desc";
+    animation anim;
+
+    EXPECT_FALSE(parse_animation_desc(TEST_ANIMATION, &anim));
+}
+
+TEST(AnimationParserTest, Test_parse_animation_desc_full) {
+    static const char TEST_ANIMATION[] = R"desc(
+        # Full animation
+        animation: 5 1 test/animation_file
+        clock_display:    11 12 13 14 15 16 test/time_font
+        percent_display:  21 22 23 24 25 26 test/percent_font
+
+        frame: 10 20 30
+        frame: 40 50 60
+    )desc";
+    animation anim;
+
+    EXPECT_TRUE(parse_animation_desc(TEST_ANIMATION, &anim));
+
+    EXPECT_EQ(5, anim.num_cycles);
+    EXPECT_EQ(1, anim.first_frame_repeats);
+    EXPECT_STREQ("test/animation_file", anim.animation_file.c_str());
+
+    EXPECT_EQ(11, anim.text_clock.pos_x);
+    EXPECT_EQ(12, anim.text_clock.pos_y);
+    EXPECT_EQ(13, anim.text_clock.color_r);
+    EXPECT_EQ(14, anim.text_clock.color_g);
+    EXPECT_EQ(15, anim.text_clock.color_b);
+    EXPECT_EQ(16, anim.text_clock.color_a);
+    EXPECT_STREQ("test/time_font", anim.text_clock.font_file.c_str());
+
+    EXPECT_EQ(21, anim.text_percent.pos_x);
+    EXPECT_EQ(22, anim.text_percent.pos_y);
+    EXPECT_EQ(23, anim.text_percent.color_r);
+    EXPECT_EQ(24, anim.text_percent.color_g);
+    EXPECT_EQ(25, anim.text_percent.color_b);
+    EXPECT_EQ(26, anim.text_percent.color_a);
+    EXPECT_STREQ("test/percent_font", anim.text_percent.font_file.c_str());
+
+    EXPECT_EQ(2, anim.num_frames);
+
+    EXPECT_EQ(10, anim.frames[0].disp_time);
+    EXPECT_EQ(20, anim.frames[0].min_level);
+    EXPECT_EQ(30, anim.frames[0].max_level);
+
+    EXPECT_EQ(40, anim.frames[1].disp_time);
+    EXPECT_EQ(50, anim.frames[1].min_level);
+    EXPECT_EQ(60, anim.frames[1].max_level);
+}
diff --git a/include/cutils/trace.h b/include/cutils/trace.h
index dc3833f..0f00417 100644
--- a/include/cutils/trace.h
+++ b/include/cutils/trace.h
@@ -70,7 +70,8 @@
 #define ATRACE_TAG_PACKAGE_MANAGER  (1<<18)
 #define ATRACE_TAG_SYSTEM_SERVER    (1<<19)
 #define ATRACE_TAG_DATABASE         (1<<20)
-#define ATRACE_TAG_LAST             ATRACE_TAG_DATABASE
+#define ATRACE_TAG_NETWORK          (1<<21)
+#define ATRACE_TAG_LAST             ATRACE_TAG_NETWORK
 
 // Reserved for initialization.
 #define ATRACE_TAG_NOT_READY        (1ULL<<63)
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index c364317..c9e1923 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -96,6 +96,9 @@
 #define AID_DNS_TETHER    1052  /* DNS resolution daemon (tether: dnsmasq) */
 #define AID_WEBVIEW_ZYGOTE 1053 /* WebView zygote process */
 #define AID_VEHICLE_NETWORK 1054 /* Vehicle network service */
+#define AID_MEDIA_AUDIO   1055 /* GID for audio files on internal media storage */
+#define AID_MEDIA_VIDEO   1056 /* GID for video files on internal media storage */
+#define AID_MEDIA_IMAGE   1057 /* GID for image files on internal media storage */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
@@ -210,6 +213,9 @@
     { "dns_tether",    AID_DNS_TETHER, },
     { "webview_zygote", AID_WEBVIEW_ZYGOTE, },
     { "vehicle_network", AID_VEHICLE_NETWORK, },
+    { "media_audio",   AID_MEDIA_AUDIO, },
+    { "media_video",   AID_MEDIA_VIDEO, },
+    { "media_image",   AID_MEDIA_IMAGE, },
 
     { "shell",         AID_SHELL, },
     { "cache",         AID_CACHE, },
diff --git a/include/system/window.h b/include/system/window.h
index 49ab4dc..f439705 100644
--- a/include/system/window.h
+++ b/include/system/window.h
@@ -287,6 +287,16 @@
      * age will be 0.
      */
     NATIVE_WINDOW_BUFFER_AGE = 13,
+
+    /*
+     * Returns the duration of the last dequeueBuffer call in microseconds
+     */
+    NATIVE_WINDOW_LAST_DEQUEUE_DURATION = 14,
+
+    /*
+     * Returns the duration of the last queueBuffer call in microseconds
+     */
+    NATIVE_WINDOW_LAST_QUEUE_DURATION = 15,
 };
 
 /* Valid operations for the (*perform)() hook.
@@ -323,6 +333,7 @@
     NATIVE_WINDOW_SET_SURFACE_DAMAGE        = 20,   /* private */
     NATIVE_WINDOW_SET_SHARED_BUFFER_MODE    = 21,
     NATIVE_WINDOW_SET_AUTO_REFRESH          = 22,
+    NATIVE_WINDOW_GET_FRAME_TIMESTAMPS      = 23,
 };
 
 /* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
@@ -985,6 +996,18 @@
     return window->perform(window, NATIVE_WINDOW_SET_AUTO_REFRESH, autoRefresh);
 }
 
+static inline int native_window_get_frame_timestamps(
+        struct ANativeWindow* window, uint32_t framesAgo,
+        int64_t* outPostedTime, int64_t* outAcquireTime,
+        int64_t* outRefreshStartTime, int64_t* outGlCompositionDoneTime,
+        int64_t* outDisplayRetireTime, int64_t* outReleaseTime)
+{
+    return window->perform(window, NATIVE_WINDOW_GET_FRAME_TIMESTAMPS,
+            framesAgo, outPostedTime, outAcquireTime, outRefreshStartTime,
+            outGlCompositionDoneTime, outDisplayRetireTime, outReleaseTime);
+}
+
+
 __END_DECLS
 
 #endif /* SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H */
diff --git a/include/sysutils/FrameworkListener.h b/include/sysutils/FrameworkListener.h
index 18049cd..2137069 100644
--- a/include/sysutils/FrameworkListener.h
+++ b/include/sysutils/FrameworkListener.h
@@ -32,6 +32,7 @@
     int mCommandCount;
     bool mWithSeq;
     FrameworkCommandCollection *mCommands;
+    bool mSkipToNextNullByte;
 
 public:
     FrameworkListener(const char *socketName);
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
index 8c4683c..d106185 100644
--- a/include/utils/Mutex.h
+++ b/include/utils/Mutex.h
@@ -64,13 +64,18 @@
     status_t    tryLock();
 
 #if defined(__ANDROID__)
-    // lock the mutex, but don't wait longer than timeoutMilliseconds.
+    // Lock the mutex, but don't wait longer than timeoutNs (relative time).
     // Returns 0 on success, TIMED_OUT for failure due to timeout expiration.
     //
     // OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep
     // capabilities consistent across host OSes, this method is only available
     // when building Android binaries.
-    status_t    timedLock(nsecs_t timeoutMilliseconds);
+    //
+    // FIXME?: pthread_mutex_timedlock is based on CLOCK_REALTIME,
+    // which is subject to NTP adjustments, and includes time during suspend,
+    // so a timeout may occur even though no processes could run.
+    // Not holding a partial wakelock may lead to a system suspend.
+    status_t    timedLock(nsecs_t timeoutNs);
 #endif
 
     // Manages the mutex automatically. It'll be locked when Autolock is
@@ -134,6 +139,7 @@
 }
 #if defined(__ANDROID__)
 inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
+    timeoutNs += systemTime(SYSTEM_TIME_REALTIME);
     const struct timespec ts = {
         /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
         /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
diff --git a/init/action.cpp b/init/action.cpp
index 0ea7e14..65bf292 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -121,7 +121,7 @@
     Timer t;
     int result = command.InvokeFunc();
 
-    double duration_ms = t.duration() * 1000;
+    double duration_ms = t.duration_s() * 1000;
     // Any action longer than 50ms will be warned to user as slow operation
     if (duration_ms > 50.0 ||
         android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 6d58754..42dd0c6 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -146,8 +146,7 @@
         LOG(ERROR) << "failed to set bootloader message: " << err;
         return -1;
     }
-    android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-    while (1) { pause(); }  // never reached
+    reboot("recovery");
 }
 
 static void unmount_and_fsck(const struct mntent *entry) {
@@ -346,6 +345,11 @@
     return 0;
 }
 
+/* umount <path> */
+static int do_umount(const std::vector<std::string>& args) {
+  return umount(args[1].c_str());
+}
+
 static struct {
     const char *name;
     unsigned flag;
@@ -727,7 +731,7 @@
         ServiceManager::GetInstance().ForEachService(
             [] (Service* s) { s->Terminate(); });
 
-        while (t.duration() < delay) {
+        while (t.duration_s() < delay) {
             ServiceManager::GetInstance().ReapAnyOutstandingChildren();
 
             int service_count = 0;
@@ -751,11 +755,10 @@
             // Wait a bit before recounting the number or running services.
             std::this_thread::sleep_for(50ms);
         }
-        LOG(VERBOSE) << "Terminating running services took " << t.duration() << " seconds";
+        LOG(VERBOSE) << "Terminating running services took " << t;
     }
 
-    return android_reboot_with_callback(cmd, 0, reboot_target,
-                                        callback_on_ro_remount);
+    return android_reboot_with_callback(cmd, 0, reboot_target, callback_on_ro_remount);
 }
 
 static int do_trigger(const std::vector<std::string>& args) {
@@ -1047,6 +1050,7 @@
         {"mkdir",                   {1,     4,    do_mkdir}},
         {"mount_all",               {1,     kMax, do_mount_all}},
         {"mount",                   {3,     kMax, do_mount}},
+        {"umount",                  {1,     1,    do_umount}},
         {"powerctl",                {1,     1,    do_powerctl}},
         {"restart",                 {1,     1,    do_restart}},
         {"restorecon",              {1,     kMax, do_restorecon}},
diff --git a/init/devices.cpp b/init/devices.cpp
index 2db24b7..6af237c 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -868,7 +868,7 @@
     if (pid == 0) {
         Timer t;
         process_firmware_event(uevent);
-        LOG(INFO) << "loading " << uevent->path << " took " << t.duration() << "s";
+        LOG(INFO) << "loading " << uevent->path << " took " << t;
         _exit(EXIT_SUCCESS);
     } else if (pid == -1) {
         PLOG(ERROR) << "could not fork to process firmware event for " << uevent->firmware;
@@ -1043,7 +1043,7 @@
     coldboot("/sys/block");
     coldboot("/sys/devices");
     close(open(COLDBOOT_DONE, O_WRONLY|O_CREAT|O_CLOEXEC, 0000));
-    LOG(INFO) << "Coldboot took " << t.duration() << "s.";
+    LOG(INFO) << "Coldboot took " << t;
 }
 
 int get_device_fd() {
diff --git a/init/init.cpp b/init/init.cpp
index 734f129..95cb62f 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -43,7 +43,6 @@
 #include <android-base/file.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <cutils/android_reboot.h>
 #include <cutils/fs.h>
 #include <cutils/iosched_policy.h>
 #include <cutils/list.h>
@@ -163,14 +162,21 @@
     Timer t;
 
     LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
-    // Any longer than 1s is an unreasonable length of time to delay booting.
-    // If you're hitting this timeout, check that you didn't make your
-    // sepolicy regular expressions too expensive (http://b/19899875).
-    if (wait_for_file(COLDBOOT_DONE, 1s)) {
+
+    // Historically we had a 1s timeout here because we weren't otherwise
+    // tracking boot time, and many OEMs made their sepolicy regular
+    // expressions too expensive (http://b/19899875).
+
+    // Now we're tracking boot time, just log the time taken to a system
+    // property. We still panic if it takes more than a minute though,
+    // because any build that slow isn't likely to boot at all, and we'd
+    // rather any test lab devices fail back to the bootloader.
+    if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
         LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
+        panic();
     }
 
-    LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE " took " << t.duration() << "s.";
+    property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration_ns()).c_str());
     return 0;
 }
 
@@ -351,11 +357,17 @@
     if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
 }
 
+static int property_enable_triggers_action(const std::vector<std::string>& args)
+{
+    /* Enable property triggers. */
+    property_triggers_enabled = 1;
+    return 0;
+}
+
 static int queue_property_triggers_action(const std::vector<std::string>& args)
 {
+    ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
     ActionManager::GetInstance().QueueAllPropertyTriggers();
-    /* enable property triggers */
-    property_triggers_enabled = 1;
     return 0;
 }
 
@@ -403,9 +415,8 @@
 }
 
 static void security_failure() {
-    LOG(ERROR) << "Security failure; rebooting into recovery mode...";
-    android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-    while (true) { pause(); }  // never reached
+    LOG(ERROR) << "Security failure...";
+    panic();
 }
 
 static void selinux_initialize(bool in_kernel_domain) {
@@ -437,8 +448,8 @@
             security_failure();
         }
 
-        LOG(INFO) << "(Initializing SELinux " << (is_enforcing ? "enforcing" : "non-enforcing")
-                  << " took " << t.duration() << "s.)";
+        // init's first stage can't set properties, so pass the time to the second stage.
+        setenv("INIT_SELINUX_TOOK", std::to_string(t.duration_ns()).c_str(), 1);
     } else {
         selinux_init_all_handles();
     }
@@ -644,7 +655,13 @@
         export_kernel_boot_props();
 
         // Make the time that init started available for bootstat to log.
-        property_set("init.start", getenv("INIT_STARTED_AT"));
+        property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
+        property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
+
+        // Clean up our environment.
+        unsetenv("INIT_SECOND_STAGE");
+        unsetenv("INIT_STARTED_AT");
+        unsetenv("INIT_SELINUX_TOOK");
 
         // Now set up SELinux for second stage.
         selinux_initialize(false);
@@ -725,15 +742,15 @@
         // By default, sleep until something happens.
         int epoll_timeout_ms = -1;
 
-        // If there's more work to do, wake up again immediately.
-        if (am.HasMoreCommands()) epoll_timeout_ms = 0;
-
         // If there's a process that needs restarting, wake up in time for that.
         if (process_needs_restart_at != 0) {
             epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
             if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
         }
 
+        // If there's more work to do, wake up again immediately.
+        if (am.HasMoreCommands()) epoll_timeout_ms = 0;
+
         bootchart_sample(&epoll_timeout_ms);
 
         epoll_event ev;
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index d017390..406b339 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -110,7 +110,7 @@
     // Nexus 9 boot time, so it's disabled by default.
     if (false) DumpState();
 
-    LOG(VERBOSE) << "(Parsing " << path << " took " << t.duration() << "s.)";
+    LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
     return true;
 }
 
diff --git a/init/keychords.cpp b/init/keychords.cpp
index 1cfdd80..3dbb2f0 100644
--- a/init/keychords.cpp
+++ b/init/keychords.cpp
@@ -78,11 +78,13 @@
     if (adb_enabled == "running") {
         Service* svc = ServiceManager::GetInstance().FindServiceByKeychord(id);
         if (svc) {
-            LOG(INFO) << "Starting service " << svc->name() << " from keychord...";
+            LOG(INFO) << "Starting service " << svc->name() << " from keychord " << id;
             svc->Start();
         } else {
-            LOG(ERROR) << "service for keychord " << id << " not found";
+            LOG(ERROR) << "Service for keychord " << id << " not found";
         }
+    } else {
+        LOG(WARNING) << "Not starting service for keychord " << id << " because ADB is disabled";
     }
 }
 
diff --git a/init/property_service.cpp b/init/property_service.cpp
index e198297..aed8438 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -169,11 +169,18 @@
     return true;
 }
 
-static int property_set_impl(const char* name, const char* value) {
+int property_set(const char* name, const char* value) {
     size_t valuelen = strlen(value);
 
-    if (!is_legal_property_name(name)) return -1;
-    if (valuelen >= PROP_VALUE_MAX) return -1;
+    if (!is_legal_property_name(name)) {
+        LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: bad name";
+        return -1;
+    }
+    if (valuelen >= PROP_VALUE_MAX) {
+        LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                   << "value too long";
+        return -1;
+    }
 
     if (strcmp("selinux.restorecon_recursive", name) == 0 && valuelen > 0) {
         if (restorecon(value, SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
@@ -182,49 +189,42 @@
     }
 
     prop_info* pi = (prop_info*) __system_property_find(name);
-
-    if(pi != 0) {
-        /* ro.* properties may NEVER be modified once set */
-        if(!strncmp(name, "ro.", 3)) return -1;
+    if (pi != nullptr) {
+        // ro.* properties are actually "write-once".
+        if (!strncmp(name, "ro.", 3)) {
+            LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                       << "property already set";
+            return -1;
+        }
 
         __system_property_update(pi, value, valuelen);
     } else {
         int rc = __system_property_add(name, strlen(name), value, valuelen);
         if (rc < 0) {
+            LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed: "
+                       << "__system_property_add failed";
             return rc;
         }
     }
-    /* If name starts with "net." treat as a DNS property. */
+
+    // If name starts with "net." treat as a DNS property.
     if (strncmp("net.", name, strlen("net.")) == 0)  {
         if (strcmp("net.change", name) == 0) {
             return 0;
         }
-       /*
-        * The 'net.change' property is a special property used track when any
-        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
-        * contains the last updated 'net.*' property.
-        */
+        // The 'net.change' property is a special property used track when any
+        // 'net.*' property name is updated. It is _ONLY_ updated here. Its value
+        // contains the last updated 'net.*' property.
         property_set("net.change", name);
-    } else if (persistent_properties_loaded &&
-            strncmp("persist.", name, strlen("persist.")) == 0) {
-        /*
-         * Don't write properties to disk until after we have read all default properties
-         * to prevent them from being overwritten by default values.
-         */
+    } else if (persistent_properties_loaded && strncmp("persist.", name, strlen("persist.")) == 0) {
+        // Don't write properties to disk until after we have read all default properties
+        // to prevent them from being overwritten by default values.
         write_persistent_property(name, value);
     }
     property_changed(name, value);
     return 0;
 }
 
-int property_set(const char* name, const char* value) {
-    int rc = property_set_impl(name, value);
-    if (rc == -1) {
-        LOG(ERROR) << "property_set(\"" << name << "\", \"" << value << "\") failed";
-    }
-    return rc;
-}
-
 static void handle_property_set_fd()
 {
     prop_msg msg;
@@ -388,7 +388,7 @@
     }
     data.push_back('\n');
     load_properties(&data[0], filter);
-    LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t.duration() << "s.)";
+    LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
 }
 
 static void load_persistent_properties() {
diff --git a/init/readme.txt b/init/readme.txt
index 7e9d21b..f0dcd47 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -398,6 +398,9 @@
    Trigger an event.  Used to queue an action from another
    action.
 
+umount <path>
+   Unmount the filesystem mounted at that path.
+
 verity_load_state
    Internal implementation detail used to load dm-verity state.
 
@@ -440,16 +443,27 @@
 Init provides information about the services that it is responsible
 for via the below properties.
 
-init.start
-  Time after boot in ns (via the CLOCK_BOOTTIME clock) at which the first
-  stage of init started.
-
 init.svc.<name>
   State of a named service ("stopped", "stopping", "running", "restarting")
 
-init.svc.<name>.start
+
+Boot timing
+-----------
+Init records some boot timing information in system properties.
+
+ro.boottime.init
+  Time after boot in ns (via the CLOCK_BOOTTIME clock) at which the first
+  stage of init started.
+
+ro.boottime.init.selinux
+  How long it took the first stage to initialize SELinux.
+
+ro.boottime.init.cold_boot_wait
+  How long init waited for ueventd's coldboot phase to end.
+
+ro.boottime.<service-name>
   Time after boot in ns (via the CLOCK_BOOTTIME clock) that the service was
-  most recently started.
+  first started.
 
 
 Bootcharting
diff --git a/init/service.cpp b/init/service.cpp
index 1f53a1b..4b9724d 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -36,7 +36,6 @@
 #include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <cutils/android_reboot.h>
 #include <system/thread_defs.h>
 
 #include <processgroup/processgroup.h>
@@ -190,9 +189,9 @@
     property_set(prop_name.c_str(), new_state.c_str());
 
     if (new_state == "running") {
-        prop_name += ".start";
         uint64_t start_ns = time_started_.time_since_epoch().count();
-        property_set(prop_name.c_str(), StringPrintf("%" PRIu64, start_ns).c_str());
+        property_set(StringPrintf("ro.boottime.%s", name_.c_str()).c_str(),
+                     StringPrintf("%" PRIu64, start_ns).c_str());
     }
 }
 
@@ -283,10 +282,8 @@
     if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
         if (now < time_crashed_ + 4min) {
             if (++crash_count_ > 4) {
-                LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes; "
-                           << "rebooting into recovery mode";
-                android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
-                return false;
+                LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
+                panic();
             }
         } else {
             time_crashed_ = now;
diff --git a/init/signal_handler.cpp b/init/signal_handler.cpp
index 0dea3e0..1041b82 100644
--- a/init/signal_handler.cpp
+++ b/init/signal_handler.cpp
@@ -24,7 +24,6 @@
 #include <unistd.h>
 
 #include <android-base/stringprintf.h>
-#include <cutils/android_reboot.h>
 #include <cutils/list.h>
 #include <cutils/sockets.h>
 
diff --git a/init/util.cpp b/init/util.cpp
index 5205ea0..38e3b8d 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -41,6 +41,8 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
+
+#include <cutils/android_reboot.h>
 /* for ANDROID_SOCKET_* */
 #include <cutils/sockets.h>
 
@@ -472,3 +474,22 @@
 
     return true;
 }
+
+void reboot(const char* destination) {
+    android_reboot(ANDROID_RB_RESTART2, 0, destination);
+    // We're init, so android_reboot will actually have been a syscall so there's nothing
+    // to wait for. If android_reboot returns, just abort so that the kernel will reboot
+    // itself when init dies.
+    PLOG(FATAL) << "reboot failed";
+    abort();
+}
+
+void panic() {
+    LOG(ERROR) << "panic: rebooting to bootloader";
+    reboot("bootloader");
+}
+
+std::ostream& operator<<(std::ostream& os, const Timer& t) {
+    os << t.duration_s() << " seconds";
+    return os;
+}
diff --git a/init/util.h b/init/util.h
index d56da39..4b54361 100644
--- a/init/util.h
+++ b/init/util.h
@@ -21,8 +21,9 @@
 #include <sys/types.h>
 
 #include <chrono>
-#include <string>
 #include <functional>
+#include <ostream>
+#include <string>
 
 #define COLDBOOT_DONE "/dev/.coldboot_done"
 
@@ -51,15 +52,21 @@
   Timer() : start_(boot_clock::now()) {
   }
 
-  double duration() {
+  double duration_s() const {
     typedef std::chrono::duration<double> double_duration;
     return std::chrono::duration_cast<double_duration>(boot_clock::now() - start_).count();
   }
 
+  int64_t duration_ns() const {
+    return (boot_clock::now() - start_).count();
+  }
+
  private:
   boot_clock::time_point start_;
 };
 
+std::ostream& operator<<(std::ostream& os, const Timer& t);
+
 unsigned int decode_uid(const char *s);
 
 int mkdir_recursive(const char *pathname, mode_t mode);
@@ -72,4 +79,8 @@
 std::string bytes_to_hex(const uint8_t *bytes, size_t bytes_len);
 bool is_dir(const char* pathname);
 bool expand_props(const std::string& src, std::string* dst);
+
+void reboot(const char* destination) __attribute__((__noreturn__));
+void panic() __attribute__((__noreturn__));
+
 #endif
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index bb17325..0f01872 100644
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -38,40 +38,15 @@
 include $(LLVM_ROOT_PATH)/llvm.mk
 
 #-------------------------------------------------------------------------
-# The libbacktrace_offline shared library.
+# The libbacktrace_offline static library.
 #-------------------------------------------------------------------------
 libbacktrace_offline_src_files := \
 	BacktraceOffline.cpp \
 
-# Use shared llvm library on device to save space.
-libbacktrace_offline_shared_libraries_target := \
-	libbacktrace \
+# Use shared libraries so their headers get included during build.
+libbacktrace_offline_shared_libraries := \
 	libbase \
-	liblog \
 	libunwind \
-	libutils \
-	libLLVM \
-
-libbacktrace_offline_static_libraries_target := \
-	libziparchive \
-	libz \
-
-# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
-# which is not included in the prebuilt.
-libbacktrace_offline_static_libraries_host := \
-	libbacktrace \
-	libunwind \
-	libziparchive \
-	libz \
-	libbase \
-	liblog \
-	libutils \
-	libLLVMObject \
-	libLLVMBitReader \
-	libLLVMMC \
-	libLLVMMCParser \
-	libLLVMCore \
-	libLLVMSupport \
 
 module := libbacktrace_offline
 build_type := target
@@ -113,10 +88,16 @@
 backtrace_test_shared_libraries_target += \
 	libdl \
 	libutils \
-	libLLVM \
 
+# Statically link LLVMlibraries to remove dependency on llvm shared library.
 backtrace_test_static_libraries := \
 	libbacktrace_offline \
+	libLLVMObject \
+	libLLVMBitReader \
+	libLLVMMC \
+	libLLVMMCParser \
+	libLLVMCore \
+	libLLVMSupport \
 
 backtrace_test_static_libraries_target := \
 	libziparchive \
@@ -126,12 +107,6 @@
 	libziparchive \
 	libz \
 	libutils \
-	libLLVMObject \
-	libLLVMBitReader \
-	libLLVMMC \
-	libLLVMMCParser \
-	libLLVMCore \
-	libLLVMSupport \
 
 backtrace_test_ldlibs_host += \
 	-ldl \
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index af7e189..159a9d4 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -42,24 +42,6 @@
     struct mntent entry;
 } mntent_list;
 
-static bool has_mount_option(const char* opts, const char* opt_to_find)
-{
-  bool ret = false;
-  char* copy = NULL;
-  char* opt;
-  char* rem;
-
-  while ((opt = strtok_r(copy ? NULL : (copy = strdup(opts)), ",", &rem))) {
-      if (!strcmp(opt, opt_to_find)) {
-          ret = true;
-          break;
-      }
-  }
-
-  free(copy);
-  return ret;
-}
-
 static bool is_block_device(const char* fsname)
 {
     return !strncmp(fsname, "/dev/block", 10);
@@ -78,8 +60,7 @@
         return;
     }
     while ((mentry = getmntent(fp)) != NULL) {
-        if (is_block_device(mentry->mnt_fsname) &&
-            has_mount_option(mentry->mnt_opts, "rw")) {
+        if (is_block_device(mentry->mnt_fsname) && hasmntopt(mentry, "rw")) {
             mntent_list* item = (mntent_list*)calloc(1, sizeof(mntent_list));
             item->entry = *mentry;
             item->entry.mnt_fsname = strdup(mentry->mnt_fsname);
@@ -170,8 +151,7 @@
             goto out;
         }
         while ((mentry = getmntent(fp)) != NULL) {
-            if (!is_block_device(mentry->mnt_fsname) ||
-                !has_mount_option(mentry->mnt_opts, "ro")) {
+            if (!is_block_device(mentry->mnt_fsname) || !hasmntopt(mentry, "ro")) {
                 continue;
             }
             mntent_list* item = find_item(&rw_entries, mentry->mnt_fsname);
diff --git a/libcutils/fs_config.c b/libcutils/fs_config.c
index 60a389b..032e361 100644
--- a/libcutils/fs_config.c
+++ b/libcutils/fs_config.c
@@ -91,6 +91,7 @@
     { 00775, AID_MEDIA_RW, AID_MEDIA_RW, 0, "data/media/Music" },
     { 00750, AID_ROOT,   AID_SHELL,  0, "data/nativetest" },
     { 00750, AID_ROOT,   AID_SHELL,  0, "data/nativetest64" },
+    { 00775, AID_ROOT,   AID_ROOT,   0, "data/preloads" },
     { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data" },
     { 00755, AID_ROOT,   AID_SYSTEM, 0, "mnt" },
     { 00755, AID_ROOT,   AID_ROOT,   0, "root" },
@@ -149,6 +150,9 @@
     { 00700, AID_SYSTEM,    AID_SHELL,     CAP_MASK_LONG(CAP_BLOCK_SUSPEND),
                                               "system/bin/inputflinger" },
 
+    /* Support FIFO scheduling mode in SurfaceFlinger. */
+    { 00755, AID_SYSTEM,    AID_GRAPHICS,     CAP_MASK_LONG(CAP_SYS_NICE), "system/bin/surfaceflinger" },
+
     /* Support hostapd administering a network interface. */
     { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
                                            CAP_MASK_LONG(CAP_NET_RAW),
diff --git a/libcutils/sched_policy.c b/libcutils/sched_policy.c
index cab9263..5c5f3a5 100644
--- a/libcutils/sched_policy.c
+++ b/libcutils/sched_policy.c
@@ -64,9 +64,12 @@
 static int bg_cpuset_fd = -1;
 static int fg_cpuset_fd = -1;
 static int ta_cpuset_fd = -1; // special cpuset for top app
+#endif
+
+// File descriptors open to /dev/stune/../tasks, setup by initialize, or -1 on error
 static int bg_schedboost_fd = -1;
 static int fg_schedboost_fd = -1;
-#endif
+static int ta_schedboost_fd = -1;
 
 /* Add tid to the scheduling group defined by the policy */
 static int add_tid_to_cgroup(int tid, int fd)
@@ -136,9 +139,11 @@
         ta_cpuset_fd = open(filename, O_WRONLY | O_CLOEXEC);
 
 #ifdef USE_SCHEDBOOST
+        filename = "/dev/stune/top-app/tasks";
+        ta_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
         filename = "/dev/stune/foreground/tasks";
         fg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        filename = "/dev/stune/tasks";
+        filename = "/dev/stune/background/tasks";
         bg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
 #endif
     }
@@ -300,11 +305,10 @@
         break;
     case SP_TOP_APP :
         fd = ta_cpuset_fd;
-        boost_fd = fg_schedboost_fd;
+        boost_fd = ta_schedboost_fd;
         break;
     case SP_SYSTEM:
         fd = system_bg_cpuset_fd;
-        boost_fd = bg_schedboost_fd;
         break;
     default:
         boost_fd = fd = -1;
@@ -316,10 +320,12 @@
             return -errno;
     }
 
+#ifdef USE_SCHEDBOOST
     if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
         if (errno != ESRCH && errno != ENOENT)
             return -errno;
     }
+#endif
 
     return 0;
 #endif
@@ -391,19 +397,26 @@
 #endif
 
     if (__sys_supports_schedgroups) {
-        int fd;
+        int fd = -1;
+        int boost_fd = -1;
         switch (policy) {
         case SP_BACKGROUND:
             fd = bg_cgroup_fd;
+            boost_fd = bg_schedboost_fd;
             break;
         case SP_FOREGROUND:
         case SP_AUDIO_APP:
         case SP_AUDIO_SYS:
+            fd = fg_cgroup_fd;
+            boost_fd = fg_schedboost_fd;
+            break;
         case SP_TOP_APP:
             fd = fg_cgroup_fd;
+            boost_fd = ta_schedboost_fd;
             break;
         default:
             fd = -1;
+            boost_fd = -1;
             break;
         }
 
@@ -412,6 +425,13 @@
             if (errno != ESRCH && errno != ENOENT)
                 return -errno;
         }
+
+#ifdef USE_SCHEDBOOST
+        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
+            if (errno != ESRCH && errno != ENOENT)
+                return -errno;
+        }
+#endif
     } else {
         struct sched_param param;
 
diff --git a/libcutils/tests/Android.bp b/libcutils/tests/Android.bp
index 72e2eac..abe3c21 100644
--- a/libcutils/tests/Android.bp
+++ b/libcutils/tests/Android.bp
@@ -24,14 +24,15 @@
                 "PropertiesTest.cpp",
                 "sched_policy_test.cpp",
                 "trace-dev_test.cpp",
+                "test_str_parms.cpp",
+                "android_get_control_socket_test.cpp",
+                "android_get_control_file_test.cpp"
             ],
         },
 
         not_windows: {
             srcs: [
                 "test_str_parms.cpp",
-                "android_get_control_socket_test.cpp",
-                "android_get_control_file_test.cpp"
             ],
         },
     },
diff --git a/libion/ion.c b/libion/ion.c
index 2db8845..a7b22b8 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -34,7 +34,7 @@
 
 int ion_open()
 {
-    int fd = open("/dev/ion", O_RDONLY);
+    int fd = open("/dev/ion", O_RDONLY | O_CLOEXEC);
     if (fd < 0)
         ALOGE("open /dev/ion failed!\n");
     return fd;
diff --git a/liblog/Android.bp b/liblog/Android.bp
index 16aa4fa..e59a460 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -27,7 +27,7 @@
     "fake_writer.c",
 ]
 liblog_target_sources = [
-    "event_tag_map.c",
+    "event_tag_map.cpp",
     "config_read.c",
     "log_time.cpp",
     "log_is_loggable.c",
@@ -68,11 +68,14 @@
             enabled: true,
         },
         not_windows: {
-            srcs: ["event_tag_map.c"],
+            srcs: ["event_tag_map.cpp"],
         },
         linux: {
             host_ldlibs: ["-lrt"],
         },
+        linux_bionic: {
+            enabled: true,
+        },
     },
 
     cflags: [
diff --git a/liblog/event_tag_map.c b/liblog/event_tag_map.cpp
similarity index 100%
rename from liblog/event_tag_map.c
rename to liblog/event_tag_map.cpp
diff --git a/liblog/logger_write.c b/liblog/logger_write.c
index 170c8d1..f19c3ab 100644
--- a/liblog/logger_write.c
+++ b/liblog/logger_write.c
@@ -48,7 +48,7 @@
 
 static int check_log_uid_permissions()
 {
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
     uid_t uid = __android_log_uid();
 
     /* Matches clientHasLogCredentials() in logd */
@@ -130,7 +130,7 @@
     return kLogNotAvailable;
 }
 
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
 static atomic_uintptr_t tagMap;
 #endif
 
@@ -140,7 +140,7 @@
 LIBLOG_ABI_PUBLIC void __android_log_close()
 {
     struct android_log_transport_write *transport;
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
     EventTagMap *m;
 #endif
 
@@ -170,7 +170,7 @@
         }
     }
 
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
     /*
      * Additional risk here somewhat mitigated by immediately unlock flushing
      * the processor cache. The multi-threaded race that we choose to accept,
@@ -188,7 +188,7 @@
 
     __android_log_unlock();
 
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
     if (m != (EventTagMap *)(uintptr_t)-1LL) android_closeEventTagMap(m);
 #endif
 
@@ -261,7 +261,7 @@
         return -EINVAL;
     }
 
-#if defined(__BIONIC__)
+#if defined(__ANDROID__)
     if (log_id == LOG_ID_SECURITY) {
         if (vec[0].iov_len < 4) {
             return -EINVAL;
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index 158987a..ec5a99b 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -74,3 +74,38 @@
 LOCAL_SHARED_LIBRARIES := liblog libcutils libbase
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
+
+cts_executable := CtsLiblogTestCases
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(cts_executable)
+LOCAL_MODULE_TAGS := tests
+LOCAL_CFLAGS += $(test_c_flags)
+LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_SHARED_LIBRARIES := liblog libcutils libbase
+LOCAL_STATIC_LIBRARIES := libgtest libgtest_main
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.core.liblog
+include $(BUILD_CTS_EXECUTABLE)
+
+ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(cts_executable)_list
+LOCAL_MODULE_TAGS := optional
+LOCAL_CFLAGS := $(test_c_flags) -DHOST
+LOCAL_C_INCLUDES := external/gtest/include
+LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_CXX_STL := libc++
+LOCAL_SHARED_LIBRARIES := liblog libcutils libbase
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+include $(BUILD_HOST_NATIVE_TEST)
+
+endif  # ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
diff --git a/liblog/tests/AndroidTest.xml b/liblog/tests/AndroidTest.xml
new file mode 100644
index 0000000..b8d87e6
--- /dev/null
+++ b/liblog/tests/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for CTS Logging Library test cases">
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsLiblogTestCases->/data/local/tmp/CtsLiblogTestCases" />
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="CtsLiblogTestCases" />
+        <option name="runtime-hint" value="65s" />
+    </test>
+</configuration>
diff --git a/liblog/tests/libc_test.cpp b/liblog/tests/libc_test.cpp
index f05a955..8cea7dc 100644
--- a/liblog/tests/libc_test.cpp
+++ b/liblog/tests/libc_test.cpp
@@ -20,6 +20,7 @@
 #include <stdio.h>
 
 TEST(libc, __pstore_append) {
+#ifdef __ANDROID__
     FILE *fp;
     ASSERT_TRUE(NULL != (fp = fopen("/dev/pmsg0", "a")));
     static const char message[] = "libc.__pstore_append\n";
@@ -42,4 +43,7 @@
                 "Reboot, ensure string libc.__pstore_append is in /sys/fs/pstore/pmsg-ramoops-0\n"
                );
     }
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 44045c3..5420f68 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -20,7 +20,10 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <unordered_set>
+
 #include <cutils/sockets.h>
+#include <log/event_tag_map.h>
 #include <private/android_logger.h>
 
 #include "benchmark.h"
@@ -689,3 +692,96 @@
     StopBenchmarkTiming();
 }
 BENCHMARK(BM_security);
+
+// Keep maps around for multiple iterations
+static std::unordered_set<uint32_t> set;
+static const EventTagMap* map;
+
+static bool prechargeEventMap() {
+    if (map) return true;
+
+    fprintf(stderr, "Precharge: start\n");
+
+    map = android_openEventTagMap(NULL);
+    for (uint32_t tag = 1; tag < USHRT_MAX; ++tag) {
+        size_t len;
+        if (android_lookupEventTag_len(map, &len, tag) == NULL) continue;
+        set.insert(tag);
+    }
+
+    fprintf(stderr, "Precharge: stop %zu\n", set.size());
+
+    return true;
+}
+
+/*
+ *	Measure the time it takes for android_lookupEventTag_len
+ */
+static void BM_lookupEventTag(int iters) {
+
+    prechargeEventMap();
+
+    std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+    StartBenchmarkTiming();
+
+    for (int i = 0; i < iters; ++i) {
+        size_t len;
+        android_lookupEventTag_len(map, &len, (*it));
+        ++it;
+        if (it == set.end()) it = set.begin();
+    }
+
+    StopBenchmarkTiming();
+}
+BENCHMARK(BM_lookupEventTag);
+
+/*
+ *	Measure the time it takes for android_lookupEventTag_len
+ */
+static uint32_t notTag = 1;
+
+static void BM_lookupEventTag_NOT(int iters) {
+
+    prechargeEventMap();
+
+    while (set.find(notTag) != set.end()) {
+        ++notTag;
+        if (notTag >= USHRT_MAX) notTag = 1;
+    }
+
+    StartBenchmarkTiming();
+
+    for (int i = 0; i < iters; ++i) {
+        size_t len;
+        android_lookupEventTag_len(map, &len, notTag);
+    }
+
+    StopBenchmarkTiming();
+
+    ++notTag;
+    if (notTag >= USHRT_MAX) notTag = 1;
+}
+BENCHMARK(BM_lookupEventTag_NOT);
+
+/*
+ *	Measure the time it takes for android_lookupEventFormat_len
+ */
+static void BM_lookupEventFormat(int iters) {
+
+    prechargeEventMap();
+
+    std::unordered_set<uint32_t>::const_iterator it = set.begin();
+
+    StartBenchmarkTiming();
+
+    for (int i = 0; i < iters; ++i) {
+        size_t len;
+        android_lookupEventFormat_len(map, &len, (*it));
+        ++it;
+        if (it == set.end()) it = set.begin();
+    }
+
+    StopBenchmarkTiming();
+}
+BENCHMARK(BM_lookupEventFormat);
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index 02a572d..d80f8b2 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -30,7 +30,9 @@
 
 #include <android-base/file.h>
 #include <android-base/stringprintf.h>
+#ifdef __ANDROID__ // includes sys/properties.h which does not exist outside
 #include <cutils/properties.h>
+#endif
 #include <gtest/gtest.h>
 #include <log/logprint.h>
 #include <log/log_event_list.h>
@@ -53,6 +55,7 @@
     _rc; })
 
 TEST(liblog, __android_log_buf_print) {
+#ifdef __ANDROID__
     EXPECT_LT(0, __android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO,
                                          "TEST__android_log_buf_print",
                                          "radio"));
@@ -65,9 +68,13 @@
                                          "TEST__android_log_buf_print",
                                          "main"));
     usleep(1000);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_buf_write) {
+#ifdef __ANDROID__
     EXPECT_LT(0, __android_log_buf_write(LOG_ID_RADIO, ANDROID_LOG_INFO,
                                          "TEST__android_log_buf_write",
                                          "radio"));
@@ -80,9 +87,13 @@
                                          "TEST__android_log_buf_write",
                                          "main"));
     usleep(1000);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_btwrite) {
+#ifdef __ANDROID__
     int intBuf = 0xDEADBEEF;
     EXPECT_LT(0, __android_log_btwrite(0,
                                       EVENT_TYPE_INT,
@@ -97,20 +108,26 @@
                                       EVENT_TYPE_STRING,
                                       Buf, sizeof(Buf) - 1));
     usleep(1000);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static void* ConcurrentPrintFn(void *arg) {
     int ret = __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
                                   "TEST__android_log_print", "Concurrent %" PRIuPTR,
                                   reinterpret_cast<uintptr_t>(arg));
     return reinterpret_cast<void*>(ret);
 }
+#endif
 
 #define NUM_CONCURRENT 64
 #define _concurrent_name(a,n) a##__concurrent##n
 #define concurrent_name(a,n) _concurrent_name(a,n)
 
 TEST(liblog, concurrent_name(__android_log_buf_print, NUM_CONCURRENT)) {
+#ifdef __ANDROID__
     pthread_t t[NUM_CONCURRENT];
     int i;
     for (i=0; i < NUM_CONCURRENT; i++) {
@@ -128,8 +145,12 @@
         }
     }
     ASSERT_LT(0, ret);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 std::string popenToString(std::string command) {
     std::string ret;
 
@@ -193,8 +214,10 @@
     }
     return false;
 }
+#endif
 
 TEST(liblog, __android_log_btwrite__android_logger_list_read) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -257,14 +280,20 @@
     EXPECT_EQ(1, second_count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static inline int32_t get4LE(const char* src)
 {
     return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
+#endif
 
 static void bswrite_test(const char *message) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -347,6 +376,10 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    message = NULL;
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_bswrite_and_print) {
@@ -370,6 +403,7 @@
 }
 
 static void buf_write_test(const char *message) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -436,6 +470,10 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    message = NULL;
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_buf_write_and_print__empty) {
@@ -451,6 +489,7 @@
 }
 
 TEST(liblog, __security) {
+#ifdef __ANDROID__
     static const char persist_key[] = "persist.logd.security";
     static const char readonly_key[] = "ro.device_owner";
     static const char nothing_val[] = "_NOTHING_TO_SEE_HERE_";
@@ -485,9 +524,13 @@
     property_set(persist_key, "");
     EXPECT_FALSE(__android_log_security());
     property_set(persist_key, persist);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __security_buffer) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
     android_event_long_t buffer;
 
@@ -621,9 +664,12 @@
                 "not system, content submitted but can not check end-to-end\n");
     }
     EXPECT_EQ(clientHasSecurityCredentials ? 1 : 0, count);
-
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static unsigned signaled;
 static log_time signal_time;
 
@@ -682,8 +728,10 @@
         *uticks = *sticks = 0;
     }
 }
+#endif
 
 TEST(liblog, android_logger_list_read__cpu_signal) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
@@ -768,8 +816,12 @@
     EXPECT_GT(one_percent_ticks, user_ticks);
     EXPECT_GT(one_percent_ticks, system_ticks);
     EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 /*
  *  Strictly, we are not allowed to log messages in a signal context, the
  * correct way to handle this is to ensure the messages are constructed in
@@ -832,8 +884,10 @@
     pthread_attr_destroy(&attr);
     return 0;
 }
+#endif
 
 TEST(liblog, android_logger_list_read__cpu_thread) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
     unsigned long long v = 0xDEADBEAFA55A0000ULL;
 
@@ -919,11 +973,16 @@
     EXPECT_GT(one_percent_ticks, user_ticks);
     EXPECT_GT(one_percent_ticks, system_ticks);
     EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static const char max_payload_tag[] = "TEST_max_payload_and_longish_tag_XXXX";
 #define SIZEOF_MAX_PAYLOAD_BUF (LOGGER_ENTRY_MAX_PAYLOAD - \
                                 sizeof(max_payload_tag) - 1)
+#endif
 static const char max_payload_buf[] = "LEONATO\n\
 I learn in this letter that Don Peter of Arragon\n\
 comes this night to Messina\n\
@@ -1056,6 +1115,7 @@
 takes his leave.";
 
 TEST(liblog, max_payload) {
+#ifdef __ANDROID__
     pid_t pid = getpid();
     char tag[sizeof(max_payload_tag)];
     memcpy(tag, max_payload_tag, sizeof(tag));
@@ -1113,9 +1173,13 @@
     EXPECT_EQ(true, matches);
 
     EXPECT_LE(SIZEOF_MAX_PAYLOAD_BUF, static_cast<size_t>(max_len));
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_buf_print__maxtag) {
+#ifdef __ANDROID__
     struct logger_list *logger_list;
 
     pid_t pid = getpid();
@@ -1169,9 +1233,13 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, too_big_payload) {
+#ifdef __ANDROID__
     pid_t pid = getpid();
     static const char big_payload_tag[] = "TEST_big_payload_XXXX";
     char tag[sizeof(big_payload_tag)];
@@ -1226,9 +1294,13 @@
               static_cast<size_t>(max_len));
 
     EXPECT_EQ(ret, max_len + static_cast<ssize_t>(sizeof(big_payload_tag)));
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, dual_reader) {
+#ifdef __ANDROID__
     struct logger_list *logger_list1;
 
     // >25 messages due to liblog.__android_log_buf_print__concurrentXX above.
@@ -1273,9 +1345,13 @@
 
     EXPECT_EQ(25, count1);
     EXPECT_EQ(15, count2);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_logger_get_) {
+#ifdef __ANDROID__
     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) {
@@ -1307,14 +1383,20 @@
     }
 
     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)
         && !android_log_shouldPrintLine(p_format, tag, (android_LogPriority)(pri - 1));
 }
+#endif
 
 TEST(liblog, filterRule) {
+#ifdef __ANDROID__
     static const char tag[] = "random";
 
     AndroidLogFormat *p_format = android_log_format_new();
@@ -1376,9 +1458,13 @@
 #endif
 
     android_log_format_free(p_format);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, is_loggable) {
+#ifdef __ANDROID__
     static const char tag[] = "is_loggable";
     static const char log_namespace[] = "persist.log.tag.";
     static const size_t base_offset = 8; /* skip "persist." */
@@ -1671,9 +1757,13 @@
     key[sizeof(log_namespace) - 2] = '\0';
     property_set(key, hold[2]);
     property_set(key + base_offset, hold[3]);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
+#ifdef __ANDROID__
     const int TAG = 123456781;
     const char SUBTAG[] = "test-subtag";
     const int UID = -1;
@@ -1755,9 +1845,13 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
+#ifdef __ANDROID__
     const int TAG = 123456782;
     const char SUBTAG[] = "test-subtag";
     const int UID = -1;
@@ -1846,9 +1940,13 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
+#ifdef __ANDROID__
     const int TAG = 123456783;
     const char SUBTAG[] = "test-subtag";
     const int UID = -1;
@@ -1892,9 +1990,13 @@
     EXPECT_EQ(0, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
+#ifdef __ANDROID__
     const int TAG = 123456784;
     const char SUBTAG[] = "abcdefghijklmnopqrstuvwxyz now i know my abc";
     const int UID = -1;
@@ -1977,6 +2079,9 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, __android_log_bswrite_and_print___max) {
@@ -1988,6 +2093,7 @@
 }
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
+#ifdef __ANDROID__
     const int TAG = 123456785;
     const char SUBTAG[] = "test-subtag";
     struct logger_list *logger_list;
@@ -2046,9 +2152,13 @@
     EXPECT_EQ(1, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
+#ifdef __ANDROID__
     const int TAG = 123456786;
     struct logger_list *logger_list;
 
@@ -2088,8 +2198,12 @@
     EXPECT_EQ(0, count);
 
     android_logger_list_close(logger_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static int is_real_element(int type) {
     return ((type == EVENT_TYPE_INT) ||
             (type == EVENT_TYPE_LONG) ||
@@ -2583,48 +2697,90 @@
 
     android_logger_list_close(logger_list);
 }
+#endif
 
 TEST(liblog, create_android_logger_int32) {
+#ifdef __ANDROID__
     create_android_logger(event_test_int32);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_int64) {
+#ifdef __ANDROID__
     create_android_logger(event_test_int64);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_list_int64) {
+#ifdef __ANDROID__
     create_android_logger(event_test_list_int64);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_simple_automagic_list) {
+#ifdef __ANDROID__
     create_android_logger(event_test_simple_automagic_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_list_empty) {
+#ifdef __ANDROID__
     create_android_logger(event_test_list_empty);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_complex_nested_list) {
+#ifdef __ANDROID__
     create_android_logger(event_test_complex_nested_list);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_7_level_prefix) {
+#ifdef __ANDROID__
     create_android_logger(event_test_7_level_prefix);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_7_level_suffix) {
+#ifdef __ANDROID__
     create_android_logger(event_test_7_level_suffix);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_android_log_error_write) {
+#ifdef __ANDROID__
     create_android_logger(event_test_android_log_error_write);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_android_log_error_write_null) {
+#ifdef __ANDROID__
     create_android_logger(event_test_android_log_error_write_null);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, create_android_logger_overflow) {
+#ifdef __ANDROID__
     android_log_context ctx;
 
     EXPECT_TRUE(NULL != (ctx = create_android_logger(1005)));
@@ -2649,9 +2805,13 @@
     EXPECT_GT(0, android_log_write_list_begin(ctx));
     EXPECT_LE(0, android_log_destroy(&ctx));
     ASSERT_TRUE(NULL == ctx);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(liblog, android_log_write_list_buffer) {
+#ifdef __ANDROID__
     __android_log_event_list ctx(1005);
     ctx << 1005 << "tag_def" << "(tag|1),(name|3),(format|3)";
     std::string buffer(ctx);
@@ -2662,12 +2822,18 @@
     EXPECT_EQ(android_log_buffer_to_string(buffer.data(), buffer.length(),
                                            msgBuf, sizeof(msgBuf)), 0);
     EXPECT_STREQ(msgBuf, "[1005,tag_def,(tag|1),(name|3),(format|3)]");
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static const char __pmsg_file[] =
         "/data/william-shakespeare/MuchAdoAboutNothing.txt";
+#endif
 
 TEST(liblog, __android_log_pmsg_file_write) {
+#ifdef __ANDROID__
     __android_log_close();
     bool pmsgActiveAfter__android_log_close = isPmsgActive();
     bool logdwActiveAfter__android_log_close = isLogdwActive();
@@ -2704,8 +2870,12 @@
     logdwActiveAfter__android_pmsg_file_write = isLogdwActive();
     EXPECT_TRUE(pmsgActiveAfter__android_pmsg_file_write);
     EXPECT_TRUE(logdwActiveAfter__android_pmsg_file_write);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 ssize_t __pmsg_fn(log_id_t logId, char prio, const char *filename,
                   const char *buf, size_t len, void *arg) {
     EXPECT_TRUE(NULL == arg);
@@ -2727,8 +2897,10 @@
            (len != sizeof(max_payload_buf)) ||
            !!strcmp(max_payload_buf, buf) ? -ENOEXEC : 1;
 }
+#endif
 
 TEST(liblog, __android_log_pmsg_file_read) {
+#ifdef __ANDROID__
     signaled = 0;
 
     __android_log_close();
@@ -2756,8 +2928,12 @@
 
     EXPECT_LT(0, ret);
     EXPECT_EQ(1U, signaled);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 // meant to be handed to ASSERT_TRUE / EXPECT_TRUE only to expand the message
 static testing::AssertionResult IsOk(bool ok, std::string &message) {
     return ok ?
@@ -2765,6 +2941,26 @@
         (testing::AssertionFailure() << message);
 }
 
+// must be: '<needle:> 0 kB'
+static bool isZero(const std::string &content, std::string::size_type pos,
+                   const char* needle) {
+    std::string::size_type offset = content.find(needle, pos);
+    return (offset != std::string::npos) &&
+           ((offset = content.find_first_not_of(" \t", offset +
+                      strlen(needle))) != std::string::npos) &&
+           (content.find_first_not_of("0", offset) != offset);
+}
+
+// must not be: '<needle:> 0 kB'
+static bool isNotZero(const std::string &content, std::string::size_type pos,
+                      const char* needle) {
+    std::string::size_type offset = content.find(needle, pos);
+    return (offset != std::string::npos) &&
+           ((offset = content.find_first_not_of(" \t", offset +
+                      strlen(needle))) != std::string::npos) &&
+           (content.find_first_not_of("123456789", offset) != offset);
+}
+
 static void event_log_tags_test_smap(pid_t pid) {
     std::string filename = android::base::StringPrintf("/proc/%d/smaps", pid);
 
@@ -2772,6 +2968,7 @@
     if (!android::base::ReadFileToString(filename, &content)) return;
 
     bool shared_ok = false;
+    bool private_ok = false;
     bool anonymous_ok = false;
     bool pass_ok = false;
 
@@ -2781,25 +2978,28 @@
         pos += strlen(event_log_tags);
 
         // must not be: 'Shared_Clean: 0 kB'
-        static const char shared_clean[] = "Shared_Clean:";
-        std::string::size_type clean = content.find(shared_clean, pos);
-        bool ok = (clean != std::string::npos) &&
-                  ((clean = content.find_first_not_of(" \t", clean +
-                                strlen(shared_clean))) != std::string::npos) &&
-                  (content.find_first_not_of("123456789", clean) != clean);
+        bool ok = isNotZero(content, pos, "Shared_Clean:") ||
+                  // If not /etc/event-log-tags, thus r/w, then half points
+                  // back for not 'Shared_Dirty: 0 kB'
+                  ((content.substr(pos - 5 - strlen(event_log_tags), 5) != "/etc/") &&
+                      isNotZero(content, pos, "Shared_Dirty:"));
         if (ok && !pass_ok) {
             shared_ok = true;
         } else if (!ok) {
             shared_ok = false;
         }
 
+        // must be: 'Private_Dirty: 0 kB' and 'Private_Clean: 0 kB'
+        ok = isZero(content, pos, "Private_Dirty:") ||
+             isZero(content, pos, "Private_Clean:");
+        if (ok && !pass_ok) {
+            private_ok = true;
+        } else if (!ok) {
+            private_ok = false;
+        }
+
         // must be: 'Anonymous: 0 kB'
-        static const char anonymous[] = "Anonymous:";
-        std::string::size_type anon = content.find(anonymous, pos);
-        ok = (anon != std::string::npos) &&
-             ((anon = content.find_first_not_of(" \t", anon +
-                          strlen(anonymous))) != std::string::npos) &&
-             (content.find_first_not_of("0", anon) != anon);
+        ok = isZero(content, pos, "Anonymous:");
         if (ok && !pass_ok) {
             anonymous_ok = true;
         } else if (!ok) {
@@ -2811,7 +3011,7 @@
     content = "";
 
     if (!pass_ok) return;
-    if (shared_ok && anonymous_ok) return;
+    if (shared_ok && anonymous_ok && private_ok) return;
 
     filename = android::base::StringPrintf("/proc/%d/comm", pid);
     android::base::ReadFileToString(filename, &content);
@@ -2819,10 +3019,13 @@
                   pid, content.substr(0, content.find("\n")).c_str());
 
     EXPECT_TRUE(IsOk(shared_ok, content));
+    EXPECT_TRUE(IsOk(private_ok, content));
     EXPECT_TRUE(IsOk(anonymous_ok, content));
 }
+#endif
 
 TEST(liblog, event_log_tags) {
+#ifdef __ANDROID__
     std::unique_ptr<DIR, int(*)(DIR*)> proc_dir(opendir("/proc"), closedir);
     ASSERT_FALSE(!proc_dir);
 
@@ -2836,4 +3039,7 @@
         if (id != pid) continue;
         event_log_tags_test_smap(pid);
     }
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
diff --git a/libsparse/include/sparse/sparse.h b/libsparse/include/sparse/sparse.h
index 42d4adb..356f65f 100644
--- a/libsparse/include/sparse/sparse.h
+++ b/libsparse/include/sparse/sparse.h
@@ -176,6 +176,13 @@
 int64_t sparse_file_len(struct sparse_file *s, bool sparse, bool crc);
 
 /**
+ * sparse_file_block_size
+ *
+ * @s - sparse file cookie
+ */
+unsigned int sparse_file_block_size(struct sparse_file *s);
+
+/**
  * sparse_file_callback - call a callback for blocks in sparse file
  *
  * @s - sparse file cookie
@@ -197,6 +204,24 @@
 		int (*write)(void *priv, const void *data, int len), void *priv);
 
 /**
+ * sparse_file_foreach_chunk - call a callback for data blocks in sparse file
+ *
+ * @s - sparse file cookie
+ * @sparse - write in the Android sparse file format
+ * @crc - append a crc chunk
+ * @write - function to call for each block
+ * @priv - value that will be passed as the first argument to write
+ *
+ * The function has the same behavior as 'sparse_file_callback', except it only
+ * iterates on blocks that contain data.
+ *
+ * Returns 0 on success, negative errno on error.
+ */
+int sparse_file_foreach_chunk(struct sparse_file *s, bool sparse, bool crc,
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks),
+	void *priv);
+/**
  * sparse_file_read - read a file into a sparse file cookie
  *
  * @s - sparse file cookie
diff --git a/libsparse/sparse.c b/libsparse/sparse.c
index 311678a..b175860 100644
--- a/libsparse/sparse.c
+++ b/libsparse/sparse.c
@@ -199,6 +199,57 @@
 	return ret;
 }
 
+struct chunk_data {
+	void		*priv;
+	unsigned int	block;
+	unsigned int	nr_blocks;
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks);
+};
+
+static int foreach_chunk_write(void *priv, const void *data, int len)
+{
+	struct chunk_data *chk = priv;
+
+	return chk->write(chk->priv, data, len, chk->block, chk->nr_blocks);
+}
+
+int sparse_file_foreach_chunk(struct sparse_file *s, bool sparse, bool crc,
+	int (*write)(void *priv, const void *data, int len, unsigned int block,
+		     unsigned int nr_blocks),
+	void *priv)
+{
+	int ret;
+	int chunks;
+	struct chunk_data chk;
+	struct output_file *out;
+	struct backed_block *bb;
+
+	chk.priv = priv;
+	chk.write = write;
+	chk.block = chk.nr_blocks = 0;
+	chunks = sparse_count_chunks(s);
+	out = output_file_open_callback(foreach_chunk_write, &chk,
+					s->block_size, s->len, false, sparse,
+					chunks, crc);
+
+	if (!out)
+		return -ENOMEM;
+
+	for (bb = backed_block_iter_new(s->backed_block_list); bb;
+			bb = backed_block_iter_next(bb)) {
+		chk.block = backed_block_block(bb);
+		chk.nr_blocks = (backed_block_len(bb) - 1) / s->block_size + 1;
+		ret = sparse_file_write_block(out, bb);
+		if (ret)
+			return ret;
+	}
+
+	output_file_close(out);
+
+	return ret;
+}
+
 static int out_counter_write(void *priv, const void *data __unused, int len)
 {
 	int64_t *count = priv;
@@ -230,6 +281,11 @@
 	return count;
 }
 
+unsigned int sparse_file_block_size(struct sparse_file *s)
+{
+	return s->block_size;
+}
+
 static struct backed_block *move_chunks_up_to_len(struct sparse_file *from,
 		struct sparse_file *to, unsigned int len)
 {
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.c
index d3fb45f..3457d5b 100644
--- a/libsuspend/autosuspend_wakeup_count.c
+++ b/libsuspend/autosuspend_wakeup_count.c
@@ -24,6 +24,7 @@
 #include <stddef.h>
 #include <stdbool.h>
 #include <string.h>
+#include <sys/param.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -35,12 +36,24 @@
 #define SYS_POWER_STATE "/sys/power/state"
 #define SYS_POWER_WAKEUP_COUNT "/sys/power/wakeup_count"
 
+#define BASE_SLEEP_TIME 100000
+
 static int state_fd;
 static int wakeup_count_fd;
 static pthread_t suspend_thread;
 static sem_t suspend_lockout;
 static const char *sleep_state = "mem";
 static void (*wakeup_func)(bool success) = NULL;
+static int sleep_time = BASE_SLEEP_TIME;
+
+static void update_sleep_time(bool success) {
+    if (success) {
+        sleep_time = BASE_SLEEP_TIME;
+        return;
+    }
+    // double sleep time after each failure up to one minute
+    sleep_time = MIN(sleep_time * 2, 60000000);
+}
 
 static void *suspend_thread_func(void *arg __attribute__((unused)))
 {
@@ -48,10 +61,12 @@
     char wakeup_count[20];
     int wakeup_count_len;
     int ret;
-    bool success;
+    bool success = true;
 
     while (1) {
-        usleep(100000);
+        update_sleep_time(success);
+        usleep(sleep_time);
+        success = false;
         ALOGV("%s: read wakeup_count\n", __func__);
         lseek(wakeup_count_fd, 0, SEEK_SET);
         wakeup_count_len = TEMP_FAILURE_RETRY(read(wakeup_count_fd, wakeup_count,
@@ -75,7 +90,6 @@
             continue;
         }
 
-        success = true;
         ALOGV("%s: write %*s to wakeup_count\n", __func__, wakeup_count_len, wakeup_count);
         ret = TEMP_FAILURE_RETRY(write(wakeup_count_fd, wakeup_count, wakeup_count_len));
         if (ret < 0) {
@@ -84,8 +98,8 @@
         } else {
             ALOGV("%s: write %s to %s\n", __func__, sleep_state, SYS_POWER_STATE);
             ret = TEMP_FAILURE_RETRY(write(state_fd, sleep_state, strlen(sleep_state)));
-            if (ret < 0) {
-                success = false;
+            if (ret >= 0) {
+                success = true;
             }
             void (*func)(bool success) = wakeup_func;
             if (func != NULL) {
diff --git a/libsysutils/src/FrameworkListener.cpp b/libsysutils/src/FrameworkListener.cpp
index 52f28af..1b6076f 100644
--- a/libsysutils/src/FrameworkListener.cpp
+++ b/libsysutils/src/FrameworkListener.cpp
@@ -50,6 +50,7 @@
     errorRate = 0;
     mCommandCount = 0;
     mWithSeq = withSeq;
+    mSkipToNextNullByte = false;
 }
 
 bool FrameworkListener::onDataAvailable(SocketClient *c) {
@@ -60,10 +61,15 @@
     if (len < 0) {
         SLOGE("read() failed (%s)", strerror(errno));
         return false;
-    } else if (!len)
+    } else if (!len) {
         return false;
-   if(buffer[len-1] != '\0')
+    } else if (buffer[len-1] != '\0') {
         SLOGW("String is not zero-terminated");
+        android_errorWriteLog(0x534e4554, "29831647");
+        c->sendMsg(500, "Command too large for buffer", false);
+        mSkipToNextNullByte = true;
+        return false;
+    }
 
     int offset = 0;
     int i;
@@ -71,11 +77,16 @@
     for (i = 0; i < len; i++) {
         if (buffer[i] == '\0') {
             /* IMPORTANT: dispatchCommand() expects a zero-terminated string */
-            dispatchCommand(c, buffer + offset);
+            if (mSkipToNextNullByte) {
+                mSkipToNextNullByte = false;
+            } else {
+                dispatchCommand(c, buffer + offset);
+            }
             offset = i + 1;
         }
     }
 
+    mSkipToNextNullByte = false;
     return true;
 }
 
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 25c779e..217b8c3 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -86,6 +86,13 @@
                 "ProcessCallStack.cpp",
             ],
         },
+        linux_bionic: {
+            enabled: true,
+            srcs: [
+                "Looper.cpp",
+                "ProcessCallStack.cpp",
+            ],
+        },
 
         darwin: {
             cflags: ["-Wno-unused-parameter"],
diff --git a/libziparchive/Android.bp b/libziparchive/Android.bp
index 5ed0fe8..fce1378 100644
--- a/libziparchive/Android.bp
+++ b/libziparchive/Android.bp
@@ -62,7 +62,17 @@
         android: {
             static_libs: ["libz"],
         },
-        host: {
+        linux_bionic: {
+            static_libs: ["libz"],
+            enabled: true,
+        },
+        linux: {
+            shared_libs: ["libz-host"],
+        },
+        darwin: {
+            shared_libs: ["libz-host"],
+        },
+        windows: {
             shared_libs: ["libz-host"],
         },
     },
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index e6e0276..0ac6f2c 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -267,9 +267,14 @@
    * Grab the CD offset and size, and the number of entries in the
    * archive and verify that they look reasonable.
    */
-  if (eocd->cd_start_offset + eocd->cd_size > eocd_offset) {
+  if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
     ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
         eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
+#if defined(__ANDROID__)
+    if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
+      android_errorWriteLog(0x534e4554, "31251826");
+    }
+#endif
     return kInvalidOffset;
   }
   if (eocd->num_records == 0) {
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 94b8691..c204a16 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -321,7 +321,7 @@
                     "  -g, --buffer-size                      Get the size of the ring buffer.\n"
                     "  -G <size>, --buffer-size=<size>\n"
                     "                  Set size of log ring buffer, may suffix with K or M.\n"
-                    "  -L, -last       Dump logs from prior to last reboot\n"
+                    "  -L, --last      Dump logs from prior to last reboot\n"
                     // Leave security (Device Owner only installations) and
                     // kernel (userdebug and eng) buffers undocumented.
                     "  -b <buffer>, --buffer=<buffer>         Request alternate ring buffer, 'main',\n"
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index 1da1942..b082a64 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -35,7 +35,8 @@
     # all exec/services are called with umask(077), so no gain beyond 0700
     mkdir /data/misc/logd 0700 logd log
     # logd for write to /data/misc/logd, log group for read from pstore (-L)
-    exec - logd log -- /system/bin/logcat -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
+    # b/28788401 b/30041146 b/30612424
+    # exec - logd log -- /system/bin/logcat -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
     start logcatd
 
 # stop logcatd service and clear data
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index fe08846..7073535 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -402,7 +402,32 @@
     }
 }
 
-pid_t LogKlog::sniffPid(const char *cp, size_t len) {
+pid_t LogKlog::sniffPid(const char **buf, size_t len) {
+    const char *cp = *buf;
+    // HTC kernels with modified printk "c0   1648 "
+    if ((len > 9) &&
+            (cp[0] == 'c') &&
+            isdigit(cp[1]) &&
+            (isdigit(cp[2]) || (cp[2] == ' ')) &&
+            (cp[3] == ' ')) {
+        bool gotDigit = false;
+        int i;
+        for (i = 4; i < 9; ++i) {
+            if (isdigit(cp[i])) {
+                gotDigit = true;
+            } else if (gotDigit || (cp[i] != ' ')) {
+                break;
+            }
+        }
+        if ((i == 9) && (cp[i] == ' ')) {
+            int pid = 0;
+            char dummy;
+            if (sscanf(cp + 4, "%d%c", &pid, &dummy) == 2) {
+                *buf = cp + 10; // skip-it-all
+                return pid;
+            }
+        }
+    }
     while (len) {
         // Mediatek kernels with modified printk
         if (*cp == '[') {
@@ -588,7 +613,7 @@
     }
 
     // Parse pid, tid and uid
-    const pid_t pid = sniffPid(p, len - (p - buf));
+    const pid_t pid = sniffPid(&p, len - (p - buf));
     const pid_t tid = pid;
     uid_t uid = AID_ROOT;
     if (pid) {
diff --git a/logd/LogKlog.h b/logd/LogKlog.h
index d812436..11d88af 100644
--- a/logd/LogKlog.h
+++ b/logd/LogKlog.h
@@ -51,7 +51,7 @@
 
 protected:
     void sniffTime(log_time &now, const char **buf, size_t len, bool reverse);
-    pid_t sniffPid(const char *buf, size_t len);
+    pid_t sniffPid(const char **buf, size_t len);
     void calculateCorrection(const log_time &monotonic,
                              const char *real_string, size_t len);
     virtual bool onDataAvailable(SocketClient *cli);
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 0fc701a..7d0c87d 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -26,6 +26,7 @@
 #######################################
 # asan.options
 ifneq ($(filter address,$(SANITIZE_TARGET)),)
+
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := asan.options
@@ -34,6 +35,72 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT)
 
 include $(BUILD_PREBUILT)
+
+# Modules for asan.options.X files.
+
+ASAN_OPTIONS_FILES :=
+
+define create-asan-options-module
+include $$(CLEAR_VARS)
+LOCAL_MODULE := asan.options.$(1)
+ASAN_OPTIONS_FILES += asan.options.$(1)
+LOCAL_MODULE_CLASS := ETC
+# The asan.options.off.template tries to turn off as much of ASAN as is possible.
+LOCAL_SRC_FILES := asan.options.off.template
+LOCAL_MODULE_PATH := $(TARGET_OUT)
+include $$(BUILD_PREBUILT)
+endef
+
+# Pretty comprehensive set of native services. This list is helpful if all that's to be checked is an
+# app.
+ifeq ($(SANITIZE_LITE),true)
+SANITIZE_ASAN_OPTIONS_FOR := \
+  adbd \
+  ATFWD-daemon \
+  audioserver \
+  bridgemgrd \
+  cameraserver \
+  cnd \
+  debuggerd \
+  debuggerd64 \
+  dex2oat \
+  drmserver \
+  fingerprintd \
+  gatekeeperd \
+  installd \
+  keystore \
+  lmkd \
+  logcat \
+  logd \
+  lowi-server \
+  media.codec \
+  mediadrmserver \
+  media.extractor \
+  mediaserver \
+  mm-qcamera-daemon \
+  mpdecision \
+  netmgrd \
+  perfd \
+  perfprofd \
+  qmuxd \
+  qseecomd \
+  rild \
+  sdcard \
+  servicemanager \
+  slim_daemon \
+  surfaceflinger \
+  thermal-engine \
+  time_daemon \
+  update_engine \
+  vold \
+  wpa_supplicant \
+  zip
+endif
+
+ifneq ($(SANITIZE_ASAN_OPTIONS_FOR),)
+  $(foreach binary, $(SANITIZE_ASAN_OPTIONS_FOR), $(eval $(call create-asan-options-module,$(binary))))
+endif
+
 endif
 
 #######################################
@@ -47,14 +114,14 @@
 EXPORT_GLOBAL_ASAN_OPTIONS :=
 ifneq ($(filter address,$(SANITIZE_TARGET)),)
   EXPORT_GLOBAL_ASAN_OPTIONS := export ASAN_OPTIONS include=/system/asan.options
-  LOCAL_REQUIRED_MODULES := asan.options
+  LOCAL_REQUIRED_MODULES := asan.options $(ASAN_OPTIONS_FILES)
 endif
 # Put it here instead of in init.rc module definition,
 # because init.rc is conditionally included.
 #
 # create some directories (some are mount points) and symlinks
 LOCAL_POST_INSTALL_CMD := mkdir -p $(addprefix $(TARGET_ROOT_OUT)/, \
-    sbin dev proc sys system data oem acct cache config storage mnt root $(BOARD_ROOT_EXTRA_FOLDERS)); \
+    sbin dev proc sys system data oem acct config storage mnt root $(BOARD_ROOT_EXTRA_FOLDERS)); \
     ln -sf /system/etc $(TARGET_ROOT_OUT)/etc; \
     ln -sf /data/user_de/0/com.android.shell/files/bugreports $(TARGET_ROOT_OUT)/bugreports; \
     ln -sf /sys/kernel/debug $(TARGET_ROOT_OUT)/d; \
@@ -64,6 +131,11 @@
 else
   LOCAL_POST_INSTALL_CMD += ; ln -sf /system/vendor $(TARGET_ROOT_OUT)/vendor
 endif
+ifdef BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE
+  LOCAL_POST_INSTALL_CMD += ; mkdir -p $(TARGET_ROOT_OUT)/cache
+else
+  LOCAL_POST_INSTALL_CMD += ; ln -sf /data/cache $(TARGET_ROOT_OUT)/cache
+endif
 ifdef BOARD_ROOT_EXTRA_SYMLINKS
 # BOARD_ROOT_EXTRA_SYMLINKS is a list of <target>:<link_name>.
   LOCAL_POST_INSTALL_CMD += $(foreach s, $(BOARD_ROOT_EXTRA_SYMLINKS),\
diff --git a/rootdir/asan.options b/rootdir/asan.options
index 43896a1..d728f12 100644
--- a/rootdir/asan.options
+++ b/rootdir/asan.options
@@ -3,3 +3,5 @@
 alloc_dealloc_mismatch=0
 allocator_may_return_null=1
 detect_container_overflow=0
+abort_on_error=1
+include_if_exists=/system/asan.options.%b
diff --git a/rootdir/asan.options.off.template b/rootdir/asan.options.off.template
new file mode 100644
index 0000000..59a1249
--- /dev/null
+++ b/rootdir/asan.options.off.template
@@ -0,0 +1,7 @@
+quarantine_size_mb=0
+max_redzone=16
+poison_heap=false
+poison_partial=false
+poison_array_cookie=false
+alloc_dealloc_mismatch=false
+new_delete_type_mismatch=false
diff --git a/rootdir/init.rc b/rootdir/init.rc
index ecc3ccd..8903255 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -50,12 +50,20 @@
     mkdir /dev/stune
     mount cgroup none /dev/stune schedtune
     mkdir /dev/stune/foreground
+    mkdir /dev/stune/background
+    mkdir /dev/stune/top-app
     chown system system /dev/stune
     chown system system /dev/stune/foreground
+    chown system system /dev/stune/background
+    chown system system /dev/stune/top-app
     chown system system /dev/stune/tasks
     chown system system /dev/stune/foreground/tasks
+    chown system system /dev/stune/background/tasks
+    chown system system /dev/stune/top-app/tasks
     chmod 0664 /dev/stune/tasks
     chmod 0664 /dev/stune/foreground/tasks
+    chmod 0664 /dev/stune/background/tasks
+    chmod 0664 /dev/stune/top-app/tasks
 
     # Mount staging areas for devices managed by vold
     # See storage config details at http://source.android.com/tech/storage/
@@ -134,16 +142,17 @@
     chown system system /dev/cpuctl
     chown system system /dev/cpuctl/tasks
     chmod 0666 /dev/cpuctl/tasks
-    write /dev/cpuctl/cpu.rt_runtime_us 800000
     write /dev/cpuctl/cpu.rt_period_us 1000000
+    write /dev/cpuctl/cpu.rt_runtime_us 950000
 
     mkdir /dev/cpuctl/bg_non_interactive
     chown system system /dev/cpuctl/bg_non_interactive/tasks
     chmod 0666 /dev/cpuctl/bg_non_interactive/tasks
     # 5.0 %
     write /dev/cpuctl/bg_non_interactive/cpu.shares 52
-    write /dev/cpuctl/bg_non_interactive/cpu.rt_runtime_us 700000
     write /dev/cpuctl/bg_non_interactive/cpu.rt_period_us 1000000
+    # active FIFO threads will never be in BG
+    write /dev/cpuctl/bg_non_interactive/cpu.rt_runtime_us 10000
 
     # sets up initial cpusets for ActivityManager
     mkdir /dev/cpuset
@@ -225,6 +234,8 @@
     # expecting it to point to /proc/self/fd
     symlink /proc/self/fd /dev/fd
 
+    export DOWNLOAD_CACHE /data/cache
+
     # set RLIMIT_NICE to allow priorities from 19 to -20
     setrlimit 13 40 40
 
@@ -412,6 +423,10 @@
     # create the A/B OTA directory, so as to enforce our permissions
     mkdir /data/ota 0771 root root
 
+    # create the OTA package directory. It will be accessed by GmsCore (cache
+    # group), update_engine and update_verifier.
+    mkdir /data/ota_package 0770 system cache
+
     # create resource-cache and double-check the perms
     mkdir /data/resource-cache 0771 system system
     chown system system /data/resource-cache
@@ -452,6 +467,11 @@
     mkdir /data/media 0770 media_rw media_rw
     mkdir /data/media/obb 0770 media_rw media_rw
 
+    mkdir /data/cache 0770 system cache
+    mkdir /data/cache/recovery 0770 system cache
+    mkdir /data/cache/backup_stage 0700 system system
+    mkdir /data/cache/backup 0700 system system
+
     init_user0
 
     # Set SELinux security contexts on upgrade or policy update.
diff --git a/rootdir/init.usb.rc b/rootdir/init.usb.rc
index 1fd1e2a..915d159 100644
--- a/rootdir/init.usb.rc
+++ b/rootdir/init.usb.rc
@@ -103,7 +103,7 @@
 
 # Used to set USB configuration at boot and to switch the configuration
 # when changing the default configuration
-on property:persist.sys.usb.config=*
+on boot && property:persist.sys.usb.config=*
     setprop sys.usb.config ${persist.sys.usb.config}
 
 #
diff --git a/rootdir/init.zygote32.rc b/rootdir/init.zygote32.rc
index bfddcfa..eedeba8 100644
--- a/rootdir/init.zygote32.rc
+++ b/rootdir/init.zygote32.rc
@@ -10,4 +10,4 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
-    writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
+    writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote32_64.rc b/rootdir/init.zygote32_64.rc
index 1bbb007..84a907f 100644
--- a/rootdir/init.zygote32_64.rc
+++ b/rootdir/init.zygote32_64.rc
@@ -19,4 +19,4 @@
     group root readproc
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
-    writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
+    writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote64.rc b/rootdir/init.zygote64.rc
index 6742127..76e2b79 100644
--- a/rootdir/init.zygote64.rc
+++ b/rootdir/init.zygote64.rc
@@ -10,4 +10,4 @@
     onrestart restart cameraserver
     onrestart restart media
     onrestart restart netd
-    writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
+    writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index 81a7609..e918b67 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -19,4 +19,4 @@
     group root readproc
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
-    writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
+    writepid /dev/cpuset/foreground/tasks
diff --git a/sdcard/fuse.cpp b/sdcard/fuse.cpp
index 9393846..3f0f95f 100644
--- a/sdcard/fuse.cpp
+++ b/sdcard/fuse.cpp
@@ -1026,7 +1026,13 @@
     }
     out.fh = ptr_to_id(h);
     out.open_flags = 0;
+
+#ifdef FUSE_SHORTCIRCUIT
+    out.lower_fd = h->fd;
+#else
     out.padding = 0;
+#endif
+
     fuse_reply(fuse, hdr->unique, &out, sizeof(out));
     return NO_STATUS;
 }
@@ -1190,7 +1196,13 @@
     }
     out.fh = ptr_to_id(h);
     out.open_flags = 0;
+
+#ifdef FUSE_SHORTCIRCUIT
+    out.lower_fd = -1;
+#else
     out.padding = 0;
+#endif
+
     fuse_reply(fuse, hdr->unique, &out, sizeof(out));
     return NO_STATUS;
 }
@@ -1270,6 +1282,11 @@
     out.major = FUSE_KERNEL_VERSION;
     out.max_readahead = req->max_readahead;
     out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
+
+#ifdef FUSE_SHORTCIRCUIT
+    out.flags |= FUSE_SHORTCIRCUIT;
+#endif
+
     out.max_background = 32;
     out.congestion_threshold = 32;
     out.max_write = MAX_WRITE;
diff --git a/sdcard/sdcard.cpp b/sdcard/sdcard.cpp
index bc502a0..df3ce85 100644
--- a/sdcard/sdcard.cpp
+++ b/sdcard/sdcard.cpp
@@ -331,6 +331,27 @@
     return true;
 }
 
+static bool sdcardfs_setup_bind_remount(const std::string& source_path, const std::string& dest_path,
+                                        gid_t gid, mode_t mask) {
+    std::string opts = android::base::StringPrintf("mask=%d,gid=%d", mask, gid);
+
+    if (mount(source_path.c_str(), dest_path.c_str(), nullptr,
+            MS_BIND, nullptr) != 0) {
+        PLOG(ERROR) << "failed to bind mount sdcardfs filesystem";
+        return false;
+    }
+
+    if (mount(source_path.c_str(), dest_path.c_str(), "none",
+            MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) != 0) {
+        PLOG(ERROR) << "failed to mount sdcardfs filesystem";
+        if (umount2(dest_path.c_str(), MNT_DETACH))
+            PLOG(WARNING) << "Failed to unmount bind";
+        return false;
+    }
+
+    return true;
+}
+
 static void run_sdcardfs(const std::string& source_path, const std::string& label, uid_t uid,
         gid_t gid, userid_t userid, bool multi_user, bool full_write) {
     std::string dest_path_default = "/mnt/runtime/default/" + label;
@@ -343,9 +364,8 @@
         // permissions are completely masked off.
         if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
                                                       AID_SDCARD_RW, 0006)
-                || !sdcardfs_setup(source_path, dest_path_read, uid, gid, multi_user, userid,
-                                                      AID_EVERYBODY, 0027)
-                || !sdcardfs_setup(source_path, dest_path_write, uid, gid, multi_user, userid,
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read, AID_EVERYBODY, 0027)
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write,
                                                       AID_EVERYBODY, full_write ? 0007 : 0027)) {
             LOG(FATAL) << "failed to sdcardfs_setup";
         }
@@ -355,9 +375,9 @@
         // deep inside attr_from_stat().
         if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
                                                       AID_SDCARD_RW, 0006)
-                || !sdcardfs_setup(source_path, dest_path_read, uid, gid, multi_user, userid,
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read,
                                                       AID_EVERYBODY, full_write ? 0027 : 0022)
-                || !sdcardfs_setup(source_path, dest_path_write, uid, gid, multi_user, userid,
+                || !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write,
                                                       AID_EVERYBODY, full_write ? 0007 : 0022)) {
             LOG(FATAL) << "failed to sdcardfs_setup";
         }
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 5319ff4..d6ead1a 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -81,15 +81,6 @@
 $(INPUT_H_LABELS_H):
 	$(transform-generated-source)
 
-# We only want 'r' on userdebug and eng builds.
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := r.c
-LOCAL_CFLAGS += $(common_cflags)
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
-LOCAL_MODULE := r
-LOCAL_MODULE_TAGS := debug
-include $(BUILD_EXECUTABLE)
-
 
 # We build BSD grep separately, so it can provide egrep and fgrep too.
 include $(CLEAR_VARS)
diff --git a/toolbox/r.c b/toolbox/r.c
deleted file mode 100644
index b96cdb2..0000000
--- a/toolbox/r.c
+++ /dev/null
@@ -1,102 +0,0 @@
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#if __LP64__
-#define strtoptr strtoull
-#else
-#define strtoptr strtoul
-#endif
-
-static int usage()
-{
-    fprintf(stderr,"r [-b|-s] <address> [<value>]\n");
-    return -1;
-}
-
-int main(int argc, char *argv[])
-{
-    if(argc < 2) return usage();
-
-    int width = 4;
-    if(!strcmp(argv[1], "-b")) {
-        width = 1;
-        argc--;
-        argv++;
-    } else if(!strcmp(argv[1], "-s")) {
-        width = 2;
-        argc--;
-        argv++;
-    }
-
-    if(argc < 2) return usage();
-    uintptr_t addr = strtoptr(argv[1], 0, 16);
-
-    uintptr_t endaddr = 0;
-    char* end = strchr(argv[1], '-');
-    if (end)
-        endaddr = strtoptr(end + 1, 0, 16);
-
-    if (!endaddr)
-        endaddr = addr + width - 1;
-
-    if (endaddr <= addr) {
-        fprintf(stderr, "end address <= start address\n");
-        return -1;
-    }
-
-    bool set = false;
-    uint32_t value = 0;
-    if(argc > 2) {
-        set = true;
-        value = strtoul(argv[2], 0, 16);
-    }
-
-    int fd = open("/dev/mem", O_RDWR | O_SYNC);
-    if(fd < 0) {
-        fprintf(stderr,"cannot open /dev/mem\n");
-        return -1;
-    }
-
-    off64_t mmap_start = addr & ~(PAGE_SIZE - 1);
-    size_t mmap_size = endaddr - mmap_start + 1;
-    mmap_size = (mmap_size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
-
-    void* page = mmap64(0, mmap_size, PROT_READ | PROT_WRITE,
-                        MAP_SHARED, fd, mmap_start);
-
-    if(page == MAP_FAILED){
-        fprintf(stderr,"cannot mmap region\n");
-        return -1;
-    }
-
-    while (addr <= endaddr) {
-        switch(width){
-        case 4: {
-            uint32_t* x = (uint32_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %08x\n", addr, *x);
-            break;
-        }
-        case 2: {
-            uint16_t* x = (uint16_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %04x\n", addr, *x);
-            break;
-        }
-        case 1: {
-            uint8_t* x = (uint8_t*) (((uintptr_t) page) + (addr & 4095));
-            if(set) *x = value;
-            fprintf(stderr,"%08"PRIxPTR": %02x\n", addr, *x);
-            break;
-        }
-        }
-        addr += width;
-    }
-    return 0;
-}