logcat: Add coding style

- Android coding standard compliance with an eye to reducing merge
  impact.
- resolve a few misbehaviors in logcat_test.

SideEffects: none
Test: gTest logcat-unit-tests
Bug: 35326290
Change-Id: I63d0667ad34c0df11086a6ffe94b7030430b865b
diff --git a/logcat/.clang-format b/logcat/.clang-format
new file mode 100644
index 0000000..393c309
--- /dev/null
+++ b/logcat/.clang-format
@@ -0,0 +1,11 @@
+BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: false
+
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 4
+PointerAlignment: Left
+TabWidth: 4
+PenaltyExcessCharacter: 32
+
+Cpp11BracedListStyle: false
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 4a171fd..c603a52 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -1,4 +1,18 @@
-// Copyright 2006-2015 The Android Open Source Project
+/*
+ * Copyright (C) 2006-2015 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 <arpa/inet.h>
 #include <assert.h>
@@ -39,16 +53,16 @@
 
 #define DEFAULT_MAX_ROTATED_LOGS 4
 
-static AndroidLogFormat * g_logformat;
+static AndroidLogFormat* g_logformat;
 
-/* logd prefixes records with a length field */
+// logd prefixes records with a length field
 #define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
 
 struct log_device_t {
     const char* device;
     bool binary;
-    struct logger *logger;
-    struct logger_list *logger_list;
+    struct logger* logger;
+    struct logger_list* logger_list;
     bool printed;
 
     log_device_t* next;
@@ -65,9 +79,9 @@
 
 namespace android {
 
-/* Global Variables */
+// Global Variables
 
-static const char * g_outputFileName;
+static const char* g_outputFileName;
 // 0 means "no log rotation"
 static size_t g_logRotateSizeKBytes;
 // 0 means "unbounded"
@@ -75,7 +89,7 @@
 static int g_outFD = -1;
 static size_t g_outByteCount;
 static int g_printBinary;
-static int g_devCount;                              // >1 means multiple
+static int g_devCount;  // >1 means multiple
 static pcrecpp::RE* g_regex;
 // 0 means "infinite"
 static size_t g_maxCount;
@@ -83,22 +97,17 @@
 static bool g_printItAnyways;
 static bool g_debug;
 
-enum helpType {
-    HELP_FALSE,
-    HELP_TRUE,
-    HELP_FORMAT
-};
+enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
 
 // if showHelp is set, newline required in fmt statement to transition to usage
-__noreturn static void logcat_panic(enum helpType showHelp, const char *fmt, ...) __printflike(2,3);
+__noreturn static void logcat_panic(enum helpType showHelp, const char* fmt,
+                                    ...) __printflike(2, 3);
 
-static int openLogFile (const char *pathname)
-{
+static int openLogFile(const char* pathname) {
     return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
 }
 
-static void rotateLogs()
-{
+static void rotateLogs() {
     int err;
 
     // Can't rotate logs if we're not outputting to a file
@@ -108,12 +117,15 @@
 
     close(g_outFD);
 
-    // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
-    // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
+    // Compute the maximum number of digits needed to count up to
+    // g_maxRotatedLogs in decimal.  eg:
+    // g_maxRotatedLogs == 30
+    //   -> log10(30) == 1.477
+    //   -> maxRotationCountDigits == 2
     int maxRotationCountDigits =
-            (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+        (g_maxRotatedLogs > 0) ? (int)(floor(log10(g_maxRotatedLogs) + 1)) : 0;
 
-    for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
+    for (int i = g_maxRotatedLogs; i > 0; i--) {
         std::string file1 = android::base::StringPrintf(
             "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
 
@@ -121,8 +133,8 @@
         if (i - 1 == 0) {
             file0 = android::base::StringPrintf("%s", g_outputFileName);
         } else {
-            file0 = android::base::StringPrintf(
-                "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
+            file0 = android::base::StringPrintf("%s.%.*d", g_outputFileName,
+                                                maxRotationCountDigits, i - 1);
         }
 
         if ((file0.length() == 0) || (file1.length() == 0)) {
@@ -144,18 +156,15 @@
     }
 
     g_outByteCount = 0;
-
 }
 
-void printBinary(struct log_msg *buf)
-{
+void printBinary(struct log_msg* buf) {
     size_t size = buf->len();
 
     TEMP_FAILURE_RETRY(write(g_outFD, buf, size));
 }
 
-static bool regexOk(const AndroidLogEntry& entry)
-{
+static bool regexOk(const AndroidLogEntry& entry) {
     if (!g_regex) {
         return true;
     }
@@ -165,8 +174,7 @@
     return g_regex->PartialMatch(messageString);
 }
 
-static void processBuffer(log_device_t* dev, struct log_msg *buf)
-{
+static void processBuffer(log_device_t* dev, struct log_msg* buf) {
     int bytesWritten = 0;
     int err;
     AndroidLogEntry entry;
@@ -174,17 +182,16 @@
 
     if (dev->binary) {
         static bool hasOpenedEventTagMap = false;
-        static EventTagMap *eventTagMap = NULL;
+        static EventTagMap* eventTagMap = NULL;
 
         if (!eventTagMap && !hasOpenedEventTagMap) {
             eventTagMap = android_openEventTagMap(NULL);
             hasOpenedEventTagMap = true;
         }
         err = android_log_processBinaryLogBuffer(&buf->entry_v1, &entry,
-                                                 eventTagMap,
-                                                 binaryMsgBuf,
+                                                 eventTagMap, binaryMsgBuf,
                                                  sizeof(binaryMsgBuf));
-        //printf(">>> pri=%d len=%d msg='%s'\n",
+        // printf(">>> pri=%d len=%d msg='%s'\n",
         //    entry.priority, entry.messageLen, entry.message);
     } else {
         err = android_log_processLogBuffer(&buf->entry_v1, &entry);
@@ -193,14 +200,15 @@
         goto error;
     }
 
-    if (android_log_shouldPrintLine(g_logformat,
-                                    std::string(entry.tag, entry.tagLen).c_str(),
-                                    entry.priority)) {
+    if (android_log_shouldPrintLine(
+            g_logformat, std::string(entry.tag, entry.tagLen).c_str(),
+            entry.priority)) {
         bool match = regexOk(entry);
 
         g_printCount += match;
         if (match || g_printItAnyways) {
-            bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
+            bytesWritten =
+                android_log_printLogLine(g_logformat, g_outFD, &entry);
 
             if (bytesWritten < 0) {
                 logcat_panic(HELP_FALSE, "output error");
@@ -210,9 +218,8 @@
 
     g_outByteCount += bytesWritten;
 
-    if (g_logRotateSizeKBytes > 0
-        && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
-    ) {
+    if (g_logRotateSizeKBytes > 0 &&
+        (g_outByteCount / 1024) >= g_logRotateSizeKBytes) {
         rotateLogs();
     }
 
@@ -225,8 +232,7 @@
         if (g_devCount > 1 && !g_printBinary) {
             char buf[1024];
             snprintf(buf, sizeof(buf), "--------- %s %s\n",
-                     dev->printed ? "switch to" : "beginning of",
-                     dev->device);
+                     dev->printed ? "switch to" : "beginning of", dev->device);
             if (write(g_outFD, buf, strlen(buf)) < 0) {
                 logcat_panic(HELP_FALSE, "output error");
             }
@@ -250,7 +256,7 @@
 
         struct sched_param param;
         memset(&param, 0, sizeof(param));
-        if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
+        if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
             fprintf(stderr, "failed to set to batch scheduler\n");
         }
 
@@ -259,7 +265,7 @@
         }
     }
 
-    g_outFD = openLogFile (g_outputFileName);
+    g_outFD = openLogFile(g_outputFileName);
 
     if (g_outFD < 0) {
         logcat_panic(HELP_FALSE, "couldn't open output file");
@@ -271,7 +277,7 @@
         logcat_panic(HELP_FALSE, "couldn't get output file stat\n");
     }
 
-    if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
+    if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
         close(g_outFD);
         logcat_panic(HELP_FALSE, "invalid output file stat\n");
     }
@@ -279,9 +285,9 @@
     g_outByteCount = statbuf.st_size;
 }
 
-static void show_help(const char *cmd)
-{
-    fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
+// clang-format off
+static void show_help(const char* cmd) {
+    fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd);
 
     fprintf(stderr, "options include:\n"
                     "  -s              Set default filter to silent. Equivalent to filterspec '*:S'\n"
@@ -347,7 +353,7 @@
                     "                  comes first. Improves efficiency of polling by providing\n"
                     "                  an about-to-wrap wakeup.\n");
 
-    fprintf(stderr,"\nfilterspecs are a series of \n"
+    fprintf(stderr, "\nfilterspecs are a series of \n"
                    "  <tag>[:priority]\n\n"
                    "where <tag> is a log component tag (or * for all) and priority is:\n"
                    "  V    Verbose (default for <tag>)\n"
@@ -365,8 +371,7 @@
                    "or defaults to \"threadtime\"\n\n");
 }
 
-static void show_format_help()
-{
+static void show_format_help() {
     fprintf(stderr,
         "-v <format>, --format=<format> options:\n"
         "  Sets log print format verb and adverbs, where <format> is:\n"
@@ -398,10 +403,10 @@
         "  \"<zone>\"    — Print using this public named timezone (experimental).\n\n"
     );
 }
+// clang-format on
 
-static int setLogFormat(const char * formatString)
-{
-    static AndroidLogPrintFormat format;
+static int setLogFormat(const char* formatString) {
+    AndroidLogPrintFormat format;
 
     format = android_log_formatFromString(formatString);
 
@@ -413,39 +418,33 @@
     return android_log_setPrintFormat(g_logformat, format);
 }
 
-static const char multipliers[][2] = {
-    { "" },
-    { "K" },
-    { "M" },
-    { "G" }
-};
+static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
 
-static unsigned long value_of_size(unsigned long value)
-{
+static unsigned long value_of_size(unsigned long value) {
     for (unsigned i = 0;
-            (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
-            value /= 1024, ++i) ;
+         (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
+         value /= 1024, ++i)
+        ;
     return value;
 }
 
-static const char *multiplier_of_size(unsigned long value)
-{
+static const char* multiplier_of_size(unsigned long value) {
     unsigned i;
     for (i = 0;
-            (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
-            value /= 1024, ++i) ;
+         (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
+         value /= 1024, ++i)
+        ;
     return multipliers[i];
 }
 
-/*String to unsigned int, returns -1 if it fails*/
-static bool getSizeTArg(const char *ptr, size_t *val, size_t min = 0,
-                        size_t max = SIZE_MAX)
-{
+// String to unsigned int, returns -1 if it fails
+static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
+                        size_t max = SIZE_MAX) {
     if (!ptr) {
         return false;
     }
 
-    char *endp;
+    char* endp;
     errno = 0;
     size_t ret = (size_t)strtoll(ptr, &endp, 0);
 
@@ -461,31 +460,29 @@
     return true;
 }
 
-static void logcat_panic(enum helpType showHelp, const char *fmt, ...)
-{
-    va_list  args;
+static void logcat_panic(enum helpType showHelp, const char* fmt, ...) {
+    va_list args;
     va_start(args, fmt);
-    vfprintf(stderr, fmt,  args);
+    vfprintf(stderr, fmt, args);
     va_end(args);
 
     switch (showHelp) {
-    case HELP_TRUE:
-       show_help(getprogname());
-       break;
-    case HELP_FORMAT:
-       show_format_help();
-       break;
-    case HELP_FALSE:
-    default:
-      break;
+        case HELP_TRUE:
+            show_help(getprogname());
+            break;
+        case HELP_FORMAT:
+            show_format_help();
+            break;
+        case HELP_FALSE:
+        default:
+            break;
     }
 
     exit(EXIT_FAILURE);
 }
 
-static char *parseTime(log_time &t, const char *cp) {
-
-    char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
+static char* parseTime(log_time& t, const char* cp) {
+    char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
     if (ep) {
         return ep;
     }
@@ -497,14 +494,14 @@
 }
 
 // Find last logged line in <outputFileName>, or <outputFileName>.1
-static log_time lastLogTime(char *outputFileName) {
+static log_time lastLogTime(char* outputFileName) {
     log_time retval(log_time::EPOCH);
     if (!outputFileName) {
         return retval;
     }
 
     std::string directory;
-    char *file = strrchr(outputFileName, '/');
+    char* file = strrchr(outputFileName, '/');
     if (!file) {
         directory = ".";
         file = outputFileName;
@@ -515,8 +512,8 @@
         ++file;
     }
 
-    std::unique_ptr<DIR, int(*)(DIR*)>
-            dir(opendir(directory.c_str()), closedir);
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
+                                            closedir);
     if (!dir.get()) {
         return retval;
     }
@@ -525,14 +522,12 @@
 
     size_t len = strlen(file);
     log_time modulo(0, NS_PER_SEC);
-    struct dirent *dp;
+    struct dirent* dp;
 
     while ((dp = readdir(dir.get())) != NULL) {
-        if ((dp->d_type != DT_REG) ||
-                (strncmp(dp->d_name, file, len) != 0) ||
-                (dp->d_name[len] &&
-                     ((dp->d_name[len] != '.') ||
-                         (strtoll(dp->d_name + 1, NULL, 10) != 1)))) {
+        if ((dp->d_type != DT_REG) || (strncmp(dp->d_name, file, len) != 0) ||
+            (dp->d_name[len] && ((dp->d_name[len] != '.') ||
+                                 (strtoll(dp->d_name + 1, NULL, 10) != 1)))) {
             continue;
         }
 
@@ -547,7 +542,7 @@
         bool found = false;
         for (const auto& line : android::base::Split(file, "\n")) {
             log_time t(log_time::EPOCH);
-            char *ep = parseTime(t, line.c_str());
+            char* ep = parseTime(t, line.c_str());
             if (!ep || (*ep != ' ')) {
                 continue;
             }
@@ -581,22 +576,20 @@
     return retval;
 }
 
-} /* namespace android */
+}  // namespace android
 
-void reportErrorName(const char **current,
-                     const char* name,
+void reportErrorName(const char** current, const char* name,
                      bool blockSecurity) {
     if (*current) {
-       return;
+        return;
     }
     if (blockSecurity && (android_name_to_log_id(name) == LOG_ID_SECURITY)) {
-       return;
+        return;
     }
     *current = name;
 }
 
-int main(int argc, char **argv)
-{
+int main(int argc, char** argv) {
     using namespace android;
     int err;
     int hasSetLogFormat = 0;
@@ -607,13 +600,13 @@
     bool printStatistics = false;
     bool printDividers = false;
     unsigned long setLogSize = 0;
-    char *setPruneList = NULL;
-    char *setId = NULL;
+    char* setPruneList = NULL;
+    char* setId = NULL;
     int mode = ANDROID_LOG_RDONLY;
-    const char *forceFilters = NULL;
+    const char* forceFilters = NULL;
     log_device_t* devices = NULL;
     log_device_t* dev;
-    struct logger_list *logger_list;
+    struct logger_list* logger_list;
     size_t tail_lines = 0;
     log_time tail_time(log_time::EPOCH);
     size_t pid = 0;
@@ -638,6 +631,7 @@
         static const char id_str[] = "id";
         static const char wrap_str[] = "wrap";
         static const char print_str[] = "print";
+        // clang-format off
         static const struct option long_options[] = {
           { "binary",        no_argument,       NULL,   'B' },
           { "buffer",        required_argument, NULL,   'b' },
@@ -667,9 +661,11 @@
           { wrap_str,        optional_argument, NULL,   0 },
           { NULL,            0,                 NULL,   0 }
         };
+        // clang-format on
 
-        ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
-                          long_options, &option_index);
+        ret = getopt_long(argc, argv,
+                          ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
+                          &option_index);
 
         if (ret < 0) {
             break;
@@ -687,8 +683,7 @@
                     break;
                 }
                 if (long_options[option_index].name == wrap_str) {
-                    mode |= ANDROID_LOG_WRAP |
-                            ANDROID_LOG_RDONLY |
+                    mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
                             ANDROID_LOG_NONBLOCK;
                     // ToDo: implement API that supports setting a wrap timeout
                     size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
@@ -716,37 +711,38 @@
                     setId = optarg && optarg[0] ? optarg : NULL;
                     break;
                 }
-            break;
+                break;
 
             case 's':
                 // default to all silent
                 android_log_addFilterRule(g_logformat, "*:s");
-            break;
+                break;
 
             case 'c':
                 clearLog = true;
                 mode |= ANDROID_LOG_WRONLY;
-            break;
+                break;
 
             case 'L':
-                mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK;
-            break;
+                mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
+                        ANDROID_LOG_NONBLOCK;
+                break;
 
             case 'd':
                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
-            break;
+                break;
 
             case 't':
                 got_t = true;
                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
-                /* FALLTHRU */
+            // FALLTHRU
             case 'T':
                 if (strspn(optarg, "0123456789") != strlen(optarg)) {
-                    char *cp = parseTime(tail_time, optarg);
+                    char* cp = parseTime(tail_time, optarg);
                     if (!cp) {
                         logcat_panic(HELP_FALSE,
-                                     "-%c \"%s\" not in time format\n",
-                                     ret, optarg);
+                                     "-%c \"%s\" not in time format\n", ret,
+                                     optarg);
                     }
                     if (*cp) {
                         char c = *cp;
@@ -759,100 +755,98 @@
                 } else {
                     if (!getSizeTArg(optarg, &tail_lines, 1)) {
                         fprintf(stderr,
-                                "WARNING: -%c %s invalid, setting to 1\n",
-                                ret, optarg);
+                                "WARNING: -%c %s invalid, setting to 1\n", ret,
+                                optarg);
                         tail_lines = 1;
                     }
                 }
-            break;
+                break;
 
             case 'D':
                 printDividers = true;
-            break;
+                break;
 
             case 'e':
                 g_regex = new pcrecpp::RE(optarg);
-            break;
+                break;
 
             case 'm': {
-                char *end = NULL;
+                char* end = NULL;
                 if (!getSizeTArg(optarg, &g_maxCount)) {
-                    logcat_panic(HELP_FALSE, "-%c \"%s\" isn't an "
-                                 "integer greater than zero\n", ret, optarg);
+                    logcat_panic(
+                        HELP_FALSE,
+                        "-%c \"%s\" isn't an integer greater than zero\n", ret,
+                        optarg);
                 }
-            }
-            break;
+            } break;
 
             case 'g':
                 if (!optarg) {
                     getLogSize = true;
                     break;
                 }
-                // FALLTHRU
+            // FALLTHRU
 
             case 'G': {
-                char *cp;
+                char* cp;
                 if (strtoll(optarg, &cp, 0) > 0) {
                     setLogSize = strtoll(optarg, &cp, 0);
                 } else {
                     setLogSize = 0;
                 }
 
-                switch(*cp) {
-                case 'g':
-                case 'G':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case 'm':
-                case 'M':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case 'k':
-                case 'K':
-                    setLogSize *= 1024;
-                /* FALLTHRU */
-                case '\0':
-                break;
+                switch (*cp) {
+                    case 'g':
+                    case 'G':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case 'm':
+                    case 'M':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case 'k':
+                    case 'K':
+                        setLogSize *= 1024;
+                    // FALLTHRU
+                    case '\0':
+                        break;
 
-                default:
-                    setLogSize = 0;
+                    default:
+                        setLogSize = 0;
                 }
 
                 if (!setLogSize) {
-                    fprintf(stderr, "ERROR: -G <num><multiplier>\n");
-                    return EXIT_FAILURE;
+                    logcat_panic(HELP_FALSE, "ERROR: -G <num><multiplier>\n");
                 }
-            }
-            break;
+            } break;
 
             case 'p':
                 if (!optarg) {
                     getPruneList = true;
                     break;
                 }
-                // FALLTHRU
+            // FALLTHRU
 
             case 'P':
                 setPruneList = optarg;
-            break;
+                break;
 
             case 'b': {
                 unsigned idMask = 0;
                 while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
                     if (strcmp(optarg, "default") == 0) {
-                        idMask |= (1 << LOG_ID_MAIN) |
-                                  (1 << LOG_ID_SYSTEM) |
+                        idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
                                   (1 << LOG_ID_CRASH);
                     } else if (strcmp(optarg, "all") == 0) {
                         allSelected = true;
                         idMask = (unsigned)-1;
                     } else {
                         log_id_t log_id = android_name_to_log_id(optarg);
-                        const char *name = android_log_id_to_name(log_id);
+                        const char* name = android_log_id_to_name(log_id);
 
                         if (strcmp(name, optarg) != 0) {
-                            logcat_panic(HELP_TRUE,
-                                         "unknown buffer %s\n", optarg);
+                            logcat_panic(HELP_TRUE, "unknown buffer %s\n",
+                                         optarg);
                         }
                         if (log_id == LOG_ID_SECURITY) allSelected = false;
                         idMask |= (1 << log_id);
@@ -861,7 +855,7 @@
                 }
 
                 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
-                    const char *name = android_log_id_to_name((log_id_t)i);
+                    const char* name = android_log_id_to_name((log_id_t)i);
                     log_id_t log_id = android_name_to_log_id(name);
 
                     if (log_id != (log_id_t)i) {
@@ -885,8 +879,8 @@
                         continue;
                     }
 
-                    bool binary = !strcmp(name, "events") ||
-                                  !strcmp(name, "security");
+                    bool binary =
+                        !strcmp(name, "events") || !strcmp(name, "security");
                     log_device_t* d = new log_device_t(name, binary);
 
                     if (dev) {
@@ -897,12 +891,11 @@
                     }
                     g_devCount++;
                 }
-            }
-            break;
+            } break;
 
             case 'B':
                 g_printBinary = 1;
-            break;
+                break;
 
             case 'f':
                 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
@@ -910,21 +903,21 @@
                 }
                 // redirect output to a file
                 g_outputFileName = optarg;
-            break;
+                break;
 
             case 'r':
                 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
-                    logcat_panic(HELP_TRUE,
-                                 "Invalid parameter \"%s\" to -r\n", optarg);
+                    logcat_panic(HELP_TRUE, "Invalid parameter \"%s\" to -r\n",
+                                 optarg);
                 }
-            break;
+                break;
 
             case 'n':
                 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
-                    logcat_panic(HELP_TRUE,
-                                 "Invalid parameter \"%s\" to -n\n", optarg);
+                    logcat_panic(HELP_TRUE, "Invalid parameter \"%s\" to -n\n",
+                                 optarg);
                 }
-            break;
+                break;
 
             case 'v':
                 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
@@ -937,26 +930,23 @@
                                  "Invalid parameter \"%s\" to -v\n", optarg);
                 }
                 hasSetLogFormat |= err;
-            break;
+                break;
 
             case 'Q':
-                /* this is a *hidden* option used to start a version of logcat                 */
-                /* in an emulated device only. it basically looks for androidboot.logcat=      */
-                /* on the kernel command line. If something is found, it extracts a log filter */
-                /* and uses it to run the program. If nothing is found, the program should     */
-                /* quit immediately                                                            */
-#define  KERNEL_OPTION  "androidboot.logcat="
-#define  CONSOLE_OPTION "androidboot.console="
+#define KERNEL_OPTION "androidboot.logcat="
+#define CONSOLE_OPTION "androidboot.console="
+                // This is a *hidden* option used to start a version of logcat
+                // in an emulated device only.  It basically looks for
+                // androidboot.logcat= on the kernel command line.  If
+                // something is found, it extracts a log filter and uses it to
+                // run the program.  If nothing is found, the program should
+                // quit immediately.
                 {
-                    int          fd;
-                    char*        logcat;
-                    char*        console;
-                    int          force_exit = 1;
-                    static char  cmdline[1024];
+                    static char cmdline[1024];
 
-                    fd = open("/proc/cmdline", O_RDONLY);
+                    int fd = open("/proc/cmdline", O_RDONLY);
                     if (fd >= 0) {
-                        int  n = read(fd, cmdline, sizeof(cmdline)-1 );
+                        int n = read(fd, cmdline, sizeof(cmdline) - 1);
                         if (n < 0) n = 0;
                         cmdline[n] = 0;
                         close(fd);
@@ -964,39 +954,39 @@
                         cmdline[0] = 0;
                     }
 
-                    logcat  = strstr( cmdline, KERNEL_OPTION );
-                    console = strstr( cmdline, CONSOLE_OPTION );
+                    char* logcat = strstr(cmdline, KERNEL_OPTION);
+                    char* console = strstr(cmdline, CONSOLE_OPTION);
+                    bool force_exit = true;
                     if (logcat != NULL) {
-                        char*  p = logcat + sizeof(KERNEL_OPTION)-1;;
-                        char*  q = strpbrk( p, " \t\n\r" );;
+                        char* p = logcat + sizeof(KERNEL_OPTION) - 1;
+                        char* q = strpbrk(p, " \t\n\r");
 
-                        if (q != NULL)
-                            *q = 0;
+                        if (q != NULL) *q = 0;
 
                         forceFilters = p;
-                        force_exit   = 0;
+                        force_exit = false;
                     }
-                    /* if nothing found or invalid filters, exit quietly */
-                    if (force_exit) {
-                        return EXIT_SUCCESS;
-                    }
+                    // if nothing found or invalid filters, exit quietly
+                    if (force_exit) return EXIT_SUCCESS;
 
-                    /* redirect our output to the emulator console */
+                    // redirect our output to the emulator console
                     if (console) {
-                        char*  p = console + sizeof(CONSOLE_OPTION)-1;
-                        char*  q = strpbrk( p, " \t\n\r" );
-                        char   devname[64];
-                        int    len;
+                        char* p = console + sizeof(CONSOLE_OPTION) - 1;
+                        char* q = strpbrk(p, " \t\n\r");
+                        char devname[64];
+                        int len;
 
                         if (q != NULL) {
                             len = q - p;
-                        } else
+                        } else {
                             len = strlen(p);
+                        }
 
-                        len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
+                        len = snprintf(devname, sizeof(devname), "/dev/%.*s",
+                                       len, p);
                         fprintf(stderr, "logcat using %s (%d)\n", devname, len);
                         if (len < (int)sizeof(devname)) {
-                            fd = open( devname, O_WRONLY );
+                            fd = open(devname, O_WRONLY);
                             if (fd >= 0) {
                                 dup2(fd, 1);
                                 dup2(fd, 2);
@@ -1012,13 +1002,12 @@
                 break;
 
             case ':':
-                logcat_panic(HELP_TRUE,
-                             "Option -%c needs an argument\n", optopt);
+                logcat_panic(HELP_TRUE, "Option -%c needs an argument\n",
+                             optopt);
                 break;
 
             default:
-                logcat_panic(HELP_TRUE,
-                             "Unrecognized Option %c\n", optopt);
+                logcat_panic(HELP_TRUE, "Unrecognized Option %c\n", optopt);
                 break;
         }
     }
@@ -1030,10 +1019,12 @@
     if (g_printItAnyways && (!g_regex || !g_maxCount)) {
         // One day it would be nice if --print -v color and --regex <expr>
         // could play with each other and show regex highlighted content.
+        // clang-format off
         fprintf(stderr, "WARNING: "
                             "--print ignored, to be used in combination with\n"
                         "         "
                             "--regex <expr> and --max-count <N>\n");
+        // clang-format on
         g_printItAnyways = false;
     }
 
@@ -1059,11 +1050,12 @@
             logcat_panic(HELP_TRUE, "--id='%s' requires -f as well\n", setId);
         }
 
-        std::string file_name = android::base::StringPrintf("%s.id", g_outputFileName);
+        std::string file_name =
+            android::base::StringPrintf("%s.id", g_outputFileName);
         std::string file;
         bool file_ok = android::base::ReadFileToString(file_name, &file);
-        android::base::WriteStringToFile(setId, file_name,
-                                         S_IRUSR | S_IWUSR, getuid(), getgid());
+        android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
+                                         getuid(), getgid());
         if (!file_ok || (file.compare(setId) == 0)) {
             setId = NULL;
         }
@@ -1076,7 +1068,7 @@
             err = setLogFormat(logFormat);
             if (err < 0) {
                 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
-                                    logFormat);
+                        logFormat);
             }
         } else {
             setLogFormat("threadtime");
@@ -1091,24 +1083,24 @@
         }
     } else if (argc == optind) {
         // Add from environment variable
-        char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
+        char* env_tags_orig = getenv("ANDROID_LOG_TAGS");
 
         if (env_tags_orig != NULL) {
             err = android_log_addFilterString(g_logformat, env_tags_orig);
 
             if (err < 0) {
                 logcat_panic(HELP_TRUE,
-                            "Invalid filter expression in ANDROID_LOG_TAGS\n");
+                             "Invalid filter expression in ANDROID_LOG_TAGS\n");
             }
         }
     } else {
         // Add from commandline
-        for (int i = optind ; i < argc ; i++) {
+        for (int i = optind; i < argc; i++) {
             err = android_log_addFilterString(g_logformat, argv[i]);
 
             if (err < 0) {
-                logcat_panic(HELP_TRUE,
-                             "Invalid filter expression '%s'\n", argv[i]);
+                logcat_panic(HELP_TRUE, "Invalid filter expression '%s'\n",
+                             argv[i]);
             }
         }
     }
@@ -1119,10 +1111,10 @@
     } else {
         logger_list = android_logger_list_alloc(mode, tail_lines, pid);
     }
-    const char *openDeviceFail = NULL;
-    const char *clearFail = NULL;
-    const char *setSizeFail = NULL;
-    const char *getSizeFail = NULL;
+    const char* openDeviceFail = NULL;
+    const char* clearFail = NULL;
+    const char* setSizeFail = NULL;
+    const char* getSizeFail = NULL;
     // We have three orthogonal actions below to clear, set log size and
     // get log size. All sharing the same iteration loop.
     while (dev) {
@@ -1138,16 +1130,20 @@
         if (clearLog || setId) {
             if (g_outputFileName) {
                 int maxRotationCountDigits =
-                    (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+                    (g_maxRotatedLogs > 0)
+                        ? (int)(floor(log10(g_maxRotatedLogs) + 1))
+                        : 0;
 
-                for (int i = g_maxRotatedLogs ; i >= 0 ; --i) {
+                for (int i = g_maxRotatedLogs; i >= 0; --i) {
                     std::string file;
 
                     if (i == 0) {
-                        file = android::base::StringPrintf("%s", g_outputFileName);
+                        file =
+                            android::base::StringPrintf("%s", g_outputFileName);
                     } else {
-                        file = android::base::StringPrintf("%s.%.*d",
-                            g_outputFileName, maxRotationCountDigits, i);
+                        file = android::base::StringPrintf(
+                            "%s.%.*d", g_outputFileName, maxRotationCountDigits,
+                            i);
                     }
 
                     if (file.length() == 0) {
@@ -1181,12 +1177,12 @@
             if ((size < 0) || (readable < 0)) {
                 reportErrorName(&getSizeFail, dev->device, allSelected);
             } else {
-                printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
-                       "max entry is %db, max payload is %db\n", dev->device,
-                       value_of_size(size), multiplier_of_size(size),
-                       value_of_size(readable), multiplier_of_size(readable),
-                       (int) LOGGER_ENTRY_MAX_LEN,
-                       (int) LOGGER_ENTRY_MAX_PAYLOAD);
+                printf(
+                    "%s: ring buffer is %ld%sb (%ld%sb consumed),"
+                    " max entry is %db, max payload is %db\n",
+                    dev->device, value_of_size(size), multiplier_of_size(size),
+                    value_of_size(readable), multiplier_of_size(readable),
+                    (int)LOGGER_ENTRY_MAX_LEN, (int)LOGGER_ENTRY_MAX_PAYLOAD);
             }
         }
 
@@ -1194,27 +1190,26 @@
     }
     // report any errors in the above loop and exit
     if (openDeviceFail) {
-        logcat_panic(HELP_FALSE,
-                     "Unable to open log device '%s'\n", openDeviceFail);
+        logcat_panic(HELP_FALSE, "Unable to open log device '%s'\n",
+                     openDeviceFail);
     }
     if (clearFail) {
-        logcat_panic(HELP_FALSE,
-                     "failed to clear the '%s' log\n", clearFail);
+        logcat_panic(HELP_FALSE, "failed to clear the '%s' log\n", clearFail);
     }
     if (setSizeFail) {
-        logcat_panic(HELP_FALSE,
-                     "failed to set the '%s' log size\n", setSizeFail);
+        logcat_panic(HELP_FALSE, "failed to set the '%s' log size\n",
+                     setSizeFail);
     }
     if (getSizeFail) {
-        logcat_panic(HELP_FALSE,
-                     "failed to get the readable '%s' log size", getSizeFail);
+        logcat_panic(HELP_FALSE, "failed to get the readable '%s' log size",
+                     getSizeFail);
     }
 
     if (setPruneList) {
         size_t len = strlen(setPruneList);
-        /*extra 32 bytes are needed by  android_logger_set_prune_list */
+        // extra 32 bytes are needed by android_logger_set_prune_list
         size_t bLen = len + 32;
-        char *buf = NULL;
+        char* buf = NULL;
         if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
             buf[len] = '\0';
             if (android_logger_set_prune_list(logger_list, buf, bLen)) {
@@ -1224,23 +1219,23 @@
         } else {
             logcat_panic(HELP_FALSE, "failed to set the prune list (alloc)");
         }
+        return EXIT_SUCCESS;
     }
 
     if (printStatistics || getPruneList) {
         size_t len = 8192;
-        char *buf;
+        char* buf;
 
-        for (int retry = 32;
-                (retry >= 0) && ((buf = new char [len]));
-                delete [] buf, buf = NULL, --retry) {
+        for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
+             delete[] buf, buf = NULL, --retry) {
             if (getPruneList) {
                 android_logger_get_prune_list(logger_list, buf, len);
             } else {
                 android_logger_get_statistics(logger_list, buf, len);
             }
-            buf[len-1] = '\0';
+            buf[len - 1] = '\0';
             if (atol(buf) < 3) {
-                delete [] buf;
+                delete[] buf;
                 buf = NULL;
                 break;
             }
@@ -1257,7 +1252,7 @@
         }
 
         // remove trailing FF
-        char *cp = buf + len - 1;
+        char* cp = buf + len - 1;
         *cp = '\0';
         bool truncated = *--cp != '\f';
         if (!truncated) {
@@ -1276,25 +1271,19 @@
         }
 
         printf("%s", cp);
-        delete [] buf;
+        delete[] buf;
         return EXIT_SUCCESS;
     }
 
-    if (getLogSize) {
-        return EXIT_SUCCESS;
-    }
-    if (setLogSize || setPruneList) {
-        return EXIT_SUCCESS;
-    }
-    if (clearLog) {
+    if (getLogSize || setLogSize || clearLog) {
         return EXIT_SUCCESS;
     }
 
     setupOutputAndSchedulingPolicy((mode & ANDROID_LOG_NONBLOCK) == 0);
 
-    //LOG_EVENT_INT(10, 12345);
-    //LOG_EVENT_LONG(11, 0x1122334455667788LL);
-    //LOG_EVENT_STRING(0, "whassup, doc?");
+    // LOG_EVENT_INT(10, 12345);
+    // LOG_EVENT_LONG(11, 0x1122334455667788LL);
+    // LOG_EVENT_STRING(0, "whassup, doc?");
 
     dev = NULL;
     log_device_t unexpected("unexpected", false);
@@ -1328,7 +1317,7 @@
             }
         }
         if (!d) {
-            g_devCount = 2; // set to Multiple
+            g_devCount = 2;  // set to Multiple
             d = &unexpected;
             d->binary = log_msg.id() == LOG_ID_EVENTS;
         }
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index 081bf92..a12524c 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -39,30 +39,31 @@
 // non-syscall libs. Since we are only using this in the emergency of
 // a signal to stuff a terminating code into the logs, we will spin rather
 // than try a usleep.
-#define LOG_FAILURE_RETRY(exp) ({  \
-    typeof (exp) _rc;              \
-    do {                           \
-        _rc = (exp);               \
-    } while (((_rc == -1)          \
-           && ((errno == EINTR)    \
-            || (errno == EAGAIN))) \
-          || (_rc == -EINTR)       \
-          || (_rc == -EAGAIN));    \
-    _rc; })
+#define LOG_FAILURE_RETRY(exp)                                               \
+    ({                                                                       \
+        typeof(exp) _rc;                                                     \
+        do {                                                                 \
+            _rc = (exp);                                                     \
+        } while (((_rc == -1) && ((errno == EINTR) || (errno == EAGAIN))) || \
+                 (_rc == -EINTR) || (_rc == -EAGAIN));                       \
+        _rc;                                                                 \
+    })
 
 static const char begin[] = "--------- beginning of ";
 
 TEST(logcat, buckets) {
-    FILE *fp;
+    FILE* fp;
 
 #undef LOG_TAG
 #define LOG_TAG "inject"
     RLOGE("logcat.buckets");
     sleep(1);
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -b radio -b events -b system -b main -d 2>/dev/null",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp =
+             popen("logcat -b radio -b events -b system -b main -d 2>/dev/null",
+                   "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -71,7 +72,7 @@
 
     while (fgets(buffer, sizeof(buffer), fp)) {
         if (!strncmp(begin, buffer, sizeof(begin) - 1)) {
-            while (char *cp = strrchr(buffer, '\n')) {
+            while (char* cp = strrchr(buffer, '\n')) {
                 *cp = '\0';
             }
             log_id_t id = android_name_to_log_id(buffer + sizeof(begin) - 1);
@@ -88,11 +89,12 @@
 }
 
 TEST(logcat, event_tag_filter) {
-    FILE *fp;
+    FILE* fp;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -b events -d -s auditd am_proc_start am_pss am_proc_bound dvm_lock_sample am_wtf 2>/dev/null",
-      "r")));
+    ASSERT_TRUE(NULL != (fp = popen("logcat -b events -d -s auditd "
+                                    "am_proc_start am_pss am_proc_bound "
+                                    "dvm_lock_sample am_wtf 2>/dev/null",
+                                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -115,7 +117,7 @@
     static const size_t retry = 4;
     size_t errors = retry;
     size_t num = 0;
-    for(;;) {
+    for (;;) {
         log_time ts(CLOCK_MONOTONIC);
         if (__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) >= 0) {
             if (++num >= (size_t)count) {
@@ -124,7 +126,7 @@
                 return num;
             }
             errors = retry;
-            usleep(100); // ~32 per timer tick, we are a spammer regardless
+            usleep(100);  // ~32 per timer tick, we are a spammer regardless
         } else if (--errors <= 0) {
             return num;
         }
@@ -134,22 +136,21 @@
 }
 
 TEST(logcat, year) {
-
     if (android_log_clockid() == CLOCK_MONOTONIC) {
         fprintf(stderr, "Skipping test, logd is monotonic time\n");
         return;
     }
 
     int count;
-    int tries = 3; // in case run too soon after system start or buffer clear
+    int tries = 3;  // in case run too soon after system start or buffer clear
 
     do {
-        FILE *fp;
+        FILE* fp;
 
         char needle[32];
         time_t now;
         time(&now);
-        struct tm *ptm;
+        struct tm* ptm;
 #if !defined(_WIN32)
         struct tm tmBuf;
         ptm = localtime_r(&now, &tmBuf);
@@ -158,9 +159,9 @@
 #endif
         strftime(needle, sizeof(needle), "[ %Y-", ptm);
 
-        ASSERT_TRUE(NULL != (fp = popen(
-          "logcat -v long -v year -b all -t 3 2>/dev/null",
-          "r")));
+        ASSERT_TRUE(
+            NULL !=
+            (fp = popen("logcat -v long -v year -b all -t 3 2>/dev/null", "r")));
 
         char buffer[BIG_BUFFER];
 
@@ -179,21 +180,21 @@
 }
 
 // Return a pointer to each null terminated -v long time field.
-char *fgetLongTime(char *buffer, size_t buflen, FILE *fp) {
+static char* fgetLongTime(char* buffer, size_t buflen, FILE* fp) {
     while (fgets(buffer, buflen, fp)) {
-        char *cp = buffer;
+        char* cp = buffer;
         if (*cp != '[') {
             continue;
         }
         while (*++cp == ' ') {
             ;
         }
-        char *ep = cp;
+        char* ep = cp;
         while (isdigit(*ep)) {
             ++ep;
         }
         if ((*ep != '-') && (*ep != '.')) {
-           continue;
+            continue;
         }
         // Find PID field
         while (((ep = strchr(ep, ':'))) && (*++ep != ' ')) {
@@ -211,21 +212,20 @@
 }
 
 TEST(logcat, tz) {
-
     if (android_log_clockid() == CLOCK_MONOTONIC) {
         fprintf(stderr, "Skipping test, logd is monotonic time\n");
         return;
     }
 
-    int tries = 4; // in case run too soon after system start or buffer clear
+    int tries = 4;  // in case run too soon after system start or buffer clear
     int count;
 
     do {
-        FILE *fp;
+        FILE* fp;
 
-        ASSERT_TRUE(NULL != (fp = popen(
-          "logcat -v long -v America/Los_Angeles -b all -t 3 2>/dev/null",
-          "r")));
+        ASSERT_TRUE(NULL != (fp = popen("logcat -v long -v America/Los_Angeles "
+                                        "-b all -t 3 2>/dev/null",
+                                        "r")));
 
         char buffer[BIG_BUFFER];
 
@@ -247,11 +247,11 @@
 }
 
 TEST(logcat, ntz) {
-    FILE *fp;
+    FILE* fp;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v long -v America/Los_Angeles -v zone -b all -t 3 2>/dev/null",
-      "r")));
+    ASSERT_TRUE(NULL != (fp = popen("logcat -v long -v America/Los_Angeles -v "
+                                    "zone -b all -t 3 2>/dev/null",
+                                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -268,8 +268,8 @@
     ASSERT_EQ(0, count);
 }
 
-void do_tail(int num) {
-    int tries = 4; // in case run too soon after system start or buffer clear
+static void do_tail(int num) {
+    int tries = 4;  // in case run too soon after system start or buffer clear
     int count;
 
     if (num > 10) ++tries;
@@ -280,7 +280,7 @@
         snprintf(buffer, sizeof(buffer),
                  "logcat -v long -b all -t %d 2>/dev/null", num);
 
-        FILE *fp;
+        FILE* fp;
         ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
 
         count = 0;
@@ -313,17 +313,17 @@
 }
 
 TEST(logcat, tail_time) {
-    FILE *fp;
+    FILE* fp;
     int count;
     char buffer[BIG_BUFFER];
-    char *last_timestamp = NULL;
+    char* last_timestamp = NULL;
     // Hard to predict 100% if first (overlap) or second line will match.
     // -v nsec will in a substantial majority be the second line.
-    char *first_timestamp = NULL;
-    char *second_timestamp = NULL;
-    char *input;
+    char* first_timestamp = NULL;
+    char* second_timestamp = NULL;
+    char* input;
 
-    int tries = 4; // in case run too soon after system start or buffer clear
+    int tries = 4;  // in case run too soon after system start or buffer clear
 
     do {
         ASSERT_TRUE(NULL != (fp = popen("logcat"
@@ -331,7 +331,8 @@
                                         " -v nsec"
                                         " -b all"
                                         " -t 10"
-                                        " 2>&1", "r")));
+                                        " 2>&1",
+                                        "r")));
         count = 0;
 
         while ((input = fgetLongTime(buffer, sizeof(buffer), fp))) {
@@ -348,24 +349,25 @@
 
     } while ((count < 10) && --tries && inject(10 - count));
 
-    EXPECT_EQ(10, count); // We want _some_ history, too small, falses below
+    EXPECT_EQ(10, count);  // We want _some_ history, too small, falses below
     EXPECT_TRUE(last_timestamp != NULL);
     EXPECT_TRUE(first_timestamp != NULL);
     EXPECT_TRUE(second_timestamp != NULL);
 
-    snprintf(buffer, sizeof(buffer), "logcat"
-                                     " -v long"
-                                     " -v nsec"
-                                     " -b all"
-                                     " -t '%s'"
-                                     " 2>&1",
-                                     first_timestamp);
+    snprintf(buffer, sizeof(buffer),
+             "logcat"
+             " -v long"
+             " -v nsec"
+             " -b all"
+             " -t '%s'"
+             " 2>&1",
+             first_timestamp);
     ASSERT_TRUE(NULL != (fp = popen(buffer, "r")));
 
     int second_count = 0;
     int last_timestamp_count = -1;
 
-    --count; // One less unless we match the first_timestamp
+    --count;  // One less unless we match the first_timestamp
     bool found = false;
     while ((input = fgetLongTime(buffer, sizeof(buffer), fp))) {
         ++second_count;
@@ -381,9 +383,8 @@
             found = !strcmp(input, first_timestamp);
             if (found) {
                 ++count;
-                GTEST_LOG_(INFO) << "input = first("
-                                 << first_timestamp
-                                 << ")\n";
+                GTEST_LOG_(INFO)
+                    << "input = first(" << first_timestamp << ")\n";
             }
             free(first_timestamp);
             first_timestamp = NULL;
@@ -391,11 +392,8 @@
         if (second_timestamp) {
             found = found || !strcmp(input, second_timestamp);
             if (!found) {
-                GTEST_LOG_(INFO) << "input("
-                                 << input
-                                 << ") != second("
-                                 << second_timestamp
-                                 << ")\n";
+                GTEST_LOG_(INFO) << "input(" << input << ") != second("
+                                 << second_timestamp << ")\n";
             }
             free(second_timestamp);
             second_timestamp = NULL;
@@ -436,10 +434,10 @@
 
     ASSERT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
 
-    FILE *fp;
-    ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -v brief -b events -t 100 2>/dev/null",
-      "r")));
+    FILE* fp;
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("logcat -v brief -b events -t 100 2>/dev/null", "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -449,12 +447,12 @@
         int p;
         unsigned long long t;
 
-        if ((2 != sscanf(buffer, "I/[0]     ( %d): %llu", &p, &t))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0]     ( %d): %llu", &p, &t)) ||
+            (p != pid)) {
             continue;
         }
 
-        log_time tx((const char *) &t);
+        log_time tx((const char*)&t);
         if (ts == tx) {
             ++count;
         }
@@ -465,8 +463,8 @@
     ASSERT_EQ(1, count);
 }
 
-int get_groups(const char *cmd) {
-    FILE *fp;
+static int get_groups(const char* cmd) {
+    FILE* fp;
 
     // NB: crash log only available in user space
     EXPECT_TRUE(NULL != (fp = popen(cmd, "r")));
@@ -487,48 +485,48 @@
         size = consumed = max = payload = 0;
         // NB: crash log can be very small, not hit a Kb of consumed space
         //     doubly lucky we are not including it.
-        if (6 != sscanf(buffer, "%*s ring buffer is %d%2s (%d%2s consumed),"
-                                " max entry is %db, max payload is %db",
-                                &size, size_mult, &consumed, consumed_mult,
-                                &max, &payload)) {
+        if (6 != sscanf(buffer,
+                        "%*s ring buffer is %d%2s (%d%2s consumed),"
+                        " max entry is %db, max payload is %db",
+                        &size, size_mult, &consumed, consumed_mult, &max,
+                        &payload)) {
             fprintf(stderr, "WARNING: Parse error: %s", buffer);
             continue;
         }
         full_size = size;
-        switch(size_mult[0]) {
-        case 'G':
-            full_size *= 1024;
+        switch (size_mult[0]) {
+            case 'G':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'M':
-            full_size *= 1024;
+            case 'M':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'K':
-            full_size *= 1024;
+            case 'K':
+                full_size *= 1024;
             /* FALLTHRU */
-        case 'b':
-            break;
+            case 'b':
+                break;
         }
         full_consumed = consumed;
-        switch(consumed_mult[0]) {
-        case 'G':
-            full_consumed *= 1024;
+        switch (consumed_mult[0]) {
+            case 'G':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'M':
-            full_consumed *= 1024;
+            case 'M':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'K':
-            full_consumed *= 1024;
+            case 'K':
+                full_consumed *= 1024;
             /* FALLTHRU */
-        case 'b':
-            break;
+            case 'b':
+                break;
         }
         EXPECT_GT((full_size * 9) / 4, full_consumed);
         EXPECT_GT(full_size, max);
         EXPECT_GT(max, payload);
 
-        if ((((full_size * 9) / 4) >= full_consumed)
-         && (full_size > max)
-         && (max > payload)) {
+        if ((((full_size * 9) / 4) >= full_consumed) && (full_size > max) &&
+            (max > payload)) {
             ++count;
         }
     }
@@ -539,23 +537,25 @@
 }
 
 TEST(logcat, get_size) {
-    ASSERT_EQ(4, get_groups(
-      "logcat -v brief -b radio -b events -b system -b main -g 2>/dev/null"));
+    ASSERT_EQ(4, get_groups("logcat -v brief -b radio -b events -b system -b "
+                            "main -g 2>/dev/null"));
 }
 
 // duplicate test for get_size, but use comma-separated list of buffers
 TEST(logcat, multiple_buffer) {
-    ASSERT_EQ(4, get_groups(
-      "logcat -v brief -b radio,events,system,main -g 2>/dev/null"));
+    ASSERT_EQ(
+        4, get_groups(
+               "logcat -v brief -b radio,events,system,main -g 2>/dev/null"));
 }
 
 TEST(logcat, bad_buffer) {
-    ASSERT_EQ(0, get_groups(
-      "logcat -v brief -b radio,events,bogo,system,main -g 2>/dev/null"));
+    ASSERT_EQ(
+        0,
+        get_groups(
+            "logcat -v brief -b radio,events,bogo,system,main -g 2>/dev/null"));
 }
 
-static void caught_blocking(int signum)
-{
+static void caught_blocking(int signum) {
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
     v += getpid() & 0xFFFF;
@@ -565,7 +565,7 @@
 }
 
 TEST(logcat, blocking) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xDEADBEEFA55F0000ULL;
 
     pid_t pid = getpid();
@@ -576,10 +576,11 @@
 
     v &= 0xFFFFFFFFFFFAFFFFULL;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -v brief -b events 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -v brief -b events 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -590,7 +591,6 @@
     signal(SIGALRM, caught_blocking);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "DONE", 4)) {
             break;
         }
@@ -600,8 +600,7 @@
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -624,8 +623,7 @@
     EXPECT_EQ(1, signals);
 }
 
-static void caught_blocking_tail(int signum)
-{
+static void caught_blocking_tail(int signum) {
     unsigned long long v = 0xA55ADEADBEEF0000ULL;
 
     v += getpid() & 0xFFFF;
@@ -635,7 +633,7 @@
 }
 
 TEST(logcat, blocking_tail) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xA55FDEADBEEF0000ULL;
 
     pid_t pid = getpid();
@@ -646,10 +644,11 @@
 
     v &= 0xFFFAFFFFFFFFFFFFULL;
 
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -v brief -b events -T 5 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -v brief -b events -T 5 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -660,7 +659,6 @@
     signal(SIGALRM, caught_blocking_tail);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "DONE", 4)) {
             break;
         }
@@ -670,8 +668,7 @@
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -698,10 +695,9 @@
 
 // meant to be handed to ASSERT_FALSE / EXPECT_FALSE to expand the message
 static testing::AssertionResult IsFalse(int ret, const char* command) {
-    return ret ?
-        (testing::AssertionSuccess() <<
-            "ret=" << ret << " command=\"" << command << "\"") :
-        testing::AssertionFailure();
+    return ret ? (testing::AssertionSuccess()
+                  << "ret=" << ret << " command=\"" << command << "\"")
+               : testing::AssertionFailure();
 }
 
 TEST(logcat, logrotate) {
@@ -709,8 +705,9 @@
     char buf[sizeof(form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(buf, form)));
 
-    static const char comm[] = "logcat -b radio -b events -b system -b main"
-                                     " -d -f %s/log.txt -n 7 -r 1";
+    static const char comm[] =
+        "logcat -b radio -b events -b system -b main"
+        " -d -f %s/log.txt -n 7 -r 1";
     char command[sizeof(buf) + sizeof(comm)];
     snprintf(command, sizeof(command), comm, buf);
 
@@ -719,7 +716,7 @@
     if (!ret) {
         snprintf(command, sizeof(command), "ls -s %s 2>/dev/null", buf);
 
-        FILE *fp;
+        FILE* fp;
         EXPECT_TRUE(NULL != (fp = popen(command, "r")));
         if (fp) {
             char buffer[BIG_BUFFER];
@@ -731,7 +728,7 @@
                 char c;
 
                 if ((2 == sscanf(buffer, "%d log.tx%c", &num, &c)) &&
-                        (num <= 40)) {
+                    (num <= 40)) {
                     ++count;
                 } else if (strncmp(buffer, total, sizeof(total) - 1)) {
                     fprintf(stderr, "WARNING: Parse error: %s", buffer);
@@ -749,12 +746,14 @@
 }
 
 TEST(logcat, logrotate_suffix) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
-    static const char logcat_cmd[] = "logcat -b radio -b events -b system -b main"
-                                     " -d -f %s/log.txt -n 10 -r 1";
+    static const char logcat_cmd[] =
+        "logcat -b radio -b events -b system -b main"
+        " -d -f %s/log.txt -n 10 -r 1";
     char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd)];
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir);
 
@@ -763,7 +762,7 @@
     if (!ret) {
         snprintf(command, sizeof(command), "ls %s 2>/dev/null", tmp_out_dir);
 
-        FILE *fp;
+        FILE* fp;
         EXPECT_TRUE(NULL != (fp = popen(command, "r")));
         char buffer[BIG_BUFFER];
         int log_file_count = 0;
@@ -774,21 +773,24 @@
                 strlen(rotated_log_filename_prefix);
             static const char log_filename[] = "log.txt";
 
-            if (!strncmp(buffer, rotated_log_filename_prefix, rotated_log_filename_prefix_len)) {
-              // Rotated file should have form log.txt.##
-              char* rotated_log_filename_suffix = buffer + rotated_log_filename_prefix_len;
-              char* endptr;
-              const long int suffix_value = strtol(rotated_log_filename_suffix, &endptr, 10);
-              EXPECT_EQ(rotated_log_filename_suffix + 2, endptr);
-              EXPECT_LE(suffix_value, 10);
-              EXPECT_GT(suffix_value, 0);
-              ++log_file_count;
-              continue;
+            if (!strncmp(buffer, rotated_log_filename_prefix,
+                         rotated_log_filename_prefix_len)) {
+                // Rotated file should have form log.txt.##
+                char* rotated_log_filename_suffix =
+                    buffer + rotated_log_filename_prefix_len;
+                char* endptr;
+                const long int suffix_value =
+                    strtol(rotated_log_filename_suffix, &endptr, 10);
+                EXPECT_EQ(rotated_log_filename_suffix + 2, endptr);
+                EXPECT_LE(suffix_value, 10);
+                EXPECT_GT(suffix_value, 0);
+                ++log_file_count;
+                continue;
             }
 
             if (!strncmp(buffer, log_filename, strlen(log_filename))) {
-              ++log_file_count;
-              continue;
+                ++log_file_count;
+                continue;
             }
 
             fprintf(stderr, "ERROR: Unexpected file: %s", buffer);
@@ -802,12 +804,14 @@
 }
 
 TEST(logcat, logrotate_continue) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
     static const char log_filename[] = "log.txt";
-    static const char logcat_cmd[] = "logcat -b all -v nsec -d -f %s/%s -n 256 -r 1024";
+    static const char logcat_cmd[] =
+        "logcat -b all -v nsec -d -f %s/%s -n 256 -r 1024";
     static const char cleanup_cmd[] = "rm -rf %s";
     char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) + sizeof(log_filename)];
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir, log_filename);
@@ -819,7 +823,7 @@
         EXPECT_FALSE(IsFalse(system(command), command));
         return;
     }
-    FILE *fp;
+    FILE* fp;
     snprintf(command, sizeof(command), "%s/%s", tmp_out_dir, log_filename);
     EXPECT_TRUE(NULL != ((fp = fopen(command, "r"))));
     if (!fp) {
@@ -827,10 +831,11 @@
         EXPECT_FALSE(IsFalse(system(command), command));
         return;
     }
-    char *line = NULL;
-    char *last_line = NULL; // this line is allowed to stutter, one-line overlap
-    char *second_last_line = NULL; // should never stutter
-    char *first_line = NULL; // help diagnose failure?
+    char* line = NULL;
+    char* last_line =
+        NULL;  // this line is allowed to stutter, one-line overlap
+    char* second_last_line = NULL;  // should never stutter
+    char* first_line = NULL;        // help diagnose failure?
     size_t len = 0;
     while (getline(&line, &len, fp) != -1) {
         if (!first_line) {
@@ -869,7 +874,8 @@
         free(first_line);
         return;
     }
-    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                  closedir);
     EXPECT_NE(nullptr, dir);
     if (!dir) {
         snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
@@ -878,7 +884,7 @@
         free(first_line);
         return;
     }
-    struct dirent *entry;
+    struct dirent* entry;
     unsigned count = 0;
     while ((entry = readdir(dir.get()))) {
         if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -904,15 +910,15 @@
         unlink(command);
     }
     if (count > 1) {
-        char *brk = strpbrk(second_last_line, "\r\n");
+        char* brk = strpbrk(second_last_line, "\r\n");
         if (!brk) brk = second_last_line + strlen(second_last_line);
         fprintf(stderr, "\"%.*s\" occurred %u times\n",
-            (int)(brk - second_last_line), second_last_line, count);
+                (int)(brk - second_last_line), second_last_line, count);
         if (first_line) {
             brk = strpbrk(first_line, "\r\n");
             if (!brk) brk = first_line + strlen(first_line);
             fprintf(stderr, "\"%.*s\" was first line, fault?\n",
-                (int)(brk - first_line), first_line);
+                    (int)(brk - first_line), first_line);
         }
     }
     free(second_last_line);
@@ -923,7 +929,8 @@
 }
 
 TEST(logcat, logrotate_clear) {
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
@@ -932,12 +939,13 @@
     static const char logcat_cmd[] = "logcat -b all -d -f %s/%s -n %d -r 1";
     static const char clear_cmd[] = " -c";
     static const char cleanup_cmd[] = "rm -rf %s";
-    char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) + sizeof(log_filename) + sizeof(clear_cmd) + 32];
+    char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) +
+                 sizeof(log_filename) + sizeof(clear_cmd) + 32];
 
     // Run command with all data
     {
-        snprintf(command, sizeof(command) - sizeof(clear_cmd),
-                 logcat_cmd, tmp_out_dir, log_filename, num_val);
+        snprintf(command, sizeof(command) - sizeof(clear_cmd), logcat_cmd,
+                 tmp_out_dir, log_filename, num_val);
 
         int ret;
         EXPECT_FALSE(IsFalse(ret = system(command), command));
@@ -946,14 +954,15 @@
             EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                      closedir);
         EXPECT_NE(nullptr, dir);
         if (!dir) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
             EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        struct dirent *entry;
+        struct dirent* entry;
         unsigned count = 0;
         while ((entry = readdir(dir.get()))) {
             if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -976,14 +985,15 @@
             EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                      closedir);
         EXPECT_NE(nullptr, dir);
         if (!dir) {
             snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
             EXPECT_FALSE(IsFalse(system(command), command));
             return;
         }
-        struct dirent *entry;
+        struct dirent* entry;
         unsigned count = 0;
         while ((entry = readdir(dir.get()))) {
             if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -999,24 +1009,25 @@
     EXPECT_FALSE(IsFalse(system(command), command));
 }
 
-static int logrotate_count_id(const char *logcat_cmd, const char *tmp_out_dir) {
-
+static int logrotate_count_id(const char* logcat_cmd, const char* tmp_out_dir) {
     static const char log_filename[] = "log.txt";
-    char command[strlen(tmp_out_dir) + strlen(logcat_cmd) + strlen(log_filename) + 32];
+    char command[strlen(tmp_out_dir) + strlen(logcat_cmd) +
+                 strlen(log_filename) + 32];
 
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir, log_filename);
 
-    int ret;
-    EXPECT_FALSE(IsFalse(ret = system(command), command));
+    int ret = system(command);
     if (ret) {
+        fprintf(stderr, "system(\"%s\")=%d", command, ret);
         return -1;
     }
-    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
-    EXPECT_NE(nullptr, dir);
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir),
+                                                  closedir);
     if (!dir) {
+        fprintf(stderr, "opendir(\"%s\") failed", tmp_out_dir);
         return -1;
     }
-    struct dirent *entry;
+    struct dirent* entry;
     int count = 0;
     while ((entry = readdir(dir.get()))) {
         if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
@@ -1028,9 +1039,12 @@
 }
 
 TEST(logcat, logrotate_id) {
-    static const char logcat_cmd[] = "logcat -b all -d -f %s/%s -n 32 -r 1 --id=test";
-    static const char logcat_short_cmd[] = "logcat -b all -t 10 -f %s/%s -n 32 -r 1 --id=test";
-    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    static const char logcat_cmd[] =
+        "logcat -b all -d -f %s/%s -n 32 -r 1 --id=test";
+    static const char logcat_short_cmd[] =
+        "logcat -b all -t 10 -f %s/%s -n 32 -r 1 --id=test";
+    static const char tmp_out_dir_form[] =
+        "/data/local/tmp/logcat.logrotate.XXXXXX";
     static const char log_filename[] = "log.txt";
     char tmp_out_dir[strlen(tmp_out_dir_form) + 1];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
@@ -1047,19 +1061,21 @@
     unlink(id_file);
     EXPECT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
 
-    FILE *fp = fopen(id_file, "w");
+    FILE* fp = fopen(id_file, "w");
     if (fp) {
         fprintf(fp, "not_a_test");
         fclose(fp);
     }
     if (getuid() != 0) {
-        chmod(id_file, 0); // API to preserve content even with signature change
+        chmod(id_file,
+              0);  // API to preserve content even with signature change
         ASSERT_EQ(34, logrotate_count_id(logcat_short_cmd, tmp_out_dir));
         chmod(id_file, 0600);
     }
 
     int new_signature;
-    EXPECT_LE(2, (new_signature = logrotate_count_id(logcat_short_cmd, tmp_out_dir)));
+    EXPECT_LE(
+        2, (new_signature = logrotate_count_id(logcat_short_cmd, tmp_out_dir)));
     EXPECT_GT(34, new_signature);
 
     static const char cleanup_cmd[] = "rm -rf %s";
@@ -1069,11 +1085,12 @@
 }
 
 TEST(logcat, logrotate_nodir) {
-    // expect logcat to error out on writing content and exit(1) for nodir
-    EXPECT_EQ(W_EXITCODE(1, 0),
-              system("logcat -b all -d"
-                     " -f /das/nein/gerfingerpoken/logcat/log.txt"
-                     " -n 256 -r 1024"));
+    // expect logcat to error out on writing content and not exit(0) for nodir
+    static const char command[] =
+        "logcat -b all -d"
+        " -f /das/nein/gerfingerpoken/logcat/log.txt"
+        " -n 256 -r 1024";
+    EXPECT_FALSE(IsFalse(0 == system(command), command));
 }
 
 static void caught_blocking_clear(int signum) {
@@ -1086,7 +1103,7 @@
 }
 
 TEST(logcat, blocking_clear) {
-    FILE *fp;
+    FILE* fp;
     unsigned long long v = 0xDEADBEEFA55C0000ULL;
 
     pid_t pid = getpid();
@@ -1095,12 +1112,13 @@
 
     // This test is racey; an event occurs between clear and dump.
     // We accept that we will get a false positive, but never a false negative.
-    ASSERT_TRUE(NULL != (fp = popen(
-      "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -b events -c 2>&1 ;"
-      " logcat -b events -g 2>&1 ;"
-      " logcat -v brief -b events 2>&1",
-      "r")));
+    ASSERT_TRUE(
+        NULL !=
+        (fp = popen("( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
+                    " logcat -b events -c 2>&1 ;"
+                    " logcat -b events -g 2>&1 ;"
+                    " logcat -v brief -b events 2>&1",
+                    "r")));
 
     char buffer[BIG_BUFFER];
 
@@ -1112,7 +1130,6 @@
     signal(SIGALRM, caught_blocking_clear);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-
         if (!strncmp(buffer, "clearLog: ", 10)) {
             fprintf(stderr, "WARNING: Test lacks permission to run :-(\n");
             count = signals = 1;
@@ -1126,37 +1143,38 @@
         int size, consumed, max, payload;
         char size_mult[3], consumed_mult[3];
         size = consumed = max = payload = 0;
-        if (6 == sscanf(buffer, "events: ring buffer is %d%2s (%d%2s consumed),"
-                                " max entry is %db, max payload is %db",
-                                &size, size_mult, &consumed, consumed_mult,
-                                &max, &payload)) {
+        if (6 == sscanf(buffer,
+                        "events: ring buffer is %d%2s (%d%2s consumed),"
+                        " max entry is %db, max payload is %db",
+                        &size, size_mult, &consumed, consumed_mult, &max,
+                        &payload)) {
             long full_size = size, full_consumed = consumed;
 
-            switch(size_mult[0]) {
-            case 'G':
-                full_size *= 1024;
+            switch (size_mult[0]) {
+                case 'G':
+                    full_size *= 1024;
                 /* FALLTHRU */
-            case 'M':
-                full_size *= 1024;
+                case 'M':
+                    full_size *= 1024;
                 /* FALLTHRU */
-            case 'K':
-                full_size *= 1024;
+                case 'K':
+                    full_size *= 1024;
                 /* FALLTHRU */
-            case 'b':
-                break;
+                case 'b':
+                    break;
             }
-            switch(consumed_mult[0]) {
-            case 'G':
-                full_consumed *= 1024;
+            switch (consumed_mult[0]) {
+                case 'G':
+                    full_consumed *= 1024;
                 /* FALLTHRU */
-            case 'M':
-                full_consumed *= 1024;
+                case 'M':
+                    full_consumed *= 1024;
                 /* FALLTHRU */
-            case 'K':
-                full_consumed *= 1024;
+                case 'K':
+                    full_consumed *= 1024;
                 /* FALLTHRU */
-            case 'b':
-                break;
+                case 'b':
+                    break;
             }
             EXPECT_GT(full_size, full_consumed);
             EXPECT_GT(full_size, max);
@@ -1172,8 +1190,7 @@
         int p;
         unsigned long long l;
 
-        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l))
-         || (p != pid)) {
+        if ((2 != sscanf(buffer, "I/[0] ( %u): %lld", &p, &l)) || (p != pid)) {
             continue;
         }
 
@@ -1200,8 +1217,8 @@
     EXPECT_EQ(1, signals);
 }
 
-static bool get_white_black(char **list) {
-    FILE *fp;
+static bool get_white_black(char** list) {
+    FILE* fp;
 
     fp = popen("logcat -p 2>/dev/null", "r");
     if (fp == NULL) {
@@ -1212,12 +1229,12 @@
     char buffer[BIG_BUFFER];
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        char *hold = *list;
-        char *buf = buffer;
+        char* hold = *list;
+        char* buf = buffer;
         while (isspace(*buf)) {
             ++buf;
         }
-        char *end = buf + strlen(buf);
+        char* end = buf + strlen(buf);
         while (isspace(*--end) && (end >= buf)) {
             *end = '\0';
         }
@@ -1235,8 +1252,8 @@
     return *list != NULL;
 }
 
-static bool set_white_black(const char *list) {
-    FILE *fp;
+static bool set_white_black(const char* list) {
+    FILE* fp;
 
     char buffer[BIG_BUFFER];
 
@@ -1248,11 +1265,11 @@
     }
 
     while (fgets(buffer, sizeof(buffer), fp)) {
-        char *buf = buffer;
+        char* buf = buffer;
         while (isspace(*buf)) {
             ++buf;
         }
-        char *end = buf + strlen(buf);
+        char* end = buf + strlen(buf);
         while ((end > buf) && isspace(*--end)) {
             *end = '\0';
         }
@@ -1267,8 +1284,8 @@
 }
 
 TEST(logcat, white_black_adjust) {
-    char *list = NULL;
-    char *adjust = NULL;
+    char* list = NULL;
+    char* adjust = NULL;
 
     get_white_black(&list);
 
@@ -1297,17 +1314,22 @@
 }
 
 TEST(logcat, regex) {
-    FILE *fp;
+    FILE* fp;
     int count = 0;
 
     char buffer[BIG_BUFFER];
 
-    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d -e logcat_test_a+b", getpid());
+    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d -e logcat_test_a+b",
+             getpid());
 
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_ab"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_b"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_aaaab"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_aaaa"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_ab"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test_b"));
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test",
+                                          "logcat_test_aaaab"));
+    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test",
+                                          "logcat_test_aaaa"));
 
     // Let the logs settle
     sleep(1);
@@ -1330,17 +1352,22 @@
 }
 
 TEST(logcat, maxcount) {
-    FILE *fp;
+    FILE* fp;
     int count = 0;
 
     char buffer[BIG_BUFFER];
 
-    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d --max-count 3", getpid());
+    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d --max-count 3",
+             getpid());
 
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
-    LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
+    LOG_FAILURE_RETRY(
+        __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
 
     // Let the logs settle
     sleep(1);
@@ -1367,8 +1394,18 @@
     ;
 
 static bool End_to_End(const char* tag, const char* fmt, ...) {
-    FILE *fp = popen("logcat -v brief -b events -v descriptive -t 100 2>/dev/null", "r");
-    if (!fp) return false;
+    FILE* fp = popen(
+        "logcat"
+        " -v brief"
+        " -b events"
+        " -v descriptive"
+        " -t 100"
+        " 2>/dev/null",
+        "r");
+    if (!fp) {
+        fprintf(stderr, "End_to_End: popen failed");
+        return false;
+    }
 
     char buffer[BIG_BUFFER];
     va_list ap;
@@ -1377,7 +1414,7 @@
     vsnprintf(buffer, sizeof(buffer), fmt, ap);
     va_end(ap);
 
-    char *str = NULL;
+    char* str = NULL;
     asprintf(&str, "I/%s ( %%d):%%c%s%%c", tag, buffer);
     std::string expect(str);
     free(str);
@@ -1405,6 +1442,8 @@
         // Help us pinpoint where things went wrong ...
         fprintf(stderr, "Closest match for\n    %s\n  is\n    %s",
                 expect.c_str(), lastMatch.c_str());
+    } else if (count > 1) {
+        fprintf(stderr, "Too many matches (%d) for %s\n", count, expect.c_str());
     }
 
     return count == 1;
@@ -1422,8 +1461,8 @@
         static const char theAnswer[] = "what is five by seven";
         ctx << theAnswer;
         ctx.write();
-        EXPECT_TRUE(End_to_End(hhgtg.tagStr,
-                               "to life the universe etc=%s", theAnswer));
+        EXPECT_TRUE(
+            End_to_End(hhgtg.tagStr, "to life the universe etc=%s", theAnswer));
     }
 
     {
@@ -1434,8 +1473,7 @@
             ctx << id << (int32_t)42 << (int32_t)-1 << (int32_t)0;
             ctx.write();
             EXPECT_TRUE(End_to_End(sync.tagStr,
-                                   "[id=%s,event=42,source=-1,account=0]",
-                                   id));
+                                   "[id=%s,event=42,source=-1,account=0]", id));
         }
 
         // Partial match to description
@@ -1443,9 +1481,7 @@
             android_log_event_list ctx(sync.tagNo);
             ctx << id << (int32_t)43 << (int64_t)-1 << (int32_t)0;
             ctx.write();
-            EXPECT_TRUE(End_to_End(sync.tagStr,
-                                   "[id=%s,event=43,-1,0]",
-                                   id));
+            EXPECT_TRUE(End_to_End(sync.tagStr, "[id=%s,event=43,-1,0]", id));
         }
 
         // Negative Test of End_to_End, ensure it is working
@@ -1454,9 +1490,8 @@
             ctx << id << (int32_t)44 << (int32_t)-1 << (int64_t)0;
             ctx.write();
             fprintf(stderr, "Expect a \"Closest match\" message\n");
-            EXPECT_FALSE(End_to_End(sync.tagStr,
-                                    "[id=%s,event=44,source=-1,account=0]",
-                                    id));
+            EXPECT_FALSE(End_to_End(
+                sync.tagStr, "[id=%s,event=44,source=-1,account=0]", id));
         }
     }
 
@@ -1466,16 +1501,16 @@
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint64_t)30 << (int32_t)2;
             ctx.write();
-            EXPECT_TRUE(End_to_End(sync.tagStr,
-                                   "[aggregation time=30ms,count=2]"));
+            EXPECT_TRUE(
+                End_to_End(sync.tagStr, "[aggregation time=30ms,count=2]"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint64_t)31570 << (int32_t)911;
             ctx.write();
-            EXPECT_TRUE(End_to_End(sync.tagStr,
-                                   "[aggregation time=31.57s,count=911]"));
+            EXPECT_TRUE(
+                End_to_End(sync.tagStr, "[aggregation time=31.57s,count=911]"));
         }
     }
 
@@ -1518,7 +1553,7 @@
 
         {
             android_log_event_list ctx(sync.tagNo);
-            ctx << (uint32_t)3221225472; // 3MB, but on purpose overflowed
+            ctx << (uint32_t)3221225472;  // 3MB, but on purpose overflowed
             ctx.write();
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=-1GB"));
         }