blob: bb63041284cefd588630adb891f6b9ec912a7341 [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 Salyzynd85f6462016-03-30 09:15:09 -0700283 " --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 Salyzynd85f6462016-03-30 09:15:09 -0700285 " --rotate-count=<count>\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800286 " -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 Salyzynd85f6462016-03-30 09:15:09 -0700306 " --buffer-size\n"
Mark Salyzynf8bff872015-11-30 12:57:56 -0800307 " -G <size> set size of log ring buffer, may suffix with K or M.\n"
Mark Salyzynd85f6462016-03-30 09:15:09 -0700308 " --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' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700569 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800570 { "clear", no_argument, NULL, 'c' },
571 { "dividers", no_argument, NULL, 'D' },
572 { "file", required_argument, NULL, 'f' },
573 { "format", required_argument, NULL, 'v' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700574 // hidden and undocumented reserved alias for --max-count
575 { "head", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800576 { "last", no_argument, NULL, 'L' },
Kristian Monsen562e5132015-06-05 14:10:12 -0700577 { pid_str, required_argument, NULL, 0 },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700578 { "max-count", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800579 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700580 { "regex", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700581 { "rotate-count", required_argument, NULL, 'n' },
582 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800583 { "statistics", no_argument, NULL, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700584 // hidden and undocumented reserved alias for -t
585 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800586 // support, but ignore and do not document, the optional argument
587 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700588 { NULL, 0, NULL, 0 }
589 };
590
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700591 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700592 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593
594 if (ret < 0) {
595 break;
596 }
597
Kristian Monsen562e5132015-06-05 14:10:12 -0700598 switch (ret) {
599 case 0:
600 // One of the long options
601 if (long_options[option_index].name == pid_str) {
602 // ToDo: determine runtime PID_MAX?
603 if (!getSizeTArg(optarg, &pid, 1)) {
604 logcat_panic(true, "%s %s out of range\n",
605 long_options[option_index].name, optarg);
606 }
607 break;
608 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800609 if (long_options[option_index].name == wrap_str) {
610 mode |= ANDROID_LOG_WRAP |
611 ANDROID_LOG_RDONLY |
612 ANDROID_LOG_NONBLOCK;
613 // ToDo: implement API that supports setting a wrap timeout
614 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
615 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
616 logcat_panic(true, "%s %s out of range\n",
617 long_options[option_index].name, optarg);
618 }
619 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
620 fprintf(stderr,
621 "WARNING: %s %u seconds, ignoring %zu\n",
622 long_options[option_index].name,
623 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
624 }
625 break;
626 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700627 break;
628
Mark Salyzyn95132e92013-11-22 10:55:48 -0800629 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630 // default to all silent
631 android_log_addFilterRule(g_logformat, "*:s");
632 break;
633
634 case 'c':
635 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800636 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637 break;
638
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800639 case 'L':
640 mode |= ANDROID_LOG_PSTORE;
641 break;
642
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800643 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800644 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800645 break;
646
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800647 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700648 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800649 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800650 /* FALLTHRU */
651 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800652 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700653 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800654 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700655 logcat_panic(false, "-%c \"%s\" not in time format\n",
656 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800657 }
658 if (*cp) {
659 char c = *cp;
660 *cp = '\0';
661 fprintf(stderr,
662 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
663 ret, optarg, c, cp + 1);
664 *cp = c;
665 }
666 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300667 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800668 fprintf(stderr,
669 "WARNING: -%c %s invalid, setting to 1\n",
670 ret, optarg);
671 tail_lines = 1;
672 }
673 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800674 break;
675
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800676 case 'D':
677 printDividers = true;
678 break;
679
Casey Dahlindc42a872016-03-17 16:18:55 -0700680 case 'e':
681 g_regex = new pcrecpp::RE(optarg);
682 break;
683
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700684 case 'm': {
685 char *end = NULL;
686 if (!getSizeTArg(optarg, &g_maxCount)) {
687 logcat_panic(false, "-%c \"%s\" isn't an "
688 "integer greater than zero\n", ret, optarg);
689 }
690 }
691 break;
692
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800693 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800694 if (!optarg) {
695 getLogSize = 1;
696 break;
697 }
698 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800700 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300701 char *cp;
702 if (strtoll(optarg, &cp, 0) > 0) {
703 setLogSize = strtoll(optarg, &cp, 0);
704 } else {
705 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800706 }
707
708 switch(*cp) {
709 case 'g':
710 case 'G':
711 setLogSize *= 1024;
712 /* FALLTHRU */
713 case 'm':
714 case 'M':
715 setLogSize *= 1024;
716 /* FALLTHRU */
717 case 'k':
718 case 'K':
719 setLogSize *= 1024;
720 /* FALLTHRU */
721 case '\0':
722 break;
723
724 default:
725 setLogSize = 0;
726 }
727
728 if (!setLogSize) {
729 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300730 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800731 }
732 }
733 break;
734
735 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800736 if (!optarg) {
737 getPruneList = 1;
738 break;
739 }
740 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800741
742 case 'P':
743 setPruneList = optarg;
744 break;
745
Joe Onorato6fa09a02010-02-26 10:04:23 -0800746 case 'b': {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800747 if (strcmp(optarg, "default") == 0) {
748 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
749 switch (i) {
750 case LOG_ID_SECURITY:
751 case LOG_ID_EVENTS:
752 continue;
753 case LOG_ID_MAIN:
754 case LOG_ID_SYSTEM:
755 case LOG_ID_CRASH:
756 break;
757 default:
758 continue;
759 }
Mark Salyzyn34facab2014-02-06 14:48:50 -0800760
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700761 const char *name = android_log_id_to_name((log_id_t)i);
762 log_id_t log_id = android_name_to_log_id(name);
763
764 if (log_id != (log_id_t)i) {
765 continue;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800766 }
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700767
Mark Salyzyn083b0372015-12-04 10:59:45 -0800768 bool found = false;
769 for (dev = devices; dev; dev = dev->next) {
770 if (!strcmp(optarg, dev->device)) {
771 found = true;
772 break;
773 }
774 if (!dev->next) {
775 break;
776 }
777 }
778 if (found) {
779 break;
780 }
781
782 log_device_t* d = new log_device_t(name, false);
783
784 if (dev) {
785 dev->next = d;
786 dev = d;
787 } else {
788 devices = dev = d;
789 }
790 g_devCount++;
791 }
792 break;
793 }
794
795 if (strcmp(optarg, "all") == 0) {
796 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
797 const char *name = android_log_id_to_name((log_id_t)i);
798 log_id_t log_id = android_name_to_log_id(name);
799
800 if (log_id != (log_id_t)i) {
801 continue;
802 }
803
804 bool found = false;
805 for (dev = devices; dev; dev = dev->next) {
806 if (!strcmp(optarg, dev->device)) {
807 found = true;
808 break;
809 }
810 if (!dev->next) {
811 break;
812 }
813 }
814 if (found) {
815 break;
816 }
817
818 bool binary = !strcmp(name, "events") ||
819 !strcmp(name, "security");
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800820 log_device_t* d = new log_device_t(name, binary);
Mark Salyzynd0bd1b12014-10-10 15:25:38 -0700821
822 if (dev) {
823 dev->next = d;
824 dev = d;
825 } else {
826 devices = dev = d;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800827 }
Traian Schiau59763032015-04-10 15:51:39 +0300828 g_devCount++;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800829 }
830 break;
831 }
832
Mark Salyzyn083b0372015-12-04 10:59:45 -0800833 bool binary = !(strcmp(optarg, "events") &&
834 strcmp(optarg, "security"));
Joe Onorato6fa09a02010-02-26 10:04:23 -0800835
836 if (devices) {
837 dev = devices;
838 while (dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800839 if (!strcmp(optarg, dev->device)) {
840 dev = NULL;
841 break;
842 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800843 dev = dev->next;
844 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800845 if (dev) {
846 dev->next = new log_device_t(optarg, binary);
847 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800848 } else {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800849 devices = new log_device_t(optarg, binary);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800850 }
Traian Schiau59763032015-04-10 15:51:39 +0300851 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800852 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 break;
854
855 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300856 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 break;
858
859 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700860 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700861 tail_time = lastLogTime(optarg);
862 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300864 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 break;
866
867 case 'r':
Traian Schiau59763032015-04-10 15:51:39 +0300868 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
869 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870 }
871 break;
872
873 case 'n':
Traian Schiau59763032015-04-10 15:51:39 +0300874 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
875 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800876 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877 break;
878
879 case 'v':
880 err = setLogFormat (optarg);
881 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300882 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800883 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700884 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800885 break;
886
887 case 'Q':
888 /* this is a *hidden* option used to start a version of logcat */
889 /* in an emulated device only. it basically looks for androidboot.logcat= */
890 /* on the kernel command line. If something is found, it extracts a log filter */
891 /* and uses it to run the program. If nothing is found, the program should */
892 /* quit immediately */
893#define KERNEL_OPTION "androidboot.logcat="
894#define CONSOLE_OPTION "androidboot.console="
895 {
896 int fd;
897 char* logcat;
898 char* console;
899 int force_exit = 1;
900 static char cmdline[1024];
901
902 fd = open("/proc/cmdline", O_RDONLY);
903 if (fd >= 0) {
904 int n = read(fd, cmdline, sizeof(cmdline)-1 );
905 if (n < 0) n = 0;
906 cmdline[n] = 0;
907 close(fd);
908 } else {
909 cmdline[0] = 0;
910 }
911
912 logcat = strstr( cmdline, KERNEL_OPTION );
913 console = strstr( cmdline, CONSOLE_OPTION );
914 if (logcat != NULL) {
915 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
916 char* q = strpbrk( p, " \t\n\r" );;
917
918 if (q != NULL)
919 *q = 0;
920
921 forceFilters = p;
922 force_exit = 0;
923 }
924 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300925 if (force_exit) {
926 return EXIT_SUCCESS;
927 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800928
929 /* redirect our output to the emulator console */
930 if (console) {
931 char* p = console + sizeof(CONSOLE_OPTION)-1;
932 char* q = strpbrk( p, " \t\n\r" );
933 char devname[64];
934 int len;
935
936 if (q != NULL) {
937 len = q - p;
938 } else
939 len = strlen(p);
940
941 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
942 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
943 if (len < (int)sizeof(devname)) {
944 fd = open( devname, O_WRONLY );
945 if (fd >= 0) {
946 dup2(fd, 1);
947 dup2(fd, 2);
948 close(fd);
949 }
950 }
951 }
952 }
953 break;
954
Mark Salyzyn34facab2014-02-06 14:48:50 -0800955 case 'S':
956 printStatistics = 1;
957 break;
958
Traian Schiau59763032015-04-10 15:51:39 +0300959 case ':':
960 logcat_panic(true, "Option -%c needs an argument\n", optopt);
961 break;
962
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963 default:
Traian Schiau59763032015-04-10 15:51:39 +0300964 logcat_panic(true, "Unrecognized Option %c\n", optopt);
965 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966 }
967 }
968
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700969 if (g_maxCount && got_t) {
Mark Salyzynaa730c12016-03-30 12:38:29 -0700970 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700971 }
972
Joe Onorato6fa09a02010-02-26 10:04:23 -0800973 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800974 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +0300975 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800976 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800977 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +0300978 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800979 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700980 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800981 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +0300982 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700983 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800984 }
985
Traian Schiau59763032015-04-10 15:51:39 +0300986 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
987 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800988 }
989
Traian Schiau59763032015-04-10 15:51:39 +0300990 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800991
992 if (hasSetLogFormat == 0) {
993 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
994
995 if (logFormat != NULL) {
996 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800998 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 logFormat);
1000 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001001 } else {
1002 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003 }
1004 }
1005
1006 if (forceFilters) {
1007 err = android_log_addFilterString(g_logformat, forceFilters);
1008 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001009 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001010 }
1011 } else if (argc == optind) {
1012 // Add from environment variable
1013 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
1014
1015 if (env_tags_orig != NULL) {
1016 err = android_log_addFilterString(g_logformat, env_tags_orig);
1017
Mark Salyzyn95132e92013-11-22 10:55:48 -08001018 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001019 logcat_panic(true,
1020 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001021 }
1022 }
1023 } else {
1024 // Add from commandline
1025 for (int i = optind ; i < argc ; i++) {
1026 err = android_log_addFilterString(g_logformat, argv[i]);
1027
Mark Salyzyn95132e92013-11-22 10:55:48 -08001028 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001029 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030 }
1031 }
1032 }
1033
Joe Onorato6fa09a02010-02-26 10:04:23 -08001034 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001035 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001036 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001037 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001038 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001039 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001040 const char *openDeviceFail = NULL;
1041 const char *clearFail = NULL;
1042 const char *setSizeFail = NULL;
1043 const char *getSizeFail = NULL;
1044 // We have three orthogonal actions below to clear, set log size and
1045 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001046 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001047 dev->logger_list = logger_list;
1048 dev->logger = android_logger_open(logger_list,
1049 android_name_to_log_id(dev->device));
1050 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001051 openDeviceFail = openDeviceFail ?: dev->device;
1052 dev = dev->next;
1053 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001054 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001055
1056 if (clearLog) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001057 if (android_logger_clear(dev->logger)) {
1058 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001059 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001060 }
1061
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001062 if (setLogSize) {
1063 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1064 setSizeFail = setSizeFail ?: dev->device;
1065 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001066 }
1067
Joe Onorato6fa09a02010-02-26 10:04:23 -08001068 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001069 long size = android_logger_get_log_size(dev->logger);
1070 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001071
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001072 if ((size < 0) || (readable < 0)) {
1073 getSizeFail = getSizeFail ?: dev->device;
1074 } else {
1075 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1076 "max entry is %db, max payload is %db\n", dev->device,
1077 value_of_size(size), multiplier_of_size(size),
1078 value_of_size(readable), multiplier_of_size(readable),
1079 (int) LOGGER_ENTRY_MAX_LEN,
1080 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001081 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001082 }
1083
1084 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001085 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001086 // report any errors in the above loop and exit
1087 if (openDeviceFail) {
1088 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1089 }
1090 if (clearFail) {
1091 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1092 }
1093 if (setSizeFail) {
1094 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1095 }
1096 if (getSizeFail) {
1097 logcat_panic(false, "failed to get the readable '%s' log size",
1098 getSizeFail);
1099 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001100
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001101 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001102 size_t len = strlen(setPruneList);
1103 /*extra 32 bytes are needed by android_logger_set_prune_list */
1104 size_t bLen = len + 32;
1105 char *buf = NULL;
1106 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1107 buf[len] = '\0';
1108 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1109 logcat_panic(false, "failed to set the prune list");
1110 }
1111 free(buf);
1112 } else {
1113 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001114 }
1115 }
1116
Mark Salyzyn1c950472014-04-01 17:19:47 -07001117 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001118 size_t len = 8192;
1119 char *buf;
1120
Mark Salyzyn083b0372015-12-04 10:59:45 -08001121 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001122 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001123 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001124 if (getPruneList) {
1125 android_logger_get_prune_list(logger_list, buf, len);
1126 } else {
1127 android_logger_get_statistics(logger_list, buf, len);
1128 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001129 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001130 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001131 delete [] buf;
1132 buf = NULL;
1133 break;
1134 }
Traian Schiau59763032015-04-10 15:51:39 +03001135 size_t ret = atol(buf) + 1;
1136 if (ret <= len) {
1137 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001138 break;
1139 }
Traian Schiau59763032015-04-10 15:51:39 +03001140 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001141 }
1142
1143 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001144 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001145 }
1146
1147 // remove trailing FF
1148 char *cp = buf + len - 1;
1149 *cp = '\0';
1150 bool truncated = *--cp != '\f';
1151 if (!truncated) {
1152 *cp = '\0';
1153 }
1154
1155 // squash out the byte count
1156 cp = buf;
1157 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001158 while (isdigit(*cp)) {
1159 ++cp;
1160 }
1161 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001162 ++cp;
1163 }
1164 }
1165
1166 printf("%s", cp);
1167 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001168 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001169 }
1170
1171
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001172 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001173 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001175 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001176 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001177 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001178 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001179 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001180 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001181
1182 //LOG_EVENT_INT(10, 12345);
1183 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1184 //LOG_EVENT_STRING(0, "whassup, doc?");
1185
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001186 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001187 log_device_t unexpected("unexpected", false);
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001188
Mark Salyzynaa730c12016-03-30 12:38:29 -07001189 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001190 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001191 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001192 int ret = android_logger_list_read(logger_list, &log_msg);
1193
1194 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001195 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001196 }
1197
1198 if (ret < 0) {
1199 if (ret == -EAGAIN) {
1200 break;
1201 }
1202
1203 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001204 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001205 }
1206 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001207 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001208 }
Traian Schiau59763032015-04-10 15:51:39 +03001209 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001210 }
1211
Mark Salyzyn083b0372015-12-04 10:59:45 -08001212 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001213 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001214 break;
1215 }
1216 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001217 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001218 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001219 d = &unexpected;
1220 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001221 }
1222
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001223 if (dev != d) {
1224 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001225 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001226 }
Traian Schiau59763032015-04-10 15:51:39 +03001227 if (g_printBinary) {
1228 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001229 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001230 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001231 }
1232 }
1233
1234 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001235
Traian Schiau59763032015-04-10 15:51:39 +03001236 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001237}