blob: 7f852d4fb44fc6b7068906c0ea1c488a57edab9c [file] [log] [blame]
Mark Salyzyn5f606602017-02-10 13:09:07 -08001/*
Mark Salyzync0cf90d2017-02-10 13:09:07 -08002 * Copyright (C) 2006-2017 The Android Open Source Project
Mark Salyzyn5f606602017-02-10 13:09:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080016
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070017#include <arpa/inet.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080018#include <assert.h>
19#include <ctype.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070020#include <dirent.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080021#include <errno.h>
22#include <fcntl.h>
Kristian Monsen562e5132015-06-05 14:10:12 -070023#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070024#include <math.h>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080025#include <pthread.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070026#include <sched.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070027#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080028#include <stdio.h>
29#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080030#include <string.h>
Traian Schiau59763032015-04-10 15:51:39 +030031#include <sys/cdefs.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070032#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080033#include <sys/socket.h>
34#include <sys/stat.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070035#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070036#include <time.h>
37#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080038
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080039#include <atomic>
Mark Salyzynf3555d92015-05-27 07:39:56 -070040#include <memory>
41#include <string>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080042#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070043
Elliott Hughes4f713192015-12-04 22:00:26 -080044#include <android-base/file.h>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070045#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080046#include <android-base/strings.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070047#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080048#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070049#include <log/event_tag_map.h>
Mark Salyzync0cf90d2017-02-10 13:09:07 -080050#include <log/logcat.h>
Colin Cross9227bd32013-07-23 16:59:20 -070051#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070052#include <private/android_logger.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080053#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Casey Dahlindc42a872016-03-17 16:18:55 -070055#include <pcrecpp.h>
56
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057#define DEFAULT_MAX_ROTATED_LOGS 4
58
Mark Salyzync0cf90d2017-02-10 13:09:07 -080059struct android_logcat_context_internal {
60 // status
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080061 volatile std::atomic_int retval; // valid if thread_stopped set
62 // Arguments passed in, or copies and storage thereof if a thread.
Mark Salyzync0cf90d2017-02-10 13:09:07 -080063 int argc;
64 char* const* argv;
65 char* const* envp;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080066 std::vector<std::string> args;
67 std::vector<const char*> argv_hold;
68 std::vector<std::string> envs;
69 std::vector<const char*> envp_hold;
Mark Salyzync0cf90d2017-02-10 13:09:07 -080070 int output_fd;
71 int error_fd;
72
73 // library
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080074 int fds[2]; // From popen call
75 FILE* output; // everything writes to fileno(output), buffer unused
76 FILE* error; // unless error == output.
77 pthread_t thr;
78 volatile std::atomic_bool stop; // quick exit flag
79 volatile std::atomic_bool thread_stopped;
Mark Salyzync0cf90d2017-02-10 13:09:07 -080080 bool stderr_null; // shell "2>/dev/null"
81 bool stderr_stdout; // shell "2>&1"
82
83 // global variables
84 AndroidLogFormat* logformat;
85 const char* outputFileName;
86 // 0 means "no log rotation"
87 size_t logRotateSizeKBytes;
88 // 0 means "unbounded"
89 size_t maxRotatedLogs;
90 size_t outByteCount;
91 int printBinary;
92 int devCount; // >1 means multiple
93 pcrecpp::RE* regex;
94 // 0 means "infinite"
95 size_t maxCount;
96 size_t printCount;
97 bool printItAnyways;
98 bool debug;
99
100 // static variables
101 bool hasOpenedEventTagMap;
102 EventTagMap* eventTagMap;
103};
104
105// Creates a context associated with this logcat instance
106android_logcat_context create_android_logcat() {
107 android_logcat_context_internal* context;
108
109 context = (android_logcat_context_internal*)calloc(
110 1, sizeof(android_logcat_context_internal));
111 if (!context) return NULL;
112
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800113 context->fds[0] = -1;
114 context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800115 context->output_fd = -1;
116 context->error_fd = -1;
117 context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
118
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800119 context->argv_hold.clear();
120 context->args.clear();
121 context->envp_hold.clear();
122 context->envs.clear();
123
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800124 return (android_logcat_context)context;
125}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126
Mark Salyzyn5f606602017-02-10 13:09:07 -0800127// logd prefixes records with a length field
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
129
Joe Onorato6fa09a02010-02-26 10:04:23 -0800130struct log_device_t {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800131 const char* device;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800132 bool binary;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800133 struct logger* logger;
134 struct logger_list* logger_list;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800135 bool printed;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800136
Joe Onorato6fa09a02010-02-26 10:04:23 -0800137 log_device_t* next;
138
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800139 log_device_t(const char* d, bool b) {
Joe Onorato6fa09a02010-02-26 10:04:23 -0800140 device = d;
141 binary = b;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800142 next = NULL;
143 printed = false;
Traian Schiau59763032015-04-10 15:51:39 +0300144 logger = NULL;
145 logger_list = NULL;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800146 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800147};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
149namespace android {
150
Mark Salyzyn5f606602017-02-10 13:09:07 -0800151enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700152
Mark Salyzynaa730c12016-03-30 12:38:29 -0700153// if showHelp is set, newline required in fmt statement to transition to usage
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800154static void logcat_panic(android_logcat_context_internal* context,
155 enum helpType showHelp, const char* fmt, ...)
156 __printflike(3, 4);
Traian Schiau59763032015-04-10 15:51:39 +0300157
Mark Salyzyn5f606602017-02-10 13:09:07 -0800158static int openLogFile(const char* pathname) {
Edwin Vane80b221c2012-08-13 12:55:07 -0400159 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160}
161
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800162static void close_output(android_logcat_context_internal* context) {
163 // split output_from_error
164 if (context->error == context->output) {
165 context->output = NULL;
166 context->output_fd = -1;
167 }
168 if (context->error && (context->output_fd == fileno(context->error))) {
169 context->output_fd = -1;
170 }
171 if (context->output_fd == context->error_fd) {
172 context->output_fd = -1;
173 }
174 // close output channel
175 if (context->output) {
176 if (context->output != stdout) {
177 if (context->output_fd == fileno(context->output)) {
178 context->output_fd = -1;
179 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800180 if (context->fds[1] == fileno(context->output)) {
181 context->fds[1] = -1;
182 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800183 fclose(context->output);
184 }
185 context->output = NULL;
186 }
187 if (context->output_fd >= 0) {
188 if (context->output_fd != fileno(stdout)) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800189 if (context->fds[1] == context->output_fd) {
190 context->fds[1] = -1;
191 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800192 close(context->output_fd);
193 }
194 context->output_fd = -1;
195 }
196}
197
198static void close_error(android_logcat_context_internal* context) {
199 // split error_from_output
200 if (context->output == context->error) {
201 context->error = NULL;
202 context->error_fd = -1;
203 }
204 if (context->output && (context->error_fd == fileno(context->output))) {
205 context->error_fd = -1;
206 }
207 if (context->error_fd == context->output_fd) {
208 context->error_fd = -1;
209 }
210 // close error channel
211 if (context->error) {
212 if ((context->error != stderr) && (context->error != stdout)) {
213 if (context->error_fd == fileno(context->error)) {
214 context->error_fd = -1;
215 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800216 if (context->fds[1] == fileno(context->error)) {
217 context->fds[1] = -1;
218 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800219 fclose(context->error);
220 }
221 context->error = NULL;
222 }
223 if (context->error_fd >= 0) {
224 if ((context->error_fd != fileno(stdout)) &&
225 (context->error_fd != fileno(stderr))) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800226 if (context->fds[1] == context->error_fd) {
227 context->fds[1] = -1;
228 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800229 close(context->error_fd);
230 }
231 context->error_fd = -1;
232 }
233}
234
235static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800236 int err;
237
238 // Can't rotate logs if we're not outputting to a file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800239 if (context->outputFileName == NULL) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240 return;
241 }
242
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800243 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800244
Mark Salyzyn5f606602017-02-10 13:09:07 -0800245 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800246 // maxRotatedLogs in decimal. eg:
247 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800248 // -> log10(30) == 1.477
249 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700250 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800251 (context->maxRotatedLogs > 0)
252 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
253 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700254
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800255 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700256 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800257 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700259 std::string file0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800260 if (i - 1 == 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800261 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800263 file0 =
264 android::base::StringPrintf("%s.%.*d", context->outputFileName,
265 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800266 }
267
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700268 if ((file0.length() == 0) || (file1.length() == 0)) {
Traian Schiau59763032015-04-10 15:51:39 +0300269 perror("while rotating log files");
270 break;
271 }
272
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700273 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274
275 if (err < 0 && errno != ENOENT) {
276 perror("while rotating log files");
277 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800278 }
279
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800280 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800282 if (context->output_fd < 0) {
283 logcat_panic(context, HELP_FALSE, "couldn't open output file");
284 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800286 context->output = fdopen(context->output_fd, "web");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800288 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800289}
290
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800291void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800292 size_t size = buf->len();
293
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800294 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295}
296
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800297static bool regexOk(android_logcat_context_internal* context,
298 const AndroidLogEntry& entry) {
299 if (!context->regex) {
Casey Dahlindc42a872016-03-17 16:18:55 -0700300 return true;
301 }
302
Casey Dahlindc42a872016-03-17 16:18:55 -0700303 std::string messageString(entry.message, entry.messageLen);
304
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800305 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700306}
307
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800308static void processBuffer(android_logcat_context_internal* context,
309 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700310 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800311 int err;
312 AndroidLogEntry entry;
313 char binaryMsgBuf[1024];
314
Joe Onorato6fa09a02010-02-26 10:04:23 -0800315 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800316 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
317 context->eventTagMap = android_openEventTagMap(NULL);
318 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800319 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800320 err = android_log_processBinaryLogBuffer(
321 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
322 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800323 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800324 // entry.priority, entry.messageLen, entry.message);
325 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800326 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800327 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800328 if ((err < 0) && !context->debug) {
329 return;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800330 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800331
Mark Salyzyn5f606602017-02-10 13:09:07 -0800332 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800333 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800334 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800335 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800336
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800337 context->printCount += match;
338 if (match || context->printItAnyways) {
339 bytesWritten = android_log_printLogLine(context->logformat,
340 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700341
Mark Salyzync9202772016-03-30 09:38:31 -0700342 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800343 logcat_panic(context, HELP_FALSE, "output error");
344 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700345 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800346 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800347 }
348
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800349 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800351 if (context->logRotateSizeKBytes > 0 &&
352 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
353 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355}
356
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800357static void maybePrintStart(android_logcat_context_internal* context,
358 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800359 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800360 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800361 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800362 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800363 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800364 if (write(context->output_fd, buf, strlen(buf)) < 0) {
365 logcat_panic(context, HELP_FALSE, "output error");
366 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800367 }
368 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800369 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800370 }
371}
372
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800373static void setupOutputAndSchedulingPolicy(
374 android_logcat_context_internal* context, bool blocking) {
375 if (context->outputFileName == NULL) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376
Mark Salyzynad5e4112016-08-04 07:53:52 -0700377 if (blocking) {
378 // Lower priority and set to batch scheduling if we are saving
379 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800380 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
381 fprintf(context->error,
382 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700383 }
384
385 struct sched_param param;
386 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800387 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700388 fprintf(stderr, "failed to set to batch scheduler\n");
389 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800390
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800391 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
392 context->error) {
393 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700394 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800395 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700396
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800397 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700398
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800399 context->output_fd = openLogFile(context->outputFileName);
400
401 if (context->output_fd < 0) {
402 logcat_panic(context, HELP_FALSE, "couldn't open output file");
403 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700404 }
405
406 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800407 if (fstat(context->output_fd, &statbuf) == -1) {
408 close_output(context);
409 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
410 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700411 }
412
Mark Salyzyn5f606602017-02-10 13:09:07 -0800413 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800414 close_output(context);
415 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
416 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700417 }
418
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800419 context->output = fdopen(context->output_fd, "web");
420
421 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422}
423
Mark Salyzyn5f606602017-02-10 13:09:07 -0800424// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800425static void show_help(android_logcat_context_internal* context) {
426 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800428 const char* cmd = strrchr(context->argv[0], '/');
429 cmd = cmd ? cmd + 1 : context->argv[0];
430
431 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
432
433 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700434 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
435 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700436 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
437 " Rotate log every kbytes. Requires -f option\n"
438 " -n <count>, --rotate-count=<count>\n"
439 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700440 " --id=<id> If the signature id for logging to file changes, then clear\n"
441 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700442 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700443 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700444 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700445 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700446 " color descriptive epoch monotonic printable uid\n"
447 " usec UTC year zone\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800448 // private and undocumented nsec, no signal, too much noise
449 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700450 " -D, --dividers Print dividers between each log buffer\n"
451 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700452 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700453 " -d Dump the log and then exit (don't block)\n"
454 " -e <expr>, --regex=<expr>\n"
455 " Only print lines where the log message matches <expr>\n"
456 " where <expr> is a regular expression\n"
457 // Leave --head undocumented as alias for -m
458 " -m <count>, --max-count=<count>\n"
459 " Quit after printing <count> lines. This is meant to be\n"
460 " paired with --regex, but will work on its own.\n"
461 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700462 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700463 // Leave --tail undocumented as alias for -t
464 " -t <count> Print only the most recent <count> lines (implies -d)\n"
465 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
466 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
467 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700468 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700469 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700470 " -g, --buffer-size Get the size of the ring buffer.\n"
471 " -G <size>, --buffer-size=<size>\n"
472 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100473 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800474 // Leave security (Device Owner only installations) and
475 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700476 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
477 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700478 " Multiple -b parameters or comma separated list of buffers are\n"
479 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700480 " -B, --binary Output the log in binary.\n"
481 " -S, --statistics Output statistics.\n"
482 " -p, --prune Print prune white and ~black list. Service is specified as\n"
483 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700484 " with ~, otherwise weighed for longevity if unadorned. All\n"
485 " other pruning activity is oldest first. Special case ~!\n"
486 " represents an automatic quicker pruning for the noisiest\n"
487 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700488 " -P '<list> ...', --prune='<list> ...'\n"
489 " Set prune white and ~black list, using same format as\n"
490 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800491 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700492 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800493 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
494 " comes first. Improves efficiency of polling by providing\n"
495 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800497 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498 " <tag>[:priority]\n\n"
499 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700500 " V Verbose (default for <tag>)\n"
501 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502 " I Info\n"
503 " W Warn\n"
504 " E Error\n"
505 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700506 " S Silent (suppress all output)\n"
507 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
508 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
509 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
510 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
511 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700512 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800513}
514
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800515static void show_format_help(android_logcat_context_internal* context) {
516 if (!context->error) return;
517 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700518 "-v <format>, --format=<format> options:\n"
519 " Sets log print format verb and adverbs, where <format> is:\n"
520 " brief long process raw tag thread threadtime time\n"
521 " and individually flagged modifying adverbs can be added:\n"
522 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
523 "\nSingle format verbs:\n"
524 " brief — Display priority/tag and PID of the process issuing the message.\n"
525 " long — Display all metadata fields, separate messages with blank lines.\n"
526 " process — Display PID only.\n"
527 " raw — Display the raw log message, with no other metadata fields.\n"
528 " tag — Display the priority/tag only.\n"
529 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
530 " and TID of the thread issuing the message. (the default format).\n"
531 " time — Display the date, invocation time, priority/tag, and PID of the\n"
532 " process issuing the message.\n"
533 "\nAdverb modifiers can be used in combination:\n"
534 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
535 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
536 " descriptive — events logs only, descriptions from event-log-tags database.\n"
537 " epoch — Display time as seconds since Jan 1 1970.\n"
538 " monotonic — Display time as cpu seconds since last boot.\n"
539 " printable — Ensure that any binary logging content is escaped.\n"
540 " uid — If permitted, display the UID or Android ID of logged process.\n"
541 " usec — Display time down the microsecond precision.\n"
542 " UTC — Display time as UTC.\n"
543 " year — Add the year to the displayed time.\n"
544 " zone — Add the local timezone to the displayed time.\n"
545 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
546 );
547}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800548// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700549
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800550static int setLogFormat(android_logcat_context_internal* context,
551 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800552 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553
554 format = android_log_formatFromString(formatString);
555
556 if (format == FORMAT_OFF) {
557 // FORMAT_OFF means invalid string
558 return -1;
559 }
560
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800561 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562}
563
Mark Salyzyn5f606602017-02-10 13:09:07 -0800564static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700565
Mark Salyzyn5f606602017-02-10 13:09:07 -0800566static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700567 for (unsigned i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800568 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
569 value /= 1024, ++i)
570 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700571 return value;
572}
573
Mark Salyzyn5f606602017-02-10 13:09:07 -0800574static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700575 unsigned i;
576 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800577 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
578 value /= 1024, ++i)
579 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700580 return multipliers[i];
581}
582
Mark Salyzyn5f606602017-02-10 13:09:07 -0800583// String to unsigned int, returns -1 if it fails
584static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
585 size_t max = SIZE_MAX) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700586 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300587 return false;
588 }
589
Mark Salyzyn5f606602017-02-10 13:09:07 -0800590 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700591 errno = 0;
592 size_t ret = (size_t)strtoll(ptr, &endp, 0);
593
594 if (endp[0] || errno) {
595 return false;
596 }
597
598 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300599 return false;
600 }
601
602 *val = ret;
603 return true;
604}
605
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800606static void logcat_panic(android_logcat_context_internal* context,
607 enum helpType showHelp, const char* fmt, ...) {
608 context->retval = EXIT_FAILURE;
609 if (!context->error) {
610 context->stop = true;
611 return;
612 }
613
Mark Salyzyn5f606602017-02-10 13:09:07 -0800614 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700615 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800616 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700617 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300618
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700619 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800620 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800621 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800622 break;
623 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800624 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800625 break;
626 case HELP_FALSE:
627 default:
628 break;
Traian Schiau59763032015-04-10 15:51:39 +0300629 }
630
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800631 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300632}
633
Mark Salyzyn5f606602017-02-10 13:09:07 -0800634static char* parseTime(log_time& t, const char* cp) {
635 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700636 if (ep) {
637 return ep;
638 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700639 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
640 if (ep) {
641 return ep;
642 }
643 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700644}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700645
Mark Salyzyn31961062016-08-04 07:43:46 -0700646// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn5f606602017-02-10 13:09:07 -0800647static log_time lastLogTime(char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700648 log_time retval(log_time::EPOCH);
649 if (!outputFileName) {
650 return retval;
651 }
652
Mark Salyzynf3555d92015-05-27 07:39:56 -0700653 std::string directory;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800654 char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700655 if (!file) {
656 directory = ".";
657 file = outputFileName;
658 } else {
659 *file = '\0';
660 directory = outputFileName;
661 *file = '/';
662 ++file;
663 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700664
Mark Salyzyn5f606602017-02-10 13:09:07 -0800665 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
666 closedir);
Mark Salyzync18c2132016-04-01 07:52:20 -0700667 if (!dir.get()) {
668 return retval;
669 }
670
Mark Salyzyn31961062016-08-04 07:43:46 -0700671 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700672
Mark Salyzynf3555d92015-05-27 07:39:56 -0700673 size_t len = strlen(file);
674 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800675 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700676
Mark Salyzynf3555d92015-05-27 07:39:56 -0700677 while ((dp = readdir(dir.get())) != NULL) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800678 if ((dp->d_type != DT_REG) || (strncmp(dp->d_name, file, len) != 0) ||
679 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
680 (strtoll(dp->d_name + 1, NULL, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700681 continue;
682 }
683
684 std::string file_name = directory;
685 file_name += "/";
686 file_name += dp->d_name;
687 std::string file;
688 if (!android::base::ReadFileToString(file_name, &file)) {
689 continue;
690 }
691
692 bool found = false;
693 for (const auto& line : android::base::Split(file, "\n")) {
694 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800695 char* ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700696 if (!ep || (*ep != ' ')) {
697 continue;
698 }
699 // determine the time precision of the logs (eg: msec or usec)
700 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
701 if (t.tv_nsec % (mod * 10)) {
702 modulo.tv_nsec = mod;
703 break;
704 }
705 }
706 // We filter any times later than current as we may not have the
707 // year stored with each log entry. Also, since it is possible for
708 // entries to be recorded out of order (very rare) we select the
709 // maximum we find just in case.
710 if ((t < now) && (t > retval)) {
711 retval = t;
712 found = true;
713 }
714 }
715 // We count on the basename file to be the definitive end, so stop here.
716 if (!dp->d_name[len] && found) {
717 break;
718 }
719 }
720 if (retval == log_time::EPOCH) {
721 return retval;
722 }
723 // tail_time prints matching or higher, round up by the modulo to prevent
724 // a replay of the last entry we have just checked.
725 retval += modulo;
726 return retval;
727}
728
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800729const char* getenv(android_logcat_context_internal* context, const char* name) {
730 if (!context->envp || !name || !*name) return NULL;
731
732 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
733 if (strncmp(context->envp[i], name, len)) continue;
734 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
735 }
736 return NULL;
737}
738
Mark Salyzyn5f606602017-02-10 13:09:07 -0800739} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300740
Mark Salyzyn5f606602017-02-10 13:09:07 -0800741void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800742 bool blockSecurity) {
743 if (*current) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800744 return;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800745 }
746 if (blockSecurity && (android_name_to_log_id(name) == LOG_ID_SECURITY)) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800747 return;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800748 }
749 *current = name;
750}
Traian Schiau59763032015-04-10 15:51:39 +0300751
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800752static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300753 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800754 int err;
755 int hasSetLogFormat = 0;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800756 bool clearLog = false;
757 bool allSelected = false;
758 bool getLogSize = false;
759 bool getPruneList = false;
760 bool printStatistics = false;
761 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800762 unsigned long setLogSize = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800763 char* setPruneList = NULL;
764 char* setId = NULL;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800765 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800766 std::string forceFilters;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800767 log_device_t* devices = NULL;
768 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800769 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300770 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800771 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700772 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700773 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800775 // object instantiations before goto's can happen
776 log_device_t unexpected("unexpected", false);
777 const char* openDeviceFail = NULL;
778 const char* clearFail = NULL;
779 const char* setSizeFail = NULL;
780 const char* getSizeFail = NULL;
781 int argc = context->argc;
782 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800783
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800784 context->output = stdout;
785 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800787 for (int i = 0; i < argc; ++i) {
788 // Simulate shell stderr redirect parsing
789 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
790
791 size_t skip = (argv[i][2] == '>') + 2;
792 if (!strcmp(&argv[i][skip], "/dev/null")) {
793 context->stderr_null = true;
794 } else if (!strcmp(&argv[i][skip], "&1")) {
795 context->stderr_stdout = true;
796 } else {
797 // stderr file redirections are not supported
798 fprintf(context->stderr_stdout ? stdout : stderr,
799 "stderr redirection to file %s unsupported, skipping\n",
800 &argv[i][skip]);
801 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800802 }
803
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800804 // Deal with setting up file descriptors and FILE pointers
805 if (context->error_fd >= 0) {
806 if (context->error_fd == context->output_fd) {
807 context->stderr_stdout = true;
808 } else if (context->stderr_null) {
809 close(context->error_fd);
810 context->error_fd = -1;
811 } else {
812 context->error = fdopen(context->error_fd, "web");
813 if (!context->error) {
814 context->retval = -errno;
815 fprintf(context->stderr_stdout ? stdout : stderr,
816 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
817 strerror(errno));
818 goto exit;
819 }
820 }
821 }
822 if (context->output_fd >= 0) {
823 context->output = fdopen(context->output_fd, "web");
824 if (!context->output) {
825 context->retval = -errno;
826 fprintf(context->stderr_stdout ? stdout : context->error,
827 "Failed to fdopen(output_fd=%d) %s\n", context->output_fd,
828 strerror(errno));
829 goto exit;
830 }
831 }
832 if (context->stderr_stdout) context->error = context->output;
833 if (context->stderr_null) {
834 context->error_fd = -1;
835 context->error = NULL;
836 }
837 // Only happens if output=stdout
838 if ((context->output_fd < 0) && context->output) {
839 context->output_fd = fileno(context->output);
840 }
841 // Only happens if error=stdout || error=stderr
842 if ((context->error_fd < 0) && context->error) {
843 context->error_fd = fileno(context->error);
844 }
845
846 context->logformat = android_log_format_new();
847
848 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
849 show_help(context);
850 context->retval = EXIT_SUCCESS;
851 goto exit;
852 }
853
854 // danger: getopt is _not_ reentrant
855 optind = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856 for (;;) {
857 int ret;
858
Kristian Monsen562e5132015-06-05 14:10:12 -0700859 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700860 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700861 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800862 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700863 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800864 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700865 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800866 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700867 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800868 { "binary", no_argument, NULL, 'B' },
869 { "buffer", required_argument, NULL, 'b' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700870 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800871 { "clear", no_argument, NULL, 'c' },
Mark Salyzyn538bc122016-11-16 15:28:31 -0800872 { debug_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800873 { "dividers", no_argument, NULL, 'D' },
874 { "file", required_argument, NULL, 'f' },
875 { "format", required_argument, NULL, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700876 // hidden and undocumented reserved alias for --regex
877 { "grep", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700878 // hidden and undocumented reserved alias for --max-count
879 { "head", required_argument, NULL, 'm' },
Mark Salyzyn02687e72016-08-03 14:20:41 -0700880 { id_str, required_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800881 { "last", no_argument, NULL, 'L' },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700882 { "max-count", required_argument, NULL, 'm' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700883 { pid_str, required_argument, NULL, 0 },
Mark Salyzync9202772016-03-30 09:38:31 -0700884 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800885 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700886 { "regex", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700887 { "rotate-count", required_argument, NULL, 'n' },
888 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800889 { "statistics", no_argument, NULL, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700890 // hidden and undocumented reserved alias for -t
891 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800892 // support, but ignore and do not document, the optional argument
893 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700894 { NULL, 0, NULL, 0 }
895 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800896 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700897
Mark Salyzyn5f606602017-02-10 13:09:07 -0800898 ret = getopt_long(argc, argv,
899 ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
900 &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901
902 if (ret < 0) {
903 break;
904 }
905
Kristian Monsen562e5132015-06-05 14:10:12 -0700906 switch (ret) {
907 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700908 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700909 if (long_options[option_index].name == pid_str) {
910 // ToDo: determine runtime PID_MAX?
911 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800912 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Kristian Monsen562e5132015-06-05 14:10:12 -0700913 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800914 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700915 }
916 break;
917 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800918 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800919 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800920 ANDROID_LOG_NONBLOCK;
921 // ToDo: implement API that supports setting a wrap timeout
922 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
923 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800924 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800925 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800926 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800927 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800928 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
929 context->error) {
930 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800931 "WARNING: %s %u seconds, ignoring %zu\n",
932 long_options[option_index].name,
933 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
934 }
935 break;
936 }
Mark Salyzync9202772016-03-30 09:38:31 -0700937 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800938 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700939 break;
940 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800941 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800942 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800943 break;
944 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700945 if (long_options[option_index].name == id_str) {
946 setId = optarg && optarg[0] ? optarg : NULL;
947 break;
948 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800949 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700950
Mark Salyzyn95132e92013-11-22 10:55:48 -0800951 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800952 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800953 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800954 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800955
956 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800957 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800958 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800959 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800960
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800961 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800962 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
963 ANDROID_LOG_NONBLOCK;
964 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800965
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800967 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800968 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800969
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800970 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700971 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800972 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800973 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800974 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800975 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800976 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800977 if (!cp) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800978 logcat_panic(context, HELP_FALSE,
Mark Salyzyn5f606602017-02-10 13:09:07 -0800979 "-%c \"%s\" not in time format\n", ret,
980 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800981 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800982 }
983 if (*cp) {
984 char c = *cp;
985 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800986 if (context->error) {
987 fprintf(
988 context->error,
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800989 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
990 ret, optarg, c, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800991 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800992 *cp = c;
993 }
994 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300995 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800996 if (context->error) {
997 fprintf(context->error,
998 "WARNING: -%c %s invalid, setting to 1\n",
999 ret, optarg);
1000 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001001 tail_lines = 1;
1002 }
1003 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001004 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -08001005
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001006 case 'D':
1007 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001008 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001009
Casey Dahlindc42a872016-03-17 16:18:55 -07001010 case 'e':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001011 context->regex = new pcrecpp::RE(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001012 break;
Casey Dahlindc42a872016-03-17 16:18:55 -07001013
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001014 case 'm': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001015 char* end = NULL;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001016 if (!getSizeTArg(optarg, &context->maxCount)) {
1017 logcat_panic(context, HELP_FALSE,
1018 "-%c \"%s\" isn't an "
1019 "integer greater than zero\n",
1020 ret, optarg);
1021 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001022 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001023 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001024
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001026 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001027 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001028 break;
1029 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001030 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001031
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001032 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001033 char* cp;
Traian Schiau59763032015-04-10 15:51:39 +03001034 if (strtoll(optarg, &cp, 0) > 0) {
1035 setLogSize = strtoll(optarg, &cp, 0);
1036 } else {
1037 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001038 }
1039
Mark Salyzyn5f606602017-02-10 13:09:07 -08001040 switch (*cp) {
1041 case 'g':
1042 case 'G':
1043 setLogSize *= 1024;
1044 // FALLTHRU
1045 case 'm':
1046 case 'M':
1047 setLogSize *= 1024;
1048 // FALLTHRU
1049 case 'k':
1050 case 'K':
1051 setLogSize *= 1024;
1052 // FALLTHRU
1053 case '\0':
1054 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001055
Mark Salyzyn5f606602017-02-10 13:09:07 -08001056 default:
1057 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001058 }
1059
1060 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001061 logcat_panic(context, HELP_FALSE,
1062 "ERROR: -G <num><multiplier>\n");
1063 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001064 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001065 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001066
1067 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001068 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001069 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001070 break;
1071 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001072 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001073
1074 case 'P':
1075 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001076 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001077
Joe Onorato6fa09a02010-02-26 10:04:23 -08001078 case 'b': {
Mark Salyzyn45177732016-04-11 14:03:48 -07001079 unsigned idMask = 0;
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001080 while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
1081 if (strcmp(optarg, "default") == 0) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001082 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001083 (1 << LOG_ID_CRASH);
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001084 } else if (strcmp(optarg, "all") == 0) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001085 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001086 idMask = (unsigned)-1;
1087 } else {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001088 log_id_t log_id = android_name_to_log_id(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001089 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001090
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001091 if (strcmp(name, optarg) != 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001092 logcat_panic(context, HELP_TRUE,
1093 "unknown buffer %s\n", optarg);
1094 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001095 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001096 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001097 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001098 }
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001099 optarg = NULL;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001100 }
1101
Mark Salyzyn45177732016-04-11 14:03:48 -07001102 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001103 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001104 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001105
Mark Salyzyn45177732016-04-11 14:03:48 -07001106 if (log_id != (log_id_t)i) {
1107 continue;
1108 }
1109 if ((idMask & (1 << i)) == 0) {
1110 continue;
1111 }
Mark Salyzyn083b0372015-12-04 10:59:45 -08001112
Mark Salyzyn45177732016-04-11 14:03:48 -07001113 bool found = false;
1114 for (dev = devices; dev; dev = dev->next) {
1115 if (!strcmp(name, dev->device)) {
1116 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001117 break;
1118 }
Mark Salyzyn45177732016-04-11 14:03:48 -07001119 if (!dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -08001120 break;
1121 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001122 }
Mark Salyzyn45177732016-04-11 14:03:48 -07001123 if (found) {
1124 continue;
1125 }
1126
Mark Salyzyn5f606602017-02-10 13:09:07 -08001127 bool binary =
1128 !strcmp(name, "events") || !strcmp(name, "security");
Mark Salyzyn45177732016-04-11 14:03:48 -07001129 log_device_t* d = new log_device_t(name, binary);
1130
Mark Salyzyn083b0372015-12-04 10:59:45 -08001131 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001132 dev->next = d;
1133 dev = d;
1134 } else {
1135 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001136 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001137 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001138 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001139 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140
1141 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001142 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001143 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001144
1145 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -07001146 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -07001147 tail_time = lastLogTime(optarg);
1148 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001149 // redirect output to a file
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001150 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001151 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001153 case 'r':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001154 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1155 logcat_panic(context, HELP_TRUE,
1156 "Invalid parameter \"%s\" to -r\n", optarg);
1157 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001158 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001159 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001160
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001161 case 'n':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001162 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1163 logcat_panic(context, HELP_TRUE,
1164 "Invalid parameter \"%s\" to -n\n", optarg);
1165 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001167 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001168
1169 case 'v':
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001170 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001171 show_format_help(context);
1172 context->retval = EXIT_SUCCESS;
1173 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001174 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001175 err = setLogFormat(context, optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001176 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001177 logcat_panic(context, HELP_FORMAT,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001178 "Invalid parameter \"%s\" to -v\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001179 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001180 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001181 hasSetLogFormat |= err;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001182 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001183
1184 case 'Q':
Mark Salyzyn5f606602017-02-10 13:09:07 -08001185#define KERNEL_OPTION "androidboot.logcat="
1186#define CONSOLE_OPTION "androidboot.console="
1187 // This is a *hidden* option used to start a version of logcat
1188 // in an emulated device only. It basically looks for
1189 // androidboot.logcat= on the kernel command line. If
1190 // something is found, it extracts a log filter and uses it to
1191 // run the program. If nothing is found, the program should
1192 // quit immediately.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001193 {
Mark Salyzynf3290292017-02-10 13:09:07 -08001194 std::string cmdline;
1195 android::base::ReadFileToString("/proc/cmdline", &cmdline);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196
Mark Salyzynf3290292017-02-10 13:09:07 -08001197 const char* logcat = strstr(cmdline.c_str(), KERNEL_OPTION);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001198 // if nothing found or invalid filters, exit quietly
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001199 if (!logcat) {
1200 context->retval = EXIT_SUCCESS;
1201 goto exit;
1202 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001203
1204 const char* p = logcat + strlen(KERNEL_OPTION);
1205 const char* q = strpbrk(p, " \t\n\r");
1206 if (!q) q = p + strlen(p);
1207 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001208
Mark Salyzyn5f606602017-02-10 13:09:07 -08001209 // redirect our output to the emulator console
Mark Salyzynf3290292017-02-10 13:09:07 -08001210 const char* console =
1211 strstr(cmdline.c_str(), CONSOLE_OPTION);
1212 if (!console) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001213
Mark Salyzynf3290292017-02-10 13:09:07 -08001214 p = console + strlen(CONSOLE_OPTION);
1215 q = strpbrk(p, " \t\n\r");
1216 int len = q ? q - p : strlen(p);
1217 std::string devname = "/dev/" + std::string(p, len);
1218 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001219
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001220 if (context->error) {
1221 fprintf(context->error, "logcat using %s\n",
1222 devname.c_str());
1223 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001224
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001225 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001226 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001227 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001228
1229 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001230 android::close_output(context);
1231 android::close_error(context);
1232 context->stderr_stdout = true;
1233 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001234 context->output_fd = fileno(fp);
1235 if (context->stderr_null) break;
1236 context->stderr_stdout = true;
1237 context->error = fp;
1238 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001239 }
1240 break;
1241
Mark Salyzyn34facab2014-02-06 14:48:50 -08001242 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001243 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001244 break;
1245
Traian Schiau59763032015-04-10 15:51:39 +03001246 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001247 logcat_panic(context, HELP_TRUE,
1248 "Option -%c needs an argument\n", optopt);
1249 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001250
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001251 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001252 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
1253 optopt);
1254 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001255 }
1256 }
1257
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001258 if (context->maxCount && got_t) {
1259 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001260 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001261 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001262 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001263 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001264 // One day it would be nice if --print -v color and --regex <expr>
1265 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001266 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001267 if (context->error) {
1268 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001269 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001270 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001271 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001272 }
1273 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001274 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001275
Joe Onorato6fa09a02010-02-26 10:04:23 -08001276 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001277 dev = devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001278 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001279 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001280 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001281 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001282 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001283 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001284 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001285 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001286 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001287 }
1288
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001289 if (context->logRotateSizeKBytes != 0 && context->outputFileName == NULL) {
1290 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1291 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001292 }
1293
Mark Salyzyn02687e72016-08-03 14:20:41 -07001294 if (setId != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001295 if (context->outputFileName == NULL) {
1296 logcat_panic(context, HELP_TRUE,
1297 "--id='%s' requires -f as well\n", setId);
1298 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001299 }
1300
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001301 std::string file_name = android::base::StringPrintf(
1302 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001303 std::string file;
1304 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001305 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1306 getuid(), getgid());
Mark Salyzyn02687e72016-08-03 14:20:41 -07001307 if (!file_ok || (file.compare(setId) == 0)) {
1308 setId = NULL;
1309 }
1310 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001311
1312 if (hasSetLogFormat == 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001313 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001314
1315 if (logFormat != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001316 err = setLogFormat(context, logFormat);
1317 if ((err < 0) && context->error) {
1318 fprintf(context->error,
1319 "invalid format in ANDROID_PRINTF_LOG '%s'\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -08001320 logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001321 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001322 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001323 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001324 }
1325 }
1326
Mark Salyzynf3290292017-02-10 13:09:07 -08001327 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001328 err = android_log_addFilterString(context->logformat,
1329 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001330 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001331 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001332 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001333 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001334 }
1335 } else if (argc == optind) {
1336 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001337 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001338
1339 if (env_tags_orig != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001340 err = android_log_addFilterString(context->logformat,
1341 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001342
Mark Salyzyn95132e92013-11-22 10:55:48 -08001343 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001344 logcat_panic(context, HELP_TRUE,
1345 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1346 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001347 }
1348 }
1349 } else {
1350 // Add from commandline
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001351 for (int i = optind ; i < argc ; i++) {
1352 // skip stderr redirections of _all_ kinds
1353 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001354
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001355 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001356 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001357 logcat_panic(context, HELP_TRUE,
1358 "Invalid filter expression '%s'\n", argv[i]);
1359 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001360 }
1361 }
1362 }
1363
Joe Onorato6fa09a02010-02-26 10:04:23 -08001364 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001365 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001366 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001367 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001368 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001369 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001370 // We have three orthogonal actions below to clear, set log size and
1371 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001372 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001373 dev->logger_list = logger_list;
1374 dev->logger = android_logger_open(logger_list,
1375 android_name_to_log_id(dev->device));
1376 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001377 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001378 dev = dev->next;
1379 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001380 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001381
Mark Salyzyn02687e72016-08-03 14:20:41 -07001382 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001383 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001384 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001385 (context->maxRotatedLogs > 0) ?
1386 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1387 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001388
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001389 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001390 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001391
1392 if (i == 0) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001393 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001394 "%s", context->outputFileName);
1395 } else {
1396 file = android::base::StringPrintf("%s.%.*d",
1397 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001398 }
1399
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001400 if (file.length() == 0) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001401 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001402 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001403 break;
1404 }
1405
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001406 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001407
1408 if (err < 0 && errno != ENOENT && clearFail == NULL) {
1409 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001410 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001411 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001412 }
1413 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001414 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001415 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001416 }
1417
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001418 if (setLogSize) {
1419 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001420 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001421 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001422 }
1423
Joe Onorato6fa09a02010-02-26 10:04:23 -08001424 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001425 long size = android_logger_get_log_size(dev->logger);
1426 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001427
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001428 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001429 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001430 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001431 std::string str = android::base::StringPrintf(
1432 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1433 " max entry is %db, max payload is %db\n",
1434 dev->device,
1435 value_of_size(size), multiplier_of_size(size),
1436 value_of_size(readable), multiplier_of_size(readable),
1437 (int)LOGGER_ENTRY_MAX_LEN,
1438 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1439 TEMP_FAILURE_RETRY(write(context->output_fd,
1440 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001441 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001442 }
1443
1444 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001445 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001446
1447 context->retval = EXIT_SUCCESS;
1448
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001449 // report any errors in the above loop and exit
1450 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001451 logcat_panic(context, HELP_FALSE,
1452 "Unable to open log device '%s'\n", openDeviceFail);
1453 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001454 }
1455 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001456 logcat_panic(context, HELP_FALSE,
1457 "failed to clear the '%s' log\n", clearFail);
1458 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001459 }
1460 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001461 logcat_panic(context, HELP_FALSE,
1462 "failed to set the '%s' log size\n", setSizeFail);
1463 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001464 }
1465 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001466 logcat_panic(context, HELP_FALSE,
1467 "failed to get the readable '%s' log size", getSizeFail);
1468 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001469 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001470
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001471 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001472 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001473 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001474 size_t bLen = len + 32;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001475 char* buf = NULL;
Traian Schiau59763032015-04-10 15:51:39 +03001476 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1477 buf[len] = '\0';
1478 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001479 logcat_panic(context, HELP_FALSE,
1480 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001481 }
1482 free(buf);
1483 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001484 logcat_panic(context, HELP_FALSE,
1485 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001486 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001487 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001488 }
1489
Mark Salyzyn1c950472014-04-01 17:19:47 -07001490 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001491 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001492 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001493
Mark Salyzyn5f606602017-02-10 13:09:07 -08001494 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
1495 delete[] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001496 if (getPruneList) {
1497 android_logger_get_prune_list(logger_list, buf, len);
1498 } else {
1499 android_logger_get_statistics(logger_list, buf, len);
1500 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001501 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001502 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001503 delete[] buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001504 buf = NULL;
1505 break;
1506 }
Traian Schiau59763032015-04-10 15:51:39 +03001507 size_t ret = atol(buf) + 1;
1508 if (ret <= len) {
1509 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001510 break;
1511 }
Traian Schiau59763032015-04-10 15:51:39 +03001512 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001513 }
1514
1515 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001516 logcat_panic(context, HELP_FALSE, "failed to read data");
1517 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001518 }
1519
1520 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001521 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001522 *cp = '\0';
1523 bool truncated = *--cp != '\f';
1524 if (!truncated) {
1525 *cp = '\0';
1526 }
1527
1528 // squash out the byte count
1529 cp = buf;
1530 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001531 while (isdigit(*cp)) {
1532 ++cp;
1533 }
1534 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001535 ++cp;
1536 }
1537 }
1538
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001539 len = strlen(cp);
1540 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001541 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001542 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001543 }
1544
Mark Salyzyn5f606602017-02-10 13:09:07 -08001545 if (getLogSize || setLogSize || clearLog) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001546 goto close;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001547 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001548
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001549 setupOutputAndSchedulingPolicy(context, (mode & ANDROID_LOG_NONBLOCK) == 0);
1550 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001551
Mark Salyzyn5f606602017-02-10 13:09:07 -08001552 // LOG_EVENT_INT(10, 12345);
1553 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1554 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001555
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001556 dev = NULL;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001557
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001558 while (!context->stop &&
1559 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001560 struct log_msg log_msg;
1561 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001562 if (ret == 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001563 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1564 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001565 }
1566
1567 if (ret < 0) {
1568 if (ret == -EAGAIN) {
1569 break;
1570 }
1571
1572 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001573 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1574 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001575 }
1576 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001577 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1578 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001579 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001580 logcat_panic(context, HELP_FALSE, "logcat read failure");
1581 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001582 }
1583
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001584 log_device_t* d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001585 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001586 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001587 break;
1588 }
1589 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001590 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001591 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001592 d = &unexpected;
1593 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001594 }
1595
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001596 if (dev != d) {
1597 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001598 maybePrintStart(context, dev, printDividers);
1599 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001600 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001601 if (context->printBinary) {
1602 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001603 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001604 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001605 }
1606 }
1607
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001608close:
Mark Salyzyn95132e92013-11-22 10:55:48 -08001609 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001610
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001611exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001612 // close write end of pipe to help things along
1613 if (context->output_fd == context->fds[1]) {
1614 android::close_output(context);
1615 }
1616 if (context->error_fd == context->fds[1]) {
1617 android::close_error(context);
1618 }
1619 if (context->fds[1] >= 0) {
1620 // NB: should be closed by the above
1621 int save_errno = errno;
1622 close(context->fds[1]);
1623 errno = save_errno;
1624 context->fds[1] = -1;
1625 }
1626 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001627 return context->retval;
1628}
1629
1630// Can block
1631int android_logcat_run_command(android_logcat_context ctx,
1632 int output, int error,
1633 int argc, char* const* argv,
1634 char* const* envp) {
1635 android_logcat_context_internal* context = ctx;
1636
1637 context->output_fd = output;
1638 context->error_fd = error;
1639 context->argc = argc;
1640 context->argv = argv;
1641 context->envp = envp;
1642 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001643 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001644 return __logcat(context);
1645}
1646
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001647// starts a thread, opens a pipe, returns reading end.
1648int android_logcat_run_command_thread(android_logcat_context ctx,
1649 int argc, char* const* argv,
1650 char* const* envp) {
1651 android_logcat_context_internal* context = ctx;
1652
1653 int save_errno = EBUSY;
1654 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) {
1655 goto exit;
1656 }
1657
1658 if (pipe(context->fds) < 0) {
1659 save_errno = errno;
1660 goto exit;
1661 }
1662
1663 pthread_attr_t attr;
1664 if (pthread_attr_init(&attr)) {
1665 save_errno = errno;
1666 goto close_exit;
1667 }
1668
1669 struct sched_param param;
1670 memset(&param, 0, sizeof(param));
1671 pthread_attr_setschedparam(&attr, &param);
1672 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1673 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1674 int save_errno = errno;
1675 goto pthread_attr_exit;
1676 }
1677
1678 context->stop = false;
1679 context->thread_stopped = false;
1680 context->output_fd = context->fds[1];
1681 // save off arguments so they remain while thread is active.
1682 for (int i = 0; i < argc; ++i) {
1683 context->args.push_back(std::string(argv[i]));
1684 }
1685 // save off environment so they remain while thread is active.
1686 if (envp) for (size_t i = 0; envp[i]; ++i) {
1687 context->envs.push_back(std::string(envp[i]));
1688 }
1689
1690 for (auto& str : context->args) {
1691 context->argv_hold.push_back(str.c_str());
1692 }
1693 context->argv_hold.push_back(NULL);
1694 for (auto& str : context->envs) {
1695 context->envp_hold.push_back(str.c_str());
1696 }
1697 context->envp_hold.push_back(NULL);
1698
1699 context->argc = context->argv_hold.size() - 1;
1700 context->argv = (char* const*)&context->argv_hold[0];
1701 context->envp = (char* const*)&context->envp_hold[0];
1702
1703#ifdef DEBUG
1704 fprintf(stderr, "argv[%d] = {", context->argc);
1705 for (auto str : context->argv_hold) {
1706 fprintf(stderr, " \"%s\"", str ?: "NULL");
1707 }
1708 fprintf(stderr, " }\n");
1709 fflush(stderr);
1710#endif
1711 context->retval = EXIT_SUCCESS;
1712 if (pthread_create(&context->thr, &attr,
1713 (void*(*)(void*))__logcat, context)) {
1714 int save_errno = errno;
1715 goto argv_exit;
1716 }
1717 pthread_attr_destroy(&attr);
1718
1719 return context->fds[0];
1720
1721argv_exit:
1722 context->argv_hold.clear();
1723 context->args.clear();
1724 context->envp_hold.clear();
1725 context->envs.clear();
1726pthread_attr_exit:
1727 pthread_attr_destroy(&attr);
1728close_exit:
1729 close(context->fds[0]);
1730 context->fds[0] = -1;
1731 close(context->fds[1]);
1732 context->fds[1] = -1;
1733exit:
1734 errno = save_errno;
1735 context->stop = true;
1736 context->thread_stopped = true;
1737 context->retval = EXIT_FAILURE;
1738 return -1;
1739}
1740
1741// test if the thread is still doing 'stuff'
1742int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1743 android_logcat_context_internal* context = ctx;
1744
1745 return context->thread_stopped == false;
1746}
1747
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001748// Finished with context
1749int android_logcat_destroy(android_logcat_context* ctx) {
1750 android_logcat_context_internal* context = *ctx;
1751
1752 *ctx = NULL;
1753
1754 context->stop = true;
1755
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001756 while (context->thread_stopped == false) {
1757 sched_yield();
1758 }
1759
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001760 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001761 context->argv_hold.clear();
1762 context->args.clear();
1763 context->envp_hold.clear();
1764 context->envs.clear();
1765 if (context->fds[0] >= 0) {
1766 close(context->fds[0]);
1767 context->fds[0] = -1;
1768 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001769 android::close_output(context);
1770 android::close_error(context);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001771 if (context->fds[1] >= 0) {
1772 // NB: could be closed by the above fclose(s), ignore error.
1773 int save_errno = errno;
1774 close(context->fds[1]);
1775 errno = save_errno;
1776 context->fds[1] = -1;
1777 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001778
1779 android_closeEventTagMap(context->eventTagMap);
1780
1781 int retval = context->retval;
1782
1783 free(context);
1784
1785 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001786}