Merge "adb: fix subprocess termination for legacy shell."
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 1f5d29f..5679711 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -472,18 +472,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.
@@ -508,7 +536,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;
@@ -537,20 +568,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
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 b9a22dc..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 {
 
@@ -253,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.
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 2190c61..0abade4 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -164,8 +164,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
@@ -517,6 +522,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/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/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/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);