Merge changes I93287b87,I30a3eb0b

* changes:
  adb: add nullability specifiers to adb_client.h.
  adb: add adb_get_feature_set.
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index db8df14..85ab4d1 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -429,18 +429,46 @@
 }
 
 static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
-#if !defined(_WIN32)
     // Old devices can't handle window size changes.
     if (shell == nullptr) return;
 
+#if defined(_WIN32)
+    struct winsize {
+        unsigned short ws_row;
+        unsigned short ws_col;
+        unsigned short ws_xpixel;
+        unsigned short ws_ypixel;
+    };
+#endif
+
     winsize ws;
+
+#if defined(_WIN32)
+    // If stdout is redirected to a non-console, we won't be able to get the
+    // console size, but that makes sense.
+    const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
+    if (intptr_handle == -1) return;
+
+    const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
+
+    CONSOLE_SCREEN_BUFFER_INFO info;
+    memset(&info, 0, sizeof(info));
+    if (!GetConsoleScreenBufferInfo(handle, &info)) return;
+
+    memset(&ws, 0, sizeof(ws));
+    // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
+    ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
+    // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
+    // than the window, in which case we should use the width of the buffer.
+    ws.ws_col = info.dwSize.X;
+#else
     if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
+#endif
 
     // Send the new window size as human-readable ASCII for debugging convenience.
     size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
                         ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
     shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
-#endif
 }
 
 // Used to pass multiple values to the stdin read thread.
@@ -465,7 +493,10 @@
     pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
 #endif
 
-#if !defined(_WIN32)
+#if defined(_WIN32)
+    // _get_interesting_input_record_uncached() causes unix_read_interruptible()
+    // to return -1 with errno == EINTR if the window size changes.
+#else
     // Unblock SIGWINCH for this thread, so our read(2) below will be
     // interrupted if the window size changes.
     sigset_t mask;
@@ -494,20 +525,15 @@
     EscapeState state = kStartOfLine;
 
     while (true) {
-        // Use unix_read() rather than adb_read() for stdin.
-        D("stdin_read_thread_loop(): pre unix_read(fdi=%d,...)", args->stdin_fd);
-#if !defined(_WIN32)
-#undef read
-        int r = read(args->stdin_fd, buffer_ptr, buffer_size);
+        // Use unix_read_interruptible() rather than adb_read() for stdin.
+        D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
+        int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
+                                        buffer_size);
         if (r == -1 && errno == EINTR) {
             send_window_size_change(args->stdin_fd, args->protocol);
             continue;
         }
-#define read ___xxx_read
-#else
-        int r = unix_read(args->stdin_fd, buffer_ptr, buffer_size);
-#endif
-        D("stdin_read_thread_loop(): post unix_read(fdi=%d,...)", args->stdin_fd);
+        D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
         if (r <= 0) {
             // Only devices using the shell protocol know to close subprocess
             // stdin. For older devices we want to just leave the connection
@@ -701,10 +727,6 @@
             argc -= 2;
             argv += 2;
         } else if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) {
-            if (!CanUseFeature(features, kFeatureShell2)) {
-                fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
-                return 1;
-            }
             // Like ssh, -t arguments are cumulative so that multiple -t's
             // are needed to force a PTY.
             if (argv[0][1] == 't') {
@@ -728,6 +750,17 @@
         }
     }
 
+    // Legacy shell protocol requires a remote PTY to close the subprocess properly which creates
+    // some weird interactions with -tT.
+    if (!use_shell_protocol && t_arg_count != 0) {
+        if (!CanUseFeature(features, kFeatureShell2)) {
+            fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
+        } else {
+            fprintf(stderr, "error: PTY args -Tt cannot be used with -x\n");
+        }
+        return 1;
+    }
+
     std::string shell_type_arg;
     if (CanUseFeature(features, kFeatureShell2)) {
         if (t_arg_count < 0) {
diff --git a/adb/file_sync_service.cpp b/adb/file_sync_service.cpp
index 781968b..ef0418e 100644
--- a/adb/file_sync_service.cpp
+++ b/adb/file_sync_service.cpp
@@ -21,6 +21,7 @@
 
 #include <dirent.h>
 #include <errno.h>
+#include <log/log.h>
 #include <selinux/android.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -34,6 +35,7 @@
 #include "adb_io.h"
 #include "adb_utils.h"
 #include "private/android_filesystem_config.h"
+#include "security_log_tags.h"
 
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
@@ -146,6 +148,8 @@
     syncmsg msg;
     unsigned int timestamp = 0;
 
+    __android_log_security_bswrite(SEC_TAG_ADB_SEND_FILE, path);
+
     int fd = adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
     if (fd < 0 && errno == ENOENT) {
         if (!secure_mkdirs(adb_dirname(path))) {
@@ -314,6 +318,8 @@
 }
 
 static bool do_recv(int s, const char* path, std::vector<char>& buffer) {
+    __android_log_security_bswrite(SEC_TAG_ADB_RECV_FILE, path);
+
     int fd = adb_open(path, O_RDONLY | O_CLOEXEC);
     if (fd < 0) {
         SendSyncFailErrno(s, "open failed");
diff --git a/adb/security_log_tags.h b/adb/security_log_tags.h
new file mode 100644
index 0000000..1d02744
--- /dev/null
+++ b/adb/security_log_tags.h
@@ -0,0 +1,28 @@
+/*
+ * 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 __SECURITY_LOG_TAGS_H
+#define __SECURITY_LOG_TAGS_H
+
+/* TODO: Automatically generate this file from the logtags file when build
+ * infrastructure is in place.
+ * Defined in frameworks/base/core/java/android/auditing/SecurityLog.logtags
+ */
+#define SEC_TAG_ADB_SHELL_INTERACTIVE 210001
+#define SEC_TAG_ADB_SHELL_CMD         210002
+#define SEC_TAG_ADB_RECV_FILE         210003
+#define SEC_TAG_ADB_SEND_FILE         210004
+
+#endif
diff --git a/adb/shell_service.cpp b/adb/shell_service.cpp
index e092dc4..491bb68 100644
--- a/adb/shell_service.cpp
+++ b/adb/shell_service.cpp
@@ -95,11 +95,13 @@
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <paths.h>
+#include <log/log.h>
 
 #include "adb.h"
 #include "adb_io.h"
 #include "adb_trace.h"
 #include "adb_utils.h"
+#include "security_log_tags.h"
 
 namespace {
 
@@ -210,6 +212,7 @@
 
     const std::string command_;
     const std::string terminal_type_;
+    bool make_pty_raw_ = false;
     SubprocessType type_;
     SubprocessProtocol protocol_;
     pid_t pid_ = -1;
@@ -229,6 +232,18 @@
       terminal_type_(terminal_type ? terminal_type : ""),
       type_(type),
       protocol_(protocol) {
+    // If we aren't using the shell protocol we must allocate a PTY to properly close the
+    // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
+    // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
+    // e.g. screenrecord, will never notice the broken pipe and terminate.
+    // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
+    // with select() and will send SIGHUP manually to the child process.
+    if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
+        // Disable PTY input/output processing since the client is expecting raw data.
+        D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
+        type_ = SubprocessType::kPty;
+        make_pty_raw_ = true;
+    }
 }
 
 Subprocess::~Subprocess() {
@@ -240,6 +255,12 @@
     ScopedFd parent_error_sfd, child_error_sfd;
     char pts_name[PATH_MAX];
 
+    if (command_.empty()) {
+        __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
+    } else {
+        __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
+    }
+
     // Create a socketpair for the fork() child to report any errors back to the parent. Since we
     // use threads, logging directly from the child might deadlock due to locks held in another
     // thread during the fork.
@@ -408,6 +429,24 @@
         exit(-1);
     }
 
+    if (make_pty_raw_) {
+        termios tattr;
+        if (tcgetattr(child_fd, &tattr) == -1) {
+            int saved_errno = errno;
+            WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
+            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
+            exit(-1);
+        }
+
+        cfmakeraw(&tattr);
+        if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
+            int saved_errno = errno;
+            WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
+            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
+            exit(-1);
+        }
+    }
+
     return child_fd;
 }
 
diff --git a/adb/shell_service_test.cpp b/adb/shell_service_test.cpp
index c85232b..839284e 100644
--- a/adb/shell_service_test.cpp
+++ b/adb/shell_service_test.cpp
@@ -175,8 +175,9 @@
             "echo foo; echo bar >&2; [ -t 0 ]; echo $?",
             SubprocessType::kRaw, SubprocessProtocol::kNone));
 
-    // [ -t 0 ] == 1 means no terminal (raw).
-    ExpectLinesEqual(ReadRaw(subprocess_fd_), {"foo", "bar", "1"});
+    // [ -t 0 ] == 0 means we have a terminal (PTY). Even when requesting a raw subprocess, without
+    // the shell protocol we should always force a PTY to ensure proper cleanup.
+    ExpectLinesEqual(ReadRaw(subprocess_fd_), {"foo", "bar", "0"});
 }
 
 // Tests a PTY subprocess with no protocol.
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index a39775e..3bd8bba 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -168,8 +168,13 @@
 #undef   close
 #define  close   ____xxx_close
 
+// Like unix_read(), but may return EINTR.
+extern int  unix_read_interruptible(int  fd, void*  buf, size_t  len);
+
 // See the comments for the !defined(_WIN32) version of unix_read().
-extern int  unix_read(int  fd, void*  buf, size_t  len);
+static __inline__ int unix_read(int fd, void* buf, size_t len) {
+    return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
+}
 
 #undef   read
 #define  read  ___xxx_read
@@ -521,6 +526,11 @@
     return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
 }
 
+// Like unix_read(), but does not handle EINTR.
+static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
+    return read(fd, buf, len);
+}
+
 #undef   read
 #define  read  ___xxx_read
 
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index c3889b6..bea47a2 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -2588,6 +2588,18 @@
             fatal("ReadConsoleInputA did not return one input record");
         }
 
+        // If the console window is resized, emulate SIGWINCH by breaking out
+        // of read() with errno == EINTR. Note that there is no event on
+        // vertical resize because we don't give the console our own custom
+        // screen buffer (with CreateConsoleScreenBuffer() +
+        // SetConsoleActiveScreenBuffer()). Instead, we use the default which
+        // supports scrollback, but doesn't seem to raise an event for vertical
+        // window resize.
+        if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
+            errno = EINTR;
+            return false;
+        }
+
         if ((input_record->EventType == KEY_EVENT) &&
             (input_record->Event.KeyEvent.bKeyDown)) {
             if (input_record->Event.KeyEvent.wRepeatCount == 0) {
@@ -3323,9 +3335,13 @@
     // Disable ENABLE_LINE_INPUT so that input is immediately sent.
     // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
     // flag also seems necessary to have proper line-ending processing.
-    if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
-                                                  ENABLE_LINE_INPUT |
-                                                  ENABLE_ECHO_INPUT))) {
+    DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
+                                                   ENABLE_LINE_INPUT |
+                                                   ENABLE_ECHO_INPUT);
+    // Enable ENABLE_WINDOW_INPUT to get window resizes.
+    new_console_mode |= ENABLE_WINDOW_INPUT;
+
+    if (!SetConsoleMode(in, new_console_mode)) {
         // This really should not fail.
         D("stdin_raw_init: SetConsoleMode() failed: %s",
           SystemErrorCodeToString(GetLastError()).c_str());
@@ -3353,8 +3369,8 @@
     }
 }
 
-// Called by 'adb shell' and 'adb exec-in' to read from stdin.
-int unix_read(int fd, void* buf, size_t len) {
+// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
+int unix_read_interruptible(int fd, void* buf, size_t len) {
     if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
         // If it is a request to read from stdin, and stdin_raw_init() has been
         // called, and it successfully configured the console, then read from
diff --git a/base/file.cpp b/base/file.cpp
index f444c0c..bcdfc5e 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -149,5 +149,32 @@
   return true;
 }
 
+bool RemoveFileIfExists(const std::string& path, std::string* err) {
+  struct stat st;
+#if defined(_WIN32)
+  //TODO: Windows version can't handle symbol link correctly.
+  int result = stat(path.c_str(), &st);
+  bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
+#else
+  int result = lstat(path.c_str(), &st);
+  bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
+#endif
+  if (result == 0) {
+    if (!file_type_removable) {
+      if (err != nullptr) {
+        *err = "is not a regular or symbol link file";
+      }
+      return false;
+    }
+    if (unlink(path.c_str()) == -1) {
+      if (err != nullptr) {
+        *err = strerror(errno);
+      }
+      return false;
+    }
+  }
+  return true;
+}
+
 }  // namespace base
 }  // namespace android
diff --git a/base/file_test.cpp b/base/file_test.cpp
index 1bf83a4..17755bf 100644
--- a/base/file_test.cpp
+++ b/base/file_test.cpp
@@ -96,3 +96,17 @@
   s.resize(1024);
   ASSERT_FALSE(android::base::ReadFully(tf.fd, &s[0], s.size()));
 }
+
+TEST(file, RemoveFileIfExist) {
+  TemporaryFile tf;
+  ASSERT_TRUE(tf.fd != -1);
+  close(tf.fd);
+  tf.fd = -1;
+  std::string err;
+  ASSERT_TRUE(android::base::RemoveFileIfExists(tf.path, &err)) << err;
+  ASSERT_TRUE(android::base::RemoveFileIfExists(tf.path));
+  TemporaryDir td;
+  ASSERT_FALSE(android::base::RemoveFileIfExists(td.path));
+  ASSERT_FALSE(android::base::RemoveFileIfExists(td.path, &err));
+  ASSERT_EQ("is not a regular or symbol link file", err);
+}
diff --git a/base/include/android-base/file.h b/base/include/android-base/file.h
index acd29b3..486befc 100644
--- a/base/include/android-base/file.h
+++ b/base/include/android-base/file.h
@@ -37,6 +37,8 @@
 bool ReadFully(int fd, void* data, size_t byte_count);
 bool WriteFully(int fd, const void* data, size_t byte_count);
 
+bool RemoveFileIfExists(const std::string& path, std::string* err = nullptr);
+
 }  // namespace base
 }  // namespace android
 
diff --git a/bootstat/Android.mk b/bootstat/Android.mk
index 223450d..bbb903d 100644
--- a/bootstat/Android.mk
+++ b/bootstat/Android.mk
@@ -110,6 +110,7 @@
 LOCAL_C_INCLUDES := $(bootstat_c_includes)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_STATIC_LIBRARIES := libbootstat
+LOCAL_INIT_RC := bootstat.rc
 LOCAL_SRC_FILES := $(bootstat_src_files)
 # Clang is required because of C++14
 LOCAL_CLANG := true
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
new file mode 100644
index 0000000..2c37dd2
--- /dev/null
+++ b/bootstat/bootstat.rc
@@ -0,0 +1,14 @@
+# This file is the LOCAL_INIT_RC file for the bootstat command.
+
+on post-fs-data
+    mkdir /data/misc/bootstat 0700 root root
+
+# This marker, boot animation stopped, is considered the point at which the
+# the user may interact with the device, so it is a good proxy for the boot
+# complete signal.
+on property:init.svc.bootanim=stopped
+    # Record boot_complete timing event.
+    exec - root root -- /system/bin/bootstat -r boot_complete
+
+    # Log all boot events.
+    exec - root root -- /system/bin/bootstat -l
diff --git a/healthd/BatteryPropertiesRegistrar.cpp b/healthd/BatteryPropertiesRegistrar.cpp
index 09667a1..d3a89d7 100644
--- a/healthd/BatteryPropertiesRegistrar.cpp
+++ b/healthd/BatteryPropertiesRegistrar.cpp
@@ -30,8 +30,9 @@
 
 namespace android {
 
-void BatteryPropertiesRegistrar::publish() {
-    defaultServiceManager()->addService(String16("batteryproperties"), this);
+void BatteryPropertiesRegistrar::publish(
+    const sp<BatteryPropertiesRegistrar>& service) {
+    defaultServiceManager()->addService(String16("batteryproperties"), service);
 }
 
 void BatteryPropertiesRegistrar::notifyListeners(struct BatteryProperties props) {
diff --git a/healthd/BatteryPropertiesRegistrar.h b/healthd/BatteryPropertiesRegistrar.h
index 8853874..d17e4a3 100644
--- a/healthd/BatteryPropertiesRegistrar.h
+++ b/healthd/BatteryPropertiesRegistrar.h
@@ -30,7 +30,7 @@
 class BatteryPropertiesRegistrar : public BnBatteryPropertiesRegistrar,
                                    public IBinder::DeathRecipient {
 public:
-    void publish();
+    void publish(const sp<BatteryPropertiesRegistrar>& service);
     void notifyListeners(struct BatteryProperties props);
 
 private:
diff --git a/healthd/healthd_mode_android.cpp b/healthd/healthd_mode_android.cpp
index fd153a2..0a64099 100644
--- a/healthd/healthd_mode_android.cpp
+++ b/healthd/healthd_mode_android.cpp
@@ -58,5 +58,5 @@
     }
 
     gBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
-    gBatteryPropertiesRegistrar->publish();
+    gBatteryPropertiesRegistrar->publish(gBatteryPropertiesRegistrar);
 }
diff --git a/include/system/graphics.h b/include/system/graphics.h
index afd9f7b..cf2d7de 100644
--- a/include/system/graphics.h
+++ b/include/system/graphics.h
@@ -41,7 +41,7 @@
  * pixel format definitions
  */
 
-enum {
+typedef enum android_pixel_format {
     /*
      * "linear" color pixel formats:
      *
@@ -440,7 +440,7 @@
     HAL_PIXEL_FORMAT_YCbCr_422_SP       = 0x10, // NV16
     HAL_PIXEL_FORMAT_YCrCb_420_SP       = 0x11, // NV21
     HAL_PIXEL_FORMAT_YCbCr_422_I        = 0x14, // YUY2
-};
+} android_pixel_format_t;
 
 /*
  * Structure for describing YCbCr formats for consumption by applications.
@@ -526,7 +526,7 @@
  *
  */
 
-enum {
+typedef enum android_transform {
     /* flip source image horizontally (around the vertical axis) */
     HAL_TRANSFORM_FLIP_H    = 0x01,
     /* flip source image vertically (around the horizontal axis)*/
@@ -539,7 +539,7 @@
     HAL_TRANSFORM_ROT_270   = 0x07,
     /* don't use. see system/window.h */
     HAL_TRANSFORM_RESERVED  = 0x08,
-};
+} android_transform_t;
 
 /**
  * Dataspace Definitions
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index 5d3dd86..6cffb11 100644
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -48,7 +48,6 @@
 	Backtrace.cpp \
 	BacktraceCurrent.cpp \
 	BacktraceMap.cpp \
-	BacktraceOffline.cpp \
 	BacktracePtrace.cpp \
 	thread_utils.c \
 	ThreadEntry.cpp \
@@ -61,25 +60,6 @@
 	liblog \
 	libunwind \
 
-# Use shared llvm library on device to save space.
-libbacktrace_shared_libraries_target := \
-	libLLVM \
-
-# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
-# which is not included in the prebuilt.
-libbacktrace_static_libraries_host := \
-	libcutils \
-	libLLVMObject \
-	libLLVMBitReader \
-	libLLVMMC \
-	libLLVMMCParser \
-	libLLVMCore \
-	libLLVMSupport \
-
-libbacktrace_ldlibs_host := \
-	-lpthread \
-	-lrt \
-
 module := libbacktrace
 module_tag := optional
 build_type := target
@@ -98,6 +78,40 @@
 libbacktrace_static_libraries :=
 
 #-------------------------------------------------------------------------
+# The libbacktrace_offline shared library.
+#-------------------------------------------------------------------------
+libbacktrace_offline_src_files := \
+	BacktraceOffline.cpp \
+
+libbacktrace_offline_shared_libraries := \
+	libbacktrace \
+	liblog \
+	libunwind \
+
+# Use shared llvm library on device to save space.
+libbacktrace_offline_shared_libraries_target := \
+	libLLVM \
+
+# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
+# which is not included in the prebuilt.
+libbacktrace_offline_static_libraries_host := \
+	libLLVMObject \
+	libLLVMBitReader \
+	libLLVMMC \
+	libLLVMMCParser \
+	libLLVMCore \
+	libLLVMSupport \
+
+module := libbacktrace_offline
+module_tag := optional
+build_type := target
+build_target := SHARED_LIBRARY
+include $(LOCAL_PATH)/Android.build.mk
+build_type := host
+libbacktrace_multilib := both
+include $(LOCAL_PATH)/Android.build.mk
+
+#-------------------------------------------------------------------------
 # The libbacktrace_test library needed by backtrace_test.
 #-------------------------------------------------------------------------
 libbacktrace_test_cflags := \
@@ -141,6 +155,7 @@
 backtrace_test_shared_libraries := \
 	libbacktrace_test \
 	libbacktrace \
+	libbacktrace_offline \
 	libbase \
 	libcutils \
 	libunwind \
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index 3c8f879..baa3d0f 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -28,7 +28,6 @@
 #include <backtrace/BacktraceMap.h>
 
 #include "BacktraceLog.h"
-#include "BacktraceOffline.h"
 #include "thread_utils.h"
 #include "UnwindCurrent.h"
 #include "UnwindPtrace.h"
@@ -149,8 +148,3 @@
     return new UnwindPtrace(pid, tid, map);
   }
 }
-
-Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
-                                    const backtrace_stackinfo_t& stack, bool cache_file) {
-  return new BacktraceOffline(pid, tid, map, stack, cache_file);
-}
diff --git a/libbacktrace/BacktraceOffline.cpp b/libbacktrace/BacktraceOffline.cpp
index abc186b..e84ae74 100644
--- a/libbacktrace/BacktraceOffline.cpp
+++ b/libbacktrace/BacktraceOffline.cpp
@@ -659,3 +659,8 @@
   }
   return nullptr;
 }
+
+Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
+                                    const backtrace_stackinfo_t& stack, bool cache_file) {
+  return new BacktraceOffline(pid, tid, map, stack, cache_file);
+}
diff --git a/liblog/logd_write.c b/liblog/logd_write.c
index 55b965b..4946073 100644
--- a/liblog/logd_write.c
+++ b/liblog/logd_write.c
@@ -204,14 +204,36 @@
         if (vec[0].iov_len < 4) {
             return -EINVAL;
         }
-        if ((last_uid != AID_SYSTEM) && (last_uid != AID_ROOT)) {
+        /* Matches clientHasLogCredentials() in logd */
+        if ((last_uid != AID_SYSTEM) && (last_uid != AID_ROOT) && (last_uid != AID_LOG)) {
             uid_t uid = geteuid();
-            if ((uid != AID_SYSTEM) && (uid != AID_ROOT)) {
+            if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
                 gid_t gid = getgid();
-                if ((gid != AID_SYSTEM) && (gid != AID_ROOT)) {
+                if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
                     gid = getegid();
-                    if ((gid != AID_SYSTEM) && (gid != AID_ROOT)) {
-                        return -EPERM;
+                    if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
+                        int num_groups;
+                        gid_t *groups;
+
+                        num_groups = getgroups(0, NULL);
+                        if (num_groups <= 0) {
+                            return -EPERM;
+                        }
+                        groups = calloc(num_groups, sizeof(gid_t));
+                        if (!groups) {
+                            return -ENOMEM;
+                        }
+                        num_groups = getgroups(num_groups, groups);
+                        while (num_groups > 0) {
+                            if (groups[num_groups - 1] == AID_LOG) {
+                                break;
+                            }
+                            --num_groups;
+                        }
+                        free(groups);
+                        if (num_groups <= 0) {
+                            return -EPERM;
+                        }
                     }
                 }
             }
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
index 4eff891..32a65ea 100644
--- a/libnativebridge/native_bridge.cc
+++ b/libnativebridge/native_bridge.cc
@@ -413,19 +413,14 @@
       if (errno == ENOENT) {
         if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
           ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
-          fprintf(stderr, "Cannot create code cache directory %s: %s.",
-              app_code_cache_dir, strerror(errno));
           ReleaseAppCodeCacheDir();
         }
       } else {
         ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
-        fprintf(stderr, "Cannot stat code cache directory %s: %s.",
-            app_code_cache_dir, strerror(errno));
         ReleaseAppCodeCacheDir();
       }
     } else if (!S_ISDIR(st.st_mode)) {
       ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
-      fprintf(stderr, "Code cache is not a directory %s.", app_code_cache_dir);
       ReleaseAppCodeCacheDir();
     }
 
diff --git a/metricsd/.clang-format b/metricsd/.clang-format
index 65d8277..c98efc2 100644
--- a/metricsd/.clang-format
+++ b/metricsd/.clang-format
@@ -2,6 +2,7 @@
 AllowShortFunctionsOnASingleLine: Inline
 AllowShortIfStatementsOnASingleLine: false
 AllowShortLoopsOnASingleLine: false
+BinPackArguments: false
 BinPackParameters: false
 CommentPragmas: NOLINT:.*
 DerivePointerAlignment: false
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
index 250c657..e140c62 100644
--- a/metricsd/Android.mk
+++ b/metricsd/Android.mk
@@ -72,10 +72,7 @@
 libmetrics_shared_libraries := libchrome libbinder libbrillo libutils
 metrics_collector_shared_libraries := $(libmetrics_shared_libraries) \
   libbrillo-binder \
-  libbrillo-dbus \
   libbrillo-http \
-  libchrome-dbus \
-  libdbus \
   libmetrics \
   librootdev \
   libweaved
diff --git a/metricsd/collectors/averaged_statistics_collector.cc b/metricsd/collectors/averaged_statistics_collector.cc
index bac2870..a3aaa98 100644
--- a/metricsd/collectors/averaged_statistics_collector.cc
+++ b/metricsd/collectors/averaged_statistics_collector.cc
@@ -16,6 +16,7 @@
 
 #include "averaged_statistics_collector.h"
 
+#include <base/bind.h>
 #include <base/files/file_util.h>
 #include <base/files/file_path.h>
 #include <base/strings/string_number_conversions.h>
diff --git a/metricsd/metrics_collector.cc b/metricsd/metrics_collector.cc
index ec7e040..c3f42dc 100644
--- a/metricsd/metrics_collector.cc
+++ b/metricsd/metrics_collector.cc
@@ -32,8 +32,6 @@
 #include <base/strings/stringprintf.h>
 #include <brillo/binder_watcher.h>
 #include <brillo/osrelease_reader.h>
-#include <dbus/dbus.h>
-#include <dbus/message.h>
 
 #include "constants.h"
 #include "metrics_collector_service_impl.h"
@@ -142,7 +140,7 @@
   // Watch Binder events in the main loop
   brillo::BinderWatcher binder_watcher;
   CHECK(binder_watcher.Init()) << "Binder FD watcher init failed";
-  return brillo::DBusDaemon::Run();
+  return brillo::Daemon::Run();
 }
 
 uint32_t MetricsCollector::GetOsVersionHash() {
@@ -218,7 +216,7 @@
 }
 
 int MetricsCollector::OnInit() {
-  int return_code = brillo::DBusDaemon::OnInit();
+  int return_code = brillo::Daemon::OnInit();
   if (return_code != EX_OK)
     return return_code;
 
@@ -232,9 +230,6 @@
   if (testing_)
     return EX_OK;
 
-  bus_->AssertOnDBusThread();
-  CHECK(bus_->SetUpAsyncOperations());
-
   weave_service_subscription_ = weaved::Service::Connect(
       brillo::MessageLoop::current(),
       base::Bind(&MetricsCollector::OnWeaveServiceConnected,
@@ -249,10 +244,6 @@
   return EX_OK;
 }
 
-void MetricsCollector::OnShutdown(int* return_code) {
-  brillo::DBusDaemon::OnShutdown(return_code);
-}
-
 void MetricsCollector::OnWeaveServiceConnected(
     const std::weak_ptr<weaved::Service>& service) {
   service_ = service;
@@ -311,7 +302,8 @@
       metrics_lib_->AreMetricsEnabled() ? "enabled" : "disabled";
 
   if (!weave_service->SetStateProperty(kWeaveComponent, kWeaveTrait,
-                                       "analyticsReportingState", enabled,
+                                       "analyticsReportingState",
+                                       *brillo::ToValue(enabled),
                                        nullptr)) {
     LOG(ERROR) << "failed to update weave's state";
   }
diff --git a/metricsd/metrics_collector.h b/metricsd/metrics_collector.h
index ca4ae52..30659bd 100644
--- a/metricsd/metrics_collector.h
+++ b/metricsd/metrics_collector.h
@@ -28,7 +28,7 @@
 #include <base/memory/weak_ptr.h>
 #include <base/time/time.h>
 #include <brillo/binder_watcher.h>
-#include <brillo/daemons/dbus_daemon.h>
+#include <brillo/daemons/daemon.h>
 #include <libweaved/command.h>
 #include <libweaved/service.h>
 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
@@ -42,7 +42,7 @@
 using chromeos_metrics::PersistentInteger;
 using std::unique_ptr;
 
-class MetricsCollector : public brillo::DBusDaemon {
+class MetricsCollector : public brillo::Daemon {
  public:
   MetricsCollector();
   ~MetricsCollector();
@@ -54,12 +54,9 @@
             const base::FilePath& private_metrics_directory,
             const base::FilePath& shared_metrics_directory);
 
-  // Initializes DBus and MessageLoop variables before running the MessageLoop.
+  // Initializes the daemon.
   int OnInit() override;
 
-  // Clean up data set up in OnInit before shutting down message loop.
-  void OnShutdown(int* return_code) override;
-
   // Does all the work.
   int Run() override;
 
diff --git a/metricsd/metrics_collector.rc b/metricsd/metrics_collector.rc
index 3dcb2d7..2d7667d 100644
--- a/metricsd/metrics_collector.rc
+++ b/metricsd/metrics_collector.rc
@@ -1,4 +1,4 @@
 service metricscollector /system/bin/metrics_collector --foreground --logtosyslog
     class late_start
     user metrics_coll
-    group metrics_coll dbus
+    group metrics_coll
diff --git a/metricsd/metrics_collector_test.cc b/metricsd/metrics_collector_test.cc
index 5fb3ac8..8dda529 100644
--- a/metricsd/metrics_collector_test.cc
+++ b/metricsd/metrics_collector_test.cc
@@ -64,37 +64,6 @@
         .RetiresOnSaturation();
   }
 
-  // Creates a new DBus signal message with zero or more string arguments.
-  // The message can be deallocated through DeleteDBusMessage.
-  //
-  // |path| is the object emitting the signal.
-  // |interface| is the interface the signal is emitted from.
-  // |name| is the name of the signal.
-  // |arg_values| contains the values of the string arguments.
-  DBusMessage* NewDBusSignalString(const string& path,
-                                   const string& interface,
-                                   const string& name,
-                                   const vector<string>& arg_values) {
-    DBusMessage* msg = dbus_message_new_signal(path.c_str(),
-                                               interface.c_str(),
-                                               name.c_str());
-    DBusMessageIter iter;
-    dbus_message_iter_init_append(msg, &iter);
-    for (vector<string>::const_iterator it = arg_values.begin();
-         it != arg_values.end(); ++it) {
-      const char* str_value = it->c_str();
-      dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &str_value);
-    }
-    return msg;
-  }
-
-  // Deallocates the DBus message |msg| previously allocated through
-  // dbus_message_new*.
-  void DeleteDBusMessage(DBusMessage* msg) {
-    dbus_message_unref(msg);
-  }
-
-
   // Creates or overwrites the file in |path| so that it contains the printable
   // representation of |value|.
   void CreateUint64ValueFile(const base::FilePath& path, uint64_t value) {
diff --git a/metricsd/metricsd.rc b/metricsd/metricsd.rc
index 825c87f..3d3e695 100644
--- a/metricsd/metricsd.rc
+++ b/metricsd/metricsd.rc
@@ -6,4 +6,4 @@
 service metricsd /system/bin/metricsd --foreground --logtosyslog
     class late_start
     user metricsd
-    group system dbus inet
+    group system inet
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index b735dc3..6ef491c 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -1,6 +1,13 @@
 subsystem adf
 	devname uevent_devname
 
+# ueventd can only set permissions on device nodes and their associated
+# sysfs attributes, not on arbitrary paths.
+#
+# format for /dev rules: devname mode uid gid
+# format for /sys rules: nodename attr mode uid gid
+# shortcut: "mtd@NN" expands to "/dev/mtd/mtdNN"
+
 /dev/null                 0666   root       root
 /dev/zero                 0666   root       root
 /dev/full                 0666   root       root
diff --git a/toolbox/ps.c b/toolbox/ps.c
index ecc1c9f..7e70c71 100644
--- a/toolbox/ps.c
+++ b/toolbox/ps.c
@@ -264,9 +264,6 @@
     int pidfilter = 0;
     int threads = 0;
 
-    d = opendir("/proc");
-    if(d == 0) return -1;
-
     while(argc > 1){
         if(!strcmp(argv[1],"-t")) {
             threads = 1;
@@ -287,7 +284,10 @@
         } else if(!strcmp(argv[1],"--ppid")) {
             ppid_filter = atoi(argv[2]);
             if (ppid_filter == 0) {
-                fprintf(stderr, "bad ppid '%s'\n", argv[2]);
+                /* Bug 26554285: Use printf because some apps require at least
+                 * one line of output to stdout even for errors.
+                 */
+                printf("bad ppid '%s'\n", argv[2]);
                 return 1;
             }
             argc--;
@@ -295,7 +295,10 @@
         } else {
             pidfilter = atoi(argv[1]);
             if (pidfilter == 0) {
-                fprintf(stderr, "bad pid '%s'\n", argv[1]);
+                /* Bug 26554285: Use printf because some apps require at least
+                 * one line of output to stdout even for errors.
+                 */
+                printf("bad pid '%s'\n", argv[1]);
                 return 1;
             }
         }
@@ -313,6 +316,9 @@
            (int) PC_WIDTH, "PC",
            (display_flags&SHOW_ABI)?"ABI " : "");
 
+    d = opendir("/proc");
+    if(d == 0) return -1;
+
     while((de = readdir(d)) != 0){
         if(isdigit(de->d_name[0])){
             int pid = atoi(de->d_name);