Merge "Add odm sepolicy support to selinux.cpp"
diff --git a/adb/Android.mk b/adb/Android.mk
index d033d5a..05b0284 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -345,18 +345,16 @@
     -D_GNU_SOURCE \
     -Wno-deprecated-declarations \
 
-LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=$(if $(filter userdebug eng,$(TARGET_BUILD_VARIANT)),1,0)
 LOCAL_CFLAGS += -DALLOW_ADBD_NO_AUTH=$(if $(filter userdebug eng,$(TARGET_BUILD_VARIANT)),1,0)
 
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
 LOCAL_CFLAGS += -DALLOW_ADBD_DISABLE_VERITY=1
+LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1
 endif
 
 LOCAL_MODULE := adbd
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN)
-LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED)
 
 LOCAL_SANITIZE := $(adb_target_sanitize)
 LOCAL_STRIP_MODULE := keep_symbols
diff --git a/adb/daemon/main.cpp b/adb/daemon/main.cpp
index e0629ab..1c94298 100644
--- a/adb/daemon/main.cpp
+++ b/adb/daemon/main.cpp
@@ -49,23 +49,17 @@
 
 static const char* root_seclabel = nullptr;
 
-static inline bool is_device_unlocked() {
-    return "orange" == android::base::GetProperty("ro.boot.verifiedbootstate", "");
-}
-
 static void drop_capabilities_bounding_set_if_needed(struct minijail *j) {
-    if (ALLOW_ADBD_ROOT || is_device_unlocked()) {
-        if (__android_log_is_debuggable()) {
-            return;
-        }
+#if defined(ALLOW_ADBD_ROOT)
+    if (__android_log_is_debuggable()) {
+        return;
     }
+#endif
     minijail_capbset_drop(j, CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_SETGID));
 }
 
 static bool should_drop_privileges() {
-    // "adb root" not allowed, always drop privileges.
-    if (!ALLOW_ADBD_ROOT && !is_device_unlocked()) return true;
-
+#if defined(ALLOW_ADBD_ROOT)
     // The properties that affect `adb root` and `adb unroot` are ro.secure and
     // ro.debuggable. In this context the names don't make the expected behavior
     // particularly obvious.
@@ -95,6 +89,9 @@
     }
 
     return drop;
+#else
+    return true; // "adb root" not allowed, always drop privileges.
+#endif // ALLOW_ADBD_ROOT
 }
 
 static void drop_privileges(int server_port) {
@@ -161,10 +158,7 @@
     // descriptor will always be open.
     adbd_cloexec_auth_socket();
 
-    // Respect ro.adb.secure in userdebug/eng builds (ALLOW_ADBD_NO_AUTH), or when the
-    // device is unlocked.
-    if ((ALLOW_ADBD_NO_AUTH || is_device_unlocked()) &&
-        !android::base::GetBoolProperty("ro.adb.secure", false)) {
+    if (ALLOW_ADBD_NO_AUTH && !android::base::GetBoolProperty("ro.adb.secure", false)) {
         auth_required = false;
     }
 
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 3513980..dfc74fb 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -47,13 +47,14 @@
 #define ATRACE_TAG ATRACE_TAG_BIONIC
 #include <utils/Trace.h>
 
-#include "backtrace.h"
-#include "tombstone.h"
-#include "utility.h"
+#include "libdebuggerd/backtrace.h"
+#include "libdebuggerd/tombstone.h"
+#include "libdebuggerd/utility.h"
 
 #include "debuggerd/handler.h"
-#include "protocol.h"
 #include "tombstoned/tombstoned.h"
+
+#include "protocol.h"
 #include "util.h"
 
 using android::base::unique_fd;
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
index 43104ec..06d4a9b 100644
--- a/debuggerd/handler/debuggerd_fallback.cpp
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -45,8 +45,8 @@
 #include "tombstoned/tombstoned.h"
 #include "util.h"
 
-#include "backtrace.h"
-#include "tombstone.h"
+#include "libdebuggerd/backtrace.h"
+#include "libdebuggerd/tombstone.h"
 
 using android::base::unique_fd;
 
diff --git a/debuggerd/libdebuggerd/arm/machine.cpp b/debuggerd/libdebuggerd/arm/machine.cpp
index ac833ae..bfb5ea4 100644
--- a/debuggerd/libdebuggerd/arm/machine.cpp
+++ b/debuggerd/libdebuggerd/arm/machine.cpp
@@ -17,6 +17,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <errno.h>
 #include <stdint.h>
 #include <string.h>
@@ -25,8 +27,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
   pt_regs regs;
diff --git a/debuggerd/libdebuggerd/arm64/machine.cpp b/debuggerd/libdebuggerd/arm64/machine.cpp
index fa73c99..ad1c951 100644
--- a/debuggerd/libdebuggerd/arm64/machine.cpp
+++ b/debuggerd/libdebuggerd/arm64/machine.cpp
@@ -17,6 +17,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <elf.h>
 #include <errno.h>
 #include <stdint.h>
@@ -27,8 +29,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
   struct user_pt_regs regs;
diff --git a/debuggerd/libdebuggerd/backtrace.cpp b/debuggerd/libdebuggerd/backtrace.cpp
index 334d97f..f616e1b 100644
--- a/debuggerd/libdebuggerd/backtrace.cpp
+++ b/debuggerd/libdebuggerd/backtrace.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/backtrace.h"
+
 #include <errno.h>
 #include <dirent.h>
 #include <limits.h>
@@ -34,9 +36,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "backtrace.h"
-
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 static void dump_process_header(log_t* log, pid_t pid, const char* process_name) {
   time_t t = time(NULL);
diff --git a/debuggerd/libdebuggerd/elf_utils.cpp b/debuggerd/libdebuggerd/elf_utils.cpp
index 4e798e2..a35102f 100644
--- a/debuggerd/libdebuggerd/elf_utils.cpp
+++ b/debuggerd/libdebuggerd/elf_utils.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/elf_utils.h"
+
 #include <elf.h>
 #include <stdint.h>
 #include <stdlib.h>
@@ -27,8 +29,6 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "elf_utils.h"
-
 #define NOTE_ALIGN(size)  (((size) + 3) & ~3)
 
 template <typename HdrType, typename PhdrType, typename NhdrType>
diff --git a/debuggerd/libdebuggerd/include/backtrace.h b/debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/backtrace.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h
diff --git a/debuggerd/libdebuggerd/include/elf_utils.h b/debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/elf_utils.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h
diff --git a/debuggerd/libdebuggerd/include/machine.h b/debuggerd/libdebuggerd/include/libdebuggerd/machine.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/machine.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/machine.h
diff --git a/debuggerd/libdebuggerd/include/open_files_list.h b/debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/open_files_list.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h
diff --git a/debuggerd/libdebuggerd/include/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/tombstone.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
diff --git a/debuggerd/libdebuggerd/include/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
similarity index 100%
rename from debuggerd/libdebuggerd/include/utility.h
rename to debuggerd/libdebuggerd/include/libdebuggerd/utility.h
diff --git a/debuggerd/libdebuggerd/mips/machine.cpp b/debuggerd/libdebuggerd/mips/machine.cpp
index cbf272a..1fc690b 100644
--- a/debuggerd/libdebuggerd/mips/machine.cpp
+++ b/debuggerd/libdebuggerd/mips/machine.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <errno.h>
 #include <inttypes.h>
 #include <stdint.h>
@@ -25,8 +27,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 #define R(x) (static_cast<uintptr_t>(x))
 
diff --git a/debuggerd/libdebuggerd/mips64/machine.cpp b/debuggerd/libdebuggerd/mips64/machine.cpp
index 0a8d532..955e507 100644
--- a/debuggerd/libdebuggerd/mips64/machine.cpp
+++ b/debuggerd/libdebuggerd/mips64/machine.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <errno.h>
 #include <inttypes.h>
 #include <stdint.h>
@@ -25,8 +27,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 #define R(x) (static_cast<uintptr_t>(x))
 
diff --git a/debuggerd/libdebuggerd/open_files_list.cpp b/debuggerd/libdebuggerd/open_files_list.cpp
index 5c7ea70..e199db8 100644
--- a/debuggerd/libdebuggerd/open_files_list.cpp
+++ b/debuggerd/libdebuggerd/open_files_list.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/open_files_list.h"
+
 #include <dirent.h>
 #include <errno.h>
 #include <stdio.h>
@@ -31,9 +33,7 @@
 #include <android-base/file.h>
 #include <log/log.h>
 
-#include "open_files_list.h"
-
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 void populate_open_files_list(pid_t pid, OpenFilesList* list) {
   std::string fd_dir_name = "/proc/" + std::to_string(pid) + "/fd";
diff --git a/debuggerd/libdebuggerd/test/dump_memory_test.cpp b/debuggerd/libdebuggerd/test/dump_memory_test.cpp
index 49f3690..0fad2cf 100644
--- a/debuggerd/libdebuggerd/test/dump_memory_test.cpp
+++ b/debuggerd/libdebuggerd/test/dump_memory_test.cpp
@@ -22,9 +22,10 @@
 #include <gtest/gtest.h>
 #include <android-base/file.h>
 
+#include "libdebuggerd/utility.h"
+
 #include "BacktraceMock.h"
 #include "log_fake.h"
-#include "utility.h"
 
 const char g_expected_full_dump[] =
 "\nmemory near r1:\n"
diff --git a/debuggerd/libdebuggerd/test/elf_fake.cpp b/debuggerd/libdebuggerd/test/elf_fake.cpp
index bb52b59..f8cbca7 100644
--- a/debuggerd/libdebuggerd/test/elf_fake.cpp
+++ b/debuggerd/libdebuggerd/test/elf_fake.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "elf_fake.h"
+
 #include <stdint.h>
 
 #include <string>
diff --git a/debuggerd/libdebuggerd/test/log_fake.cpp b/debuggerd/libdebuggerd/test/log_fake.cpp
index 3336bcb..68f4013 100644
--- a/debuggerd/libdebuggerd/test/log_fake.cpp
+++ b/debuggerd/libdebuggerd/test/log_fake.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "log_fake.h"
+
 #include <errno.h>
 #include <stdarg.h>
 
diff --git a/debuggerd/libdebuggerd/test/open_files_list_test.cpp b/debuggerd/libdebuggerd/test/open_files_list_test.cpp
index 85e0695..acac72c 100644
--- a/debuggerd/libdebuggerd/test/open_files_list_test.cpp
+++ b/debuggerd/libdebuggerd/test/open_files_list_test.cpp
@@ -24,7 +24,7 @@
 
 #include "android-base/test_utils.h"
 
-#include "open_files_list.h"
+#include "libdebuggerd/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.
diff --git a/debuggerd/libdebuggerd/test/ptrace_fake.cpp b/debuggerd/libdebuggerd/test/ptrace_fake.cpp
index f40cbd4..0d4080e 100644
--- a/debuggerd/libdebuggerd/test/ptrace_fake.cpp
+++ b/debuggerd/libdebuggerd/test/ptrace_fake.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "ptrace_fake.h"
+
 #include <errno.h>
 #include <signal.h>
 #include <stdarg.h>
@@ -21,8 +23,6 @@
 
 #include <string>
 
-#include "ptrace_fake.h"
-
 siginfo_t g_fake_si = {.si_signo = 0};
 
 void ptrace_set_fake_getsiginfo(const siginfo_t& si) {
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 6be59e7..e79dd96 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -22,7 +22,7 @@
 #include <gtest/gtest.h>
 #include <android-base/file.h>
 
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 #include "BacktraceMock.h"
 #include "elf_fake.h"
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index b809ed4..50d19bd 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/tombstone.h"
+
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -43,22 +45,18 @@
 #include <log/logprint.h>
 #include <private/android_filesystem_config.h>
 
+// Needed to get DEBUGGER_SIGNAL.
 #include "debuggerd/handler.h"
 
-#include "backtrace.h"
-#include "elf_utils.h"
-#include "machine.h"
-#include "open_files_list.h"
-#include "tombstone.h"
+#include "libdebuggerd/backtrace.h"
+#include "libdebuggerd/elf_utils.h"
+#include "libdebuggerd/machine.h"
+#include "libdebuggerd/open_files_list.h"
 
 using android::base::StringPrintf;
 
 #define STACK_WORDS 16
 
-#define MAX_TOMBSTONES  10
-#define TOMBSTONE_DIR   "/data/tombstones"
-#define TOMBSTONE_TEMPLATE (TOMBSTONE_DIR"/tombstone_%02d")
-
 static bool signal_has_si_addr(int si_signo, int si_code) {
   // Manually sent signals won't have si_addr.
   if (si_code == SI_USER || si_code == SI_QUEUE || si_code == SI_TKILL) {
@@ -764,59 +762,6 @@
   }
 }
 
-// open_tombstone - find an available tombstone slot, if any, of the
-// form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
-// file is available, we reuse the least-recently-modified file.
-int open_tombstone(std::string* out_path) {
-  // In a single pass, find an available slot and, in case none
-  // exist, find and record the least-recently-modified file.
-  char path[128];
-  int fd = -1;
-  int oldest = -1;
-  struct stat oldest_sb;
-  for (int i = 0; i < MAX_TOMBSTONES; i++) {
-    snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, i);
-
-    struct stat sb;
-    if (stat(path, &sb) == 0) {
-      if (oldest < 0 || sb.st_mtime < oldest_sb.st_mtime) {
-        oldest = i;
-        oldest_sb.st_mtime = sb.st_mtime;
-      }
-      continue;
-    }
-    if (errno != ENOENT) continue;
-
-    fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
-    if (fd < 0) continue;  // raced ?
-
-    if (out_path) {
-      *out_path = path;
-    }
-    fchown(fd, AID_SYSTEM, AID_SYSTEM);
-    return fd;
-  }
-
-  if (oldest < 0) {
-    ALOGE("debuggerd: failed to find a valid tombstone, default to using tombstone 0.\n");
-    oldest = 0;
-  }
-
-  // we didn't find an available file, so we clobber the oldest one
-  snprintf(path, sizeof(path), TOMBSTONE_TEMPLATE, oldest);
-  fd = open(path, O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0600);
-  if (fd < 0) {
-    ALOGE("debuggerd: failed to open tombstone file '%s': %s\n", path, strerror(errno));
-    return -1;
-  }
-
-  if (out_path) {
-    *out_path = path;
-  }
-  fchown(fd, AID_SYSTEM, AID_SYSTEM);
-  return fd;
-}
-
 void engrave_tombstone(int tombstone_fd, BacktraceMap* map, BacktraceMap* map_new,
                        const OpenFilesList* open_files, pid_t pid, pid_t tid,
                        const std::string& process_name, const std::map<pid_t, std::string>& threads,
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 7f450e6..1b74652 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "DEBUG"
 
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 #include <errno.h>
 #include <signal.h>
diff --git a/debuggerd/libdebuggerd/x86/machine.cpp b/debuggerd/libdebuggerd/x86/machine.cpp
index af10817..09a64cd 100644
--- a/debuggerd/libdebuggerd/x86/machine.cpp
+++ b/debuggerd/libdebuggerd/x86/machine.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <errno.h>
 #include <stdint.h>
 #include <string.h>
@@ -24,8 +26,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
   struct pt_regs r;
diff --git a/debuggerd/libdebuggerd/x86_64/machine.cpp b/debuggerd/libdebuggerd/x86_64/machine.cpp
index bf2c2b4..de1c268 100644
--- a/debuggerd/libdebuggerd/x86_64/machine.cpp
+++ b/debuggerd/libdebuggerd/x86_64/machine.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "DEBUG"
 
+#include "libdebuggerd/machine.h"
+
 #include <errno.h>
 #include <stdint.h>
 #include <string.h>
@@ -25,8 +27,7 @@
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
-#include "machine.h"
-#include "utility.h"
+#include "libdebuggerd/utility.h"
 
 void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
   struct user_regs_struct r;
diff --git a/init/Android.bp b/init/Android.bp
index 33dfe56..8737def 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -72,6 +72,7 @@
         "import_parser.cpp",
         "log.cpp",
         "parser.cpp",
+        "persistent_properties.cpp",
         "property_service.cpp",
         "security.cpp",
         "selinux.cpp",
@@ -162,6 +163,7 @@
     srcs: [
         "devices_test.cpp",
         "init_test.cpp",
+        "persistent_properties_test.cpp",
         "property_service_test.cpp",
         "result_test.cpp",
         "rlimit_parser_test.cpp",
diff --git a/init/README.md b/init/README.md
index b681f21..7df37ff 100644
--- a/init/README.md
+++ b/init/README.md
@@ -453,8 +453,9 @@
 `rmdir <path>`
 > Calls rmdir(2) on the given path.
 
-`readahead <file|dir>`
+`readahead <file|dir> [--fully]`
 > Calls readahead(2) on the file or files within given directory.
+  Use option --fully to read the full file content.
 
 `setprop <name> <value>`
 > Set system property _name_ to _value_. Properties are expanded
diff --git a/init/builtins.cpp b/init/builtins.cpp
index e2e3d93..140ef75 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -56,6 +56,7 @@
 #include <selinux/android.h>
 #include <selinux/label.h>
 #include <selinux/selinux.h>
+#include <system/thread_defs.h>
 
 #include "action.h"
 #include "bootchart.h"
@@ -670,6 +671,29 @@
     return Success();
 }
 
+static Result<Success> readahead_file(const std::string& filename, bool fully) {
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY)));
+    if (fd == -1) {
+        return ErrnoError() << "Error opening file";
+    }
+    if (posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED)) {
+        return ErrnoError() << "Error posix_fadvise file";
+    }
+    if (readahead(fd, 0, std::numeric_limits<size_t>::max())) {
+        return ErrnoError() << "Error readahead file";
+    }
+    if (fully) {
+        char buf[BUFSIZ];
+        ssize_t n;
+        while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
+        }
+        if (n != 0) {
+            return ErrnoError() << "Error reading file";
+        }
+    }
+    return Success();
+}
+
 static Result<Success> do_readahead(const std::vector<std::string>& args) {
     struct stat sb;
 
@@ -677,6 +701,10 @@
         return ErrnoError() << "Error opening " << args[1];
     }
 
+    bool readfully = false;
+    if (args.size() == 3 && args[2] == "--fully") {
+        readfully = true;
+    }
     // We will do readahead in a forked process in order not to block init
     // since it may block while it reads the
     // filesystem metadata needed to locate the requested blocks.  This
@@ -685,15 +713,16 @@
     // the requested data has been read.
     pid_t pid = fork();
     if (pid == 0) {
+        if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
+            PLOG(WARNING) << "setpriority failed";
+        }
+        if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
+            PLOG(WARNING) << "ioprio_get failed";
+        }
         android::base::Timer t;
         if (S_ISREG(sb.st_mode)) {
-            android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(args[1].c_str(), O_RDONLY)));
-            if (fd == -1) {
-                PLOG(ERROR) << "Error opening file: " << args[1];
-                _exit(EXIT_FAILURE);
-            }
-            if (readahead(fd, 0, std::numeric_limits<size_t>::max())) {
-                PLOG(ERROR) << "Error readahead file: " << args[1];
+            if (auto result = readahead_file(args[1], readfully); !result) {
+                LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
                 _exit(EXIT_FAILURE);
             }
         } else if (S_ISDIR(sb.st_mode)) {
@@ -708,19 +737,15 @@
             for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
                  ftsent = fts_read(fts.get())) {
                 if (ftsent->fts_info & FTS_F) {
-                    android::base::unique_fd fd(
-                        TEMP_FAILURE_RETRY(open(ftsent->fts_accpath, O_RDONLY)));
-                    if (fd == -1) {
-                        PLOG(ERROR) << "Error opening file: " << args[1];
-                        continue;
-                    }
-                    if (readahead(fd, 0, std::numeric_limits<size_t>::max())) {
-                        PLOG(ERROR) << "Unable to readahead on file: " << ftsent->fts_accpath;
+                    const std::string filename = ftsent->fts_accpath;
+                    if (auto result = readahead_file(filename, readfully); !result) {
+                        LOG(WARNING)
+                            << "Unable to readahead '" << filename << "': " << result.error();
                     }
                 }
             }
         }
-        LOG(INFO) << "Readahead " << args[1] << " took " << t;
+        LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
         _exit(0);
     } else if (pid < 0) {
         return ErrnoError() << "Fork failed";
@@ -949,7 +974,7 @@
         {"mount_all",               {1,     kMax, do_mount_all}},
         {"mount",                   {3,     kMax, do_mount}},
         {"umount",                  {1,     1,    do_umount}},
-        {"readahead",               {1,     1,    do_readahead}},
+        {"readahead",               {1,     2,    do_readahead}},
         {"restart",                 {1,     1,    do_restart}},
         {"restorecon",              {1,     kMax, do_restorecon}},
         {"restorecon_recursive",    {1,     kMax, do_restorecon_recursive}},
diff --git a/init/persistent_properties.cpp b/init/persistent_properties.cpp
new file mode 100644
index 0000000..66fa011
--- /dev/null
+++ b/init/persistent_properties.cpp
@@ -0,0 +1,341 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "persistent_properties.h"
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/system_properties.h>
+#include <sys/types.h>
+
+#include <memory>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+
+#include "util.h"
+
+using android::base::ReadFdToString;
+using android::base::StartsWith;
+using android::base::WriteStringToFd;
+using android::base::unique_fd;
+
+namespace android {
+namespace init {
+
+std::string persistent_property_filename = "/data/property/persistent_properties";
+
+namespace {
+
+constexpr const uint32_t kMagic = 0x8495E0B4;
+constexpr const char kLegacyPersistentPropertyDir[] = "/data/property";
+
+Result<std::vector<std::pair<std::string, std::string>>> LoadLegacyPersistentProperties() {
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kLegacyPersistentPropertyDir), closedir);
+    if (!dir) {
+        return ErrnoError() << "Unable to open persistent property directory \""
+                            << kLegacyPersistentPropertyDir << "\"";
+    }
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties;
+    dirent* entry;
+    while ((entry = readdir(dir.get())) != nullptr) {
+        if (!StartsWith(entry->d_name, "persist.")) {
+            continue;
+        }
+        if (entry->d_type != DT_REG) {
+            continue;
+        }
+
+        unique_fd fd(openat(dirfd(dir.get()), entry->d_name, O_RDONLY | O_NOFOLLOW));
+        if (fd == -1) {
+            PLOG(ERROR) << "Unable to open persistent property file \"" << entry->d_name << "\"";
+            continue;
+        }
+
+        struct stat sb;
+        if (fstat(fd, &sb) == -1) {
+            PLOG(ERROR) << "fstat on property file \"" << entry->d_name << "\" failed";
+            continue;
+        }
+
+        // File must not be accessible to others, be owned by root/root, and
+        // not be a hard link to any other file.
+        if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || sb.st_uid != 0 || sb.st_gid != 0 ||
+            sb.st_nlink != 1) {
+            PLOG(ERROR) << "skipping insecure property file " << entry->d_name
+                        << " (uid=" << sb.st_uid << " gid=" << sb.st_gid << " nlink=" << sb.st_nlink
+                        << " mode=" << std::oct << sb.st_mode << ")";
+            continue;
+        }
+
+        std::string value;
+        if (ReadFdToString(fd, &value)) {
+            persistent_properties.emplace_back(entry->d_name, value);
+        } else {
+            PLOG(ERROR) << "Unable to read persistent property file " << entry->d_name;
+        }
+    }
+    return persistent_properties;
+}
+
+void RemoveLegacyPersistentPropertyFiles() {
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kLegacyPersistentPropertyDir), closedir);
+    if (!dir) {
+        PLOG(ERROR) << "Unable to open persistent property directory \""
+                    << kLegacyPersistentPropertyDir << "\"";
+        return;
+    }
+
+    dirent* entry;
+    while ((entry = readdir(dir.get())) != nullptr) {
+        if (!StartsWith(entry->d_name, "persist.")) {
+            continue;
+        }
+        if (entry->d_type != DT_REG) {
+            continue;
+        }
+        unlinkat(dirfd(dir.get()), entry->d_name, 0);
+    }
+}
+
+std::vector<std::pair<std::string, std::string>> LoadPersistentPropertiesFromMemory() {
+    std::vector<std::pair<std::string, std::string>> properties;
+    __system_property_foreach(
+        [](const prop_info* pi, void* cookie) {
+            __system_property_read_callback(
+                pi,
+                [](void* cookie, const char* name, const char* value, unsigned serial) {
+                    if (StartsWith(name, "persist.")) {
+                        auto properties =
+                            reinterpret_cast<std::vector<std::pair<std::string, std::string>>*>(
+                                cookie);
+                        properties->emplace_back(name, value);
+                    }
+                },
+                cookie);
+        },
+        &properties);
+    return properties;
+}
+
+class PersistentPropertyFileParser {
+  public:
+    PersistentPropertyFileParser(const std::string& contents) : contents_(contents), position_(0) {}
+    Result<std::vector<std::pair<std::string, std::string>>> Parse();
+
+  private:
+    Result<std::string> ReadString();
+    Result<uint32_t> ReadUint32();
+
+    const std::string& contents_;
+    size_t position_;
+};
+
+Result<std::vector<std::pair<std::string, std::string>>> PersistentPropertyFileParser::Parse() {
+    std::vector<std::pair<std::string, std::string>> result;
+
+    if (auto magic = ReadUint32(); magic) {
+        if (*magic != kMagic) {
+            return Error() << "Magic value '0x" << std::hex << *magic
+                           << "' does not match expected value '0x" << kMagic << "'";
+        }
+    } else {
+        return Error() << "Could not read magic value: " << magic.error();
+    }
+
+    if (auto version = ReadUint32(); version) {
+        if (*version != 1) {
+            return Error() << "Version '" << *version
+                           << "' does not match any compatible version: (1)";
+        }
+    } else {
+        return Error() << "Could not read version: " << version.error();
+    }
+
+    auto num_properties = ReadUint32();
+    if (!num_properties) {
+        return Error() << "Could not read num_properties: " << num_properties.error();
+    }
+
+    while (position_ < contents_.size()) {
+        auto key = ReadString();
+        if (!key) {
+            return Error() << "Could not read key: " << key.error();
+        }
+        if (!StartsWith(*key, "persist.")) {
+            return Error() << "Property '" << *key << "' does not starts with 'persist.'";
+        }
+        auto value = ReadString();
+        if (!value) {
+            return Error() << "Could not read value: " << value.error();
+        }
+        result.emplace_back(*key, *value);
+    }
+
+    if (result.size() != *num_properties) {
+        return Error() << "Mismatch of number of persistent properties read, " << result.size()
+                       << " and number of persistent properties expected, " << *num_properties;
+    }
+
+    return result;
+}
+
+Result<std::string> PersistentPropertyFileParser::ReadString() {
+    auto string_length = ReadUint32();
+    if (!string_length) {
+        return Error() << "Could not read size for string";
+    }
+
+    if (position_ + *string_length > contents_.size()) {
+        return Error() << "String size would cause it to overflow the input buffer";
+    }
+    auto result = std::string(contents_, position_, *string_length);
+    position_ += *string_length;
+    return result;
+}
+
+Result<uint32_t> PersistentPropertyFileParser::ReadUint32() {
+    if (position_ + 3 > contents_.size()) {
+        return Error() << "Input buffer not large enough to read uint32_t";
+    }
+    uint32_t result = *reinterpret_cast<const uint32_t*>(&contents_[position_]);
+    position_ += sizeof(uint32_t);
+    return result;
+}
+
+}  // namespace
+
+Result<std::vector<std::pair<std::string, std::string>>> LoadPersistentPropertyFile() {
+    const std::string temp_filename = persistent_property_filename + ".tmp";
+    if (access(temp_filename.c_str(), F_OK) == 0) {
+        LOG(INFO)
+            << "Found temporary property file while attempting to persistent system properties"
+               " a previous persistent property write may have failed";
+        unlink(temp_filename.c_str());
+    }
+    auto file_contents = ReadFile(persistent_property_filename);
+    if (!file_contents) {
+        return Error() << "Unable to read persistent property file: " << file_contents.error();
+    }
+    auto parsed_contents = PersistentPropertyFileParser(*file_contents).Parse();
+    if (!parsed_contents) {
+        // If the file cannot be parsed, then we don't have any recovery mechanisms, so we delete
+        // it to allow for future writes to take place successfully.
+        unlink(persistent_property_filename.c_str());
+        return Error() << "Unable to parse persistent property file: " << parsed_contents.error();
+    }
+    return parsed_contents;
+}
+
+std::string GenerateFileContents(
+    const std::vector<std::pair<std::string, std::string>>& persistent_properties) {
+    std::string result;
+
+    uint32_t magic = kMagic;
+    result.append(reinterpret_cast<char*>(&magic), sizeof(uint32_t));
+
+    uint32_t version = 1;
+    result.append(reinterpret_cast<char*>(&version), sizeof(uint32_t));
+
+    uint32_t num_properties = persistent_properties.size();
+    result.append(reinterpret_cast<char*>(&num_properties), sizeof(uint32_t));
+
+    for (const auto& [key, value] : persistent_properties) {
+        uint32_t key_length = key.length();
+        result.append(reinterpret_cast<char*>(&key_length), sizeof(uint32_t));
+        result.append(key);
+        uint32_t value_length = value.length();
+        result.append(reinterpret_cast<char*>(&value_length), sizeof(uint32_t));
+        result.append(value);
+    }
+    return result;
+}
+
+Result<Success> WritePersistentPropertyFile(
+    const std::vector<std::pair<std::string, std::string>>& persistent_properties) {
+    auto file_contents = GenerateFileContents(persistent_properties);
+
+    const std::string temp_filename = persistent_property_filename + ".tmp";
+    unique_fd fd(TEMP_FAILURE_RETRY(
+        open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
+    if (fd == -1) {
+        return ErrnoError() << "Could not open temporary properties file";
+    }
+    if (!WriteStringToFd(file_contents, fd)) {
+        return ErrnoError() << "Unable to write file contents";
+    }
+    fsync(fd);
+    fd.reset();
+
+    if (rename(temp_filename.c_str(), persistent_property_filename.c_str())) {
+        int saved_errno = errno;
+        unlink(temp_filename.c_str());
+        return Error(saved_errno) << "Unable to rename persistent property file";
+    }
+    return Success();
+}
+
+// Persistent properties are not written often, so we rather not keep any data in memory and read
+// then rewrite the persistent property file for each update.
+void WritePersistentProperty(const std::string& name, const std::string& value) {
+    auto persistent_properties = LoadPersistentPropertyFile();
+    if (!persistent_properties) {
+        LOG(ERROR) << "Recovering persistent properties from memory: "
+                   << persistent_properties.error();
+        persistent_properties = LoadPersistentPropertiesFromMemory();
+    }
+    auto it = std::find_if(persistent_properties->begin(), persistent_properties->end(),
+                           [&name](const auto& entry) { return entry.first == name; });
+    if (it != persistent_properties->end()) {
+        *it = {name, value};
+    } else {
+        persistent_properties->emplace_back(name, value);
+    }
+
+    if (auto result = WritePersistentPropertyFile(*persistent_properties); !result) {
+        LOG(ERROR) << "Could not store persistent property: " << result.error();
+    }
+}
+
+std::vector<std::pair<std::string, std::string>> LoadPersistentProperties() {
+    auto persistent_properties = LoadPersistentPropertyFile();
+
+    if (!persistent_properties) {
+        LOG(ERROR) << "Could not load single persistent property file, trying legacy directory: "
+                   << persistent_properties.error();
+        persistent_properties = LoadLegacyPersistentProperties();
+        if (!persistent_properties) {
+            LOG(ERROR) << "Unable to load legacy persistent properties: "
+                       << persistent_properties.error();
+            return {};
+        }
+        if (auto result = WritePersistentPropertyFile(*persistent_properties); result) {
+            RemoveLegacyPersistentPropertyFiles();
+        } else {
+            LOG(ERROR) << "Unable to write single persistent property file: " << result.error();
+            // Fall through so that we still set the properties that we've read.
+        }
+    }
+
+    return *persistent_properties;
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/init/persistent_properties.h b/init/persistent_properties.h
new file mode 100644
index 0000000..d84d9db
--- /dev/null
+++ b/init/persistent_properties.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _INIT_PERSISTENT_PROPERTIES_H
+#define _INIT_PERSISTENT_PROPERTIES_H
+
+#include <string>
+#include <vector>
+
+#include "result.h"
+
+namespace android {
+namespace init {
+
+std::vector<std::pair<std::string, std::string>> LoadPersistentProperties();
+void WritePersistentProperty(const std::string& name, const std::string& value);
+
+// Exposed only for testing
+Result<std::vector<std::pair<std::string, std::string>>> LoadPersistentPropertyFile();
+std::string GenerateFileContents(
+    const std::vector<std::pair<std::string, std::string>>& persistent_properties);
+Result<Success> WritePersistentPropertyFile(
+    const std::vector<std::pair<std::string, std::string>>& persistent_properties);
+extern std::string persistent_property_filename;
+
+}  // namespace init
+}  // namespace android
+
+#endif
diff --git a/init/persistent_properties_test.cpp b/init/persistent_properties_test.cpp
new file mode 100644
index 0000000..9ab5b22
--- /dev/null
+++ b/init/persistent_properties_test.cpp
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "persistent_properties.h"
+
+#include <errno.h>
+
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "util.h"
+
+using namespace std::string_literals;
+
+namespace android {
+namespace init {
+
+TEST(persistent_properties, GeneratedContents) {
+    const std::vector<std::pair<std::string, std::string>> persistent_properties = {
+        {"persist.abc", ""},
+        {"persist.def", "test_success"},
+    };
+    auto generated_contents = GenerateFileContents(persistent_properties);
+
+    // Manually serialized contents below:
+    std::string file_contents;
+    // All values below are written and read as little endian.
+    // Add magic value: 0x8495E0B4
+    file_contents += "\xB4\xE0\x95\x84"s;
+    // Add version: 1
+    file_contents += "\x01\x00\x00\x00"s;
+    // Add number of properties: 2
+    file_contents += "\x02\x00\x00\x00"s;
+
+    // Add first key: persist.abc
+    file_contents += "\x0B\x00\x00\x00persist.abc"s;
+    // Add first value: (empty string)
+    file_contents += "\x00\x00\x00\x00"s;
+
+    // Add second key: persist.def
+    file_contents += "\x0B\x00\x00\x00persist.def"s;
+    // Add second value: test_success
+    file_contents += "\x0C\x00\x00\x00test_success"s;
+
+    EXPECT_EQ(file_contents, generated_contents);
+}
+
+TEST(persistent_properties, EndToEnd) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    persistent_property_filename = tf.path;
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties = {
+        {"persist.sys.locale", "en-US"},
+        {"persist.sys.timezone", "America/Los_Angeles"},
+        {"persist.test.empty.value", ""},
+        {"persist.test.new.line", "abc\n\n\nabc"},
+        {"persist.test.numbers", "1234567890"},
+        {"persist.test.non.ascii", "\x00\x01\x02\xFF\xFE\xFD\x7F\x8F\x9F"},
+        // We don't currently allow for non-ascii keys for system properties, but this is a policy
+        // decision, not a technical limitation.
+        {"persist.\x00\x01\x02\xFF\xFE\xFD\x7F\x8F\x9F", "non-ascii-key"},
+    };
+
+    ASSERT_TRUE(WritePersistentPropertyFile(persistent_properties));
+
+    auto read_back_properties = LoadPersistentProperties();
+    EXPECT_EQ(persistent_properties, read_back_properties);
+}
+
+TEST(persistent_properties, BadMagic) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    persistent_property_filename = tf.path;
+
+    ASSERT_TRUE(WriteFile(tf.path, "ab"));
+
+    auto read_back_properties = LoadPersistentPropertyFile();
+
+    ASSERT_FALSE(read_back_properties);
+    EXPECT_EQ(
+        "Unable to parse persistent property file: Could not read magic value: Input buffer not "
+        "large enough to read uint32_t",
+        read_back_properties.error_string());
+
+    ASSERT_TRUE(WriteFile(tf.path, "\xFF\xFF\xFF\xFF"));
+
+    read_back_properties = LoadPersistentPropertyFile();
+
+    ASSERT_FALSE(read_back_properties);
+    EXPECT_EQ(
+        "Unable to parse persistent property file: Magic value '0xffffffff' does not match "
+        "expected value '0x8495e0b4'",
+        read_back_properties.error_string());
+}
+
+TEST(persistent_properties, AddProperty) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    persistent_property_filename = tf.path;
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties = {
+        {"persist.sys.timezone", "America/Los_Angeles"},
+    };
+    ASSERT_TRUE(WritePersistentPropertyFile(persistent_properties));
+
+    WritePersistentProperty("persist.sys.locale", "pt-BR");
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties_expected = {
+        {"persist.sys.timezone", "America/Los_Angeles"},
+        {"persist.sys.locale", "pt-BR"},
+    };
+
+    auto read_back_properties = LoadPersistentProperties();
+    EXPECT_EQ(persistent_properties_expected, read_back_properties);
+}
+
+TEST(persistent_properties, UpdateProperty) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    persistent_property_filename = tf.path;
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties = {
+        {"persist.sys.locale", "en-US"},
+        {"persist.sys.timezone", "America/Los_Angeles"},
+    };
+    ASSERT_TRUE(WritePersistentPropertyFile(persistent_properties));
+
+    WritePersistentProperty("persist.sys.locale", "pt-BR");
+
+    std::vector<std::pair<std::string, std::string>> persistent_properties_expected = {
+        {"persist.sys.locale", "pt-BR"},
+        {"persist.sys.timezone", "America/Los_Angeles"},
+    };
+
+    auto read_back_properties = LoadPersistentProperties();
+    EXPECT_EQ(persistent_properties_expected, read_back_properties);
+}
+
+TEST(persistent_properties, UpdatePropertyBadParse) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    persistent_property_filename = tf.path;
+
+    ASSERT_TRUE(WriteFile(tf.path, "ab"));
+
+    WritePersistentProperty("persist.sys.locale", "pt-BR");
+
+    auto read_back_properties = LoadPersistentProperties();
+    EXPECT_GT(read_back_properties.size(), 0U);
+
+    auto it = std::find_if(
+        read_back_properties.begin(), read_back_properties.end(), [](const auto& entry) {
+            return entry.first == "persist.sys.locale" && entry.second == "pt-BR";
+        });
+    EXPECT_FALSE(it == read_back_properties.end());
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/init/property_service.cpp b/init/property_service.cpp
index f0e4d2e..8c592cb 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -17,7 +17,6 @@
 #include "property_service.h"
 
 #include <ctype.h>
-#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
@@ -54,17 +53,17 @@
 #include <selinux/selinux.h>
 
 #include "init.h"
+#include "persistent_properties.h"
 #include "util.h"
 
 using android::base::Timer;
 
-#define PERSISTENT_PROPERTY_DIR  "/data/property"
 #define RECOVERY_MOUNT_POINT "/recovery"
 
 namespace android {
 namespace init {
 
-static int persistent_properties_loaded = 0;
+static bool persistent_properties_loaded = false;
 
 static int property_set_fd = -1;
 
@@ -120,29 +119,6 @@
     return check_mac_perms(ctl_name, sctx, cr);
 }
 
-static void write_persistent_property(const char *name, const char *value)
-{
-    char tempPath[PATH_MAX];
-    char path[PATH_MAX];
-    int fd;
-
-    snprintf(tempPath, sizeof(tempPath), "%s/.temp.XXXXXX", PERSISTENT_PROPERTY_DIR);
-    fd = mkstemp(tempPath);
-    if (fd < 0) {
-        PLOG(ERROR) << "Unable to write persistent property to temp file " << tempPath;
-        return;
-    }
-    write(fd, value, strlen(value));
-    fsync(fd);
-    close(fd);
-
-    snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);
-    if (rename(tempPath, path)) {
-        PLOG(ERROR) << "Unable to rename persistent property file " << tempPath << " to " << path;
-        unlink(tempPath);
-    }
-}
-
 bool is_legal_property_name(const std::string& name) {
     size_t namelen = name.size();
 
@@ -204,7 +180,7 @@
     // Don't write properties to disk until after we have read all default
     // properties to prevent them from being overwritten by default values.
     if (persistent_properties_loaded && android::base::StartsWith(name, "persist.")) {
-        write_persistent_property(name.c_str(), value.c_str());
+        WritePersistentProperty(name, value);
     }
     property_changed(name, value);
     return PROP_SUCCESS;
@@ -599,61 +575,6 @@
     LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
 }
 
-static void load_persistent_properties() {
-    persistent_properties_loaded = 1;
-
-    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(PERSISTENT_PROPERTY_DIR), closedir);
-    if (!dir) {
-        PLOG(ERROR) << "Unable to open persistent property directory \""
-                    << PERSISTENT_PROPERTY_DIR << "\"";
-        return;
-    }
-
-    struct dirent* entry;
-    while ((entry = readdir(dir.get())) != NULL) {
-        if (strncmp("persist.", entry->d_name, strlen("persist."))) {
-            continue;
-        }
-        if (entry->d_type != DT_REG) {
-            continue;
-        }
-
-        // Open the file and read the property value.
-        int fd = openat(dirfd(dir.get()), entry->d_name, O_RDONLY | O_NOFOLLOW);
-        if (fd == -1) {
-            PLOG(ERROR) << "Unable to open persistent property file \"" << entry->d_name << "\"";
-            continue;
-        }
-
-        struct stat sb;
-        if (fstat(fd, &sb) == -1) {
-            PLOG(ERROR) << "fstat on property file \"" << entry->d_name << "\" failed";
-            close(fd);
-            continue;
-        }
-
-        // File must not be accessible to others, be owned by root/root, and
-        // not be a hard link to any other file.
-        if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || sb.st_uid != 0 || sb.st_gid != 0 || sb.st_nlink != 1) {
-            PLOG(ERROR) << "skipping insecure property file " << entry->d_name
-                        << " (uid=" << sb.st_uid << " gid=" << sb.st_gid
-                        << " nlink=" << sb.st_nlink << " mode=" << std::oct << sb.st_mode << ")";
-            close(fd);
-            continue;
-        }
-
-        char value[PROP_VALUE_MAX];
-        int length = read(fd, value, sizeof(value) - 1);
-        if (length >= 0) {
-            value[length] = 0;
-            property_set(entry->d_name, value);
-        } else {
-            PLOG(ERROR) << "Unable to read persistent property file " << entry->d_name;
-        }
-        close(fd);
-    }
-}
-
 // persist.sys.usb.config values can't be combined on build-time when property
 // files are split into each partition.
 // So we need to apply the same rule of build/make/tools/post_process_props.py
@@ -703,7 +624,11 @@
 
     load_override_properties();
     /* Read persistent properties after all default values have been loaded. */
-    load_persistent_properties();
+    auto persistent_properties = LoadPersistentProperties();
+    for (const auto& [name, value] : persistent_properties) {
+        property_set(name, value);
+    }
+    persistent_properties_loaded = true;
     property_set("ro.persistent_properties.ready", "true");
 }
 
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
index 4fc7c67..4f7476d 100644
--- a/libunwindstack/Elf.cpp
+++ b/libunwindstack/Elf.cpp
@@ -124,6 +124,28 @@
   return true;
 }
 
+void Elf::GetInfo(Memory* memory, bool* valid, uint64_t* size) {
+  if (!IsValidElf(memory)) {
+    *valid = false;
+    return;
+  }
+  *size = 0;
+  *valid = true;
+
+  // Now read the section header information.
+  uint8_t class_type;
+  if (!memory->Read(EI_CLASS, &class_type, 1)) {
+    return;
+  }
+  if (class_type == ELFCLASS32) {
+    ElfInterface32::GetMaxSize(memory, size);
+  } else if (class_type == ELFCLASS64) {
+    ElfInterface64::GetMaxSize(memory, size);
+  } else {
+    *valid = false;
+  }
+}
+
 ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
   if (!IsValidElf(memory)) {
     return nullptr;
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index 75abc85..be4f88a 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -370,6 +370,22 @@
   return false;
 }
 
+// This is an estimation of the size of the elf file using the location
+// of the section headers and size. This assumes that the section headers
+// are at the end of the elf file. If the elf has a load bias, the size
+// will be too large, but this is acceptable.
+template <typename EhdrType>
+void ElfInterface::GetMaxSizeWithTemplate(Memory* memory, uint64_t* size) {
+  EhdrType ehdr;
+  if (!memory->Read(0, &ehdr, sizeof(ehdr))) {
+    return;
+  }
+  if (ehdr.e_shnum == 0) {
+    return;
+  }
+  *size = ehdr.e_shoff + ehdr.e_shentsize * ehdr.e_shnum;
+}
+
 // Instantiate all of the needed template functions.
 template void ElfInterface::InitHeadersWithTemplate<uint32_t>();
 template void ElfInterface::InitHeadersWithTemplate<uint64_t>();
@@ -391,4 +407,7 @@
 template bool ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(uint64_t, std::string*,
                                                                    uint64_t*);
 
+template void ElfInterface::GetMaxSizeWithTemplate<Elf32_Ehdr>(Memory*, uint64_t*);
+template void ElfInterface::GetMaxSizeWithTemplate<Elf64_Ehdr>(Memory*, uint64_t*);
+
 }  // namespace unwindstack
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index d0e1216..3272215 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -27,6 +27,55 @@
 
 namespace unwindstack {
 
+Memory* MapInfo::GetFileMemory() {
+  std::unique_ptr<MemoryFileAtOffset> memory(new MemoryFileAtOffset);
+  if (offset == 0) {
+    if (memory->Init(name, 0)) {
+      return memory.release();
+    }
+    return nullptr;
+  }
+
+  // There are two possibilities when the offset is non-zero.
+  // - There is an elf file embedded in a file.
+  // - The whole file is an elf file, and the offset needs to be saved.
+  //
+  // Map in just the part of the file for the map. If this is not
+  // a valid elf, then reinit as if the whole file is an elf file.
+  // If the offset is a valid elf, then determine the size of the map
+  // and reinit to that size. This is needed because the dynamic linker
+  // only maps in a portion of the original elf, and never the symbol
+  // file data.
+  uint64_t map_size = end - start;
+  if (!memory->Init(name, offset, map_size)) {
+    return nullptr;
+  }
+
+  bool valid;
+  uint64_t max_size;
+  Elf::GetInfo(memory.get(), &valid, &max_size);
+  if (!valid) {
+    // Init as if the whole file is an elf.
+    if (memory->Init(name, 0)) {
+      elf_offset = offset;
+      return memory.release();
+    }
+    return nullptr;
+  }
+
+  if (max_size > map_size) {
+    if (memory->Init(name, offset, max_size)) {
+      return memory.release();
+    }
+    // Try to reinit using the default map_size.
+    if (memory->Init(name, offset, map_size)) {
+      return memory.release();
+    }
+    return nullptr;
+  }
+  return memory.release();
+}
+
 Memory* MapInfo::CreateMemory(pid_t pid) {
   if (end <= start) {
     return nullptr;
@@ -40,33 +89,13 @@
     if (flags & MAPS_FLAGS_DEVICE_MAP) {
       return nullptr;
     }
-
-    std::unique_ptr<MemoryFileAtOffset> file_memory(new MemoryFileAtOffset);
-    uint64_t map_size;
-    if (offset != 0) {
-      // Only map in a piece of the file.
-      map_size = end - start;
-    } else {
-      map_size = UINT64_MAX;
-    }
-    if (file_memory->Init(name, offset, map_size)) {
-      // It's possible that a non-zero offset might not be pointing to
-      // valid elf data. Check if this is a valid elf, and if not assume
-      // that this was meant to incorporate the entire file.
-      if (offset != 0 && !Elf::IsValidElf(file_memory.get())) {
-        // Don't bother checking the validity that will happen on the elf init.
-        if (file_memory->Init(name, 0)) {
-          elf_offset = offset;
-          return file_memory.release();
-        }
-        // Fall through if the init fails.
-      } else {
-        return file_memory.release();
-      }
+    Memory* memory = GetFileMemory();
+    if (memory != nullptr) {
+      return memory;
     }
   }
 
-  Memory* memory = nullptr;
+  Memory* memory;
   if (pid == getpid()) {
     memory = new MemoryLocal();
   } else {
diff --git a/libunwindstack/include/unwindstack/Elf.h b/libunwindstack/include/unwindstack/Elf.h
index d89a746..4e7eb34 100644
--- a/libunwindstack/include/unwindstack/Elf.h
+++ b/libunwindstack/include/unwindstack/Elf.h
@@ -70,6 +70,8 @@
 
   static bool IsValidElf(Memory* memory);
 
+  static void GetInfo(Memory* memory, bool* valid, uint64_t* size);
+
  protected:
   bool valid_ = false;
   std::unique_ptr<ElfInterface> interface_;
diff --git a/libunwindstack/include/unwindstack/ElfInterface.h b/libunwindstack/include/unwindstack/ElfInterface.h
index 5cac0d3..142a625 100644
--- a/libunwindstack/include/unwindstack/ElfInterface.h
+++ b/libunwindstack/include/unwindstack/ElfInterface.h
@@ -102,6 +102,9 @@
 
   virtual bool HandleType(uint64_t, uint32_t) { return false; }
 
+  template <typename EhdrType>
+  static void GetMaxSizeWithTemplate(Memory* memory, uint64_t* size);
+
   Memory* memory_;
   std::unordered_map<uint64_t, LoadInfo> pt_loads_;
   uint64_t load_bias_ = 0;
@@ -146,6 +149,10 @@
   bool GetFunctionName(uint64_t addr, std::string* name, uint64_t* func_offset) override {
     return ElfInterface::GetFunctionNameWithTemplate<Elf32_Sym>(addr, name, func_offset);
   }
+
+  static void GetMaxSize(Memory* memory, uint64_t* size) {
+    GetMaxSizeWithTemplate<Elf32_Ehdr>(memory, size);
+  }
 };
 
 class ElfInterface64 : public ElfInterface {
@@ -166,6 +173,10 @@
   bool GetFunctionName(uint64_t addr, std::string* name, uint64_t* func_offset) override {
     return ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(addr, name, func_offset);
   }
+
+  static void GetMaxSize(Memory* memory, uint64_t* size) {
+    GetMaxSizeWithTemplate<Elf64_Ehdr>(memory, size);
+  }
 };
 
 }  // namespace unwindstack
diff --git a/libunwindstack/include/unwindstack/MapInfo.h b/libunwindstack/include/unwindstack/MapInfo.h
index 1854767..b8ba925 100644
--- a/libunwindstack/include/unwindstack/MapInfo.h
+++ b/libunwindstack/include/unwindstack/MapInfo.h
@@ -40,6 +40,7 @@
   // instead of a portion of the file.
   uint64_t elf_offset;
 
+  Memory* GetFileMemory();
   Memory* CreateMemory(pid_t pid);
   // This function guarantees it will never return nullptr.
   Elf* GetElf(pid_t pid, bool init_gnu_debugdata = false);
diff --git a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
index 9e45e78..2aab9c6 100644
--- a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
+++ b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
@@ -38,30 +38,50 @@
 
 class MapInfoCreateMemoryTest : public ::testing::Test {
  protected:
+  template <typename Ehdr, typename Shdr>
+  static void InitElf(int fd, uint64_t file_offset, uint64_t sh_offset, uint8_t class_type) {
+    std::vector<uint8_t> buffer(20000);
+    memset(buffer.data(), 0, buffer.size());
+
+    Ehdr ehdr;
+    memset(&ehdr, 0, sizeof(ehdr));
+    memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
+    ehdr.e_ident[EI_CLASS] = class_type;
+    ehdr.e_shoff = sh_offset;
+    ehdr.e_shentsize = sizeof(Shdr) + 100;
+    ehdr.e_shnum = 4;
+    memcpy(&buffer[file_offset], &ehdr, sizeof(ehdr));
+
+    ASSERT_TRUE(android::base::WriteFully(fd, buffer.data(), buffer.size()));
+  }
+
   static void SetUpTestCase() {
     std::vector<uint8_t> buffer(1024);
+    memset(buffer.data(), 0, buffer.size());
     memcpy(buffer.data(), ELFMAG, SELFMAG);
-    for (size_t i = SELFMAG; i < buffer.size(); i++) {
-      buffer[i] = i / 256 + 1;
-    }
+    buffer[EI_CLASS] = ELFCLASS32;
     ASSERT_TRUE(android::base::WriteFully(elf_.fd, buffer.data(), buffer.size()));
 
-    for (size_t i = 0; i < 0x100; i++) {
-      buffer[i] = i / 256 + 1;
-    }
+    memset(buffer.data(), 0, buffer.size());
     memcpy(&buffer[0x100], ELFMAG, SELFMAG);
-    for (size_t i = 0x100 + SELFMAG; i < buffer.size(); i++) {
-      buffer[i] = i / 256 + 1;
-    }
+    buffer[0x100 + EI_CLASS] = ELFCLASS64;
     ASSERT_TRUE(android::base::WriteFully(elf_at_100_.fd, buffer.data(), buffer.size()));
+
+    InitElf<Elf32_Ehdr, Elf32_Shdr>(elf32_at_map_.fd, 0x1000, 0x2000, ELFCLASS32);
+    InitElf<Elf64_Ehdr, Elf64_Shdr>(elf64_at_map_.fd, 0x2000, 0x3000, ELFCLASS64);
   }
 
   static TemporaryFile elf_;
 
   static TemporaryFile elf_at_100_;
+
+  static TemporaryFile elf32_at_map_;
+  static TemporaryFile elf64_at_map_;
 };
 TemporaryFile MapInfoCreateMemoryTest::elf_;
 TemporaryFile MapInfoCreateMemoryTest::elf_at_100_;
+TemporaryFile MapInfoCreateMemoryTest::elf32_at_map_;
+TemporaryFile MapInfoCreateMemoryTest::elf64_at_map_;
 
 TEST_F(MapInfoCreateMemoryTest, end_le_start) {
   MapInfo info{.start = 0x100, .end = 0x100, .offset = 0, .name = elf_.path};
@@ -93,8 +113,9 @@
   std::vector<uint8_t> buffer(1024);
   ASSERT_TRUE(memory->Read(0, buffer.data(), 1024));
   ASSERT_TRUE(memcmp(buffer.data(), ELFMAG, SELFMAG) == 0);
-  for (size_t i = SELFMAG; i < buffer.size(); i++) {
-    ASSERT_EQ(i / 256 + 1, buffer[i]) << "Failed at byte " << i;
+  ASSERT_EQ(ELFCLASS32, buffer[EI_CLASS]);
+  for (size_t i = EI_CLASS + 1; i < buffer.size(); i++) {
+    ASSERT_EQ(0, buffer[i]) << "Failed at byte " << i;
   }
 
   ASSERT_FALSE(memory->Read(1024, buffer.data(), 1));
@@ -113,13 +134,50 @@
   std::vector<uint8_t> buffer(0x100);
   ASSERT_TRUE(memory->Read(0, buffer.data(), 0x100));
   ASSERT_TRUE(memcmp(buffer.data(), ELFMAG, SELFMAG) == 0);
-  for (size_t i = SELFMAG; i < buffer.size(); i++) {
-    ASSERT_EQ(2, buffer[i]) << "Failed at byte " << i;
+  ASSERT_EQ(ELFCLASS64, buffer[EI_CLASS]);
+  for (size_t i = EI_CLASS + 1; i < buffer.size(); i++) {
+    ASSERT_EQ(0, buffer[i]) << "Failed at byte " << i;
   }
 
   ASSERT_FALSE(memory->Read(0x100, buffer.data(), 1));
 }
 
+// Verify that if the offset is non-zero and there is an elf at that
+// offset, that only part of the file is used. Further verify that if the
+// embedded elf is bigger than the initial map, the new object is larger
+// than the original map size. Do this for a 32 bit elf and a 64 bit elf.
+TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_partial_file_whole_elf32) {
+  MapInfo info{.start = 0x5000, .end = 0x6000, .offset = 0x1000, .name = elf32_at_map_.path};
+
+  std::unique_ptr<Memory> memory(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() != nullptr);
+  ASSERT_EQ(0U, info.elf_offset);
+
+  // Verify the memory is a valid elf.
+  uint8_t e_ident[SELFMAG + 1];
+  ASSERT_TRUE(memory->Read(0, e_ident, SELFMAG));
+  ASSERT_EQ(0, memcmp(e_ident, ELFMAG, SELFMAG));
+
+  // Read past the end of what would normally be the size of the map.
+  ASSERT_TRUE(memory->Read(0x1000, e_ident, 1));
+}
+
+TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_partial_file_whole_elf64) {
+  MapInfo info{.start = 0x7000, .end = 0x8000, .offset = 0x2000, .name = elf64_at_map_.path};
+
+  std::unique_ptr<Memory> memory(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() != nullptr);
+  ASSERT_EQ(0U, info.elf_offset);
+
+  // Verify the memory is a valid elf.
+  uint8_t e_ident[SELFMAG + 1];
+  ASSERT_TRUE(memory->Read(0, e_ident, SELFMAG));
+  ASSERT_EQ(0, memcmp(e_ident, ELFMAG, SELFMAG));
+
+  // Read past the end of what would normally be the size of the map.
+  ASSERT_TRUE(memory->Read(0x1000, e_ident, 1));
+}
+
 // Verify that device file names will never result in Memory object creation.
 TEST_F(MapInfoCreateMemoryTest, check_device_maps) {
   // Set up some memory so that a valid local memory object would
diff --git a/libunwindstack/tools/unwind_symbols.cpp b/libunwindstack/tools/unwind_symbols.cpp
index b757c1e..dc9ae5a 100644
--- a/libunwindstack/tools/unwind_symbols.cpp
+++ b/libunwindstack/tools/unwind_symbols.cpp
@@ -28,8 +28,11 @@
 #include <unwindstack/Memory.h>
 
 int main(int argc, char** argv) {
-  if (argc != 2) {
-    printf("Need to pass the name of an elf file to the program.\n");
+  if (argc != 2 && argc != 3) {
+    printf("Usage: unwind_symbols <ELF_FILE> [<FUNC_ADDRESS>]\n");
+    printf("  Dump all function symbols in ELF_FILE. If FUNC_ADDRESS is\n");
+    printf("  specified, then get the function at that address.\n");
+    printf("  FUNC_ADDRESS must be a hex number.\n");
     return 1;
   }
 
@@ -43,6 +46,16 @@
     return 1;
   }
 
+  uint64_t func_addr;
+  if (argc == 3) {
+    char* name;
+    func_addr = strtoull(argv[2], &name, 16);
+    if (*name != '\0') {
+      printf("%s is not a hex number.\n", argv[2]);
+      return 1;
+    }
+  }
+
   // Send all log messages to stdout.
   unwindstack::log_to_stdout(true);
 
@@ -76,9 +89,24 @@
       return 1;
   }
 
-  // This is a crude way to get the symbols in order.
   std::string name;
   uint64_t load_bias = elf.interface()->load_bias();
+  if (argc == 3) {
+    std::string cur_name;
+    uint64_t func_offset;
+    if (!elf.GetFunctionName(func_addr, &cur_name, &func_offset)) {
+      printf("No known function at 0x%" PRIx64 "\n", func_addr);
+      return 1;
+    }
+    printf("<0x%" PRIx64 ">", func_addr - func_offset);
+    if (func_offset != 0) {
+      printf("+%" PRId64, func_offset);
+    }
+    printf(": %s\n", cur_name.c_str());
+    return 0;
+  }
+
+  // This is a crude way to get the symbols in order.
   for (const auto& entry : elf.interface()->pt_loads()) {
     uint64_t start = entry.second.offset + load_bias;
     uint64_t end = entry.second.table_size + load_bias;
diff --git a/rootdir/init.usb.rc b/rootdir/init.usb.rc
index 915d159..3168f40 100644
--- a/rootdir/init.usb.rc
+++ b/rootdir/init.usb.rc
@@ -12,7 +12,7 @@
     mkdir /data/adb 0700 root root
 
 # adbd is controlled via property triggers in init.<platform>.usb.rc
-service adbd /sbin/adbd --root_seclabel=u:r:su:s0
+service adbd /system/bin/adbd --root_seclabel=u:r:su:s0
     class core
     socket adbd stream 660 system system
     disabled