Merge "metricsd: Fix unit tests."
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 60966d6..19dd03d 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -334,7 +334,7 @@
 #endif
 
     connection_properties.push_back(android::base::StringPrintf(
-        "features=%s", android::base::Join(supported_features(), ',').c_str()));
+        "features=%s", FeatureSetToString(supported_features()).c_str()));
 
     return android::base::StringPrintf(
         "%s::%s", adb_device_banner,
@@ -396,9 +396,7 @@
             } else if (key == "ro.product.device") {
                 qual_overwrite(&t->device, value);
             } else if (key == "features") {
-                for (const auto& feature : android::base::Split(value, ",")) {
-                    t->add_feature(feature);
-                }
+                t->SetFeatures(value);
             }
         }
     }
@@ -1149,27 +1147,13 @@
         std::string error_msg;
         atransport* t = acquire_one_transport(kCsAny, type, serial, &error_msg);
         if (t != nullptr) {
-            SendOkay(reply_fd, android::base::Join(t->features(), '\n'));
+            SendOkay(reply_fd, FeatureSetToString(t->features()));
         } else {
             SendFail(reply_fd, error_msg);
         }
         return 0;
     }
 
-    if (!strncmp(service, "check-feature:", strlen("check-feature:"))) {
-        std::string error_msg;
-        atransport* t = acquire_one_transport(kCsAny, type, serial, &error_msg);
-        if (t && t->CanUseFeature(service + strlen("check-feature:"))) {
-            // We could potentially extend this to reply with the feature
-            // version if that becomes necessary.
-            SendOkay(reply_fd, "1");
-        } else {
-            // Empty response means unsupported feature.
-            SendOkay(reply_fd, "");
-        }
-        return 0;
-    }
-
     // remove TCP transport
     if (!strncmp(service, "disconnect:", 11)) {
         const std::string address(service + 11);
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index 623108e..b4155df 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -50,9 +50,7 @@
 #define D(...) \
         do { \
             if (ADB_TRACING) { \
-                int saved_errno = errno; \
                 LOG(INFO) << android::base::StringPrintf(__VA_ARGS__); \
-                errno = saved_errno; \
            } \
         } while (0)
 
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index d287480..4e93dee 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -36,6 +36,7 @@
 
 #include <base/logging.h>
 #include <base/stringprintf.h>
+#include <base/strings.h>
 
 #if !defined(_WIN32)
 #include <termios.h>
@@ -108,7 +109,9 @@
         "  adb sync [ <directory> ]     - copy host->device only if changed\n"
         "                                 (-l means list but don't copy)\n"
         "  adb shell                    - run remote shell interactively\n"
-        "  adb shell <command>          - run remote shell command\n"
+        "  adb shell [-Tt] <command>    - run remote shell command\n"
+        "                                 (-T disables PTY allocation)\n"
+        "                                 (-t forces PTY allocation)\n"
         "  adb emu <command>            - run emulator console command\n"
         "  adb logcat [ <filter-spec> ] - View device log\n"
         "  adb forward --list           - list all forward socket connections.\n"
@@ -475,9 +478,10 @@
     return nullptr;
 }
 
-static int interactive_shell(bool use_shell_protocol) {
+static int interactive_shell(const std::string& service_string,
+                             bool use_shell_protocol) {
     std::string error;
-    int fd = adb_connect("shell:", &error);
+    int fd = adb_connect(service_string, &error);
     if (fd < 0) {
         fprintf(stderr,"error: %s\n", error.c_str());
         return 1;
@@ -524,18 +528,16 @@
     return android::base::StringPrintf("%s:%s", prefix, command);
 }
 
-// Checks whether the device indicated by |transport_type| and |serial| supports
-// |feature|. Returns the response string, which will be empty if the device
-// could not be found or the feature is not supported.
-static std::string CheckFeature(const std::string& feature,
-                                TransportType transport_type,
+// Returns the FeatureSet for the indicated transport.
+static FeatureSet GetFeatureSet(TransportType transport_type,
                                 const char* serial) {
-    std::string result, error, command("check-feature:" + feature);
-    if (!adb_query(format_host_command(command.c_str(), transport_type, serial),
-                   &result, &error)) {
-        return "";
+    std::string result, error;
+
+    if (adb_query(format_host_command("features", transport_type, serial),
+                  &result, &error)) {
+        return StringToFeatureSet(result);
     }
-    return result;
+    return FeatureSet();
 }
 
 static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz,
@@ -797,9 +799,8 @@
         wait_for_device("wait-for-device", transport_type, serial);
     }
 
-    bool use_shell_protocol = !CheckFeature(kFeatureShell2, transport_type,
-                                            serial).empty();
-    int exit_code = read_and_dump(fd, use_shell_protocol);
+    FeatureSet features = GetFeatureSet(transport_type, serial);
+    int exit_code = read_and_dump(fd, features.count(kFeatureShell2) > 0);
 
     if (adb_close(fd) < 0) {
         PLOG(ERROR) << "failure closing FD " << fd;
@@ -1238,24 +1239,44 @@
     else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
         char h = (argv[0][0] == 'h');
 
+        FeatureSet features = GetFeatureSet(transport_type, serial);
+
+        bool use_shell_protocol = (features.count(kFeatureShell2) > 0);
+        if (!use_shell_protocol) {
+            D("shell protocol not supported, using raw data transfer");
+        } else {
+            D("using shell protocol");
+        }
+
+        // Parse shell-specific command-line options.
+        // argv[0] is always "shell".
+        --argc;
+        ++argv;
+        std::string shell_type_arg;
+        while (argc) {
+            if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) {
+                if (features.count(kFeatureShell2) == 0) {
+                    fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
+                    return 1;
+                }
+                shell_type_arg = argv[0];
+                --argc;
+                ++argv;
+            } else {
+                break;
+            }
+        }
+        std::string service_string = android::base::StringPrintf(
+                "shell%s:", shell_type_arg.c_str());
+
         if (h) {
             printf("\x1b[41;33m");
             fflush(stdout);
         }
 
-        bool use_shell_protocol;
-        if (CheckFeature(kFeatureShell2, transport_type, serial).empty()) {
-            D("shell protocol not supported, using raw data transfer");
-            use_shell_protocol = false;
-        } else {
-            D("using shell protocol");
-            use_shell_protocol = true;
-        }
-
-
-        if (argc < 2) {
+        if (!argc) {
             D("starting interactive shell");
-            r = interactive_shell(use_shell_protocol);
+            r = interactive_shell(service_string, use_shell_protocol);
             if (h) {
                 printf("\x1b[0m");
                 fflush(stdout);
@@ -1263,19 +1284,14 @@
             return r;
         }
 
-        std::string cmd = "shell:";
-        --argc;
-        ++argv;
-        while (argc-- > 0) {
-            // We don't escape here, just like ssh(1). http://b/20564385.
-            cmd += *argv++;
-            if (*argv) cmd += " ";
-        }
+        // We don't escape here, just like ssh(1). http://b/20564385.
+        service_string += android::base::Join(
+                std::vector<const char*>(argv, argv + argc), ' ');
 
         while (true) {
-            D("non-interactive shell loop. cmd=%s", cmd.c_str());
+            D("non-interactive shell loop. cmd=%s", service_string.c_str());
             std::string error;
-            int fd = adb_connect(cmd, &error);
+            int fd = adb_connect(service_string, &error);
             int r;
             if (fd >= 0) {
                 D("about to read_and_dump(fd=%d)", fd);
@@ -1545,7 +1561,14 @@
         return 0;
     }
     else if (!strcmp(argv[0], "features")) {
-        return adb_query_command(format_host_command("features", transport_type, serial));
+        // Only list the features common to both the adb client and the device.
+        FeatureSet features = GetFeatureSet(transport_type, serial);
+        for (const std::string& name : features) {
+            if (supported_features().count(name) > 0) {
+                printf("%s\n", name.c_str());
+            }
+        }
+        return 0;
     }
 
     usage();
diff --git a/adb/services.cpp b/adb/services.cpp
index d128efc..d0494ec 100644
--- a/adb/services.cpp
+++ b/adb/services.cpp
@@ -194,7 +194,39 @@
     adb_close(fd);
 }
 
-#endif
+// Shell service string can look like:
+//   shell[args]:[command]
+// Currently the only supported args are -T (force raw) and -t (force PTY).
+static int ShellService(const std::string& args, const atransport* transport) {
+    size_t delimiter_index = args.find(':');
+    if (delimiter_index == std::string::npos) {
+        LOG(ERROR) << "No ':' found in shell service arguments: " << args;
+        return -1;
+    }
+    const std::string service_args = args.substr(0, delimiter_index);
+    const std::string command = args.substr(delimiter_index + 1);
+
+    SubprocessType type;
+    if (service_args.empty()) {
+        // Default: use PTY for interactive, raw for non-interactive.
+        type = (command.empty() ? SubprocessType::kPty : SubprocessType::kRaw);
+    } else if (service_args == "-T") {
+        type = SubprocessType::kRaw;
+    } else if (service_args == "-t") {
+        type = SubprocessType::kPty;
+    } else {
+        LOG(ERROR) << "Unsupported shell service arguments: " << args;
+        return -1;
+    }
+
+    SubprocessProtocol protocol =
+            (transport->CanUseFeature(kFeatureShell2) ? SubprocessProtocol::kShell
+                                                      : SubprocessProtocol::kNone);
+
+    return StartSubprocess(command.c_str(), type, protocol);
+}
+
+#endif  // !ADB_HOST
 
 static int create_service_thread(void (*func)(int, void *), void *cookie)
 {
@@ -265,14 +297,8 @@
         ret = create_service_thread(framebuffer_service, 0);
     } else if (!strncmp(name, "jdwp:", 5)) {
         ret = create_jdwp_connection_fd(atoi(name+5));
-    } else if(!strncmp(name, "shell:", 6)) {
-        const char* args = name + 6;
-        // Use raw for non-interactive, PTY for interactive.
-        SubprocessType type = (*args ? SubprocessType::kRaw : SubprocessType::kPty);
-        SubprocessProtocol protocol =
-                (transport->CanUseFeature(kFeatureShell2) ? SubprocessProtocol::kShell
-                                                          : SubprocessProtocol::kNone);
-        ret = StartSubprocess(args, type, protocol);
+    } else if(!strncmp(name, "shell", 5)) {
+        ret = ShellService(name + 5, transport);
     } else if(!strncmp(name, "exec:", 5)) {
         ret = StartSubprocess(name + 5, SubprocessType::kRaw,
                               SubprocessProtocol::kNone);
diff --git a/adb/transport.cpp b/adb/transport.cpp
index db9236e..402546b 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -779,27 +779,37 @@
     return max_payload;
 }
 
-// Do not use any of [:;=,] in feature strings, they have special meaning
-// in the connection banner.
-// TODO(dpursell): add this in once we can pass features through to the client.
-const char kFeatureShell2[] = "shell_2";
+namespace {
 
-// The list of features supported by the current system. Will be sent to the
-// other side of the connection in the banner.
-static const FeatureSet gSupportedFeatures = {
-        kFeatureShell2,
-};
+constexpr char kFeatureStringDelimiter = ',';
+
+}  // namespace
 
 const FeatureSet& supported_features() {
-    return gSupportedFeatures;
+    // Local static allocation to avoid global non-POD variables.
+    static const FeatureSet* features = new FeatureSet{
+        kFeatureShell2
+    };
+
+    return *features;
+}
+
+std::string FeatureSetToString(const FeatureSet& features) {
+    return android::base::Join(features, kFeatureStringDelimiter);
+}
+
+FeatureSet StringToFeatureSet(const std::string& features_string) {
+    auto names = android::base::Split(features_string,
+                                      {kFeatureStringDelimiter});
+    return FeatureSet(names.begin(), names.end());
 }
 
 bool atransport::has_feature(const std::string& feature) const {
     return features_.count(feature) > 0;
 }
 
-void atransport::add_feature(const std::string& feature) {
-    features_.insert(feature);
+void atransport::SetFeatures(const std::string& features_string) {
+    features_ = StringToFeatureSet(features_string);
 }
 
 bool atransport::CanUseFeature(const std::string& feature) const {
@@ -855,9 +865,6 @@
         append_transport_info(result, "product:", t->product, false);
         append_transport_info(result, "model:", t->model, true);
         append_transport_info(result, "device:", t->device, false);
-        append_transport_info(result, "features:",
-                              android::base::Join(t->features(), ',').c_str(),
-                              false);
     }
     *result += '\n';
 }
diff --git a/adb/transport.h b/adb/transport.h
index 999922a..0ec8ceb 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -29,7 +29,13 @@
 
 const FeatureSet& supported_features();
 
-const extern char kFeatureShell2[];
+// Encodes and decodes FeatureSet objects into human-readable strings.
+std::string FeatureSetToString(const FeatureSet& features);
+FeatureSet StringToFeatureSet(const std::string& features_string);
+
+// Do not use any of [:;=,] in feature strings, they have special meaning
+// in the connection banner.
+constexpr char kFeatureShell2[] = "shell_2";
 
 class atransport {
 public:
@@ -85,12 +91,14 @@
     int get_protocol_version() const;
     size_t get_max_payload() const;
 
-    inline const FeatureSet features() const {
+    const FeatureSet& features() const {
         return features_;
     }
 
     bool has_feature(const std::string& feature) const;
-    void add_feature(const std::string& feature);
+
+    // Loads the transport's feature set from the given string.
+    void SetFeatures(const std::string& features_string);
 
     // Returns true if both we and the other end of the transport support the
     // feature.
diff --git a/adb/transport_test.cpp b/adb/transport_test.cpp
index 10872ac..7d69c3e 100644
--- a/adb/transport_test.cpp
+++ b/adb/transport_test.cpp
@@ -144,23 +144,29 @@
     ASSERT_EQ(0, count);
 }
 
-TEST(transport, add_feature) {
+TEST(transport, SetFeatures) {
     atransport t;
     ASSERT_EQ(0U, t.features().size());
 
-    t.add_feature("foo");
+    t.SetFeatures(FeatureSetToString(FeatureSet{"foo"}));
     ASSERT_EQ(1U, t.features().size());
     ASSERT_TRUE(t.has_feature("foo"));
 
-    t.add_feature("bar");
+    t.SetFeatures(FeatureSetToString(FeatureSet{"foo", "bar"}));
     ASSERT_EQ(2U, t.features().size());
     ASSERT_TRUE(t.has_feature("foo"));
     ASSERT_TRUE(t.has_feature("bar"));
 
-    t.add_feature("foo");
+    t.SetFeatures(FeatureSetToString(FeatureSet{"foo", "bar", "foo"}));
     ASSERT_EQ(2U, t.features().size());
     ASSERT_TRUE(t.has_feature("foo"));
     ASSERT_TRUE(t.has_feature("bar"));
+
+    t.SetFeatures(FeatureSetToString(FeatureSet{"bar", "baz"}));
+    ASSERT_EQ(2U, t.features().size());
+    ASSERT_FALSE(t.has_feature("foo"));
+    ASSERT_TRUE(t.has_feature("bar"));
+    ASSERT_TRUE(t.has_feature("baz"));
 }
 
 TEST(transport, parse_banner_no_features) {
diff --git a/base/include/base/logging.h b/base/include/base/logging.h
index 283a7bc..30f6906 100644
--- a/base/include/base/logging.h
+++ b/base/include/base/logging.h
@@ -87,30 +87,64 @@
 // Replace the current logger.
 extern void SetLogger(LogFunction&& logger);
 
+// Get the minimum severity level for logging.
+extern LogSeverity GetMinimumLogSeverity();
+
+class ErrnoRestorer {
+ public:
+  ErrnoRestorer()
+      : saved_errno_(errno) {
+  }
+
+  ~ErrnoRestorer() {
+    errno = saved_errno_;
+  }
+
+  // Allow this object to evaluate to false which is useful in macros.
+  operator bool() const {
+    return false;
+  }
+
+ private:
+  const int saved_errno_;
+
+  DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
+};
+
 // Logs a message to logcat on Android otherwise to stderr. If the severity is
 // FATAL it also causes an abort. For example:
 //
 //     LOG(FATAL) << "We didn't expect to reach here";
-#define LOG(severity)                                                       \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
-                              ::android::base::severity, -1).stream()
+#define LOG(severity) LOG_TO(DEFAULT, severity)
 
 // Logs a message to logcat with the specified log ID on Android otherwise to
 // stderr. If the severity is FATAL it also causes an abort.
-#define LOG_TO(dest, severity)                                           \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest, \
-                              ::android::base::severity, -1).stream()
+// Use an if-else statement instead of just an if statement here. So if there is a
+// else statement after LOG() macro, it won't bind to the if statement in the macro.
+// do-while(0) statement doesn't work here. Because we need to support << operator
+// following the macro, like "LOG(DEBUG) << xxx;".
+#define LOG_TO(dest, severity)                                                      \
+  if (LIKELY(::android::base::severity < ::android::base::GetMinimumLogSeverity())) \
+    ;                                                                               \
+  else                                                                              \
+    ::android::base::ErrnoRestorer() ? *(std::ostream*)nullptr :                    \
+      ::android::base::LogMessage(__FILE__, __LINE__,                               \
+          ::android::base::dest,                                                    \
+          ::android::base::severity, -1).stream()
 
 // A variant of LOG that also logs the current errno value. To be used when
 // library calls fail.
-#define PLOG(severity)                                                      \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
-                              ::android::base::severity, errno).stream()
+#define PLOG(severity) PLOG_TO(DEFAULT, severity)
 
 // Behaves like PLOG, but logs to the specified log ID.
-#define PLOG_TO(dest, severity)                                          \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest, \
-                              ::android::base::severity, errno).stream()
+#define PLOG_TO(dest, severity)                                                     \
+  if (LIKELY(::android::base::severity < ::android::base::GetMinimumLogSeverity())) \
+    ;                                                                               \
+  else                                                                              \
+    ::android::base::ErrnoRestorer() ? *(std::ostream*)nullptr :                    \
+      ::android::base::LogMessage(__FILE__, __LINE__,                               \
+          ::android::base::dest,                                                    \
+          ::android::base::severity, errno).stream()
 
 // Marker that code is yet to be implemented.
 #define UNIMPLEMENTED(level) \
@@ -122,11 +156,13 @@
 //
 //     CHECK(false == true) results in a log message of
 //       "Check failed: false == true".
-#define CHECK(x)                                                            \
-  if (UNLIKELY(!(x)))                                                       \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
-                              ::android::base::FATAL, -1).stream()          \
-      << "Check failed: " #x << " "
+#define CHECK(x)                                                              \
+  if (LIKELY((x)))                                                            \
+    ;                                                                         \
+  else                                                                        \
+    ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
+                                ::android::base::FATAL, -1).stream()          \
+        << "Check failed: " #x << " "
 
 // Helper for CHECK_xx(x,y) macros.
 #define CHECK_OP(LHS, RHS, OP)                                              \
@@ -153,7 +189,9 @@
 
 // Helper for CHECK_STRxx(s1,s2) macros.
 #define CHECK_STROP(s1, s2, sense)                                         \
-  if (UNLIKELY((strcmp(s1, s2) == 0) != sense))                            \
+  if (LIKELY((strcmp(s1, s2) == 0) == sense))                              \
+    ;                                                                      \
+  else                                                                     \
     LOG(FATAL) << "Check failed: "                                         \
                << "\"" << s1 << "\""                                       \
                << (sense ? " == " : " != ") << "\"" << s2 << "\""
diff --git a/base/logging.cpp b/base/logging.cpp
index e9e06df..6bfaaec 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -139,6 +139,10 @@
 static LogSeverity gMinimumLogSeverity = INFO;
 static std::unique_ptr<std::string> gProgramInvocationName;
 
+LogSeverity GetMinimumLogSeverity() {
+  return gMinimumLogSeverity;
+}
+
 static const char* ProgramInvocationName() {
   if (gProgramInvocationName == nullptr) {
     gProgramInvocationName.reset(new std::string(getprogname()));
@@ -200,20 +204,6 @@
   InitLogging(argv);
 }
 
-// TODO: make this public; it's independently useful.
-class ErrnoRestorer {
- public:
-  ErrnoRestorer(int saved_errno) : saved_errno_(saved_errno) {
-  }
-
-  ~ErrnoRestorer() {
-    errno = saved_errno_;
-  }
-
- private:
-  const int saved_errno_;
-};
-
 void InitLogging(char* argv[]) {
   if (gInitialized) {
     return;
@@ -286,13 +276,12 @@
 class LogMessageData {
  public:
   LogMessageData(const char* file, unsigned int line, LogId id,
-                 LogSeverity severity, int error, int saved_errno)
+                 LogSeverity severity, int error)
       : file_(GetFileBasename(file)),
         line_number_(line),
         id_(id),
         severity_(severity),
-        error_(error),
-        errno_restorer_(saved_errno) {
+        error_(error) {
   }
 
   const char* GetFile() const {
@@ -330,39 +319,38 @@
   const LogId id_;
   const LogSeverity severity_;
   const int error_;
-  ErrnoRestorer errno_restorer_;
 
   DISALLOW_COPY_AND_ASSIGN(LogMessageData);
 };
 
 LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
                        LogSeverity severity, int error)
-    : data_(new LogMessageData(file, line, id, severity, error, errno)) {
+    : data_(new LogMessageData(file, line, id, severity, error)) {
 }
 
 LogMessage::~LogMessage() {
-  if (data_->GetSeverity() < gMinimumLogSeverity) {
-    return;  // No need to format something we're not going to output.
-  }
-
   // Finish constructing the message.
   if (data_->GetError() != -1) {
     data_->GetBuffer() << ": " << strerror(data_->GetError());
   }
   std::string msg(data_->ToString());
 
-  if (msg.find('\n') == std::string::npos) {
-    LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-            data_->GetSeverity(), msg.c_str());
-  } else {
-    msg += '\n';
-    size_t i = 0;
-    while (i < msg.size()) {
-      size_t nl = msg.find('\n', i);
-      msg[nl] = '\0';
+  {
+    // Do the actual logging with the lock held.
+    lock_guard<mutex> lock(logging_lock);
+    if (msg.find('\n') == std::string::npos) {
       LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-              data_->GetSeverity(), &msg[i]);
-      i = nl + 1;
+              data_->GetSeverity(), msg.c_str());
+    } else {
+      msg += '\n';
+      size_t i = 0;
+      while (i < msg.size()) {
+        size_t nl = msg.find('\n', i);
+        msg[nl] = '\0';
+        LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
+                data_->GetSeverity(), &msg[i]);
+        i = nl + 1;
+      }
     }
   }
 
@@ -382,7 +370,6 @@
 void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
                          LogSeverity severity, const char* message) {
   const char* tag = ProgramInvocationName();
-  lock_guard<mutex> lock(logging_lock);
   gLogger(id, severity, tag, file, line, message);
 }
 
diff --git a/base/logging_test.cpp b/base/logging_test.cpp
index c12dfa5..9cf1aad 100644
--- a/base/logging_test.cpp
+++ b/base/logging_test.cpp
@@ -18,6 +18,10 @@
 
 #include <libgen.h>
 
+#if defined(_WIN32)
+#include <signal.h>
+#endif
+
 #include <regex>
 #include <string>
 
@@ -49,6 +53,11 @@
 
  private:
   void init() {
+#if defined(_WIN32)
+    // On Windows, stderr is often buffered, so make sure it is unbuffered so
+    // that we can immediately read back what was written to stderr.
+    ASSERT_EQ(0, setvbuf(stderr, NULL, _IONBF, 0));
+#endif
     old_stderr_ = dup(STDERR_FILENO);
     ASSERT_NE(-1, old_stderr_);
     ASSERT_NE(-1, dup2(fd(), STDERR_FILENO));
@@ -57,21 +66,58 @@
   void reset() {
     ASSERT_NE(-1, dup2(old_stderr_, STDERR_FILENO));
     ASSERT_EQ(0, close(old_stderr_));
+    // Note: cannot restore prior setvbuf() setting.
   }
 
   TemporaryFile temp_file_;
   int old_stderr_;
 };
 
+#if defined(_WIN32)
+static void ExitSignalAbortHandler(int) {
+  _exit(3);
+}
+#endif
+
+static void SuppressAbortUI() {
+#if defined(_WIN32)
+  // We really just want to call _set_abort_behavior(0, _CALL_REPORTFAULT) to
+  // suppress the Windows Error Reporting dialog box, but that API is not
+  // available in the OS-supplied C Runtime, msvcrt.dll, that we currently
+  // use (it is available in the Visual Studio C runtime).
+  //
+  // Instead, we setup a SIGABRT handler, which is called in abort() right
+  // before calling Windows Error Reporting. In the handler, we exit the
+  // process just like abort() does.
+  ASSERT_NE(SIG_ERR, signal(SIGABRT, ExitSignalAbortHandler));
+#endif
+}
+
 TEST(logging, CHECK) {
-  ASSERT_DEATH(CHECK(false), "Check failed: false ");
+  ASSERT_DEATH({SuppressAbortUI(); CHECK(false);}, "Check failed: false ");
   CHECK(true);
 
-  ASSERT_DEATH(CHECK_EQ(0, 1), "Check failed: 0 == 1 ");
+  ASSERT_DEATH({SuppressAbortUI(); CHECK_EQ(0, 1);}, "Check failed: 0 == 1 ");
   CHECK_EQ(0, 0);
 
-  ASSERT_DEATH(CHECK_STREQ("foo", "bar"), R"(Check failed: "foo" == "bar")");
+  ASSERT_DEATH({SuppressAbortUI(); CHECK_STREQ("foo", "bar");},
+               R"(Check failed: "foo" == "bar")");
   CHECK_STREQ("foo", "foo");
+
+  // Test whether CHECK() and CHECK_STREQ() have a dangling if with no else.
+  bool flag = false;
+  if (true)
+    CHECK(true);
+  else
+    flag = true;
+  EXPECT_FALSE(flag) << "CHECK macro probably has a dangling if with no else";
+
+  flag = false;
+  if (true)
+    CHECK_STREQ("foo", "foo");
+  else
+    flag = true;
+  EXPECT_FALSE(flag) << "CHECK_STREQ probably has a dangling if with no else";
 }
 
 std::string make_log_pattern(android::base::LogSeverity severity,
@@ -85,7 +131,7 @@
 }
 
 TEST(logging, LOG) {
-  ASSERT_DEATH(LOG(FATAL) << "foobar", "foobar");
+  ASSERT_DEATH({SuppressAbortUI(); LOG(FATAL) << "foobar";}, "foobar");
 
   // We can't usefully check the output of any of these on Windows because we
   // don't have std::regex, but we can at least make sure we printed at least as
@@ -148,6 +194,50 @@
     ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
 #endif
   }
+
+  // Test whether LOG() saves and restores errno.
+  {
+    CapturedStderr cap;
+    errno = 12345;
+    LOG(INFO) << (errno = 67890);
+    EXPECT_EQ(12345, errno) << "errno was not restored";
+
+    ASSERT_EQ(0, lseek(cap.fd(), SEEK_SET, 0));
+
+    std::string output;
+    android::base::ReadFdToString(cap.fd(), &output);
+    EXPECT_NE(nullptr, strstr(output.c_str(), "67890")) << output;
+
+#if !defined(_WIN32)
+    std::regex message_regex(
+        make_log_pattern(android::base::INFO, "67890"));
+    ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
+#endif
+  }
+
+  // Test whether LOG() has a dangling if with no else.
+  {
+    CapturedStderr cap;
+
+    // Do the test two ways: once where we hypothesize that LOG()'s if
+    // will evaluate to true (when severity is high enough) and once when we
+    // expect it to evaluate to false (when severity is not high enough).
+    bool flag = false;
+    if (true)
+      LOG(INFO) << "foobar";
+    else
+      flag = true;
+
+    EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
+
+    flag = false;
+    if (true)
+      LOG(VERBOSE) << "foobar";
+    else
+      flag = true;
+
+    EXPECT_FALSE(flag) << "LOG macro probably has a dangling if with no else";
+  }
 }
 
 TEST(logging, PLOG) {
diff --git a/logcat/Android.mk b/logcat/Android.mk
index 844ab8b..c4a9550 100644
--- a/logcat/Android.mk
+++ b/logcat/Android.mk
@@ -15,4 +15,15 @@
 
 include $(BUILD_EXECUTABLE)
 
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := logpersist.start
+LOCAL_MODULE_TAGS := debug
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_MODULE_PATH := $(bin_dir)
+LOCAL_SRC_FILES := logpersist
+ALL_TOOLS := logpersist.start logpersist.stop logpersist.cat
+LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(filter-out $(LOCAL_MODULE),$(ALL_TOOLS)),ln -sf $(LOCAL_MODULE) $(TARGET_OUT)/bin/$(t);)
+include $(BUILD_PREBUILT)
+
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index 0bc581e..33d39ac 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -2,10 +2,10 @@
     # all exec/services are called with umask(077), so no gain beyond 0700
     mkdir /data/misc/logd 0700 logd log
     # logd for write to /data/misc/logd, log group for read from pstore (-L)
-    exec - logd log -- /system/bin/logcat -L -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 64 -n 256
+    exec - logd log -- /system/bin/logcat -L -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n 256
     start logcatd
 
-service logcatd /system/bin/logcat -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 64 -n 256
+service logcatd /system/bin/logcat -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n 256
     class late_start
     disabled
     # logd for write to /data/misc/logd, log group for read from log daemon
diff --git a/logd/logpersist b/logcat/logpersist
similarity index 88%
rename from logd/logpersist
rename to logcat/logpersist
index 215e1e2..6f666f6 100755
--- a/logd/logpersist
+++ b/logcat/logpersist
@@ -1,9 +1,15 @@
 #! /system/bin/sh
 # logpersist cat start and stop handlers
+progname="${0##*/}"
+case `getprop ro.build.type` in
+userdebug|eng) ;;
+*) echo "${progname} - Permission denied"
+   exit 1
+   ;;
+esac
 data=/data/misc/logd
 property=persist.logd.logpersistd
 service=logcatd
-progname="${0##*/}"
 if [ X"${1}" = "-h" -o X"${1}" = X"--help" ]; then
   echo "${progname%.*}.cat            - dump current ${service%d} logs"
   echo "${progname%.*}.start          - start ${service} service"
diff --git a/logd/Android.mk b/logd/Android.mk
index 01c51c7..c00061b 100644
--- a/logd/Android.mk
+++ b/logd/Android.mk
@@ -43,15 +43,4 @@
 
 include $(BUILD_EXECUTABLE)
 
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := logpersist.start
-LOCAL_MODULE_TAGS := debug
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_PATH := $(bin_dir)
-LOCAL_SRC_FILES := logpersist
-ALL_TOOLS := logpersist.start logpersist.stop logpersist.cat
-LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(filter-out $(LOCAL_MODULE),$(ALL_TOOLS)),ln -sf $(LOCAL_MODULE) $(TARGET_OUT)/bin/$(t);)
-include $(BUILD_PREBUILT)
-
 include $(call first-makefiles-under,$(LOCAL_PATH))