blob: 04b096f0b3aa6cda5575b55fca54d967dfecae83 [file] [log] [blame]
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001// Copyright 2006-2015 The Android Open Source Project
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002
Mark Salyzynffe87bf2015-06-02 07:57:16 -07003#include <arpa/inet.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -08004#include <assert.h>
5#include <ctype.h>
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -07006#include <dirent.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -08007#include <errno.h>
8#include <fcntl.h>
Kristian Monsen12afa632015-06-05 14:10:12 -07009#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070010#include <math.h>
Mark Salyzynffe87bf2015-06-02 07:57:16 -070011#include <sched.h>
12#include <signal.h>
13#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080014#include <stdio.h>
15#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080016#include <string.h>
Traian Schiaua4808162015-04-10 15:51:39 +030017#include <sys/cdefs.h>
Riley Andrews99186a42015-06-08 23:36:34 -070018#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080019#include <sys/socket.h>
20#include <sys/stat.h>
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -070021#include <sys/types.h>
Mark Salyzynffe87bf2015-06-02 07:57:16 -070022#include <time.h>
23#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080024
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -070025#include <memory>
26#include <string>
27
Elliott Hughese016f5c2015-12-04 22:00:26 -080028#include <android-base/file.h>
29#include <android-base/strings.h>
Mark Salyzynffe87bf2015-06-02 07:57:16 -070030#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080031#include <cutils/sockets.h>
Mark Salyzynffe87bf2015-06-02 07:57:16 -070032#include <log/event_tag_map.h>
Mark Salyzyn95132e92013-11-22 10:55:48 -080033#include <log/log.h>
Mark Salyzynfa3716b2014-02-14 16:05:05 -080034#include <log/log_read.h>
Colin Cross9227bd32013-07-23 16:59:20 -070035#include <log/logd.h>
Mark Salyzynffe87bf2015-06-02 07:57:16 -070036#include <log/logger.h>
Colin Cross9227bd32013-07-23 16:59:20 -070037#include <log/logprint.h>
Elliott Hughesc0c649e2016-02-17 11:58:01 -080038#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039
Casey Dahlin02834892016-03-17 16:18:55 -070040#include <pcrecpp.h>
41
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#define DEFAULT_MAX_ROTATED_LOGS 4
43
44static AndroidLogFormat * g_logformat;
45
46/* logd prefixes records with a length field */
47#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
48
Joe Onorato6fa09a02010-02-26 10:04:23 -080049struct log_device_t {
Mark Salyzyn95132e92013-11-22 10:55:48 -080050 const char* device;
Joe Onorato6fa09a02010-02-26 10:04:23 -080051 bool binary;
Mark Salyzyn95132e92013-11-22 10:55:48 -080052 struct logger *logger;
53 struct logger_list *logger_list;
Joe Onorato6fa09a02010-02-26 10:04:23 -080054 bool printed;
Joe Onorato6fa09a02010-02-26 10:04:23 -080055
Joe Onorato6fa09a02010-02-26 10:04:23 -080056 log_device_t* next;
57
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -080058 log_device_t(const char* d, bool b) {
Joe Onorato6fa09a02010-02-26 10:04:23 -080059 device = d;
60 binary = b;
Joe Onorato6fa09a02010-02-26 10:04:23 -080061 next = NULL;
62 printed = false;
Traian Schiaua4808162015-04-10 15:51:39 +030063 logger = NULL;
64 logger_list = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -080065 }
Joe Onorato6fa09a02010-02-26 10:04:23 -080066};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080067
68namespace android {
69
70/* Global Variables */
71
Mark Salyzyn96005072016-03-30 12:38:29 -070072static const char * g_outputFileName;
Traian Schiaua4808162015-04-10 15:51:39 +030073// 0 means "no log rotation"
Mark Salyzyn96005072016-03-30 12:38:29 -070074static size_t g_logRotateSizeKBytes;
Traian Schiaua4808162015-04-10 15:51:39 +030075// 0 means "unbounded"
76static size_t g_maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080077static int g_outFD = -1;
Mark Salyzyn96005072016-03-30 12:38:29 -070078static size_t g_outByteCount;
79static int g_printBinary;
80static int g_devCount; // >1 means multiple
Casey Dahlin02834892016-03-17 16:18:55 -070081static pcrecpp::RE* g_regex;
Casey Dahlin4915bbf2016-03-17 14:04:52 -070082// 0 means "infinite"
Mark Salyzyn96005072016-03-30 12:38:29 -070083static size_t g_maxCount;
84static size_t g_printCount;
Mark Salyzyn46557d12016-03-30 09:38:31 -070085static bool g_printItAnyways;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080086
Mark Salyzyn9391ebd2016-03-30 12:38:29 -070087// if showHelp is set, newline required in fmt statement to transition to usage
Traian Schiaua4808162015-04-10 15:51:39 +030088__noreturn static void logcat_panic(bool showHelp, const char *fmt, ...) __printflike(2,3);
89
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080090static int openLogFile (const char *pathname)
91{
Edwin Vane80b221c2012-08-13 12:55:07 -040092 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093}
94
95static void rotateLogs()
96{
97 int err;
98
99 // Can't rotate logs if we're not outputting to a file
100 if (g_outputFileName == NULL) {
101 return;
102 }
103
104 close(g_outFD);
105
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700106 // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
107 // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
108 int maxRotationCountDigits =
109 (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
110
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800111 for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
112 char *file0, *file1;
113
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700114 asprintf(&file1, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800115
116 if (i - 1 == 0) {
117 asprintf(&file0, "%s", g_outputFileName);
118 } else {
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700119 asprintf(&file0, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120 }
121
Traian Schiaua4808162015-04-10 15:51:39 +0300122 if (!file0 || !file1) {
123 perror("while rotating log files");
124 break;
125 }
126
127 err = rename(file0, file1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128
129 if (err < 0 && errno != ENOENT) {
130 perror("while rotating log files");
131 }
132
133 free(file1);
134 free(file0);
135 }
136
Traian Schiaua4808162015-04-10 15:51:39 +0300137 g_outFD = openLogFile(g_outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800138
139 if (g_outFD < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +0300140 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800141 }
142
143 g_outByteCount = 0;
144
145}
146
Mark Salyzyn95132e92013-11-22 10:55:48 -0800147void printBinary(struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148{
Mark Salyzyn95132e92013-11-22 10:55:48 -0800149 size_t size = buf->len();
150
151 TEMP_FAILURE_RETRY(write(g_outFD, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152}
153
Mark Salyzyn9391ebd2016-03-30 12:38:29 -0700154static bool regexOk(const AndroidLogEntry& entry)
Casey Dahlin02834892016-03-17 16:18:55 -0700155{
Mark Salyzyn9391ebd2016-03-30 12:38:29 -0700156 if (!g_regex) {
Casey Dahlin02834892016-03-17 16:18:55 -0700157 return true;
158 }
159
Casey Dahlin02834892016-03-17 16:18:55 -0700160 std::string messageString(entry.message, entry.messageLen);
161
162 return g_regex->PartialMatch(messageString);
163}
164
Mark Salyzyn95132e92013-11-22 10:55:48 -0800165static void processBuffer(log_device_t* dev, struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800166{
Mathias Agopian50844522010-03-17 16:10:26 -0700167 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800168 int err;
169 AndroidLogEntry entry;
170 char binaryMsgBuf[1024];
171
Joe Onorato6fa09a02010-02-26 10:04:23 -0800172 if (dev->binary) {
Mark Salyzyn51a71422015-02-26 14:33:35 -0800173 static bool hasOpenedEventTagMap = false;
174 static EventTagMap *eventTagMap = NULL;
175
176 if (!eventTagMap && !hasOpenedEventTagMap) {
177 eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
178 hasOpenedEventTagMap = true;
179 }
Mark Salyzyn95132e92013-11-22 10:55:48 -0800180 err = android_log_processBinaryLogBuffer(&buf->entry_v1, &entry,
Mark Salyzyn51a71422015-02-26 14:33:35 -0800181 eventTagMap,
Mark Salyzyn95132e92013-11-22 10:55:48 -0800182 binaryMsgBuf,
183 sizeof(binaryMsgBuf));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800184 //printf(">>> pri=%d len=%d msg='%s'\n",
185 // entry.priority, entry.messageLen, entry.message);
186 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800187 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800189 if (err < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800190 goto error;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800191 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192
Mark Salyzyn46557d12016-03-30 09:38:31 -0700193 if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
194 bool match = regexOk(entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800195
Mark Salyzyn46557d12016-03-30 09:38:31 -0700196 g_printCount += match;
197 if (match || g_printItAnyways) {
198 bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700199
Mark Salyzyn46557d12016-03-30 09:38:31 -0700200 if (bytesWritten < 0) {
201 logcat_panic(false, "output error");
202 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800203 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800204 }
205
206 g_outByteCount += bytesWritten;
207
Mark Salyzyn95132e92013-11-22 10:55:48 -0800208 if (g_logRotateSizeKBytes > 0
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800209 && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
210 ) {
211 rotateLogs();
212 }
213
214error:
215 //fprintf (stderr, "Error processing record\n");
216 return;
217}
218
Mark Salyzyn0a890f92015-01-26 13:41:33 -0800219static void maybePrintStart(log_device_t* dev, bool printDividers) {
220 if (!dev->printed || printDividers) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800221 if (g_devCount > 1 && !g_printBinary) {
222 char buf[1024];
Mark Salyzyn0a890f92015-01-26 13:41:33 -0800223 snprintf(buf, sizeof(buf), "--------- %s %s\n",
224 dev->printed ? "switch to" : "beginning of",
Mark Salyzyn95132e92013-11-22 10:55:48 -0800225 dev->device);
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800226 if (write(g_outFD, buf, strlen(buf)) < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +0300227 logcat_panic(false, "output error");
Joe Onorato6fa09a02010-02-26 10:04:23 -0800228 }
229 }
Mark Salyzyn0a890f92015-01-26 13:41:33 -0800230 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800231 }
232}
233
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234static void setupOutput()
235{
236
237 if (g_outputFileName == NULL) {
238 g_outFD = STDOUT_FILENO;
239
240 } else {
Mark Salyzynffe87bf2015-06-02 07:57:16 -0700241 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
242 fprintf(stderr, "failed to set background scheduling policy\n");
243 }
244
245 struct sched_param param;
246 memset(&param, 0, sizeof(param));
247 if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
248 fprintf(stderr, "failed to set to batch scheduler\n");
249 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800250
Riley Andrews99186a42015-06-08 23:36:34 -0700251 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
252 fprintf(stderr, "failed set to priority\n");
253 }
254
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800255 g_outFD = openLogFile (g_outputFileName);
256
257 if (g_outFD < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +0300258 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800259 }
260
Mark Salyzynffe87bf2015-06-02 07:57:16 -0700261 struct stat statbuf;
Traian Schiaua4808162015-04-10 15:51:39 +0300262 if (fstat(g_outFD, &statbuf) == -1) {
263 close(g_outFD);
264 logcat_panic(false, "couldn't get output file stat\n");
265 }
266
267 if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
268 close(g_outFD);
269 logcat_panic(false, "invalid output file stat\n");
270 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800271
272 g_outByteCount = statbuf.st_size;
273 }
274}
275
276static void show_help(const char *cmd)
277{
278 fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
279
280 fprintf(stderr, "options include:\n"
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700281 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
282 " -f <file>, --file=<file> Log to file. Default is stdout\n"
283 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
284 " Rotate log every kbytes. Requires -f option\n"
285 " -n <count>, --rotate-count=<count>\n"
286 " Sets max number of rotated logs to <count>, default 4\n"
287 " -v <format>, --format=<format>\n"
288 " Sets the log print format, where <format> is:\n"
289 " brief color epoch long monotonic printable process raw\n"
290 " tag thread threadtime time uid usec UTC year zone\n"
291 " -D, --dividers Print dividers between each log buffer\n"
292 " -c, --clear Clear (flush) the entire log and exit\n"
293 " -d Dump the log and then exit (don't block)\n"
294 " -e <expr>, --regex=<expr>\n"
295 " Only print lines where the log message matches <expr>\n"
296 " where <expr> is a regular expression\n"
297 // Leave --head undocumented as alias for -m
298 " -m <count>, --max-count=<count>\n"
299 " Quit after printing <count> lines. This is meant to be\n"
300 " paired with --regex, but will work on its own.\n"
301 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzyn46557d12016-03-30 09:38:31 -0700302 " regex filter but still stop at number of matches.\n"
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700303 // Leave --tail undocumented as alias for -t
304 " -t <count> Print only the most recent <count> lines (implies -d)\n"
305 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
306 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
307 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700308 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn46d758e2015-08-31 15:53:41 -0700309 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700310 " -g, --buffer-size Get the size of the ring buffer.\n"
311 " -G <size>, --buffer-size=<size>\n"
312 " Set size of log ring buffer, may suffix with K or M.\n"
313 " -L, -last Dump logs from prior to last reboot\n"
Mark Salyzynef5f6642015-12-04 10:59:45 -0800314 // Leave security (Device Owner only installations) and
315 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700316 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
317 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
318 " Multiple -b parameters are allowed. Buffers interleaved.\n"
319 " Default -b main -b system -b crash.\n"
320 " -B, --binary Output the log in binary.\n"
321 " -S, --statistics Output statistics.\n"
322 " -p, --prune Print prune white and ~black list. Service is specified as\n"
323 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700324 " with ~, otherwise weighed for longevity if unadorned. All\n"
325 " other pruning activity is oldest first. Special case ~!\n"
326 " represents an automatic quicker pruning for the noisiest\n"
327 " UID as determined by the current statistics.\n"
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700328 " -P '<list> ...', --prune='<list> ...'\n"
329 " Set prune white and ~black list, using same format as\n"
330 " listed above. Must be quoted.\n"
Mark Salyzyn229a5b62015-11-30 13:48:56 -0800331 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn46a24de2016-04-12 09:11:46 -0700332 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn229a5b62015-11-30 13:48:56 -0800333 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
334 " comes first. Improves efficiency of polling by providing\n"
335 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800336
337 fprintf(stderr,"\nfilterspecs are a series of \n"
338 " <tag>[:priority]\n\n"
339 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzyna23cd1c2015-03-09 09:32:56 -0700340 " V Verbose (default for <tag>)\n"
341 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800342 " I Info\n"
343 " W Warn\n"
344 " E Error\n"
345 " F Fatal\n"
Mark Salyzyna23cd1c2015-03-09 09:32:56 -0700346 " S Silent (suppress all output)\n"
347 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
348 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
349 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
350 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
351 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700352 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800353}
354
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355static int setLogFormat(const char * formatString)
356{
357 static AndroidLogPrintFormat format;
358
359 format = android_log_formatFromString(formatString);
360
361 if (format == FORMAT_OFF) {
362 // FORMAT_OFF means invalid string
363 return -1;
364 }
365
Mark Salyzyndbc49232015-05-06 08:40:40 -0700366 return android_log_setPrintFormat(g_logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800367}
368
Mark Salyzyn671e3432014-05-06 07:34:59 -0700369static const char multipliers[][2] = {
370 { "" },
371 { "K" },
372 { "M" },
373 { "G" }
374};
375
376static unsigned long value_of_size(unsigned long value)
377{
378 for (unsigned i = 0;
379 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
380 value /= 1024, ++i) ;
381 return value;
382}
383
384static const char *multiplier_of_size(unsigned long value)
385{
386 unsigned i;
387 for (i = 0;
388 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
389 value /= 1024, ++i) ;
390 return multipliers[i];
391}
392
Traian Schiaua4808162015-04-10 15:51:39 +0300393/*String to unsigned int, returns -1 if it fails*/
394static bool getSizeTArg(char *ptr, size_t *val, size_t min = 0,
395 size_t max = SIZE_MAX)
396{
Kristian Monsen12afa632015-06-05 14:10:12 -0700397 if (!ptr) {
Traian Schiaua4808162015-04-10 15:51:39 +0300398 return false;
399 }
400
Kristian Monsen12afa632015-06-05 14:10:12 -0700401 char *endp;
402 errno = 0;
403 size_t ret = (size_t)strtoll(ptr, &endp, 0);
404
405 if (endp[0] || errno) {
406 return false;
407 }
408
409 if ((ret > max) || (ret < min)) {
Traian Schiaua4808162015-04-10 15:51:39 +0300410 return false;
411 }
412
413 *val = ret;
414 return true;
415}
416
417static void logcat_panic(bool showHelp, const char *fmt, ...)
418{
Mark Salyzyn2e4282a2015-04-13 09:27:57 -0700419 va_list args;
420 va_start(args, fmt);
421 vfprintf(stderr, fmt, args);
422 va_end(args);
Traian Schiaua4808162015-04-10 15:51:39 +0300423
424 if (showHelp) {
425 show_help(getprogname());
426 }
427
428 exit(EXIT_FAILURE);
429}
430
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700431static char *parseTime(log_time &t, const char *cp) {
432
433 char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
434 if (ep) {
435 return ep;
436 }
Mark Salyzyn46d758e2015-08-31 15:53:41 -0700437 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
438 if (ep) {
439 return ep;
440 }
441 return t.strptime(cp, "%s.%q");
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700442}
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700443
444// Find last logged line in gestalt of all matching existing output files
445static log_time lastLogTime(char *outputFileName) {
446 log_time retval(log_time::EPOCH);
447 if (!outputFileName) {
448 return retval;
449 }
450
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700451 std::string directory;
452 char *file = strrchr(outputFileName, '/');
453 if (!file) {
454 directory = ".";
455 file = outputFileName;
456 } else {
457 *file = '\0';
458 directory = outputFileName;
459 *file = '/';
460 ++file;
461 }
Mark Salyzynd66535a2016-04-01 07:52:20 -0700462
463 std::unique_ptr<DIR, int(*)(DIR*)>
464 dir(opendir(directory.c_str()), closedir);
465 if (!dir.get()) {
466 return retval;
467 }
468
469 clockid_t clock_type = android_log_clockid();
470 log_time now(clock_type);
471 bool monotonic = clock_type == CLOCK_MONOTONIC;
472
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700473 size_t len = strlen(file);
474 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700475 struct dirent *dp;
Mark Salyzynd66535a2016-04-01 07:52:20 -0700476
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700477 while ((dp = readdir(dir.get())) != NULL) {
478 if ((dp->d_type != DT_REG)
Mark Salyzyn029215b2015-09-08 08:56:32 -0700479 // If we are using realtime, check all files that match the
480 // basename for latest time. If we are using monotonic time
481 // then only check the main file because time cycles on
482 // every reboot.
483 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700484 || (dp->d_name[len]
485 && ((dp->d_name[len] != '.')
486 || !isdigit(dp->d_name[len+1])))) {
487 continue;
488 }
489
490 std::string file_name = directory;
491 file_name += "/";
492 file_name += dp->d_name;
493 std::string file;
494 if (!android::base::ReadFileToString(file_name, &file)) {
495 continue;
496 }
497
498 bool found = false;
499 for (const auto& line : android::base::Split(file, "\n")) {
500 log_time t(log_time::EPOCH);
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700501 char *ep = parseTime(t, line.c_str());
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700502 if (!ep || (*ep != ' ')) {
503 continue;
504 }
505 // determine the time precision of the logs (eg: msec or usec)
506 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
507 if (t.tv_nsec % (mod * 10)) {
508 modulo.tv_nsec = mod;
509 break;
510 }
511 }
512 // We filter any times later than current as we may not have the
513 // year stored with each log entry. Also, since it is possible for
514 // entries to be recorded out of order (very rare) we select the
515 // maximum we find just in case.
516 if ((t < now) && (t > retval)) {
517 retval = t;
518 found = true;
519 }
520 }
521 // We count on the basename file to be the definitive end, so stop here.
522 if (!dp->d_name[len] && found) {
523 break;
524 }
525 }
526 if (retval == log_time::EPOCH) {
527 return retval;
528 }
529 // tail_time prints matching or higher, round up by the modulo to prevent
530 // a replay of the last entry we have just checked.
531 retval += modulo;
532 return retval;
533}
534
Traian Schiaua4808162015-04-10 15:51:39 +0300535} /* namespace android */
536
537
Joe Onorato6fa09a02010-02-26 10:04:23 -0800538int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800539{
Traian Schiaua4808162015-04-10 15:51:39 +0300540 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541 int err;
542 int hasSetLogFormat = 0;
543 int clearLog = 0;
544 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800545 unsigned long setLogSize = 0;
546 int getPruneList = 0;
547 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800548 int printStatistics = 0;
Mark Salyzyneae52fb2015-01-26 10:46:44 -0800549 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800551 log_device_t* devices = NULL;
552 log_device_t* dev;
Mark Salyzyn0a890f92015-01-26 13:41:33 -0800553 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800554 struct logger_list *logger_list;
Traian Schiaua4808162015-04-10 15:51:39 +0300555 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800556 log_time tail_time(log_time::EPOCH);
Kristian Monsen12afa632015-06-05 14:10:12 -0700557 size_t pid = 0;
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700558 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800560 signal(SIGPIPE, exit);
561
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562 g_logformat = android_log_format_new();
563
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiaua4808162015-04-10 15:51:39 +0300565 show_help(argv[0]);
566 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567 }
568
569 for (;;) {
570 int ret;
571
Kristian Monsen12afa632015-06-05 14:10:12 -0700572 int option_index = 0;
Mark Salyzyn46557d12016-03-30 09:38:31 -0700573 // list of long-argument only strings for later comparison
Kristian Monsen12afa632015-06-05 14:10:12 -0700574 static const char pid_str[] = "pid";
Mark Salyzyn229a5b62015-11-30 13:48:56 -0800575 static const char wrap_str[] = "wrap";
Mark Salyzyn46557d12016-03-30 09:38:31 -0700576 static const char print_str[] = "print";
Kristian Monsen12afa632015-06-05 14:10:12 -0700577 static const struct option long_options[] = {
Mark Salyzynf747f272015-11-30 12:57:56 -0800578 { "binary", no_argument, NULL, 'B' },
579 { "buffer", required_argument, NULL, 'b' },
Mark Salyzyn31710c02016-03-30 09:15:09 -0700580 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf747f272015-11-30 12:57:56 -0800581 { "clear", no_argument, NULL, 'c' },
582 { "dividers", no_argument, NULL, 'D' },
583 { "file", required_argument, NULL, 'f' },
584 { "format", required_argument, NULL, 'v' },
Mark Salyzynd66535a2016-04-01 07:52:20 -0700585 // hidden and undocumented reserved alias for --regex
586 { "grep", required_argument, NULL, 'e' },
Mark Salyzyn31710c02016-03-30 09:15:09 -0700587 // hidden and undocumented reserved alias for --max-count
588 { "head", required_argument, NULL, 'm' },
Mark Salyzynf747f272015-11-30 12:57:56 -0800589 { "last", no_argument, NULL, 'L' },
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700590 { "max-count", required_argument, NULL, 'm' },
Mark Salyzynd66535a2016-04-01 07:52:20 -0700591 { pid_str, required_argument, NULL, 0 },
Mark Salyzyn46557d12016-03-30 09:38:31 -0700592 { print_str, no_argument, NULL, 0 },
Mark Salyzynf747f272015-11-30 12:57:56 -0800593 { "prune", optional_argument, NULL, 'p' },
Casey Dahlin02834892016-03-17 16:18:55 -0700594 { "regex", required_argument, NULL, 'e' },
Mark Salyzyn31710c02016-03-30 09:15:09 -0700595 { "rotate-count", required_argument, NULL, 'n' },
596 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf747f272015-11-30 12:57:56 -0800597 { "statistics", no_argument, NULL, 'S' },
Mark Salyzyn31710c02016-03-30 09:15:09 -0700598 // hidden and undocumented reserved alias for -t
599 { "tail", required_argument, NULL, 't' },
Mark Salyzyn229a5b62015-11-30 13:48:56 -0800600 // support, but ignore and do not document, the optional argument
601 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen12afa632015-06-05 14:10:12 -0700602 { NULL, 0, NULL, 0 }
603 };
604
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700605 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen12afa632015-06-05 14:10:12 -0700606 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800607
608 if (ret < 0) {
609 break;
610 }
611
Kristian Monsen12afa632015-06-05 14:10:12 -0700612 switch (ret) {
613 case 0:
614 // One of the long options
615 if (long_options[option_index].name == pid_str) {
616 // ToDo: determine runtime PID_MAX?
617 if (!getSizeTArg(optarg, &pid, 1)) {
618 logcat_panic(true, "%s %s out of range\n",
619 long_options[option_index].name, optarg);
620 }
621 break;
622 }
Mark Salyzyn229a5b62015-11-30 13:48:56 -0800623 if (long_options[option_index].name == wrap_str) {
624 mode |= ANDROID_LOG_WRAP |
625 ANDROID_LOG_RDONLY |
626 ANDROID_LOG_NONBLOCK;
627 // ToDo: implement API that supports setting a wrap timeout
628 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
629 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
630 logcat_panic(true, "%s %s out of range\n",
631 long_options[option_index].name, optarg);
632 }
633 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
634 fprintf(stderr,
635 "WARNING: %s %u seconds, ignoring %zu\n",
636 long_options[option_index].name,
637 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
638 }
639 break;
640 }
Mark Salyzyn46557d12016-03-30 09:38:31 -0700641 if (long_options[option_index].name == print_str) {
642 g_printItAnyways = true;
643 break;
644 }
Kristian Monsen12afa632015-06-05 14:10:12 -0700645 break;
646
Mark Salyzyn95132e92013-11-22 10:55:48 -0800647 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800648 // default to all silent
649 android_log_addFilterRule(g_logformat, "*:s");
650 break;
651
652 case 'c':
653 clearLog = 1;
Mark Salyzyneae52fb2015-01-26 10:46:44 -0800654 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655 break;
656
Mark Salyzyna8e998e2014-12-15 10:01:31 -0800657 case 'L':
658 mode |= ANDROID_LOG_PSTORE;
659 break;
660
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800661 case 'd':
Mark Salyzyneae52fb2015-01-26 10:46:44 -0800662 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800663 break;
664
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800665 case 't':
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700666 got_t = true;
Mark Salyzyneae52fb2015-01-26 10:46:44 -0800667 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800668 /* FALLTHRU */
669 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800670 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700671 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800672 if (!cp) {
Mark Salyzyn8c680ac2015-08-31 08:01:33 -0700673 logcat_panic(false, "-%c \"%s\" not in time format\n",
674 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800675 }
676 if (*cp) {
677 char c = *cp;
678 *cp = '\0';
679 fprintf(stderr,
680 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
681 ret, optarg, c, cp + 1);
682 *cp = c;
683 }
684 } else {
Traian Schiaua4808162015-04-10 15:51:39 +0300685 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800686 fprintf(stderr,
687 "WARNING: -%c %s invalid, setting to 1\n",
688 ret, optarg);
689 tail_lines = 1;
690 }
691 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800692 break;
693
Mark Salyzyn0a890f92015-01-26 13:41:33 -0800694 case 'D':
695 printDividers = true;
696 break;
697
Casey Dahlin02834892016-03-17 16:18:55 -0700698 case 'e':
699 g_regex = new pcrecpp::RE(optarg);
700 break;
701
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700702 case 'm': {
703 char *end = NULL;
704 if (!getSizeTArg(optarg, &g_maxCount)) {
705 logcat_panic(false, "-%c \"%s\" isn't an "
706 "integer greater than zero\n", ret, optarg);
707 }
708 }
709 break;
710
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800711 case 'g':
Mark Salyzynf747f272015-11-30 12:57:56 -0800712 if (!optarg) {
713 getLogSize = 1;
714 break;
715 }
716 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800717
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800718 case 'G': {
Traian Schiaua4808162015-04-10 15:51:39 +0300719 char *cp;
720 if (strtoll(optarg, &cp, 0) > 0) {
721 setLogSize = strtoll(optarg, &cp, 0);
722 } else {
723 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800724 }
725
726 switch(*cp) {
727 case 'g':
728 case 'G':
729 setLogSize *= 1024;
730 /* FALLTHRU */
731 case 'm':
732 case 'M':
733 setLogSize *= 1024;
734 /* FALLTHRU */
735 case 'k':
736 case 'K':
737 setLogSize *= 1024;
738 /* FALLTHRU */
739 case '\0':
740 break;
741
742 default:
743 setLogSize = 0;
744 }
745
746 if (!setLogSize) {
747 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiaua4808162015-04-10 15:51:39 +0300748 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800749 }
750 }
751 break;
752
753 case 'p':
Mark Salyzynf747f272015-11-30 12:57:56 -0800754 if (!optarg) {
755 getPruneList = 1;
756 break;
757 }
758 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800759
760 case 'P':
761 setPruneList = optarg;
762 break;
763
Joe Onorato6fa09a02010-02-26 10:04:23 -0800764 case 'b': {
Mark Salyzynef5f6642015-12-04 10:59:45 -0800765 if (strcmp(optarg, "default") == 0) {
766 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
767 switch (i) {
768 case LOG_ID_SECURITY:
769 case LOG_ID_EVENTS:
770 continue;
771 case LOG_ID_MAIN:
772 case LOG_ID_SYSTEM:
773 case LOG_ID_CRASH:
774 break;
775 default:
776 continue;
777 }
Mark Salyzyn34facab2014-02-06 14:48:50 -0800778
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700779 const char *name = android_log_id_to_name((log_id_t)i);
780 log_id_t log_id = android_name_to_log_id(name);
781
782 if (log_id != (log_id_t)i) {
783 continue;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800784 }
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700785
Mark Salyzynef5f6642015-12-04 10:59:45 -0800786 bool found = false;
787 for (dev = devices; dev; dev = dev->next) {
788 if (!strcmp(optarg, dev->device)) {
789 found = true;
790 break;
791 }
792 if (!dev->next) {
793 break;
794 }
795 }
796 if (found) {
797 break;
798 }
799
800 log_device_t* d = new log_device_t(name, false);
801
802 if (dev) {
803 dev->next = d;
804 dev = d;
805 } else {
806 devices = dev = d;
807 }
808 g_devCount++;
809 }
810 break;
811 }
812
813 if (strcmp(optarg, "all") == 0) {
814 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
815 const char *name = android_log_id_to_name((log_id_t)i);
816 log_id_t log_id = android_name_to_log_id(name);
817
818 if (log_id != (log_id_t)i) {
819 continue;
820 }
821
822 bool found = false;
823 for (dev = devices; dev; dev = dev->next) {
824 if (!strcmp(optarg, dev->device)) {
825 found = true;
826 break;
827 }
828 if (!dev->next) {
829 break;
830 }
831 }
832 if (found) {
833 break;
834 }
835
836 bool binary = !strcmp(name, "events") ||
837 !strcmp(name, "security");
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -0800838 log_device_t* d = new log_device_t(name, binary);
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700839
840 if (dev) {
841 dev->next = d;
842 dev = d;
843 } else {
844 devices = dev = d;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800845 }
Traian Schiaua4808162015-04-10 15:51:39 +0300846 g_devCount++;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800847 }
848 break;
849 }
850
Mark Salyzynef5f6642015-12-04 10:59:45 -0800851 bool binary = !(strcmp(optarg, "events") &&
852 strcmp(optarg, "security"));
Joe Onorato6fa09a02010-02-26 10:04:23 -0800853
854 if (devices) {
855 dev = devices;
856 while (dev->next) {
Mark Salyzynef5f6642015-12-04 10:59:45 -0800857 if (!strcmp(optarg, dev->device)) {
858 dev = NULL;
859 break;
860 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800861 dev = dev->next;
862 }
Mark Salyzynef5f6642015-12-04 10:59:45 -0800863 if (dev) {
864 dev->next = new log_device_t(optarg, binary);
865 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800866 } else {
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -0800867 devices = new log_device_t(optarg, binary);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800868 }
Traian Schiaua4808162015-04-10 15:51:39 +0300869 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800870 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800871 break;
872
873 case 'B':
Traian Schiaua4808162015-04-10 15:51:39 +0300874 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800875 break;
876
877 case 'f':
Mark Salyzyn3fe8f1c2015-10-06 08:59:02 -0700878 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzyn0acc3ef2015-05-27 07:39:56 -0700879 tail_time = lastLogTime(optarg);
880 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800881 // redirect output to a file
Traian Schiaua4808162015-04-10 15:51:39 +0300882 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800883 break;
884
885 case 'r':
Traian Schiaua4808162015-04-10 15:51:39 +0300886 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
887 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888 }
889 break;
890
891 case 'n':
Traian Schiaua4808162015-04-10 15:51:39 +0300892 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
893 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800894 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800895 break;
896
897 case 'v':
898 err = setLogFormat (optarg);
899 if (err < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +0300900 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901 }
Mark Salyzyndbc49232015-05-06 08:40:40 -0700902 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800903 break;
904
905 case 'Q':
906 /* this is a *hidden* option used to start a version of logcat */
907 /* in an emulated device only. it basically looks for androidboot.logcat= */
908 /* on the kernel command line. If something is found, it extracts a log filter */
909 /* and uses it to run the program. If nothing is found, the program should */
910 /* quit immediately */
911#define KERNEL_OPTION "androidboot.logcat="
912#define CONSOLE_OPTION "androidboot.console="
913 {
914 int fd;
915 char* logcat;
916 char* console;
917 int force_exit = 1;
918 static char cmdline[1024];
919
920 fd = open("/proc/cmdline", O_RDONLY);
921 if (fd >= 0) {
922 int n = read(fd, cmdline, sizeof(cmdline)-1 );
923 if (n < 0) n = 0;
924 cmdline[n] = 0;
925 close(fd);
926 } else {
927 cmdline[0] = 0;
928 }
929
930 logcat = strstr( cmdline, KERNEL_OPTION );
931 console = strstr( cmdline, CONSOLE_OPTION );
932 if (logcat != NULL) {
933 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
934 char* q = strpbrk( p, " \t\n\r" );;
935
936 if (q != NULL)
937 *q = 0;
938
939 forceFilters = p;
940 force_exit = 0;
941 }
942 /* if nothing found or invalid filters, exit quietly */
Traian Schiaua4808162015-04-10 15:51:39 +0300943 if (force_exit) {
944 return EXIT_SUCCESS;
945 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800946
947 /* redirect our output to the emulator console */
948 if (console) {
949 char* p = console + sizeof(CONSOLE_OPTION)-1;
950 char* q = strpbrk( p, " \t\n\r" );
951 char devname[64];
952 int len;
953
954 if (q != NULL) {
955 len = q - p;
956 } else
957 len = strlen(p);
958
959 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
960 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
961 if (len < (int)sizeof(devname)) {
962 fd = open( devname, O_WRONLY );
963 if (fd >= 0) {
964 dup2(fd, 1);
965 dup2(fd, 2);
966 close(fd);
967 }
968 }
969 }
970 }
971 break;
972
Mark Salyzyn34facab2014-02-06 14:48:50 -0800973 case 'S':
974 printStatistics = 1;
975 break;
976
Traian Schiaua4808162015-04-10 15:51:39 +0300977 case ':':
978 logcat_panic(true, "Option -%c needs an argument\n", optopt);
979 break;
980
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800981 default:
Traian Schiaua4808162015-04-10 15:51:39 +0300982 logcat_panic(true, "Unrecognized Option %c\n", optopt);
983 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800984 }
985 }
986
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700987 if (g_maxCount && got_t) {
Mark Salyzyn9391ebd2016-03-30 12:38:29 -0700988 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700989 }
Mark Salyzyn46557d12016-03-30 09:38:31 -0700990 if (g_printItAnyways && (!g_regex || !g_maxCount)) {
991 // One day it would be nice if --print -v color and --regex <expr>
992 // could play with each other and show regex highlighted content.
993 fprintf(stderr, "WARNING: "
994 "--print ignored, to be used in combination with\n"
995 " "
996 "--regex <expr> and --max-count <N>\n");
997 g_printItAnyways = false;
998 }
Casey Dahlin4915bbf2016-03-17 14:04:52 -0700999
Joe Onorato6fa09a02010-02-26 10:04:23 -08001000 if (!devices) {
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -08001001 dev = devices = new log_device_t("main", false);
Traian Schiaua4808162015-04-10 15:51:39 +03001002 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001003 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -08001004 dev = dev->next = new log_device_t("system", false);
Traian Schiaua4808162015-04-10 15:51:39 +03001005 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001006 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001007 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -08001008 dev = dev->next = new log_device_t("crash", false);
Traian Schiaua4808162015-04-10 15:51:39 +03001009 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001010 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001011 }
1012
Traian Schiaua4808162015-04-10 15:51:39 +03001013 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
1014 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001015 }
1016
Traian Schiaua4808162015-04-10 15:51:39 +03001017 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018
1019 if (hasSetLogFormat == 0) {
1020 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
1021
1022 if (logFormat != NULL) {
1023 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001025 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026 logFormat);
1027 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001028 } else {
1029 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030 }
1031 }
1032
1033 if (forceFilters) {
1034 err = android_log_addFilterString(g_logformat, forceFilters);
1035 if (err < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +03001036 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001037 }
1038 } else if (argc == optind) {
1039 // Add from environment variable
1040 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1041
1042 if (env_tags_orig != NULL) {
1043 err = android_log_addFilterString(g_logformat, env_tags_orig);
1044
Mark Salyzyn95132e92013-11-22 10:55:48 -08001045 if (err < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +03001046 logcat_panic(true,
1047 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001048 }
1049 }
1050 } else {
1051 // Add from commandline
1052 for (int i = optind ; i < argc ; i++) {
1053 err = android_log_addFilterString(g_logformat, argv[i]);
1054
Mark Salyzyn95132e92013-11-22 10:55:48 -08001055 if (err < 0) {
Traian Schiaua4808162015-04-10 15:51:39 +03001056 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001057 }
1058 }
1059 }
1060
Joe Onorato6fa09a02010-02-26 10:04:23 -08001061 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001062 if (tail_time != log_time::EPOCH) {
Kristian Monsen12afa632015-06-05 14:10:12 -07001063 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001064 } else {
Kristian Monsen12afa632015-06-05 14:10:12 -07001065 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001066 }
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001067 const char *openDeviceFail = NULL;
1068 const char *clearFail = NULL;
1069 const char *setSizeFail = NULL;
1070 const char *getSizeFail = NULL;
1071 // We have three orthogonal actions below to clear, set log size and
1072 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001073 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001074 dev->logger_list = logger_list;
1075 dev->logger = android_logger_open(logger_list,
1076 android_name_to_log_id(dev->device));
1077 if (!dev->logger) {
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001078 openDeviceFail = openDeviceFail ?: dev->device;
1079 dev = dev->next;
1080 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001081 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001082
1083 if (clearLog) {
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001084 if (android_logger_clear(dev->logger)) {
1085 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001086 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001087 }
1088
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001089 if (setLogSize) {
1090 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1091 setSizeFail = setSizeFail ?: dev->device;
1092 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001093 }
1094
Joe Onorato6fa09a02010-02-26 10:04:23 -08001095 if (getLogSize) {
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001096 long size = android_logger_get_log_size(dev->logger);
1097 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001098
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001099 if ((size < 0) || (readable < 0)) {
1100 getSizeFail = getSizeFail ?: dev->device;
1101 } else {
1102 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1103 "max entry is %db, max payload is %db\n", dev->device,
1104 value_of_size(size), multiplier_of_size(size),
1105 value_of_size(readable), multiplier_of_size(readable),
1106 (int) LOGGER_ENTRY_MAX_LEN,
1107 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001108 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001109 }
1110
1111 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001112 }
Mark Salyzynfef00ae2015-09-16 15:34:00 -07001113 // report any errors in the above loop and exit
1114 if (openDeviceFail) {
1115 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1116 }
1117 if (clearFail) {
1118 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1119 }
1120 if (setSizeFail) {
1121 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1122 }
1123 if (getSizeFail) {
1124 logcat_panic(false, "failed to get the readable '%s' log size",
1125 getSizeFail);
1126 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001127
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001128 if (setPruneList) {
Traian Schiaua4808162015-04-10 15:51:39 +03001129 size_t len = strlen(setPruneList);
1130 /*extra 32 bytes are needed by android_logger_set_prune_list */
1131 size_t bLen = len + 32;
1132 char *buf = NULL;
1133 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1134 buf[len] = '\0';
1135 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1136 logcat_panic(false, "failed to set the prune list");
1137 }
1138 free(buf);
1139 } else {
1140 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001141 }
1142 }
1143
Mark Salyzyn1c950472014-04-01 17:19:47 -07001144 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001145 size_t len = 8192;
1146 char *buf;
1147
Mark Salyzynef5f6642015-12-04 10:59:45 -08001148 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001149 (retry >= 0) && ((buf = new char [len]));
Traian Schiaua4808162015-04-10 15:51:39 +03001150 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001151 if (getPruneList) {
1152 android_logger_get_prune_list(logger_list, buf, len);
1153 } else {
1154 android_logger_get_statistics(logger_list, buf, len);
1155 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001156 buf[len-1] = '\0';
Traian Schiaua4808162015-04-10 15:51:39 +03001157 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001158 delete [] buf;
1159 buf = NULL;
1160 break;
1161 }
Traian Schiaua4808162015-04-10 15:51:39 +03001162 size_t ret = atol(buf) + 1;
1163 if (ret <= len) {
1164 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001165 break;
1166 }
Traian Schiaua4808162015-04-10 15:51:39 +03001167 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001168 }
1169
1170 if (!buf) {
Traian Schiaua4808162015-04-10 15:51:39 +03001171 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001172 }
1173
1174 // remove trailing FF
1175 char *cp = buf + len - 1;
1176 *cp = '\0';
1177 bool truncated = *--cp != '\f';
1178 if (!truncated) {
1179 *cp = '\0';
1180 }
1181
1182 // squash out the byte count
1183 cp = buf;
1184 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001185 while (isdigit(*cp)) {
1186 ++cp;
1187 }
1188 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001189 ++cp;
1190 }
1191 }
1192
1193 printf("%s", cp);
1194 delete [] buf;
Traian Schiaua4808162015-04-10 15:51:39 +03001195 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001196 }
1197
1198
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001199 if (getLogSize) {
Traian Schiaua4808162015-04-10 15:51:39 +03001200 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001202 if (setLogSize || setPruneList) {
Traian Schiaua4808162015-04-10 15:51:39 +03001203 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001204 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001205 if (clearLog) {
Traian Schiaua4808162015-04-10 15:51:39 +03001206 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001207 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001208
1209 //LOG_EVENT_INT(10, 12345);
1210 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1211 //LOG_EVENT_STRING(0, "whassup, doc?");
1212
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001213 dev = NULL;
Mark Salyzyn7ae3cf12015-02-27 13:41:34 -08001214 log_device_t unexpected("unexpected", false);
Casey Dahlin4915bbf2016-03-17 14:04:52 -07001215
Mark Salyzyn9391ebd2016-03-30 12:38:29 -07001216 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001217 struct log_msg log_msg;
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001218 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001219 int ret = android_logger_list_read(logger_list, &log_msg);
1220
1221 if (ret == 0) {
Traian Schiaua4808162015-04-10 15:51:39 +03001222 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001223 }
1224
1225 if (ret < 0) {
1226 if (ret == -EAGAIN) {
1227 break;
1228 }
1229
1230 if (ret == -EIO) {
Traian Schiaua4808162015-04-10 15:51:39 +03001231 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001232 }
1233 if (ret == -EINVAL) {
Traian Schiaua4808162015-04-10 15:51:39 +03001234 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001235 }
Traian Schiaua4808162015-04-10 15:51:39 +03001236 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001237 }
1238
Mark Salyzynef5f6642015-12-04 10:59:45 -08001239 for (d = devices; d; d = d->next) {
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001240 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001241 break;
1242 }
1243 }
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001244 if (!d) {
Traian Schiaua4808162015-04-10 15:51:39 +03001245 g_devCount = 2; // set to Multiple
Mark Salyzyn51a71422015-02-26 14:33:35 -08001246 d = &unexpected;
1247 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001248 }
1249
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001250 if (dev != d) {
1251 dev = d;
Traian Schiaua4808162015-04-10 15:51:39 +03001252 maybePrintStart(dev, printDividers);
Mark Salyzyn0a890f92015-01-26 13:41:33 -08001253 }
Traian Schiaua4808162015-04-10 15:51:39 +03001254 if (g_printBinary) {
1255 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001256 } else {
Traian Schiaua4808162015-04-10 15:51:39 +03001257 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001258 }
1259 }
1260
1261 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001262
Traian Schiaua4808162015-04-10 15:51:39 +03001263 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001264}