blob: d67dee56cef76e9de649b531840183281a016af9 [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 Salyzyne3d0c962017-02-17 13:15:51 -080070 int output_fd; // duplication of fileno(output) (below)
71 int error_fd; // duplication of fileno(error) (below)
Mark Salyzync0cf90d2017-02-10 13:09:07 -080072
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");
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800287 if (context->output == NULL) {
288 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
289 return;
290 }
291 if (context->stderr_stdout) {
292 close_error(context);
293 context->error = context->output;
294 context->error_fd = context->output_fd;
295 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800296
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800297 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800298}
299
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800300void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800301 size_t size = buf->len();
302
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800303 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800304}
305
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800306static bool regexOk(android_logcat_context_internal* context,
307 const AndroidLogEntry& entry) {
308 if (!context->regex) {
Casey Dahlindc42a872016-03-17 16:18:55 -0700309 return true;
310 }
311
Casey Dahlindc42a872016-03-17 16:18:55 -0700312 std::string messageString(entry.message, entry.messageLen);
313
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800314 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700315}
316
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800317static void processBuffer(android_logcat_context_internal* context,
318 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700319 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800320 int err;
321 AndroidLogEntry entry;
322 char binaryMsgBuf[1024];
323
Joe Onorato6fa09a02010-02-26 10:04:23 -0800324 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800325 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
326 context->eventTagMap = android_openEventTagMap(NULL);
327 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800328 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800329 err = android_log_processBinaryLogBuffer(
330 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
331 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800332 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333 // entry.priority, entry.messageLen, entry.message);
334 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800335 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800336 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800337 if ((err < 0) && !context->debug) {
338 return;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800339 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800340
Mark Salyzyn5f606602017-02-10 13:09:07 -0800341 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800342 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800343 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800344 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800345
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800346 context->printCount += match;
347 if (match || context->printItAnyways) {
348 bytesWritten = android_log_printLogLine(context->logformat,
349 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700350
Mark Salyzync9202772016-03-30 09:38:31 -0700351 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800352 logcat_panic(context, HELP_FALSE, "output error");
353 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700354 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800355 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356 }
357
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800358 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800359
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800360 if (context->logRotateSizeKBytes > 0 &&
361 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
362 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364}
365
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800366static void maybePrintStart(android_logcat_context_internal* context,
367 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800368 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800369 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800370 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800371 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800372 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800373 if (write(context->output_fd, buf, strlen(buf)) < 0) {
374 logcat_panic(context, HELP_FALSE, "output error");
375 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800376 }
377 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800378 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800379 }
380}
381
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800382static void setupOutputAndSchedulingPolicy(
383 android_logcat_context_internal* context, bool blocking) {
384 if (context->outputFileName == NULL) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385
Mark Salyzynad5e4112016-08-04 07:53:52 -0700386 if (blocking) {
387 // Lower priority and set to batch scheduling if we are saving
388 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800389 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
390 fprintf(context->error,
391 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700392 }
393
394 struct sched_param param;
395 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800396 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700397 fprintf(stderr, "failed to set to batch scheduler\n");
398 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800399
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800400 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
401 context->error) {
402 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700403 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700405
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800406 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700407
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800408 context->output_fd = openLogFile(context->outputFileName);
409
410 if (context->output_fd < 0) {
411 logcat_panic(context, HELP_FALSE, "couldn't open output file");
412 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700413 }
414
415 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800416 if (fstat(context->output_fd, &statbuf) == -1) {
417 close_output(context);
418 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
419 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700420 }
421
Mark Salyzyn5f606602017-02-10 13:09:07 -0800422 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800423 close_output(context);
424 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
425 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700426 }
427
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800428 context->output = fdopen(context->output_fd, "web");
429
430 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800431}
432
Mark Salyzyn5f606602017-02-10 13:09:07 -0800433// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800434static void show_help(android_logcat_context_internal* context) {
435 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800436
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800437 const char* cmd = strrchr(context->argv[0], '/');
438 cmd = cmd ? cmd + 1 : context->argv[0];
439
440 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
441
442 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700443 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
444 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700445 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
446 " Rotate log every kbytes. Requires -f option\n"
447 " -n <count>, --rotate-count=<count>\n"
448 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700449 " --id=<id> If the signature id for logging to file changes, then clear\n"
450 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700451 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700452 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700453 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700454 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700455 " color descriptive epoch monotonic printable uid\n"
456 " usec UTC year zone\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800457 // private and undocumented nsec, no signal, too much noise
458 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700459 " -D, --dividers Print dividers between each log buffer\n"
460 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700461 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700462 " -d Dump the log and then exit (don't block)\n"
463 " -e <expr>, --regex=<expr>\n"
464 " Only print lines where the log message matches <expr>\n"
465 " where <expr> is a regular expression\n"
466 // Leave --head undocumented as alias for -m
467 " -m <count>, --max-count=<count>\n"
468 " Quit after printing <count> lines. This is meant to be\n"
469 " paired with --regex, but will work on its own.\n"
470 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700471 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700472 // Leave --tail undocumented as alias for -t
473 " -t <count> Print only the most recent <count> lines (implies -d)\n"
474 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
475 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
476 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700477 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700478 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700479 " -g, --buffer-size Get the size of the ring buffer.\n"
480 " -G <size>, --buffer-size=<size>\n"
481 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100482 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800483 // Leave security (Device Owner only installations) and
484 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700485 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
486 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700487 " Multiple -b parameters or comma separated list of buffers are\n"
488 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700489 " -B, --binary Output the log in binary.\n"
490 " -S, --statistics Output statistics.\n"
491 " -p, --prune Print prune white and ~black list. Service is specified as\n"
492 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700493 " with ~, otherwise weighed for longevity if unadorned. All\n"
494 " other pruning activity is oldest first. Special case ~!\n"
495 " represents an automatic quicker pruning for the noisiest\n"
496 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700497 " -P '<list> ...', --prune='<list> ...'\n"
498 " Set prune white and ~black list, using same format as\n"
499 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800500 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700501 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800502 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
503 " comes first. Improves efficiency of polling by providing\n"
504 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800506 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507 " <tag>[:priority]\n\n"
508 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700509 " V Verbose (default for <tag>)\n"
510 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800511 " I Info\n"
512 " W Warn\n"
513 " E Error\n"
514 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700515 " S Silent (suppress all output)\n"
516 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
517 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
518 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
519 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
520 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700521 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522}
523
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800524static void show_format_help(android_logcat_context_internal* context) {
525 if (!context->error) return;
526 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700527 "-v <format>, --format=<format> options:\n"
528 " Sets log print format verb and adverbs, where <format> is:\n"
529 " brief long process raw tag thread threadtime time\n"
530 " and individually flagged modifying adverbs can be added:\n"
531 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
532 "\nSingle format verbs:\n"
533 " brief — Display priority/tag and PID of the process issuing the message.\n"
534 " long — Display all metadata fields, separate messages with blank lines.\n"
535 " process — Display PID only.\n"
536 " raw — Display the raw log message, with no other metadata fields.\n"
537 " tag — Display the priority/tag only.\n"
538 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
539 " and TID of the thread issuing the message. (the default format).\n"
540 " time — Display the date, invocation time, priority/tag, and PID of the\n"
541 " process issuing the message.\n"
542 "\nAdverb modifiers can be used in combination:\n"
543 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
544 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
545 " descriptive — events logs only, descriptions from event-log-tags database.\n"
546 " epoch — Display time as seconds since Jan 1 1970.\n"
547 " monotonic — Display time as cpu seconds since last boot.\n"
548 " printable — Ensure that any binary logging content is escaped.\n"
549 " uid — If permitted, display the UID or Android ID of logged process.\n"
550 " usec — Display time down the microsecond precision.\n"
551 " UTC — Display time as UTC.\n"
552 " year — Add the year to the displayed time.\n"
553 " zone — Add the local timezone to the displayed time.\n"
554 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
555 );
556}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800557// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700558
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800559static int setLogFormat(android_logcat_context_internal* context,
560 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800561 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562
563 format = android_log_formatFromString(formatString);
564
565 if (format == FORMAT_OFF) {
566 // FORMAT_OFF means invalid string
567 return -1;
568 }
569
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800570 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800571}
572
Mark Salyzyn5f606602017-02-10 13:09:07 -0800573static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700574
Mark Salyzyn5f606602017-02-10 13:09:07 -0800575static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700576 for (unsigned 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 value;
581}
582
Mark Salyzyn5f606602017-02-10 13:09:07 -0800583static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700584 unsigned i;
585 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800586 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
587 value /= 1024, ++i)
588 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700589 return multipliers[i];
590}
591
Mark Salyzyn5f606602017-02-10 13:09:07 -0800592// String to unsigned int, returns -1 if it fails
593static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
594 size_t max = SIZE_MAX) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700595 if (!ptr) {
Traian Schiau59763032015-04-10 15:51:39 +0300596 return false;
597 }
598
Mark Salyzyn5f606602017-02-10 13:09:07 -0800599 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700600 errno = 0;
601 size_t ret = (size_t)strtoll(ptr, &endp, 0);
602
603 if (endp[0] || errno) {
604 return false;
605 }
606
607 if ((ret > max) || (ret < min)) {
Traian Schiau59763032015-04-10 15:51:39 +0300608 return false;
609 }
610
611 *val = ret;
612 return true;
613}
614
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800615static void logcat_panic(android_logcat_context_internal* context,
616 enum helpType showHelp, const char* fmt, ...) {
617 context->retval = EXIT_FAILURE;
618 if (!context->error) {
619 context->stop = true;
620 return;
621 }
622
Mark Salyzyn5f606602017-02-10 13:09:07 -0800623 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700624 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800625 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700626 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300627
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700628 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800629 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800630 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800631 break;
632 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800633 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800634 break;
635 case HELP_FALSE:
636 default:
637 break;
Traian Schiau59763032015-04-10 15:51:39 +0300638 }
639
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800640 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300641}
642
Mark Salyzyn5f606602017-02-10 13:09:07 -0800643static char* parseTime(log_time& t, const char* cp) {
644 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700645 if (ep) {
646 return ep;
647 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700648 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
649 if (ep) {
650 return ep;
651 }
652 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700653}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700654
Mark Salyzyn31961062016-08-04 07:43:46 -0700655// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn5f606602017-02-10 13:09:07 -0800656static log_time lastLogTime(char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700657 log_time retval(log_time::EPOCH);
658 if (!outputFileName) {
659 return retval;
660 }
661
Mark Salyzynf3555d92015-05-27 07:39:56 -0700662 std::string directory;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800663 char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700664 if (!file) {
665 directory = ".";
666 file = outputFileName;
667 } else {
668 *file = '\0';
669 directory = outputFileName;
670 *file = '/';
671 ++file;
672 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700673
Mark Salyzyn5f606602017-02-10 13:09:07 -0800674 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
675 closedir);
Mark Salyzync18c2132016-04-01 07:52:20 -0700676 if (!dir.get()) {
677 return retval;
678 }
679
Mark Salyzyn31961062016-08-04 07:43:46 -0700680 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700681
Mark Salyzynf3555d92015-05-27 07:39:56 -0700682 size_t len = strlen(file);
683 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800684 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700685
Mark Salyzynf3555d92015-05-27 07:39:56 -0700686 while ((dp = readdir(dir.get())) != NULL) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800687 if ((dp->d_type != DT_REG) || (strncmp(dp->d_name, file, len) != 0) ||
688 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
689 (strtoll(dp->d_name + 1, NULL, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700690 continue;
691 }
692
693 std::string file_name = directory;
694 file_name += "/";
695 file_name += dp->d_name;
696 std::string file;
697 if (!android::base::ReadFileToString(file_name, &file)) {
698 continue;
699 }
700
701 bool found = false;
702 for (const auto& line : android::base::Split(file, "\n")) {
703 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800704 char* ep = parseTime(t, line.c_str());
Mark Salyzynf3555d92015-05-27 07:39:56 -0700705 if (!ep || (*ep != ' ')) {
706 continue;
707 }
708 // determine the time precision of the logs (eg: msec or usec)
709 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
710 if (t.tv_nsec % (mod * 10)) {
711 modulo.tv_nsec = mod;
712 break;
713 }
714 }
715 // We filter any times later than current as we may not have the
716 // year stored with each log entry. Also, since it is possible for
717 // entries to be recorded out of order (very rare) we select the
718 // maximum we find just in case.
719 if ((t < now) && (t > retval)) {
720 retval = t;
721 found = true;
722 }
723 }
724 // We count on the basename file to be the definitive end, so stop here.
725 if (!dp->d_name[len] && found) {
726 break;
727 }
728 }
729 if (retval == log_time::EPOCH) {
730 return retval;
731 }
732 // tail_time prints matching or higher, round up by the modulo to prevent
733 // a replay of the last entry we have just checked.
734 retval += modulo;
735 return retval;
736}
737
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800738const char* getenv(android_logcat_context_internal* context, const char* name) {
739 if (!context->envp || !name || !*name) return NULL;
740
741 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
742 if (strncmp(context->envp[i], name, len)) continue;
743 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
744 }
745 return NULL;
746}
747
Mark Salyzyn5f606602017-02-10 13:09:07 -0800748} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300749
Mark Salyzyn5f606602017-02-10 13:09:07 -0800750void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800751 bool blockSecurity) {
752 if (*current) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800753 return;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800754 }
755 if (blockSecurity && (android_name_to_log_id(name) == LOG_ID_SECURITY)) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800756 return;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800757 }
758 *current = name;
759}
Traian Schiau59763032015-04-10 15:51:39 +0300760
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800761static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300762 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800763 int err;
764 int hasSetLogFormat = 0;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800765 bool clearLog = false;
766 bool allSelected = false;
767 bool getLogSize = false;
768 bool getPruneList = false;
769 bool printStatistics = false;
770 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800771 unsigned long setLogSize = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800772 char* setPruneList = NULL;
773 char* setId = NULL;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800774 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800775 std::string forceFilters;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800776 log_device_t* devices = NULL;
777 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800778 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300779 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800780 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700781 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700782 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800783
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800784 // object instantiations before goto's can happen
785 log_device_t unexpected("unexpected", false);
786 const char* openDeviceFail = NULL;
787 const char* clearFail = NULL;
788 const char* setSizeFail = NULL;
789 const char* getSizeFail = NULL;
790 int argc = context->argc;
791 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800792
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800793 context->output = stdout;
794 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800795
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800796 for (int i = 0; i < argc; ++i) {
797 // Simulate shell stderr redirect parsing
798 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
799
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800800 // Append to file not implemented, just open file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800801 size_t skip = (argv[i][2] == '>') + 2;
802 if (!strcmp(&argv[i][skip], "/dev/null")) {
803 context->stderr_null = true;
804 } else if (!strcmp(&argv[i][skip], "&1")) {
805 context->stderr_stdout = true;
806 } else {
807 // stderr file redirections are not supported
808 fprintf(context->stderr_stdout ? stdout : stderr,
809 "stderr redirection to file %s unsupported, skipping\n",
810 &argv[i][skip]);
811 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800812 // Only the first one
813 break;
814 }
815
816 const char* filename = NULL;
817 for (int i = 0; i < argc; ++i) {
818 // Simulate shell stdout redirect parsing
819 if (argv[i][0] != '>') continue;
820
821 // Append to file not implemented, just open file
822 filename = &argv[i][(argv[i][1] == '>') + 1];
823 // Only the first one
824 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800825 }
826
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800827 // Deal with setting up file descriptors and FILE pointers
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800828 if (context->error_fd >= 0) { // Is an error file descriptor supplied?
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800829 if (context->error_fd == context->output_fd) {
830 context->stderr_stdout = true;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800831 } else if (context->stderr_null) { // redirection told us to close it
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800832 close(context->error_fd);
833 context->error_fd = -1;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800834 } else { // All Ok, convert error to a FILE pointer
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800835 context->error = fdopen(context->error_fd, "web");
836 if (!context->error) {
837 context->retval = -errno;
838 fprintf(context->stderr_stdout ? stdout : stderr,
839 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
840 strerror(errno));
841 goto exit;
842 }
843 }
844 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800845 if (context->output_fd >= 0) { // Is an output file descriptor supplied?
846 if (filename) { // redirect to file, close the supplied file descriptor.
847 close(context->output_fd);
848 context->output_fd = -1;
849 } else { // All Ok, convert output to a FILE pointer
850 context->output = fdopen(context->output_fd, "web");
851 if (!context->output) {
852 context->retval = -errno;
853 fprintf(context->stderr_stdout ? stdout : context->error,
854 "Failed to fdopen(output_fd=%d) %s\n",
855 context->output_fd, strerror(errno));
856 goto exit;
857 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800858 }
859 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800860 if (filename) { // We supplied an output file redirected in command line
861 context->output = fopen(filename, "web");
862 }
863 // Deal with 2>&1
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800864 if (context->stderr_stdout) context->error = context->output;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800865 // Deal with 2>/dev/null
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800866 if (context->stderr_null) {
867 context->error_fd = -1;
868 context->error = NULL;
869 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800870 // Only happens if output=stdout or output=filename
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800871 if ((context->output_fd < 0) && context->output) {
872 context->output_fd = fileno(context->output);
873 }
874 // Only happens if error=stdout || error=stderr
875 if ((context->error_fd < 0) && context->error) {
876 context->error_fd = fileno(context->error);
877 }
878
879 context->logformat = android_log_format_new();
880
881 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
882 show_help(context);
883 context->retval = EXIT_SUCCESS;
884 goto exit;
885 }
886
887 // danger: getopt is _not_ reentrant
888 optind = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889 for (;;) {
890 int ret;
891
Kristian Monsen562e5132015-06-05 14:10:12 -0700892 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700893 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700894 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800895 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700896 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800897 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700898 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800899 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700900 static const struct option long_options[] = {
Mark Salyzynf8bff872015-11-30 12:57:56 -0800901 { "binary", no_argument, NULL, 'B' },
902 { "buffer", required_argument, NULL, 'b' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700903 { "buffer-size", optional_argument, NULL, 'g' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800904 { "clear", no_argument, NULL, 'c' },
Mark Salyzyn538bc122016-11-16 15:28:31 -0800905 { debug_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800906 { "dividers", no_argument, NULL, 'D' },
907 { "file", required_argument, NULL, 'f' },
908 { "format", required_argument, NULL, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700909 // hidden and undocumented reserved alias for --regex
910 { "grep", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700911 // hidden and undocumented reserved alias for --max-count
912 { "head", required_argument, NULL, 'm' },
Mark Salyzyn02687e72016-08-03 14:20:41 -0700913 { id_str, required_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800914 { "last", no_argument, NULL, 'L' },
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700915 { "max-count", required_argument, NULL, 'm' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700916 { pid_str, required_argument, NULL, 0 },
Mark Salyzync9202772016-03-30 09:38:31 -0700917 { print_str, no_argument, NULL, 0 },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800918 { "prune", optional_argument, NULL, 'p' },
Casey Dahlindc42a872016-03-17 16:18:55 -0700919 { "regex", required_argument, NULL, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700920 { "rotate-count", required_argument, NULL, 'n' },
921 { "rotate-kbytes", required_argument, NULL, 'r' },
Mark Salyzynf8bff872015-11-30 12:57:56 -0800922 { "statistics", no_argument, NULL, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700923 // hidden and undocumented reserved alias for -t
924 { "tail", required_argument, NULL, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800925 // support, but ignore and do not document, the optional argument
926 { wrap_str, optional_argument, NULL, 0 },
Kristian Monsen562e5132015-06-05 14:10:12 -0700927 { NULL, 0, NULL, 0 }
928 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800929 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700930
Mark Salyzyn5f606602017-02-10 13:09:07 -0800931 ret = getopt_long(argc, argv,
932 ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
933 &option_index);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800934
935 if (ret < 0) {
936 break;
937 }
938
Kristian Monsen562e5132015-06-05 14:10:12 -0700939 switch (ret) {
940 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700941 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700942 if (long_options[option_index].name == pid_str) {
943 // ToDo: determine runtime PID_MAX?
944 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800945 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Kristian Monsen562e5132015-06-05 14:10:12 -0700946 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800947 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700948 }
949 break;
950 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800951 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800952 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800953 ANDROID_LOG_NONBLOCK;
954 // ToDo: implement API that supports setting a wrap timeout
955 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
956 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800957 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800958 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800959 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800960 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800961 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
962 context->error) {
963 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800964 "WARNING: %s %u seconds, ignoring %zu\n",
965 long_options[option_index].name,
966 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
967 }
968 break;
969 }
Mark Salyzync9202772016-03-30 09:38:31 -0700970 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800971 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700972 break;
973 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800974 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800975 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800976 break;
977 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700978 if (long_options[option_index].name == id_str) {
979 setId = optarg && optarg[0] ? optarg : NULL;
980 break;
981 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800982 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700983
Mark Salyzyn95132e92013-11-22 10:55:48 -0800984 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800985 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800986 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800987 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800988
989 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800990 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800991 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800992 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800993
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800994 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800995 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
996 ANDROID_LOG_NONBLOCK;
997 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800998
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -08001000 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001001 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001002
Dan Egnord1d3b6d2010-03-11 20:32:17 -08001003 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001004 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -08001005 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001006 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -08001007 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001008 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001009 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001010 if (!cp) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001011 logcat_panic(context, HELP_FALSE,
Mark Salyzyn5f606602017-02-10 13:09:07 -08001012 "-%c \"%s\" not in time format\n", ret,
1013 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001014 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001015 }
1016 if (*cp) {
1017 char c = *cp;
1018 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001019 if (context->error) {
1020 fprintf(
1021 context->error,
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001022 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
1023 ret, optarg, c, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001024 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001025 *cp = c;
1026 }
1027 } else {
Traian Schiau59763032015-04-10 15:51:39 +03001028 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001029 if (context->error) {
1030 fprintf(context->error,
1031 "WARNING: -%c %s invalid, setting to 1\n",
1032 ret, optarg);
1033 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001034 tail_lines = 1;
1035 }
1036 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001037 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -08001038
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001039 case 'D':
1040 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001041 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001042
Casey Dahlindc42a872016-03-17 16:18:55 -07001043 case 'e':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001044 context->regex = new pcrecpp::RE(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001045 break;
Casey Dahlindc42a872016-03-17 16:18:55 -07001046
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001047 case 'm': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001048 char* end = NULL;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001049 if (!getSizeTArg(optarg, &context->maxCount)) {
1050 logcat_panic(context, HELP_FALSE,
1051 "-%c \"%s\" isn't an "
1052 "integer greater than zero\n",
1053 ret, optarg);
1054 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001055 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001056 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001057
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001058 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001059 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001060 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001061 break;
1062 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001063 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001064
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001065 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001066 char* cp;
Traian Schiau59763032015-04-10 15:51:39 +03001067 if (strtoll(optarg, &cp, 0) > 0) {
1068 setLogSize = strtoll(optarg, &cp, 0);
1069 } else {
1070 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001071 }
1072
Mark Salyzyn5f606602017-02-10 13:09:07 -08001073 switch (*cp) {
1074 case 'g':
1075 case 'G':
1076 setLogSize *= 1024;
1077 // FALLTHRU
1078 case 'm':
1079 case 'M':
1080 setLogSize *= 1024;
1081 // FALLTHRU
1082 case 'k':
1083 case 'K':
1084 setLogSize *= 1024;
1085 // FALLTHRU
1086 case '\0':
1087 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001088
Mark Salyzyn5f606602017-02-10 13:09:07 -08001089 default:
1090 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001091 }
1092
1093 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001094 logcat_panic(context, HELP_FALSE,
1095 "ERROR: -G <num><multiplier>\n");
1096 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001097 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001098 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001099
1100 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001101 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001102 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001103 break;
1104 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001105 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001106
1107 case 'P':
1108 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001109 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001110
Joe Onorato6fa09a02010-02-26 10:04:23 -08001111 case 'b': {
Mark Salyzyn45177732016-04-11 14:03:48 -07001112 unsigned idMask = 0;
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001113 while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
1114 if (strcmp(optarg, "default") == 0) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001115 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001116 (1 << LOG_ID_CRASH);
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001117 } else if (strcmp(optarg, "all") == 0) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001118 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001119 idMask = (unsigned)-1;
1120 } else {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001121 log_id_t log_id = android_name_to_log_id(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001122 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001123
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001124 if (strcmp(name, optarg) != 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001125 logcat_panic(context, HELP_TRUE,
1126 "unknown buffer %s\n", optarg);
1127 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001128 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001129 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001130 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001131 }
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001132 optarg = NULL;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001133 }
1134
Mark Salyzyn45177732016-04-11 14:03:48 -07001135 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001136 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001137 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001138
Mark Salyzyn45177732016-04-11 14:03:48 -07001139 if (log_id != (log_id_t)i) {
1140 continue;
1141 }
1142 if ((idMask & (1 << i)) == 0) {
1143 continue;
1144 }
Mark Salyzyn083b0372015-12-04 10:59:45 -08001145
Mark Salyzyn45177732016-04-11 14:03:48 -07001146 bool found = false;
1147 for (dev = devices; dev; dev = dev->next) {
1148 if (!strcmp(name, dev->device)) {
1149 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001150 break;
1151 }
Mark Salyzyn45177732016-04-11 14:03:48 -07001152 if (!dev->next) {
Mark Salyzyn083b0372015-12-04 10:59:45 -08001153 break;
1154 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001155 }
Mark Salyzyn45177732016-04-11 14:03:48 -07001156 if (found) {
1157 continue;
1158 }
1159
Mark Salyzyn5f606602017-02-10 13:09:07 -08001160 bool binary =
1161 !strcmp(name, "events") || !strcmp(name, "security");
Mark Salyzyn45177732016-04-11 14:03:48 -07001162 log_device_t* d = new log_device_t(name, binary);
1163
Mark Salyzyn083b0372015-12-04 10:59:45 -08001164 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001165 dev->next = d;
1166 dev = d;
1167 } else {
1168 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001169 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001170 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001171 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001172 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001173
1174 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001175 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001176 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177
1178 case 'f':
Mark Salyzyn9812fc42015-10-06 08:59:02 -07001179 if ((tail_time == log_time::EPOCH) && (tail_lines == 0)) {
Mark Salyzynf3555d92015-05-27 07:39:56 -07001180 tail_time = lastLogTime(optarg);
1181 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001182 // redirect output to a file
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001183 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001184 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001186 case 'r':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001187 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1188 logcat_panic(context, HELP_TRUE,
1189 "Invalid parameter \"%s\" to -r\n", optarg);
1190 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001191 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001192 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001193
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001194 case 'n':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001195 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1196 logcat_panic(context, HELP_TRUE,
1197 "Invalid parameter \"%s\" to -n\n", optarg);
1198 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001199 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001200 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201
1202 case 'v':
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001203 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001204 show_format_help(context);
1205 context->retval = EXIT_SUCCESS;
1206 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001207 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001208 err = setLogFormat(context, optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001209 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001210 logcat_panic(context, HELP_FORMAT,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001211 "Invalid parameter \"%s\" to -v\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001212 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001213 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001214 hasSetLogFormat |= err;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001215 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001216
1217 case 'Q':
Mark Salyzyn5f606602017-02-10 13:09:07 -08001218#define KERNEL_OPTION "androidboot.logcat="
1219#define CONSOLE_OPTION "androidboot.console="
1220 // This is a *hidden* option used to start a version of logcat
1221 // in an emulated device only. It basically looks for
1222 // androidboot.logcat= on the kernel command line. If
1223 // something is found, it extracts a log filter and uses it to
1224 // run the program. If nothing is found, the program should
1225 // quit immediately.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001226 {
Mark Salyzynf3290292017-02-10 13:09:07 -08001227 std::string cmdline;
1228 android::base::ReadFileToString("/proc/cmdline", &cmdline);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001229
Mark Salyzynf3290292017-02-10 13:09:07 -08001230 const char* logcat = strstr(cmdline.c_str(), KERNEL_OPTION);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001231 // if nothing found or invalid filters, exit quietly
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001232 if (!logcat) {
1233 context->retval = EXIT_SUCCESS;
1234 goto exit;
1235 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001236
1237 const char* p = logcat + strlen(KERNEL_OPTION);
1238 const char* q = strpbrk(p, " \t\n\r");
1239 if (!q) q = p + strlen(p);
1240 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001241
Mark Salyzyn5f606602017-02-10 13:09:07 -08001242 // redirect our output to the emulator console
Mark Salyzynf3290292017-02-10 13:09:07 -08001243 const char* console =
1244 strstr(cmdline.c_str(), CONSOLE_OPTION);
1245 if (!console) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001246
Mark Salyzynf3290292017-02-10 13:09:07 -08001247 p = console + strlen(CONSOLE_OPTION);
1248 q = strpbrk(p, " \t\n\r");
1249 int len = q ? q - p : strlen(p);
1250 std::string devname = "/dev/" + std::string(p, len);
1251 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001252
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001253 if (context->error) {
1254 fprintf(context->error, "logcat using %s\n",
1255 devname.c_str());
1256 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001257
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001258 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001259 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001260 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001261
1262 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001263 android::close_output(context);
1264 android::close_error(context);
1265 context->stderr_stdout = true;
1266 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001267 context->output_fd = fileno(fp);
1268 if (context->stderr_null) break;
1269 context->stderr_stdout = true;
1270 context->error = fp;
1271 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001272 }
1273 break;
1274
Mark Salyzyn34facab2014-02-06 14:48:50 -08001275 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001276 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001277 break;
1278
Traian Schiau59763032015-04-10 15:51:39 +03001279 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001280 logcat_panic(context, HELP_TRUE,
1281 "Option -%c needs an argument\n", optopt);
1282 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001283
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001284 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001285 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
1286 optopt);
1287 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001288 }
1289 }
1290
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001291 if (context->maxCount && got_t) {
1292 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001293 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001294 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001295 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001296 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001297 // One day it would be nice if --print -v color and --regex <expr>
1298 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001299 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001300 if (context->error) {
1301 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001302 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001303 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001304 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001305 }
1306 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001307 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001308
Joe Onorato6fa09a02010-02-26 10:04:23 -08001309 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001310 dev = devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001311 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001312 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001313 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001314 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001315 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001316 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001317 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001318 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001319 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001320 }
1321
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001322 if (context->logRotateSizeKBytes != 0 && context->outputFileName == NULL) {
1323 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1324 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001325 }
1326
Mark Salyzyn02687e72016-08-03 14:20:41 -07001327 if (setId != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001328 if (context->outputFileName == NULL) {
1329 logcat_panic(context, HELP_TRUE,
1330 "--id='%s' requires -f as well\n", setId);
1331 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001332 }
1333
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001334 std::string file_name = android::base::StringPrintf(
1335 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001336 std::string file;
1337 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001338 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1339 getuid(), getgid());
Mark Salyzyn02687e72016-08-03 14:20:41 -07001340 if (!file_ok || (file.compare(setId) == 0)) {
1341 setId = NULL;
1342 }
1343 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001344
1345 if (hasSetLogFormat == 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001346 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001347
1348 if (logFormat != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001349 err = setLogFormat(context, logFormat);
1350 if ((err < 0) && context->error) {
1351 fprintf(context->error,
1352 "invalid format in ANDROID_PRINTF_LOG '%s'\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -08001353 logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001354 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001355 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001356 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001357 }
1358 }
1359
Mark Salyzynf3290292017-02-10 13:09:07 -08001360 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001361 err = android_log_addFilterString(context->logformat,
1362 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001363 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001364 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001365 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001366 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001367 }
1368 } else if (argc == optind) {
1369 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001370 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001371
1372 if (env_tags_orig != NULL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001373 err = android_log_addFilterString(context->logformat,
1374 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001375
Mark Salyzyn95132e92013-11-22 10:55:48 -08001376 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001377 logcat_panic(context, HELP_TRUE,
1378 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1379 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001380 }
1381 }
1382 } else {
1383 // Add from commandline
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001384 for (int i = optind ; i < argc ; i++) {
1385 // skip stderr redirections of _all_ kinds
1386 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001387 // skip stdout redirections of _all_ kinds
1388 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001389
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001390 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001391 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001392 logcat_panic(context, HELP_TRUE,
1393 "Invalid filter expression '%s'\n", argv[i]);
1394 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001395 }
1396 }
1397 }
1398
Joe Onorato6fa09a02010-02-26 10:04:23 -08001399 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001400 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001401 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001402 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001403 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001404 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001405 // We have three orthogonal actions below to clear, set log size and
1406 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001407 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001408 dev->logger_list = logger_list;
1409 dev->logger = android_logger_open(logger_list,
1410 android_name_to_log_id(dev->device));
1411 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001412 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001413 dev = dev->next;
1414 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001415 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001416
Mark Salyzyn02687e72016-08-03 14:20:41 -07001417 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001418 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001419 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001420 (context->maxRotatedLogs > 0) ?
1421 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1422 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001423
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001424 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001425 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001426
1427 if (i == 0) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001428 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001429 "%s", context->outputFileName);
1430 } else {
1431 file = android::base::StringPrintf("%s.%.*d",
1432 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001433 }
1434
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001435 if (file.length() == 0) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001436 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001437 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001438 break;
1439 }
1440
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001441 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001442
1443 if (err < 0 && errno != ENOENT && clearFail == NULL) {
1444 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001445 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001446 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001447 }
1448 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001449 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001450 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001451 }
1452
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001453 if (setLogSize) {
1454 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001455 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001456 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001457 }
1458
Joe Onorato6fa09a02010-02-26 10:04:23 -08001459 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001460 long size = android_logger_get_log_size(dev->logger);
1461 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001462
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001463 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001464 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001465 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001466 std::string str = android::base::StringPrintf(
1467 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1468 " max entry is %db, max payload is %db\n",
1469 dev->device,
1470 value_of_size(size), multiplier_of_size(size),
1471 value_of_size(readable), multiplier_of_size(readable),
1472 (int)LOGGER_ENTRY_MAX_LEN,
1473 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1474 TEMP_FAILURE_RETRY(write(context->output_fd,
1475 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001476 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001477 }
1478
1479 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001480 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001481
1482 context->retval = EXIT_SUCCESS;
1483
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001484 // report any errors in the above loop and exit
1485 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001486 logcat_panic(context, HELP_FALSE,
1487 "Unable to open log device '%s'\n", openDeviceFail);
1488 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001489 }
1490 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001491 logcat_panic(context, HELP_FALSE,
1492 "failed to clear the '%s' log\n", clearFail);
1493 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001494 }
1495 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001496 logcat_panic(context, HELP_FALSE,
1497 "failed to set the '%s' log size\n", setSizeFail);
1498 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001499 }
1500 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001501 logcat_panic(context, HELP_FALSE,
1502 "failed to get the readable '%s' log size", getSizeFail);
1503 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001504 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001505
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001506 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001507 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001508 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001509 size_t bLen = len + 32;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001510 char* buf = NULL;
Traian Schiau59763032015-04-10 15:51:39 +03001511 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1512 buf[len] = '\0';
1513 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001514 logcat_panic(context, HELP_FALSE,
1515 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001516 }
1517 free(buf);
1518 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001519 logcat_panic(context, HELP_FALSE,
1520 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001521 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001522 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001523 }
1524
Mark Salyzyn1c950472014-04-01 17:19:47 -07001525 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001526 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001527 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001528
Mark Salyzyn5f606602017-02-10 13:09:07 -08001529 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
1530 delete[] buf, buf = NULL, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001531 if (getPruneList) {
1532 android_logger_get_prune_list(logger_list, buf, len);
1533 } else {
1534 android_logger_get_statistics(logger_list, buf, len);
1535 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001536 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001537 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001538 delete[] buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001539 buf = NULL;
1540 break;
1541 }
Traian Schiau59763032015-04-10 15:51:39 +03001542 size_t ret = atol(buf) + 1;
1543 if (ret <= len) {
1544 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001545 break;
1546 }
Traian Schiau59763032015-04-10 15:51:39 +03001547 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001548 }
1549
1550 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001551 logcat_panic(context, HELP_FALSE, "failed to read data");
1552 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001553 }
1554
1555 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001556 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001557 *cp = '\0';
1558 bool truncated = *--cp != '\f';
1559 if (!truncated) {
1560 *cp = '\0';
1561 }
1562
1563 // squash out the byte count
1564 cp = buf;
1565 if (!truncated) {
Mark Salyzyn22e287d2014-03-21 13:12:16 -07001566 while (isdigit(*cp)) {
1567 ++cp;
1568 }
1569 if (*cp == '\n') {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001570 ++cp;
1571 }
1572 }
1573
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001574 len = strlen(cp);
1575 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001576 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001577 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001578 }
1579
Mark Salyzyn5f606602017-02-10 13:09:07 -08001580 if (getLogSize || setLogSize || clearLog) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001581 goto close;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001582 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001583
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001584 setupOutputAndSchedulingPolicy(context, (mode & ANDROID_LOG_NONBLOCK) == 0);
1585 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001586
Mark Salyzyn5f606602017-02-10 13:09:07 -08001587 // LOG_EVENT_INT(10, 12345);
1588 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1589 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001590
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001591 dev = NULL;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001592
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001593 while (!context->stop &&
1594 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001595 struct log_msg log_msg;
1596 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001597 if (ret == 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001598 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1599 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001600 }
1601
1602 if (ret < 0) {
1603 if (ret == -EAGAIN) {
1604 break;
1605 }
1606
1607 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001608 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1609 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001610 }
1611 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001612 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1613 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001614 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001615 logcat_panic(context, HELP_FALSE, "logcat read failure");
1616 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001617 }
1618
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001619 log_device_t* d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001620 for (d = devices; d; d = d->next) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001621 if (android_name_to_log_id(d->device) == log_msg.id()) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001622 break;
1623 }
1624 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001625 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001626 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001627 d = &unexpected;
1628 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001629 }
1630
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001631 if (dev != d) {
1632 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001633 maybePrintStart(context, dev, printDividers);
1634 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001635 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001636 if (context->printBinary) {
1637 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001638 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001639 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001640 }
1641 }
1642
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001643close:
Mark Salyzyn95132e92013-11-22 10:55:48 -08001644 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001645
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001646exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001647 // close write end of pipe to help things along
1648 if (context->output_fd == context->fds[1]) {
1649 android::close_output(context);
1650 }
1651 if (context->error_fd == context->fds[1]) {
1652 android::close_error(context);
1653 }
1654 if (context->fds[1] >= 0) {
1655 // NB: should be closed by the above
1656 int save_errno = errno;
1657 close(context->fds[1]);
1658 errno = save_errno;
1659 context->fds[1] = -1;
1660 }
1661 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001662 return context->retval;
1663}
1664
1665// Can block
1666int android_logcat_run_command(android_logcat_context ctx,
1667 int output, int error,
1668 int argc, char* const* argv,
1669 char* const* envp) {
1670 android_logcat_context_internal* context = ctx;
1671
1672 context->output_fd = output;
1673 context->error_fd = error;
1674 context->argc = argc;
1675 context->argv = argv;
1676 context->envp = envp;
1677 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001678 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001679 return __logcat(context);
1680}
1681
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001682// starts a thread, opens a pipe, returns reading end.
1683int android_logcat_run_command_thread(android_logcat_context ctx,
1684 int argc, char* const* argv,
1685 char* const* envp) {
1686 android_logcat_context_internal* context = ctx;
1687
1688 int save_errno = EBUSY;
1689 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) {
1690 goto exit;
1691 }
1692
1693 if (pipe(context->fds) < 0) {
1694 save_errno = errno;
1695 goto exit;
1696 }
1697
1698 pthread_attr_t attr;
1699 if (pthread_attr_init(&attr)) {
1700 save_errno = errno;
1701 goto close_exit;
1702 }
1703
1704 struct sched_param param;
1705 memset(&param, 0, sizeof(param));
1706 pthread_attr_setschedparam(&attr, &param);
1707 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1708 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1709 int save_errno = errno;
1710 goto pthread_attr_exit;
1711 }
1712
1713 context->stop = false;
1714 context->thread_stopped = false;
1715 context->output_fd = context->fds[1];
1716 // save off arguments so they remain while thread is active.
1717 for (int i = 0; i < argc; ++i) {
1718 context->args.push_back(std::string(argv[i]));
1719 }
1720 // save off environment so they remain while thread is active.
1721 if (envp) for (size_t i = 0; envp[i]; ++i) {
1722 context->envs.push_back(std::string(envp[i]));
1723 }
1724
1725 for (auto& str : context->args) {
1726 context->argv_hold.push_back(str.c_str());
1727 }
1728 context->argv_hold.push_back(NULL);
1729 for (auto& str : context->envs) {
1730 context->envp_hold.push_back(str.c_str());
1731 }
1732 context->envp_hold.push_back(NULL);
1733
1734 context->argc = context->argv_hold.size() - 1;
1735 context->argv = (char* const*)&context->argv_hold[0];
1736 context->envp = (char* const*)&context->envp_hold[0];
1737
1738#ifdef DEBUG
1739 fprintf(stderr, "argv[%d] = {", context->argc);
1740 for (auto str : context->argv_hold) {
1741 fprintf(stderr, " \"%s\"", str ?: "NULL");
1742 }
1743 fprintf(stderr, " }\n");
1744 fflush(stderr);
1745#endif
1746 context->retval = EXIT_SUCCESS;
1747 if (pthread_create(&context->thr, &attr,
1748 (void*(*)(void*))__logcat, context)) {
1749 int save_errno = errno;
1750 goto argv_exit;
1751 }
1752 pthread_attr_destroy(&attr);
1753
1754 return context->fds[0];
1755
1756argv_exit:
1757 context->argv_hold.clear();
1758 context->args.clear();
1759 context->envp_hold.clear();
1760 context->envs.clear();
1761pthread_attr_exit:
1762 pthread_attr_destroy(&attr);
1763close_exit:
1764 close(context->fds[0]);
1765 context->fds[0] = -1;
1766 close(context->fds[1]);
1767 context->fds[1] = -1;
1768exit:
1769 errno = save_errno;
1770 context->stop = true;
1771 context->thread_stopped = true;
1772 context->retval = EXIT_FAILURE;
1773 return -1;
1774}
1775
1776// test if the thread is still doing 'stuff'
1777int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1778 android_logcat_context_internal* context = ctx;
1779
1780 return context->thread_stopped == false;
1781}
1782
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001783// Finished with context
1784int android_logcat_destroy(android_logcat_context* ctx) {
1785 android_logcat_context_internal* context = *ctx;
1786
1787 *ctx = NULL;
1788
1789 context->stop = true;
1790
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001791 while (context->thread_stopped == false) {
1792 sched_yield();
1793 }
1794
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001795 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001796 context->argv_hold.clear();
1797 context->args.clear();
1798 context->envp_hold.clear();
1799 context->envs.clear();
1800 if (context->fds[0] >= 0) {
1801 close(context->fds[0]);
1802 context->fds[0] = -1;
1803 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001804 android::close_output(context);
1805 android::close_error(context);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001806 if (context->fds[1] >= 0) {
1807 // NB: could be closed by the above fclose(s), ignore error.
1808 int save_errno = errno;
1809 close(context->fds[1]);
1810 errno = save_errno;
1811 context->fds[1] = -1;
1812 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001813
1814 android_closeEventTagMap(context->eventTagMap);
1815
1816 int retval = context->retval;
1817
1818 free(context);
1819
1820 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001821}