blob: 04efd68e02ecb448c0c8a52c7c0aa57115624a51 [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>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070029#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080030#include <android-base/strings.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070031#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080032#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070033#include <log/event_tag_map.h>
Mark Salyzyn95132e92013-11-22 10:55:48 -080034#include <log/log.h>
Mark Salyzynfa3716b2014-02-14 16:05:05 -080035#include <log/log_read.h>
Colin Cross9227bd32013-07-23 16:59:20 -070036#include <log/logd.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070037#include <log/logger.h>
Colin Cross9227bd32013-07-23 16:59:20 -070038#include <log/logprint.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080039#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080040
Casey Dahlindc42a872016-03-17 16:18:55 -070041#include <pcrecpp.h>
42
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043#define DEFAULT_MAX_ROTATED_LOGS 4
44
45static AndroidLogFormat * g_logformat;
46
47/* logd prefixes records with a length field */
48#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
49
Joe Onorato6fa09a02010-02-26 10:04:23 -080050struct log_device_t {
Mark Salyzyn95132e92013-11-22 10:55:48 -080051 const char* device;
Joe Onorato6fa09a02010-02-26 10:04:23 -080052 bool binary;
Mark Salyzyn95132e92013-11-22 10:55:48 -080053 struct logger *logger;
54 struct logger_list *logger_list;
Joe Onorato6fa09a02010-02-26 10:04:23 -080055 bool printed;
Joe Onorato6fa09a02010-02-26 10:04:23 -080056
Joe Onorato6fa09a02010-02-26 10:04:23 -080057 log_device_t* next;
58
Mark Salyzyn5f6738a2015-02-27 13:41:34 -080059 log_device_t(const char* d, bool b) {
Joe Onorato6fa09a02010-02-26 10:04:23 -080060 device = d;
61 binary = b;
Joe Onorato6fa09a02010-02-26 10:04:23 -080062 next = NULL;
63 printed = false;
Traian Schiau59763032015-04-10 15:51:39 +030064 logger = NULL;
65 logger_list = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -080066 }
Joe Onorato6fa09a02010-02-26 10:04:23 -080067};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080068
69namespace android {
70
71/* Global Variables */
72
Mark Salyzync6d66522016-03-30 12:38:29 -070073static const char * g_outputFileName;
Traian Schiau59763032015-04-10 15:51:39 +030074// 0 means "no log rotation"
Mark Salyzync6d66522016-03-30 12:38:29 -070075static size_t g_logRotateSizeKBytes;
Traian Schiau59763032015-04-10 15:51:39 +030076// 0 means "unbounded"
77static size_t g_maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080078static int g_outFD = -1;
Mark Salyzync6d66522016-03-30 12:38:29 -070079static size_t g_outByteCount;
80static int g_printBinary;
81static int g_devCount; // >1 means multiple
Casey Dahlindc42a872016-03-17 16:18:55 -070082static pcrecpp::RE* g_regex;
Casey Dahlin6ac498d2016-03-17 14:04:52 -070083// 0 means "infinite"
Mark Salyzync6d66522016-03-30 12:38:29 -070084static size_t g_maxCount;
85static size_t g_printCount;
Mark Salyzync9202772016-03-30 09:38:31 -070086static bool g_printItAnyways;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080087
Mark Salyzynaa730c12016-03-30 12:38:29 -070088// if showHelp is set, newline required in fmt statement to transition to usage
Traian Schiau59763032015-04-10 15:51:39 +030089__noreturn static void logcat_panic(bool showHelp, const char *fmt, ...) __printflike(2,3);
90
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080091static int openLogFile (const char *pathname)
92{
Edwin Vane80b221c2012-08-13 12:55:07 -040093 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080094}
95
96static void rotateLogs()
97{
98 int err;
99
100 // Can't rotate logs if we're not outputting to a file
101 if (g_outputFileName == NULL) {
102 return;
103 }
104
105 close(g_outFD);
106
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700107 // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
108 // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
109 int maxRotationCountDigits =
110 (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
111
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800112 for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700113 std::string file1 = android::base::StringPrintf(
114 "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800115
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700116 std::string file0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800117 if (i - 1 == 0) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700118 file0 = android::base::StringPrintf("%s", g_outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800119 } else {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700120 file0 = android::base::StringPrintf(
121 "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800122 }
123
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700124 if ((file0.length() == 0) || (file1.length() == 0)) {
Traian Schiau59763032015-04-10 15:51:39 +0300125 perror("while rotating log files");
126 break;
127 }
128
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700129 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800130
131 if (err < 0 && errno != ENOENT) {
132 perror("while rotating log files");
133 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800134 }
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
Mark Salyzync9202772016-03-30 09:38:31 -0700192 if (android_log_shouldPrintLine(g_logformat, entry.tag, entry.priority)) {
193 bool match = regexOk(entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800194
Mark Salyzync9202772016-03-30 09:38:31 -0700195 g_printCount += match;
196 if (match || g_printItAnyways) {
197 bytesWritten = android_log_printLogLine(g_logformat, g_outFD, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700198
Mark Salyzync9202772016-03-30 09:38:31 -0700199 if (bytesWritten < 0) {
200 logcat_panic(false, "output error");
201 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800202 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800203 }
204
205 g_outByteCount += bytesWritten;
206
Mark Salyzyn95132e92013-11-22 10:55:48 -0800207 if (g_logRotateSizeKBytes > 0
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800208 && (g_outByteCount / 1024) >= g_logRotateSizeKBytes
209 ) {
210 rotateLogs();
211 }
212
213error:
214 //fprintf (stderr, "Error processing record\n");
215 return;
216}
217
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800218static void maybePrintStart(log_device_t* dev, bool printDividers) {
219 if (!dev->printed || printDividers) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800220 if (g_devCount > 1 && !g_printBinary) {
221 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800222 snprintf(buf, sizeof(buf), "--------- %s %s\n",
223 dev->printed ? "switch to" : "beginning of",
Mark Salyzyn95132e92013-11-22 10:55:48 -0800224 dev->device);
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800225 if (write(g_outFD, buf, strlen(buf)) < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300226 logcat_panic(false, "output error");
Joe Onorato6fa09a02010-02-26 10:04:23 -0800227 }
228 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800229 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800230 }
231}
232
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233static void setupOutput()
234{
235
236 if (g_outputFileName == NULL) {
237 g_outFD = STDOUT_FILENO;
238
239 } else {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700240 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
241 fprintf(stderr, "failed to set background scheduling policy\n");
242 }
243
244 struct sched_param param;
245 memset(&param, 0, sizeof(param));
246 if (sched_setscheduler((pid_t) 0, SCHED_BATCH, &param) < 0) {
247 fprintf(stderr, "failed to set to batch scheduler\n");
248 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249
Riley Andrewsaede9892015-06-08 23:36:34 -0700250 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
251 fprintf(stderr, "failed set to priority\n");
252 }
253
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254 g_outFD = openLogFile (g_outputFileName);
255
256 if (g_outFD < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300257 logcat_panic(false, "couldn't open output file");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 }
259
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700260 struct stat statbuf;
Traian Schiau59763032015-04-10 15:51:39 +0300261 if (fstat(g_outFD, &statbuf) == -1) {
262 close(g_outFD);
263 logcat_panic(false, "couldn't get output file stat\n");
264 }
265
266 if ((size_t) statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
267 close(g_outFD);
268 logcat_panic(false, "invalid output file stat\n");
269 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270
271 g_outByteCount = statbuf.st_size;
272 }
273}
274
275static void show_help(const char *cmd)
276{
277 fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
278
279 fprintf(stderr, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700280 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
281 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700282 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
283 " Rotate log every kbytes. Requires -f option\n"
284 " -n <count>, --rotate-count=<count>\n"
285 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700286 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700287 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700288 " brief long process raw tag thread threadtime time\n"
289 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700290 " color epoch monotonic printable uid usec UTC year zone\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700291 " -D, --dividers Print dividers between each log buffer\n"
292 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700293 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700294 " -d Dump the log and then exit (don't block)\n"
295 " -e <expr>, --regex=<expr>\n"
296 " Only print lines where the log message matches <expr>\n"
297 " where <expr> is a regular expression\n"
298 // Leave --head undocumented as alias for -m
299 " -m <count>, --max-count=<count>\n"
300 " Quit after printing <count> lines. This is meant to be\n"
301 " paired with --regex, but will work on its own.\n"
302 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700303 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700304 // Leave --tail undocumented as alias for -t
305 " -t <count> Print only the most recent <count> lines (implies -d)\n"
306 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
307 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
308 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700309 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700310 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700311 " -g, --buffer-size Get the size of the ring buffer.\n"
312 " -G <size>, --buffer-size=<size>\n"
313 " Set size of log ring buffer, may suffix with K or M.\n"
314 " -L, -last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800315 // Leave security (Device Owner only installations) and
316 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700317 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
318 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700319 " Multiple -b parameters or comma separated list of buffers are\n"
320 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700321 " -B, --binary Output the log in binary.\n"
322 " -S, --statistics Output statistics.\n"
323 " -p, --prune Print prune white and ~black list. Service is specified as\n"
324 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700325 " with ~, otherwise weighed for longevity if unadorned. All\n"
326 " other pruning activity is oldest first. Special case ~!\n"
327 " represents an automatic quicker pruning for the noisiest\n"
328 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700329 " -P '<list> ...', --prune='<list> ...'\n"
330 " Set prune white and ~black list, using same format as\n"
331 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800332 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700333 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800334 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
335 " comes first. Improves efficiency of polling by providing\n"
336 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800337
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700338 fprintf(stderr,"\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 " <tag>[:priority]\n\n"
340 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700341 " V Verbose (default for <tag>)\n"
342 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800343 " I Info\n"
344 " W Warn\n"
345 " E Error\n"
346 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700347 " S Silent (suppress all output)\n"
348 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
349 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
350 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
351 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
352 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700353 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354}
355
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356static int setLogFormat(const char * formatString)
357{
358 static AndroidLogPrintFormat format;
359
360 format = android_log_formatFromString(formatString);
361
362 if (format == FORMAT_OFF) {
363 // FORMAT_OFF means invalid string
364 return -1;
365 }
366
Mark Salyzyne1f20042015-05-06 08:40:40 -0700367 return android_log_setPrintFormat(g_logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800368}
369
Mark Salyzyn671e3432014-05-06 07:34:59 -0700370static const char multipliers[][2] = {
371 { "" },
372 { "K" },
373 { "M" },
374 { "G" }
375};
376
377static unsigned long value_of_size(unsigned long value)
378{
379 for (unsigned i = 0;
380 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
381 value /= 1024, ++i) ;
382 return value;
383}
384
385static const char *multiplier_of_size(unsigned long value)
386{
387 unsigned i;
388 for (i = 0;
389 (i < sizeof(multipliers)/sizeof(multipliers[0])) && (value >= 1024);
390 value /= 1024, ++i) ;
391 return multipliers[i];
392}
393
Traian Schiau59763032015-04-10 15:51:39 +0300394/*String to unsigned int, returns -1 if it fails*/
Mark Salyzyn33c26252016-04-12 09:11:46 -0700395static bool getSizeTArg(const char *ptr, size_t *val, size_t min = 0,
Traian Schiau59763032015-04-10 15:51:39 +0300396 size_t max = SIZE_MAX)
397{
Kristian Monsen562e5132015-06-05 14:10:12 -0700398 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300399 return false;
400 }
401
Kristian Monsen562e5132015-06-05 14:10:12 -0700402 char *endp;
403 errno = 0;
404 size_t ret = (size_t)strtoll(ptr, &endp, 0);
405
406 if (endp[0] || errno) {
407 return false;
408 }
409
410 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300411 return false;
412 }
413
414 *val = ret;
415 return true;
416}
417
418static void logcat_panic(bool showHelp, const char *fmt, ...)
419{
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700420 va_list args;
421 va_start(args, fmt);
422 vfprintf(stderr, fmt, args);
423 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300424
425 if (showHelp) {
426 show_help(getprogname());
427 }
428
429 exit(EXIT_FAILURE);
430}
431
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700432static char *parseTime(log_time &t, const char *cp) {
433
434 char *ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
435 if (ep) {
436 return ep;
437 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700438 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
439 if (ep) {
440 return ep;
441 }
442 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700443}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700444
445// Find last logged line in gestalt of all matching existing output files
446static log_time lastLogTime(char *outputFileName) {
447 log_time retval(log_time::EPOCH);
448 if (!outputFileName) {
449 return retval;
450 }
451
Mark Salyzynf3555d92015-05-27 07:39:56 -0700452 std::string directory;
453 char *file = strrchr(outputFileName, '/');
454 if (!file) {
455 directory = ".";
456 file = outputFileName;
457 } else {
458 *file = '\0';
459 directory = outputFileName;
460 *file = '/';
461 ++file;
462 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700463
464 std::unique_ptr<DIR, int(*)(DIR*)>
465 dir(opendir(directory.c_str()), closedir);
466 if (!dir.get()) {
467 return retval;
468 }
469
470 clockid_t clock_type = android_log_clockid();
471 log_time now(clock_type);
472 bool monotonic = clock_type == CLOCK_MONOTONIC;
473
Mark Salyzynf3555d92015-05-27 07:39:56 -0700474 size_t len = strlen(file);
475 log_time modulo(0, NS_PER_SEC);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700476 struct dirent *dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700477
Mark Salyzynf3555d92015-05-27 07:39:56 -0700478 while ((dp = readdir(dir.get())) != NULL) {
479 if ((dp->d_type != DT_REG)
Mark Salyzynb6bee332015-09-08 08:56:32 -0700480 // If we are using realtime, check all files that match the
481 // basename for latest time. If we are using monotonic time
482 // then only check the main file because time cycles on
483 // every reboot.
484 || strncmp(dp->d_name, file, len + monotonic)
Mark Salyzynf3555d92015-05-27 07:39:56 -0700485 || (dp->d_name[len]
486 && ((dp->d_name[len] != '.')
487 || !isdigit(dp->d_name[len+1])))) {
488 continue;
489 }
490
491 std::string file_name = directory;
492 file_name += "/";
493 file_name += dp->d_name;
494 std::string file;
495 if (!android::base::ReadFileToString(file_name, &file)) {
496 continue;
497 }
498
499 bool found = false;
500 for (const auto& line : android::base::Split(file, "\n")) {
501 log_time t(log_time::EPOCH);
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700502 char *ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700503 if (!ep || (*ep != ' ')) {
504 continue;
505 }
506 // determine the time precision of the logs (eg: msec or usec)
507 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
508 if (t.tv_nsec % (mod * 10)) {
509 modulo.tv_nsec = mod;
510 break;
511 }
512 }
513 // We filter any times later than current as we may not have the
514 // year stored with each log entry. Also, since it is possible for
515 // entries to be recorded out of order (very rare) we select the
516 // maximum we find just in case.
517 if ((t < now) && (t > retval)) {
518 retval = t;
519 found = true;
520 }
521 }
522 // We count on the basename file to be the definitive end, so stop here.
523 if (!dp->d_name[len] && found) {
524 break;
525 }
526 }
527 if (retval == log_time::EPOCH) {
528 return retval;
529 }
530 // tail_time prints matching or higher, round up by the modulo to prevent
531 // a replay of the last entry we have just checked.
532 retval += modulo;
533 return retval;
534}
535
Traian Schiau59763032015-04-10 15:51:39 +0300536} /* namespace android */
537
538
Joe Onorato6fa09a02010-02-26 10:04:23 -0800539int main(int argc, char **argv)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540{
Traian Schiau59763032015-04-10 15:51:39 +0300541 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542 int err;
543 int hasSetLogFormat = 0;
544 int clearLog = 0;
545 int getLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800546 unsigned long setLogSize = 0;
547 int getPruneList = 0;
548 char *setPruneList = NULL;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800549 int printStatistics = 0;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800550 int mode = ANDROID_LOG_RDONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551 const char *forceFilters = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800552 log_device_t* devices = NULL;
553 log_device_t* dev;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800554 bool printDividers = false;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800555 struct logger_list *logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300556 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800557 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700558 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700559 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800561 signal(SIGPIPE, exit);
562
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563 g_logformat = android_log_format_new();
564
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
Traian Schiau59763032015-04-10 15:51:39 +0300566 show_help(argv[0]);
567 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568 }
569
570 for (;;) {
571 int ret;
572
Kristian Monsen562e5132015-06-05 14:10:12 -0700573 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700574 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700575 static const char pid_str[] = "pid";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800576 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700577 static const char print_str[] = "print";
Kristian Monsen562e5132015-06-05 14:10:12 -0700578 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800579 { "binary", no_argument, NULL, 'B' },
580 { "buffer", required_argument, NULL, 'b' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700581 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800582 { "clear", no_argument, NULL, 'c' },
583 { "dividers", no_argument, NULL, 'D' },
584 { "file", required_argument, NULL, 'f' },
585 { "format", required_argument, NULL, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700586 // hidden and undocumented reserved alias for --regex
587 { "grep", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700588 // hidden and undocumented reserved alias for --max-count
589 { "head", required_argument, NULL, 'm' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800590 { "last", no_argument, NULL, 'L' },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700591 { "max-count", required_argument, NULL, 'm' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700592 { pid_str, required_argument, NULL, 0 },
Mark Salyzync9202772016-03-30 09:38:31 -0700593 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800594 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700595 { "regex", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700596 { "rotate-count", required_argument, NULL, 'n' },
597 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800598 { "statistics", no_argument, NULL, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700599 // hidden and undocumented reserved alias for -t
600 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800601 // support, but ignore and do not document, the optional argument
602 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700603 { NULL, 0, NULL, 0 }
604 };
605
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700606 ret = getopt_long(argc, argv, ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
Kristian Monsen562e5132015-06-05 14:10:12 -0700607 long_options, &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608
609 if (ret < 0) {
610 break;
611 }
612
Kristian Monsen562e5132015-06-05 14:10:12 -0700613 switch (ret) {
614 case 0:
615 // One of the long options
616 if (long_options[option_index].name == pid_str) {
617 // ToDo: determine runtime PID_MAX?
618 if (!getSizeTArg(optarg, &pid, 1)) {
619 logcat_panic(true, "%s %s out of range\n",
620 long_options[option_index].name, optarg);
621 }
622 break;
623 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800624 if (long_options[option_index].name == wrap_str) {
625 mode |= ANDROID_LOG_WRAP |
626 ANDROID_LOG_RDONLY |
627 ANDROID_LOG_NONBLOCK;
628 // ToDo: implement API that supports setting a wrap timeout
629 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
630 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
631 logcat_panic(true, "%s %s out of range\n",
632 long_options[option_index].name, optarg);
633 }
634 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
635 fprintf(stderr,
636 "WARNING: %s %u seconds, ignoring %zu\n",
637 long_options[option_index].name,
638 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
639 }
640 break;
641 }
Mark Salyzync9202772016-03-30 09:38:31 -0700642 if (long_options[option_index].name == print_str) {
643 g_printItAnyways = true;
644 break;
645 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700646 break;
647
Mark Salyzyn95132e92013-11-22 10:55:48 -0800648 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800649 // default to all silent
650 android_log_addFilterRule(g_logformat, "*:s");
651 break;
652
653 case 'c':
654 clearLog = 1;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800655 mode |= ANDROID_LOG_WRONLY;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656 break;
657
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800658 case 'L':
659 mode |= ANDROID_LOG_PSTORE;
660 break;
661
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800662 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800663 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664 break;
665
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800666 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700667 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800668 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800669 /* FALLTHRU */
670 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800671 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700672 char *cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800673 if (!cp) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700674 logcat_panic(false, "-%c \"%s\" not in time format\n",
675 ret, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800676 }
677 if (*cp) {
678 char c = *cp;
679 *cp = '\0';
680 fprintf(stderr,
681 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
682 ret, optarg, c, cp + 1);
683 *cp = c;
684 }
685 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300686 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800687 fprintf(stderr,
688 "WARNING: -%c %s invalid, setting to 1\n",
689 ret, optarg);
690 tail_lines = 1;
691 }
692 }
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800693 break;
694
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800695 case 'D':
696 printDividers = true;
697 break;
698
Casey Dahlindc42a872016-03-17 16:18:55 -0700699 case 'e':
700 g_regex = new pcrecpp::RE(optarg);
701 break;
702
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700703 case 'm': {
704 char *end = NULL;
705 if (!getSizeTArg(optarg, &g_maxCount)) {
706 logcat_panic(false, "-%c \"%s\" isn't an "
707 "integer greater than zero\n", ret, optarg);
708 }
709 }
710 break;
711
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800712 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800713 if (!optarg) {
714 getLogSize = 1;
715 break;
716 }
717 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800718
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800719 case 'G': {
Traian Schiau59763032015-04-10 15:51:39 +0300720 char *cp;
721 if (strtoll(optarg, &cp, 0) > 0) {
722 setLogSize = strtoll(optarg, &cp, 0);
723 } else {
724 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800725 }
726
727 switch(*cp) {
728 case 'g':
729 case 'G':
730 setLogSize *= 1024;
731 /* FALLTHRU */
732 case 'm':
733 case 'M':
734 setLogSize *= 1024;
735 /* FALLTHRU */
736 case 'k':
737 case 'K':
738 setLogSize *= 1024;
739 /* FALLTHRU */
740 case '\0':
741 break;
742
743 default:
744 setLogSize = 0;
745 }
746
747 if (!setLogSize) {
748 fprintf(stderr, "ERROR: -G <num><multiplier>\n");
Traian Schiau59763032015-04-10 15:51:39 +0300749 return EXIT_FAILURE;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800750 }
751 }
752 break;
753
754 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -0800755 if (!optarg) {
756 getPruneList = 1;
757 break;
758 }
759 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800760
761 case 'P':
762 setPruneList = optarg;
763 break;
764
Joe Onorato6fa09a02010-02-26 10:04:23 -0800765 case 'b': {
Mark Salyzyn45177732016-04-11 14:03:48 -0700766 unsigned idMask = 0;
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700767 while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
768 if (strcmp(optarg, "default") == 0) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700769 idMask |= (1 << LOG_ID_MAIN) |
770 (1 << LOG_ID_SYSTEM) |
771 (1 << LOG_ID_CRASH);
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700772 } else if (strcmp(optarg, "all") == 0) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700773 idMask = (unsigned)-1;
774 } else {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700775 log_id_t log_id = android_name_to_log_id(optarg);
Mark Salyzyn45177732016-04-11 14:03:48 -0700776 const char *name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800777
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700778 if (strcmp(name, optarg) != 0) {
779 logcat_panic(true, "unknown buffer %s\n", optarg);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800780 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700781 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800782 }
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700783 optarg = NULL;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800784 }
785
Mark Salyzyn45177732016-04-11 14:03:48 -0700786 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
787 const char *name = android_log_id_to_name((log_id_t)i);
788 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800789
Mark Salyzyn45177732016-04-11 14:03:48 -0700790 if (log_id != (log_id_t)i) {
791 continue;
792 }
793 if ((idMask & (1 << i)) == 0) {
794 continue;
795 }
Mark Salyzyn083b0372015-12-04 10:59:45 -0800796
Mark Salyzyn45177732016-04-11 14:03:48 -0700797 bool found = false;
798 for (dev = devices; dev; dev = dev->next) {
799 if (!strcmp(name, dev->device)) {
800 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800801 break;
802 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700803 if (!dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -0800804 break;
805 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800806 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700807 if (found) {
808 continue;
809 }
810
811 bool binary = !strcmp(name, "events") ||
812 !strcmp(name, "security");
813 log_device_t* d = new log_device_t(name, binary);
814
Mark Salyzyn083b0372015-12-04 10:59:45 -0800815 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -0700816 dev->next = d;
817 dev = d;
818 } else {
819 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800820 }
Mark Salyzyn45177732016-04-11 14:03:48 -0700821 g_devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800822 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800823 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824 break;
825
826 case 'B':
Traian Schiau59763032015-04-10 15:51:39 +0300827 g_printBinary = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 break;
829
830 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -0700831 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700832 tail_time = lastLogTime(optarg);
833 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800834 // redirect output to a file
Traian Schiau59763032015-04-10 15:51:39 +0300835 g_outputFileName = optarg;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836 break;
837
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700838 case 'r':
839 if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
840 logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841 }
842 break;
843
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700844 case 'n':
845 if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
846 logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848 break;
849
850 case 'v':
851 err = setLogFormat (optarg);
852 if (err < 0) {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700853 logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800854 }
Mark Salyzyne1f20042015-05-06 08:40:40 -0700855 hasSetLogFormat |= err;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856 break;
857
858 case 'Q':
859 /* this is a *hidden* option used to start a version of logcat */
860 /* in an emulated device only. it basically looks for androidboot.logcat= */
861 /* on the kernel command line. If something is found, it extracts a log filter */
862 /* and uses it to run the program. If nothing is found, the program should */
863 /* quit immediately */
864#define KERNEL_OPTION "androidboot.logcat="
865#define CONSOLE_OPTION "androidboot.console="
866 {
867 int fd;
868 char* logcat;
869 char* console;
870 int force_exit = 1;
871 static char cmdline[1024];
872
873 fd = open("/proc/cmdline", O_RDONLY);
874 if (fd >= 0) {
875 int n = read(fd, cmdline, sizeof(cmdline)-1 );
876 if (n < 0) n = 0;
877 cmdline[n] = 0;
878 close(fd);
879 } else {
880 cmdline[0] = 0;
881 }
882
883 logcat = strstr( cmdline, KERNEL_OPTION );
884 console = strstr( cmdline, CONSOLE_OPTION );
885 if (logcat != NULL) {
886 char* p = logcat + sizeof(KERNEL_OPTION)-1;;
887 char* q = strpbrk( p, " \t\n\r" );;
888
889 if (q != NULL)
890 *q = 0;
891
892 forceFilters = p;
893 force_exit = 0;
894 }
895 /* if nothing found or invalid filters, exit quietly */
Traian Schiau59763032015-04-10 15:51:39 +0300896 if (force_exit) {
897 return EXIT_SUCCESS;
898 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800899
900 /* redirect our output to the emulator console */
901 if (console) {
902 char* p = console + sizeof(CONSOLE_OPTION)-1;
903 char* q = strpbrk( p, " \t\n\r" );
904 char devname[64];
905 int len;
906
907 if (q != NULL) {
908 len = q - p;
909 } else
910 len = strlen(p);
911
912 len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
913 fprintf(stderr, "logcat using %s (%d)\n", devname, len);
914 if (len < (int)sizeof(devname)) {
915 fd = open( devname, O_WRONLY );
916 if (fd >= 0) {
917 dup2(fd, 1);
918 dup2(fd, 2);
919 close(fd);
920 }
921 }
922 }
923 }
924 break;
925
Mark Salyzyn34facab2014-02-06 14:48:50 -0800926 case 'S':
927 printStatistics = 1;
928 break;
929
Traian Schiau59763032015-04-10 15:51:39 +0300930 case ':':
931 logcat_panic(true, "Option -%c needs an argument\n", optopt);
932 break;
933
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800934 default:
Traian Schiau59763032015-04-10 15:51:39 +0300935 logcat_panic(true, "Unrecognized Option %c\n", optopt);
936 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937 }
938 }
939
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700940 if (g_maxCount && got_t) {
Mark Salyzynaa730c12016-03-30 12:38:29 -0700941 logcat_panic(true, "Cannot use -m (--max-count) and -t together\n");
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700942 }
Mark Salyzync9202772016-03-30 09:38:31 -0700943 if (g_printItAnyways && (!g_regex || !g_maxCount)) {
944 // One day it would be nice if --print -v color and --regex <expr>
945 // could play with each other and show regex highlighted content.
946 fprintf(stderr, "WARNING: "
947 "--print ignored, to be used in combination with\n"
948 " "
949 "--regex <expr> and --max-count <N>\n");
950 g_printItAnyways = false;
951 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700952
Joe Onorato6fa09a02010-02-26 10:04:23 -0800953 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800954 dev = devices = new log_device_t("main", false);
Traian Schiau59763032015-04-10 15:51:39 +0300955 g_devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -0800956 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800957 dev = dev->next = new log_device_t("system", false);
Traian Schiau59763032015-04-10 15:51:39 +0300958 g_devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800959 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700960 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800961 dev = dev->next = new log_device_t("crash", false);
Traian Schiau59763032015-04-10 15:51:39 +0300962 g_devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -0700963 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800964 }
965
Traian Schiau59763032015-04-10 15:51:39 +0300966 if (g_logRotateSizeKBytes != 0 && g_outputFileName == NULL) {
967 logcat_panic(true, "-r requires -f as well\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800968 }
969
Traian Schiau59763032015-04-10 15:51:39 +0300970 setupOutput();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800971
972 if (hasSetLogFormat == 0) {
973 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
974
975 if (logFormat != NULL) {
976 err = setLogFormat(logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800977 if (err < 0) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800978 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800979 logFormat);
980 }
Mark Salyzyn649fc602014-09-16 09:15:15 -0700981 } else {
982 setLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800983 }
984 }
985
986 if (forceFilters) {
987 err = android_log_addFilterString(g_logformat, forceFilters);
988 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300989 logcat_panic(false, "Invalid filter expression in logcat args\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990 }
991 } else if (argc == optind) {
992 // Add from environment variable
993 char *env_tags_orig = getenv("ANDROID_LOG_TAGS");
994
995 if (env_tags_orig != NULL) {
996 err = android_log_addFilterString(g_logformat, env_tags_orig);
997
Mark Salyzyn95132e92013-11-22 10:55:48 -0800998 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +0300999 logcat_panic(true,
1000 "Invalid filter expression in ANDROID_LOG_TAGS\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001001 }
1002 }
1003 } else {
1004 // Add from commandline
1005 for (int i = optind ; i < argc ; i++) {
1006 err = android_log_addFilterString(g_logformat, argv[i]);
1007
Mark Salyzyn95132e92013-11-22 10:55:48 -08001008 if (err < 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001009 logcat_panic(true, "Invalid filter expression '%s'\n", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001010 }
1011 }
1012 }
1013
Joe Onorato6fa09a02010-02-26 10:04:23 -08001014 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001015 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001016 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001017 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001018 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001019 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001020 const char *openDeviceFail = NULL;
1021 const char *clearFail = NULL;
1022 const char *setSizeFail = NULL;
1023 const char *getSizeFail = NULL;
1024 // We have three orthogonal actions below to clear, set log size and
1025 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001026 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001027 dev->logger_list = logger_list;
1028 dev->logger = android_logger_open(logger_list,
1029 android_name_to_log_id(dev->device));
1030 if (!dev->logger) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001031 openDeviceFail = openDeviceFail ?: dev->device;
1032 dev = dev->next;
1033 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001034 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001035
1036 if (clearLog) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001037 if (g_outputFileName) {
1038 int maxRotationCountDigits =
1039 (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
1040
1041 for (int i = g_maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001042 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001043
1044 if (i == 0) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001045 file = android::base::StringPrintf("%s", g_outputFileName);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001046 } else {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001047 file = android::base::StringPrintf("%s.%.*d",
1048 g_outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001049 }
1050
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001051 if (file.length() == 0) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001052 perror("while clearing log files");
1053 clearFail = clearFail ?: dev->device;
1054 break;
1055 }
1056
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001057 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001058
1059 if (err < 0 && errno != ENOENT && clearFail == NULL) {
1060 perror("while clearing log files");
1061 clearFail = dev->device;
1062 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001063 }
1064 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001065 clearFail = clearFail ?: dev->device;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001066 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001067 }
1068
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001069 if (setLogSize) {
1070 if (android_logger_set_log_size(dev->logger, setLogSize)) {
1071 setSizeFail = setSizeFail ?: dev->device;
1072 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001073 }
1074
Joe Onorato6fa09a02010-02-26 10:04:23 -08001075 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001076 long size = android_logger_get_log_size(dev->logger);
1077 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001078
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001079 if ((size < 0) || (readable < 0)) {
1080 getSizeFail = getSizeFail ?: dev->device;
1081 } else {
1082 printf("%s: ring buffer is %ld%sb (%ld%sb consumed), "
1083 "max entry is %db, max payload is %db\n", dev->device,
1084 value_of_size(size), multiplier_of_size(size),
1085 value_of_size(readable), multiplier_of_size(readable),
1086 (int) LOGGER_ENTRY_MAX_LEN,
1087 (int) LOGGER_ENTRY_MAX_PAYLOAD);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001088 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001089 }
1090
1091 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001092 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001093 // report any errors in the above loop and exit
1094 if (openDeviceFail) {
1095 logcat_panic(false, "Unable to open log device '%s'\n", openDeviceFail);
1096 }
1097 if (clearFail) {
1098 logcat_panic(false, "failed to clear the '%s' log\n", clearFail);
1099 }
1100 if (setSizeFail) {
1101 logcat_panic(false, "failed to set the '%s' log size\n", setSizeFail);
1102 }
1103 if (getSizeFail) {
1104 logcat_panic(false, "failed to get the readable '%s' log size",
1105 getSizeFail);
1106 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001107
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001108 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001109 size_t len = strlen(setPruneList);
1110 /*extra 32 bytes are needed by android_logger_set_prune_list */
1111 size_t bLen = len + 32;
1112 char *buf = NULL;
1113 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1114 buf[len] = '\0';
1115 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
1116 logcat_panic(false, "failed to set the prune list");
1117 }
1118 free(buf);
1119 } else {
1120 logcat_panic(false, "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001121 }
1122 }
1123
Mark Salyzyn1c950472014-04-01 17:19:47 -07001124 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001125 size_t len = 8192;
1126 char *buf;
1127
Mark Salyzyn083b0372015-12-04 10:59:45 -08001128 for (int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001129 (retry >= 0) && ((buf = new char [len]));
Traian Schiau59763032015-04-10 15:51:39 +03001130 delete [] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001131 if (getPruneList) {
1132 android_logger_get_prune_list(logger_list, buf, len);
1133 } else {
1134 android_logger_get_statistics(logger_list, buf, len);
1135 }
Mark Salyzyn34facab2014-02-06 14:48:50 -08001136 buf[len-1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001137 if (atol(buf) < 3) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001138 delete [] buf;
1139 buf = NULL;
1140 break;
1141 }
Traian Schiau59763032015-04-10 15:51:39 +03001142 size_t ret = atol(buf) + 1;
1143 if (ret <= len) {
1144 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001145 break;
1146 }
Traian Schiau59763032015-04-10 15:51:39 +03001147 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001148 }
1149
1150 if (!buf) {
Traian Schiau59763032015-04-10 15:51:39 +03001151 logcat_panic(false, "failed to read data");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001152 }
1153
1154 // remove trailing FF
1155 char *cp = buf + len - 1;
1156 *cp = '\0';
1157 bool truncated = *--cp != '\f';
1158 if (!truncated) {
1159 *cp = '\0';
1160 }
1161
1162 // squash out the byte count
1163 cp = buf;
1164 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001165 while (isdigit(*cp)) {
1166 ++cp;
1167 }
1168 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001169 ++cp;
1170 }
1171 }
1172
1173 printf("%s", cp);
1174 delete [] buf;
Traian Schiau59763032015-04-10 15:51:39 +03001175 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001176 }
1177
1178
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001179 if (getLogSize) {
Traian Schiau59763032015-04-10 15:51:39 +03001180 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001181 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001182 if (setLogSize || setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001183 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001184 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001185 if (clearLog) {
Traian Schiau59763032015-04-10 15:51:39 +03001186 return EXIT_SUCCESS;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001187 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001188
1189 //LOG_EVENT_INT(10, 12345);
1190 //LOG_EVENT_LONG(11, 0x1122334455667788LL);
1191 //LOG_EVENT_STRING(0, "whassup, doc?");
1192
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001193 dev = NULL;
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001194 log_device_t unexpected("unexpected", false);
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001195
Mark Salyzynaa730c12016-03-30 12:38:29 -07001196 while (!g_maxCount || (g_printCount < g_maxCount)) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001197 struct log_msg log_msg;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001198 log_device_t* d;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001199 int ret = android_logger_list_read(logger_list, &log_msg);
1200
1201 if (ret == 0) {
Traian Schiau59763032015-04-10 15:51:39 +03001202 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001203 }
1204
1205 if (ret < 0) {
1206 if (ret == -EAGAIN) {
1207 break;
1208 }
1209
1210 if (ret == -EIO) {
Traian Schiau59763032015-04-10 15:51:39 +03001211 logcat_panic(false, "read: unexpected EOF!\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001212 }
1213 if (ret == -EINVAL) {
Traian Schiau59763032015-04-10 15:51:39 +03001214 logcat_panic(false, "read: unexpected length.\n");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001215 }
Traian Schiau59763032015-04-10 15:51:39 +03001216 logcat_panic(false, "logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001217 }
1218
Mark Salyzyn083b0372015-12-04 10:59:45 -08001219 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001220 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001221 break;
1222 }
1223 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001224 if (!d) {
Traian Schiau59763032015-04-10 15:51:39 +03001225 g_devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001226 d = &unexpected;
1227 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001228 }
1229
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001230 if (dev != d) {
1231 dev = d;
Traian Schiau59763032015-04-10 15:51:39 +03001232 maybePrintStart(dev, printDividers);
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001233 }
Traian Schiau59763032015-04-10 15:51:39 +03001234 if (g_printBinary) {
1235 printBinary(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001236 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001237 processBuffer(dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001238 }
1239 }
1240
1241 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001242
Traian Schiau59763032015-04-10 15:51:39 +03001243 return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001244}