Home | History | Annotate | Download | only in logcat
      1 /*
      2  * Copyright (C) 2006-2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include <arpa/inet.h>
     18 #include <assert.h>
     19 #include <ctype.h>
     20 #include <dirent.h>
     21 #include <errno.h>
     22 #include <fcntl.h>
     23 #include <math.h>
     24 #include <pthread.h>
     25 #include <sched.h>
     26 #include <stdarg.h>
     27 #include <stdio.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #include <sys/cdefs.h>
     31 #include <sys/resource.h>
     32 #include <sys/socket.h>
     33 #include <sys/stat.h>
     34 #include <sys/types.h>
     35 #include <time.h>
     36 #include <unistd.h>
     37 
     38 #include <atomic>
     39 #include <memory>
     40 #include <string>
     41 #include <vector>
     42 
     43 #include <android-base/file.h>
     44 #include <android-base/properties.h>
     45 #include <android-base/stringprintf.h>
     46 #include <android-base/strings.h>
     47 #include <cutils/sched_policy.h>
     48 #include <cutils/sockets.h>
     49 #include <log/event_tag_map.h>
     50 #include <log/getopt.h>
     51 #include <log/logcat.h>
     52 #include <log/logprint.h>
     53 #include <private/android_logger.h>
     54 #include <system/thread_defs.h>
     55 
     56 #include <pcrecpp.h>
     57 
     58 #define DEFAULT_MAX_ROTATED_LOGS 4
     59 
     60 struct log_device_t {
     61     const char* device;
     62     bool binary;
     63     struct logger* logger;
     64     struct logger_list* logger_list;
     65     bool printed;
     66 
     67     log_device_t* next;
     68 
     69     log_device_t(const char* d, bool b) {
     70         device = d;
     71         binary = b;
     72         next = nullptr;
     73         printed = false;
     74         logger = nullptr;
     75         logger_list = nullptr;
     76     }
     77 };
     78 
     79 struct android_logcat_context_internal {
     80     // status
     81     volatile std::atomic_int retval;  // valid if thread_stopped set
     82     // Arguments passed in, or copies and storage thereof if a thread.
     83     int argc;
     84     char* const* argv;
     85     char* const* envp;
     86     std::vector<std::string> args;
     87     std::vector<const char*> argv_hold;
     88     std::vector<std::string> envs;
     89     std::vector<const char*> envp_hold;
     90     int output_fd;  // duplication of fileno(output) (below)
     91     int error_fd;   // duplication of fileno(error) (below)
     92 
     93     // library
     94     int fds[2];    // From popen call
     95     FILE* output;  // everything writes to fileno(output), buffer unused
     96     FILE* error;   // unless error == output.
     97     pthread_t thr;
     98     volatile std::atomic_bool stop;  // quick exit flag
     99     volatile std::atomic_bool thread_stopped;
    100     bool stderr_null;    // shell "2>/dev/null"
    101     bool stderr_stdout;  // shell "2>&1"
    102 
    103     // global variables
    104     AndroidLogFormat* logformat;
    105     const char* outputFileName;
    106     // 0 means "no log rotation"
    107     size_t logRotateSizeKBytes;
    108     // 0 means "unbounded"
    109     size_t maxRotatedLogs;
    110     size_t outByteCount;
    111     int printBinary;
    112     int devCount;  // >1 means multiple
    113     pcrecpp::RE* regex;
    114     log_device_t* devices;
    115     EventTagMap* eventTagMap;
    116     // 0 means "infinite"
    117     size_t maxCount;
    118     size_t printCount;
    119 
    120     bool printItAnyways;
    121     bool debug;
    122     bool hasOpenedEventTagMap;
    123 };
    124 
    125 // Creates a context associated with this logcat instance
    126 android_logcat_context create_android_logcat() {
    127     android_logcat_context_internal* context;
    128 
    129     context = (android_logcat_context_internal*)calloc(
    130         1, sizeof(android_logcat_context_internal));
    131     if (!context) return nullptr;
    132 
    133     context->fds[0] = -1;
    134     context->fds[1] = -1;
    135     context->output_fd = -1;
    136     context->error_fd = -1;
    137     context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
    138 
    139     context->argv_hold.clear();
    140     context->args.clear();
    141     context->envp_hold.clear();
    142     context->envs.clear();
    143 
    144     return (android_logcat_context)context;
    145 }
    146 
    147 // logd prefixes records with a length field
    148 #define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
    149 
    150 namespace android {
    151 
    152 enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
    153 
    154 // if showHelp is set, newline required in fmt statement to transition to usage
    155 static void logcat_panic(android_logcat_context_internal* context,
    156                          enum helpType showHelp, const char* fmt, ...)
    157     __printflike(3, 4);
    158 
    159 static int openLogFile(const char* pathname) {
    160     return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
    161 }
    162 
    163 static void close_output(android_logcat_context_internal* context) {
    164     // split output_from_error
    165     if (context->error == context->output) {
    166         context->output = nullptr;
    167         context->output_fd = -1;
    168     }
    169     if (context->error && (context->output_fd == fileno(context->error))) {
    170         context->output_fd = -1;
    171     }
    172     if (context->output_fd == context->error_fd) {
    173         context->output_fd = -1;
    174     }
    175     // close output channel
    176     if (context->output) {
    177         if (context->output != stdout) {
    178             if (context->output_fd == fileno(context->output)) {
    179                 context->output_fd = -1;
    180             }
    181             if (context->fds[1] == fileno(context->output)) {
    182                 context->fds[1] = -1;
    183             }
    184             fclose(context->output);
    185         }
    186         context->output = nullptr;
    187     }
    188     if (context->output_fd >= 0) {
    189         if (context->output_fd != fileno(stdout)) {
    190             if (context->fds[1] == context->output_fd) {
    191                 context->fds[1] = -1;
    192             }
    193             close(context->output_fd);
    194         }
    195         context->output_fd = -1;
    196     }
    197 }
    198 
    199 static void close_error(android_logcat_context_internal* context) {
    200     // split error_from_output
    201     if (context->output == context->error) {
    202         context->error = nullptr;
    203         context->error_fd = -1;
    204     }
    205     if (context->output && (context->error_fd == fileno(context->output))) {
    206         context->error_fd = -1;
    207     }
    208     if (context->error_fd == context->output_fd) {
    209         context->error_fd = -1;
    210     }
    211     // close error channel
    212     if (context->error) {
    213         if ((context->error != stderr) && (context->error != stdout)) {
    214             if (context->error_fd == fileno(context->error)) {
    215                 context->error_fd = -1;
    216             }
    217             if (context->fds[1] == fileno(context->error)) {
    218                 context->fds[1] = -1;
    219             }
    220             fclose(context->error);
    221         }
    222         context->error = nullptr;
    223     }
    224     if (context->error_fd >= 0) {
    225         if ((context->error_fd != fileno(stdout)) &&
    226             (context->error_fd != fileno(stderr))) {
    227             if (context->fds[1] == context->error_fd) context->fds[1] = -1;
    228             close(context->error_fd);
    229         }
    230         context->error_fd = -1;
    231     }
    232 }
    233 
    234 static void rotateLogs(android_logcat_context_internal* context) {
    235     int err;
    236 
    237     // Can't rotate logs if we're not outputting to a file
    238     if (!context->outputFileName) return;
    239 
    240     close_output(context);
    241 
    242     // Compute the maximum number of digits needed to count up to
    243     // maxRotatedLogs in decimal.  eg:
    244     // maxRotatedLogs == 30
    245     //   -> log10(30) == 1.477
    246     //   -> maxRotationCountDigits == 2
    247     int maxRotationCountDigits =
    248         (context->maxRotatedLogs > 0)
    249             ? (int)(floor(log10(context->maxRotatedLogs) + 1))
    250             : 0;
    251 
    252     for (int i = context->maxRotatedLogs; i > 0; i--) {
    253         std::string file1 = android::base::StringPrintf(
    254             "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
    255 
    256         std::string file0;
    257         if (!(i - 1)) {
    258             file0 = android::base::StringPrintf("%s", context->outputFileName);
    259         } else {
    260             file0 =
    261                 android::base::StringPrintf("%s.%.*d", context->outputFileName,
    262                                             maxRotationCountDigits, i - 1);
    263         }
    264 
    265         if (!file0.length() || !file1.length()) {
    266             perror("while rotating log files");
    267             break;
    268         }
    269 
    270         err = rename(file0.c_str(), file1.c_str());
    271 
    272         if (err < 0 && errno != ENOENT) {
    273             perror("while rotating log files");
    274         }
    275     }
    276 
    277     context->output_fd = openLogFile(context->outputFileName);
    278 
    279     if (context->output_fd < 0) {
    280         logcat_panic(context, HELP_FALSE, "couldn't open output file");
    281         return;
    282     }
    283     context->output = fdopen(context->output_fd, "web");
    284     if (!context->output) {
    285         logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
    286         return;
    287     }
    288     if (context->stderr_stdout) {
    289         close_error(context);
    290         context->error = context->output;
    291         context->error_fd = context->output_fd;
    292     }
    293 
    294     context->outByteCount = 0;
    295 }
    296 
    297 void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
    298     size_t size = buf->len();
    299 
    300     TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
    301 }
    302 
    303 static bool regexOk(android_logcat_context_internal* context,
    304                     const AndroidLogEntry& entry) {
    305     if (!context->regex) return true;
    306 
    307     std::string messageString(entry.message, entry.messageLen);
    308 
    309     return context->regex->PartialMatch(messageString);
    310 }
    311 
    312 static void processBuffer(android_logcat_context_internal* context,
    313                           log_device_t* dev, struct log_msg* buf) {
    314     int bytesWritten = 0;
    315     int err;
    316     AndroidLogEntry entry;
    317     char binaryMsgBuf[1024];
    318 
    319     if (dev->binary) {
    320         if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
    321             context->eventTagMap = android_openEventTagMap(nullptr);
    322             context->hasOpenedEventTagMap = true;
    323         }
    324         err = android_log_processBinaryLogBuffer(
    325             &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
    326             sizeof(binaryMsgBuf));
    327         // printf(">>> pri=%d len=%d msg='%s'\n",
    328         //    entry.priority, entry.messageLen, entry.message);
    329     } else {
    330         err = android_log_processLogBuffer(&buf->entry_v1, &entry);
    331     }
    332     if ((err < 0) && !context->debug) return;
    333 
    334     if (android_log_shouldPrintLine(
    335             context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
    336             entry.priority)) {
    337         bool match = regexOk(context, entry);
    338 
    339         context->printCount += match;
    340         if (match || context->printItAnyways) {
    341             bytesWritten = android_log_printLogLine(context->logformat,
    342                                                     context->output_fd, &entry);
    343 
    344             if (bytesWritten < 0) {
    345                 logcat_panic(context, HELP_FALSE, "output error");
    346                 return;
    347             }
    348         }
    349     }
    350 
    351     context->outByteCount += bytesWritten;
    352 
    353     if (context->logRotateSizeKBytes > 0 &&
    354         (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
    355         rotateLogs(context);
    356     }
    357 }
    358 
    359 static void maybePrintStart(android_logcat_context_internal* context,
    360                             log_device_t* dev, bool printDividers) {
    361     if (!dev->printed || printDividers) {
    362         if (context->devCount > 1 && !context->printBinary) {
    363             char buf[1024];
    364             snprintf(buf, sizeof(buf), "--------- %s %s\n",
    365                      dev->printed ? "switch to" : "beginning of", dev->device);
    366             if (write(context->output_fd, buf, strlen(buf)) < 0) {
    367                 logcat_panic(context, HELP_FALSE, "output error");
    368                 return;
    369             }
    370         }
    371         dev->printed = true;
    372     }
    373 }
    374 
    375 static void setupOutputAndSchedulingPolicy(
    376     android_logcat_context_internal* context, bool blocking) {
    377     if (!context->outputFileName) return;
    378 
    379     if (blocking) {
    380         // Lower priority and set to batch scheduling if we are saving
    381         // the logs into files and taking continuous content.
    382         if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
    383             fprintf(context->error,
    384                     "failed to set background scheduling policy\n");
    385         }
    386 
    387         struct sched_param param;
    388         memset(&param, 0, sizeof(param));
    389         if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
    390             fprintf(stderr, "failed to set to batch scheduler\n");
    391         }
    392 
    393         if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
    394             context->error) {
    395             fprintf(context->error, "failed set to priority\n");
    396         }
    397     }
    398 
    399     close_output(context);
    400 
    401     context->output_fd = openLogFile(context->outputFileName);
    402 
    403     if (context->output_fd < 0) {
    404         logcat_panic(context, HELP_FALSE, "couldn't open output file");
    405         return;
    406     }
    407 
    408     struct stat statbuf;
    409     if (fstat(context->output_fd, &statbuf) == -1) {
    410         close_output(context);
    411         logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
    412         return;
    413     }
    414 
    415     if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
    416         close_output(context);
    417         logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
    418         return;
    419     }
    420 
    421     context->output = fdopen(context->output_fd, "web");
    422 
    423     context->outByteCount = statbuf.st_size;
    424 }
    425 
    426 // clang-format off
    427 static void show_help(android_logcat_context_internal* context) {
    428     if (!context->error) return;
    429 
    430     const char* cmd = strrchr(context->argv[0], '/');
    431     cmd = cmd ? cmd + 1 : context->argv[0];
    432 
    433     fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
    434 
    435     fprintf(context->error, "options include:\n"
    436                     "  -s              Set default filter to silent. Equivalent to filterspec '*:S'\n"
    437                     "  -f <file>, --file=<file>               Log to file. Default is stdout\n"
    438                     "  -r <kbytes>, --rotate-kbytes=<kbytes>\n"
    439                     "                  Rotate log every kbytes. Requires -f option\n"
    440                     "  -n <count>, --rotate-count=<count>\n"
    441                     "                  Sets max number of rotated logs to <count>, default 4\n"
    442                     "  --id=<id>       If the signature id for logging to file changes, then clear\n"
    443                     "                  the fileset and continue\n"
    444                     "  -v <format>, --format=<format>\n"
    445                     "                  Sets log print format verb and adverbs, where <format> is:\n"
    446                     "                    brief help long process raw tag thread threadtime time\n"
    447                     "                  and individually flagged modifying adverbs can be added:\n"
    448                     "                    color descriptive epoch monotonic printable uid\n"
    449                     "                    usec UTC year zone\n"
    450                     "                  Multiple -v parameters or comma separated list of format and\n"
    451                     "                  format modifiers are allowed.\n"
    452                     // private and undocumented nsec, no signal, too much noise
    453                     // useful for -T or -t <timestamp> accurate testing though.
    454                     "  -D, --dividers  Print dividers between each log buffer\n"
    455                     "  -c, --clear     Clear (flush) the entire log and exit\n"
    456                     "                  if Log to File specified, clear fileset instead\n"
    457                     "  -d              Dump the log and then exit (don't block)\n"
    458                     "  -e <expr>, --regex=<expr>\n"
    459                     "                  Only print lines where the log message matches <expr>\n"
    460                     "                  where <expr> is a regular expression\n"
    461                     // Leave --head undocumented as alias for -m
    462                     "  -m <count>, --max-count=<count>\n"
    463                     "                  Quit after printing <count> lines. This is meant to be\n"
    464                     "                  paired with --regex, but will work on its own.\n"
    465                     "  --print         Paired with --regex and --max-count to let content bypass\n"
    466                     "                  regex filter but still stop at number of matches.\n"
    467                     // Leave --tail undocumented as alias for -t
    468                     "  -t <count>      Print only the most recent <count> lines (implies -d)\n"
    469                     "  -t '<time>'     Print most recent lines since specified time (implies -d)\n"
    470                     "  -T <count>      Print only the most recent <count> lines (does not imply -d)\n"
    471                     "  -T '<time>'     Print most recent lines since specified time (not imply -d)\n"
    472                     "                  count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
    473                     "                  'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
    474                     "  -g, --buffer-size                      Get the size of the ring buffer.\n"
    475                     "  -G <size>, --buffer-size=<size>\n"
    476                     "                  Set size of log ring buffer, may suffix with K or M.\n"
    477                     "  -L, --last      Dump logs from prior to last reboot\n"
    478                     // Leave security (Device Owner only installations) and
    479                     // kernel (userdebug and eng) buffers undocumented.
    480                     "  -b <buffer>, --buffer=<buffer>         Request alternate ring buffer, 'main',\n"
    481                     "                  'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
    482                     "                  Multiple -b parameters or comma separated list of buffers are\n"
    483                     "                  allowed. Buffers interleaved. Default -b main,system,crash.\n"
    484                     "  -B, --binary    Output the log in binary.\n"
    485                     "  -S, --statistics                       Output statistics.\n"
    486                     "  -p, --prune     Print prune white and ~black list. Service is specified as\n"
    487                     "                  UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
    488                     "                  with ~, otherwise weighed for longevity if unadorned. All\n"
    489                     "                  other pruning activity is oldest first. Special case ~!\n"
    490                     "                  represents an automatic quicker pruning for the noisiest\n"
    491                     "                  UID as determined by the current statistics.\n"
    492                     "  -P '<list> ...', --prune='<list> ...'\n"
    493                     "                  Set prune white and ~black list, using same format as\n"
    494                     "                  listed above. Must be quoted.\n"
    495                     "  --pid=<pid>     Only prints logs from the given pid.\n"
    496                     // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
    497                     "  --wrap          Sleep for 2 hours or when buffer about to wrap whichever\n"
    498                     "                  comes first. Improves efficiency of polling by providing\n"
    499                     "                  an about-to-wrap wakeup.\n");
    500 
    501     fprintf(context->error, "\nfilterspecs are a series of \n"
    502                    "  <tag>[:priority]\n\n"
    503                    "where <tag> is a log component tag (or * for all) and priority is:\n"
    504                    "  V    Verbose (default for <tag>)\n"
    505                    "  D    Debug (default for '*')\n"
    506                    "  I    Info\n"
    507                    "  W    Warn\n"
    508                    "  E    Error\n"
    509                    "  F    Fatal\n"
    510                    "  S    Silent (suppress all output)\n"
    511                    "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
    512                    "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
    513                    "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
    514                    "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
    515                    "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
    516                    "or defaults to \"threadtime\"\n\n");
    517 }
    518 
    519 static void show_format_help(android_logcat_context_internal* context) {
    520     if (!context->error) return;
    521     fprintf(context->error,
    522         "-v <format>, --format=<format> options:\n"
    523         "  Sets log print format verb and adverbs, where <format> is:\n"
    524         "    brief long process raw tag thread threadtime time\n"
    525         "  and individually flagged modifying adverbs can be added:\n"
    526         "    color descriptive epoch monotonic printable uid usec UTC year zone\n"
    527         "\nSingle format verbs:\n"
    528         "  brief       Display priority/tag and PID of the process issuing the message.\n"
    529         "  long        Display all metadata fields, separate messages with blank lines.\n"
    530         "  process     Display PID only.\n"
    531         "  raw         Display the raw log message, with no other metadata fields.\n"
    532         "  tag         Display the priority/tag only.\n"
    533         "  thread      Display priority, PID and TID of process issuing the message.\n"
    534         "  threadtime  Display the date, invocation time, priority, tag, and the PID\n"
    535         "               and TID of the thread issuing the message. (the default format).\n"
    536         "  time        Display the date, invocation time, priority/tag, and PID of the\n"
    537         "             process issuing the message.\n"
    538         "\nAdverb modifiers can be used in combination:\n"
    539         "  color        Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
    540         "                \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
    541         "  descriptive  events logs only, descriptions from event-log-tags database.\n"
    542         "  epoch        Display time as seconds since Jan 1 1970.\n"
    543         "  monotonic    Display time as cpu seconds since last boot.\n"
    544         "  printable    Ensure that any binary logging content is escaped.\n"
    545         "  uid          If permitted, display the UID or Android ID of logged process.\n"
    546         "  usec         Display time down the microsecond precision.\n"
    547         "  UTC          Display time as UTC.\n"
    548         "  year         Add the year to the displayed time.\n"
    549         "  zone         Add the local timezone to the displayed time.\n"
    550         "  \"<zone>\"     Print using this public named timezone (experimental).\n\n"
    551     );
    552 }
    553 // clang-format on
    554 
    555 static int setLogFormat(android_logcat_context_internal* context,
    556                         const char* formatString) {
    557     AndroidLogPrintFormat format;
    558 
    559     format = android_log_formatFromString(formatString);
    560 
    561     // invalid string?
    562     if (format == FORMAT_OFF) return -1;
    563 
    564     return android_log_setPrintFormat(context->logformat, format);
    565 }
    566 
    567 static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
    568 
    569 static unsigned long value_of_size(unsigned long value) {
    570     for (unsigned i = 0;
    571          (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
    572          value /= 1024, ++i)
    573         ;
    574     return value;
    575 }
    576 
    577 static const char* multiplier_of_size(unsigned long value) {
    578     unsigned i;
    579     for (i = 0;
    580          (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
    581          value /= 1024, ++i)
    582         ;
    583     return multipliers[i];
    584 }
    585 
    586 // String to unsigned int, returns -1 if it fails
    587 static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
    588                         size_t max = SIZE_MAX) {
    589     if (!ptr) return false;
    590 
    591     char* endp;
    592     errno = 0;
    593     size_t ret = (size_t)strtoll(ptr, &endp, 0);
    594 
    595     if (endp[0] || errno) return false;
    596 
    597     if ((ret > max) || (ret < min)) return false;
    598 
    599     *val = ret;
    600     return true;
    601 }
    602 
    603 static void logcat_panic(android_logcat_context_internal* context,
    604                          enum helpType showHelp, const char* fmt, ...) {
    605     context->retval = EXIT_FAILURE;
    606     if (!context->error) {
    607         context->stop = true;
    608         return;
    609     }
    610 
    611     va_list args;
    612     va_start(args, fmt);
    613     vfprintf(context->error, fmt, args);
    614     va_end(args);
    615 
    616     switch (showHelp) {
    617         case HELP_TRUE:
    618             show_help(context);
    619             break;
    620         case HELP_FORMAT:
    621             show_format_help(context);
    622             break;
    623         case HELP_FALSE:
    624         default:
    625             break;
    626     }
    627 
    628     context->stop = true;
    629 }
    630 
    631 static char* parseTime(log_time& t, const char* cp) {
    632     char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
    633     if (ep) return ep;
    634     ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
    635     if (ep) return ep;
    636     return t.strptime(cp, "%s.%q");
    637 }
    638 
    639 // Find last logged line in <outputFileName>, or <outputFileName>.1
    640 static log_time lastLogTime(const char* outputFileName) {
    641     log_time retval(log_time::EPOCH);
    642     if (!outputFileName) return retval;
    643 
    644     std::string directory;
    645     const char* file = strrchr(outputFileName, '/');
    646     if (!file) {
    647         directory = ".";
    648         file = outputFileName;
    649     } else {
    650         directory = std::string(outputFileName, file - outputFileName);
    651         ++file;
    652     }
    653 
    654     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
    655                                             closedir);
    656     if (!dir.get()) return retval;
    657 
    658     log_time now(android_log_clockid());
    659 
    660     size_t len = strlen(file);
    661     log_time modulo(0, NS_PER_SEC);
    662     struct dirent* dp;
    663 
    664     while (!!(dp = readdir(dir.get()))) {
    665         if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
    666             (dp->d_name[len] && ((dp->d_name[len] != '.') ||
    667                                  (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
    668             continue;
    669         }
    670 
    671         std::string file_name = directory;
    672         file_name += "/";
    673         file_name += dp->d_name;
    674         std::string file;
    675         if (!android::base::ReadFileToString(file_name, &file)) continue;
    676 
    677         bool found = false;
    678         for (const auto& line : android::base::Split(file, "\n")) {
    679             log_time t(log_time::EPOCH);
    680             char* ep = parseTime(t, line.c_str());
    681             if (!ep || (*ep != ' ')) continue;
    682             // determine the time precision of the logs (eg: msec or usec)
    683             for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
    684                 if (t.tv_nsec % (mod * 10)) {
    685                     modulo.tv_nsec = mod;
    686                     break;
    687                 }
    688             }
    689             // We filter any times later than current as we may not have the
    690             // year stored with each log entry. Also, since it is possible for
    691             // entries to be recorded out of order (very rare) we select the
    692             // maximum we find just in case.
    693             if ((t < now) && (t > retval)) {
    694                 retval = t;
    695                 found = true;
    696             }
    697         }
    698         // We count on the basename file to be the definitive end, so stop here.
    699         if (!dp->d_name[len] && found) break;
    700     }
    701     if (retval == log_time::EPOCH) return retval;
    702     // tail_time prints matching or higher, round up by the modulo to prevent
    703     // a replay of the last entry we have just checked.
    704     retval += modulo;
    705     return retval;
    706 }
    707 
    708 const char* getenv(android_logcat_context_internal* context, const char* name) {
    709     if (!context->envp || !name || !*name) return nullptr;
    710 
    711     for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
    712         if (strncmp(context->envp[i], name, len)) continue;
    713         if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
    714     }
    715     return nullptr;
    716 }
    717 
    718 }  // namespace android
    719 
    720 void reportErrorName(const char** current, const char* name,
    721                      bool blockSecurity) {
    722     if (*current) return;
    723     if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
    724         *current = name;
    725     }
    726 }
    727 
    728 static int __logcat(android_logcat_context_internal* context) {
    729     using namespace android;
    730     int err;
    731     bool hasSetLogFormat = false;
    732     bool clearLog = false;
    733     bool allSelected = false;
    734     bool getLogSize = false;
    735     bool getPruneList = false;
    736     bool printStatistics = false;
    737     bool printDividers = false;
    738     unsigned long setLogSize = 0;
    739     const char* setPruneList = nullptr;
    740     const char* setId = nullptr;
    741     int mode = ANDROID_LOG_RDONLY;
    742     std::string forceFilters;
    743     log_device_t* dev;
    744     struct logger_list* logger_list;
    745     size_t tail_lines = 0;
    746     log_time tail_time(log_time::EPOCH);
    747     size_t pid = 0;
    748     bool got_t = false;
    749 
    750     // object instantiations before goto's can happen
    751     log_device_t unexpected("unexpected", false);
    752     const char* openDeviceFail = nullptr;
    753     const char* clearFail = nullptr;
    754     const char* setSizeFail = nullptr;
    755     const char* getSizeFail = nullptr;
    756     int argc = context->argc;
    757     char* const* argv = context->argv;
    758 
    759     context->output = stdout;
    760     context->error = stderr;
    761 
    762     for (int i = 0; i < argc; ++i) {
    763         // Simulate shell stderr redirect parsing
    764         if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
    765 
    766         // Append to file not implemented, just open file
    767         size_t skip = (argv[i][2] == '>') + 2;
    768         if (!strcmp(&argv[i][skip], "/dev/null")) {
    769             context->stderr_null = true;
    770         } else if (!strcmp(&argv[i][skip], "&1")) {
    771             context->stderr_stdout = true;
    772         } else {
    773             // stderr file redirections are not supported
    774             fprintf(context->stderr_stdout ? stdout : stderr,
    775                     "stderr redirection to file %s unsupported, skipping\n",
    776                     &argv[i][skip]);
    777         }
    778         // Only the first one
    779         break;
    780     }
    781 
    782     const char* filename = nullptr;
    783     for (int i = 0; i < argc; ++i) {
    784         // Simulate shell stdout redirect parsing
    785         if (argv[i][0] != '>') continue;
    786 
    787         // Append to file not implemented, just open file
    788         filename = &argv[i][(argv[i][1] == '>') + 1];
    789         // Only the first one
    790         break;
    791     }
    792 
    793     // Deal with setting up file descriptors and FILE pointers
    794     if (context->error_fd >= 0) {  // Is an error file descriptor supplied?
    795         if (context->error_fd == context->output_fd) {
    796             context->stderr_stdout = true;
    797         } else if (context->stderr_null) {  // redirection told us to close it
    798             close(context->error_fd);
    799             context->error_fd = -1;
    800         } else {  // All Ok, convert error to a FILE pointer
    801             context->error = fdopen(context->error_fd, "web");
    802             if (!context->error) {
    803                 context->retval = -errno;
    804                 fprintf(context->stderr_stdout ? stdout : stderr,
    805                         "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
    806                         strerror(errno));
    807                 goto exit;
    808             }
    809         }
    810     }
    811     if (context->output_fd >= 0) {  // Is an output file descriptor supplied?
    812         if (filename) {  // redirect to file, close supplied file descriptor.
    813             close(context->output_fd);
    814             context->output_fd = -1;
    815         } else {  // All Ok, convert output to a FILE pointer
    816             context->output = fdopen(context->output_fd, "web");
    817             if (!context->output) {
    818                 context->retval = -errno;
    819                 fprintf(context->stderr_stdout ? stdout : context->error,
    820                         "Failed to fdopen(output_fd=%d) %s\n",
    821                         context->output_fd, strerror(errno));
    822                 goto exit;
    823             }
    824         }
    825     }
    826     if (filename) {  // We supplied an output file redirected in command line
    827         context->output = fopen(filename, "web");
    828     }
    829     // Deal with 2>&1
    830     if (context->stderr_stdout) context->error = context->output;
    831     // Deal with 2>/dev/null
    832     if (context->stderr_null) {
    833         context->error_fd = -1;
    834         context->error = nullptr;
    835     }
    836     // Only happens if output=stdout or output=filename
    837     if ((context->output_fd < 0) && context->output) {
    838         context->output_fd = fileno(context->output);
    839     }
    840     // Only happens if error=stdout || error=stderr
    841     if ((context->error_fd < 0) && context->error) {
    842         context->error_fd = fileno(context->error);
    843     }
    844 
    845     context->logformat = android_log_format_new();
    846 
    847     if (argc == 2 && !strcmp(argv[1], "--help")) {
    848         show_help(context);
    849         context->retval = EXIT_SUCCESS;
    850         goto exit;
    851     }
    852 
    853     // meant to catch comma-delimited values, but cast a wider
    854     // net for stability dealing with possible mistaken inputs.
    855     static const char delimiters[] = ",:; \t\n\r\f";
    856 
    857     struct getopt_context optctx;
    858     INIT_GETOPT_CONTEXT(optctx);
    859     optctx.opterr = !!context->error;
    860     optctx.optstderr = context->error;
    861 
    862     for (;;) {
    863         int ret;
    864 
    865         int option_index = 0;
    866         // list of long-argument only strings for later comparison
    867         static const char pid_str[] = "pid";
    868         static const char debug_str[] = "debug";
    869         static const char id_str[] = "id";
    870         static const char wrap_str[] = "wrap";
    871         static const char print_str[] = "print";
    872         // clang-format off
    873         static const struct option long_options[] = {
    874           { "binary",        no_argument,       nullptr, 'B' },
    875           { "buffer",        required_argument, nullptr, 'b' },
    876           { "buffer-size",   optional_argument, nullptr, 'g' },
    877           { "clear",         no_argument,       nullptr, 'c' },
    878           { debug_str,       no_argument,       nullptr, 0 },
    879           { "dividers",      no_argument,       nullptr, 'D' },
    880           { "file",          required_argument, nullptr, 'f' },
    881           { "format",        required_argument, nullptr, 'v' },
    882           // hidden and undocumented reserved alias for --regex
    883           { "grep",          required_argument, nullptr, 'e' },
    884           // hidden and undocumented reserved alias for --max-count
    885           { "head",          required_argument, nullptr, 'm' },
    886           { "help",          no_argument,       nullptr, 'h' },
    887           { id_str,          required_argument, nullptr, 0 },
    888           { "last",          no_argument,       nullptr, 'L' },
    889           { "max-count",     required_argument, nullptr, 'm' },
    890           { pid_str,         required_argument, nullptr, 0 },
    891           { print_str,       no_argument,       nullptr, 0 },
    892           { "prune",         optional_argument, nullptr, 'p' },
    893           { "regex",         required_argument, nullptr, 'e' },
    894           { "rotate-count",  required_argument, nullptr, 'n' },
    895           { "rotate-kbytes", required_argument, nullptr, 'r' },
    896           { "statistics",    no_argument,       nullptr, 'S' },
    897           // hidden and undocumented reserved alias for -t
    898           { "tail",          required_argument, nullptr, 't' },
    899           // support, but ignore and do not document, the optional argument
    900           { wrap_str,        optional_argument, nullptr, 0 },
    901           { nullptr,         0,                 nullptr, 0 }
    902         };
    903         // clang-format on
    904 
    905         ret = getopt_long_r(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
    906                             long_options, &option_index, &optctx);
    907         if (ret < 0) break;
    908 
    909         switch (ret) {
    910             case 0:
    911                 // only long options
    912                 if (long_options[option_index].name == pid_str) {
    913                     // ToDo: determine runtime PID_MAX?
    914                     if (!getSizeTArg(optctx.optarg, &pid, 1)) {
    915                         logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
    916                                      long_options[option_index].name,
    917                                      optctx.optarg);
    918                         goto exit;
    919                     }
    920                     break;
    921                 }
    922                 if (long_options[option_index].name == wrap_str) {
    923                     mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
    924                             ANDROID_LOG_NONBLOCK;
    925                     // ToDo: implement API that supports setting a wrap timeout
    926                     size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
    927                     if (optctx.optarg &&
    928                         !getSizeTArg(optctx.optarg, &dummy, 1)) {
    929                         logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
    930                                      long_options[option_index].name,
    931                                      optctx.optarg);
    932                         goto exit;
    933                     }
    934                     if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
    935                         context->error) {
    936                         fprintf(context->error,
    937                                 "WARNING: %s %u seconds, ignoring %zu\n",
    938                                 long_options[option_index].name,
    939                                 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
    940                     }
    941                     break;
    942                 }
    943                 if (long_options[option_index].name == print_str) {
    944                     context->printItAnyways = true;
    945                     break;
    946                 }
    947                 if (long_options[option_index].name == debug_str) {
    948                     context->debug = true;
    949                     break;
    950                 }
    951                 if (long_options[option_index].name == id_str) {
    952                     setId = (optctx.optarg && optctx.optarg[0]) ? optctx.optarg
    953                                                                 : nullptr;
    954                 }
    955                 break;
    956 
    957             case 's':
    958                 // default to all silent
    959                 android_log_addFilterRule(context->logformat, "*:s");
    960                 break;
    961 
    962             case 'c':
    963                 clearLog = true;
    964                 mode |= ANDROID_LOG_WRONLY;
    965                 break;
    966 
    967             case 'L':
    968                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
    969                         ANDROID_LOG_NONBLOCK;
    970                 break;
    971 
    972             case 'd':
    973                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
    974                 break;
    975 
    976             case 't':
    977                 got_t = true;
    978                 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
    979             // FALLTHRU
    980             case 'T':
    981                 if (strspn(optctx.optarg, "0123456789") !=
    982                     strlen(optctx.optarg)) {
    983                     char* cp = parseTime(tail_time, optctx.optarg);
    984                     if (!cp) {
    985                         logcat_panic(context, HELP_FALSE,
    986                                      "-%c \"%s\" not in time format\n", ret,
    987                                      optctx.optarg);
    988                         goto exit;
    989                     }
    990                     if (*cp) {
    991                         char c = *cp;
    992                         *cp = '\0';
    993                         if (context->error) {
    994                             fprintf(
    995                                 context->error,
    996                                 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
    997                                 ret, optctx.optarg, c, cp + 1);
    998                         }
    999                         *cp = c;
   1000                     }
   1001                 } else {
   1002                     if (!getSizeTArg(optctx.optarg, &tail_lines, 1)) {
   1003                         if (context->error) {
   1004                             fprintf(context->error,
   1005                                     "WARNING: -%c %s invalid, setting to 1\n",
   1006                                     ret, optctx.optarg);
   1007                         }
   1008                         tail_lines = 1;
   1009                     }
   1010                 }
   1011                 break;
   1012 
   1013             case 'D':
   1014                 printDividers = true;
   1015                 break;
   1016 
   1017             case 'e':
   1018                 context->regex = new pcrecpp::RE(optctx.optarg);
   1019                 break;
   1020 
   1021             case 'm': {
   1022                 char* end = nullptr;
   1023                 if (!getSizeTArg(optctx.optarg, &context->maxCount)) {
   1024                     logcat_panic(context, HELP_FALSE,
   1025                                  "-%c \"%s\" isn't an "
   1026                                  "integer greater than zero\n",
   1027                                  ret, optctx.optarg);
   1028                     goto exit;
   1029                 }
   1030             } break;
   1031 
   1032             case 'g':
   1033                 if (!optctx.optarg) {
   1034                     getLogSize = true;
   1035                     break;
   1036                 }
   1037             // FALLTHRU
   1038 
   1039             case 'G': {
   1040                 char* cp;
   1041                 if (strtoll(optctx.optarg, &cp, 0) > 0) {
   1042                     setLogSize = strtoll(optctx.optarg, &cp, 0);
   1043                 } else {
   1044                     setLogSize = 0;
   1045                 }
   1046 
   1047                 switch (*cp) {
   1048                     case 'g':
   1049                     case 'G':
   1050                         setLogSize *= 1024;
   1051                     // FALLTHRU
   1052                     case 'm':
   1053                     case 'M':
   1054                         setLogSize *= 1024;
   1055                     // FALLTHRU
   1056                     case 'k':
   1057                     case 'K':
   1058                         setLogSize *= 1024;
   1059                     // FALLTHRU
   1060                     case '\0':
   1061                         break;
   1062 
   1063                     default:
   1064                         setLogSize = 0;
   1065                 }
   1066 
   1067                 if (!setLogSize) {
   1068                     logcat_panic(context, HELP_FALSE,
   1069                                  "ERROR: -G <num><multiplier>\n");
   1070                     goto exit;
   1071                 }
   1072             } break;
   1073 
   1074             case 'p':
   1075                 if (!optctx.optarg) {
   1076                     getPruneList = true;
   1077                     break;
   1078                 }
   1079             // FALLTHRU
   1080 
   1081             case 'P':
   1082                 setPruneList = optctx.optarg;
   1083                 break;
   1084 
   1085             case 'b': {
   1086                 std::unique_ptr<char, void (*)(void*)> buffers(
   1087                     strdup(optctx.optarg), free);
   1088                 char* arg = buffers.get();
   1089                 unsigned idMask = 0;
   1090                 char* sv = nullptr;  // protect against -ENOMEM above
   1091                 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
   1092                     if (!strcmp(arg, "default")) {
   1093                         idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
   1094                                   (1 << LOG_ID_CRASH);
   1095                     } else if (!strcmp(arg, "all")) {
   1096                         allSelected = true;
   1097                         idMask = (unsigned)-1;
   1098                     } else {
   1099                         log_id_t log_id = android_name_to_log_id(arg);
   1100                         const char* name = android_log_id_to_name(log_id);
   1101 
   1102                         if (!!strcmp(name, arg)) {
   1103                             logcat_panic(context, HELP_TRUE,
   1104                                          "unknown buffer %s\n", arg);
   1105                             goto exit;
   1106                         }
   1107                         if (log_id == LOG_ID_SECURITY) allSelected = false;
   1108                         idMask |= (1 << log_id);
   1109                     }
   1110                     arg = nullptr;
   1111                 }
   1112 
   1113                 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
   1114                     const char* name = android_log_id_to_name((log_id_t)i);
   1115                     log_id_t log_id = android_name_to_log_id(name);
   1116 
   1117                     if (log_id != (log_id_t)i) continue;
   1118                     if (!(idMask & (1 << i))) continue;
   1119 
   1120                     bool found = false;
   1121                     for (dev = context->devices; dev; dev = dev->next) {
   1122                         if (!strcmp(name, dev->device)) {
   1123                             found = true;
   1124                             break;
   1125                         }
   1126                         if (!dev->next) break;
   1127                     }
   1128                     if (found) continue;
   1129 
   1130                     bool binary =
   1131                         !strcmp(name, "events") || !strcmp(name, "security");
   1132                     log_device_t* d = new log_device_t(name, binary);
   1133 
   1134                     if (dev) {
   1135                         dev->next = d;
   1136                         dev = d;
   1137                     } else {
   1138                         context->devices = dev = d;
   1139                     }
   1140                     context->devCount++;
   1141                 }
   1142             } break;
   1143 
   1144             case 'B':
   1145                 context->printBinary = 1;
   1146                 break;
   1147 
   1148             case 'f':
   1149                 if ((tail_time == log_time::EPOCH) && !tail_lines) {
   1150                     tail_time = lastLogTime(optctx.optarg);
   1151                 }
   1152                 // redirect output to a file
   1153                 context->outputFileName = optctx.optarg;
   1154                 break;
   1155 
   1156             case 'r':
   1157                 if (!getSizeTArg(optctx.optarg, &context->logRotateSizeKBytes,
   1158                                  1)) {
   1159                     logcat_panic(context, HELP_TRUE,
   1160                                  "Invalid parameter \"%s\" to -r\n",
   1161                                  optctx.optarg);
   1162                     goto exit;
   1163                 }
   1164                 break;
   1165 
   1166             case 'n':
   1167                 if (!getSizeTArg(optctx.optarg, &context->maxRotatedLogs, 1)) {
   1168                     logcat_panic(context, HELP_TRUE,
   1169                                  "Invalid parameter \"%s\" to -n\n",
   1170                                  optctx.optarg);
   1171                     goto exit;
   1172                 }
   1173                 break;
   1174 
   1175             case 'v': {
   1176                 if (!strcmp(optctx.optarg, "help") ||
   1177                     !strcmp(optctx.optarg, "--help")) {
   1178                     show_format_help(context);
   1179                     context->retval = EXIT_SUCCESS;
   1180                     goto exit;
   1181                 }
   1182                 std::unique_ptr<char, void (*)(void*)> formats(
   1183                     strdup(optctx.optarg), free);
   1184                 char* arg = formats.get();
   1185                 unsigned idMask = 0;
   1186                 char* sv = nullptr;  // protect against -ENOMEM above
   1187                 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
   1188                     err = setLogFormat(context, arg);
   1189                     if (err < 0) {
   1190                         logcat_panic(context, HELP_FORMAT,
   1191                                      "Invalid parameter \"%s\" to -v\n", arg);
   1192                         goto exit;
   1193                     }
   1194                     arg = nullptr;
   1195                     if (err) hasSetLogFormat = true;
   1196                 }
   1197             } break;
   1198 
   1199             case 'Q':
   1200 #define LOGCAT_FILTER "androidboot.logcat="
   1201 #define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
   1202 #define CONSOLE_OPTION "androidboot.console="
   1203 #define QEMU_PROPERTY "ro.kernel.qemu"
   1204 #define QEMU_CMDLINE "qemu.cmdline"
   1205                 // This is a *hidden* option used to start a version of logcat
   1206                 // in an emulated device only.  It basically looks for
   1207                 // androidboot.logcat= on the kernel command line.  If
   1208                 // something is found, it extracts a log filter and uses it to
   1209                 // run the program. The logcat output will go to consolepipe if
   1210                 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
   1211                 // it goes to androidboot.console (e.g. tty)
   1212                 {
   1213                     // if not in emulator, exit quietly
   1214                     if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
   1215                         context->retval = EXIT_SUCCESS;
   1216                         goto exit;
   1217                     }
   1218 
   1219                     std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
   1220                     if (cmdline.empty()) {
   1221                         android::base::ReadFileToString("/proc/cmdline", &cmdline);
   1222                     }
   1223 
   1224                     const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
   1225                     // if nothing found or invalid filters, exit quietly
   1226                     if (!logcatFilter) {
   1227                         context->retval = EXIT_SUCCESS;
   1228                         goto exit;
   1229                     }
   1230 
   1231                     const char* p = logcatFilter + strlen(LOGCAT_FILTER);
   1232                     const char* q = strpbrk(p, " \t\n\r");
   1233                     if (!q) q = p + strlen(p);
   1234                     forceFilters = std::string(p, q);
   1235 
   1236                     // redirect our output to the emulator console pipe or console
   1237                     const char* consolePipe =
   1238                         strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
   1239                     const char* console =
   1240                         strstr(cmdline.c_str(), CONSOLE_OPTION);
   1241 
   1242                     if (consolePipe) {
   1243                         p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
   1244                     } else if (console) {
   1245                         p = console + strlen(CONSOLE_OPTION);
   1246                     } else {
   1247                         context->retval = EXIT_FAILURE;
   1248                         goto exit;
   1249                     }
   1250 
   1251                     q = strpbrk(p, " \t\n\r");
   1252                     int len = q ? q - p : strlen(p);
   1253                     std::string devname = "/dev/" + std::string(p, len);
   1254                     std::string pipePurpose("pipe:logcat");
   1255                     if (consolePipe) {
   1256                         // example: "qemu_pipe,pipe:logcat"
   1257                         // upon opening of /dev/qemu_pipe, the "pipe:logcat"
   1258                         // string with trailing '\0' should be written to the fd
   1259                         size_t pos = devname.find(",");
   1260                         if (pos != std::string::npos) {
   1261                             pipePurpose = devname.substr(pos + 1);
   1262                             devname = devname.substr(0, pos);
   1263                         }
   1264                     }
   1265                     cmdline.erase();
   1266 
   1267                     if (context->error) {
   1268                         fprintf(context->error, "logcat using %s\n",
   1269                                 devname.c_str());
   1270                     }
   1271 
   1272                     FILE* fp = fopen(devname.c_str(), "web");
   1273                     devname.erase();
   1274                     if (!fp) break;
   1275 
   1276                     if (consolePipe) {
   1277                         // need the trailing '\0'
   1278                         if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
   1279                                     pipePurpose.size() + 1)) {
   1280                             fclose(fp);
   1281                             context->retval = EXIT_FAILURE;
   1282                             goto exit;
   1283                         }
   1284                     }
   1285 
   1286                     // close output and error channels, replace with console
   1287                     android::close_output(context);
   1288                     android::close_error(context);
   1289                     context->stderr_stdout = true;
   1290                     context->output = fp;
   1291                     context->output_fd = fileno(fp);
   1292                     if (context->stderr_null) break;
   1293                     context->stderr_stdout = true;
   1294                     context->error = fp;
   1295                     context->error_fd = fileno(fp);
   1296                 }
   1297                 break;
   1298 
   1299             case 'S':
   1300                 printStatistics = true;
   1301                 break;
   1302 
   1303             case ':':
   1304                 logcat_panic(context, HELP_TRUE,
   1305                              "Option -%c needs an argument\n", optctx.optopt);
   1306                 goto exit;
   1307 
   1308             case 'h':
   1309                 show_help(context);
   1310                 show_format_help(context);
   1311                 goto exit;
   1312 
   1313             default:
   1314                 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
   1315                              optctx.optopt);
   1316                 goto exit;
   1317         }
   1318     }
   1319 
   1320     if (context->maxCount && got_t) {
   1321         logcat_panic(context, HELP_TRUE,
   1322                      "Cannot use -m (--max-count) and -t together\n");
   1323         goto exit;
   1324     }
   1325     if (context->printItAnyways && (!context->regex || !context->maxCount)) {
   1326         // One day it would be nice if --print -v color and --regex <expr>
   1327         // could play with each other and show regex highlighted content.
   1328         // clang-format off
   1329         if (context->error) {
   1330             fprintf(context->error, "WARNING: "
   1331                             "--print ignored, to be used in combination with\n"
   1332                                 "         "
   1333                             "--regex <expr> and --max-count <N>\n");
   1334         }
   1335         context->printItAnyways = false;
   1336     }
   1337 
   1338     if (!context->devices) {
   1339         dev = context->devices = new log_device_t("main", false);
   1340         context->devCount = 1;
   1341         if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
   1342             dev = dev->next = new log_device_t("system", false);
   1343             context->devCount++;
   1344         }
   1345         if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
   1346             dev = dev->next = new log_device_t("crash", false);
   1347             context->devCount++;
   1348         }
   1349     }
   1350 
   1351     if (!!context->logRotateSizeKBytes && !context->outputFileName) {
   1352         logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
   1353         goto exit;
   1354     }
   1355 
   1356     if (!!setId) {
   1357         if (!context->outputFileName) {
   1358             logcat_panic(context, HELP_TRUE,
   1359                          "--id='%s' requires -f as well\n", setId);
   1360             goto exit;
   1361         }
   1362 
   1363         std::string file_name = android::base::StringPrintf(
   1364                                         "%s.id", context->outputFileName);
   1365         std::string file;
   1366         bool file_ok = android::base::ReadFileToString(file_name, &file);
   1367         android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
   1368                                          getuid(), getgid());
   1369         if (!file_ok || !file.compare(setId)) setId = nullptr;
   1370     }
   1371 
   1372     if (!hasSetLogFormat) {
   1373         const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
   1374 
   1375         if (!!logFormat) {
   1376             std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
   1377                                                            free);
   1378             char* sv = nullptr;  // protect against -ENOMEM above
   1379             char* arg = formats.get();
   1380             while (!!(arg = strtok_r(arg, delimiters, &sv))) {
   1381                 err = setLogFormat(context, arg);
   1382                 // environment should not cause crash of logcat
   1383                 if ((err < 0) && context->error) {
   1384                     fprintf(context->error,
   1385                             "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
   1386                 }
   1387                 arg = nullptr;
   1388                 if (err > 0) hasSetLogFormat = true;
   1389             }
   1390         }
   1391         if (!hasSetLogFormat) {
   1392             setLogFormat(context, "threadtime");
   1393         }
   1394     }
   1395 
   1396     if (forceFilters.size()) {
   1397         err = android_log_addFilterString(context->logformat,
   1398                                           forceFilters.c_str());
   1399         if (err < 0) {
   1400             logcat_panic(context, HELP_FALSE,
   1401                          "Invalid filter expression in logcat args\n");
   1402             goto exit;
   1403         }
   1404     } else if (argc == optctx.optind) {
   1405         // Add from environment variable
   1406         const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
   1407 
   1408         if (!!env_tags_orig) {
   1409             err = android_log_addFilterString(context->logformat,
   1410                                               env_tags_orig);
   1411 
   1412             if (err < 0) {
   1413                 logcat_panic(context, HELP_TRUE,
   1414                             "Invalid filter expression in ANDROID_LOG_TAGS\n");
   1415                 goto exit;
   1416             }
   1417         }
   1418     } else {
   1419         // Add from commandline
   1420         for (int i = optctx.optind ; i < argc ; i++) {
   1421             // skip stderr redirections of _all_ kinds
   1422             if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
   1423             // skip stdout redirections of _all_ kinds
   1424             if (argv[i][0] == '>') continue;
   1425 
   1426             err = android_log_addFilterString(context->logformat, argv[i]);
   1427             if (err < 0) {
   1428                 logcat_panic(context, HELP_TRUE,
   1429                              "Invalid filter expression '%s'\n", argv[i]);
   1430                 goto exit;
   1431             }
   1432         }
   1433     }
   1434 
   1435     dev = context->devices;
   1436     if (tail_time != log_time::EPOCH) {
   1437         logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
   1438     } else {
   1439         logger_list = android_logger_list_alloc(mode, tail_lines, pid);
   1440     }
   1441     // We have three orthogonal actions below to clear, set log size and
   1442     // get log size. All sharing the same iteration loop.
   1443     while (dev) {
   1444         dev->logger_list = logger_list;
   1445         dev->logger = android_logger_open(logger_list,
   1446                                           android_name_to_log_id(dev->device));
   1447         if (!dev->logger) {
   1448             reportErrorName(&openDeviceFail, dev->device, allSelected);
   1449             dev = dev->next;
   1450             continue;
   1451         }
   1452 
   1453         if (clearLog || setId) {
   1454             if (context->outputFileName) {
   1455                 int maxRotationCountDigits =
   1456                     (context->maxRotatedLogs > 0) ?
   1457                         (int)(floor(log10(context->maxRotatedLogs) + 1)) :
   1458                         0;
   1459 
   1460                 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
   1461                     std::string file;
   1462 
   1463                     if (!i) {
   1464                         file = android::base::StringPrintf(
   1465                             "%s", context->outputFileName);
   1466                     } else {
   1467                         file = android::base::StringPrintf("%s.%.*d",
   1468                             context->outputFileName, maxRotationCountDigits, i);
   1469                     }
   1470 
   1471                     if (!file.length()) {
   1472                         perror("while clearing log files");
   1473                         reportErrorName(&clearFail, dev->device, allSelected);
   1474                         break;
   1475                     }
   1476 
   1477                     err = unlink(file.c_str());
   1478 
   1479                     if (err < 0 && errno != ENOENT && !clearFail) {
   1480                         perror("while clearing log files");
   1481                         reportErrorName(&clearFail, dev->device, allSelected);
   1482                     }
   1483                 }
   1484             } else if (android_logger_clear(dev->logger)) {
   1485                 reportErrorName(&clearFail, dev->device, allSelected);
   1486             }
   1487         }
   1488 
   1489         if (setLogSize) {
   1490             if (android_logger_set_log_size(dev->logger, setLogSize)) {
   1491                 reportErrorName(&setSizeFail, dev->device, allSelected);
   1492             }
   1493         }
   1494 
   1495         if (getLogSize) {
   1496             long size = android_logger_get_log_size(dev->logger);
   1497             long readable = android_logger_get_log_readable_size(dev->logger);
   1498 
   1499             if ((size < 0) || (readable < 0)) {
   1500                 reportErrorName(&getSizeFail, dev->device, allSelected);
   1501             } else {
   1502                 std::string str = android::base::StringPrintf(
   1503                        "%s: ring buffer is %ld%sb (%ld%sb consumed),"
   1504                          " max entry is %db, max payload is %db\n",
   1505                        dev->device,
   1506                        value_of_size(size), multiplier_of_size(size),
   1507                        value_of_size(readable), multiplier_of_size(readable),
   1508                        (int)LOGGER_ENTRY_MAX_LEN,
   1509                        (int)LOGGER_ENTRY_MAX_PAYLOAD);
   1510                 TEMP_FAILURE_RETRY(write(context->output_fd,
   1511                                          str.data(), str.length()));
   1512             }
   1513         }
   1514 
   1515         dev = dev->next;
   1516     }
   1517 
   1518     context->retval = EXIT_SUCCESS;
   1519 
   1520     // report any errors in the above loop and exit
   1521     if (openDeviceFail) {
   1522         logcat_panic(context, HELP_FALSE,
   1523                      "Unable to open log device '%s'\n", openDeviceFail);
   1524         goto close;
   1525     }
   1526     if (clearFail) {
   1527         logcat_panic(context, HELP_FALSE,
   1528                      "failed to clear the '%s' log\n", clearFail);
   1529         goto close;
   1530     }
   1531     if (setSizeFail) {
   1532         logcat_panic(context, HELP_FALSE,
   1533                      "failed to set the '%s' log size\n", setSizeFail);
   1534         goto close;
   1535     }
   1536     if (getSizeFail) {
   1537         logcat_panic(context, HELP_FALSE,
   1538                      "failed to get the readable '%s' log size", getSizeFail);
   1539         goto close;
   1540     }
   1541 
   1542     if (setPruneList) {
   1543         size_t len = strlen(setPruneList);
   1544         // extra 32 bytes are needed by android_logger_set_prune_list
   1545         size_t bLen = len + 32;
   1546         char* buf = nullptr;
   1547         if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
   1548             buf[len] = '\0';
   1549             if (android_logger_set_prune_list(logger_list, buf, bLen)) {
   1550                 logcat_panic(context, HELP_FALSE,
   1551                              "failed to set the prune list");
   1552             }
   1553             free(buf);
   1554         } else {
   1555             logcat_panic(context, HELP_FALSE,
   1556                          "failed to set the prune list (alloc)");
   1557         }
   1558         goto close;
   1559     }
   1560 
   1561     if (printStatistics || getPruneList) {
   1562         size_t len = 8192;
   1563         char* buf;
   1564 
   1565         for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
   1566              delete[] buf, buf = nullptr, --retry) {
   1567             if (getPruneList) {
   1568                 android_logger_get_prune_list(logger_list, buf, len);
   1569             } else {
   1570                 android_logger_get_statistics(logger_list, buf, len);
   1571             }
   1572             buf[len - 1] = '\0';
   1573             if (atol(buf) < 3) {
   1574                 delete[] buf;
   1575                 buf = nullptr;
   1576                 break;
   1577             }
   1578             size_t ret = atol(buf) + 1;
   1579             if (ret <= len) {
   1580                 len = ret;
   1581                 break;
   1582             }
   1583             len = ret;
   1584         }
   1585 
   1586         if (!buf) {
   1587             logcat_panic(context, HELP_FALSE, "failed to read data");
   1588             goto close;
   1589         }
   1590 
   1591         // remove trailing FF
   1592         char* cp = buf + len - 1;
   1593         *cp = '\0';
   1594         bool truncated = *--cp != '\f';
   1595         if (!truncated) *cp = '\0';
   1596 
   1597         // squash out the byte count
   1598         cp = buf;
   1599         if (!truncated) {
   1600             while (isdigit(*cp)) ++cp;
   1601             if (*cp == '\n') ++cp;
   1602         }
   1603 
   1604         len = strlen(cp);
   1605         TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
   1606         delete[] buf;
   1607         goto close;
   1608     }
   1609 
   1610     if (getLogSize || setLogSize || clearLog) goto close;
   1611 
   1612     setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
   1613     if (context->stop) goto close;
   1614 
   1615     // LOG_EVENT_INT(10, 12345);
   1616     // LOG_EVENT_LONG(11, 0x1122334455667788LL);
   1617     // LOG_EVENT_STRING(0, "whassup, doc?");
   1618 
   1619     dev = nullptr;
   1620 
   1621     while (!context->stop &&
   1622            (!context->maxCount || (context->printCount < context->maxCount))) {
   1623         struct log_msg log_msg;
   1624         int ret = android_logger_list_read(logger_list, &log_msg);
   1625         if (!ret) {
   1626             logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
   1627             break;
   1628         }
   1629 
   1630         if (ret < 0) {
   1631             if (ret == -EAGAIN) break;
   1632 
   1633             if (ret == -EIO) {
   1634                 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
   1635                 break;
   1636             }
   1637             if (ret == -EINVAL) {
   1638                 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
   1639                 break;
   1640             }
   1641             logcat_panic(context, HELP_FALSE, "logcat read failure\n");
   1642             break;
   1643         }
   1644 
   1645         log_device_t* d;
   1646         for (d = context->devices; d; d = d->next) {
   1647             if (android_name_to_log_id(d->device) == log_msg.id()) break;
   1648         }
   1649         if (!d) {
   1650             context->devCount = 2; // set to Multiple
   1651             d = &unexpected;
   1652             d->binary = log_msg.id() == LOG_ID_EVENTS;
   1653         }
   1654 
   1655         if (dev != d) {
   1656             dev = d;
   1657             maybePrintStart(context, dev, printDividers);
   1658             if (context->stop) break;
   1659         }
   1660         if (context->printBinary) {
   1661             printBinary(context, &log_msg);
   1662         } else {
   1663             processBuffer(context, dev, &log_msg);
   1664         }
   1665     }
   1666 
   1667 close:
   1668     // Short and sweet. Implemented generic version in android_logcat_destroy.
   1669     while (!!(dev = context->devices)) {
   1670         context->devices = dev->next;
   1671         delete dev;
   1672     }
   1673     android_logger_list_free(logger_list);
   1674 
   1675 exit:
   1676     // close write end of pipe to help things along
   1677     if (context->output_fd == context->fds[1]) {
   1678         android::close_output(context);
   1679     }
   1680     if (context->error_fd == context->fds[1]) {
   1681         android::close_error(context);
   1682     }
   1683     if (context->fds[1] >= 0) {
   1684         // NB: should be closed by the above
   1685         int save_errno = errno;
   1686         close(context->fds[1]);
   1687         errno = save_errno;
   1688         context->fds[1] = -1;
   1689     }
   1690     context->thread_stopped = true;
   1691     return context->retval;
   1692 }
   1693 
   1694 // Can block
   1695 int android_logcat_run_command(android_logcat_context ctx,
   1696                                int output, int error,
   1697                                int argc, char* const* argv,
   1698                                char* const* envp) {
   1699     android_logcat_context_internal* context = ctx;
   1700 
   1701     context->output_fd = output;
   1702     context->error_fd = error;
   1703     context->argc = argc;
   1704     context->argv = argv;
   1705     context->envp = envp;
   1706     context->stop = false;
   1707     context->thread_stopped = false;
   1708     return __logcat(context);
   1709 }
   1710 
   1711 // starts a thread, opens a pipe, returns reading end.
   1712 int android_logcat_run_command_thread(android_logcat_context ctx,
   1713                                       int argc, char* const* argv,
   1714                                       char* const* envp) {
   1715     android_logcat_context_internal* context = ctx;
   1716 
   1717     int save_errno = EBUSY;
   1718     if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
   1719 
   1720     if (pipe(context->fds) < 0) {
   1721         save_errno = errno;
   1722         goto exit;
   1723     }
   1724 
   1725     pthread_attr_t attr;
   1726     if (pthread_attr_init(&attr)) {
   1727         save_errno = errno;
   1728         goto close_exit;
   1729     }
   1730 
   1731     struct sched_param param;
   1732     memset(&param, 0, sizeof(param));
   1733     pthread_attr_setschedparam(&attr, &param);
   1734     pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
   1735     if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
   1736         int save_errno = errno;
   1737         goto pthread_attr_exit;
   1738     }
   1739 
   1740     context->stop = false;
   1741     context->thread_stopped = false;
   1742     context->output_fd = context->fds[1];
   1743     // save off arguments so they remain while thread is active.
   1744     for (int i = 0; i < argc; ++i) {
   1745         context->args.push_back(std::string(argv[i]));
   1746     }
   1747     // save off environment so they remain while thread is active.
   1748     if (envp) for (size_t i = 0; envp[i]; ++i) {
   1749         context->envs.push_back(std::string(envp[i]));
   1750     }
   1751 
   1752     for (auto& str : context->args) {
   1753         context->argv_hold.push_back(str.c_str());
   1754     }
   1755     context->argv_hold.push_back(nullptr);
   1756     for (auto& str : context->envs) {
   1757         context->envp_hold.push_back(str.c_str());
   1758     }
   1759     context->envp_hold.push_back(nullptr);
   1760 
   1761     context->argc = context->argv_hold.size() - 1;
   1762     context->argv = (char* const*)&context->argv_hold[0];
   1763     context->envp = (char* const*)&context->envp_hold[0];
   1764 
   1765 #ifdef DEBUG
   1766     fprintf(stderr, "argv[%d] = {", context->argc);
   1767     for (auto str : context->argv_hold) {
   1768         fprintf(stderr, " \"%s\"", str ?: "nullptr");
   1769     }
   1770     fprintf(stderr, " }\n");
   1771     fflush(stderr);
   1772 #endif
   1773     context->retval = EXIT_SUCCESS;
   1774     if (pthread_create(&context->thr, &attr,
   1775                        (void*(*)(void*))__logcat, context)) {
   1776         int save_errno = errno;
   1777         goto argv_exit;
   1778     }
   1779     pthread_attr_destroy(&attr);
   1780 
   1781     return context->fds[0];
   1782 
   1783 argv_exit:
   1784     context->argv_hold.clear();
   1785     context->args.clear();
   1786     context->envp_hold.clear();
   1787     context->envs.clear();
   1788 pthread_attr_exit:
   1789     pthread_attr_destroy(&attr);
   1790 close_exit:
   1791     close(context->fds[0]);
   1792     context->fds[0] = -1;
   1793     close(context->fds[1]);
   1794     context->fds[1] = -1;
   1795 exit:
   1796     errno = save_errno;
   1797     context->stop = true;
   1798     context->thread_stopped = true;
   1799     context->retval = EXIT_FAILURE;
   1800     return -1;
   1801 }
   1802 
   1803 // test if the thread is still doing 'stuff'
   1804 int android_logcat_run_command_thread_running(android_logcat_context ctx) {
   1805     android_logcat_context_internal* context = ctx;
   1806 
   1807     return context->thread_stopped == false;
   1808 }
   1809 
   1810 // Finished with context
   1811 int android_logcat_destroy(android_logcat_context* ctx) {
   1812     android_logcat_context_internal* context = *ctx;
   1813 
   1814     if (!context) return -EBADF;
   1815 
   1816     *ctx = nullptr;
   1817 
   1818     context->stop = true;
   1819 
   1820     while (context->thread_stopped == false) {
   1821         // Makes me sad, replace thread_stopped with semaphore.  Short lived.
   1822         sched_yield();
   1823     }
   1824 
   1825     delete context->regex;
   1826     context->argv_hold.clear();
   1827     context->args.clear();
   1828     context->envp_hold.clear();
   1829     context->envs.clear();
   1830     if (context->fds[0] >= 0) {
   1831         close(context->fds[0]);
   1832         context->fds[0] = -1;
   1833     }
   1834     android::close_output(context);
   1835     android::close_error(context);
   1836     if (context->fds[1] >= 0) {
   1837         // NB: could be closed by the above fclose(s), ignore error.
   1838         int save_errno = errno;
   1839         close(context->fds[1]);
   1840         errno = save_errno;
   1841         context->fds[1] = -1;
   1842     }
   1843 
   1844     android_closeEventTagMap(context->eventTagMap);
   1845 
   1846     // generic cleanup of devices list to handle all possible dirty cases
   1847     log_device_t* dev;
   1848     while (!!(dev = context->devices)) {
   1849         struct logger_list* logger_list = dev->logger_list;
   1850         if (logger_list) {
   1851             for (log_device_t* d = dev; d; d = d->next) {
   1852                 if (d->logger_list == logger_list) d->logger_list = nullptr;
   1853             }
   1854             android_logger_list_free(logger_list);
   1855         }
   1856         context->devices = dev->next;
   1857         delete dev;
   1858     }
   1859 
   1860     int retval = context->retval;
   1861 
   1862     free(context);
   1863 
   1864     return retval;
   1865 }
   1866