blob: 15fc0354139b0cfddad13a25f8aaa70a2c027daa [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 Salyzynba7a9a02015-12-01 15:57:25 -0800454 clockid_t clock_type = android_log_clockid();
455 log_time now(clock_type);
456 bool monotonic = clock_type == CLOCK_MONOTONIC;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700457
458 std::string directory;
459 char *file = strrchr(outputFileName, '/');
460 if (!file) {
461 directory = ".";
462 file = outputFileName;
463 } else {
464 *file = '\0';
465 directory = outputFileName;
466 *file = '/';
467 ++file;
468 }
469 size_t len = strlen(file);
470 log_time modulo(0, NS_PER_SEC);
471 std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(directory.c_str()), closedir);
472 struct dirent *dp;
473 while ((dp = readdir(dir.get())) != NULL) {
474 if ((dp->d_type != DT_REG)
Mark Salyzynb6bee332015-09-08 08:56:32 -0700475 // If we are using realtime, check all files that match the
476 // basename for latest time. If we are using monotonic time
477 // then only check the main file because time cycles on
478 // every reboot.
479 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzynf3555d92015-05-27 07:39:56 -0700480 || (dp->d_name[len]
481 && ((dp->d_name[len] != '.')
482 || !isdigit(dp->d_name[len+1])))) {
483 continue;
484 }
485
486 std::string file_name = directory;
487 file_name += "/";
488 file_name += dp->d_name;
489 std::string file;
490 if (!android::base::ReadFileToString(file_name, &file)) {
491 continue;
492 }
493
494 bool found = false;
495 for (const auto& line : android::base::Split(file, "\n")) {
496 log_time t(log_time::EPOCH);
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700497 char *ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700498 if (!ep || (*ep != ' ')) {
499 continue;
500 }
501 // determine the time precision of the logs (eg: msec or usec)
502 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
503 if (t.tv_nsec % (mod * 10)) {
504 modulo.tv_nsec = mod;
505 break;
506 }
507 }
508 // We filter any times later than current as we may not have the
509 // year stored with each log entry. Also, since it is possible for
510 // entries to be recorded out of order (very rare) we select the
511 // maximum we find just in case.
512 if ((t < now) && (t > retval)) {
513 retval = t;
514 found = true;
515 }
516 }
517 // We count on the basename file to be the definitive end, so stop here.
518 if (!dp->d_name[len] && found) {
519 break;
520 }
521 }
522 if (retval == log_time::EPOCH) {
523 return retval;
524 }
525 // tail_time prints matching or higher, round up by the modulo to prevent
526 // a replay of the last entry we have just checked.
527 retval += modulo;
528 return retval;
529}
530
Traian Schiau59763032015-04-10 15:51:39 +0300531} /* namespace android */
532
533
Joe Onorato6fa09a02010-02-26 10:04:23 -0800534int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800535{
Traian Schiau59763032015-04-10 15:51:39 +0300536 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800537 int err;
538 int hasSetLogFormat = 0;
539 int clearLog = 0;
540 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800541 unsigned long setLogSize = 0;
542 int getPruneList = 0;
543 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800544 int printStatistics = 0;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800545 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800547 log_device_t* devices = NULL;
548 log_device_t* dev;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800549 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800550 struct logger_list *logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300551 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800552 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700553 size_t pid = 0;
Casey Dahlin1164ef62016-03-17 14:04:52 -0700554 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800555
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800556 signal(SIGPIPE, exit);
557
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 g_logformat = android_log_format_new();
559
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiau59763032015-04-10 15:51:39 +0300561 show_help(argv[0]);
562 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563 }
564
565 for (;;) {
566 int ret;
567
Kristian Monsen562e5132015-06-05 14:10:12 -0700568 int option_index = 0;
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700569 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700570 static const char pid_str[] = "pid";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800571 static const char wrap_str[] = "wrap";
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700572 static const char print_str[] = "print";
Kristian Monsen562e5132015-06-05 14:10:12 -0700573 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800574 { "binary", no_argument, NULL, 'B' },
575 { "buffer", required_argument, NULL, 'b' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700576 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800577 { "clear", no_argument, NULL, 'c' },
578 { "dividers", no_argument, NULL, 'D' },
579 { "file", required_argument, NULL, 'f' },
580 { "format", required_argument, NULL, 'v' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700581 // hidden and undocumented reserved alias for --max-count
582 { "head", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800583 { "last", no_argument, NULL, 'L' },
Kristian Monsen562e5132015-06-05 14:10:12 -0700584 { pid_str, required_argument, NULL, 0 },
Casey Dahlin1164ef62016-03-17 14:04:52 -0700585 { "max-count", required_argument, NULL, 'm' },
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700586 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800587 { "prune", optional_argument, NULL, 'p' },
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700588 { "regex", required_argument, NULL, 'e' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700589 { "rotate-count", required_argument, NULL, 'n' },
590 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800591 { "statistics", no_argument, NULL, 'S' },
Mark Salyzyn7ec59402016-03-30 09:15:09 -0700592 // hidden and undocumented reserved alias for -t
593 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800594 // support, but ignore and do not document, the optional argument
595 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700596 { NULL, 0, NULL, 0 }
597 };
598
Casey Dahlin1164ef62016-03-17 14:04:52 -0700599 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700600 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601
602 if (ret < 0) {
603 break;
604 }
605
Kristian Monsen562e5132015-06-05 14:10:12 -0700606 switch (ret) {
607 case 0:
608 // One of the long options
609 if (long_options[option_index].name == pid_str) {
610 // ToDo: determine runtime PID_MAX?
611 if (!getSizeTArg(optarg, &pid, 1)) {
612 logcat_panic(true, "%s %s out of range\n",
613 long_options[option_index].name, optarg);
614 }
615 break;
616 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800617 if (long_options[option_index].name == wrap_str) {
618 mode |= ANDROID_LOG_WRAP |
619 ANDROID_LOG_RDONLY |
620 ANDROID_LOG_NONBLOCK;
621 // ToDo: implement API that supports setting a wrap timeout
622 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
623 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
624 logcat_panic(true, "%s %s out of range\n",
625 long_options[option_index].name, optarg);
626 }
627 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
628 fprintf(stderr,
629 "WARNING: %s %u seconds, ignoring %zu\n",
630 long_options[option_index].name,
631 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
632 }
633 break;
634 }
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700635 if (long_options[option_index].name == print_str) {
636 g_printItAnyways = true;
637 break;
638 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700639 break;
640
Mark Salyzyn95132e92013-11-22 10:55:48 -0800641 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642 // default to all silent
643 android_log_addFilterRule(g_logformat, "*:s");
644 break;
645
646 case 'c':
647 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800648 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800649 break;
650
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800651 case 'L':
652 mode |= ANDROID_LOG_PSTORE;
653 break;
654
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800656 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657 break;
658
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800659 case 't':
Casey Dahlin1164ef62016-03-17 14:04:52 -0700660 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800661 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800662 /* FALLTHRU */
663 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800664 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700665 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800666 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700667 logcat_panic(false, "-%c \"%s\" not in time format\n",
668 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800669 }
670 if (*cp) {
671 char c = *cp;
672 *cp = '\0';
673 fprintf(stderr,
674 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
675 ret, optarg, c, cp + 1);
676 *cp = c;
677 }
678 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300679 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800680 fprintf(stderr,
681 "WARNING: -%c %s invalid, setting to 1\n",
682 ret, optarg);
683 tail_lines = 1;
684 }
685 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800686 break;
687
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800688 case 'D':
689 printDividers = true;
690 break;
691
Casey Dahlin0f7732d2016-03-17 16:18:55 -0700692 case 'e':
693 g_regex = new pcrecpp::RE(optarg);
694 break;
695
Casey Dahlin1164ef62016-03-17 14:04:52 -0700696 case 'm': {
697 char *end = NULL;
698 if (!getSizeTArg(optarg, &g_maxCount)) {
699 logcat_panic(false, "-%c \"%s\" isn't an "
700 "integer greater than zero\n", ret, optarg);
701 }
702 }
703 break;
704
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800705 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800706 if (!optarg) {
707 getLogSize = 1;
708 break;
709 }
710 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800711
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800712 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300713 char *cp;
714 if (strtoll(optarg, &cp, 0) > 0) {
715 setLogSize = strtoll(optarg, &cp, 0);
716 } else {
717 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800718 }
719
720 switch(*cp) {
721 case 'g':
722 case 'G':
723 setLogSize *= 1024;
724 /* FALLTHRU */
725 case 'm':
726 case 'M':
727 setLogSize *= 1024;
728 /* FALLTHRU */
729 case 'k':
730 case 'K':
731 setLogSize *= 1024;
732 /* FALLTHRU */
733 case '\0':
734 break;
735
736 default:
737 setLogSize = 0;
738 }
739
740 if (!setLogSize) {
741 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300742 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800743 }
744 }
745 break;
746
747 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800748 if (!optarg) {
749 getPruneList = 1;
750 break;
751 }
752 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800753
754 case 'P':
755 setPruneList = optarg;
756 break;
757
Joe Onorato6fa09a02010-02-26 10:04:23 -0800758 case 'b': {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800759 if (strcmp(optarg, "default") == 0) {
760 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
761 switch (i) {
762 case LOG_ID_SECURITY:
763 case LOG_ID_EVENTS:
764 continue;
765 case LOG_ID_MAIN:
766 case LOG_ID_SYSTEM:
767 case LOG_ID_CRASH:
768 break;
769 default:
770 continue;
771 }
Mark Salyzyn34facab2014-02-06 14:48:50 -0800772
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700773 const char *name = android_log_id_to_name((log_id_t)i);
774 log_id_t log_id = android_name_to_log_id(name);
775
776 if (log_id != (log_id_t)i) {
777 continue;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800778 }
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700779
Mark Salyzyn083b0372015-12-04 10:59:45 -0800780 bool found = false;
781 for (dev = devices; dev; dev = dev->next) {
782 if (!strcmp(optarg, dev->device)) {
783 found = true;
784 break;
785 }
786 if (!dev->next) {
787 break;
788 }
789 }
790 if (found) {
791 break;
792 }
793
794 log_device_t* d = new log_device_t(name, false);
795
796 if (dev) {
797 dev->next = d;
798 dev = d;
799 } else {
800 devices = dev = d;
801 }
802 g_devCount++;
803 }
804 break;
805 }
806
807 if (strcmp(optarg, "all") == 0) {
808 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
809 const char *name = android_log_id_to_name((log_id_t)i);
810 log_id_t log_id = android_name_to_log_id(name);
811
812 if (log_id != (log_id_t)i) {
813 continue;
814 }
815
816 bool found = false;
817 for (dev = devices; dev; dev = dev->next) {
818 if (!strcmp(optarg, dev->device)) {
819 found = true;
820 break;
821 }
822 if (!dev->next) {
823 break;
824 }
825 }
826 if (found) {
827 break;
828 }
829
830 bool binary = !strcmp(name, "events") ||
831 !strcmp(name, "security");
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800832 log_device_t* d = new log_device_t(name, binary);
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700833
834 if (dev) {
835 dev->next = d;
836 dev = d;
837 } else {
838 devices = dev = d;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800839 }
Traian Schiau59763032015-04-10 15:51:39 +0300840 g_devCount++;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800841 }
842 break;
843 }
844
Mark Salyzyn083b0372015-12-04 10:59:45 -0800845 bool binary = !(strcmp(optarg, "events") &&
846 strcmp(optarg, "security"));
Joe Onorato6fa09a02010-02-26 10:04:23 -0800847
848 if (devices) {
849 dev = devices;
850 while (dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800851 if (!strcmp(optarg, dev->device)) {
852 dev = NULL;
853 break;
854 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800855 dev = dev->next;
856 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800857 if (dev) {
858 dev->next = new log_device_t(optarg, binary);
859 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800860 } else {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800861 devices = new log_device_t(optarg, binary);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800862 }
Traian Schiau59763032015-04-10 15:51:39 +0300863 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800864 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 break;
866
867 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300868 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800869 break;
870
871 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700872 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700873 tail_time = lastLogTime(optarg);
874 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800875 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300876 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877 break;
878
879 case 'r':
Traian Schiau59763032015-04-10 15:51:39 +0300880 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
881 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800882 }
883 break;
884
885 case 'n':
Traian Schiau59763032015-04-10 15:51:39 +0300886 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
887 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889 break;
890
891 case 'v':
892 err = setLogFormat (optarg);
893 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300894 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800895 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700896 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897 break;
898
899 case 'Q':
900 /* this is a *hidden* option used to start a version of logcat */
901 /* in an emulated device only. it basically looks for androidboot.logcat= */
902 /* on the kernel command line. If something is found, it extracts a log filter */
903 /* and uses it to run the program. If nothing is found, the program should */
904 /* quit immediately */
905#define KERNEL_OPTION "androidboot.logcat="
906#define CONSOLE_OPTION "androidboot.console="
907 {
908 int fd;
909 char* logcat;
910 char* console;
911 int force_exit = 1;
912 static char cmdline[1024];
913
914 fd = open("/proc/cmdline", O_RDONLY);
915 if (fd >= 0) {
916 int n = read(fd, cmdline, sizeof(cmdline)-1 );
917 if (n < 0) n = 0;
918 cmdline[n] = 0;
919 close(fd);
920 } else {
921 cmdline[0] = 0;
922 }
923
924 logcat = strstr( cmdline, KERNEL_OPTION );
925 console = strstr( cmdline, CONSOLE_OPTION );
926 if (logcat != NULL) {
927 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
928 char* q = strpbrk( p, " \t\n\r" );;
929
930 if (q != NULL)
931 *q = 0;
932
933 forceFilters = p;
934 force_exit = 0;
935 }
936 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300937 if (force_exit) {
938 return EXIT_SUCCESS;
939 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800940
941 /* redirect our output to the emulator console */
942 if (console) {
943 char* p = console + sizeof(CONSOLE_OPTION)-1;
944 char* q = strpbrk( p, " \t\n\r" );
945 char devname[64];
946 int len;
947
948 if (q != NULL) {
949 len = q - p;
950 } else
951 len = strlen(p);
952
953 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
954 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
955 if (len < (int)sizeof(devname)) {
956 fd = open( devname, O_WRONLY );
957 if (fd >= 0) {
958 dup2(fd, 1);
959 dup2(fd, 2);
960 close(fd);
961 }
962 }
963 }
964 }
965 break;
966
Mark Salyzyn34facab2014-02-06 14:48:50 -0800967 case 'S':
968 printStatistics = 1;
969 break;
970
Traian Schiau59763032015-04-10 15:51:39 +0300971 case ':':
972 logcat_panic(true, "Option -%c needs an argument\n", optopt);
973 break;
974
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800975 default:
Traian Schiau59763032015-04-10 15:51:39 +0300976 logcat_panic(true, "Unrecognized Option %c\n", optopt);
977 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800978 }
979 }
980
Casey Dahlin1164ef62016-03-17 14:04:52 -0700981 if (g_maxCount && got_t) {
Mark Salyzyndf42ce42016-03-30 12:38:29 -0700982 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin1164ef62016-03-17 14:04:52 -0700983 }
Mark Salyzyn3bef8972016-03-30 09:38:31 -0700984 if (g_printItAnyways && (!g_regex || !g_maxCount)) {
985 // One day it would be nice if --print -v color and --regex <expr>
986 // could play with each other and show regex highlighted content.
987 fprintf(stderr, "WARNING: "
988 "--print ignored, to be used in combination with\n"
989 " "
990 "--regex <expr> and --max-count <N>\n");
991 g_printItAnyways = false;
992 }
Casey Dahlin1164ef62016-03-17 14:04:52 -0700993
Joe Onorato6fa09a02010-02-26 10:04:23 -0800994 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800995 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +0300996 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800997 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800998 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +0300999 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001000 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001001 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001002 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +03001003 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001004 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001005 }
1006
Traian Schiau59763032015-04-10 15:51:39 +03001007 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
1008 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009 }
1010
Traian Schiau59763032015-04-10 15:51:39 +03001011 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001012
1013 if (hasSetLogFormat == 0) {
1014 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
1015
1016 if (logFormat != NULL) {
1017 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001019 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020 logFormat);
1021 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001022 } else {
1023 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024 }
1025 }
1026
1027 if (forceFilters) {
1028 err = android_log_addFilterString(g_logformat, forceFilters);
1029 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001030 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001031 }
1032 } else if (argc == optind) {
1033 // Add from environment variable
1034 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1035
1036 if (env_tags_orig != NULL) {
1037 err = android_log_addFilterString(g_logformat, env_tags_orig);
1038
Mark Salyzyn95132e92013-11-22 10:55:48 -08001039 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001040 logcat_panic(true,
1041 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001042 }
1043 }
1044 } else {
1045 // Add from commandline
1046 for (int i = optind ; i < argc ; i++) {
1047 err = android_log_addFilterString(g_logformat, argv[i]);
1048
Mark Salyzyn95132e92013-11-22 10:55:48 -08001049 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001050 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001051 }
1052 }
1053 }
1054
Joe Onorato6fa09a02010-02-26 10:04:23 -08001055 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001056 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001057 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001058 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001059 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001060 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001061 const char *openDeviceFail = NULL;
1062 const char *clearFail = NULL;
1063 const char *setSizeFail = NULL;
1064 const char *getSizeFail = NULL;
1065 // We have three orthogonal actions below to clear, set log size and
1066 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001067 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001068 dev->logger_list = logger_list;
1069 dev->logger = android_logger_open(logger_list,
1070 android_name_to_log_id(dev->device));
1071 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001072 openDeviceFail = openDeviceFail ?: dev->device;
1073 dev = dev->next;
1074 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001075 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001076
1077 if (clearLog) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001078 if (android_logger_clear(dev->logger)) {
1079 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001080 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001081 }
1082
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001083 if (setLogSize) {
1084 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1085 setSizeFail = setSizeFail ?: dev->device;
1086 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001087 }
1088
Joe Onorato6fa09a02010-02-26 10:04:23 -08001089 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001090 long size = android_logger_get_log_size(dev->logger);
1091 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001092
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001093 if ((size < 0) || (readable < 0)) {
1094 getSizeFail = getSizeFail ?: dev->device;
1095 } else {
1096 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1097 "max entry is %db, max payload is %db\n", dev->device,
1098 value_of_size(size), multiplier_of_size(size),
1099 value_of_size(readable), multiplier_of_size(readable),
1100 (int) LOGGER_ENTRY_MAX_LEN,
1101 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001102 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001103 }
1104
1105 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001106 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001107 // report any errors in the above loop and exit
1108 if (openDeviceFail) {
1109 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1110 }
1111 if (clearFail) {
1112 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1113 }
1114 if (setSizeFail) {
1115 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1116 }
1117 if (getSizeFail) {
1118 logcat_panic(false, "failed to get the readable '%s' log size",
1119 getSizeFail);
1120 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001122 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001123 size_t len = strlen(setPruneList);
1124 /*extra 32 bytes are needed by android_logger_set_prune_list */
1125 size_t bLen = len + 32;
1126 char *buf = NULL;
1127 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1128 buf[len] = '\0';
1129 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1130 logcat_panic(false, "failed to set the prune list");
1131 }
1132 free(buf);
1133 } else {
1134 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001135 }
1136 }
1137
Mark Salyzyn1c950472014-04-01 17:19:47 -07001138 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001139 size_t len = 8192;
1140 char *buf;
1141
Mark Salyzyn083b0372015-12-04 10:59:45 -08001142 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001143 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001144 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001145 if (getPruneList) {
1146 android_logger_get_prune_list(logger_list, buf, len);
1147 } else {
1148 android_logger_get_statistics(logger_list, buf, len);
1149 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001150 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001151 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001152 delete [] buf;
1153 buf = NULL;
1154 break;
1155 }
Traian Schiau59763032015-04-10 15:51:39 +03001156 size_t ret = atol(buf) + 1;
1157 if (ret <= len) {
1158 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001159 break;
1160 }
Traian Schiau59763032015-04-10 15:51:39 +03001161 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001162 }
1163
1164 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001165 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001166 }
1167
1168 // remove trailing FF
1169 char *cp = buf + len - 1;
1170 *cp = '\0';
1171 bool truncated = *--cp != '\f';
1172 if (!truncated) {
1173 *cp = '\0';
1174 }
1175
1176 // squash out the byte count
1177 cp = buf;
1178 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001179 while (isdigit(*cp)) {
1180 ++cp;
1181 }
1182 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001183 ++cp;
1184 }
1185 }
1186
1187 printf("%s", cp);
1188 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001189 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001190 }
1191
1192
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001193 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001194 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001195 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001196 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001197 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001198 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001199 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001200 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001201 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202
1203 //LOG_EVENT_INT(10, 12345);
1204 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1205 //LOG_EVENT_STRING(0, "whassup, doc?");
1206
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001207 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001208 log_device_t unexpected("unexpected", false);
Casey Dahlin1164ef62016-03-17 14:04:52 -07001209
Mark Salyzyndf42ce42016-03-30 12:38:29 -07001210 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001211 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001212 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001213 int ret = android_logger_list_read(logger_list, &log_msg);
1214
1215 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001216 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001217 }
1218
1219 if (ret < 0) {
1220 if (ret == -EAGAIN) {
1221 break;
1222 }
1223
1224 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001225 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001226 }
1227 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001228 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001229 }
Traian Schiau59763032015-04-10 15:51:39 +03001230 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001231 }
1232
Mark Salyzyn083b0372015-12-04 10:59:45 -08001233 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001234 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001235 break;
1236 }
1237 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001238 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001239 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001240 d = &unexpected;
1241 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001242 }
1243
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001244 if (dev != d) {
1245 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001246 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001247 }
Traian Schiau59763032015-04-10 15:51:39 +03001248 if (g_printBinary) {
1249 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001250 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001251 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001252 }
1253 }
1254
1255 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001256
Traian Schiau59763032015-04-10 15:51:39 +03001257 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001258}