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/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;
         }