blob: 52f49cc3dc1e5986d49084c5cbccf99497ab026a [file] [log] [blame]
Mark Salyzyn7b30ff82015-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 Salyzyn3ef730c2015-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 Salyzynf3555d92015-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 Monsen562e5132015-06-05 14:10:12 -07009#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070010#include <math.h>
Mark Salyzyn3ef730c2015-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 Schiau59763032015-04-10 15:51:39 +030017#include <sys/cdefs.h>
Riley Andrewsaede9892015-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 Salyzynf3555d92015-05-27 07:39:56 -070021#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070022#include <time.h>
23#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080024
Mark Salyzynf3555d92015-05-27 07:39:56 -070025#include <memory>
26#include <string>
27
Elliott Hughes4f713192015-12-04 22:00:26 -080028#include <android-base/file.h>
29#include <android-base/strings.h>
Mark Salyzyn33c26252016-04-12 09:11:46 -070030#include <cutils/properties.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070031#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080032#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070033#include <log/event_tag_map.h>
Mark Salyzyn95132e92013-11-22 10:55:48 -080034#include <log/log.h>
Mark Salyzynfa3716b2014-02-14 16:05:05 -080035#include <log/log_read.h>
Colin Cross9227bd32013-07-23 16:59:20 -070036#include <log/logd.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070037#include <log/logger.h>
Colin Cross9227bd32013-07-23 16:59:20 -070038#include <log/logprint.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080039#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080040
Casey Dahlindc42a872016-03-17 16:18:55 -070041#include <pcrecpp.h>
42
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043#define DEFAULT_MAX_ROTATED_LOGS 4
44
45static AndroidLogFormat * g_logformat;
46
47/* logd prefixes records with a length field */
48#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
49
Joe Onorato6fa09a02010-02-26 10:04:23 -080050struct log_device_t {
Mark Salyzyn95132e92013-11-22 10:55:48 -080051 const char* device;
Joe Onorato6fa09a02010-02-26 10:04:23 -080052 bool binary;
Mark Salyzyn95132e92013-11-22 10:55:48 -080053 struct logger *logger;
54 struct logger_list *logger_list;
Joe Onorato6fa09a02010-02-26 10:04:23 -080055 bool printed;
Joe Onorato6fa09a02010-02-26 10:04:23 -080056
Joe Onorato6fa09a02010-02-26 10:04:23 -080057 log_device_t* next;
58
Mark Salyzyn5f6738a2015-02-27 13:41:34 -080059 log_device_t(const char* d, bool b) {
Joe Onorato6fa09a02010-02-26 10:04:23 -080060 device = d;
61 binary = b;
Joe Onorato6fa09a02010-02-26 10:04:23 -080062 next = NULL;
63 printed = false;
Traian Schiau59763032015-04-10 15:51:39 +030064 logger = NULL;
65 logger_list = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -080066 }
Joe Onorato6fa09a02010-02-26 10:04:23 -080067};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080068
69namespace android {
70
71/* Global Variables */
72
Mark Salyzync6d66522016-03-30 12:38:29 -070073static const char * g_outputFileName;
Traian Schiau59763032015-04-10 15:51:39 +030074// 0 means "no log rotation"
Mark Salyzync6d66522016-03-30 12:38:29 -070075static size_t g_logRotateSizeKBytes;
Traian Schiau59763032015-04-10 15:51:39 +030076// 0 means "unbounded"
77static size_t g_maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080078static int g_outFD = -1;
Mark Salyzync6d66522016-03-30 12:38:29 -070079static size_t g_outByteCount;
80static int g_printBinary;
81static int g_devCount; // >1 means multiple
Casey Dahlindc42a872016-03-17 16:18:55 -070082static pcrecpp::RE* g_regex;
Casey Dahlin6ac498d2016-03-17 14:04:52 -070083// 0 means "infinite"
Mark Salyzync6d66522016-03-30 12:38:29 -070084static size_t g_maxCount;
85static size_t g_printCount;
Mark Salyzync9202772016-03-30 09:38:31 -070086static bool g_printItAnyways;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080087
Mark Salyzynaa730c12016-03-30 12:38:29 -070088// if showHelp is set, newline required in fmt statement to transition to usage
Traian Schiau59763032015-04-10 15:51:39 +030089__noreturn static void logcat_panic(bool showHelp, const char *fmt, ...) __printflike(2,3);
90
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080091static int openLogFile (const char *pathname)
92{
Edwin Vane80b221c2012-08-13 12:55:07 -040093 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080094}
95
96static void rotateLogs()
97{
98 int err;
99
100 // Can't rotate logs if we're not outputting to a file
101 if (g_outputFileName == NULL) {
102 return;
103 }
104
105 close(g_outFD);
106
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700107 // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
108 // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
109 int maxRotationCountDigits =
110 (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
111
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800112 for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
113 char *file0, *file1;
114
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700115 asprintf(&file1, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800116
117 if (i - 1 == 0) {
118 asprintf(&file0, "%s", g_outputFileName);
119 } else {
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700120 asprintf(&file0, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800121 }
122
Traian Schiau59763032015-04-10 15:51:39 +0300123 if (!file0 || !file1) {
124 perror("while rotating log files");
125 break;
126 }
127
128 err = rename(file0, file1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800129
130 if (err < 0 && errno != ENOENT) {
131 perror("while rotating log files");
132 }
133
134 free(file1);
135 free(file0);
136 }
137
Traian Schiau59763032015-04-10 15:51:39 +0300138 g_outFD = openLogFile(g_outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139
140 if (g_outFD < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300141 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800142 }
143
144 g_outByteCount = 0;
145
146}
147
Mark Salyzyn95132e92013-11-22 10:55:48 -0800148void printBinary(struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149{
Mark Salyzyn95132e92013-11-22 10:55:48 -0800150 size_t size = buf->len();
151
152 TEMP_FAILURE_RETRY(write(g_outFD, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800153}
154
Mark Salyzynaa730c12016-03-30 12:38:29 -0700155static bool regexOk(const AndroidLogEntry& entry)
Casey Dahlindc42a872016-03-17 16:18:55 -0700156{
Mark Salyzynaa730c12016-03-30 12:38:29 -0700157 if (!g_regex) {
Casey Dahlindc42a872016-03-17 16:18:55 -0700158 return true;
159 }
160
Casey Dahlindc42a872016-03-17 16:18:55 -0700161 std::string messageString(entry.message, entry.messageLen);
162
163 return g_regex->PartialMatch(messageString);
164}
165
Mark Salyzyn95132e92013-11-22 10:55:48 -0800166static void processBuffer(log_device_t* dev, struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167{
Mathias Agopian50844522010-03-17 16:10:26 -0700168 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800169 int err;
170 AndroidLogEntry entry;
171 char binaryMsgBuf[1024];
172
Joe Onorato6fa09a02010-02-26 10:04:23 -0800173 if (dev->binary) {
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800174 static bool hasOpenedEventTagMap = false;
175 static EventTagMap *eventTagMap = NULL;
176
177 if (!eventTagMap && !hasOpenedEventTagMap) {
178 eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
179 hasOpenedEventTagMap = true;
180 }
Mark Salyzyn95132e92013-11-22 10:55:48 -0800181 err = android_log_processBinaryLogBuffer(&buf->entry_v1, &entry,
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800182 eventTagMap,
Mark Salyzyn95132e92013-11-22 10:55:48 -0800183 binaryMsgBuf,
184 sizeof(binaryMsgBuf));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800185 //printf(">>> pri=%d len=%d msg='%s'\n",
186 // entry.priority, entry.messageLen, entry.message);
187 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800188 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800190 if (err < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800191 goto error;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800192 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800193
Mark Salyzync9202772016-03-30 09:38:31 -0700194 if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
195 bool match = regexOk(entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800196
Mark Salyzync9202772016-03-30 09:38:31 -0700197 g_printCount += match;
198 if (match || g_printItAnyways) {
199 bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700200
Mark Salyzync9202772016-03-30 09:38:31 -0700201 if (bytesWritten < 0) {
202 logcat_panic(false, "output error");
203 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800204 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800205 }
206
207 g_outByteCount += bytesWritten;
208
Mark Salyzyn95132e92013-11-22 10:55:48 -0800209 if (g_logRotateSizeKBytes > 0
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210 && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
211 ) {
212 rotateLogs();
213 }
214
215error:
216 //fprintf (stderr, "Error processing record\n");
217 return;
218}
219
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800220static void maybePrintStart(log_device_t* dev, bool printDividers) {
221 if (!dev->printed || printDividers) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800222 if (g_devCount > 1 && !g_printBinary) {
223 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800224 snprintf(buf, sizeof(buf), "--------- %s %s\n",
225 dev->printed ? "switch to" : "beginning of",
Mark Salyzyn95132e92013-11-22 10:55:48 -0800226 dev->device);
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800227 if (write(g_outFD, buf, strlen(buf)) < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300228 logcat_panic(false, "output error");
Joe Onorato6fa09a02010-02-26 10:04:23 -0800229 }
230 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800231 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800232 }
233}
234
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235static void setupOutput()
236{
237
238 if (g_outputFileName == NULL) {
239 g_outFD = STDOUT_FILENO;
240
241 } else {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700242 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
243 fprintf(stderr, "failed to set background scheduling policy\n");
244 }
245
246 struct sched_param param;
247 memset(&param, 0, sizeof(param));
248 if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
249 fprintf(stderr, "failed to set to batch scheduler\n");
250 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800251
Riley Andrewsaede9892015-06-08 23:36:34 -0700252 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
253 fprintf(stderr, "failed set to priority\n");
254 }
255
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800256 g_outFD = openLogFile (g_outputFileName);
257
258 if (g_outFD < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300259 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800260 }
261
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700262 struct stat statbuf;
Traian Schiau59763032015-04-10 15:51:39 +0300263 if (fstat(g_outFD, &statbuf) == -1) {
264 close(g_outFD);
265 logcat_panic(false, "couldn't get output file stat\n");
266 }
267
268 if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
269 close(g_outFD);
270 logcat_panic(false, "invalid output file stat\n");
271 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272
273 g_outByteCount = statbuf.st_size;
274 }
275}
276
277static void show_help(const char *cmd)
278{
279 fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
280
281 fprintf(stderr, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700282 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
283 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn33c26252016-04-12 09:11:46 -0700284 " -r <kbytes>, --rotate-kbytes=<kbytes> Rotate log every kbytes. Requires -f\n"
285 " option. Permits property expansion.\n"
286 " -n <count>, --rotate-count=<count> Sets max number of rotated logs to\n"
287 " <count>, default 4. Permits property expansion.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700288 " -v <format>, --format=<format>\n"
289 " Sets the log print format, where <format> is:\n"
290 " brief color epoch long monotonic printable process raw\n"
291 " tag thread threadtime time uid usec UTC year zone\n"
292 " -D, --dividers Print dividers between each log buffer\n"
293 " -c, --clear Clear (flush) the entire log and exit\n"
294 " -d Dump the log and then exit (don't block)\n"
295 " -e <expr>, --regex=<expr>\n"
296 " Only print lines where the log message matches <expr>\n"
297 " where <expr> is a regular expression\n"
298 // Leave --head undocumented as alias for -m
299 " -m <count>, --max-count=<count>\n"
300 " Quit after printing <count> lines. This is meant to be\n"
301 " paired with --regex, but will work on its own.\n"
302 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700303 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700304 // Leave --tail undocumented as alias for -t
305 " -t <count> Print only the most recent <count> lines (implies -d)\n"
306 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
307 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
308 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700309 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700310 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700311 " -g, --buffer-size Get the size of the ring buffer.\n"
312 " -G <size>, --buffer-size=<size>\n"
313 " Set size of log ring buffer, may suffix with K or M.\n"
314 " -L, -last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800315 // Leave security (Device Owner only installations) and
316 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700317 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
318 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700319 " Multiple -b parameters or comma separated list of buffers are\n"
320 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn33c26252016-04-12 09:11:46 -0700321 " Permits property expansion.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700322 " -B, --binary Output the log in binary.\n"
323 " -S, --statistics Output statistics.\n"
324 " -p, --prune Print prune white and ~black list. Service is specified as\n"
325 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700326 " with ~, otherwise weighed for longevity if unadorned. All\n"
327 " other pruning activity is oldest first. Special case ~!\n"
328 " represents an automatic quicker pruning for the noisiest\n"
329 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700330 " -P '<list> ...', --prune='<list> ...'\n"
331 " Set prune white and ~black list, using same format as\n"
332 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800333 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700334 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800335 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
336 " comes first. Improves efficiency of polling by providing\n"
337 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800338
Mark Salyzyn33c26252016-04-12 09:11:46 -0700339 fprintf(stderr,"\nProperty expansion where available, may need to be single quoted to prevent\n"
340 "shell expansion:\n"
341 " ${key} - Expand string with property value associated with key\n"
342 " ${key:-default} - Expand, if property key value clear, use default\n"
343 "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800344 " <tag>[:priority]\n\n"
345 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700346 " V Verbose (default for <tag>)\n"
347 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348 " I Info\n"
349 " W Warn\n"
350 " E Error\n"
351 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700352 " S Silent (suppress all output)\n"
353 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
354 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
355 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
356 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
357 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700358 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800359}
360
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800361static int setLogFormat(const char * formatString)
362{
363 static AndroidLogPrintFormat format;
364
365 format = android_log_formatFromString(formatString);
366
367 if (format == FORMAT_OFF) {
368 // FORMAT_OFF means invalid string
369 return -1;
370 }
371
Mark Salyzyne1f20042015-05-06 08:40:40 -0700372 return android_log_setPrintFormat(g_logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373}
374
Mark Salyzyn671e3432014-05-06 07:34:59 -0700375static const char multipliers[][2] = {
376 { "" },
377 { "K" },
378 { "M" },
379 { "G" }
380};
381
382static unsigned long value_of_size(unsigned long value)
383{
384 for (unsigned i = 0;
385 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
386 value /= 1024, ++i) ;
387 return value;
388}
389
390static const char *multiplier_of_size(unsigned long value)
391{
392 unsigned i;
393 for (i = 0;
394 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
395 value /= 1024, ++i) ;
396 return multipliers[i];
397}
398
Traian Schiau59763032015-04-10 15:51:39 +0300399/*String to unsigned int, returns -1 if it fails*/
Mark Salyzyn33c26252016-04-12 09:11:46 -0700400static bool getSizeTArg(const char *ptr, size_t *val, size_t min = 0,
Traian Schiau59763032015-04-10 15:51:39 +0300401 size_t max = SIZE_MAX)
402{
Kristian Monsen562e5132015-06-05 14:10:12 -0700403 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300404 return false;
405 }
406
Kristian Monsen562e5132015-06-05 14:10:12 -0700407 char *endp;
408 errno = 0;
409 size_t ret = (size_t)strtoll(ptr, &endp, 0);
410
411 if (endp[0] || errno) {
412 return false;
413 }
414
415 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300416 return false;
417 }
418
419 *val = ret;
420 return true;
421}
422
423static void logcat_panic(bool showHelp, const char *fmt, ...)
424{
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700425 va_list args;
426 va_start(args, fmt);
427 vfprintf(stderr, fmt, args);
428 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300429
430 if (showHelp) {
431 show_help(getprogname());
432 }
433
434 exit(EXIT_FAILURE);
435}
436
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700437static char *parseTime(log_time &t, const char *cp) {
438
439 char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
440 if (ep) {
441 return ep;
442 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700443 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
444 if (ep) {
445 return ep;
446 }
447 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700448}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700449
450// Find last logged line in gestalt of all matching existing output files
451static log_time lastLogTime(char *outputFileName) {
452 log_time retval(log_time::EPOCH);
453 if (!outputFileName) {
454 return retval;
455 }
456
Mark Salyzynf3555d92015-05-27 07:39:56 -0700457 std::string directory;
458 char *file = strrchr(outputFileName, '/');
459 if (!file) {
460 directory = ".";
461 file = outputFileName;
462 } else {
463 *file = '\0';
464 directory = outputFileName;
465 *file = '/';
466 ++file;
467 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700468
469 std::unique_ptr<DIR, int(*)(DIR*)>
470 dir(opendir(directory.c_str()), closedir);
471 if (!dir.get()) {
472 return retval;
473 }
474
475 clockid_t clock_type = android_log_clockid();
476 log_time now(clock_type);
477 bool monotonic = clock_type == CLOCK_MONOTONIC;
478
Mark Salyzynf3555d92015-05-27 07:39:56 -0700479 size_t len = strlen(file);
480 log_time modulo(0, NS_PER_SEC);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700481 struct dirent *dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700482
Mark Salyzynf3555d92015-05-27 07:39:56 -0700483 while ((dp = readdir(dir.get())) != NULL) {
484 if ((dp->d_type != DT_REG)
Mark Salyzynb6bee332015-09-08 08:56:32 -0700485 // If we are using realtime, check all files that match the
486 // basename for latest time. If we are using monotonic time
487 // then only check the main file because time cycles on
488 // every reboot.
489 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzynf3555d92015-05-27 07:39:56 -0700490 || (dp->d_name[len]
491 && ((dp->d_name[len] != '.')
492 || !isdigit(dp->d_name[len+1])))) {
493 continue;
494 }
495
496 std::string file_name = directory;
497 file_name += "/";
498 file_name += dp->d_name;
499 std::string file;
500 if (!android::base::ReadFileToString(file_name, &file)) {
501 continue;
502 }
503
504 bool found = false;
505 for (const auto& line : android::base::Split(file, "\n")) {
506 log_time t(log_time::EPOCH);
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700507 char *ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700508 if (!ep || (*ep != ' ')) {
509 continue;
510 }
511 // determine the time precision of the logs (eg: msec or usec)
512 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
513 if (t.tv_nsec % (mod * 10)) {
514 modulo.tv_nsec = mod;
515 break;
516 }
517 }
518 // We filter any times later than current as we may not have the
519 // year stored with each log entry. Also, since it is possible for
520 // entries to be recorded out of order (very rare) we select the
521 // maximum we find just in case.
522 if ((t < now) && (t > retval)) {
523 retval = t;
524 found = true;
525 }
526 }
527 // We count on the basename file to be the definitive end, so stop here.
528 if (!dp->d_name[len] && found) {
529 break;
530 }
531 }
532 if (retval == log_time::EPOCH) {
533 return retval;
534 }
535 // tail_time prints matching or higher, round up by the modulo to prevent
536 // a replay of the last entry we have just checked.
537 retval += modulo;
538 return retval;
539}
540
Mark Salyzyn33c26252016-04-12 09:11:46 -0700541// Expand multiple flat property references ${<tag>:-default} or ${tag}.
542//
543// ToDo: Do we permit nesting?
544// ${persist.logcat.something:-${ro.logcat.something:-maybesomething}}
545// For now this will result in a syntax error for caller and is acceptable.
546//
547std::string expand(const char *str)
548{
549 std::string retval(str);
550
551 // Caller has no use for ${, } or :- as literals so no use for escape
552 // character. Result expectations are a number or a string, with validity
553 // checking for both in caller. Recursive expansion or other syntax errors
554 // will result in content caller can not obviously tolerate, error must
555 // report substring if applicable, expanded and original content (if
556 // different) so that it will be clear to user what they did wrong.
557 for (size_t pos; (pos = retval.find("${")) != std::string::npos; ) {
558 size_t epos = retval.find("}", pos + 2);
559 if (epos == std::string::npos) {
560 break; // Caller will error out, showing this unexpanded.
561 }
562 size_t def = retval.find(":-", pos + 2);
563 if (def >= epos) {
564 def = std::string::npos;
565 }
566 std::string default_value("");
567 std::string key;
568 if (def == std::string::npos) {
569 key = retval.substr(pos + 2, epos - (pos + 2));
570 } else {
571 key = retval.substr(pos + 2, def - (pos + 2));
572 default_value = retval.substr(def + 2, epos - (def + 2));
573 }
574 char value[PROPERTY_VALUE_MAX];
575 property_get(key.c_str(), value, default_value.c_str());
576 // Caller will error out, syntactically empty content at this point
577 // will not be tolerated as expected.
578 retval.replace(pos, epos - pos + 1, value);
579 }
580
581 return retval;
582}
583
Traian Schiau59763032015-04-10 15:51:39 +0300584} /* namespace android */
585
586
Joe Onorato6fa09a02010-02-26 10:04:23 -0800587int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800588{
Traian Schiau59763032015-04-10 15:51:39 +0300589 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800590 int err;
591 int hasSetLogFormat = 0;
592 int clearLog = 0;
593 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800594 unsigned long setLogSize = 0;
595 int getPruneList = 0;
596 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800597 int printStatistics = 0;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800598 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800600 log_device_t* devices = NULL;
601 log_device_t* dev;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800602 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800603 struct logger_list *logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300604 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800605 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700606 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700607 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800609 signal(SIGPIPE, exit);
610
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800611 g_logformat = android_log_format_new();
612
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiau59763032015-04-10 15:51:39 +0300614 show_help(argv[0]);
615 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616 }
617
618 for (;;) {
619 int ret;
620
Kristian Monsen562e5132015-06-05 14:10:12 -0700621 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700622 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700623 static const char pid_str[] = "pid";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800624 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700625 static const char print_str[] = "print";
Kristian Monsen562e5132015-06-05 14:10:12 -0700626 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800627 { "binary", no_argument, NULL, 'B' },
628 { "buffer", required_argument, NULL, 'b' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700629 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800630 { "clear", no_argument, NULL, 'c' },
631 { "dividers", no_argument, NULL, 'D' },
632 { "file", required_argument, NULL, 'f' },
633 { "format", required_argument, NULL, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700634 // hidden and undocumented reserved alias for --regex
635 { "grep", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700636 // hidden and undocumented reserved alias for --max-count
637 { "head", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800638 { "last", no_argument, NULL, 'L' },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700639 { "max-count", required_argument, NULL, 'm' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700640 { pid_str, required_argument, NULL, 0 },
Mark Salyzync9202772016-03-30 09:38:31 -0700641 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800642 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700643 { "regex", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700644 { "rotate-count", required_argument, NULL, 'n' },
645 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800646 { "statistics", no_argument, NULL, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700647 // hidden and undocumented reserved alias for -t
648 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800649 // support, but ignore and do not document, the optional argument
650 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700651 { NULL, 0, NULL, 0 }
652 };
653
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700654 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700655 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656
657 if (ret < 0) {
658 break;
659 }
660
Kristian Monsen562e5132015-06-05 14:10:12 -0700661 switch (ret) {
662 case 0:
663 // One of the long options
664 if (long_options[option_index].name == pid_str) {
665 // ToDo: determine runtime PID_MAX?
666 if (!getSizeTArg(optarg, &pid, 1)) {
667 logcat_panic(true, "%s %s out of range\n",
668 long_options[option_index].name, optarg);
669 }
670 break;
671 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800672 if (long_options[option_index].name == wrap_str) {
673 mode |= ANDROID_LOG_WRAP |
674 ANDROID_LOG_RDONLY |
675 ANDROID_LOG_NONBLOCK;
676 // ToDo: implement API that supports setting a wrap timeout
677 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
678 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
679 logcat_panic(true, "%s %s out of range\n",
680 long_options[option_index].name, optarg);
681 }
682 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
683 fprintf(stderr,
684 "WARNING: %s %u seconds, ignoring %zu\n",
685 long_options[option_index].name,
686 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
687 }
688 break;
689 }
Mark Salyzync9202772016-03-30 09:38:31 -0700690 if (long_options[option_index].name == print_str) {
691 g_printItAnyways = true;
692 break;
693 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700694 break;
695
Mark Salyzyn95132e92013-11-22 10:55:48 -0800696 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800697 // default to all silent
698 android_log_addFilterRule(g_logformat, "*:s");
699 break;
700
701 case 'c':
702 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800703 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800704 break;
705
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800706 case 'L':
707 mode |= ANDROID_LOG_PSTORE;
708 break;
709
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800710 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800711 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800712 break;
713
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800714 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700715 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800716 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800717 /* FALLTHRU */
718 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800719 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700720 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800721 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700722 logcat_panic(false, "-%c \"%s\" not in time format\n",
723 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800724 }
725 if (*cp) {
726 char c = *cp;
727 *cp = '\0';
728 fprintf(stderr,
729 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
730 ret, optarg, c, cp + 1);
731 *cp = c;
732 }
733 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300734 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800735 fprintf(stderr,
736 "WARNING: -%c %s invalid, setting to 1\n",
737 ret, optarg);
738 tail_lines = 1;
739 }
740 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800741 break;
742
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800743 case 'D':
744 printDividers = true;
745 break;
746
Casey Dahlindc42a872016-03-17 16:18:55 -0700747 case 'e':
748 g_regex = new pcrecpp::RE(optarg);
749 break;
750
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700751 case 'm': {
752 char *end = NULL;
753 if (!getSizeTArg(optarg, &g_maxCount)) {
754 logcat_panic(false, "-%c \"%s\" isn't an "
755 "integer greater than zero\n", ret, optarg);
756 }
757 }
758 break;
759
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800760 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800761 if (!optarg) {
762 getLogSize = 1;
763 break;
764 }
765 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800767 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300768 char *cp;
769 if (strtoll(optarg, &cp, 0) > 0) {
770 setLogSize = strtoll(optarg, &cp, 0);
771 } else {
772 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800773 }
774
775 switch(*cp) {
776 case 'g':
777 case 'G':
778 setLogSize *= 1024;
779 /* FALLTHRU */
780 case 'm':
781 case 'M':
782 setLogSize *= 1024;
783 /* FALLTHRU */
784 case 'k':
785 case 'K':
786 setLogSize *= 1024;
787 /* FALLTHRU */
788 case '\0':
789 break;
790
791 default:
792 setLogSize = 0;
793 }
794
795 if (!setLogSize) {
796 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300797 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800798 }
799 }
800 break;
801
802 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800803 if (!optarg) {
804 getPruneList = 1;
805 break;
806 }
807 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800808
809 case 'P':
810 setPruneList = optarg;
811 break;
812
Joe Onorato6fa09a02010-02-26 10:04:23 -0800813 case 'b': {
Mark Salyzyn45177732016-04-11 14:03:48 -0700814 unsigned idMask = 0;
Mark Salyzyn33c26252016-04-12 09:11:46 -0700815 std::string expanded = expand(optarg);
816 std::istringstream copy(expanded);
817 std::string token;
818 // wish for strtok and ",:; \t\n\r\f" for hidden flexibility
819 while (std::getline(copy, token, ',')) { // settle for ","
820 if (token.compare("default") == 0) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700821 idMask |= (1 << LOG_ID_MAIN) |
822 (1 << LOG_ID_SYSTEM) |
823 (1 << LOG_ID_CRASH);
Mark Salyzyn33c26252016-04-12 09:11:46 -0700824 } else if (token.compare("all") == 0) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700825 idMask = (unsigned)-1;
826 } else {
Mark Salyzyn33c26252016-04-12 09:11:46 -0700827 log_id_t log_id = android_name_to_log_id(token.c_str());
Mark Salyzyn45177732016-04-11 14:03:48 -0700828 const char *name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800829
Mark Salyzyn33c26252016-04-12 09:11:46 -0700830 if (token.compare(name) != 0) {
831 bool strDifferent = expanded.compare(token);
832 if (expanded.compare(optarg)) {
833 expanded += " expanded from ";
834 expanded += optarg;
835 }
836 if (strDifferent) {
837 expanded = token + " within " + expanded;
838 }
839 logcat_panic(true, "unknown buffer -b %s\n",
840 expanded.c_str());
Mark Salyzyn34facab2014-02-06 14:48:50 -0800841 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700842 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800843 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800844 }
845
Mark Salyzyn45177732016-04-11 14:03:48 -0700846 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
847 const char *name = android_log_id_to_name((log_id_t)i);
848 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800849
Mark Salyzyn45177732016-04-11 14:03:48 -0700850 if (log_id != (log_id_t)i) {
851 continue;
852 }
853 if ((idMask & (1 << i)) == 0) {
854 continue;
855 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800856
Mark Salyzyn45177732016-04-11 14:03:48 -0700857 bool found = false;
858 for (dev = devices; dev; dev = dev->next) {
859 if (!strcmp(name, dev->device)) {
860 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800861 break;
862 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700863 if (!dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800864 break;
865 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800866 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700867 if (found) {
868 continue;
869 }
870
871 bool binary = !strcmp(name, "events") ||
872 !strcmp(name, "security");
873 log_device_t* d = new log_device_t(name, binary);
874
Mark Salyzyn083b0372015-12-04 10:59:45 -0800875 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700876 dev->next = d;
877 dev = d;
878 } else {
879 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800880 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700881 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800882 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800883 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800884 break;
885
886 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300887 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888 break;
889
890 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700891 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700892 tail_time = lastLogTime(optarg);
893 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800894 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300895 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800896 break;
897
Mark Salyzyn33c26252016-04-12 09:11:46 -0700898 case 'r': {
899 std::string expanded = expand(optarg);
900 if (!getSizeTArg(expanded.c_str(), &g_logRotateSizeKBytes, 1)) {
901 if (expanded.compare(optarg)) {
902 expanded += " expanded from ";
903 expanded += optarg;
904 }
905 logcat_panic(true, "Invalid parameter -r %s\n",
906 expanded.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800907 }
Mark Salyzyn33c26252016-04-12 09:11:46 -0700908 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800909 break;
910
Mark Salyzyn33c26252016-04-12 09:11:46 -0700911 case 'n': {
912 std::string expanded = expand(optarg);
913 if (!getSizeTArg(expanded.c_str(), &g_maxRotatedLogs, 1)) {
914 if (expanded.compare(optarg)) {
915 expanded += " expanded from ";
916 expanded += optarg;
917 }
918 logcat_panic(true, "Invalid parameter -n %s\n",
919 expanded.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800920 }
Mark Salyzyn33c26252016-04-12 09:11:46 -0700921 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800922 break;
923
924 case 'v':
925 err = setLogFormat (optarg);
926 if (err < 0) {
Mark Salyzyn33c26252016-04-12 09:11:46 -0700927 logcat_panic(true, "Invalid parameter -v %s\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800928 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700929 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800930 break;
931
932 case 'Q':
933 /* this is a *hidden* option used to start a version of logcat */
934 /* in an emulated device only. it basically looks for androidboot.logcat= */
935 /* on the kernel command line. If something is found, it extracts a log filter */
936 /* and uses it to run the program. If nothing is found, the program should */
937 /* quit immediately */
938#define KERNEL_OPTION "androidboot.logcat="
939#define CONSOLE_OPTION "androidboot.console="
940 {
941 int fd;
942 char* logcat;
943 char* console;
944 int force_exit = 1;
945 static char cmdline[1024];
946
947 fd = open("/proc/cmdline", O_RDONLY);
948 if (fd >= 0) {
949 int n = read(fd, cmdline, sizeof(cmdline)-1 );
950 if (n < 0) n = 0;
951 cmdline[n] = 0;
952 close(fd);
953 } else {
954 cmdline[0] = 0;
955 }
956
957 logcat = strstr( cmdline, KERNEL_OPTION );
958 console = strstr( cmdline, CONSOLE_OPTION );
959 if (logcat != NULL) {
960 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
961 char* q = strpbrk( p, " \t\n\r" );;
962
963 if (q != NULL)
964 *q = 0;
965
966 forceFilters = p;
967 force_exit = 0;
968 }
969 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300970 if (force_exit) {
971 return EXIT_SUCCESS;
972 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800973
974 /* redirect our output to the emulator console */
975 if (console) {
976 char* p = console + sizeof(CONSOLE_OPTION)-1;
977 char* q = strpbrk( p, " \t\n\r" );
978 char devname[64];
979 int len;
980
981 if (q != NULL) {
982 len = q - p;
983 } else
984 len = strlen(p);
985
986 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
987 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
988 if (len < (int)sizeof(devname)) {
989 fd = open( devname, O_WRONLY );
990 if (fd >= 0) {
991 dup2(fd, 1);
992 dup2(fd, 2);
993 close(fd);
994 }
995 }
996 }
997 }
998 break;
999
Mark Salyzyn34facab2014-02-06 14:48:50 -08001000 case 'S':
1001 printStatistics = 1;
1002 break;
1003
Traian Schiau59763032015-04-10 15:51:39 +03001004 case ':':
1005 logcat_panic(true, "Option -%c needs an argument\n", optopt);
1006 break;
1007
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001008 default:
Traian Schiau59763032015-04-10 15:51:39 +03001009 logcat_panic(true, "Unrecognized Option %c\n", optopt);
1010 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011 }
1012 }
1013
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001014 if (g_maxCount && got_t) {
Mark Salyzynaa730c12016-03-30 12:38:29 -07001015 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001016 }
Mark Salyzync9202772016-03-30 09:38:31 -07001017 if (g_printItAnyways && (!g_regex || !g_maxCount)) {
1018 // One day it would be nice if --print -v color and --regex <expr>
1019 // could play with each other and show regex highlighted content.
1020 fprintf(stderr, "WARNING: "
1021 "--print ignored, to be used in combination with\n"
1022 " "
1023 "--regex <expr> and --max-count <N>\n");
1024 g_printItAnyways = false;
1025 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001026
Joe Onorato6fa09a02010-02-26 10:04:23 -08001027 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001028 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +03001029 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001030 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001031 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +03001032 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001033 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001034 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001035 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +03001036 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001037 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001038 }
1039
Traian Schiau59763032015-04-10 15:51:39 +03001040 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
1041 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001042 }
1043
Traian Schiau59763032015-04-10 15:51:39 +03001044 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001045
1046 if (hasSetLogFormat == 0) {
1047 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
1048
1049 if (logFormat != NULL) {
1050 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001051 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001052 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001053 logFormat);
1054 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001055 } else {
1056 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001057 }
1058 }
1059
1060 if (forceFilters) {
1061 err = android_log_addFilterString(g_logformat, forceFilters);
1062 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001063 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001064 }
1065 } else if (argc == optind) {
1066 // Add from environment variable
1067 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1068
1069 if (env_tags_orig != NULL) {
1070 err = android_log_addFilterString(g_logformat, env_tags_orig);
1071
Mark Salyzyn95132e92013-11-22 10:55:48 -08001072 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001073 logcat_panic(true,
1074 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001075 }
1076 }
1077 } else {
1078 // Add from commandline
1079 for (int i = optind ; i < argc ; i++) {
1080 err = android_log_addFilterString(g_logformat, argv[i]);
1081
Mark Salyzyn95132e92013-11-22 10:55:48 -08001082 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001083 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001084 }
1085 }
1086 }
1087
Joe Onorato6fa09a02010-02-26 10:04:23 -08001088 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001089 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001090 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001091 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001092 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001093 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001094 const char *openDeviceFail = NULL;
1095 const char *clearFail = NULL;
1096 const char *setSizeFail = NULL;
1097 const char *getSizeFail = NULL;
1098 // We have three orthogonal actions below to clear, set log size and
1099 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001100 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001101 dev->logger_list = logger_list;
1102 dev->logger = android_logger_open(logger_list,
1103 android_name_to_log_id(dev->device));
1104 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001105 openDeviceFail = openDeviceFail ?: dev->device;
1106 dev = dev->next;
1107 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001108 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001109
1110 if (clearLog) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001111 if (android_logger_clear(dev->logger)) {
1112 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001113 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001114 }
1115
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001116 if (setLogSize) {
1117 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1118 setSizeFail = setSizeFail ?: dev->device;
1119 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001120 }
1121
Joe Onorato6fa09a02010-02-26 10:04:23 -08001122 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001123 long size = android_logger_get_log_size(dev->logger);
1124 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001125
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001126 if ((size < 0) || (readable < 0)) {
1127 getSizeFail = getSizeFail ?: dev->device;
1128 } else {
1129 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1130 "max entry is %db, max payload is %db\n", dev->device,
1131 value_of_size(size), multiplier_of_size(size),
1132 value_of_size(readable), multiplier_of_size(readable),
1133 (int) LOGGER_ENTRY_MAX_LEN,
1134 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001135 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001136 }
1137
1138 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001139 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001140 // report any errors in the above loop and exit
1141 if (openDeviceFail) {
1142 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1143 }
1144 if (clearFail) {
1145 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1146 }
1147 if (setSizeFail) {
1148 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1149 }
1150 if (getSizeFail) {
1151 logcat_panic(false, "failed to get the readable '%s' log size",
1152 getSizeFail);
1153 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001155 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001156 size_t len = strlen(setPruneList);
1157 /*extra 32 bytes are needed by android_logger_set_prune_list */
1158 size_t bLen = len + 32;
1159 char *buf = NULL;
1160 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1161 buf[len] = '\0';
1162 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1163 logcat_panic(false, "failed to set the prune list");
1164 }
1165 free(buf);
1166 } else {
1167 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001168 }
1169 }
1170
Mark Salyzyn1c950472014-04-01 17:19:47 -07001171 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001172 size_t len = 8192;
1173 char *buf;
1174
Mark Salyzyn083b0372015-12-04 10:59:45 -08001175 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001176 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001177 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001178 if (getPruneList) {
1179 android_logger_get_prune_list(logger_list, buf, len);
1180 } else {
1181 android_logger_get_statistics(logger_list, buf, len);
1182 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001183 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001184 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001185 delete [] buf;
1186 buf = NULL;
1187 break;
1188 }
Traian Schiau59763032015-04-10 15:51:39 +03001189 size_t ret = atol(buf) + 1;
1190 if (ret <= len) {
1191 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001192 break;
1193 }
Traian Schiau59763032015-04-10 15:51:39 +03001194 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001195 }
1196
1197 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001198 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001199 }
1200
1201 // remove trailing FF
1202 char *cp = buf + len - 1;
1203 *cp = '\0';
1204 bool truncated = *--cp != '\f';
1205 if (!truncated) {
1206 *cp = '\0';
1207 }
1208
1209 // squash out the byte count
1210 cp = buf;
1211 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001212 while (isdigit(*cp)) {
1213 ++cp;
1214 }
1215 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001216 ++cp;
1217 }
1218 }
1219
1220 printf("%s", cp);
1221 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001222 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001223 }
1224
1225
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001226 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001227 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001228 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001229 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001230 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001231 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001232 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001233 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001234 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001235
1236 //LOG_EVENT_INT(10, 12345);
1237 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1238 //LOG_EVENT_STRING(0, "whassup, doc?");
1239
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001240 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001241 log_device_t unexpected("unexpected", false);
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001242
Mark Salyzynaa730c12016-03-30 12:38:29 -07001243 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001244 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001245 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001246 int ret = android_logger_list_read(logger_list, &log_msg);
1247
1248 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001249 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001250 }
1251
1252 if (ret < 0) {
1253 if (ret == -EAGAIN) {
1254 break;
1255 }
1256
1257 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001258 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001259 }
1260 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001261 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001262 }
Traian Schiau59763032015-04-10 15:51:39 +03001263 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001264 }
1265
Mark Salyzyn083b0372015-12-04 10:59:45 -08001266 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001267 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001268 break;
1269 }
1270 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001271 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001272 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001273 d = &unexpected;
1274 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001275 }
1276
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001277 if (dev != d) {
1278 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001279 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001280 }
Traian Schiau59763032015-04-10 15:51:39 +03001281 if (g_printBinary) {
1282 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001283 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001284 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001285 }
1286 }
1287
1288 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001289
Traian Schiau59763032015-04-10 15:51:39 +03001290 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001291}