blob: 077332a6407a3a80c6964d9277081567b11c7387 [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 Salyzynde022a82017-03-01 08:30:06 -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));
Mark Salyzynde022a82017-03-01 08:30:06 -0800111 if (!context) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800112
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;
Mark Salyzynde022a82017-03-01 08:30:06 -0800142 next = nullptr;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800143 printed = false;
Mark Salyzynde022a82017-03-01 08:30:06 -0800144 logger = nullptr;
145 logger_list = nullptr;
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) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800165 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800166 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 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800185 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800186 }
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) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800201 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800202 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 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800221 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800222 }
223 if (context->error_fd >= 0) {
224 if ((context->error_fd != fileno(stdout)) &&
225 (context->error_fd != fileno(stderr))) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800226 if (context->fds[1] == context->error_fd) context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800227 close(context->error_fd);
228 }
229 context->error_fd = -1;
230 }
231}
232
233static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234 int err;
235
236 // Can't rotate logs if we're not outputting to a file
Mark Salyzynde022a82017-03-01 08:30:06 -0800237 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800238
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800239 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240
Mark Salyzyn5f606602017-02-10 13:09:07 -0800241 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800242 // maxRotatedLogs in decimal. eg:
243 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800244 // -> log10(30) == 1.477
245 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700246 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800247 (context->maxRotatedLogs > 0)
248 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
249 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700250
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800251 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700252 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800253 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700255 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800256 if (!(i - 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800257 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800259 file0 =
260 android::base::StringPrintf("%s.%.*d", context->outputFileName,
261 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 }
263
Mark Salyzynde022a82017-03-01 08:30:06 -0800264 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300265 perror("while rotating log files");
266 break;
267 }
268
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700269 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270
271 if (err < 0 && errno != ENOENT) {
272 perror("while rotating log files");
273 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274 }
275
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800276 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800278 if (context->output_fd < 0) {
279 logcat_panic(context, HELP_FALSE, "couldn't open output file");
280 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800282 context->output = fdopen(context->output_fd, "web");
Mark Salyzynde022a82017-03-01 08:30:06 -0800283 if (!context->output) {
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800284 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
285 return;
286 }
287 if (context->stderr_stdout) {
288 close_error(context);
289 context->error = context->output;
290 context->error_fd = context->output_fd;
291 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800292
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800293 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294}
295
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800296void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800297 size_t size = buf->len();
298
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800299 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800300}
301
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800302static bool regexOk(android_logcat_context_internal* context,
303 const AndroidLogEntry& entry) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800304 if (!context->regex) return true;
Casey Dahlindc42a872016-03-17 16:18:55 -0700305
Casey Dahlindc42a872016-03-17 16:18:55 -0700306 std::string messageString(entry.message, entry.messageLen);
307
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800308 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700309}
310
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800311static void processBuffer(android_logcat_context_internal* context,
312 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700313 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800314 int err;
315 AndroidLogEntry entry;
316 char binaryMsgBuf[1024];
317
Joe Onorato6fa09a02010-02-26 10:04:23 -0800318 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800319 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800320 context->eventTagMap = android_openEventTagMap(nullptr);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800321 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800322 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800323 err = android_log_processBinaryLogBuffer(
324 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
325 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800326 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800327 // entry.priority, entry.messageLen, entry.message);
328 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800329 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800331 if ((err < 0) && !context->debug) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800332
Mark Salyzyn5f606602017-02-10 13:09:07 -0800333 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800334 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800335 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800336 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800337
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800338 context->printCount += match;
339 if (match || context->printItAnyways) {
340 bytesWritten = android_log_printLogLine(context->logformat,
341 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700342
Mark Salyzync9202772016-03-30 09:38:31 -0700343 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800344 logcat_panic(context, HELP_FALSE, "output error");
345 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700346 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800347 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348 }
349
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800350 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800352 if (context->logRotateSizeKBytes > 0 &&
353 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
354 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356}
357
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800358static void maybePrintStart(android_logcat_context_internal* context,
359 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800360 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800361 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800362 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800363 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800364 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800365 if (write(context->output_fd, buf, strlen(buf)) < 0) {
366 logcat_panic(context, HELP_FALSE, "output error");
367 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800368 }
369 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800370 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800371 }
372}
373
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800374static void setupOutputAndSchedulingPolicy(
375 android_logcat_context_internal* context, bool blocking) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800376 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377
Mark Salyzynad5e4112016-08-04 07:53:52 -0700378 if (blocking) {
379 // Lower priority and set to batch scheduling if we are saving
380 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800381 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
382 fprintf(context->error,
383 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700384 }
385
386 struct sched_param param;
387 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800388 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700389 fprintf(stderr, "failed to set to batch scheduler\n");
390 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800392 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
393 context->error) {
394 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700395 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800396 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700397
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800398 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700399
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800400 context->output_fd = openLogFile(context->outputFileName);
401
402 if (context->output_fd < 0) {
403 logcat_panic(context, HELP_FALSE, "couldn't open output file");
404 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700405 }
406
407 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800408 if (fstat(context->output_fd, &statbuf) == -1) {
409 close_output(context);
410 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
411 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700412 }
413
Mark Salyzyn5f606602017-02-10 13:09:07 -0800414 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800415 close_output(context);
416 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
417 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700418 }
419
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800420 context->output = fdopen(context->output_fd, "web");
421
422 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423}
424
Mark Salyzyn5f606602017-02-10 13:09:07 -0800425// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800426static void show_help(android_logcat_context_internal* context) {
427 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800428
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800429 const char* cmd = strrchr(context->argv[0], '/');
430 cmd = cmd ? cmd + 1 : context->argv[0];
431
432 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
433
434 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700435 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
436 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700437 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
438 " Rotate log every kbytes. Requires -f option\n"
439 " -n <count>, --rotate-count=<count>\n"
440 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700441 " --id=<id> If the signature id for logging to file changes, then clear\n"
442 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700443 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700444 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700445 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700446 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700447 " color descriptive epoch monotonic printable uid\n"
448 " usec UTC year zone\n"
Mark Salyzynb45a1752017-02-28 09:20:31 -0800449 " Multiple -v parameters or comma separated list of format and\n"
450 " format modifiers are allowed.\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800451 // private and undocumented nsec, no signal, too much noise
452 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700453 " -D, --dividers Print dividers between each log buffer\n"
454 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700455 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700456 " -d Dump the log and then exit (don't block)\n"
457 " -e <expr>, --regex=<expr>\n"
458 " Only print lines where the log message matches <expr>\n"
459 " where <expr> is a regular expression\n"
460 // Leave --head undocumented as alias for -m
461 " -m <count>, --max-count=<count>\n"
462 " Quit after printing <count> lines. This is meant to be\n"
463 " paired with --regex, but will work on its own.\n"
464 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700465 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700466 // Leave --tail undocumented as alias for -t
467 " -t <count> Print only the most recent <count> lines (implies -d)\n"
468 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
469 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
470 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700471 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700472 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700473 " -g, --buffer-size Get the size of the ring buffer.\n"
474 " -G <size>, --buffer-size=<size>\n"
475 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100476 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800477 // Leave security (Device Owner only installations) and
478 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700479 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
480 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700481 " Multiple -b parameters or comma separated list of buffers are\n"
482 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700483 " -B, --binary Output the log in binary.\n"
484 " -S, --statistics Output statistics.\n"
485 " -p, --prune Print prune white and ~black list. Service is specified as\n"
486 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700487 " with ~, otherwise weighed for longevity if unadorned. All\n"
488 " other pruning activity is oldest first. Special case ~!\n"
489 " represents an automatic quicker pruning for the noisiest\n"
490 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700491 " -P '<list> ...', --prune='<list> ...'\n"
492 " Set prune white and ~black list, using same format as\n"
493 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800494 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700495 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800496 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
497 " comes first. Improves efficiency of polling by providing\n"
498 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800500 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800501 " <tag>[:priority]\n\n"
502 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700503 " V Verbose (default for <tag>)\n"
504 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505 " I Info\n"
506 " W Warn\n"
507 " E Error\n"
508 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700509 " S Silent (suppress all output)\n"
510 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
511 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
512 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
513 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
514 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700515 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516}
517
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800518static void show_format_help(android_logcat_context_internal* context) {
519 if (!context->error) return;
520 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700521 "-v <format>, --format=<format> options:\n"
522 " Sets log print format verb and adverbs, where <format> is:\n"
523 " brief long process raw tag thread threadtime time\n"
524 " and individually flagged modifying adverbs can be added:\n"
525 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
526 "\nSingle format verbs:\n"
527 " brief — Display priority/tag and PID of the process issuing the message.\n"
528 " long — Display all metadata fields, separate messages with blank lines.\n"
529 " process — Display PID only.\n"
530 " raw — Display the raw log message, with no other metadata fields.\n"
531 " tag — Display the priority/tag only.\n"
532 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
533 " and TID of the thread issuing the message. (the default format).\n"
534 " time — Display the date, invocation time, priority/tag, and PID of the\n"
535 " process issuing the message.\n"
536 "\nAdverb modifiers can be used in combination:\n"
537 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
538 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
539 " descriptive — events logs only, descriptions from event-log-tags database.\n"
540 " epoch — Display time as seconds since Jan 1 1970.\n"
541 " monotonic — Display time as cpu seconds since last boot.\n"
542 " printable — Ensure that any binary logging content is escaped.\n"
543 " uid — If permitted, display the UID or Android ID of logged process.\n"
544 " usec — Display time down the microsecond precision.\n"
545 " UTC — Display time as UTC.\n"
546 " year — Add the year to the displayed time.\n"
547 " zone — Add the local timezone to the displayed time.\n"
548 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
549 );
550}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800551// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700552
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800553static int setLogFormat(android_logcat_context_internal* context,
554 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800555 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556
557 format = android_log_formatFromString(formatString);
558
Mark Salyzynde022a82017-03-01 08:30:06 -0800559 // invalid string?
560 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800562 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563}
564
Mark Salyzyn5f606602017-02-10 13:09:07 -0800565static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700566
Mark Salyzyn5f606602017-02-10 13:09:07 -0800567static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700568 for (unsigned i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800569 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
570 value /= 1024, ++i)
571 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700572 return value;
573}
574
Mark Salyzyn5f606602017-02-10 13:09:07 -0800575static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700576 unsigned i;
577 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800578 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
579 value /= 1024, ++i)
580 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700581 return multipliers[i];
582}
583
Mark Salyzyn5f606602017-02-10 13:09:07 -0800584// String to unsigned int, returns -1 if it fails
585static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
586 size_t max = SIZE_MAX) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800587 if (!ptr) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300588
Mark Salyzyn5f606602017-02-10 13:09:07 -0800589 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700590 errno = 0;
591 size_t ret = (size_t)strtoll(ptr, &endp, 0);
592
Mark Salyzynde022a82017-03-01 08:30:06 -0800593 if (endp[0] || errno) return false;
Kristian Monsen562e5132015-06-05 14:10:12 -0700594
Mark Salyzynde022a82017-03-01 08:30:06 -0800595 if ((ret > max) || (ret < min)) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300596
597 *val = ret;
598 return true;
599}
600
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800601static void logcat_panic(android_logcat_context_internal* context,
602 enum helpType showHelp, const char* fmt, ...) {
603 context->retval = EXIT_FAILURE;
604 if (!context->error) {
605 context->stop = true;
606 return;
607 }
608
Mark Salyzyn5f606602017-02-10 13:09:07 -0800609 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700610 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800611 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700612 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300613
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700614 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800615 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800616 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800617 break;
618 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800619 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800620 break;
621 case HELP_FALSE:
622 default:
623 break;
Traian Schiau59763032015-04-10 15:51:39 +0300624 }
625
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800626 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300627}
628
Mark Salyzyn5f606602017-02-10 13:09:07 -0800629static char* parseTime(log_time& t, const char* cp) {
630 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800631 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700632 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800633 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700634 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700635}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700636
Mark Salyzyn31961062016-08-04 07:43:46 -0700637// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn5f606602017-02-10 13:09:07 -0800638static log_time lastLogTime(char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700639 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800640 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700641
Mark Salyzynf3555d92015-05-27 07:39:56 -0700642 std::string directory;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800643 char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700644 if (!file) {
645 directory = ".";
646 file = outputFileName;
647 } else {
648 *file = '\0';
649 directory = outputFileName;
650 *file = '/';
651 ++file;
652 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700653
Mark Salyzyn5f606602017-02-10 13:09:07 -0800654 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
655 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800656 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700657
Mark Salyzyn31961062016-08-04 07:43:46 -0700658 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700659
Mark Salyzynf3555d92015-05-27 07:39:56 -0700660 size_t len = strlen(file);
661 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800662 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700663
Mark Salyzynde022a82017-03-01 08:30:06 -0800664 while (!!(dp = readdir(dir.get()))) {
665 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800666 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800667 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700668 continue;
669 }
670
671 std::string file_name = directory;
672 file_name += "/";
673 file_name += dp->d_name;
674 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800675 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700676
677 bool found = false;
678 for (const auto& line : android::base::Split(file, "\n")) {
679 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800680 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800681 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700682 // determine the time precision of the logs (eg: msec or usec)
683 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
684 if (t.tv_nsec % (mod * 10)) {
685 modulo.tv_nsec = mod;
686 break;
687 }
688 }
689 // We filter any times later than current as we may not have the
690 // year stored with each log entry. Also, since it is possible for
691 // entries to be recorded out of order (very rare) we select the
692 // maximum we find just in case.
693 if ((t < now) && (t > retval)) {
694 retval = t;
695 found = true;
696 }
697 }
698 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800699 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700700 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800701 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700702 // tail_time prints matching or higher, round up by the modulo to prevent
703 // a replay of the last entry we have just checked.
704 retval += modulo;
705 return retval;
706}
707
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800708const char* getenv(android_logcat_context_internal* context, const char* name) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800709 if (!context->envp || !name || !*name) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800710
711 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
712 if (strncmp(context->envp[i], name, len)) continue;
713 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
714 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800715 return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800716}
717
Mark Salyzyn5f606602017-02-10 13:09:07 -0800718} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300719
Mark Salyzyn5f606602017-02-10 13:09:07 -0800720void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800721 bool blockSecurity) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800722 if (*current) return;
723 if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
724 *current = name;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800725 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800726}
Traian Schiau59763032015-04-10 15:51:39 +0300727
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800728static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300729 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730 int err;
Mark Salyzynb45a1752017-02-28 09:20:31 -0800731 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800732 bool clearLog = false;
733 bool allSelected = false;
734 bool getLogSize = false;
735 bool getPruneList = false;
736 bool printStatistics = false;
737 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800738 unsigned long setLogSize = 0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800739 char* setPruneList = nullptr;
740 char* setId = nullptr;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800741 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800742 std::string forceFilters;
Mark Salyzynde022a82017-03-01 08:30:06 -0800743 log_device_t* devices = nullptr;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800744 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800745 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300746 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800747 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700748 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700749 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800751 // object instantiations before goto's can happen
752 log_device_t unexpected("unexpected", false);
Mark Salyzynde022a82017-03-01 08:30:06 -0800753 const char* openDeviceFail = nullptr;
754 const char* clearFail = nullptr;
755 const char* setSizeFail = nullptr;
756 const char* getSizeFail = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800757 int argc = context->argc;
758 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800759
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800760 context->output = stdout;
761 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800762
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800763 for (int i = 0; i < argc; ++i) {
764 // Simulate shell stderr redirect parsing
765 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
766
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800767 // Append to file not implemented, just open file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800768 size_t skip = (argv[i][2] == '>') + 2;
769 if (!strcmp(&argv[i][skip], "/dev/null")) {
770 context->stderr_null = true;
771 } else if (!strcmp(&argv[i][skip], "&1")) {
772 context->stderr_stdout = true;
773 } else {
774 // stderr file redirections are not supported
775 fprintf(context->stderr_stdout ? stdout : stderr,
776 "stderr redirection to file %s unsupported, skipping\n",
777 &argv[i][skip]);
778 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800779 // Only the first one
780 break;
781 }
782
Mark Salyzynde022a82017-03-01 08:30:06 -0800783 const char* filename = nullptr;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800784 for (int i = 0; i < argc; ++i) {
785 // Simulate shell stdout redirect parsing
786 if (argv[i][0] != '>') continue;
787
788 // Append to file not implemented, just open file
789 filename = &argv[i][(argv[i][1] == '>') + 1];
790 // Only the first one
791 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800792 }
793
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800794 // Deal with setting up file descriptors and FILE pointers
Mark Salyzynde022a82017-03-01 08:30:06 -0800795 if (context->error_fd >= 0) { // Is an error file descriptor supplied?
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800796 if (context->error_fd == context->output_fd) {
797 context->stderr_stdout = true;
Mark Salyzynde022a82017-03-01 08:30:06 -0800798 } else if (context->stderr_null) { // redirection told us to close it
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800799 close(context->error_fd);
800 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800801 } else { // All Ok, convert error to a FILE pointer
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800802 context->error = fdopen(context->error_fd, "web");
803 if (!context->error) {
804 context->retval = -errno;
805 fprintf(context->stderr_stdout ? stdout : stderr,
806 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
807 strerror(errno));
808 goto exit;
809 }
810 }
811 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800812 if (context->output_fd >= 0) { // Is an output file descriptor supplied?
813 if (filename) { // redirect to file, close supplied file descriptor.
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800814 close(context->output_fd);
815 context->output_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800816 } else { // All Ok, convert output to a FILE pointer
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800817 context->output = fdopen(context->output_fd, "web");
818 if (!context->output) {
819 context->retval = -errno;
820 fprintf(context->stderr_stdout ? stdout : context->error,
821 "Failed to fdopen(output_fd=%d) %s\n",
822 context->output_fd, strerror(errno));
823 goto exit;
824 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800825 }
826 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800827 if (filename) { // We supplied an output file redirected in command line
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800828 context->output = fopen(filename, "web");
829 }
830 // Deal with 2>&1
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800831 if (context->stderr_stdout) context->error = context->output;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800832 // Deal with 2>/dev/null
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800833 if (context->stderr_null) {
834 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800835 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800836 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800837 // Only happens if output=stdout or output=filename
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800838 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
Mark Salyzynde022a82017-03-01 08:30:06 -0800848 if (argc == 2 && !strcmp(argv[1], "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800849 show_help(context);
850 context->retval = EXIT_SUCCESS;
851 goto exit;
852 }
853
Mark Salyzynb45a1752017-02-28 09:20:31 -0800854 // meant to catch comma-delimited values, but cast a wider
855 // net for stability dealing with possible mistaken inputs.
856 static const char delimiters[] = ",:; \t\n\r\f";
857
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800858 // danger: getopt is _not_ reentrant
859 optind = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800860 for (;;) {
861 int ret;
862
Kristian Monsen562e5132015-06-05 14:10:12 -0700863 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700864 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700865 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800866 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700867 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800868 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700869 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800870 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700871 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800872 { "binary", no_argument, nullptr, 'B' },
873 { "buffer", required_argument, nullptr, 'b' },
874 { "buffer-size", optional_argument, nullptr, 'g' },
875 { "clear", no_argument, nullptr, 'c' },
876 { debug_str, no_argument, nullptr, 0 },
877 { "dividers", no_argument, nullptr, 'D' },
878 { "file", required_argument, nullptr, 'f' },
879 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700880 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800881 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700882 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800883 { "head", required_argument, nullptr, 'm' },
884 { id_str, required_argument, nullptr, 0 },
885 { "last", no_argument, nullptr, 'L' },
886 { "max-count", required_argument, nullptr, 'm' },
887 { pid_str, required_argument, nullptr, 0 },
888 { print_str, no_argument, nullptr, 0 },
889 { "prune", optional_argument, nullptr, 'p' },
890 { "regex", required_argument, nullptr, 'e' },
891 { "rotate-count", required_argument, nullptr, 'n' },
892 { "rotate-kbytes", required_argument, nullptr, 'r' },
893 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700894 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800895 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800896 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800897 { wrap_str, optional_argument, nullptr, 0 },
898 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700899 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800900 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700901
Mark Salyzyn5f606602017-02-10 13:09:07 -0800902 ret = getopt_long(argc, argv,
903 ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
904 &option_index);
Mark Salyzynde022a82017-03-01 08:30:06 -0800905 if (ret < 0) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800906
Kristian Monsen562e5132015-06-05 14:10:12 -0700907 switch (ret) {
908 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700909 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700910 if (long_options[option_index].name == pid_str) {
911 // ToDo: determine runtime PID_MAX?
912 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800913 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Kristian Monsen562e5132015-06-05 14:10:12 -0700914 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800915 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700916 }
917 break;
918 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800919 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800920 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800921 ANDROID_LOG_NONBLOCK;
922 // ToDo: implement API that supports setting a wrap timeout
923 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
924 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800925 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800926 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800927 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800928 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800929 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
930 context->error) {
931 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800932 "WARNING: %s %u seconds, ignoring %zu\n",
933 long_options[option_index].name,
934 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
935 }
936 break;
937 }
Mark Salyzync9202772016-03-30 09:38:31 -0700938 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800939 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700940 break;
941 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800942 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800943 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800944 break;
945 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700946 if (long_options[option_index].name == id_str) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800947 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700948 }
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 Salyzynde022a82017-03-01 08:30:06 -08001015 char* end = nullptr;
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 Salyzynb45a1752017-02-28 09:20:31 -08001079 std::unique_ptr<char, void (*)(void*)> buffers(strdup(optarg),
1080 free);
1081 optarg = buffers.get();
Mark Salyzyn45177732016-04-11 14:03:48 -07001082 unsigned idMask = 0;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001083 char* sv = nullptr; // protect against -ENOMEM above
1084 while (!!(optarg = strtok_r(optarg, delimiters, &sv))) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001085 if (!strcmp(optarg, "default")) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001086 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001087 (1 << LOG_ID_CRASH);
Mark Salyzynde022a82017-03-01 08:30:06 -08001088 } else if (!strcmp(optarg, "all")) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001089 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001090 idMask = (unsigned)-1;
1091 } else {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001092 log_id_t log_id = android_name_to_log_id(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001093 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001094
Mark Salyzynde022a82017-03-01 08:30:06 -08001095 if (!!strcmp(name, optarg)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001096 logcat_panic(context, HELP_TRUE,
1097 "unknown buffer %s\n", optarg);
1098 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001099 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001100 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001101 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001102 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001103 optarg = nullptr;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001104 }
1105
Mark Salyzyn45177732016-04-11 14:03:48 -07001106 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001107 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001108 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001109
Mark Salyzynde022a82017-03-01 08:30:06 -08001110 if (log_id != (log_id_t)i) continue;
1111 if (!(idMask & (1 << i))) continue;
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 Salyzynde022a82017-03-01 08:30:06 -08001119 if (!dev->next) break;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001120 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001121 if (found) continue;
Mark Salyzyn45177732016-04-11 14:03:48 -07001122
Mark Salyzyn5f606602017-02-10 13:09:07 -08001123 bool binary =
1124 !strcmp(name, "events") || !strcmp(name, "security");
Mark Salyzyn45177732016-04-11 14:03:48 -07001125 log_device_t* d = new log_device_t(name, binary);
1126
Mark Salyzyn083b0372015-12-04 10:59:45 -08001127 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001128 dev->next = d;
1129 dev = d;
1130 } else {
1131 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001132 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001133 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001134 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001135 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001136
1137 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001138 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001139 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140
1141 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001142 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Mark Salyzynf3555d92015-05-27 07:39:56 -07001143 tail_time = lastLogTime(optarg);
1144 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001145 // redirect output to a file
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001146 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001147 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001148
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001149 case 'r':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001150 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1151 logcat_panic(context, HELP_TRUE,
1152 "Invalid parameter \"%s\" to -r\n", optarg);
1153 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001155 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001156
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001157 case 'n':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001158 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1159 logcat_panic(context, HELP_TRUE,
1160 "Invalid parameter \"%s\" to -n\n", optarg);
1161 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001163 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001164
Mark Salyzynb45a1752017-02-28 09:20:31 -08001165 case 'v': {
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001166 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001167 show_format_help(context);
1168 context->retval = EXIT_SUCCESS;
1169 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001170 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001171 std::unique_ptr<char, void (*)(void*)> formats(strdup(optarg),
1172 free);
1173 optarg = formats.get();
1174 unsigned idMask = 0;
1175 char* sv = nullptr; // protect against -ENOMEM above
1176 while (!!(optarg = strtok_r(optarg, delimiters, &sv))) {
1177 err = setLogFormat(context, optarg);
1178 if (err < 0) {
1179 logcat_panic(context, HELP_FORMAT,
1180 "Invalid parameter \"%s\" to -v\n", optarg);
1181 goto exit;
1182 }
1183 optarg = nullptr;
1184 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001186 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187
1188 case 'Q':
Mark Salyzyn5f606602017-02-10 13:09:07 -08001189#define KERNEL_OPTION "androidboot.logcat="
1190#define CONSOLE_OPTION "androidboot.console="
1191 // This is a *hidden* option used to start a version of logcat
1192 // in an emulated device only. It basically looks for
1193 // androidboot.logcat= on the kernel command line. If
1194 // something is found, it extracts a log filter and uses it to
1195 // run the program. If nothing is found, the program should
1196 // quit immediately.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001197 {
Mark Salyzynf3290292017-02-10 13:09:07 -08001198 std::string cmdline;
1199 android::base::ReadFileToString("/proc/cmdline", &cmdline);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001200
Mark Salyzynf3290292017-02-10 13:09:07 -08001201 const char* logcat = strstr(cmdline.c_str(), KERNEL_OPTION);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001202 // if nothing found or invalid filters, exit quietly
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001203 if (!logcat) {
1204 context->retval = EXIT_SUCCESS;
1205 goto exit;
1206 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001207
1208 const char* p = logcat + strlen(KERNEL_OPTION);
1209 const char* q = strpbrk(p, " \t\n\r");
1210 if (!q) q = p + strlen(p);
1211 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001212
Mark Salyzyn5f606602017-02-10 13:09:07 -08001213 // redirect our output to the emulator console
Mark Salyzynf3290292017-02-10 13:09:07 -08001214 const char* console =
1215 strstr(cmdline.c_str(), CONSOLE_OPTION);
1216 if (!console) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001217
Mark Salyzynf3290292017-02-10 13:09:07 -08001218 p = console + strlen(CONSOLE_OPTION);
1219 q = strpbrk(p, " \t\n\r");
1220 int len = q ? q - p : strlen(p);
1221 std::string devname = "/dev/" + std::string(p, len);
1222 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001223
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001224 if (context->error) {
1225 fprintf(context->error, "logcat using %s\n",
1226 devname.c_str());
1227 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001228
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001229 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001230 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001231 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001232
1233 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001234 android::close_output(context);
1235 android::close_error(context);
1236 context->stderr_stdout = true;
1237 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001238 context->output_fd = fileno(fp);
1239 if (context->stderr_null) break;
1240 context->stderr_stdout = true;
1241 context->error = fp;
1242 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001243 }
1244 break;
1245
Mark Salyzyn34facab2014-02-06 14:48:50 -08001246 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001247 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001248 break;
1249
Traian Schiau59763032015-04-10 15:51:39 +03001250 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001251 logcat_panic(context, HELP_TRUE,
1252 "Option -%c needs an argument\n", optopt);
1253 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001254
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001255 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001256 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
1257 optopt);
1258 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001259 }
1260 }
1261
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001262 if (context->maxCount && got_t) {
1263 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001264 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001265 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001266 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001267 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001268 // One day it would be nice if --print -v color and --regex <expr>
1269 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001270 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001271 if (context->error) {
1272 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001273 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001274 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001275 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001276 }
1277 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001278 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001279
Joe Onorato6fa09a02010-02-26 10:04:23 -08001280 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001281 dev = devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001282 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001283 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001284 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001285 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001286 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001287 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001288 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001289 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001290 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001291 }
1292
Mark Salyzynde022a82017-03-01 08:30:06 -08001293 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001294 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1295 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001296 }
1297
Mark Salyzynde022a82017-03-01 08:30:06 -08001298 if (!!setId) {
1299 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001300 logcat_panic(context, HELP_TRUE,
1301 "--id='%s' requires -f as well\n", setId);
1302 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001303 }
1304
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001305 std::string file_name = android::base::StringPrintf(
1306 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001307 std::string file;
1308 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001309 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1310 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001311 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001312 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001313
Mark Salyzynde022a82017-03-01 08:30:06 -08001314 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001315 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001316
Mark Salyzynde022a82017-03-01 08:30:06 -08001317 if (!!logFormat) {
Mark Salyzynb45a1752017-02-28 09:20:31 -08001318 std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
1319 free);
1320 char* sv = nullptr; // protect against -ENOMEM above
1321 char* arg = formats.get();
1322 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1323 err = setLogFormat(context, arg);
1324 // environment should not cause crash of logcat
1325 if ((err < 0) && context->error) {
1326 fprintf(context->error,
1327 "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
1328 }
1329 arg = nullptr;
1330 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001331 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001332 }
1333 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001334 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001335 }
1336 }
1337
Mark Salyzynf3290292017-02-10 13:09:07 -08001338 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001339 err = android_log_addFilterString(context->logformat,
1340 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001341 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001342 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001343 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001344 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001345 }
1346 } else if (argc == optind) {
1347 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001348 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001349
Mark Salyzynde022a82017-03-01 08:30:06 -08001350 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001351 err = android_log_addFilterString(context->logformat,
1352 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001353
Mark Salyzyn95132e92013-11-22 10:55:48 -08001354 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001355 logcat_panic(context, HELP_TRUE,
1356 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1357 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001358 }
1359 }
1360 } else {
1361 // Add from commandline
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001362 for (int i = optind ; i < argc ; i++) {
1363 // skip stderr redirections of _all_ kinds
1364 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001365 // skip stdout redirections of _all_ kinds
1366 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001367
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001368 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001369 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001370 logcat_panic(context, HELP_TRUE,
1371 "Invalid filter expression '%s'\n", argv[i]);
1372 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001373 }
1374 }
1375 }
1376
Joe Onorato6fa09a02010-02-26 10:04:23 -08001377 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001378 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001379 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001380 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001381 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001382 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001383 // We have three orthogonal actions below to clear, set log size and
1384 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001385 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001386 dev->logger_list = logger_list;
1387 dev->logger = android_logger_open(logger_list,
1388 android_name_to_log_id(dev->device));
1389 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001390 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001391 dev = dev->next;
1392 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001393 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001394
Mark Salyzyn02687e72016-08-03 14:20:41 -07001395 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001396 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001397 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001398 (context->maxRotatedLogs > 0) ?
1399 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1400 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001401
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001402 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001403 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001404
Mark Salyzynde022a82017-03-01 08:30:06 -08001405 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001406 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001407 "%s", context->outputFileName);
1408 } else {
1409 file = android::base::StringPrintf("%s.%.*d",
1410 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001411 }
1412
Mark Salyzynde022a82017-03-01 08:30:06 -08001413 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001414 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001415 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001416 break;
1417 }
1418
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001419 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001420
Mark Salyzynde022a82017-03-01 08:30:06 -08001421 if (err < 0 && errno != ENOENT && !clearFail) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001422 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001423 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001424 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001425 }
1426 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001427 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001428 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001429 }
1430
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001431 if (setLogSize) {
1432 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001433 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001434 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001435 }
1436
Joe Onorato6fa09a02010-02-26 10:04:23 -08001437 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001438 long size = android_logger_get_log_size(dev->logger);
1439 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001440
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001441 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001442 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001443 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001444 std::string str = android::base::StringPrintf(
1445 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1446 " max entry is %db, max payload is %db\n",
1447 dev->device,
1448 value_of_size(size), multiplier_of_size(size),
1449 value_of_size(readable), multiplier_of_size(readable),
1450 (int)LOGGER_ENTRY_MAX_LEN,
1451 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1452 TEMP_FAILURE_RETRY(write(context->output_fd,
1453 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001454 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001455 }
1456
1457 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001458 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001459
1460 context->retval = EXIT_SUCCESS;
1461
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001462 // report any errors in the above loop and exit
1463 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001464 logcat_panic(context, HELP_FALSE,
1465 "Unable to open log device '%s'\n", openDeviceFail);
1466 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001467 }
1468 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001469 logcat_panic(context, HELP_FALSE,
1470 "failed to clear the '%s' log\n", clearFail);
1471 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001472 }
1473 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001474 logcat_panic(context, HELP_FALSE,
1475 "failed to set the '%s' log size\n", setSizeFail);
1476 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001477 }
1478 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001479 logcat_panic(context, HELP_FALSE,
1480 "failed to get the readable '%s' log size", getSizeFail);
1481 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001482 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001483
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001484 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001485 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001486 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001487 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001488 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001489 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1490 buf[len] = '\0';
1491 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001492 logcat_panic(context, HELP_FALSE,
1493 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001494 }
1495 free(buf);
1496 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001497 logcat_panic(context, HELP_FALSE,
1498 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001499 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001500 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001501 }
1502
Mark Salyzyn1c950472014-04-01 17:19:47 -07001503 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001504 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001505 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001506
Mark Salyzyn5f606602017-02-10 13:09:07 -08001507 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001508 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001509 if (getPruneList) {
1510 android_logger_get_prune_list(logger_list, buf, len);
1511 } else {
1512 android_logger_get_statistics(logger_list, buf, len);
1513 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001514 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001515 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001516 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001517 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001518 break;
1519 }
Traian Schiau59763032015-04-10 15:51:39 +03001520 size_t ret = atol(buf) + 1;
1521 if (ret <= len) {
1522 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001523 break;
1524 }
Traian Schiau59763032015-04-10 15:51:39 +03001525 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001526 }
1527
1528 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001529 logcat_panic(context, HELP_FALSE, "failed to read data");
1530 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001531 }
1532
1533 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001534 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001535 *cp = '\0';
1536 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001537 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001538
1539 // squash out the byte count
1540 cp = buf;
1541 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001542 while (isdigit(*cp)) ++cp;
1543 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001544 }
1545
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001546 len = strlen(cp);
1547 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001548 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001549 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001550 }
1551
Mark Salyzynde022a82017-03-01 08:30:06 -08001552 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001553
Mark Salyzynde022a82017-03-01 08:30:06 -08001554 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001555 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001556
Mark Salyzyn5f606602017-02-10 13:09:07 -08001557 // LOG_EVENT_INT(10, 12345);
1558 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1559 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001560
Mark Salyzynde022a82017-03-01 08:30:06 -08001561 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001562
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001563 while (!context->stop &&
1564 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001565 struct log_msg log_msg;
1566 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001567 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001568 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1569 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001570 }
1571
1572 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001573 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001574
1575 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001576 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1577 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001578 }
1579 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001580 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1581 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001582 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001583 logcat_panic(context, HELP_FALSE, "logcat read failure");
1584 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001585 }
1586
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001587 log_device_t* d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001588 for (d = devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001589 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001590 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001591 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001592 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001593 d = &unexpected;
1594 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001595 }
1596
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001597 if (dev != d) {
1598 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001599 maybePrintStart(context, dev, printDividers);
1600 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001601 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001602 if (context->printBinary) {
1603 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001604 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001605 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001606 }
1607 }
1608
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001609close:
Mark Salyzyn95132e92013-11-22 10:55:48 -08001610 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001611
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001612exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001613 // close write end of pipe to help things along
1614 if (context->output_fd == context->fds[1]) {
1615 android::close_output(context);
1616 }
1617 if (context->error_fd == context->fds[1]) {
1618 android::close_error(context);
1619 }
1620 if (context->fds[1] >= 0) {
1621 // NB: should be closed by the above
1622 int save_errno = errno;
1623 close(context->fds[1]);
1624 errno = save_errno;
1625 context->fds[1] = -1;
1626 }
1627 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001628 return context->retval;
1629}
1630
1631// Can block
1632int android_logcat_run_command(android_logcat_context ctx,
1633 int output, int error,
1634 int argc, char* const* argv,
1635 char* const* envp) {
1636 android_logcat_context_internal* context = ctx;
1637
1638 context->output_fd = output;
1639 context->error_fd = error;
1640 context->argc = argc;
1641 context->argv = argv;
1642 context->envp = envp;
1643 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001644 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001645 return __logcat(context);
1646}
1647
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001648// starts a thread, opens a pipe, returns reading end.
1649int android_logcat_run_command_thread(android_logcat_context ctx,
1650 int argc, char* const* argv,
1651 char* const* envp) {
1652 android_logcat_context_internal* context = ctx;
1653
1654 int save_errno = EBUSY;
Mark Salyzynde022a82017-03-01 08:30:06 -08001655 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001656
1657 if (pipe(context->fds) < 0) {
1658 save_errno = errno;
1659 goto exit;
1660 }
1661
1662 pthread_attr_t attr;
1663 if (pthread_attr_init(&attr)) {
1664 save_errno = errno;
1665 goto close_exit;
1666 }
1667
1668 struct sched_param param;
1669 memset(&param, 0, sizeof(param));
1670 pthread_attr_setschedparam(&attr, &param);
1671 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1672 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1673 int save_errno = errno;
1674 goto pthread_attr_exit;
1675 }
1676
1677 context->stop = false;
1678 context->thread_stopped = false;
1679 context->output_fd = context->fds[1];
1680 // save off arguments so they remain while thread is active.
1681 for (int i = 0; i < argc; ++i) {
1682 context->args.push_back(std::string(argv[i]));
1683 }
1684 // save off environment so they remain while thread is active.
1685 if (envp) for (size_t i = 0; envp[i]; ++i) {
1686 context->envs.push_back(std::string(envp[i]));
1687 }
1688
1689 for (auto& str : context->args) {
1690 context->argv_hold.push_back(str.c_str());
1691 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001692 context->argv_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001693 for (auto& str : context->envs) {
1694 context->envp_hold.push_back(str.c_str());
1695 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001696 context->envp_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001697
1698 context->argc = context->argv_hold.size() - 1;
1699 context->argv = (char* const*)&context->argv_hold[0];
1700 context->envp = (char* const*)&context->envp_hold[0];
1701
1702#ifdef DEBUG
1703 fprintf(stderr, "argv[%d] = {", context->argc);
1704 for (auto str : context->argv_hold) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001705 fprintf(stderr, " \"%s\"", str ?: "nullptr");
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001706 }
1707 fprintf(stderr, " }\n");
1708 fflush(stderr);
1709#endif
1710 context->retval = EXIT_SUCCESS;
1711 if (pthread_create(&context->thr, &attr,
1712 (void*(*)(void*))__logcat, context)) {
1713 int save_errno = errno;
1714 goto argv_exit;
1715 }
1716 pthread_attr_destroy(&attr);
1717
1718 return context->fds[0];
1719
1720argv_exit:
1721 context->argv_hold.clear();
1722 context->args.clear();
1723 context->envp_hold.clear();
1724 context->envs.clear();
1725pthread_attr_exit:
1726 pthread_attr_destroy(&attr);
1727close_exit:
1728 close(context->fds[0]);
1729 context->fds[0] = -1;
1730 close(context->fds[1]);
1731 context->fds[1] = -1;
1732exit:
1733 errno = save_errno;
1734 context->stop = true;
1735 context->thread_stopped = true;
1736 context->retval = EXIT_FAILURE;
1737 return -1;
1738}
1739
1740// test if the thread is still doing 'stuff'
1741int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1742 android_logcat_context_internal* context = ctx;
1743
1744 return context->thread_stopped == false;
1745}
1746
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001747// Finished with context
1748int android_logcat_destroy(android_logcat_context* ctx) {
1749 android_logcat_context_internal* context = *ctx;
1750
Mark Salyzynde022a82017-03-01 08:30:06 -08001751 if (!context) return -EBADF;
1752
1753 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001754
1755 context->stop = true;
1756
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001757 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001758 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001759 sched_yield();
1760 }
1761
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001762 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001763 context->argv_hold.clear();
1764 context->args.clear();
1765 context->envp_hold.clear();
1766 context->envs.clear();
1767 if (context->fds[0] >= 0) {
1768 close(context->fds[0]);
1769 context->fds[0] = -1;
1770 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001771 android::close_output(context);
1772 android::close_error(context);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001773 if (context->fds[1] >= 0) {
1774 // NB: could be closed by the above fclose(s), ignore error.
1775 int save_errno = errno;
1776 close(context->fds[1]);
1777 errno = save_errno;
1778 context->fds[1] = -1;
1779 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001780
1781 android_closeEventTagMap(context->eventTagMap);
1782
1783 int retval = context->retval;
1784
1785 free(context);
1786
1787 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001788}