blob: 37f4f4f2737180d6e19b0cf7257e9db747a4e32c [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 Salyzyn3ef730c2015-06-02 07:57:16 -070030#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080031#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-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 Salyzyn3ef730c2015-06-02 07:57:16 -070036#include <log/logger.h>
Colin Cross9227bd32013-07-23 16:59:20 -070037#include <log/logprint.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070038#include <utils/threads.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039
Casey Dahlin0f7732d2016-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 Salyzyn5f6738a2015-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 Schiau59763032015-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 Salyzyn9cc9cf02016-03-30 12:38:29 -070072static const char * g_outputFileName;
Traian Schiau59763032015-04-10 15:51:39 +030073// 0 means "no log rotation"
Mark Salyzyn9cc9cf02016-03-30 12:38:29 -070074static size_t g_logRotateSizeKBytes;
Traian Schiau59763032015-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 Salyzyn9cc9cf02016-03-30 12:38:29 -070078static size_t g_outByteCount;
79static int g_printBinary;
80static int g_devCount; // >1 means multiple
Casey Dahlin0f7732d2016-03-17 16:18:55 -070081static pcrecpp::RE* g_regex;
Casey Dahlin1164ef62016-03-17 14:04:52 -070082// 0 means "infinite"
Mark Salyzyn9cc9cf02016-03-30 12:38:29 -070083static size_t g_maxCount;
84static size_t g_printCount;
Mark Salyzyn3bef8972016-03-30 09:38:31 -070085static bool g_printItAnyways;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080086
Mark Salyzyndf42ce42016-03-30 12:38:29 -070087// if showHelp is set, newline required in fmt statement to transition to usage
Traian Schiau59763032015-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 Schiau59763032015-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 Schiau59763032015-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 Schiau59763032015-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 Salyzyndf42ce42016-03-30 12:38:29 -0700154static bool regexOk(const AndroidLogEntry& entry)
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700155{
Mark Salyzyndf42ce42016-03-30 12:38:29 -0700156 if (!g_regex) {
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700157 return true;
158 }
159
Casey Dahlin0f7732d2016-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 Salyzyn9421b0c2015-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 Salyzyn9421b0c2015-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 Salyzyn3bef8972016-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 Salyzyn3bef8972016-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 Dahlin1164ef62016-03-17 14:04:52 -0700199
Mark Salyzyn3bef8972016-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 Salyzyn7b30ff82015-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 Salyzyn7b30ff82015-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 Schiau59763032015-04-10 15:51:39 +0300227 logcat_panic(false, "output error");
Joe Onorato6fa09a02010-02-26 10:04:23 -0800228 }
229 }
Mark Salyzyn7b30ff82015-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 Salyzyn3ef730c2015-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 Andrewsaede9892015-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 Schiau59763032015-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 Salyzyn3ef730c2015-06-02 07:57:16 -0700261 struct stat statbuf;
Traian Schiau59763032015-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"
281 " -s Set default filter to silent.\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700282 " Like specifying filterspec '*:S'\n"
Mark Salyzynf3555d92015-05-27 07:39:56 -0700283 " -f <filename> Log to file. Default is stdout\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800284 " --file=<filename>\n"
Traian Schiau59763032015-04-10 15:51:39 +0300285 " -r <kbytes> Rotate log every kbytes. Requires -f\n"
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700286 " --rotate-kbytes=<kbytes>\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287 " -n <count> Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700288 " --rotate-count=<count>\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800289 " -v <format> Sets the log print format, where <format> is:\n"
290 " --format=<format>\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700291 " brief color epoch long monotonic printable process raw\n"
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800292 " tag thread threadtime time uid usec UTC year zone\n\n"
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800293 " -D print dividers between each log buffer\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800294 " --dividers\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295 " -c clear (flush) the entire log and exit\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800296 " --clear\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800297 " -d dump the log and then exit (don't block)\n"
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700298 " -e <expr> only print lines where the log message matches <expr>\n"
299 " --regex <expr> where <expr> is a regular expression\n"
Casey Dahlin1164ef62016-03-17 14:04:52 -0700300 " -m <count> quit after printing <count> lines. This is meant to be\n"
301 " --max-count=<count> paired with --regex, but will work on its own.\n"
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700302 " --print paired with --regex and --max-count to let content bypass\n"
303 " regex filter but still stop at number of matches.\n"
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800304 " -t <count> print only the most recent <count> lines (implies -d)\n"
Mark Salyzyn190b7ac2014-09-01 10:41:33 -0700305 " -t '<time>' print most recent lines since specified time (implies -d)\n"
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800306 " -T <count> print only the most recent <count> lines (does not imply -d)\n"
Mark Salyzyn190b7ac2014-09-01 10:41:33 -0700307 " -T '<time>' print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700308 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700309 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800310 " -g get the size of the log's ring buffer and exit\n"
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700311 " --buffer-size\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800312 " -G <size> set size of log ring buffer, may suffix with K or M.\n"
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700313 " --buffer-size=<size>\n"
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800314 " -L dump logs from prior to last reboot\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800315 " --last\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800316 // Leave security (Device Owner only installations) and
317 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn34facab2014-02-06 14:48:50 -0800318 " -b <buffer> Request alternate ring buffer, 'main', 'system', 'radio',\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800319 " --buffer=<buffer> 'events', 'crash', 'default' or 'all'. Multiple -b\n"
320 " parameters are allowed and results are interleaved. The\n"
321 " default is -b main -b system -b crash.\n"
Mark Salyzyn34facab2014-02-06 14:48:50 -0800322 " -B output the log in binary.\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800323 " --binary\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700324 " -S output statistics.\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800325 " --statistics\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700326 " -p print prune white and ~black list. Service is specified as\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800327 " --prune UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700328 " with ~, otherwise weighed for longevity if unadorned. All\n"
329 " other pruning activity is oldest first. Special case ~!\n"
330 " represents an automatic quicker pruning for the noisiest\n"
331 " UID as determined by the current statistics.\n"
332 " -P '<list> ...' set prune white and ~black list, using same format as\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800333 " --prune='<list> ...' printed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800334 " --pid=<pid> Only prints logs from the given pid.\n"
335 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value
336 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
337 " comes first. Improves efficiency of polling by providing\n"
338 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339
340 fprintf(stderr,"\nfilterspecs are a series of \n"
341 " <tag>[:priority]\n\n"
342 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700343 " V Verbose (default for <tag>)\n"
344 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345 " I Info\n"
346 " W Warn\n"
347 " E Error\n"
348 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700349 " S Silent (suppress all output)\n"
350 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
351 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
352 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
353 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
354 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700355 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356}
357
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358static int setLogFormat(const char * formatString)
359{
360 static AndroidLogPrintFormat format;
361
362 format = android_log_formatFromString(formatString);
363
364 if (format == FORMAT_OFF) {
365 // FORMAT_OFF means invalid string
366 return -1;
367 }
368
Mark Salyzyne1f20042015-05-06 08:40:40 -0700369 return android_log_setPrintFormat(g_logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800370}
371
Mark Salyzyn671e3432014-05-06 07:34:59 -0700372static const char multipliers[][2] = {
373 { "" },
374 { "K" },
375 { "M" },
376 { "G" }
377};
378
379static unsigned long value_of_size(unsigned long value)
380{
381 for (unsigned i = 0;
382 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
383 value /= 1024, ++i) ;
384 return value;
385}
386
387static const char *multiplier_of_size(unsigned long value)
388{
389 unsigned i;
390 for (i = 0;
391 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
392 value /= 1024, ++i) ;
393 return multipliers[i];
394}
395
Traian Schiau59763032015-04-10 15:51:39 +0300396/*String to unsigned int, returns -1 if it fails*/
397static bool getSizeTArg(char *ptr, size_t *val, size_t min = 0,
398 size_t max = SIZE_MAX)
399{
Kristian Monsen562e5132015-06-05 14:10:12 -0700400 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300401 return false;
402 }
403
Kristian Monsen562e5132015-06-05 14:10:12 -0700404 char *endp;
405 errno = 0;
406 size_t ret = (size_t)strtoll(ptr, &endp, 0);
407
408 if (endp[0] || errno) {
409 return false;
410 }
411
412 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300413 return false;
414 }
415
416 *val = ret;
417 return true;
418}
419
420static void logcat_panic(bool showHelp, const char *fmt, ...)
421{
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700422 va_list args;
423 va_start(args, fmt);
424 vfprintf(stderr, fmt, args);
425 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300426
427 if (showHelp) {
428 show_help(getprogname());
429 }
430
431 exit(EXIT_FAILURE);
432}
433
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700434static char *parseTime(log_time &t, const char *cp) {
435
436 char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
437 if (ep) {
438 return ep;
439 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700440 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
441 if (ep) {
442 return ep;
443 }
444 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700445}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700446
447// Find last logged line in gestalt of all matching existing output files
448static log_time lastLogTime(char *outputFileName) {
449 log_time retval(log_time::EPOCH);
450 if (!outputFileName) {
451 return retval;
452 }
453
Mark Salyzynf3555d92015-05-27 07:39:56 -0700454 std::string directory;
455 char *file = strrchr(outputFileName, '/');
456 if (!file) {
457 directory = ".";
458 file = outputFileName;
459 } else {
460 *file = '\0';
461 directory = outputFileName;
462 *file = '/';
463 ++file;
464 }
Mark Salyzyn1ab87e72016-04-01 07:52:20 -0700465
466 std::unique_ptr<DIR, int(*)(DIR*)>
467 dir(opendir(directory.c_str()), closedir);
468 if (!dir.get()) {
469 return retval;
470 }
471
472 clockid_t clock_type = android_log_clockid();
473 log_time now(clock_type);
474 bool monotonic = clock_type == CLOCK_MONOTONIC;
475
Mark Salyzynf3555d92015-05-27 07:39:56 -0700476 size_t len = strlen(file);
477 log_time modulo(0, NS_PER_SEC);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700478 struct dirent *dp;
Mark Salyzyn1ab87e72016-04-01 07:52:20 -0700479
Mark Salyzynf3555d92015-05-27 07:39:56 -0700480 while ((dp = readdir(dir.get())) != NULL) {
481 if ((dp->d_type != DT_REG)
Mark Salyzynb6bee332015-09-08 08:56:32 -0700482 // If we are using realtime, check all files that match the
483 // basename for latest time. If we are using monotonic time
484 // then only check the main file because time cycles on
485 // every reboot.
486 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzynf3555d92015-05-27 07:39:56 -0700487 || (dp->d_name[len]
488 && ((dp->d_name[len] != '.')
489 || !isdigit(dp->d_name[len+1])))) {
490 continue;
491 }
492
493 std::string file_name = directory;
494 file_name += "/";
495 file_name += dp->d_name;
496 std::string file;
497 if (!android::base::ReadFileToString(file_name, &file)) {
498 continue;
499 }
500
501 bool found = false;
502 for (const auto& line : android::base::Split(file, "\n")) {
503 log_time t(log_time::EPOCH);
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700504 char *ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700505 if (!ep || (*ep != ' ')) {
506 continue;
507 }
508 // determine the time precision of the logs (eg: msec or usec)
509 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
510 if (t.tv_nsec % (mod * 10)) {
511 modulo.tv_nsec = mod;
512 break;
513 }
514 }
515 // We filter any times later than current as we may not have the
516 // year stored with each log entry. Also, since it is possible for
517 // entries to be recorded out of order (very rare) we select the
518 // maximum we find just in case.
519 if ((t < now) && (t > retval)) {
520 retval = t;
521 found = true;
522 }
523 }
524 // We count on the basename file to be the definitive end, so stop here.
525 if (!dp->d_name[len] && found) {
526 break;
527 }
528 }
529 if (retval == log_time::EPOCH) {
530 return retval;
531 }
532 // tail_time prints matching or higher, round up by the modulo to prevent
533 // a replay of the last entry we have just checked.
534 retval += modulo;
535 return retval;
536}
537
Traian Schiau59763032015-04-10 15:51:39 +0300538} /* namespace android */
539
540
Joe Onorato6fa09a02010-02-26 10:04:23 -0800541int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542{
Traian Schiau59763032015-04-10 15:51:39 +0300543 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800544 int err;
545 int hasSetLogFormat = 0;
546 int clearLog = 0;
547 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800548 unsigned long setLogSize = 0;
549 int getPruneList = 0;
550 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800551 int printStatistics = 0;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800552 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800554 log_device_t* devices = NULL;
555 log_device_t* dev;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800556 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800557 struct logger_list *logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300558 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800559 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700560 size_t pid = 0;
Casey Dahlin1164ef62016-03-17 14:04:52 -0700561 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800563 signal(SIGPIPE, exit);
564
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565 g_logformat = android_log_format_new();
566
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiau59763032015-04-10 15:51:39 +0300568 show_help(argv[0]);
569 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570 }
571
572 for (;;) {
573 int ret;
574
Kristian Monsen562e5132015-06-05 14:10:12 -0700575 int option_index = 0;
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700576 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700577 static const char pid_str[] = "pid";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800578 static const char wrap_str[] = "wrap";
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700579 static const char print_str[] = "print";
Kristian Monsen562e5132015-06-05 14:10:12 -0700580 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800581 { "binary", no_argument, NULL, 'B' },
582 { "buffer", required_argument, NULL, 'b' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700583 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800584 { "clear", no_argument, NULL, 'c' },
585 { "dividers", no_argument, NULL, 'D' },
586 { "file", required_argument, NULL, 'f' },
587 { "format", required_argument, NULL, 'v' },
Mark Salyzyn1ab87e72016-04-01 07:52:20 -0700588 // hidden and undocumented reserved alias for --regex
589 { "grep", required_argument, NULL, 'e' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700590 // hidden and undocumented reserved alias for --max-count
591 { "head", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800592 { "last", no_argument, NULL, 'L' },
Casey Dahlin1164ef62016-03-17 14:04:52 -0700593 { "max-count", required_argument, NULL, 'm' },
Mark Salyzyn1ab87e72016-04-01 07:52:20 -0700594 { pid_str, required_argument, NULL, 0 },
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700595 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800596 { "prune", optional_argument, NULL, 'p' },
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700597 { "regex", required_argument, NULL, 'e' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700598 { "rotate-count", required_argument, NULL, 'n' },
599 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800600 { "statistics", no_argument, NULL, 'S' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700601 // hidden and undocumented reserved alias for -t
602 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800603 // support, but ignore and do not document, the optional argument
604 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700605 { NULL, 0, NULL, 0 }
606 };
607
Casey Dahlin1164ef62016-03-17 14:04:52 -0700608 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700609 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800610
611 if (ret < 0) {
612 break;
613 }
614
Kristian Monsen562e5132015-06-05 14:10:12 -0700615 switch (ret) {
616 case 0:
617 // One of the long options
618 if (long_options[option_index].name == pid_str) {
619 // ToDo: determine runtime PID_MAX?
620 if (!getSizeTArg(optarg, &pid, 1)) {
621 logcat_panic(true, "%s %s out of range\n",
622 long_options[option_index].name, optarg);
623 }
624 break;
625 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800626 if (long_options[option_index].name == wrap_str) {
627 mode |= ANDROID_LOG_WRAP |
628 ANDROID_LOG_RDONLY |
629 ANDROID_LOG_NONBLOCK;
630 // ToDo: implement API that supports setting a wrap timeout
631 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
632 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
633 logcat_panic(true, "%s %s out of range\n",
634 long_options[option_index].name, optarg);
635 }
636 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
637 fprintf(stderr,
638 "WARNING: %s %u seconds, ignoring %zu\n",
639 long_options[option_index].name,
640 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
641 }
642 break;
643 }
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700644 if (long_options[option_index].name == print_str) {
645 g_printItAnyways = true;
646 break;
647 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700648 break;
649
Mark Salyzyn95132e92013-11-22 10:55:48 -0800650 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800651 // default to all silent
652 android_log_addFilterRule(g_logformat, "*:s");
653 break;
654
655 case 'c':
656 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800657 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 break;
659
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800660 case 'L':
661 mode |= ANDROID_LOG_PSTORE;
662 break;
663
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800665 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666 break;
667
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800668 case 't':
Casey Dahlin1164ef62016-03-17 14:04:52 -0700669 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800670 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800671 /* FALLTHRU */
672 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800673 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700674 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800675 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700676 logcat_panic(false, "-%c \"%s\" not in time format\n",
677 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800678 }
679 if (*cp) {
680 char c = *cp;
681 *cp = '\0';
682 fprintf(stderr,
683 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
684 ret, optarg, c, cp + 1);
685 *cp = c;
686 }
687 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300688 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800689 fprintf(stderr,
690 "WARNING: -%c %s invalid, setting to 1\n",
691 ret, optarg);
692 tail_lines = 1;
693 }
694 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800695 break;
696
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800697 case 'D':
698 printDividers = true;
699 break;
700
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700701 case 'e':
702 g_regex = new pcrecpp::RE(optarg);
703 break;
704
Casey Dahlin1164ef62016-03-17 14:04:52 -0700705 case 'm': {
706 char *end = NULL;
707 if (!getSizeTArg(optarg, &g_maxCount)) {
708 logcat_panic(false, "-%c \"%s\" isn't an "
709 "integer greater than zero\n", ret, optarg);
710 }
711 }
712 break;
713
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800714 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800715 if (!optarg) {
716 getLogSize = 1;
717 break;
718 }
719 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800721 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300722 char *cp;
723 if (strtoll(optarg, &cp, 0) > 0) {
724 setLogSize = strtoll(optarg, &cp, 0);
725 } else {
726 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800727 }
728
729 switch(*cp) {
730 case 'g':
731 case 'G':
732 setLogSize *= 1024;
733 /* FALLTHRU */
734 case 'm':
735 case 'M':
736 setLogSize *= 1024;
737 /* FALLTHRU */
738 case 'k':
739 case 'K':
740 setLogSize *= 1024;
741 /* FALLTHRU */
742 case '\0':
743 break;
744
745 default:
746 setLogSize = 0;
747 }
748
749 if (!setLogSize) {
750 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300751 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800752 }
753 }
754 break;
755
756 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800757 if (!optarg) {
758 getPruneList = 1;
759 break;
760 }
761 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800762
763 case 'P':
764 setPruneList = optarg;
765 break;
766
Joe Onorato6fa09a02010-02-26 10:04:23 -0800767 case 'b': {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800768 if (strcmp(optarg, "default") == 0) {
769 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
770 switch (i) {
771 case LOG_ID_SECURITY:
772 case LOG_ID_EVENTS:
773 continue;
774 case LOG_ID_MAIN:
775 case LOG_ID_SYSTEM:
776 case LOG_ID_CRASH:
777 break;
778 default:
779 continue;
780 }
Mark Salyzyn34facab2014-02-06 14:48:50 -0800781
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700782 const char *name = android_log_id_to_name((log_id_t)i);
783 log_id_t log_id = android_name_to_log_id(name);
784
785 if (log_id != (log_id_t)i) {
786 continue;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800787 }
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700788
Mark Salyzyn083b0372015-12-04 10:59:45 -0800789 bool found = false;
790 for (dev = devices; dev; dev = dev->next) {
791 if (!strcmp(optarg, dev->device)) {
792 found = true;
793 break;
794 }
795 if (!dev->next) {
796 break;
797 }
798 }
799 if (found) {
800 break;
801 }
802
803 log_device_t* d = new log_device_t(name, false);
804
805 if (dev) {
806 dev->next = d;
807 dev = d;
808 } else {
809 devices = dev = d;
810 }
811 g_devCount++;
812 }
813 break;
814 }
815
816 if (strcmp(optarg, "all") == 0) {
817 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
818 const char *name = android_log_id_to_name((log_id_t)i);
819 log_id_t log_id = android_name_to_log_id(name);
820
821 if (log_id != (log_id_t)i) {
822 continue;
823 }
824
825 bool found = false;
826 for (dev = devices; dev; dev = dev->next) {
827 if (!strcmp(optarg, dev->device)) {
828 found = true;
829 break;
830 }
831 if (!dev->next) {
832 break;
833 }
834 }
835 if (found) {
836 break;
837 }
838
839 bool binary = !strcmp(name, "events") ||
840 !strcmp(name, "security");
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800841 log_device_t* d = new log_device_t(name, binary);
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700842
843 if (dev) {
844 dev->next = d;
845 dev = d;
846 } else {
847 devices = dev = d;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800848 }
Traian Schiau59763032015-04-10 15:51:39 +0300849 g_devCount++;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800850 }
851 break;
852 }
853
Mark Salyzyn083b0372015-12-04 10:59:45 -0800854 bool binary = !(strcmp(optarg, "events") &&
855 strcmp(optarg, "security"));
Joe Onorato6fa09a02010-02-26 10:04:23 -0800856
857 if (devices) {
858 dev = devices;
859 while (dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800860 if (!strcmp(optarg, dev->device)) {
861 dev = NULL;
862 break;
863 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800864 dev = dev->next;
865 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800866 if (dev) {
867 dev->next = new log_device_t(optarg, binary);
868 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800869 } else {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800870 devices = new log_device_t(optarg, binary);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800871 }
Traian Schiau59763032015-04-10 15:51:39 +0300872 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800873 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800874 break;
875
876 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300877 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878 break;
879
880 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700881 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700882 tail_time = lastLogTime(optarg);
883 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800884 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300885 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800886 break;
887
888 case 'r':
Traian Schiau59763032015-04-10 15:51:39 +0300889 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
890 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800891 }
892 break;
893
894 case 'n':
Traian Schiau59763032015-04-10 15:51:39 +0300895 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
896 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898 break;
899
900 case 'v':
901 err = setLogFormat (optarg);
902 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300903 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700905 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800906 break;
907
908 case 'Q':
909 /* this is a *hidden* option used to start a version of logcat */
910 /* in an emulated device only. it basically looks for androidboot.logcat= */
911 /* on the kernel command line. If something is found, it extracts a log filter */
912 /* and uses it to run the program. If nothing is found, the program should */
913 /* quit immediately */
914#define KERNEL_OPTION "androidboot.logcat="
915#define CONSOLE_OPTION "androidboot.console="
916 {
917 int fd;
918 char* logcat;
919 char* console;
920 int force_exit = 1;
921 static char cmdline[1024];
922
923 fd = open("/proc/cmdline", O_RDONLY);
924 if (fd >= 0) {
925 int n = read(fd, cmdline, sizeof(cmdline)-1 );
926 if (n < 0) n = 0;
927 cmdline[n] = 0;
928 close(fd);
929 } else {
930 cmdline[0] = 0;
931 }
932
933 logcat = strstr( cmdline, KERNEL_OPTION );
934 console = strstr( cmdline, CONSOLE_OPTION );
935 if (logcat != NULL) {
936 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
937 char* q = strpbrk( p, " \t\n\r" );;
938
939 if (q != NULL)
940 *q = 0;
941
942 forceFilters = p;
943 force_exit = 0;
944 }
945 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300946 if (force_exit) {
947 return EXIT_SUCCESS;
948 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949
950 /* redirect our output to the emulator console */
951 if (console) {
952 char* p = console + sizeof(CONSOLE_OPTION)-1;
953 char* q = strpbrk( p, " \t\n\r" );
954 char devname[64];
955 int len;
956
957 if (q != NULL) {
958 len = q - p;
959 } else
960 len = strlen(p);
961
962 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
963 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
964 if (len < (int)sizeof(devname)) {
965 fd = open( devname, O_WRONLY );
966 if (fd >= 0) {
967 dup2(fd, 1);
968 dup2(fd, 2);
969 close(fd);
970 }
971 }
972 }
973 }
974 break;
975
Mark Salyzyn34facab2014-02-06 14:48:50 -0800976 case 'S':
977 printStatistics = 1;
978 break;
979
Traian Schiau59763032015-04-10 15:51:39 +0300980 case ':':
981 logcat_panic(true, "Option -%c needs an argument\n", optopt);
982 break;
983
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800984 default:
Traian Schiau59763032015-04-10 15:51:39 +0300985 logcat_panic(true, "Unrecognized Option %c\n", optopt);
986 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800987 }
988 }
989
Casey Dahlin1164ef62016-03-17 14:04:52 -0700990 if (g_maxCount && got_t) {
Mark Salyzyndf42ce42016-03-30 12:38:29 -0700991 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin1164ef62016-03-17 14:04:52 -0700992 }
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700993 if (g_printItAnyways && (!g_regex || !g_maxCount)) {
994 // One day it would be nice if --print -v color and --regex <expr>
995 // could play with each other and show regex highlighted content.
996 fprintf(stderr, "WARNING: "
997 "--print ignored, to be used in combination with\n"
998 " "
999 "--regex <expr> and --max-count <N>\n");
1000 g_printItAnyways = false;
1001 }
Casey Dahlin1164ef62016-03-17 14:04:52 -07001002
Joe Onorato6fa09a02010-02-26 10:04:23 -08001003 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001004 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +03001005 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001006 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001007 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +03001008 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001009 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001010 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001011 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +03001012 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001013 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001014 }
1015
Traian Schiau59763032015-04-10 15:51:39 +03001016 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
1017 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 }
1019
Traian Schiau59763032015-04-10 15:51:39 +03001020 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001021
1022 if (hasSetLogFormat == 0) {
1023 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
1024
1025 if (logFormat != NULL) {
1026 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001027 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001028 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001029 logFormat);
1030 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001031 } else {
1032 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001033 }
1034 }
1035
1036 if (forceFilters) {
1037 err = android_log_addFilterString(g_logformat, forceFilters);
1038 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001039 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001040 }
1041 } else if (argc == optind) {
1042 // Add from environment variable
1043 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1044
1045 if (env_tags_orig != NULL) {
1046 err = android_log_addFilterString(g_logformat, env_tags_orig);
1047
Mark Salyzyn95132e92013-11-22 10:55:48 -08001048 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001049 logcat_panic(true,
1050 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001051 }
1052 }
1053 } else {
1054 // Add from commandline
1055 for (int i = optind ; i < argc ; i++) {
1056 err = android_log_addFilterString(g_logformat, argv[i]);
1057
Mark Salyzyn95132e92013-11-22 10:55:48 -08001058 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001059 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001060 }
1061 }
1062 }
1063
Joe Onorato6fa09a02010-02-26 10:04:23 -08001064 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001065 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001066 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001067 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001068 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001069 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001070 const char *openDeviceFail = NULL;
1071 const char *clearFail = NULL;
1072 const char *setSizeFail = NULL;
1073 const char *getSizeFail = NULL;
1074 // We have three orthogonal actions below to clear, set log size and
1075 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001076 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001077 dev->logger_list = logger_list;
1078 dev->logger = android_logger_open(logger_list,
1079 android_name_to_log_id(dev->device));
1080 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001081 openDeviceFail = openDeviceFail ?: dev->device;
1082 dev = dev->next;
1083 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001084 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001085
1086 if (clearLog) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001087 if (android_logger_clear(dev->logger)) {
1088 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001089 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001090 }
1091
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001092 if (setLogSize) {
1093 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1094 setSizeFail = setSizeFail ?: dev->device;
1095 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001096 }
1097
Joe Onorato6fa09a02010-02-26 10:04:23 -08001098 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001099 long size = android_logger_get_log_size(dev->logger);
1100 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001101
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001102 if ((size < 0) || (readable < 0)) {
1103 getSizeFail = getSizeFail ?: dev->device;
1104 } else {
1105 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1106 "max entry is %db, max payload is %db\n", dev->device,
1107 value_of_size(size), multiplier_of_size(size),
1108 value_of_size(readable), multiplier_of_size(readable),
1109 (int) LOGGER_ENTRY_MAX_LEN,
1110 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001111 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001112 }
1113
1114 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001115 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001116 // report any errors in the above loop and exit
1117 if (openDeviceFail) {
1118 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1119 }
1120 if (clearFail) {
1121 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1122 }
1123 if (setSizeFail) {
1124 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1125 }
1126 if (getSizeFail) {
1127 logcat_panic(false, "failed to get the readable '%s' log size",
1128 getSizeFail);
1129 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001131 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001132 size_t len = strlen(setPruneList);
1133 /*extra 32 bytes are needed by android_logger_set_prune_list */
1134 size_t bLen = len + 32;
1135 char *buf = NULL;
1136 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1137 buf[len] = '\0';
1138 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1139 logcat_panic(false, "failed to set the prune list");
1140 }
1141 free(buf);
1142 } else {
1143 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001144 }
1145 }
1146
Mark Salyzyn1c950472014-04-01 17:19:47 -07001147 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001148 size_t len = 8192;
1149 char *buf;
1150
Mark Salyzyn083b0372015-12-04 10:59:45 -08001151 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001152 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001153 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001154 if (getPruneList) {
1155 android_logger_get_prune_list(logger_list, buf, len);
1156 } else {
1157 android_logger_get_statistics(logger_list, buf, len);
1158 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001159 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001160 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001161 delete [] buf;
1162 buf = NULL;
1163 break;
1164 }
Traian Schiau59763032015-04-10 15:51:39 +03001165 size_t ret = atol(buf) + 1;
1166 if (ret <= len) {
1167 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001168 break;
1169 }
Traian Schiau59763032015-04-10 15:51:39 +03001170 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001171 }
1172
1173 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001174 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001175 }
1176
1177 // remove trailing FF
1178 char *cp = buf + len - 1;
1179 *cp = '\0';
1180 bool truncated = *--cp != '\f';
1181 if (!truncated) {
1182 *cp = '\0';
1183 }
1184
1185 // squash out the byte count
1186 cp = buf;
1187 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001188 while (isdigit(*cp)) {
1189 ++cp;
1190 }
1191 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001192 ++cp;
1193 }
1194 }
1195
1196 printf("%s", cp);
1197 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001198 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001199 }
1200
1201
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001203 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001204 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001205 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001206 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001207 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001208 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001209 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001210 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001211
1212 //LOG_EVENT_INT(10, 12345);
1213 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1214 //LOG_EVENT_STRING(0, "whassup, doc?");
1215
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001216 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001217 log_device_t unexpected("unexpected", false);
Casey Dahlin1164ef62016-03-17 14:04:52 -07001218
Mark Salyzyndf42ce42016-03-30 12:38:29 -07001219 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001220 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001221 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001222 int ret = android_logger_list_read(logger_list, &log_msg);
1223
1224 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001225 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001226 }
1227
1228 if (ret < 0) {
1229 if (ret == -EAGAIN) {
1230 break;
1231 }
1232
1233 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001234 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001235 }
1236 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001237 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001238 }
Traian Schiau59763032015-04-10 15:51:39 +03001239 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001240 }
1241
Mark Salyzyn083b0372015-12-04 10:59:45 -08001242 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001243 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001244 break;
1245 }
1246 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001247 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001248 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001249 d = &unexpected;
1250 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001251 }
1252
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001253 if (dev != d) {
1254 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001255 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001256 }
Traian Schiau59763032015-04-10 15:51:39 +03001257 if (g_printBinary) {
1258 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001259 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001260 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001261 }
1262 }
1263
1264 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001265
Traian Schiau59763032015-04-10 15:51:39 +03001266 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001267}