Merge "Set up configfs" into nyc-dev
diff --git a/bootstat/Android.mk b/bootstat/Android.mk
index c6349c1..3d02752 100644
--- a/bootstat/Android.mk
+++ b/bootstat/Android.mk
@@ -20,32 +20,33 @@
 
 bootstat_lib_src_files := \
         boot_event_record_store.cpp \
-        event_log_list_builder.cpp
+        event_log_list_builder.cpp \
+        uptime_parser.cpp \
 
 bootstat_src_files := \
-        bootstat.cpp
+        bootstat.cpp \
 
 bootstat_test_src_files := \
         boot_event_record_store_test.cpp \
         event_log_list_builder_test.cpp \
-        testrunner.cpp
+        testrunner.cpp \
 
 bootstat_shared_libs := \
         libbase \
         libcutils \
-        liblog
+        liblog \
 
 bootstat_cflags := \
         -Wall \
         -Wextra \
-        -Werror
+        -Werror \
 
 bootstat_cppflags := \
-        -Wno-non-virtual-dtor
+        -Wno-non-virtual-dtor \
 
 bootstat_debug_cflags := \
         $(bootstat_cflags) \
-        -UNDEBUG
+        -UNDEBUG \
 
 # 524291 corresponds to sysui_histogram, from
 # frameworks/base/core/java/com/android/internal/logging/EventLogTags.logtags
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 8282b40..40254f8 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -24,6 +24,7 @@
 #include <utility>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include "uptime_parser.h"
 
 namespace {
 
@@ -51,14 +52,7 @@
 }
 
 void BootEventRecordStore::AddBootEvent(const std::string& event) {
-  std::string uptime_str;
-  if (!android::base::ReadFileToString("/proc/uptime", &uptime_str)) {
-    LOG(ERROR) << "Failed to read /proc/uptime";
-  }
-
-  // Cast intentionally rounds down.
-  int32_t uptime = static_cast<int32_t>(strtod(uptime_str.c_str(), NULL));
-  AddBootEventWithValue(event, uptime);
+  AddBootEventWithValue(event, bootstat::ParseUptime());
 }
 
 // The implementation of AddBootEventValue makes use of the mtime file
diff --git a/bootstat/boot_event_record_store_test.cpp b/bootstat/boot_event_record_store_test.cpp
index 0d7bbb0..343f9d0 100644
--- a/bootstat/boot_event_record_store_test.cpp
+++ b/bootstat/boot_event_record_store_test.cpp
@@ -25,6 +25,7 @@
 #include <android-base/test_utils.h>
 #include <gtest/gtest.h>
 #include <gmock/gmock.h>
+#include "uptime_parser.h"
 
 using testing::UnorderedElementsAreArray;
 
@@ -38,17 +39,6 @@
   return (abs(a - b) <= FUZZ_SECONDS);
 }
 
-// Returns the uptime as read from /proc/uptime, rounded down to an integer.
-int32_t ReadUptime() {
-  std::string uptime_str;
-  if (!android::base::ReadFileToString("/proc/uptime", &uptime_str)) {
-    return -1;
-  }
-
-  // Cast to int to round down.
-  return static_cast<int32_t>(strtod(uptime_str.c_str(), NULL));
-}
-
 // Recursively deletes the directory at |path|.
 void DeleteDirectory(const std::string& path) {
   typedef std::unique_ptr<DIR, decltype(&closedir)> ScopedDIR;
@@ -110,7 +100,7 @@
   BootEventRecordStore store;
   store.SetStorePath(GetStorePathForTesting());
 
-  int32_t uptime = ReadUptime();
+  time_t uptime = bootstat::ParseUptime();
   ASSERT_NE(-1, uptime);
 
   store.AddBootEvent("cenozoic");
@@ -125,7 +115,7 @@
   BootEventRecordStore store;
   store.SetStorePath(GetStorePathForTesting());
 
-  int32_t uptime = ReadUptime();
+  time_t uptime = bootstat::ParseUptime();
   ASSERT_NE(-1, uptime);
 
   store.AddBootEvent("cretaceous");
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index 1460803..4c8c8b6 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -32,6 +32,7 @@
 #include <log/log.h>
 #include "boot_event_record_store.h"
 #include "event_log_list_builder.h"
+#include "uptime_parser.h"
 
 namespace {
 
@@ -150,6 +151,37 @@
   return kUnknownBootReason;
 }
 
+// Records several metrics related to the time it takes to boot the device,
+// including disambiguating boot time on encrypted or non-encrypted devices.
+void RecordBootComplete() {
+  BootEventRecordStore boot_event_store;
+  time_t uptime = bootstat::ParseUptime();
+
+  BootEventRecordStore::BootEventRecord record;
+
+  // post_decrypt_time_elapsed is only logged on encrypted devices.
+  if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
+    // Log the amount of time elapsed until the device is decrypted, which
+    // includes the variable amount of time the user takes to enter the
+    // decryption password.
+    boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime);
+
+    // Subtract the decryption time to normalize the boot cycle timing.
+    time_t boot_complete = uptime - record.second;
+    boot_event_store.AddBootEventWithValue("boot_complete_post_decrypt",
+                                           boot_complete);
+
+
+  } else {
+    boot_event_store.AddBootEventWithValue("boot_complete_no_encryption",
+                                           uptime);
+  }
+
+  // Record the total time from device startup to boot complete, regardless of
+  // encryption state.
+  boot_event_store.AddBootEventWithValue("boot_complete", uptime);
+}
+
 // Records the boot_reason metric by querying the ro.boot.bootreason system
 // property.
 void RecordBootReason() {
@@ -205,6 +237,7 @@
   LOG(INFO) << "Service started: " << cmd_line;
 
   int option_index = 0;
+  static const char boot_complete_str[] = "record_boot_complete";
   static const char boot_reason_str[] = "record_boot_reason";
   static const char factory_reset_str[] = "record_time_since_factory_reset";
   static const struct option long_options[] = {
@@ -212,6 +245,7 @@
     { "log",             no_argument,       NULL,   'l' },
     { "print",           no_argument,       NULL,   'p' },
     { "record",          required_argument, NULL,   'r' },
+    { boot_complete_str, no_argument,       NULL,   0 },
     { boot_reason_str,   no_argument,       NULL,   0 },
     { factory_reset_str, no_argument,       NULL,   0 },
     { NULL,              0,                 NULL,   0 }
@@ -223,7 +257,9 @@
       // This case handles long options which have no single-character mapping.
       case 0: {
         const std::string option_name = long_options[option_index].name;
-        if (option_name == boot_reason_str) {
+        if (option_name == boot_complete_str) {
+          RecordBootComplete();
+        } else if (option_name == boot_reason_str) {
           RecordBootReason();
         } else if (option_name == factory_reset_str) {
           RecordFactoryReset();
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index 3c20fc8..ba8f81c 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -3,6 +3,14 @@
 on post-fs-data
     mkdir /data/misc/bootstat 0700 root root
 
+# Record the time at which the user has successfully entered the pin to decrypt
+# the device, /data is decrypted, and the system is entering the main boot phase.
+#
+# post-fs-data: /data is writable
+# property:init.svc.bootanim=running: The boot animation is running
+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.
@@ -10,8 +18,8 @@
 # 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 timing event.
-    exec - root root -- /system/bin/bootstat -r boot_complete
+    # Record boot_complete and related stats (decryption, etc).
+    exec - root root -- /system/bin/bootstat --record_boot_complete
 
     # Record the boot reason.
     exec - root root -- /system/bin/bootstat --record_boot_reason
diff --git a/bootstat/uptime_parser.cpp b/bootstat/uptime_parser.cpp
new file mode 100644
index 0000000..7c2034c
--- /dev/null
+++ b/bootstat/uptime_parser.cpp
@@ -0,0 +1,38 @@
+/*
+ * 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 "uptime_parser.h"
+
+#include <time.h>
+#include <cstdlib>
+#include <string>
+#include <android-base/file.h>
+#include <android-base/logging.h>
+
+namespace bootstat {
+
+time_t ParseUptime() {
+  std::string uptime_str;
+  if (!android::base::ReadFileToString("/proc/uptime", &uptime_str)) {
+    PLOG(ERROR) << "Failed to read /proc/uptime";
+    return -1;
+  }
+
+  // Cast intentionally rounds down.
+  return static_cast<time_t>(strtod(uptime_str.c_str(), NULL));
+}
+
+}  // namespace bootstat
\ No newline at end of file
diff --git a/bootstat/uptime_parser.h b/bootstat/uptime_parser.h
new file mode 100644
index 0000000..756ae9b
--- /dev/null
+++ b/bootstat/uptime_parser.h
@@ -0,0 +1,29 @@
+/*
+ * 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 UPTIME_PARSER_H_
+#define UPTIME_PARSER_H_
+
+#include <time.h>
+
+namespace bootstat {
+
+// Returns the number of seconds the system has been on since reboot.
+time_t ParseUptime();
+
+}  // namespace bootstat
+
+#endif  // UPTIME_PARSER_H_
\ No newline at end of file
diff --git a/debuggerd/Android.mk b/debuggerd/Android.mk
index 9e4f1f7..6469db4 100644
--- a/debuggerd/Android.mk
+++ b/debuggerd/Android.mk
@@ -15,6 +15,7 @@
     debuggerd.cpp \
     elf_utils.cpp \
     getevent.cpp \
+    signal_sender.cpp \
     tombstone.cpp \
     utility.cpp \
 
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 86d7c14..71c1e83 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -15,21 +15,20 @@
  */
 
 #include <dirent.h>
+#include <elf.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <pthread.h>
 #include <signal.h>
 #include <stdarg.h>
 #include <stdio.h>
-#include <sys/types.h>
-#include <time.h>
-
-#include <elf.h>
 #include <sys/poll.h>
 #include <sys/prctl.h>
 #include <sys/ptrace.h>
 #include <sys/stat.h>
+#include <sys/types.h>
 #include <sys/wait.h>
+#include <time.h>
 
 #include <set>
 
@@ -48,6 +47,7 @@
 
 #include "backtrace.h"
 #include "getevent.h"
+#include "signal_sender.h"
 #include "tombstone.h"
 #include "utility.h"
 
@@ -374,7 +374,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 std::set<pid_t>& siblings,
+                         int* crash_signal) {
   if (TEMP_FAILURE_RETRY(write(fd, "\0", 1)) != 1) {
     ALOGE("debuggerd: failed to respond to client: %s\n", strerror(errno));
     return false;
@@ -420,7 +421,8 @@
         // the non-signaled threads stop moving.  Without
         // this we get a lot of "ptrace detach failed:
         // No such process".
-        kill(request.pid, SIGSTOP);
+        *crash_signal = signal;
+        send_signal(request.pid, 0, SIGSTOP);
         engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings, signal,
                           request.original_si_code, request.abort_msg_address);
         break;
@@ -449,99 +451,7 @@
   return true;
 }
 
-// Fork a process that listens for signals to send, or 0, to exit.
-static bool fork_signal_sender(int* out_fd, pid_t* sender_pid, pid_t target_pid) {
-  int sfd[2];
-  if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sfd) != 0) {
-    ALOGE("debuggerd: failed to create socketpair for signal sender: %s", strerror(errno));
-    return false;
-  }
-
-  pid_t fork_pid = fork();
-  if (fork_pid == -1) {
-    ALOGE("debuggerd: failed to initialize signal sender: fork failed: %s", strerror(errno));
-    return false;
-  } else if (fork_pid == 0) {
-    close(sfd[1]);
-
-    while (true) {
-      int signal;
-      int rc = TEMP_FAILURE_RETRY(read(sfd[0], &signal, sizeof(signal)));
-      if (rc < 0) {
-        ALOGE("debuggerd: signal sender failed to read from socket");
-        kill(target_pid, SIGKILL);
-        exit(1);
-      } else if (rc != sizeof(signal)) {
-        ALOGE("debuggerd: signal sender read unexpected number of bytes: %d", rc);
-        kill(target_pid, SIGKILL);
-        exit(1);
-      }
-
-      // Report success after sending a signal, or before exiting.
-      int err = 0;
-      if (signal != 0) {
-        if (kill(target_pid, signal) != 0) {
-          err = errno;
-        }
-      }
-
-      if (TEMP_FAILURE_RETRY(write(sfd[0], &err, sizeof(err))) < 0) {
-        ALOGE("debuggerd: signal sender failed to write: %s", strerror(errno));
-        kill(target_pid, SIGKILL);
-        exit(1);
-      }
-
-      if (signal == 0) {
-        exit(0);
-      }
-    }
-  } else {
-    close(sfd[0]);
-    *out_fd = sfd[1];
-    *sender_pid = fork_pid;
-    return true;
-  }
-}
-
-static void handle_request(int fd) {
-  ALOGV("handle_request(%d)\n", fd);
-
-  ScopedFd closer(fd);
-  debugger_request_t request;
-  memset(&request, 0, sizeof(request));
-  int status = read_request(fd, &request);
-  if (status != 0) {
-    return;
-  }
-
-  ALOGV("BOOM: pid=%d uid=%d gid=%d tid=%d\n", request.pid, request.uid, request.gid, request.tid);
-
-#if defined(__LP64__)
-  // On 64 bit systems, requests to dump 32 bit and 64 bit tids come
-  // to the 64 bit debuggerd. If the process is a 32 bit executable,
-  // redirect the request to the 32 bit debuggerd.
-  if (is32bit(request.tid)) {
-    // Only dump backtrace and dump tombstone requests can be redirected.
-    if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE ||
-        request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
-      redirect_to_32(fd, &request);
-    } else {
-      ALOGE("debuggerd: Not allowed to redirect action %d to 32 bit debuggerd\n", request.action);
-    }
-    return;
-  }
-#endif
-
-  // Fork a child to handle the rest of the request.
-  pid_t fork_pid = fork();
-  if (fork_pid == -1) {
-    ALOGE("debuggerd: failed to fork: %s\n", strerror(errno));
-    return;
-  } else if (fork_pid != 0) {
-    waitpid(fork_pid, nullptr, 0);
-    return;
-  }
-
+static void worker_process(int fd, debugger_request_t& request) {
   // Open the tombstone file if we need it.
   std::string tombstone_path;
   int tombstone_fd = -1;
@@ -583,15 +493,6 @@
   // 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);
-  int signal_fd = -1;
-  pid_t signal_pid = 0;
-
-  // Fork a process that stays root, and listens on a pipe to pause and resume the target.
-  if (!fork_signal_sender(&signal_fd, &signal_pid, request.pid)) {
-    ALOGE("debuggerd: failed to fork signal sender");
-    exit(1);
-  }
-
   if (attach_gdb) {
     // Open all of the input devices we need to listen for VOLUMEDOWN before dropping privileges.
     if (init_getevent() != 0) {
@@ -601,21 +502,6 @@
 
   }
 
-  auto send_signal = [=](int signal) {
-    int error;
-    if (TEMP_FAILURE_RETRY(write(signal_fd, &signal, sizeof(signal))) < 0) {
-      ALOGE("debuggerd: failed to notify signal process: %s", strerror(errno));
-      return false;
-    } else if (TEMP_FAILURE_RETRY(read(signal_fd, &error, sizeof(error))) < 0) {
-      ALOGE("debuggerd: failed to read response from signal process: %s", strerror(errno));
-      return false;
-    } else if (error != 0) {
-      errno = error;
-      return false;
-    }
-    return true;
-  };
-
   std::set<pid_t> siblings;
   if (!attach_gdb) {
     ptrace_siblings(request.pid, request.tid, siblings);
@@ -632,7 +518,8 @@
     _exit(1);
   }
 
-  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings);
+  int crash_signal = SIGKILL;
+  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings, &crash_signal);
   if (succeeded) {
     if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
       if (!tombstone_path.empty()) {
@@ -643,7 +530,7 @@
 
   if (attach_gdb) {
     // Tell the signal process to send SIGSTOP to the target.
-    if (!send_signal(SIGSTOP)) {
+    if (!send_signal(request.pid, 0, SIGSTOP)) {
       ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno));
       attach_gdb = false;
     }
@@ -659,9 +546,7 @@
 
   // Send the signal back to the process if it crashed and we're not waiting for gdb.
   if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) {
-    // TODO: Send the same signal that triggered the dump, so that shell says "Segmentation fault"
-    //       instead of "Killed"?
-    if (!send_signal(SIGKILL)) {
+    if (!send_signal(request.pid, request.tid, crash_signal)) {
       ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno));
     }
   }
@@ -671,21 +556,121 @@
     wait_for_user_action(request);
 
     // Tell the signal process to send SIGCONT to the target.
-    if (!send_signal(SIGCONT)) {
+    if (!send_signal(request.pid, 0, SIGCONT)) {
       ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno));
     }
 
     uninit_getevent();
   }
 
-  if (!send_signal(0)) {
-    ALOGE("debuggerd: failed to notify signal sender to finish");
-    kill(signal_pid, SIGKILL);
-  }
-  waitpid(signal_pid, nullptr, 0);
   exit(!succeeded);
 }
 
+static void monitor_worker_process(int child_pid, const debugger_request_t& request) {
+  struct timespec timeout = {.tv_sec = 10, .tv_nsec = 0 };
+
+  sigset_t signal_set;
+  sigemptyset(&signal_set);
+  sigaddset(&signal_set, SIGCHLD);
+
+  bool kill_worker = false;
+  bool kill_target = false;
+  bool kill_self = false;
+
+  int status;
+  siginfo_t siginfo;
+  int signal = TEMP_FAILURE_RETRY(sigtimedwait(&signal_set, &siginfo, &timeout));
+  if (signal == SIGCHLD) {
+    pid_t rc = waitpid(0, &status, WNOHANG | WUNTRACED);
+    if (rc != child_pid) {
+      ALOGE("debuggerd: waitpid returned unexpected pid (%d), committing murder-suicide", rc);
+      kill_worker = true;
+      kill_target = true;
+      kill_self = true;
+    }
+
+    if (WIFSIGNALED(status)) {
+      ALOGE("debuggerd: worker process %d terminated due to signal %d", child_pid, WTERMSIG(status));
+      kill_worker = false;
+      kill_target = true;
+    } else if (WIFSTOPPED(status)) {
+      ALOGE("debuggerd: worker process %d stopped due to signal %d", child_pid, WSTOPSIG(status));
+      kill_worker = true;
+      kill_target = true;
+    }
+  } else {
+    ALOGE("debuggerd: worker process %d timed out", child_pid);
+    kill_worker = true;
+    kill_target = true;
+  }
+
+  if (kill_worker) {
+    // Something bad happened, kill the worker.
+    if (kill(child_pid, SIGKILL) != 0) {
+      ALOGE("debuggerd: failed to kill worker process %d: %s", child_pid, strerror(errno));
+    } else {
+      waitpid(child_pid, &status, 0);
+    }
+  }
+
+  if (kill_target) {
+    // Resume or kill the target, depending on what the initial request was.
+    if (request.action == DEBUGGER_ACTION_CRASH) {
+      ALOGE("debuggerd: killing target %d", request.pid);
+      kill(request.pid, SIGKILL);
+    } else {
+      ALOGE("debuggerd: resuming target %d", request.pid);
+      kill(request.pid, SIGCONT);
+    }
+  }
+
+  if (kill_self) {
+    stop_signal_sender();
+    _exit(1);
+  }
+}
+
+static void handle_request(int fd) {
+  ALOGV("handle_request(%d)\n", fd);
+
+  ScopedFd closer(fd);
+  debugger_request_t request;
+  memset(&request, 0, sizeof(request));
+  int status = read_request(fd, &request);
+  if (status != 0) {
+    return;
+  }
+
+  ALOGW("debuggerd: handling request: pid=%d uid=%d gid=%d tid=%d\n", request.pid, request.uid,
+        request.gid, request.tid);
+
+#if defined(__LP64__)
+  // On 64 bit systems, requests to dump 32 bit and 64 bit tids come
+  // to the 64 bit debuggerd. If the process is a 32 bit executable,
+  // redirect the request to the 32 bit debuggerd.
+  if (is32bit(request.tid)) {
+    // Only dump backtrace and dump tombstone requests can be redirected.
+    if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE ||
+        request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
+      redirect_to_32(fd, &request);
+    } else {
+      ALOGE("debuggerd: Not allowed to redirect action %d to 32 bit debuggerd\n", request.action);
+    }
+    return;
+  }
+#endif
+
+  // Fork a child to handle the rest of the request.
+  pid_t fork_pid = fork();
+  if (fork_pid == -1) {
+    ALOGE("debuggerd: failed to fork: %s\n", strerror(errno));
+  } else if (fork_pid == 0) {
+    worker_process(fd, request);
+  } else {
+    monitor_worker_process(fork_pid, request);
+  }
+}
+
 static int do_server() {
   // debuggerd crashes can't be reported to debuggerd.
   // Reset all of the crash handlers.
@@ -702,24 +687,21 @@
   // Ignore failed writes to closed sockets
   signal(SIGPIPE, SIG_IGN);
 
-  int logsocket = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_DGRAM);
-  if (logsocket < 0) {
-    logsocket = -1;
-  } else {
-    fcntl(logsocket, F_SETFD, FD_CLOEXEC);
-  }
+  // Block SIGCHLD so we can sigtimedwait for it.
+  sigset_t sigchld;
+  sigemptyset(&sigchld);
+  sigaddset(&sigchld, SIGCHLD);
+  sigprocmask(SIG_SETMASK, &sigchld, nullptr);
 
-  struct sigaction act;
-  act.sa_handler = SIG_DFL;
-  sigemptyset(&act.sa_mask);
-  sigaddset(&act.sa_mask,SIGCHLD);
-  act.sa_flags = SA_NOCLDWAIT;
-  sigaction(SIGCHLD, &act, 0);
+  int s = socket_local_server(SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
+                              SOCK_STREAM | SOCK_CLOEXEC);
+  if (s == -1) return 1;
 
-  int s = socket_local_server(SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
-  if (s < 0)
+  // Fork a process that stays root, and listens on a pipe to pause and resume the target.
+  if (!start_signal_sender()) {
+    ALOGE("debuggerd: failed to fork signal sender");
     return 1;
-  fcntl(s, F_SETFD, FD_CLOEXEC);
+  }
 
   ALOGI("debuggerd: starting\n");
 
@@ -729,14 +711,12 @@
     socklen_t alen = sizeof(ss);
 
     ALOGV("waiting for connection\n");
-    int fd = accept(s, addrp, &alen);
-    if (fd < 0) {
-      ALOGV("accept failed: %s\n", strerror(errno));
+    int fd = accept4(s, addrp, &alen, SOCK_CLOEXEC);
+    if (fd == -1) {
+      ALOGE("accept failed: %s\n", strerror(errno));
       continue;
     }
 
-    fcntl(fd, F_SETFD, FD_CLOEXEC);
-
     handle_request(fd);
   }
   return 0;
diff --git a/debuggerd/signal_sender.cpp b/debuggerd/signal_sender.cpp
new file mode 100644
index 0000000..1cfb704
--- /dev/null
+++ b/debuggerd/signal_sender.cpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <log/logger.h>
+
+#include "signal_sender.h"
+
+static int signal_fd = -1;
+static pid_t signal_pid;
+struct signal_message {
+  pid_t pid;
+  pid_t tid;
+  int signal;
+};
+
+// Fork a process to send signals for the worker processes to use after they've dropped privileges.
+bool start_signal_sender() {
+  if (signal_pid != 0) {
+    ALOGE("debuggerd: attempted to start signal sender multiple times");
+    return false;
+  }
+
+  int sfd[2];
+  if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sfd) != 0) {
+    ALOGE("debuggerd: failed to create socketpair for signal sender: %s", strerror(errno));
+    return false;
+  }
+
+  pid_t parent = getpid();
+  pid_t fork_pid = fork();
+  if (fork_pid == -1) {
+    ALOGE("debuggerd: failed to initialize signal sender: fork failed: %s", strerror(errno));
+    return false;
+  } else if (fork_pid == 0) {
+    close(sfd[1]);
+
+    while (true) {
+      signal_message msg;
+      int rc = TEMP_FAILURE_RETRY(read(sfd[0], &msg, sizeof(msg)));
+      if (rc < 0) {
+        ALOGE("debuggerd: signal sender failed to read from socket");
+        break;
+      } else if (rc != sizeof(msg)) {
+        ALOGE("debuggerd: signal sender read unexpected number of bytes: %d", rc);
+        break;
+      }
+
+      // Report success after sending a signal
+      int err = 0;
+      if (msg.tid > 0) {
+        if (syscall(SYS_tgkill, msg.pid, msg.tid, msg.signal) != 0) {
+          err = errno;
+        }
+      } else {
+        if (kill(msg.pid, msg.signal) != 0) {
+          err = errno;
+        }
+      }
+
+      if (TEMP_FAILURE_RETRY(write(sfd[0], &err, sizeof(err))) < 0) {
+        ALOGE("debuggerd: signal sender failed to write: %s", strerror(errno));
+      }
+    }
+
+    // Our parent proably died, but if not, kill them.
+    if (getppid() == parent) {
+      kill(parent, SIGKILL);
+    }
+    _exit(1);
+  } else {
+    close(sfd[0]);
+    signal_fd = sfd[1];
+    signal_pid = fork_pid;
+    return true;
+  }
+}
+
+bool stop_signal_sender() {
+  if (signal_pid <= 0) {
+    return false;
+  }
+
+  if (kill(signal_pid, SIGKILL) != 0) {
+    ALOGE("debuggerd: failed to kill signal sender: %s", strerror(errno));
+    return false;
+  }
+
+  close(signal_fd);
+  signal_fd = -1;
+
+  int status;
+  waitpid(signal_pid, &status, 0);
+  signal_pid = 0;
+
+  return true;
+}
+
+bool send_signal(pid_t pid, pid_t tid, int signal) {
+  if (signal_fd == -1) {
+    ALOGE("debuggerd: attempted to send signal before signal sender was started");
+    errno = EHOSTUNREACH;
+    return false;
+  }
+
+  signal_message msg = {.pid = pid, .tid = tid, .signal = signal };
+  if (TEMP_FAILURE_RETRY(write(signal_fd, &msg, sizeof(msg))) < 0) {
+    ALOGE("debuggerd: failed to send message to signal sender: %s", strerror(errno));
+    errno = EHOSTUNREACH;
+    return false;
+  }
+
+  int response;
+  ssize_t rc = TEMP_FAILURE_RETRY(read(signal_fd, &response, sizeof(response)));
+  if (rc == 0) {
+    ALOGE("debuggerd: received EOF from signal sender");
+    errno = EHOSTUNREACH;
+    return false;
+  } else if (rc < 0) {
+    ALOGE("debuggerd: failed to receive response from signal sender: %s", strerror(errno));
+    errno = EHOSTUNREACH;
+    return false;
+  }
+
+  if (response == 0) {
+    return true;
+  }
+
+  errno = response;
+  return false;
+}
diff --git a/debuggerd/signal_sender.h b/debuggerd/signal_sender.h
new file mode 100644
index 0000000..0443272
--- /dev/null
+++ b/debuggerd/signal_sender.h
@@ -0,0 +1,30 @@
+/*
+ * 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_SIGNAL_SENDER_H
+#define _DEBUGGERD_SIGNAL_SENDER_H
+
+#include <sys/types.h>
+
+bool start_signal_sender();
+bool stop_signal_sender();
+
+// Sends a signal to a target process or thread.
+// If tid is greater than zero, this performs tgkill(pid, tid, signal).
+// Otherwise, it performs kill(pid, signal).
+bool send_signal(pid_t pid, pid_t tid, int signal);
+
+#endif
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index ecd3b04..af3a3b4 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -16,6 +16,7 @@
 
 #include <fcntl.h>
 #include <inttypes.h>
+#include <semaphore.h>
 #include <signal.h>
 #include <string.h>
 #include <sys/types.h>
@@ -470,9 +471,15 @@
 }
 
 static unsigned signaled;
-log_time signal_time;
+static log_time signal_time;
 
-static void caught_blocking(int /*signum*/)
+/*
+ *  Strictly, we are not allowed to log messages in a signal context, but we
+ * do make an effort to keep the failure surface minimized, and this in-effect
+ * should catch any regressions in that effort. The odds of a logged message
+ * in a signal handler causing a lockup problem should be _very_ small.
+ */
+static void caught_blocking_signal(int /*signum*/)
 {
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
@@ -522,7 +529,7 @@
     }
 }
 
-TEST(liblog, android_logger_list_read__cpu) {
+TEST(liblog, android_logger_list_read__cpu_signal) {
     struct logger_list *logger_list;
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
@@ -545,7 +552,7 @@
 
     memset(&signal_time, 0, sizeof(signal_time));
 
-    signal(SIGALRM, caught_blocking);
+    signal(SIGALRM, caught_blocking_signal);
     alarm(alarm_time);
 
     signaled = 0;
@@ -590,7 +597,158 @@
     alarm(0);
     signal(SIGALRM, SIG_DFL);
 
-    EXPECT_LT(1, count);
+    EXPECT_LE(1, count);
+
+    EXPECT_EQ(1, signals);
+
+    android_logger_list_close(logger_list);
+
+    unsigned long long uticks_end;
+    unsigned long long sticks_end;
+    get_ticks(&uticks_end, &sticks_end);
+
+    // Less than 1% in either user or system time, or both
+    const unsigned long long one_percent_ticks = alarm_time;
+    unsigned long long user_ticks = uticks_end - uticks_start;
+    unsigned long long system_ticks = sticks_end - sticks_start;
+    EXPECT_GT(one_percent_ticks, user_ticks);
+    EXPECT_GT(one_percent_ticks, system_ticks);
+    EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
+}
+
+/*
+ *  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
+ * a thread; the signal handler should only unblock the thread.
+ */
+static sem_t thread_trigger;
+
+static void caught_blocking_thread(int /*signum*/)
+{
+    sem_post(&thread_trigger);
+}
+
+static void *running_thread(void *) {
+    unsigned long long v = 0xDEADBEAFA55A0000ULL;
+
+    v += getpid() & 0xFFFF;
+
+    struct timespec timeout;
+    clock_gettime(CLOCK_REALTIME, &timeout);
+    timeout.tv_sec += 55;
+    sem_timedwait(&thread_trigger, &timeout);
+
+    ++signaled;
+    if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
+        signal_time = log_time(CLOCK_MONOTONIC);
+        signal_time.tv_sec += 2;
+    }
+
+    LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
+
+    return NULL;
+}
+
+int start_thread()
+{
+    sem_init(&thread_trigger, 0, 0);
+
+    pthread_attr_t attr;
+    if (pthread_attr_init(&attr)) {
+        return -1;
+    }
+
+    struct sched_param param;
+
+    memset(&param, 0, sizeof(param));
+    pthread_attr_setschedparam(&attr, &param);
+    pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
+
+    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
+        pthread_attr_destroy(&attr);
+        return -1;
+    }
+
+    pthread_t thread;
+    if (pthread_create(&thread, &attr, running_thread, NULL)) {
+        pthread_attr_destroy(&attr);
+        return -1;
+    }
+
+    pthread_attr_destroy(&attr);
+    return 0;
+}
+
+TEST(liblog, android_logger_list_read__cpu_thread) {
+    struct logger_list *logger_list;
+    unsigned long long v = 0xDEADBEAFA55A0000ULL;
+
+    pid_t pid = getpid();
+
+    v += pid & 0xFFFF;
+
+    ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
+        LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));
+
+    int count = 0;
+
+    int signals = 0;
+
+    unsigned long long uticks_start;
+    unsigned long long sticks_start;
+    get_ticks(&uticks_start, &sticks_start);
+
+    const unsigned alarm_time = 10;
+
+    memset(&signal_time, 0, sizeof(signal_time));
+
+    signaled = 0;
+    EXPECT_EQ(0, start_thread());
+
+    signal(SIGALRM, caught_blocking_thread);
+    alarm(alarm_time);
+
+    do {
+        log_msg log_msg;
+        if (LOG_FAILURE_RETRY(android_logger_list_read(logger_list, &log_msg)) <= 0) {
+            break;
+        }
+
+        alarm(alarm_time);
+
+        ++count;
+
+        ASSERT_EQ(log_msg.entry.pid, pid);
+
+        if ((log_msg.entry.len != (4 + 1 + 8))
+         || (log_msg.id() != LOG_ID_EVENTS)) {
+            continue;
+        }
+
+        char *eventData = log_msg.msg();
+
+        if (eventData[4] != EVENT_TYPE_LONG) {
+            continue;
+        }
+
+        unsigned long long l = eventData[4 + 1 + 0] & 0xFF;
+        l |= (unsigned long long) (eventData[4 + 1 + 1] & 0xFF) << 8;
+        l |= (unsigned long long) (eventData[4 + 1 + 2] & 0xFF) << 16;
+        l |= (unsigned long long) (eventData[4 + 1 + 3] & 0xFF) << 24;
+        l |= (unsigned long long) (eventData[4 + 1 + 4] & 0xFF) << 32;
+        l |= (unsigned long long) (eventData[4 + 1 + 5] & 0xFF) << 40;
+        l |= (unsigned long long) (eventData[4 + 1 + 6] & 0xFF) << 48;
+        l |= (unsigned long long) (eventData[4 + 1 + 7] & 0xFF) << 56;
+
+        if (l == v) {
+            ++signals;
+            break;
+        }
+    } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
+    alarm(0);
+    signal(SIGALRM, SIG_DFL);
+
+    EXPECT_LE(1, count);
 
     EXPECT_EQ(1, signals);
 
@@ -971,11 +1129,20 @@
         struct logger * logger;
         EXPECT_TRUE(NULL != (logger = android_logger_open(logger_list, id)));
         EXPECT_EQ(id, android_logger_get_id(logger));
-        EXPECT_LT(0, android_logger_get_log_size(logger));
-        /* crash buffer is allowed to be empty, that is actually healthy! */
-        if (android_logger_get_log_readable_size(logger) ||
-                (strcmp("crash", name) && strcmp("security", name))) {
-            EXPECT_LT(0, android_logger_get_log_readable_size(logger));
+        ssize_t get_log_size = android_logger_get_log_size(logger);
+        /* security buffer is allowed to be denied */
+        if (strcmp("security", name)) {
+            EXPECT_LT(0, get_log_size);
+            /* crash buffer is allowed to be empty, that is actually healthy! */
+            EXPECT_LE((strcmp("crash", name)) != 0,
+                      android_logger_get_log_readable_size(logger));
+        } else {
+            EXPECT_NE(0, get_log_size);
+            if (get_log_size < 0) {
+                EXPECT_GT(0, android_logger_get_log_readable_size(logger));
+            } else {
+                EXPECT_LE(0, android_logger_get_log_readable_size(logger));
+            }
         }
         EXPECT_LT(0, android_logger_get_log_version(logger));
     }
diff --git a/libnativeloader/include/nativeloader/native_loader.h b/libnativeloader/include/nativeloader/native_loader.h
index b16c0e6..1bd3b8f 100644
--- a/libnativeloader/include/nativeloader/native_loader.h
+++ b/libnativeloader/include/nativeloader/native_loader.h
@@ -26,7 +26,7 @@
 namespace android {
 
 __attribute__((visibility("default")))
-void PreloadPublicNativeLibraries();
+void InitializeNativeLoader();
 
 __attribute__((visibility("default")))
 jstring CreateClassLoaderNamespace(JNIEnv* env,
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index 3e4b15a..e6b37ed 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -29,34 +29,14 @@
 #include <string>
 #include <mutex>
 
+#include "android-base/file.h"
 #include "android-base/macros.h"
 #include "android-base/strings.h"
 
 namespace android {
 
-#ifdef __ANDROID__
-// TODO(dimitry): move this to system properties.
-static const char* kPublicNativeLibraries = "libandroid.so:"
-                                            "libc.so:"
-                                            "libcamera2ndk.so:"
-                                            "libdl.so:"
-                                            "libEGL.so:"
-                                            "libGLESv1_CM.so:"
-                                            "libGLESv2.so:"
-                                            "libGLESv3.so:"
-                                            "libicui18n.so:"
-                                            "libicuuc.so:"
-                                            "libjnigraphics.so:"
-                                            "liblog.so:"
-                                            "libmediandk.so:"
-                                            "libm.so:"
-                                            "libOpenMAXAL.so:"
-                                            "libOpenSLES.so:"
-                                            "libRS.so:"
-                                            "libstdc++.so:"
-                                            "libvulkan.so:"
-                                            "libwebviewchromium_plat_support.so:"
-                                            "libz.so";
+#if defined(__ANDROID__)
+static constexpr const char* kPublicNativeLibrariesConfig = "/system/etc/public.libraries.txt";
 
 class LibraryNamespaces {
  public:
@@ -82,7 +62,8 @@
 
     android_namespace_t* ns = FindNamespaceByClassLoader(env, class_loader);
 
-    LOG_FATAL_IF(ns != nullptr, "There is already a namespace associated with this classloader");
+    LOG_ALWAYS_FATAL_IF(ns != nullptr,
+                        "There is already a namespace associated with this classloader");
 
     uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
     if (is_shared) {
@@ -112,10 +93,30 @@
     return it != namespaces_.end() ? it->second : nullptr;
   }
 
-  void PreloadPublicLibraries() {
+  void Initialize() {
+    // Read list of public native libraries from the config file.
+    std::string file_content;
+    LOG_ALWAYS_FATAL_IF(!base::ReadFileToString(kPublicNativeLibrariesConfig, &file_content),
+                        "Error reading public native library list from \"%s\": %s",
+                        kPublicNativeLibrariesConfig, strerror(errno));
+
+    std::vector<std::string> lines = base::Split(file_content, "\n");
+
+    std::vector<std::string> sonames;
+
+    for (const auto& line : lines) {
+      auto trimmed_line = base::Trim(line);
+      if (trimmed_line[0] == '#' || trimmed_line.empty()) {
+        continue;
+      }
+
+      sonames.push_back(trimmed_line);
+    }
+
+    public_libraries_ = base::Join(sonames, ':');
+
     // android_init_namespaces() expects all the public libraries
     // to be loaded so that they can be found by soname alone.
-    std::vector<std::string> sonames = android::base::Split(kPublicNativeLibraries, ":");
     for (const auto& soname : sonames) {
       dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE);
     }
@@ -123,9 +124,7 @@
 
  private:
   bool InitPublicNamespace(const char* library_path, int32_t target_sdk_version) {
-    // Some apps call dlopen from generated code unknown to linker in which
-    // case linker uses anonymous namespace. See b/25844435 for details.
-    std::string publicNativeLibraries = kPublicNativeLibraries;
+    std::string publicNativeLibraries = public_libraries_;
 
     // TODO (dimitry): This is a workaround for http://b/26436837
     // will be removed before the release.
@@ -139,6 +138,10 @@
     }
     // END OF WORKAROUND
 
+    // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
+    // code is one example) unknown to linker in which  case linker uses anonymous
+    // namespace. The second argument specifies the search path for the anonymous
+    // namespace which is the library_path of the classloader.
     initialized_ = android_init_namespaces(publicNativeLibraries.c_str(), library_path);
 
     return initialized_;
@@ -146,6 +149,8 @@
 
   bool initialized_;
   std::vector<std::pair<jweak, android_namespace_t*>> namespaces_;
+  std::string public_libraries_;
+
 
   DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
 };
@@ -158,10 +163,10 @@
 }
 #endif
 
-void PreloadPublicNativeLibraries() {
+void InitializeNativeLoader() {
 #if defined(__ANDROID__)
   std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  g_namespaces->PreloadPublicLibraries();
+  g_namespaces->Initialize();
 #endif
 }
 
diff --git a/mkbootimg/bootimg.h b/mkbootimg/bootimg.h
index 5ab6195..60834fe 100644
--- a/mkbootimg/bootimg.h
+++ b/mkbootimg/bootimg.h
@@ -43,7 +43,14 @@
 
     uint32_t tags_addr;    /* physical addr for kernel tags */
     uint32_t page_size;    /* flash page size we assume */
-    uint32_t unused[2];    /* future expansion: should be 0 */
+    uint32_t unused;       /* reserved for future expansion: MUST be 0 */
+
+    /* operating system version and security patch level; for
+     * version "A.B.C" and patch level "Y-M-D":
+     * ver = A << 14 | B << 7 | C         (7 bits for each of A, B, C)
+     * lvl = ((Y - 2000) & 127) << 4 | M  (7 bits for Y, 4 bits for M)
+     * os_version = ver << 11 | lvl */
+    uint32_t os_version;
 
     uint8_t name[BOOT_NAME_SIZE]; /* asciiz product name */
 
diff --git a/mkbootimg/mkbootimg b/mkbootimg/mkbootimg
index f95d703..7b04bcc 100755
--- a/mkbootimg/mkbootimg
+++ b/mkbootimg/mkbootimg
@@ -20,6 +20,7 @@
 from struct import pack
 from hashlib import sha1
 import sys
+import re
 
 def filesize(f):
     if f is None:
@@ -47,7 +48,7 @@
 def write_header(args):
     BOOT_MAGIC = 'ANDROID!'.encode()
     args.output.write(pack('8s', BOOT_MAGIC))
-    args.output.write(pack('8I',
+    args.output.write(pack('10I',
         filesize(args.kernel),                          # size in bytes
         args.base + args.kernel_offset,                 # physical load addr
         filesize(args.ramdisk),                         # size in bytes
@@ -55,8 +56,9 @@
         filesize(args.second),                          # size in bytes
         args.base + args.second_offset,                 # physical load addr
         args.base + args.tags_offset,                   # physical addr for kernel tags
-        args.pagesize))                                 # flash page size we assume
-    args.output.write(pack('8x'))                       # future expansion: should be 0
+        args.pagesize,                                  # flash page size we assume
+        0,                                              # future expansion: MUST be 0
+        (args.os_version << 11) | args.os_patch_level)) # os version and patch level
     args.output.write(pack('16s', args.board.encode())) # asciiz product name
     args.output.write(pack('512s', args.cmdline[:512].encode()))
 
@@ -97,6 +99,32 @@
 def parse_int(x):
     return int(x, 0)
 
+def parse_os_version(x):
+    match = re.search(r'^(\d{1,3})(?:\.(\d{1,3})(?:\.(\d{1,3}))?)?', x)
+    if match:
+        a = parse_int(match.group(1))
+        b = c = 0
+        if match.lastindex >= 2:
+            b = parse_int(match.group(2))
+        if match.lastindex == 3:
+            c = parse_int(match.group(3))
+        # 7 bits allocated for each field
+        assert a < 128
+        assert b < 128
+        assert c < 128
+        return (a << 14) | (b << 7) | c
+    return 0
+
+def parse_os_patch_level(x):
+    match = re.search(r'^(\d{4})-(\d{2})-(\d{2})', x)
+    if match:
+        y = parse_int(match.group(1)) - 2000
+        m = parse_int(match.group(2))
+        # 7 bits allocated for the year, 4 bits for the month
+        assert y >= 0 and y < 128
+        assert m > 0 and m <= 12
+        return (y << 4) | m
+    return 0
 
 def parse_cmdline():
     parser = ArgumentParser()
@@ -111,6 +139,10 @@
     parser.add_argument('--ramdisk_offset', help='ramdisk offset', type=parse_int, default=0x01000000)
     parser.add_argument('--second_offset', help='2nd bootloader offset', type=parse_int,
                         default=0x00f00000)
+    parser.add_argument('--os_version', help='operating system version', type=parse_os_version,
+                        default=0)
+    parser.add_argument('--os_patch_level', help='operating system patch level',
+                        type=parse_os_patch_level, default=0)
     parser.add_argument('--tags_offset', help='tags offset', type=parse_int, default=0x00000100)
     parser.add_argument('--board', help='board name', default='', action=ValidateStrLenAction,
                         maxlen=16)
diff --git a/rootdir/etc/public.libraries.android.txt b/rootdir/etc/public.libraries.android.txt
new file mode 100644
index 0000000..6244761
--- /dev/null
+++ b/rootdir/etc/public.libraries.android.txt
@@ -0,0 +1,20 @@
+libandroid.so
+libc.so
+libdl.so
+libEGL.so
+libGLESv1_CM.so
+libGLESv2.so
+libGLESv3.so
+libicui18n.so
+libicuuc.so
+libjnigraphics.so
+liblog.so
+libmediandk.so
+libm.so
+libOpenMAXAL.so
+libOpenSLES.so
+libRS.so
+libstdc++.so
+libvulkan.so
+libwebviewchromium_plat_support.so
+libz.so
diff --git a/rootdir/etc/public.libraries.wear.txt b/rootdir/etc/public.libraries.wear.txt
new file mode 100644
index 0000000..d499f38
--- /dev/null
+++ b/rootdir/etc/public.libraries.wear.txt
@@ -0,0 +1,19 @@
+libandroid.so
+libc.so
+libdl.so
+libEGL.so
+libGLESv1_CM.so
+libGLESv2.so
+libGLESv3.so
+libicui18n.so
+libicuuc.so
+libjnigraphics.so
+liblog.so
+libmediandk.so
+libm.so
+libOpenMAXAL.so
+libOpenSLES.so
+libRS.so
+libstdc++.so
+libvulkan.so
+libz.so