blob: 6d20f4ae9ad722430518d8ee54cd269195d94b99 [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>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080038#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039
Casey Dahlindc42a872016-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 Salyzync6d66522016-03-30 12:38:29 -070072static const char * g_outputFileName;
Traian Schiau59763032015-04-10 15:51:39 +030073// 0 means "no log rotation"
Mark Salyzync6d66522016-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 Salyzync6d66522016-03-30 12:38:29 -070078static size_t g_outByteCount;
79static int g_printBinary;
80static int g_devCount; // >1 means multiple
Casey Dahlindc42a872016-03-17 16:18:55 -070081static pcrecpp::RE* g_regex;
Casey Dahlin6ac498d2016-03-17 14:04:52 -070082// 0 means "infinite"
Mark Salyzync6d66522016-03-30 12:38:29 -070083static size_t g_maxCount;
84static size_t g_printCount;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080085
Mark Salyzynaa730c12016-03-30 12:38:29 -070086// if showHelp is set, newline required in fmt statement to transition to usage
Traian Schiau59763032015-04-10 15:51:39 +030087__noreturn static void logcat_panic(bool showHelp, const char *fmt, ...) __printflike(2,3);
88
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080089static int openLogFile (const char *pathname)
90{
Edwin Vane80b221c2012-08-13 12:55:07 -040091 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080092}
93
94static void rotateLogs()
95{
96 int err;
97
98 // Can't rotate logs if we're not outputting to a file
99 if (g_outputFileName == NULL) {
100 return;
101 }
102
103 close(g_outFD);
104
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700105 // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
106 // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
107 int maxRotationCountDigits =
108 (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
109
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800110 for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
111 char *file0, *file1;
112
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700113 asprintf(&file1, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800114
115 if (i - 1 == 0) {
116 asprintf(&file0, "%s", g_outputFileName);
117 } else {
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700118 asprintf(&file0, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800119 }
120
Traian Schiau59763032015-04-10 15:51:39 +0300121 if (!file0 || !file1) {
122 perror("while rotating log files");
123 break;
124 }
125
126 err = rename(file0, file1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800127
128 if (err < 0 && errno != ENOENT) {
129 perror("while rotating log files");
130 }
131
132 free(file1);
133 free(file0);
134 }
135
Traian Schiau59763032015-04-10 15:51:39 +0300136 g_outFD = openLogFile(g_outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800137
138 if (g_outFD < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300139 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800140 }
141
142 g_outByteCount = 0;
143
144}
145
Mark Salyzyn95132e92013-11-22 10:55:48 -0800146void printBinary(struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147{
Mark Salyzyn95132e92013-11-22 10:55:48 -0800148 size_t size = buf->len();
149
150 TEMP_FAILURE_RETRY(write(g_outFD, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800151}
152
Mark Salyzynaa730c12016-03-30 12:38:29 -0700153static bool regexOk(const AndroidLogEntry& entry)
Casey Dahlindc42a872016-03-17 16:18:55 -0700154{
Mark Salyzynaa730c12016-03-30 12:38:29 -0700155 if (!g_regex) {
Casey Dahlindc42a872016-03-17 16:18:55 -0700156 return true;
157 }
158
Casey Dahlindc42a872016-03-17 16:18:55 -0700159 std::string messageString(entry.message, entry.messageLen);
160
161 return g_regex->PartialMatch(messageString);
162}
163
Mark Salyzyn95132e92013-11-22 10:55:48 -0800164static void processBuffer(log_device_t* dev, struct log_msg *buf)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800165{
Mathias Agopian50844522010-03-17 16:10:26 -0700166 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167 int err;
168 AndroidLogEntry entry;
169 char binaryMsgBuf[1024];
170
Joe Onorato6fa09a02010-02-26 10:04:23 -0800171 if (dev->binary) {
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800172 static bool hasOpenedEventTagMap = false;
173 static EventTagMap *eventTagMap = NULL;
174
175 if (!eventTagMap && !hasOpenedEventTagMap) {
176 eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);
177 hasOpenedEventTagMap = true;
178 }
Mark Salyzyn95132e92013-11-22 10:55:48 -0800179 err = android_log_processBinaryLogBuffer(&buf->entry_v1, &entry,
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800180 eventTagMap,
Mark Salyzyn95132e92013-11-22 10:55:48 -0800181 binaryMsgBuf,
182 sizeof(binaryMsgBuf));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183 //printf(">>> pri=%d len=%d msg='%s'\n",
184 // entry.priority, entry.messageLen, entry.message);
185 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800186 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800187 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800188 if (err < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 goto error;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800190 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800191
Casey Dahlindc42a872016-03-17 16:18:55 -0700192 if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority) &&
Mark Salyzynaa730c12016-03-30 12:38:29 -0700193 regexOk(entry)) {
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800194 bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
195
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700196 g_printCount++;
197
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800198 if (bytesWritten < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300199 logcat_panic(false, "output error");
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800200 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201 }
202
203 g_outByteCount += bytesWritten;
204
Mark Salyzyn95132e92013-11-22 10:55:48 -0800205 if (g_logRotateSizeKBytes > 0
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800206 && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
207 ) {
208 rotateLogs();
209 }
210
211error:
212 //fprintf (stderr, "Error processing record\n");
213 return;
214}
215
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800216static void maybePrintStart(log_device_t* dev, bool printDividers) {
217 if (!dev->printed || printDividers) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800218 if (g_devCount > 1 && !g_printBinary) {
219 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800220 snprintf(buf, sizeof(buf), "--------- %s %s\n",
221 dev->printed ? "switch to" : "beginning of",
Mark Salyzyn95132e92013-11-22 10:55:48 -0800222 dev->device);
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800223 if (write(g_outFD, buf, strlen(buf)) < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300224 logcat_panic(false, "output error");
Joe Onorato6fa09a02010-02-26 10:04:23 -0800225 }
226 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800227 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800228 }
229}
230
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800231static void setupOutput()
232{
233
234 if (g_outputFileName == NULL) {
235 g_outFD = STDOUT_FILENO;
236
237 } else {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700238 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
239 fprintf(stderr, "failed to set background scheduling policy\n");
240 }
241
242 struct sched_param param;
243 memset(&param, 0, sizeof(param));
244 if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
245 fprintf(stderr, "failed to set to batch scheduler\n");
246 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800247
Riley Andrewsaede9892015-06-08 23:36:34 -0700248 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
249 fprintf(stderr, "failed set to priority\n");
250 }
251
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800252 g_outFD = openLogFile (g_outputFileName);
253
254 if (g_outFD < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300255 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800256 }
257
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700258 struct stat statbuf;
Traian Schiau59763032015-04-10 15:51:39 +0300259 if (fstat(g_outFD, &statbuf) == -1) {
260 close(g_outFD);
261 logcat_panic(false, "couldn't get output file stat\n");
262 }
263
264 if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
265 close(g_outFD);
266 logcat_panic(false, "invalid output file stat\n");
267 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268
269 g_outByteCount = statbuf.st_size;
270 }
271}
272
273static void show_help(const char *cmd)
274{
275 fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
276
277 fprintf(stderr, "options include:\n"
278 " -s Set default filter to silent.\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700279 " Like specifying filterspec '*:S'\n"
Mark Salyzynf3555d92015-05-27 07:39:56 -0700280 " -f <filename> Log to file. Default is stdout\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800281 " --file=<filename>\n"
Traian Schiau59763032015-04-10 15:51:39 +0300282 " -r <kbytes> Rotate log every kbytes. Requires -f\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800283 " --rotate_kbytes=<kbytes>\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284 " -n <count> Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800285 " --rotate_count=<count>\n"
286 " -v <format> Sets the log print format, where <format> is:\n"
287 " --format=<format>\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700288 " brief color epoch long monotonic printable process raw\n"
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800289 " tag thread threadtime time uid usec UTC year zone\n\n"
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800290 " -D print dividers between each log buffer\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800291 " --dividers\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800292 " -c clear (flush) the entire log and exit\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800293 " --clear\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294 " -d dump the log and then exit (don't block)\n"
Casey Dahlindc42a872016-03-17 16:18:55 -0700295 " -e <expr> only print lines where the log message matches <expr>\n"
296 " --regex <expr> where <expr> is a regular expression\n"
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700297 " -m <count> quit after printing <count> lines. This is meant to be\n"
298 " --max-count=<count> paired with --regex, but will work on its own.\n"
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800299 " -t <count> print only the most recent <count> lines (implies -d)\n"
Mark Salyzyn190b7ac2014-09-01 10:41:33 -0700300 " -t '<time>' print most recent lines since specified time (implies -d)\n"
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800301 " -T <count> print only the most recent <count> lines (does not imply -d)\n"
Mark Salyzyn190b7ac2014-09-01 10:41:33 -0700302 " -T '<time>' print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700303 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700304 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800305 " -g get the size of the log's ring buffer and exit\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800306 " --buffer_size\n"
307 " -G <size> set size of log ring buffer, may suffix with K or M.\n"
308 " --buffer_size=<size>\n"
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800309 " -L dump logs from prior to last reboot\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800310 " --last\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800311 // Leave security (Device Owner only installations) and
312 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn34facab2014-02-06 14:48:50 -0800313 " -b <buffer> Request alternate ring buffer, 'main', 'system', 'radio',\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800314 " --buffer=<buffer> 'events', 'crash', 'default' or 'all'. Multiple -b\n"
315 " parameters are allowed and results are interleaved. The\n"
316 " default is -b main -b system -b crash.\n"
Mark Salyzyn34facab2014-02-06 14:48:50 -0800317 " -B output the log in binary.\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800318 " --binary\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700319 " -S output statistics.\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800320 " --statistics\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700321 " -p print prune white and ~black list. Service is specified as\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800322 " --prune UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700323 " with ~, otherwise weighed for longevity if unadorned. All\n"
324 " other pruning activity is oldest first. Special case ~!\n"
325 " represents an automatic quicker pruning for the noisiest\n"
326 " UID as determined by the current statistics.\n"
327 " -P '<list> ...' set prune white and ~black list, using same format as\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800328 " --prune='<list> ...' printed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800329 " --pid=<pid> Only prints logs from the given pid.\n"
330 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value
331 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
332 " comes first. Improves efficiency of polling by providing\n"
333 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800334
335 fprintf(stderr,"\nfilterspecs are a series of \n"
336 " <tag>[:priority]\n\n"
337 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700338 " V Verbose (default for <tag>)\n"
339 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800340 " I Info\n"
341 " W Warn\n"
342 " E Error\n"
343 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700344 " S Silent (suppress all output)\n"
345 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
346 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
347 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
348 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
349 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700350 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351}
352
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800353static int setLogFormat(const char * formatString)
354{
355 static AndroidLogPrintFormat format;
356
357 format = android_log_formatFromString(formatString);
358
359 if (format == FORMAT_OFF) {
360 // FORMAT_OFF means invalid string
361 return -1;
362 }
363
Mark Salyzyne1f20042015-05-06 08:40:40 -0700364 return android_log_setPrintFormat(g_logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800365}
366
Mark Salyzyn671e3432014-05-06 07:34:59 -0700367static const char multipliers[][2] = {
368 { "" },
369 { "K" },
370 { "M" },
371 { "G" }
372};
373
374static unsigned long value_of_size(unsigned long value)
375{
376 for (unsigned i = 0;
377 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
378 value /= 1024, ++i) ;
379 return value;
380}
381
382static const char *multiplier_of_size(unsigned long value)
383{
384 unsigned i;
385 for (i = 0;
386 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
387 value /= 1024, ++i) ;
388 return multipliers[i];
389}
390
Traian Schiau59763032015-04-10 15:51:39 +0300391/*String to unsigned int, returns -1 if it fails*/
392static bool getSizeTArg(char *ptr, size_t *val, size_t min = 0,
393 size_t max = SIZE_MAX)
394{
Kristian Monsen562e5132015-06-05 14:10:12 -0700395 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300396 return false;
397 }
398
Kristian Monsen562e5132015-06-05 14:10:12 -0700399 char *endp;
400 errno = 0;
401 size_t ret = (size_t)strtoll(ptr, &endp, 0);
402
403 if (endp[0] || errno) {
404 return false;
405 }
406
407 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300408 return false;
409 }
410
411 *val = ret;
412 return true;
413}
414
415static void logcat_panic(bool showHelp, const char *fmt, ...)
416{
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700417 va_list args;
418 va_start(args, fmt);
419 vfprintf(stderr, fmt, args);
420 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300421
422 if (showHelp) {
423 show_help(getprogname());
424 }
425
426 exit(EXIT_FAILURE);
427}
428
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700429static char *parseTime(log_time &t, const char *cp) {
430
431 char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
432 if (ep) {
433 return ep;
434 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700435 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
436 if (ep) {
437 return ep;
438 }
439 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700440}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700441
442// Find last logged line in gestalt of all matching existing output files
443static log_time lastLogTime(char *outputFileName) {
444 log_time retval(log_time::EPOCH);
445 if (!outputFileName) {
446 return retval;
447 }
448
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800449 clockid_t clock_type = android_log_clockid();
450 log_time now(clock_type);
451 bool monotonic = clock_type == CLOCK_MONOTONIC;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700452
453 std::string directory;
454 char *file = strrchr(outputFileName, '/');
455 if (!file) {
456 directory = ".";
457 file = outputFileName;
458 } else {
459 *file = '\0';
460 directory = outputFileName;
461 *file = '/';
462 ++file;
463 }
464 size_t len = strlen(file);
465 log_time modulo(0, NS_PER_SEC);
466 std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(directory.c_str()), closedir);
467 struct dirent *dp;
468 while ((dp = readdir(dir.get())) != NULL) {
469 if ((dp->d_type != DT_REG)
Mark Salyzynb6bee332015-09-08 08:56:32 -0700470 // If we are using realtime, check all files that match the
471 // basename for latest time. If we are using monotonic time
472 // then only check the main file because time cycles on
473 // every reboot.
474 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzynf3555d92015-05-27 07:39:56 -0700475 || (dp->d_name[len]
476 && ((dp->d_name[len] != '.')
477 || !isdigit(dp->d_name[len+1])))) {
478 continue;
479 }
480
481 std::string file_name = directory;
482 file_name += "/";
483 file_name += dp->d_name;
484 std::string file;
485 if (!android::base::ReadFileToString(file_name, &file)) {
486 continue;
487 }
488
489 bool found = false;
490 for (const auto& line : android::base::Split(file, "\n")) {
491 log_time t(log_time::EPOCH);
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700492 char *ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700493 if (!ep || (*ep != ' ')) {
494 continue;
495 }
496 // determine the time precision of the logs (eg: msec or usec)
497 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
498 if (t.tv_nsec % (mod * 10)) {
499 modulo.tv_nsec = mod;
500 break;
501 }
502 }
503 // We filter any times later than current as we may not have the
504 // year stored with each log entry. Also, since it is possible for
505 // entries to be recorded out of order (very rare) we select the
506 // maximum we find just in case.
507 if ((t < now) && (t > retval)) {
508 retval = t;
509 found = true;
510 }
511 }
512 // We count on the basename file to be the definitive end, so stop here.
513 if (!dp->d_name[len] && found) {
514 break;
515 }
516 }
517 if (retval == log_time::EPOCH) {
518 return retval;
519 }
520 // tail_time prints matching or higher, round up by the modulo to prevent
521 // a replay of the last entry we have just checked.
522 retval += modulo;
523 return retval;
524}
525
Traian Schiau59763032015-04-10 15:51:39 +0300526} /* namespace android */
527
528
Joe Onorato6fa09a02010-02-26 10:04:23 -0800529int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530{
Traian Schiau59763032015-04-10 15:51:39 +0300531 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532 int err;
533 int hasSetLogFormat = 0;
534 int clearLog = 0;
535 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800536 unsigned long setLogSize = 0;
537 int getPruneList = 0;
538 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800539 int printStatistics = 0;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800540 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800542 log_device_t* devices = NULL;
543 log_device_t* dev;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800544 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800545 struct logger_list *logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300546 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800547 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700548 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700549 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800551 signal(SIGPIPE, exit);
552
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553 g_logformat = android_log_format_new();
554
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800555 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiau59763032015-04-10 15:51:39 +0300556 show_help(argv[0]);
557 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 }
559
560 for (;;) {
561 int ret;
562
Kristian Monsen562e5132015-06-05 14:10:12 -0700563 int option_index = 0;
564 static const char pid_str[] = "pid";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800565 static const char wrap_str[] = "wrap";
Kristian Monsen562e5132015-06-05 14:10:12 -0700566 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800567 { "binary", no_argument, NULL, 'B' },
568 { "buffer", required_argument, NULL, 'b' },
569 { "buffer_size", optional_argument, NULL, 'g' },
570 { "clear", no_argument, NULL, 'c' },
571 { "dividers", no_argument, NULL, 'D' },
572 { "file", required_argument, NULL, 'f' },
573 { "format", required_argument, NULL, 'v' },
574 { "last", no_argument, NULL, 'L' },
Kristian Monsen562e5132015-06-05 14:10:12 -0700575 { pid_str, required_argument, NULL, 0 },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700576 { "max-count", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800577 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700578 { "regex", required_argument, NULL, 'e' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800579 { "rotate_count", required_argument, NULL, 'n' },
580 { "rotate_kbytes", required_argument, NULL, 'r' },
581 { "statistics", no_argument, NULL, 'S' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800582 // support, but ignore and do not document, the optional argument
583 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700584 { NULL, 0, NULL, 0 }
585 };
586
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700587 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700588 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589
590 if (ret < 0) {
591 break;
592 }
593
Kristian Monsen562e5132015-06-05 14:10:12 -0700594 switch (ret) {
595 case 0:
596 // One of the long options
597 if (long_options[option_index].name == pid_str) {
598 // ToDo: determine runtime PID_MAX?
599 if (!getSizeTArg(optarg, &pid, 1)) {
600 logcat_panic(true, "%s %s out of range\n",
601 long_options[option_index].name, optarg);
602 }
603 break;
604 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800605 if (long_options[option_index].name == wrap_str) {
606 mode |= ANDROID_LOG_WRAP |
607 ANDROID_LOG_RDONLY |
608 ANDROID_LOG_NONBLOCK;
609 // ToDo: implement API that supports setting a wrap timeout
610 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
611 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
612 logcat_panic(true, "%s %s out of range\n",
613 long_options[option_index].name, optarg);
614 }
615 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
616 fprintf(stderr,
617 "WARNING: %s %u seconds, ignoring %zu\n",
618 long_options[option_index].name,
619 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
620 }
621 break;
622 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700623 break;
624
Mark Salyzyn95132e92013-11-22 10:55:48 -0800625 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626 // default to all silent
627 android_log_addFilterRule(g_logformat, "*:s");
628 break;
629
630 case 'c':
631 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800632 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633 break;
634
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800635 case 'L':
636 mode |= ANDROID_LOG_PSTORE;
637 break;
638
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800639 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800640 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800641 break;
642
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800643 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700644 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800645 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800646 /* FALLTHRU */
647 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800648 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700649 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800650 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700651 logcat_panic(false, "-%c \"%s\" not in time format\n",
652 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800653 }
654 if (*cp) {
655 char c = *cp;
656 *cp = '\0';
657 fprintf(stderr,
658 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
659 ret, optarg, c, cp + 1);
660 *cp = c;
661 }
662 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300663 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800664 fprintf(stderr,
665 "WARNING: -%c %s invalid, setting to 1\n",
666 ret, optarg);
667 tail_lines = 1;
668 }
669 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800670 break;
671
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800672 case 'D':
673 printDividers = true;
674 break;
675
Casey Dahlindc42a872016-03-17 16:18:55 -0700676 case 'e':
677 g_regex = new pcrecpp::RE(optarg);
678 break;
679
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700680 case 'm': {
681 char *end = NULL;
682 if (!getSizeTArg(optarg, &g_maxCount)) {
683 logcat_panic(false, "-%c \"%s\" isn't an "
684 "integer greater than zero\n", ret, optarg);
685 }
686 }
687 break;
688
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800690 if (!optarg) {
691 getLogSize = 1;
692 break;
693 }
694 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800695
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800696 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300697 char *cp;
698 if (strtoll(optarg, &cp, 0) > 0) {
699 setLogSize = strtoll(optarg, &cp, 0);
700 } else {
701 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800702 }
703
704 switch(*cp) {
705 case 'g':
706 case 'G':
707 setLogSize *= 1024;
708 /* FALLTHRU */
709 case 'm':
710 case 'M':
711 setLogSize *= 1024;
712 /* FALLTHRU */
713 case 'k':
714 case 'K':
715 setLogSize *= 1024;
716 /* FALLTHRU */
717 case '\0':
718 break;
719
720 default:
721 setLogSize = 0;
722 }
723
724 if (!setLogSize) {
725 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300726 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800727 }
728 }
729 break;
730
731 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800732 if (!optarg) {
733 getPruneList = 1;
734 break;
735 }
736 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800737
738 case 'P':
739 setPruneList = optarg;
740 break;
741
Joe Onorato6fa09a02010-02-26 10:04:23 -0800742 case 'b': {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800743 if (strcmp(optarg, "default") == 0) {
744 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
745 switch (i) {
746 case LOG_ID_SECURITY:
747 case LOG_ID_EVENTS:
748 continue;
749 case LOG_ID_MAIN:
750 case LOG_ID_SYSTEM:
751 case LOG_ID_CRASH:
752 break;
753 default:
754 continue;
755 }
Mark Salyzyn34facab2014-02-06 14:48:50 -0800756
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700757 const char *name = android_log_id_to_name((log_id_t)i);
758 log_id_t log_id = android_name_to_log_id(name);
759
760 if (log_id != (log_id_t)i) {
761 continue;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800762 }
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700763
Mark Salyzyn083b0372015-12-04 10:59:45 -0800764 bool found = false;
765 for (dev = devices; dev; dev = dev->next) {
766 if (!strcmp(optarg, dev->device)) {
767 found = true;
768 break;
769 }
770 if (!dev->next) {
771 break;
772 }
773 }
774 if (found) {
775 break;
776 }
777
778 log_device_t* d = new log_device_t(name, false);
779
780 if (dev) {
781 dev->next = d;
782 dev = d;
783 } else {
784 devices = dev = d;
785 }
786 g_devCount++;
787 }
788 break;
789 }
790
791 if (strcmp(optarg, "all") == 0) {
792 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
793 const char *name = android_log_id_to_name((log_id_t)i);
794 log_id_t log_id = android_name_to_log_id(name);
795
796 if (log_id != (log_id_t)i) {
797 continue;
798 }
799
800 bool found = false;
801 for (dev = devices; dev; dev = dev->next) {
802 if (!strcmp(optarg, dev->device)) {
803 found = true;
804 break;
805 }
806 if (!dev->next) {
807 break;
808 }
809 }
810 if (found) {
811 break;
812 }
813
814 bool binary = !strcmp(name, "events") ||
815 !strcmp(name, "security");
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800816 log_device_t* d = new log_device_t(name, binary);
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700817
818 if (dev) {
819 dev->next = d;
820 dev = d;
821 } else {
822 devices = dev = d;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800823 }
Traian Schiau59763032015-04-10 15:51:39 +0300824 g_devCount++;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800825 }
826 break;
827 }
828
Mark Salyzyn083b0372015-12-04 10:59:45 -0800829 bool binary = !(strcmp(optarg, "events") &&
830 strcmp(optarg, "security"));
Joe Onorato6fa09a02010-02-26 10:04:23 -0800831
832 if (devices) {
833 dev = devices;
834 while (dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800835 if (!strcmp(optarg, dev->device)) {
836 dev = NULL;
837 break;
838 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800839 dev = dev->next;
840 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800841 if (dev) {
842 dev->next = new log_device_t(optarg, binary);
843 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800844 } else {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800845 devices = new log_device_t(optarg, binary);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800846 }
Traian Schiau59763032015-04-10 15:51:39 +0300847 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800848 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849 break;
850
851 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300852 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 break;
854
855 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700856 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700857 tail_time = lastLogTime(optarg);
858 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300860 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800861 break;
862
863 case 'r':
Traian Schiau59763032015-04-10 15:51:39 +0300864 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
865 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866 }
867 break;
868
869 case 'n':
Traian Schiau59763032015-04-10 15:51:39 +0300870 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
871 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800872 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800873 break;
874
875 case 'v':
876 err = setLogFormat (optarg);
877 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300878 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700880 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800881 break;
882
883 case 'Q':
884 /* this is a *hidden* option used to start a version of logcat */
885 /* in an emulated device only. it basically looks for androidboot.logcat= */
886 /* on the kernel command line. If something is found, it extracts a log filter */
887 /* and uses it to run the program. If nothing is found, the program should */
888 /* quit immediately */
889#define KERNEL_OPTION "androidboot.logcat="
890#define CONSOLE_OPTION "androidboot.console="
891 {
892 int fd;
893 char* logcat;
894 char* console;
895 int force_exit = 1;
896 static char cmdline[1024];
897
898 fd = open("/proc/cmdline", O_RDONLY);
899 if (fd >= 0) {
900 int n = read(fd, cmdline, sizeof(cmdline)-1 );
901 if (n < 0) n = 0;
902 cmdline[n] = 0;
903 close(fd);
904 } else {
905 cmdline[0] = 0;
906 }
907
908 logcat = strstr( cmdline, KERNEL_OPTION );
909 console = strstr( cmdline, CONSOLE_OPTION );
910 if (logcat != NULL) {
911 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
912 char* q = strpbrk( p, " \t\n\r" );;
913
914 if (q != NULL)
915 *q = 0;
916
917 forceFilters = p;
918 force_exit = 0;
919 }
920 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300921 if (force_exit) {
922 return EXIT_SUCCESS;
923 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800924
925 /* redirect our output to the emulator console */
926 if (console) {
927 char* p = console + sizeof(CONSOLE_OPTION)-1;
928 char* q = strpbrk( p, " \t\n\r" );
929 char devname[64];
930 int len;
931
932 if (q != NULL) {
933 len = q - p;
934 } else
935 len = strlen(p);
936
937 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
938 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
939 if (len < (int)sizeof(devname)) {
940 fd = open( devname, O_WRONLY );
941 if (fd >= 0) {
942 dup2(fd, 1);
943 dup2(fd, 2);
944 close(fd);
945 }
946 }
947 }
948 }
949 break;
950
Mark Salyzyn34facab2014-02-06 14:48:50 -0800951 case 'S':
952 printStatistics = 1;
953 break;
954
Traian Schiau59763032015-04-10 15:51:39 +0300955 case ':':
956 logcat_panic(true, "Option -%c needs an argument\n", optopt);
957 break;
958
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800959 default:
Traian Schiau59763032015-04-10 15:51:39 +0300960 logcat_panic(true, "Unrecognized Option %c\n", optopt);
961 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800962 }
963 }
964
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700965 if (g_maxCount && got_t) {
Mark Salyzynaa730c12016-03-30 12:38:29 -0700966 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700967 }
968
Joe Onorato6fa09a02010-02-26 10:04:23 -0800969 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800970 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +0300971 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800972 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800973 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +0300974 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800975 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700976 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800977 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +0300978 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700979 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800980 }
981
Traian Schiau59763032015-04-10 15:51:39 +0300982 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
983 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800984 }
985
Traian Schiau59763032015-04-10 15:51:39 +0300986 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800987
988 if (hasSetLogFormat == 0) {
989 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
990
991 if (logFormat != NULL) {
992 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800993 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800994 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 logFormat);
996 }
Mark Salyzyn649fc602014-09-16 09:15:15 -0700997 } else {
998 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 }
1000 }
1001
1002 if (forceFilters) {
1003 err = android_log_addFilterString(g_logformat, forceFilters);
1004 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001005 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001006 }
1007 } else if (argc == optind) {
1008 // Add from environment variable
1009 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1010
1011 if (env_tags_orig != NULL) {
1012 err = android_log_addFilterString(g_logformat, env_tags_orig);
1013
Mark Salyzyn95132e92013-11-22 10:55:48 -08001014 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001015 logcat_panic(true,
1016 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001017 }
1018 }
1019 } else {
1020 // Add from commandline
1021 for (int i = optind ; i < argc ; i++) {
1022 err = android_log_addFilterString(g_logformat, argv[i]);
1023
Mark Salyzyn95132e92013-11-22 10:55:48 -08001024 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001025 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026 }
1027 }
1028 }
1029
Joe Onorato6fa09a02010-02-26 10:04:23 -08001030 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001031 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001032 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001033 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001034 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001035 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001036 const char *openDeviceFail = NULL;
1037 const char *clearFail = NULL;
1038 const char *setSizeFail = NULL;
1039 const char *getSizeFail = NULL;
1040 // We have three orthogonal actions below to clear, set log size and
1041 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001042 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001043 dev->logger_list = logger_list;
1044 dev->logger = android_logger_open(logger_list,
1045 android_name_to_log_id(dev->device));
1046 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001047 openDeviceFail = openDeviceFail ?: dev->device;
1048 dev = dev->next;
1049 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001050 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001051
1052 if (clearLog) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001053 if (android_logger_clear(dev->logger)) {
1054 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001055 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001056 }
1057
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001058 if (setLogSize) {
1059 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1060 setSizeFail = setSizeFail ?: dev->device;
1061 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001062 }
1063
Joe Onorato6fa09a02010-02-26 10:04:23 -08001064 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001065 long size = android_logger_get_log_size(dev->logger);
1066 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001067
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001068 if ((size < 0) || (readable < 0)) {
1069 getSizeFail = getSizeFail ?: dev->device;
1070 } else {
1071 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1072 "max entry is %db, max payload is %db\n", dev->device,
1073 value_of_size(size), multiplier_of_size(size),
1074 value_of_size(readable), multiplier_of_size(readable),
1075 (int) LOGGER_ENTRY_MAX_LEN,
1076 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001077 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001078 }
1079
1080 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001081 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001082 // report any errors in the above loop and exit
1083 if (openDeviceFail) {
1084 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1085 }
1086 if (clearFail) {
1087 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1088 }
1089 if (setSizeFail) {
1090 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1091 }
1092 if (getSizeFail) {
1093 logcat_panic(false, "failed to get the readable '%s' log size",
1094 getSizeFail);
1095 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001096
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001097 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001098 size_t len = strlen(setPruneList);
1099 /*extra 32 bytes are needed by android_logger_set_prune_list */
1100 size_t bLen = len + 32;
1101 char *buf = NULL;
1102 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1103 buf[len] = '\0';
1104 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1105 logcat_panic(false, "failed to set the prune list");
1106 }
1107 free(buf);
1108 } else {
1109 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001110 }
1111 }
1112
Mark Salyzyn1c950472014-04-01 17:19:47 -07001113 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001114 size_t len = 8192;
1115 char *buf;
1116
Mark Salyzyn083b0372015-12-04 10:59:45 -08001117 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001118 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001119 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001120 if (getPruneList) {
1121 android_logger_get_prune_list(logger_list, buf, len);
1122 } else {
1123 android_logger_get_statistics(logger_list, buf, len);
1124 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001125 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001126 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001127 delete [] buf;
1128 buf = NULL;
1129 break;
1130 }
Traian Schiau59763032015-04-10 15:51:39 +03001131 size_t ret = atol(buf) + 1;
1132 if (ret <= len) {
1133 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001134 break;
1135 }
Traian Schiau59763032015-04-10 15:51:39 +03001136 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001137 }
1138
1139 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001140 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001141 }
1142
1143 // remove trailing FF
1144 char *cp = buf + len - 1;
1145 *cp = '\0';
1146 bool truncated = *--cp != '\f';
1147 if (!truncated) {
1148 *cp = '\0';
1149 }
1150
1151 // squash out the byte count
1152 cp = buf;
1153 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001154 while (isdigit(*cp)) {
1155 ++cp;
1156 }
1157 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001158 ++cp;
1159 }
1160 }
1161
1162 printf("%s", cp);
1163 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001164 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001165 }
1166
1167
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001168 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001169 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001170 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001171 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001172 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001173 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001174 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001175 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001176 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177
1178 //LOG_EVENT_INT(10, 12345);
1179 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1180 //LOG_EVENT_STRING(0, "whassup, doc?");
1181
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001182 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001183 log_device_t unexpected("unexpected", false);
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001184
Mark Salyzynaa730c12016-03-30 12:38:29 -07001185 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001186 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001187 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001188 int ret = android_logger_list_read(logger_list, &log_msg);
1189
1190 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001191 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001192 }
1193
1194 if (ret < 0) {
1195 if (ret == -EAGAIN) {
1196 break;
1197 }
1198
1199 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001200 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001201 }
1202 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001203 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001204 }
Traian Schiau59763032015-04-10 15:51:39 +03001205 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001206 }
1207
Mark Salyzyn083b0372015-12-04 10:59:45 -08001208 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001209 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001210 break;
1211 }
1212 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001213 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001214 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001215 d = &unexpected;
1216 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001217 }
1218
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001219 if (dev != d) {
1220 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001221 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001222 }
Traian Schiau59763032015-04-10 15:51:39 +03001223 if (g_printBinary) {
1224 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001225 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001226 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001227 }
1228 }
1229
1230 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001231
Traian Schiau59763032015-04-10 15:51:39 +03001232 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001233}