blob: 0f563371c166b7668a99fe2b33b63c8e31c5140a [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
Elliott Hughes61b580e2018-06-15 15:16:20 -070017#include "logcat.h"
18
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070019#include <arpa/inet.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080020#include <assert.h>
21#include <ctype.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070022#include <dirent.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080023#include <errno.h>
24#include <fcntl.h>
Elliott Hughes61b580e2018-06-15 15:16:20 -070025#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070026#include <math.h>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080027#include <pthread.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070028#include <sched.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070029#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080030#include <stdio.h>
31#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080032#include <string.h>
Traian Schiau59763032015-04-10 15:51:39 +030033#include <sys/cdefs.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070034#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080035#include <sys/socket.h>
36#include <sys/stat.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070037#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070038#include <time.h>
39#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080040
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080041#include <atomic>
Mark Salyzynf3555d92015-05-27 07:39:56 -070042#include <memory>
43#include <string>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080044#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070045
Elliott Hughes4f713192015-12-04 22:00:26 -080046#include <android-base/file.h>
bohu94aab862017-02-21 14:31:19 -080047#include <android-base/properties.h>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070048#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080049#include <android-base/strings.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070050#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080051#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070052#include <log/event_tag_map.h>
Colin Cross9227bd32013-07-23 16:59:20 -070053#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070054#include <private/android_logger.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080055#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080056
Casey Dahlindc42a872016-03-17 16:18:55 -070057#include <pcrecpp.h>
58
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059#define DEFAULT_MAX_ROTATED_LOGS 4
60
Mark Salyzyn13e47352017-03-06 14:56:04 -080061struct log_device_t {
62 const char* device;
63 bool binary;
64 struct logger* logger;
65 struct logger_list* logger_list;
66 bool printed;
67
68 log_device_t* next;
69
70 log_device_t(const char* d, bool b) {
71 device = d;
72 binary = b;
73 next = nullptr;
74 printed = false;
75 logger = nullptr;
76 logger_list = nullptr;
77 }
78};
79
Mark Salyzync0cf90d2017-02-10 13:09:07 -080080struct android_logcat_context_internal {
81 // status
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080082 volatile std::atomic_int retval; // valid if thread_stopped set
83 // Arguments passed in, or copies and storage thereof if a thread.
Mark Salyzync0cf90d2017-02-10 13:09:07 -080084 int argc;
85 char* const* argv;
86 char* const* envp;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080087 std::vector<std::string> args;
88 std::vector<const char*> argv_hold;
89 std::vector<std::string> envs;
90 std::vector<const char*> envp_hold;
Mark Salyzynde022a82017-03-01 08:30:06 -080091 int output_fd; // duplication of fileno(output) (below)
92 int error_fd; // duplication of fileno(error) (below)
Mark Salyzync0cf90d2017-02-10 13:09:07 -080093
94 // library
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080095 int fds[2]; // From popen call
96 FILE* output; // everything writes to fileno(output), buffer unused
97 FILE* error; // unless error == output.
98 pthread_t thr;
99 volatile std::atomic_bool stop; // quick exit flag
100 volatile std::atomic_bool thread_stopped;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800101 bool stderr_null; // shell "2>/dev/null"
102 bool stderr_stdout; // shell "2>&1"
103
104 // global variables
105 AndroidLogFormat* logformat;
106 const char* outputFileName;
107 // 0 means "no log rotation"
108 size_t logRotateSizeKBytes;
109 // 0 means "unbounded"
110 size_t maxRotatedLogs;
111 size_t outByteCount;
112 int printBinary;
113 int devCount; // >1 means multiple
114 pcrecpp::RE* regex;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800115 log_device_t* devices;
116 EventTagMap* eventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800117 // 0 means "infinite"
118 size_t maxCount;
119 size_t printCount;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800120
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800121 bool printItAnyways;
122 bool debug;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800123 bool hasOpenedEventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800124};
125
126// Creates a context associated with this logcat instance
127android_logcat_context create_android_logcat() {
128 android_logcat_context_internal* context;
129
130 context = (android_logcat_context_internal*)calloc(
131 1, sizeof(android_logcat_context_internal));
Mark Salyzynde022a82017-03-01 08:30:06 -0800132 if (!context) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800133
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800134 context->fds[0] = -1;
135 context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800136 context->output_fd = -1;
137 context->error_fd = -1;
138 context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
139
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800140 context->argv_hold.clear();
141 context->args.clear();
142 context->envp_hold.clear();
143 context->envs.clear();
144
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800145 return (android_logcat_context)context;
146}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147
Mark Salyzyn5f606602017-02-10 13:09:07 -0800148// logd prefixes records with a length field
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
150
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800151namespace android {
152
Mark Salyzyn5f606602017-02-10 13:09:07 -0800153enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700154
Mark Salyzynaa730c12016-03-30 12:38:29 -0700155// if showHelp is set, newline required in fmt statement to transition to usage
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800156static void logcat_panic(android_logcat_context_internal* context,
157 enum helpType showHelp, const char* fmt, ...)
158 __printflike(3, 4);
Traian Schiau59763032015-04-10 15:51:39 +0300159
Mark Salyzyn5f606602017-02-10 13:09:07 -0800160static int openLogFile(const char* pathname) {
Edwin Vane80b221c2012-08-13 12:55:07 -0400161 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800162}
163
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800164static void close_output(android_logcat_context_internal* context) {
165 // split output_from_error
166 if (context->error == context->output) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800167 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800168 context->output_fd = -1;
169 }
170 if (context->error && (context->output_fd == fileno(context->error))) {
171 context->output_fd = -1;
172 }
173 if (context->output_fd == context->error_fd) {
174 context->output_fd = -1;
175 }
176 // close output channel
177 if (context->output) {
178 if (context->output != stdout) {
179 if (context->output_fd == fileno(context->output)) {
180 context->output_fd = -1;
181 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800182 if (context->fds[1] == fileno(context->output)) {
183 context->fds[1] = -1;
184 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800185 fclose(context->output);
186 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800187 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800188 }
189 if (context->output_fd >= 0) {
190 if (context->output_fd != fileno(stdout)) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800191 if (context->fds[1] == context->output_fd) {
192 context->fds[1] = -1;
193 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800194 close(context->output_fd);
195 }
196 context->output_fd = -1;
197 }
198}
199
200static void close_error(android_logcat_context_internal* context) {
201 // split error_from_output
202 if (context->output == context->error) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800203 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800204 context->error_fd = -1;
205 }
206 if (context->output && (context->error_fd == fileno(context->output))) {
207 context->error_fd = -1;
208 }
209 if (context->error_fd == context->output_fd) {
210 context->error_fd = -1;
211 }
212 // close error channel
213 if (context->error) {
214 if ((context->error != stderr) && (context->error != stdout)) {
215 if (context->error_fd == fileno(context->error)) {
216 context->error_fd = -1;
217 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800218 if (context->fds[1] == fileno(context->error)) {
219 context->fds[1] = -1;
220 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800221 fclose(context->error);
222 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800223 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800224 }
225 if (context->error_fd >= 0) {
226 if ((context->error_fd != fileno(stdout)) &&
227 (context->error_fd != fileno(stderr))) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800228 if (context->fds[1] == context->error_fd) context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800229 close(context->error_fd);
230 }
231 context->error_fd = -1;
232 }
233}
234
235static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800236 int err;
237
238 // Can't rotate logs if we're not outputting to a file
Mark Salyzynde022a82017-03-01 08:30:06 -0800239 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800241 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242
Mark Salyzyn5f606602017-02-10 13:09:07 -0800243 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800244 // maxRotatedLogs in decimal. eg:
245 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800246 // -> log10(30) == 1.477
247 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700248 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800249 (context->maxRotatedLogs > 0)
250 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
251 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700252
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800253 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700254 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800255 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800256
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700257 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800258 if (!(i - 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800259 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800260 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800261 file0 =
262 android::base::StringPrintf("%s.%.*d", context->outputFileName,
263 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264 }
265
Mark Salyzynde022a82017-03-01 08:30:06 -0800266 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300267 perror("while rotating log files");
268 break;
269 }
270
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700271 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272
273 if (err < 0 && errno != ENOENT) {
274 perror("while rotating log files");
275 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800276 }
277
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800278 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800279
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800280 if (context->output_fd < 0) {
281 logcat_panic(context, HELP_FALSE, "couldn't open output file");
282 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800284 context->output = fdopen(context->output_fd, "web");
Mark Salyzynde022a82017-03-01 08:30:06 -0800285 if (!context->output) {
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800286 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
287 return;
288 }
289 if (context->stderr_stdout) {
290 close_error(context);
291 context->error = context->output;
292 context->error_fd = context->output_fd;
293 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800295 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800296}
297
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800298void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800299 size_t size = buf->len();
300
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800301 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800302}
303
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800304static bool regexOk(android_logcat_context_internal* context,
305 const AndroidLogEntry& entry) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800306 if (!context->regex) return true;
Casey Dahlindc42a872016-03-17 16:18:55 -0700307
Casey Dahlindc42a872016-03-17 16:18:55 -0700308 std::string messageString(entry.message, entry.messageLen);
309
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800310 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700311}
312
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800313static void processBuffer(android_logcat_context_internal* context,
314 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700315 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800316 int err;
317 AndroidLogEntry entry;
318 char binaryMsgBuf[1024];
319
Joe Onorato6fa09a02010-02-26 10:04:23 -0800320 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800321 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800322 context->eventTagMap = android_openEventTagMap(nullptr);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800323 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800324 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800325 err = android_log_processBinaryLogBuffer(
326 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
327 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800328 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800329 // entry.priority, entry.messageLen, entry.message);
330 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800331 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800332 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800333 if ((err < 0) && !context->debug) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800334
Mark Salyzyn5f606602017-02-10 13:09:07 -0800335 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800336 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800337 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800338 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800339
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800340 context->printCount += match;
341 if (match || context->printItAnyways) {
342 bytesWritten = android_log_printLogLine(context->logformat,
343 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700344
Mark Salyzync9202772016-03-30 09:38:31 -0700345 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800346 logcat_panic(context, HELP_FALSE, "output error");
347 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700348 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800349 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350 }
351
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800352 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800353
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800354 if (context->logRotateSizeKBytes > 0 &&
355 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
356 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800357 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358}
359
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800360static void maybePrintStart(android_logcat_context_internal* context,
361 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800362 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800363 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800364 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800365 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800366 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800367 if (write(context->output_fd, buf, strlen(buf)) < 0) {
368 logcat_panic(context, HELP_FALSE, "output error");
369 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800370 }
371 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800372 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800373 }
374}
375
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800376static void setupOutputAndSchedulingPolicy(
377 android_logcat_context_internal* context, bool blocking) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800378 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800379
Mark Salyzynad5e4112016-08-04 07:53:52 -0700380 if (blocking) {
381 // Lower priority and set to batch scheduling if we are saving
382 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800383 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
384 fprintf(context->error,
385 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700386 }
387
388 struct sched_param param;
389 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800390 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700391 fprintf(stderr, "failed to set to batch scheduler\n");
392 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800394 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
395 context->error) {
396 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700397 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700399
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800400 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700401
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800402 context->output_fd = openLogFile(context->outputFileName);
403
404 if (context->output_fd < 0) {
405 logcat_panic(context, HELP_FALSE, "couldn't open output file");
406 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700407 }
408
409 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800410 if (fstat(context->output_fd, &statbuf) == -1) {
411 close_output(context);
412 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
413 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700414 }
415
Mark Salyzyn5f606602017-02-10 13:09:07 -0800416 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800417 close_output(context);
418 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
419 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700420 }
421
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800422 context->output = fdopen(context->output_fd, "web");
423
424 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800425}
426
Mark Salyzyn5f606602017-02-10 13:09:07 -0800427// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800428static void show_help(android_logcat_context_internal* context) {
429 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800431 const char* cmd = strrchr(context->argv[0], '/');
432 cmd = cmd ? cmd + 1 : context->argv[0];
433
434 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
435
436 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700437 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
438 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700439 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
440 " Rotate log every kbytes. Requires -f option\n"
441 " -n <count>, --rotate-count=<count>\n"
442 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700443 " --id=<id> If the signature id for logging to file changes, then clear\n"
444 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700445 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700446 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700447 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700448 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700449 " color descriptive epoch monotonic printable uid\n"
450 " usec UTC year zone\n"
Mark Salyzynb45a1752017-02-28 09:20:31 -0800451 " Multiple -v parameters or comma separated list of format and\n"
452 " format modifiers are allowed.\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800453 // private and undocumented nsec, no signal, too much noise
454 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700455 " -D, --dividers Print dividers between each log buffer\n"
456 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700457 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700458 " -d Dump the log and then exit (don't block)\n"
459 " -e <expr>, --regex=<expr>\n"
460 " Only print lines where the log message matches <expr>\n"
Brendan Jackmana5141132017-10-31 12:44:54 +0000461 " where <expr> is a Perl-compatible regular expression\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700462 // Leave --head undocumented as alias for -m
463 " -m <count>, --max-count=<count>\n"
464 " Quit after printing <count> lines. This is meant to be\n"
465 " paired with --regex, but will work on its own.\n"
466 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700467 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700468 // Leave --tail undocumented as alias for -t
469 " -t <count> Print only the most recent <count> lines (implies -d)\n"
470 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
471 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
472 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700473 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700474 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700475 " -g, --buffer-size Get the size of the ring buffer.\n"
476 " -G <size>, --buffer-size=<size>\n"
477 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100478 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800479 // Leave security (Device Owner only installations) and
480 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700481 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
482 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700483 " Multiple -b parameters or comma separated list of buffers are\n"
484 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700485 " -B, --binary Output the log in binary.\n"
486 " -S, --statistics Output statistics.\n"
487 " -p, --prune Print prune white and ~black list. Service is specified as\n"
488 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700489 " with ~, otherwise weighed for longevity if unadorned. All\n"
490 " other pruning activity is oldest first. Special case ~!\n"
491 " represents an automatic quicker pruning for the noisiest\n"
492 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700493 " -P '<list> ...', --prune='<list> ...'\n"
494 " Set prune white and ~black list, using same format as\n"
495 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800496 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700497 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800498 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
499 " comes first. Improves efficiency of polling by providing\n"
500 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800501
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800502 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 " <tag>[:priority]\n\n"
504 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700505 " V Verbose (default for <tag>)\n"
506 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507 " I Info\n"
508 " W Warn\n"
509 " E Error\n"
510 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700511 " S Silent (suppress all output)\n"
512 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
513 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
514 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
515 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
516 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700517 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518}
519
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800520static void show_format_help(android_logcat_context_internal* context) {
521 if (!context->error) return;
522 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700523 "-v <format>, --format=<format> options:\n"
524 " Sets log print format verb and adverbs, where <format> is:\n"
525 " brief long process raw tag thread threadtime time\n"
526 " and individually flagged modifying adverbs can be added:\n"
527 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
528 "\nSingle format verbs:\n"
529 " brief — Display priority/tag and PID of the process issuing the message.\n"
530 " long — Display all metadata fields, separate messages with blank lines.\n"
531 " process — Display PID only.\n"
532 " raw — Display the raw log message, with no other metadata fields.\n"
533 " tag — Display the priority/tag only.\n"
Mark Salyzync74f8d92017-05-15 13:40:33 -0700534 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700535 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
536 " and TID of the thread issuing the message. (the default format).\n"
537 " time — Display the date, invocation time, priority/tag, and PID of the\n"
538 " process issuing the message.\n"
539 "\nAdverb modifiers can be used in combination:\n"
540 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
541 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
542 " descriptive — events logs only, descriptions from event-log-tags database.\n"
543 " epoch — Display time as seconds since Jan 1 1970.\n"
544 " monotonic — Display time as cpu seconds since last boot.\n"
545 " printable — Ensure that any binary logging content is escaped.\n"
546 " uid — If permitted, display the UID or Android ID of logged process.\n"
547 " usec — Display time down the microsecond precision.\n"
548 " UTC — Display time as UTC.\n"
549 " year — Add the year to the displayed time.\n"
550 " zone — Add the local timezone to the displayed time.\n"
551 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
552 );
553}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800554// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700555
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800556static int setLogFormat(android_logcat_context_internal* context,
557 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800558 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559
560 format = android_log_formatFromString(formatString);
561
Mark Salyzynde022a82017-03-01 08:30:06 -0800562 // invalid string?
563 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800565 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566}
567
Mark Salyzyn5f606602017-02-10 13:09:07 -0800568static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700569
Mark Salyzyn5f606602017-02-10 13:09:07 -0800570static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700571 for (unsigned i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800572 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
573 value /= 1024, ++i)
574 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700575 return value;
576}
577
Mark Salyzyn5f606602017-02-10 13:09:07 -0800578static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700579 unsigned i;
580 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800581 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
582 value /= 1024, ++i)
583 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700584 return multipliers[i];
585}
586
Mark Salyzyn5f606602017-02-10 13:09:07 -0800587// String to unsigned int, returns -1 if it fails
588static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
589 size_t max = SIZE_MAX) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800590 if (!ptr) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300591
Mark Salyzyn5f606602017-02-10 13:09:07 -0800592 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700593 errno = 0;
594 size_t ret = (size_t)strtoll(ptr, &endp, 0);
595
Mark Salyzynde022a82017-03-01 08:30:06 -0800596 if (endp[0] || errno) return false;
Kristian Monsen562e5132015-06-05 14:10:12 -0700597
Mark Salyzynde022a82017-03-01 08:30:06 -0800598 if ((ret > max) || (ret < min)) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300599
600 *val = ret;
601 return true;
602}
603
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800604static void logcat_panic(android_logcat_context_internal* context,
605 enum helpType showHelp, const char* fmt, ...) {
606 context->retval = EXIT_FAILURE;
607 if (!context->error) {
608 context->stop = true;
609 return;
610 }
611
Mark Salyzyn5f606602017-02-10 13:09:07 -0800612 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700613 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800614 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700615 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300616
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700617 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800618 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800619 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800620 break;
621 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800622 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800623 break;
624 case HELP_FALSE:
625 default:
626 break;
Traian Schiau59763032015-04-10 15:51:39 +0300627 }
628
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800629 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300630}
631
Mark Salyzyn5f606602017-02-10 13:09:07 -0800632static char* parseTime(log_time& t, const char* cp) {
633 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800634 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700635 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800636 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700637 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700638}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700639
Mark Salyzyn31961062016-08-04 07:43:46 -0700640// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyne9ade172017-03-02 15:09:41 -0800641static log_time lastLogTime(const char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700642 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800643 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700644
Mark Salyzynf3555d92015-05-27 07:39:56 -0700645 std::string directory;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800646 const char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700647 if (!file) {
648 directory = ".";
649 file = outputFileName;
650 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800651 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700652 ++file;
653 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700654
Mark Salyzyn5f606602017-02-10 13:09:07 -0800655 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
656 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800657 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700658
Mark Salyzyn31961062016-08-04 07:43:46 -0700659 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700660
Mark Salyzynf3555d92015-05-27 07:39:56 -0700661 size_t len = strlen(file);
662 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800663 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700664
Mark Salyzynde022a82017-03-01 08:30:06 -0800665 while (!!(dp = readdir(dir.get()))) {
666 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800667 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800668 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700669 continue;
670 }
671
672 std::string file_name = directory;
673 file_name += "/";
674 file_name += dp->d_name;
675 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800676 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700677
678 bool found = false;
679 for (const auto& line : android::base::Split(file, "\n")) {
680 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800681 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800682 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700683 // determine the time precision of the logs (eg: msec or usec)
684 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
685 if (t.tv_nsec % (mod * 10)) {
686 modulo.tv_nsec = mod;
687 break;
688 }
689 }
690 // We filter any times later than current as we may not have the
691 // year stored with each log entry. Also, since it is possible for
692 // entries to be recorded out of order (very rare) we select the
693 // maximum we find just in case.
694 if ((t < now) && (t > retval)) {
695 retval = t;
696 found = true;
697 }
698 }
699 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800700 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700701 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800702 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700703 // tail_time prints matching or higher, round up by the modulo to prevent
704 // a replay of the last entry we have just checked.
705 retval += modulo;
706 return retval;
707}
708
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800709const char* getenv(android_logcat_context_internal* context, const char* name) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800710 if (!context->envp || !name || !*name) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800711
712 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
713 if (strncmp(context->envp[i], name, len)) continue;
714 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
715 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800716 return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800717}
718
Mark Salyzyn5f606602017-02-10 13:09:07 -0800719} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300720
Mark Salyzyn5f606602017-02-10 13:09:07 -0800721void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800722 bool blockSecurity) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800723 if (*current) return;
724 if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
725 *current = name;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800726 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800727}
Traian Schiau59763032015-04-10 15:51:39 +0300728
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800729static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300730 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731 int err;
Mark Salyzynb45a1752017-02-28 09:20:31 -0800732 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800733 bool clearLog = false;
734 bool allSelected = false;
735 bool getLogSize = false;
736 bool getPruneList = false;
737 bool printStatistics = false;
738 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800739 unsigned long setLogSize = 0;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800740 const char* setPruneList = nullptr;
741 const char* setId = nullptr;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800742 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800743 std::string forceFilters;
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
Elliott Hughes61b580e2018-06-15 15:16:20 -0700858 optind = 0;
859 while (true) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700860 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700861 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700862 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800863 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700864 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800865 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700866 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800867 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700868 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800869 { "binary", no_argument, nullptr, 'B' },
870 { "buffer", required_argument, nullptr, 'b' },
871 { "buffer-size", optional_argument, nullptr, 'g' },
872 { "clear", no_argument, nullptr, 'c' },
873 { debug_str, no_argument, nullptr, 0 },
874 { "dividers", no_argument, nullptr, 'D' },
875 { "file", required_argument, nullptr, 'f' },
876 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700877 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800878 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700879 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800880 { "head", required_argument, nullptr, 'm' },
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700881 { "help", no_argument, nullptr, 'h' },
Mark Salyzynde022a82017-03-01 08:30:06 -0800882 { id_str, required_argument, nullptr, 0 },
883 { "last", no_argument, nullptr, 'L' },
884 { "max-count", required_argument, nullptr, 'm' },
885 { pid_str, required_argument, nullptr, 0 },
886 { print_str, no_argument, nullptr, 0 },
887 { "prune", optional_argument, nullptr, 'p' },
888 { "regex", required_argument, nullptr, 'e' },
889 { "rotate-count", required_argument, nullptr, 'n' },
890 { "rotate-kbytes", required_argument, nullptr, 'r' },
891 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700892 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800893 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800894 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800895 { wrap_str, optional_argument, nullptr, 0 },
896 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700897 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800898 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700899
Elliott Hughes61b580e2018-06-15 15:16:20 -0700900 int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
901 &option_index);
902 if (c == -1) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800903
Elliott Hughes61b580e2018-06-15 15:16:20 -0700904 switch (c) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700905 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700906 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700907 if (long_options[option_index].name == pid_str) {
908 // ToDo: determine runtime PID_MAX?
Elliott Hughes61b580e2018-06-15 15:16:20 -0700909 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800910 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Elliott Hughes61b580e2018-06-15 15:16:20 -0700911 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800912 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700913 }
914 break;
915 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800916 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800917 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800918 ANDROID_LOG_NONBLOCK;
919 // ToDo: implement API that supports setting a wrap timeout
920 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Elliott Hughes61b580e2018-06-15 15:16:20 -0700921 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800922 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Elliott Hughes61b580e2018-06-15 15:16:20 -0700923 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800924 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800925 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800926 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
927 context->error) {
928 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800929 "WARNING: %s %u seconds, ignoring %zu\n",
930 long_options[option_index].name,
931 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
932 }
933 break;
934 }
Mark Salyzync9202772016-03-30 09:38:31 -0700935 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800936 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700937 break;
938 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800939 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800940 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800941 break;
942 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700943 if (long_options[option_index].name == id_str) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700944 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700945 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800946 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700947
Mark Salyzyn95132e92013-11-22 10:55:48 -0800948 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800950 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800951 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800952
953 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800954 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800955 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800956 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800957
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800958 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800959 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
960 ANDROID_LOG_NONBLOCK;
961 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800962
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800964 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800965 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800967 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700968 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800969 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800970 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800971 case 'T':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700972 if (strspn(optarg, "0123456789") != strlen(optarg)) {
973 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800974 if (!cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700975 logcat_panic(context, HELP_FALSE, "-%c \"%s\" not in time format\n", c,
976 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800977 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800978 }
979 if (*cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700980 char ch = *cp;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800981 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800982 if (context->error) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700983 fprintf(context->error, "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
984 c, optarg, ch, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800985 }
Elliott Hughes61b580e2018-06-15 15:16:20 -0700986 *cp = ch;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800987 }
988 } else {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700989 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800990 if (context->error) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700991 fprintf(context->error, "WARNING: -%c %s invalid, setting to 1\n", c,
992 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800993 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800994 tail_lines = 1;
995 }
996 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800997 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800998
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800999 case 'D':
1000 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001001 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001002
Casey Dahlindc42a872016-03-17 16:18:55 -07001003 case 'e':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001004 context->regex = new pcrecpp::RE(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001005 break;
Casey Dahlindc42a872016-03-17 16:18:55 -07001006
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001007 case 'm': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001008 if (!getSizeTArg(optarg, &context->maxCount)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001009 logcat_panic(context, HELP_FALSE,
Elliott Hughes61b580e2018-06-15 15:16:20 -07001010 "-%c \"%s\" isn't an integer greater than zero\n", c, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001011 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001012 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001013 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001014
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001015 case 'g':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001016 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001017 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001018 break;
1019 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001020 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001021
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001022 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001023 char* cp;
Elliott Hughes61b580e2018-06-15 15:16:20 -07001024 if (strtoll(optarg, &cp, 0) > 0) {
1025 setLogSize = strtoll(optarg, &cp, 0);
Traian Schiau59763032015-04-10 15:51:39 +03001026 } else {
1027 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001028 }
1029
Mark Salyzyn5f606602017-02-10 13:09:07 -08001030 switch (*cp) {
1031 case 'g':
1032 case 'G':
1033 setLogSize *= 1024;
1034 // FALLTHRU
1035 case 'm':
1036 case 'M':
1037 setLogSize *= 1024;
1038 // FALLTHRU
1039 case 'k':
1040 case 'K':
1041 setLogSize *= 1024;
1042 // FALLTHRU
1043 case '\0':
1044 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001045
Mark Salyzyn5f606602017-02-10 13:09:07 -08001046 default:
1047 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001048 }
1049
1050 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001051 logcat_panic(context, HELP_FALSE,
1052 "ERROR: -G <num><multiplier>\n");
1053 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001054 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001055 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001056
1057 case 'p':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001058 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001059 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001060 break;
1061 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001062 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001063
1064 case 'P':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001065 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001066 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001067
Joe Onorato6fa09a02010-02-26 10:04:23 -08001068 case 'b': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001069 std::unique_ptr<char, void (*)(void*)> buffers(strdup(optarg), free);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001070 char* arg = buffers.get();
Mark Salyzyn45177732016-04-11 14:03:48 -07001071 unsigned idMask = 0;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001072 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001073 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1074 if (!strcmp(arg, "default")) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001075 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001076 (1 << LOG_ID_CRASH);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001077 } else if (!strcmp(arg, "all")) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001078 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001079 idMask = (unsigned)-1;
1080 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001081 log_id_t log_id = android_name_to_log_id(arg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001082 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001083
Mark Salyzyne9ade172017-03-02 15:09:41 -08001084 if (!!strcmp(name, arg)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001085 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001086 "unknown buffer %s\n", arg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001087 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001088 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001089 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001090 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001091 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001092 arg = nullptr;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001093 }
1094
Mark Salyzyn45177732016-04-11 14:03:48 -07001095 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001096 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001097 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001098
Mark Salyzynde022a82017-03-01 08:30:06 -08001099 if (log_id != (log_id_t)i) continue;
1100 if (!(idMask & (1 << i))) continue;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001101
Mark Salyzyn45177732016-04-11 14:03:48 -07001102 bool found = false;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001103 for (dev = context->devices; dev; dev = dev->next) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001104 if (!strcmp(name, dev->device)) {
1105 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001106 break;
1107 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001108 if (!dev->next) break;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001109 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001110 if (found) continue;
Mark Salyzyn45177732016-04-11 14:03:48 -07001111
Stefan Lafon701a0652017-08-24 20:14:06 -07001112 bool binary = !strcmp(name, "events") ||
1113 !strcmp(name, "security") ||
1114 !strcmp(name, "stats");
Mark Salyzyn45177732016-04-11 14:03:48 -07001115 log_device_t* d = new log_device_t(name, binary);
1116
Mark Salyzyn083b0372015-12-04 10:59:45 -08001117 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001118 dev->next = d;
1119 dev = d;
1120 } else {
Mark Salyzyn13e47352017-03-06 14:56:04 -08001121 context->devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001122 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001123 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001124 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001125 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001126
1127 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001128 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001129 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130
1131 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001132 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001133 tail_time = lastLogTime(optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -07001134 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135 // redirect output to a file
Elliott Hughes61b580e2018-06-15 15:16:20 -07001136 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001137 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001138
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001139 case 'r':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001140 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1141 logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -r\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001142 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001143 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001144 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001145
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001146 case 'n':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001147 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1148 logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -n\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001149 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001150 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001151 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152
Mark Salyzynb45a1752017-02-28 09:20:31 -08001153 case 'v': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001154 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001155 show_format_help(context);
1156 context->retval = EXIT_SUCCESS;
1157 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001158 }
Elliott Hughes61b580e2018-06-15 15:16:20 -07001159 std::unique_ptr<char, void (*)(void*)> formats(strdup(optarg), free);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001160 char* arg = formats.get();
Mark Salyzynb45a1752017-02-28 09:20:31 -08001161 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001162 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1163 err = setLogFormat(context, arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001164 if (err < 0) {
1165 logcat_panic(context, HELP_FORMAT,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001166 "Invalid parameter \"%s\" to -v\n", arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001167 goto exit;
1168 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001169 arg = nullptr;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001170 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001172 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001173
1174 case 'Q':
bohu94aab862017-02-21 14:31:19 -08001175#define LOGCAT_FILTER "androidboot.logcat="
1176#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -08001177#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -08001178#define QEMU_PROPERTY "ro.kernel.qemu"
1179#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -08001180 // This is a *hidden* option used to start a version of logcat
1181 // in an emulated device only. It basically looks for
1182 // androidboot.logcat= on the kernel command line. If
1183 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -08001184 // run the program. The logcat output will go to consolepipe if
1185 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
1186 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187 {
bohu94aab862017-02-21 14:31:19 -08001188 // if not in emulator, exit quietly
1189 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001190 context->retval = EXIT_SUCCESS;
1191 goto exit;
1192 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001193
bohu94aab862017-02-21 14:31:19 -08001194 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
1195 if (cmdline.empty()) {
1196 android::base::ReadFileToString("/proc/cmdline", &cmdline);
1197 }
1198
1199 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
1200 // if nothing found or invalid filters, exit quietly
1201 if (!logcatFilter) {
1202 context->retval = EXIT_SUCCESS;
1203 goto exit;
1204 }
1205
1206 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -08001207 const char* q = strpbrk(p, " \t\n\r");
1208 if (!q) q = p + strlen(p);
1209 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001210
bohu94aab862017-02-21 14:31:19 -08001211 // redirect our output to the emulator console pipe or console
1212 const char* consolePipe =
1213 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -08001214 const char* console =
1215 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001216
bohu94aab862017-02-21 14:31:19 -08001217 if (consolePipe) {
1218 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
1219 } else if (console) {
1220 p = console + strlen(CONSOLE_OPTION);
1221 } else {
1222 context->retval = EXIT_FAILURE;
1223 goto exit;
1224 }
1225
Mark Salyzynf3290292017-02-10 13:09:07 -08001226 q = strpbrk(p, " \t\n\r");
1227 int len = q ? q - p : strlen(p);
1228 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -08001229 std::string pipePurpose("pipe:logcat");
1230 if (consolePipe) {
1231 // example: "qemu_pipe,pipe:logcat"
1232 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
1233 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -07001234 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -08001235 if (pos != std::string::npos) {
1236 pipePurpose = devname.substr(pos + 1);
1237 devname = devname.substr(0, pos);
1238 }
1239 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001240 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001241
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001242 if (context->error) {
1243 fprintf(context->error, "logcat using %s\n",
1244 devname.c_str());
1245 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001246
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001247 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001248 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001249 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001250
bohu94aab862017-02-21 14:31:19 -08001251 if (consolePipe) {
1252 // need the trailing '\0'
1253 if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
1254 pipePurpose.size() + 1)) {
1255 fclose(fp);
1256 context->retval = EXIT_FAILURE;
1257 goto exit;
1258 }
1259 }
1260
Mark Salyzynf3290292017-02-10 13:09:07 -08001261 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001262 android::close_output(context);
1263 android::close_error(context);
1264 context->stderr_stdout = true;
1265 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001266 context->output_fd = fileno(fp);
1267 if (context->stderr_null) break;
1268 context->stderr_stdout = true;
1269 context->error = fp;
1270 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001271 }
1272 break;
1273
Mark Salyzyn34facab2014-02-06 14:48:50 -08001274 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001275 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001276 break;
1277
Traian Schiau59763032015-04-10 15:51:39 +03001278 case ':':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001279 logcat_panic(context, HELP_TRUE, "Option -%c needs an argument\n", optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001280 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001281
Mark Salyzyne74e51d2017-04-03 09:30:20 -07001282 case 'h':
1283 show_help(context);
1284 show_format_help(context);
1285 goto exit;
1286
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001287 default:
Elliott Hughes61b580e2018-06-15 15:16:20 -07001288 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n", optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001289 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001290 }
1291 }
1292
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001293 if (context->maxCount && got_t) {
1294 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001295 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001296 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001297 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001298 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001299 // One day it would be nice if --print -v color and --regex <expr>
1300 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001301 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001302 if (context->error) {
1303 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001304 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001305 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001306 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001307 }
1308 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001309 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001310
Mark Salyzyn13e47352017-03-06 14:56:04 -08001311 if (!context->devices) {
1312 dev = context->devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001313 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001314 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001315 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001316 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001317 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001318 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001319 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001320 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001321 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001322 }
1323
Mark Salyzynde022a82017-03-01 08:30:06 -08001324 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001325 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1326 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001327 }
1328
Mark Salyzynde022a82017-03-01 08:30:06 -08001329 if (!!setId) {
1330 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001331 logcat_panic(context, HELP_TRUE,
1332 "--id='%s' requires -f as well\n", setId);
1333 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001334 }
1335
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001336 std::string file_name = android::base::StringPrintf(
1337 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001338 std::string file;
1339 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001340 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1341 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001342 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001343 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001344
Mark Salyzynde022a82017-03-01 08:30:06 -08001345 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001346 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001347
Mark Salyzynde022a82017-03-01 08:30:06 -08001348 if (!!logFormat) {
Mark Salyzynb45a1752017-02-28 09:20:31 -08001349 std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
1350 free);
1351 char* sv = nullptr; // protect against -ENOMEM above
1352 char* arg = formats.get();
1353 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1354 err = setLogFormat(context, arg);
1355 // environment should not cause crash of logcat
1356 if ((err < 0) && context->error) {
1357 fprintf(context->error,
1358 "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
1359 }
1360 arg = nullptr;
1361 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001362 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001363 }
1364 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001365 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001366 }
1367 }
1368
Mark Salyzynf3290292017-02-10 13:09:07 -08001369 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001370 err = android_log_addFilterString(context->logformat,
1371 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001372 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001373 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001374 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001375 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001376 }
Elliott Hughes61b580e2018-06-15 15:16:20 -07001377 } else if (argc == optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001378 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001379 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001380
Mark Salyzynde022a82017-03-01 08:30:06 -08001381 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001382 err = android_log_addFilterString(context->logformat,
1383 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001384
Mark Salyzyn95132e92013-11-22 10:55:48 -08001385 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001386 logcat_panic(context, HELP_TRUE,
1387 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1388 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001389 }
1390 }
1391 } else {
1392 // Add from commandline
Elliott Hughes61b580e2018-06-15 15:16:20 -07001393 for (int i = optind ; i < argc ; i++) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001394 // skip stderr redirections of _all_ kinds
1395 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001396 // skip stdout redirections of _all_ kinds
1397 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001398
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001399 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001400 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001401 logcat_panic(context, HELP_TRUE,
1402 "Invalid filter expression '%s'\n", argv[i]);
1403 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001404 }
1405 }
1406 }
1407
Mark Salyzyn13e47352017-03-06 14:56:04 -08001408 dev = context->devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001409 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001410 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001411 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001412 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001413 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001414 // We have three orthogonal actions below to clear, set log size and
1415 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001416 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001417 dev->logger_list = logger_list;
1418 dev->logger = android_logger_open(logger_list,
1419 android_name_to_log_id(dev->device));
1420 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001421 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001422 dev = dev->next;
1423 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001424 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001425
Mark Salyzyn02687e72016-08-03 14:20:41 -07001426 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001427 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001428 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001429 (context->maxRotatedLogs > 0) ?
1430 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1431 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001432
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001433 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001434 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001435
Mark Salyzynde022a82017-03-01 08:30:06 -08001436 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001437 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001438 "%s", context->outputFileName);
1439 } else {
1440 file = android::base::StringPrintf("%s.%.*d",
1441 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001442 }
1443
Mark Salyzynde022a82017-03-01 08:30:06 -08001444 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001445 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001446 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001447 break;
1448 }
1449
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001450 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001451
Mark Salyzynde022a82017-03-01 08:30:06 -08001452 if (err < 0 && errno != ENOENT && !clearFail) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001453 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001454 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001455 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001456 }
1457 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001458 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001459 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001460 }
1461
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001462 if (setLogSize) {
1463 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001464 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001465 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001466 }
1467
Joe Onorato6fa09a02010-02-26 10:04:23 -08001468 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001469 long size = android_logger_get_log_size(dev->logger);
1470 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001471
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001472 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001473 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001474 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001475 std::string str = android::base::StringPrintf(
1476 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1477 " max entry is %db, max payload is %db\n",
1478 dev->device,
1479 value_of_size(size), multiplier_of_size(size),
1480 value_of_size(readable), multiplier_of_size(readable),
1481 (int)LOGGER_ENTRY_MAX_LEN,
1482 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1483 TEMP_FAILURE_RETRY(write(context->output_fd,
1484 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001485 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001486 }
1487
1488 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001489 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001490
1491 context->retval = EXIT_SUCCESS;
1492
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001493 // report any errors in the above loop and exit
1494 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001495 logcat_panic(context, HELP_FALSE,
1496 "Unable to open log device '%s'\n", openDeviceFail);
1497 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001498 }
1499 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001500 logcat_panic(context, HELP_FALSE,
1501 "failed to clear the '%s' log\n", clearFail);
1502 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001503 }
1504 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001505 logcat_panic(context, HELP_FALSE,
1506 "failed to set the '%s' log size\n", setSizeFail);
1507 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001508 }
1509 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001510 logcat_panic(context, HELP_FALSE,
1511 "failed to get the readable '%s' log size", getSizeFail);
1512 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001513 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001514
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001515 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001516 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001517 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001518 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001519 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001520 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1521 buf[len] = '\0';
1522 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001523 logcat_panic(context, HELP_FALSE,
1524 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001525 }
1526 free(buf);
1527 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001528 logcat_panic(context, HELP_FALSE,
1529 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001530 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001531 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001532 }
1533
Mark Salyzyn1c950472014-04-01 17:19:47 -07001534 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001535 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001536 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001537
Mark Salyzyn5f606602017-02-10 13:09:07 -08001538 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001539 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001540 if (getPruneList) {
1541 android_logger_get_prune_list(logger_list, buf, len);
1542 } else {
1543 android_logger_get_statistics(logger_list, buf, len);
1544 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001545 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001546 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001547 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001548 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001549 break;
1550 }
Traian Schiau59763032015-04-10 15:51:39 +03001551 size_t ret = atol(buf) + 1;
1552 if (ret <= len) {
1553 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001554 break;
1555 }
Traian Schiau59763032015-04-10 15:51:39 +03001556 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001557 }
1558
1559 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001560 logcat_panic(context, HELP_FALSE, "failed to read data");
1561 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001562 }
1563
1564 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001565 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001566 *cp = '\0';
1567 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001568 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001569
1570 // squash out the byte count
1571 cp = buf;
1572 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001573 while (isdigit(*cp)) ++cp;
1574 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001575 }
1576
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001577 len = strlen(cp);
1578 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001579 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001580 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001581 }
1582
Mark Salyzynde022a82017-03-01 08:30:06 -08001583 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001584
Mark Salyzynde022a82017-03-01 08:30:06 -08001585 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001586 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001587
Mark Salyzyn5f606602017-02-10 13:09:07 -08001588 // LOG_EVENT_INT(10, 12345);
1589 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1590 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001591
Mark Salyzynde022a82017-03-01 08:30:06 -08001592 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001593
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001594 while (!context->stop &&
1595 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001596 struct log_msg log_msg;
1597 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001598 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001599 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1600 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001601 }
1602
1603 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001604 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001605
1606 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001607 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1608 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001609 }
1610 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001611 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1612 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001613 }
Luca Stefani08705142017-07-08 17:48:00 +02001614 logcat_panic(context, HELP_FALSE, "logcat read failure\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001615 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001616 }
1617
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001618 log_device_t* d;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001619 for (d = context->devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001620 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001621 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001622 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001623 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001624 d = &unexpected;
1625 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001626 }
1627
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001628 if (dev != d) {
1629 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001630 maybePrintStart(context, dev, printDividers);
1631 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001632 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001633 if (context->printBinary) {
1634 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001635 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001636 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001637 }
1638 }
1639
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001640close:
Mark Salyzyn13e47352017-03-06 14:56:04 -08001641 // Short and sweet. Implemented generic version in android_logcat_destroy.
1642 while (!!(dev = context->devices)) {
1643 context->devices = dev->next;
1644 delete dev;
1645 }
Mark Salyzyn95132e92013-11-22 10:55:48 -08001646 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001647
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001648exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001649 // close write end of pipe to help things along
1650 if (context->output_fd == context->fds[1]) {
1651 android::close_output(context);
1652 }
1653 if (context->error_fd == context->fds[1]) {
1654 android::close_error(context);
1655 }
1656 if (context->fds[1] >= 0) {
1657 // NB: should be closed by the above
1658 int save_errno = errno;
1659 close(context->fds[1]);
1660 errno = save_errno;
1661 context->fds[1] = -1;
1662 }
1663 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001664 return context->retval;
1665}
1666
1667// Can block
1668int android_logcat_run_command(android_logcat_context ctx,
1669 int output, int error,
1670 int argc, char* const* argv,
1671 char* const* envp) {
1672 android_logcat_context_internal* context = ctx;
1673
1674 context->output_fd = output;
1675 context->error_fd = error;
1676 context->argc = argc;
1677 context->argv = argv;
1678 context->envp = envp;
1679 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001680 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001681 return __logcat(context);
1682}
1683
1684// Finished with context
1685int android_logcat_destroy(android_logcat_context* ctx) {
1686 android_logcat_context_internal* context = *ctx;
1687
Mark Salyzynde022a82017-03-01 08:30:06 -08001688 if (!context) return -EBADF;
1689
1690 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001691
1692 context->stop = true;
1693
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001694 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001695 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001696 sched_yield();
1697 }
1698
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001699 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001700 context->argv_hold.clear();
1701 context->args.clear();
1702 context->envp_hold.clear();
1703 context->envs.clear();
1704 if (context->fds[0] >= 0) {
1705 close(context->fds[0]);
1706 context->fds[0] = -1;
1707 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001708 android::close_output(context);
1709 android::close_error(context);
Josh Gao03d055d2017-10-18 15:42:00 -07001710
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001711 if (context->fds[1] >= 0) {
Josh Gao03d055d2017-10-18 15:42:00 -07001712 // NB: this should be closed by close_output, but just in case...
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001713 close(context->fds[1]);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001714 context->fds[1] = -1;
1715 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001716
1717 android_closeEventTagMap(context->eventTagMap);
1718
Mark Salyzyn13e47352017-03-06 14:56:04 -08001719 // generic cleanup of devices list to handle all possible dirty cases
1720 log_device_t* dev;
1721 while (!!(dev = context->devices)) {
1722 struct logger_list* logger_list = dev->logger_list;
1723 if (logger_list) {
1724 for (log_device_t* d = dev; d; d = d->next) {
1725 if (d->logger_list == logger_list) d->logger_list = nullptr;
1726 }
1727 android_logger_list_free(logger_list);
1728 }
1729 context->devices = dev->next;
1730 delete dev;
1731 }
1732
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001733 int retval = context->retval;
1734
1735 free(context);
1736
1737 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001738}