blob: 0f1badb15a848be264ccac6fdadd73a5c86ac675 [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>
Wei Wangc27d4812018-09-05 11:05:57 -070044#include <utility>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080045#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070046
Elliott Hughes4f713192015-12-04 22:00:26 -080047#include <android-base/file.h>
bohu94aab862017-02-21 14:31:19 -080048#include <android-base/properties.h>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070049#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080050#include <android-base/strings.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070051#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080052#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070053#include <log/event_tag_map.h>
Colin Cross9227bd32013-07-23 16:59:20 -070054#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070055#include <private/android_logger.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080056#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
Casey Dahlindc42a872016-03-17 16:18:55 -070058#include <pcrecpp.h>
59
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080060#define DEFAULT_MAX_ROTATED_LOGS 4
61
Mark Salyzyn13e47352017-03-06 14:56:04 -080062struct log_device_t {
63 const char* device;
64 bool binary;
65 struct logger* logger;
66 struct logger_list* logger_list;
67 bool printed;
68
69 log_device_t* next;
70
71 log_device_t(const char* d, bool b) {
72 device = d;
73 binary = b;
74 next = nullptr;
75 printed = false;
76 logger = nullptr;
77 logger_list = nullptr;
78 }
79};
80
Mark Salyzync0cf90d2017-02-10 13:09:07 -080081struct android_logcat_context_internal {
82 // status
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080083 volatile std::atomic_int retval; // valid if thread_stopped set
84 // Arguments passed in, or copies and storage thereof if a thread.
Mark Salyzync0cf90d2017-02-10 13:09:07 -080085 int argc;
86 char* const* argv;
87 char* const* envp;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080088 std::vector<std::string> args;
89 std::vector<const char*> argv_hold;
90 std::vector<std::string> envs;
91 std::vector<const char*> envp_hold;
Mark Salyzynde022a82017-03-01 08:30:06 -080092 int output_fd; // duplication of fileno(output) (below)
93 int error_fd; // duplication of fileno(error) (below)
Mark Salyzync0cf90d2017-02-10 13:09:07 -080094
95 // library
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080096 int fds[2]; // From popen call
97 FILE* output; // everything writes to fileno(output), buffer unused
98 FILE* error; // unless error == output.
99 pthread_t thr;
100 volatile std::atomic_bool stop; // quick exit flag
101 volatile std::atomic_bool thread_stopped;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800102 bool stderr_null; // shell "2>/dev/null"
103 bool stderr_stdout; // shell "2>&1"
104
105 // global variables
106 AndroidLogFormat* logformat;
107 const char* outputFileName;
108 // 0 means "no log rotation"
109 size_t logRotateSizeKBytes;
110 // 0 means "unbounded"
111 size_t maxRotatedLogs;
112 size_t outByteCount;
113 int printBinary;
114 int devCount; // >1 means multiple
115 pcrecpp::RE* regex;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800116 log_device_t* devices;
117 EventTagMap* eventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800118 // 0 means "infinite"
119 size_t maxCount;
120 size_t printCount;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800121
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800122 bool printItAnyways;
123 bool debug;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800124 bool hasOpenedEventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800125};
126
127// Creates a context associated with this logcat instance
128android_logcat_context create_android_logcat() {
129 android_logcat_context_internal* context;
130
131 context = (android_logcat_context_internal*)calloc(
132 1, sizeof(android_logcat_context_internal));
Mark Salyzynde022a82017-03-01 08:30:06 -0800133 if (!context) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800134
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800135 context->fds[0] = -1;
136 context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800137 context->output_fd = -1;
138 context->error_fd = -1;
139 context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
140
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800141 context->argv_hold.clear();
142 context->args.clear();
143 context->envp_hold.clear();
144 context->envs.clear();
145
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800146 return (android_logcat_context)context;
147}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
Mark Salyzyn5f606602017-02-10 13:09:07 -0800149// logd prefixes records with a length field
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800150#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
151
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152namespace android {
153
Mark Salyzyn5f606602017-02-10 13:09:07 -0800154enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700155
Mark Salyzynaa730c12016-03-30 12:38:29 -0700156// if showHelp is set, newline required in fmt statement to transition to usage
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800157static void logcat_panic(android_logcat_context_internal* context,
158 enum helpType showHelp, const char* fmt, ...)
159 __printflike(3, 4);
Traian Schiau59763032015-04-10 15:51:39 +0300160
Mark Salyzyn5f606602017-02-10 13:09:07 -0800161static int openLogFile(const char* pathname) {
Edwin Vane80b221c2012-08-13 12:55:07 -0400162 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163}
164
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800165static void close_output(android_logcat_context_internal* context) {
166 // split output_from_error
167 if (context->error == context->output) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800168 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800169 context->output_fd = -1;
170 }
171 if (context->error && (context->output_fd == fileno(context->error))) {
172 context->output_fd = -1;
173 }
174 if (context->output_fd == context->error_fd) {
175 context->output_fd = -1;
176 }
177 // close output channel
178 if (context->output) {
179 if (context->output != stdout) {
180 if (context->output_fd == fileno(context->output)) {
181 context->output_fd = -1;
182 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800183 if (context->fds[1] == fileno(context->output)) {
184 context->fds[1] = -1;
185 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800186 fclose(context->output);
187 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800188 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800189 }
190 if (context->output_fd >= 0) {
191 if (context->output_fd != fileno(stdout)) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800192 if (context->fds[1] == context->output_fd) {
193 context->fds[1] = -1;
194 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800195 close(context->output_fd);
196 }
197 context->output_fd = -1;
198 }
199}
200
201static void close_error(android_logcat_context_internal* context) {
202 // split error_from_output
203 if (context->output == context->error) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800204 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800205 context->error_fd = -1;
206 }
207 if (context->output && (context->error_fd == fileno(context->output))) {
208 context->error_fd = -1;
209 }
210 if (context->error_fd == context->output_fd) {
211 context->error_fd = -1;
212 }
213 // close error channel
214 if (context->error) {
215 if ((context->error != stderr) && (context->error != stdout)) {
216 if (context->error_fd == fileno(context->error)) {
217 context->error_fd = -1;
218 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800219 if (context->fds[1] == fileno(context->error)) {
220 context->fds[1] = -1;
221 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800222 fclose(context->error);
223 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800224 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800225 }
226 if (context->error_fd >= 0) {
227 if ((context->error_fd != fileno(stdout)) &&
228 (context->error_fd != fileno(stderr))) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800229 if (context->fds[1] == context->error_fd) context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800230 close(context->error_fd);
231 }
232 context->error_fd = -1;
233 }
234}
235
236static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800237 int err;
238
239 // Can't rotate logs if we're not outputting to a file
Mark Salyzynde022a82017-03-01 08:30:06 -0800240 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800241
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800242 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800243
Mark Salyzyn5f606602017-02-10 13:09:07 -0800244 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800245 // maxRotatedLogs in decimal. eg:
246 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800247 // -> log10(30) == 1.477
248 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700249 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800250 (context->maxRotatedLogs > 0)
251 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
252 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700253
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800254 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700255 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800256 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700258 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800259 if (!(i - 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800260 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800261 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800262 file0 =
263 android::base::StringPrintf("%s.%.*d", context->outputFileName,
264 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800265 }
266
Mark Salyzynde022a82017-03-01 08:30:06 -0800267 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300268 perror("while rotating log files");
269 break;
270 }
271
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700272 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800273
274 if (err < 0 && errno != ENOENT) {
275 perror("while rotating log files");
276 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277 }
278
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800279 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800280
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800281 if (context->output_fd < 0) {
282 logcat_panic(context, HELP_FALSE, "couldn't open output file");
283 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800285 context->output = fdopen(context->output_fd, "web");
Mark Salyzynde022a82017-03-01 08:30:06 -0800286 if (!context->output) {
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800287 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
288 return;
289 }
290 if (context->stderr_stdout) {
291 close_error(context);
292 context->error = context->output;
293 context->error_fd = context->output_fd;
294 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800296 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800297}
298
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800299void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800300 size_t size = buf->len();
301
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800302 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800303}
304
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800305static bool regexOk(android_logcat_context_internal* context,
306 const AndroidLogEntry& entry) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800307 if (!context->regex) return true;
Casey Dahlindc42a872016-03-17 16:18:55 -0700308
Casey Dahlindc42a872016-03-17 16:18:55 -0700309 std::string messageString(entry.message, entry.messageLen);
310
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800311 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700312}
313
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800314static void processBuffer(android_logcat_context_internal* context,
315 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700316 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317 int err;
318 AndroidLogEntry entry;
319 char binaryMsgBuf[1024];
320
Joe Onorato6fa09a02010-02-26 10:04:23 -0800321 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800322 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800323 context->eventTagMap = android_openEventTagMap(nullptr);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800324 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800325 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800326 err = android_log_processBinaryLogBuffer(
327 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
328 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800329 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 // entry.priority, entry.messageLen, entry.message);
331 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800332 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800334 if ((err < 0) && !context->debug) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800335
Mark Salyzyn5f606602017-02-10 13:09:07 -0800336 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800337 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800338 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800339 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800340
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800341 context->printCount += match;
342 if (match || context->printItAnyways) {
343 bytesWritten = android_log_printLogLine(context->logformat,
344 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700345
Mark Salyzync9202772016-03-30 09:38:31 -0700346 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800347 logcat_panic(context, HELP_FALSE, "output error");
348 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700349 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800350 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351 }
352
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800353 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800355 if (context->logRotateSizeKBytes > 0 &&
356 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
357 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800359}
360
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800361static void maybePrintStart(android_logcat_context_internal* context,
362 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800363 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800364 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800365 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800366 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800367 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800368 if (write(context->output_fd, buf, strlen(buf)) < 0) {
369 logcat_panic(context, HELP_FALSE, "output error");
370 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800371 }
372 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800373 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800374 }
375}
376
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800377static void setupOutputAndSchedulingPolicy(
378 android_logcat_context_internal* context, bool blocking) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800379 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800380
Mark Salyzynad5e4112016-08-04 07:53:52 -0700381 if (blocking) {
382 // Lower priority and set to batch scheduling if we are saving
383 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800384 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
385 fprintf(context->error,
386 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700387 }
388
389 struct sched_param param;
390 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800391 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700392 fprintf(stderr, "failed to set to batch scheduler\n");
393 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800394
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800395 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
396 context->error) {
397 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700398 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800399 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700400
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800401 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700402
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800403 context->output_fd = openLogFile(context->outputFileName);
404
405 if (context->output_fd < 0) {
406 logcat_panic(context, HELP_FALSE, "couldn't open output file");
407 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700408 }
409
410 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800411 if (fstat(context->output_fd, &statbuf) == -1) {
412 close_output(context);
413 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
414 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700415 }
416
Mark Salyzyn5f606602017-02-10 13:09:07 -0800417 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800418 close_output(context);
419 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
420 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700421 }
422
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800423 context->output = fdopen(context->output_fd, "web");
424
425 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800426}
427
Mark Salyzyn5f606602017-02-10 13:09:07 -0800428// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800429static void show_help(android_logcat_context_internal* context) {
430 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800431
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800432 const char* cmd = strrchr(context->argv[0], '/');
433 cmd = cmd ? cmd + 1 : context->argv[0];
434
435 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
436
437 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700438 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
439 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700440 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
441 " Rotate log every kbytes. Requires -f option\n"
442 " -n <count>, --rotate-count=<count>\n"
443 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700444 " --id=<id> If the signature id for logging to file changes, then clear\n"
445 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700446 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700447 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700448 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700449 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700450 " color descriptive epoch monotonic printable uid\n"
451 " usec UTC year zone\n"
Mark Salyzynb45a1752017-02-28 09:20:31 -0800452 " Multiple -v parameters or comma separated list of format and\n"
453 " format modifiers are allowed.\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800454 // private and undocumented nsec, no signal, too much noise
455 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700456 " -D, --dividers Print dividers between each log buffer\n"
457 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700458 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700459 " -d Dump the log and then exit (don't block)\n"
460 " -e <expr>, --regex=<expr>\n"
461 " Only print lines where the log message matches <expr>\n"
Brendan Jackmana5141132017-10-31 12:44:54 +0000462 " where <expr> is a Perl-compatible regular expression\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700463 // Leave --head undocumented as alias for -m
464 " -m <count>, --max-count=<count>\n"
465 " Quit after printing <count> lines. This is meant to be\n"
466 " paired with --regex, but will work on its own.\n"
467 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700468 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700469 // Leave --tail undocumented as alias for -t
470 " -t <count> Print only the most recent <count> lines (implies -d)\n"
471 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
472 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
473 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700474 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700475 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700476 " -g, --buffer-size Get the size of the ring buffer.\n"
477 " -G <size>, --buffer-size=<size>\n"
478 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100479 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800480 // Leave security (Device Owner only installations) and
481 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700482 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
483 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700484 " Multiple -b parameters or comma separated list of buffers are\n"
485 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700486 " -B, --binary Output the log in binary.\n"
487 " -S, --statistics Output statistics.\n"
488 " -p, --prune Print prune white and ~black list. Service is specified as\n"
489 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700490 " with ~, otherwise weighed for longevity if unadorned. All\n"
491 " other pruning activity is oldest first. Special case ~!\n"
492 " represents an automatic quicker pruning for the noisiest\n"
493 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700494 " -P '<list> ...', --prune='<list> ...'\n"
495 " Set prune white and ~black list, using same format as\n"
496 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800497 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700498 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800499 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
500 " comes first. Improves efficiency of polling by providing\n"
501 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800503 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800504 " <tag>[:priority]\n\n"
505 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700506 " V Verbose (default for <tag>)\n"
507 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508 " I Info\n"
509 " W Warn\n"
510 " E Error\n"
511 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700512 " S Silent (suppress all output)\n"
513 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
514 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
515 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
516 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
517 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700518 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800519}
520
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800521static void show_format_help(android_logcat_context_internal* context) {
522 if (!context->error) return;
523 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700524 "-v <format>, --format=<format> options:\n"
525 " Sets log print format verb and adverbs, where <format> is:\n"
526 " brief long process raw tag thread threadtime time\n"
527 " and individually flagged modifying adverbs can be added:\n"
528 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
529 "\nSingle format verbs:\n"
530 " brief — Display priority/tag and PID of the process issuing the message.\n"
531 " long — Display all metadata fields, separate messages with blank lines.\n"
532 " process — Display PID only.\n"
533 " raw — Display the raw log message, with no other metadata fields.\n"
534 " tag — Display the priority/tag only.\n"
Mark Salyzync74f8d92017-05-15 13:40:33 -0700535 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700536 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
537 " and TID of the thread issuing the message. (the default format).\n"
538 " time — Display the date, invocation time, priority/tag, and PID of the\n"
539 " process issuing the message.\n"
540 "\nAdverb modifiers can be used in combination:\n"
541 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
542 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
543 " descriptive — events logs only, descriptions from event-log-tags database.\n"
544 " epoch — Display time as seconds since Jan 1 1970.\n"
545 " monotonic — Display time as cpu seconds since last boot.\n"
546 " printable — Ensure that any binary logging content is escaped.\n"
547 " uid — If permitted, display the UID or Android ID of logged process.\n"
548 " usec — Display time down the microsecond precision.\n"
549 " UTC — Display time as UTC.\n"
550 " year — Add the year to the displayed time.\n"
551 " zone — Add the local timezone to the displayed time.\n"
552 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
553 );
554}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800555// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700556
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800557static int setLogFormat(android_logcat_context_internal* context,
558 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800559 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560
561 format = android_log_formatFromString(formatString);
562
Mark Salyzynde022a82017-03-01 08:30:06 -0800563 // invalid string?
564 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800566 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567}
568
Wei Wangc27d4812018-09-05 11:05:57 -0700569static std::pair<unsigned long, const char*> format_of_size(unsigned long value) {
570 static const char multipliers[][3] = {{""}, {"Ki"}, {"Mi"}, {"Gi"}};
571 size_t i;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700572 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800573 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
574 value /= 1024, ++i)
575 ;
Wei Wangc27d4812018-09-05 11:05:57 -0700576 return std::make_pair(value, multipliers[i]);
Mark Salyzyn671e3432014-05-06 07:34:59 -0700577}
578
Mark Salyzyn5f606602017-02-10 13:09:07 -0800579// String to unsigned int, returns -1 if it fails
580static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
581 size_t max = SIZE_MAX) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800582 if (!ptr) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300583
Mark Salyzyn5f606602017-02-10 13:09:07 -0800584 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700585 errno = 0;
586 size_t ret = (size_t)strtoll(ptr, &endp, 0);
587
Mark Salyzynde022a82017-03-01 08:30:06 -0800588 if (endp[0] || errno) return false;
Kristian Monsen562e5132015-06-05 14:10:12 -0700589
Mark Salyzynde022a82017-03-01 08:30:06 -0800590 if ((ret > max) || (ret < min)) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300591
592 *val = ret;
593 return true;
594}
595
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800596static void logcat_panic(android_logcat_context_internal* context,
597 enum helpType showHelp, const char* fmt, ...) {
598 context->retval = EXIT_FAILURE;
599 if (!context->error) {
600 context->stop = true;
601 return;
602 }
603
Mark Salyzyn5f606602017-02-10 13:09:07 -0800604 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700605 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800606 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700607 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300608
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700609 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800610 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800611 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800612 break;
613 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800614 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800615 break;
616 case HELP_FALSE:
617 default:
618 break;
Traian Schiau59763032015-04-10 15:51:39 +0300619 }
620
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800621 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300622}
623
Mark Salyzyn5f606602017-02-10 13:09:07 -0800624static char* parseTime(log_time& t, const char* cp) {
625 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800626 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700627 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800628 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700629 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700630}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700631
Mark Salyzyn31961062016-08-04 07:43:46 -0700632// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyne9ade172017-03-02 15:09:41 -0800633static log_time lastLogTime(const char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700634 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800635 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700636
Mark Salyzynf3555d92015-05-27 07:39:56 -0700637 std::string directory;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800638 const char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700639 if (!file) {
640 directory = ".";
641 file = outputFileName;
642 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800643 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700644 ++file;
645 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700646
Mark Salyzyn5f606602017-02-10 13:09:07 -0800647 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
648 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800649 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700650
Mark Salyzyn31961062016-08-04 07:43:46 -0700651 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700652
Mark Salyzynf3555d92015-05-27 07:39:56 -0700653 size_t len = strlen(file);
654 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800655 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700656
Mark Salyzynde022a82017-03-01 08:30:06 -0800657 while (!!(dp = readdir(dir.get()))) {
658 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800659 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800660 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700661 continue;
662 }
663
664 std::string file_name = directory;
665 file_name += "/";
666 file_name += dp->d_name;
667 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800668 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700669
670 bool found = false;
671 for (const auto& line : android::base::Split(file, "\n")) {
672 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800673 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800674 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700675 // determine the time precision of the logs (eg: msec or usec)
676 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
677 if (t.tv_nsec % (mod * 10)) {
678 modulo.tv_nsec = mod;
679 break;
680 }
681 }
682 // We filter any times later than current as we may not have the
683 // year stored with each log entry. Also, since it is possible for
684 // entries to be recorded out of order (very rare) we select the
685 // maximum we find just in case.
686 if ((t < now) && (t > retval)) {
687 retval = t;
688 found = true;
689 }
690 }
691 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800692 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700693 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800694 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700695 // tail_time prints matching or higher, round up by the modulo to prevent
696 // a replay of the last entry we have just checked.
697 retval += modulo;
698 return retval;
699}
700
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800701const char* getenv(android_logcat_context_internal* context, const char* name) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800702 if (!context->envp || !name || !*name) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800703
704 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
705 if (strncmp(context->envp[i], name, len)) continue;
706 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
707 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800708 return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800709}
710
Mark Salyzyn5f606602017-02-10 13:09:07 -0800711} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300712
Mark Salyzyn5f606602017-02-10 13:09:07 -0800713void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800714 bool blockSecurity) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800715 if (*current) return;
716 if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
717 *current = name;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800718 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800719}
Traian Schiau59763032015-04-10 15:51:39 +0300720
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800721static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300722 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800723 int err;
Mark Salyzynb45a1752017-02-28 09:20:31 -0800724 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800725 bool clearLog = false;
726 bool allSelected = false;
727 bool getLogSize = false;
728 bool getPruneList = false;
729 bool printStatistics = false;
730 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800731 unsigned long setLogSize = 0;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800732 const char* setPruneList = nullptr;
733 const char* setId = nullptr;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800734 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800735 std::string forceFilters;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800736 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800737 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300738 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800739 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700740 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700741 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800742
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800743 // object instantiations before goto's can happen
744 log_device_t unexpected("unexpected", false);
Mark Salyzynde022a82017-03-01 08:30:06 -0800745 const char* openDeviceFail = nullptr;
746 const char* clearFail = nullptr;
747 const char* setSizeFail = nullptr;
748 const char* getSizeFail = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800749 int argc = context->argc;
750 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800751
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800752 context->output = stdout;
753 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800754
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800755 for (int i = 0; i < argc; ++i) {
756 // Simulate shell stderr redirect parsing
757 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
758
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800759 // Append to file not implemented, just open file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800760 size_t skip = (argv[i][2] == '>') + 2;
761 if (!strcmp(&argv[i][skip], "/dev/null")) {
762 context->stderr_null = true;
763 } else if (!strcmp(&argv[i][skip], "&1")) {
764 context->stderr_stdout = true;
765 } else {
766 // stderr file redirections are not supported
767 fprintf(context->stderr_stdout ? stdout : stderr,
768 "stderr redirection to file %s unsupported, skipping\n",
769 &argv[i][skip]);
770 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800771 // Only the first one
772 break;
773 }
774
Mark Salyzynde022a82017-03-01 08:30:06 -0800775 const char* filename = nullptr;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800776 for (int i = 0; i < argc; ++i) {
777 // Simulate shell stdout redirect parsing
778 if (argv[i][0] != '>') continue;
779
780 // Append to file not implemented, just open file
781 filename = &argv[i][(argv[i][1] == '>') + 1];
782 // Only the first one
783 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800784 }
785
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800786 // Deal with setting up file descriptors and FILE pointers
Mark Salyzynde022a82017-03-01 08:30:06 -0800787 if (context->error_fd >= 0) { // Is an error file descriptor supplied?
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800788 if (context->error_fd == context->output_fd) {
789 context->stderr_stdout = true;
Mark Salyzynde022a82017-03-01 08:30:06 -0800790 } else if (context->stderr_null) { // redirection told us to close it
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800791 close(context->error_fd);
792 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800793 } else { // All Ok, convert error to a FILE pointer
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800794 context->error = fdopen(context->error_fd, "web");
795 if (!context->error) {
796 context->retval = -errno;
797 fprintf(context->stderr_stdout ? stdout : stderr,
798 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
799 strerror(errno));
800 goto exit;
801 }
802 }
803 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800804 if (context->output_fd >= 0) { // Is an output file descriptor supplied?
805 if (filename) { // redirect to file, close supplied file descriptor.
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800806 close(context->output_fd);
807 context->output_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800808 } else { // All Ok, convert output to a FILE pointer
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800809 context->output = fdopen(context->output_fd, "web");
810 if (!context->output) {
811 context->retval = -errno;
812 fprintf(context->stderr_stdout ? stdout : context->error,
813 "Failed to fdopen(output_fd=%d) %s\n",
814 context->output_fd, strerror(errno));
815 goto exit;
816 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800817 }
818 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800819 if (filename) { // We supplied an output file redirected in command line
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800820 context->output = fopen(filename, "web");
821 }
822 // Deal with 2>&1
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800823 if (context->stderr_stdout) context->error = context->output;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800824 // Deal with 2>/dev/null
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800825 if (context->stderr_null) {
826 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800827 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800828 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800829 // Only happens if output=stdout or output=filename
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800830 if ((context->output_fd < 0) && context->output) {
831 context->output_fd = fileno(context->output);
832 }
833 // Only happens if error=stdout || error=stderr
834 if ((context->error_fd < 0) && context->error) {
835 context->error_fd = fileno(context->error);
836 }
837
838 context->logformat = android_log_format_new();
839
Mark Salyzynde022a82017-03-01 08:30:06 -0800840 if (argc == 2 && !strcmp(argv[1], "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800841 show_help(context);
842 context->retval = EXIT_SUCCESS;
843 goto exit;
844 }
845
Mark Salyzynb45a1752017-02-28 09:20:31 -0800846 // meant to catch comma-delimited values, but cast a wider
847 // net for stability dealing with possible mistaken inputs.
848 static const char delimiters[] = ",:; \t\n\r\f";
849
Elliott Hughes61b580e2018-06-15 15:16:20 -0700850 optind = 0;
851 while (true) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700852 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700853 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700854 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800855 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700856 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800857 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700858 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800859 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700860 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800861 { "binary", no_argument, nullptr, 'B' },
862 { "buffer", required_argument, nullptr, 'b' },
863 { "buffer-size", optional_argument, nullptr, 'g' },
864 { "clear", no_argument, nullptr, 'c' },
865 { debug_str, no_argument, nullptr, 0 },
866 { "dividers", no_argument, nullptr, 'D' },
867 { "file", required_argument, nullptr, 'f' },
868 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700869 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800870 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700871 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800872 { "head", required_argument, nullptr, 'm' },
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700873 { "help", no_argument, nullptr, 'h' },
Mark Salyzynde022a82017-03-01 08:30:06 -0800874 { id_str, required_argument, nullptr, 0 },
875 { "last", no_argument, nullptr, 'L' },
876 { "max-count", required_argument, nullptr, 'm' },
877 { pid_str, required_argument, nullptr, 0 },
878 { print_str, no_argument, nullptr, 0 },
879 { "prune", optional_argument, nullptr, 'p' },
880 { "regex", required_argument, nullptr, 'e' },
881 { "rotate-count", required_argument, nullptr, 'n' },
882 { "rotate-kbytes", required_argument, nullptr, 'r' },
883 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700884 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800885 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800886 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800887 { wrap_str, optional_argument, nullptr, 0 },
888 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700889 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800890 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700891
Elliott Hughes61b580e2018-06-15 15:16:20 -0700892 int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
893 &option_index);
894 if (c == -1) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800895
Elliott Hughes61b580e2018-06-15 15:16:20 -0700896 switch (c) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700897 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700898 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700899 if (long_options[option_index].name == pid_str) {
900 // ToDo: determine runtime PID_MAX?
Elliott Hughes61b580e2018-06-15 15:16:20 -0700901 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800902 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Elliott Hughes61b580e2018-06-15 15:16:20 -0700903 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800904 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700905 }
906 break;
907 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800908 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800909 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800910 ANDROID_LOG_NONBLOCK;
911 // ToDo: implement API that supports setting a wrap timeout
912 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Elliott Hughes61b580e2018-06-15 15:16:20 -0700913 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800914 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Elliott Hughes61b580e2018-06-15 15:16:20 -0700915 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800916 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800917 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800918 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
919 context->error) {
920 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800921 "WARNING: %s %u seconds, ignoring %zu\n",
922 long_options[option_index].name,
923 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
924 }
925 break;
926 }
Mark Salyzync9202772016-03-30 09:38:31 -0700927 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800928 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700929 break;
930 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800931 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800932 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800933 break;
934 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700935 if (long_options[option_index].name == id_str) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700936 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700937 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800938 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700939
Mark Salyzyn95132e92013-11-22 10:55:48 -0800940 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800941 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800942 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800943 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800944
945 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800946 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800947 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800948 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800950 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800951 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
952 ANDROID_LOG_NONBLOCK;
953 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800954
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800955 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800956 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800957 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800958
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800959 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700960 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800961 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800962 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800963 case 'T':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700964 if (strspn(optarg, "0123456789") != strlen(optarg)) {
965 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800966 if (!cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700967 logcat_panic(context, HELP_FALSE, "-%c \"%s\" not in time format\n", c,
968 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800969 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800970 }
971 if (*cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700972 char ch = *cp;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800973 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800974 if (context->error) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700975 fprintf(context->error, "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
976 c, optarg, ch, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800977 }
Elliott Hughes61b580e2018-06-15 15:16:20 -0700978 *cp = ch;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800979 }
980 } else {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700981 if (!getSizeTArg(optarg, &tail_lines, 1)) {
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 invalid, setting to 1\n", c,
984 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800985 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800986 tail_lines = 1;
987 }
988 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800989 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800990
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800991 case 'D':
992 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800993 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800994
Casey Dahlindc42a872016-03-17 16:18:55 -0700995 case 'e':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700996 context->regex = new pcrecpp::RE(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800997 break;
Casey Dahlindc42a872016-03-17 16:18:55 -0700998
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700999 case 'm': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001000 if (!getSizeTArg(optarg, &context->maxCount)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001001 logcat_panic(context, HELP_FALSE,
Elliott Hughes61b580e2018-06-15 15:16:20 -07001002 "-%c \"%s\" isn't an integer greater than zero\n", c, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001003 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001004 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001005 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001006
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 case 'g':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001008 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001009 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001010 break;
1011 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001012 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001014 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001015 char* cp;
Elliott Hughes61b580e2018-06-15 15:16:20 -07001016 if (strtoll(optarg, &cp, 0) > 0) {
1017 setLogSize = strtoll(optarg, &cp, 0);
Traian Schiau59763032015-04-10 15:51:39 +03001018 } else {
1019 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001020 }
1021
Mark Salyzyn5f606602017-02-10 13:09:07 -08001022 switch (*cp) {
1023 case 'g':
1024 case 'G':
1025 setLogSize *= 1024;
1026 // FALLTHRU
1027 case 'm':
1028 case 'M':
1029 setLogSize *= 1024;
1030 // FALLTHRU
1031 case 'k':
1032 case 'K':
1033 setLogSize *= 1024;
1034 // FALLTHRU
1035 case '\0':
1036 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001037
Mark Salyzyn5f606602017-02-10 13:09:07 -08001038 default:
1039 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001040 }
1041
1042 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001043 logcat_panic(context, HELP_FALSE,
1044 "ERROR: -G <num><multiplier>\n");
1045 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001046 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001047 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001048
1049 case 'p':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001050 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001051 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001052 break;
1053 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001054 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001055
1056 case 'P':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001057 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001058 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001059
Joe Onorato6fa09a02010-02-26 10:04:23 -08001060 case 'b': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001061 std::unique_ptr<char, void (*)(void*)> buffers(strdup(optarg), free);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001062 char* arg = buffers.get();
Mark Salyzyn45177732016-04-11 14:03:48 -07001063 unsigned idMask = 0;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001064 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001065 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1066 if (!strcmp(arg, "default")) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001067 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001068 (1 << LOG_ID_CRASH);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001069 } else if (!strcmp(arg, "all")) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001070 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001071 idMask = (unsigned)-1;
1072 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001073 log_id_t log_id = android_name_to_log_id(arg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001074 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001075
Mark Salyzyne9ade172017-03-02 15:09:41 -08001076 if (!!strcmp(name, arg)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001077 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001078 "unknown buffer %s\n", arg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001079 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001080 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001081 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001082 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001083 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001084 arg = nullptr;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001085 }
1086
Mark Salyzyn45177732016-04-11 14:03:48 -07001087 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001088 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001089 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001090
Mark Salyzynde022a82017-03-01 08:30:06 -08001091 if (log_id != (log_id_t)i) continue;
1092 if (!(idMask & (1 << i))) continue;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001093
Mark Salyzyn45177732016-04-11 14:03:48 -07001094 bool found = false;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001095 for (dev = context->devices; dev; dev = dev->next) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001096 if (!strcmp(name, dev->device)) {
1097 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001098 break;
1099 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001100 if (!dev->next) break;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001101 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001102 if (found) continue;
Mark Salyzyn45177732016-04-11 14:03:48 -07001103
Stefan Lafon701a0652017-08-24 20:14:06 -07001104 bool binary = !strcmp(name, "events") ||
1105 !strcmp(name, "security") ||
1106 !strcmp(name, "stats");
Mark Salyzyn45177732016-04-11 14:03:48 -07001107 log_device_t* d = new log_device_t(name, binary);
1108
Mark Salyzyn083b0372015-12-04 10:59:45 -08001109 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001110 dev->next = d;
1111 dev = d;
1112 } else {
Mark Salyzyn13e47352017-03-06 14:56:04 -08001113 context->devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001114 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001115 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001116 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001117 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001118
1119 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001120 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001121 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001122
1123 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001124 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001125 tail_time = lastLogTime(optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -07001126 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001127 // redirect output to a file
Elliott Hughes61b580e2018-06-15 15:16:20 -07001128 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001129 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001131 case 'r':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001132 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1133 logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -r\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001134 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001136 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001137
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001138 case 'n':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001139 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1140 logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -n\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001141 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001142 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001143 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001144
Mark Salyzynb45a1752017-02-28 09:20:31 -08001145 case 'v': {
Elliott Hughes61b580e2018-06-15 15:16:20 -07001146 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001147 show_format_help(context);
1148 context->retval = EXIT_SUCCESS;
1149 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001150 }
Elliott Hughes61b580e2018-06-15 15:16:20 -07001151 std::unique_ptr<char, void (*)(void*)> formats(strdup(optarg), free);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001152 char* arg = formats.get();
Mark Salyzynb45a1752017-02-28 09:20:31 -08001153 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001154 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1155 err = setLogFormat(context, arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001156 if (err < 0) {
1157 logcat_panic(context, HELP_FORMAT,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001158 "Invalid parameter \"%s\" to -v\n", arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001159 goto exit;
1160 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001161 arg = nullptr;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001162 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001163 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001164 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165
1166 case 'Q':
bohu94aab862017-02-21 14:31:19 -08001167#define LOGCAT_FILTER "androidboot.logcat="
1168#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -08001169#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -08001170#define QEMU_PROPERTY "ro.kernel.qemu"
1171#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -08001172 // This is a *hidden* option used to start a version of logcat
1173 // in an emulated device only. It basically looks for
1174 // androidboot.logcat= on the kernel command line. If
1175 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -08001176 // run the program. The logcat output will go to consolepipe if
1177 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
1178 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001179 {
bohu94aab862017-02-21 14:31:19 -08001180 // if not in emulator, exit quietly
1181 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001182 context->retval = EXIT_SUCCESS;
1183 goto exit;
1184 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001185
bohu94aab862017-02-21 14:31:19 -08001186 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
1187 if (cmdline.empty()) {
1188 android::base::ReadFileToString("/proc/cmdline", &cmdline);
1189 }
1190
1191 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
1192 // if nothing found or invalid filters, exit quietly
1193 if (!logcatFilter) {
1194 context->retval = EXIT_SUCCESS;
1195 goto exit;
1196 }
1197
1198 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -08001199 const char* q = strpbrk(p, " \t\n\r");
1200 if (!q) q = p + strlen(p);
1201 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202
bohu94aab862017-02-21 14:31:19 -08001203 // redirect our output to the emulator console pipe or console
1204 const char* consolePipe =
1205 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -08001206 const char* console =
1207 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001208
bohu94aab862017-02-21 14:31:19 -08001209 if (consolePipe) {
1210 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
1211 } else if (console) {
1212 p = console + strlen(CONSOLE_OPTION);
1213 } else {
1214 context->retval = EXIT_FAILURE;
1215 goto exit;
1216 }
1217
Mark Salyzynf3290292017-02-10 13:09:07 -08001218 q = strpbrk(p, " \t\n\r");
1219 int len = q ? q - p : strlen(p);
1220 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -08001221 std::string pipePurpose("pipe:logcat");
1222 if (consolePipe) {
1223 // example: "qemu_pipe,pipe:logcat"
1224 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
1225 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -07001226 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -08001227 if (pos != std::string::npos) {
1228 pipePurpose = devname.substr(pos + 1);
1229 devname = devname.substr(0, pos);
1230 }
1231 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001232 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001233
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001234 if (context->error) {
1235 fprintf(context->error, "logcat using %s\n",
1236 devname.c_str());
1237 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001238
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001239 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001240 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001241 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001242
bohu94aab862017-02-21 14:31:19 -08001243 if (consolePipe) {
1244 // need the trailing '\0'
1245 if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
1246 pipePurpose.size() + 1)) {
1247 fclose(fp);
1248 context->retval = EXIT_FAILURE;
1249 goto exit;
1250 }
1251 }
1252
Mark Salyzynf3290292017-02-10 13:09:07 -08001253 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001254 android::close_output(context);
1255 android::close_error(context);
1256 context->stderr_stdout = true;
1257 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001258 context->output_fd = fileno(fp);
1259 if (context->stderr_null) break;
1260 context->stderr_stdout = true;
1261 context->error = fp;
1262 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001263 }
1264 break;
1265
Mark Salyzyn34facab2014-02-06 14:48:50 -08001266 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001267 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001268 break;
1269
Traian Schiau59763032015-04-10 15:51:39 +03001270 case ':':
Elliott Hughes61b580e2018-06-15 15:16:20 -07001271 logcat_panic(context, HELP_TRUE, "Option -%c needs an argument\n", optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001272 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001273
Mark Salyzyne74e51d2017-04-03 09:30:20 -07001274 case 'h':
1275 show_help(context);
1276 show_format_help(context);
1277 goto exit;
1278
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001279 default:
Elliott Hughes61b580e2018-06-15 15:16:20 -07001280 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n", optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001281 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001282 }
1283 }
1284
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001285 if (context->maxCount && got_t) {
1286 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001287 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001288 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001289 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001290 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001291 // One day it would be nice if --print -v color and --regex <expr>
1292 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001293 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001294 if (context->error) {
1295 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001296 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001297 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001298 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001299 }
1300 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001301 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001302
Mark Salyzyn13e47352017-03-06 14:56:04 -08001303 if (!context->devices) {
1304 dev = context->devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001305 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001306 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001307 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001308 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001309 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001310 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001311 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001312 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001313 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001314 }
1315
Mark Salyzynde022a82017-03-01 08:30:06 -08001316 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001317 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1318 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001319 }
1320
Mark Salyzynde022a82017-03-01 08:30:06 -08001321 if (!!setId) {
1322 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001323 logcat_panic(context, HELP_TRUE,
1324 "--id='%s' requires -f as well\n", setId);
1325 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001326 }
1327
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001328 std::string file_name = android::base::StringPrintf(
1329 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001330 std::string file;
1331 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001332 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1333 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001334 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001335 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001336
Mark Salyzynde022a82017-03-01 08:30:06 -08001337 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001338 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001339
Mark Salyzynde022a82017-03-01 08:30:06 -08001340 if (!!logFormat) {
Mark Salyzynb45a1752017-02-28 09:20:31 -08001341 std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
1342 free);
1343 char* sv = nullptr; // protect against -ENOMEM above
1344 char* arg = formats.get();
1345 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1346 err = setLogFormat(context, arg);
1347 // environment should not cause crash of logcat
1348 if ((err < 0) && context->error) {
1349 fprintf(context->error,
1350 "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
1351 }
1352 arg = nullptr;
1353 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001354 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001355 }
1356 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001357 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001358 }
1359 }
1360
Mark Salyzynf3290292017-02-10 13:09:07 -08001361 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001362 err = android_log_addFilterString(context->logformat,
1363 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001364 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001365 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001366 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001367 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001368 }
Elliott Hughes61b580e2018-06-15 15:16:20 -07001369 } else if (argc == optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001370 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001371 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001372
Mark Salyzynde022a82017-03-01 08:30:06 -08001373 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001374 err = android_log_addFilterString(context->logformat,
1375 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001376
Mark Salyzyn95132e92013-11-22 10:55:48 -08001377 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001378 logcat_panic(context, HELP_TRUE,
1379 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1380 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001381 }
1382 }
1383 } else {
1384 // Add from commandline
Elliott Hughes61b580e2018-06-15 15:16:20 -07001385 for (int i = optind ; i < argc ; i++) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001386 // skip stderr redirections of _all_ kinds
1387 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001388 // skip stdout redirections of _all_ kinds
1389 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001390
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001391 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001392 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001393 logcat_panic(context, HELP_TRUE,
1394 "Invalid filter expression '%s'\n", argv[i]);
1395 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001396 }
1397 }
1398 }
1399
Mark Salyzyn13e47352017-03-06 14:56:04 -08001400 dev = context->devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001401 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001402 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001403 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001404 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001405 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001406 // We have three orthogonal actions below to clear, set log size and
1407 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001408 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001409 dev->logger_list = logger_list;
1410 dev->logger = android_logger_open(logger_list,
1411 android_name_to_log_id(dev->device));
1412 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001413 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001414 dev = dev->next;
1415 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001416 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001417
Mark Salyzyn02687e72016-08-03 14:20:41 -07001418 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001419 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001420 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001421 (context->maxRotatedLogs > 0) ?
1422 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1423 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001424
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001425 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001426 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001427
Mark Salyzynde022a82017-03-01 08:30:06 -08001428 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001429 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001430 "%s", context->outputFileName);
1431 } else {
1432 file = android::base::StringPrintf("%s.%.*d",
1433 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001434 }
1435
Mark Salyzynde022a82017-03-01 08:30:06 -08001436 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001437 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001438 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001439 break;
1440 }
1441
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001442 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001443
Mark Salyzynde022a82017-03-01 08:30:06 -08001444 if (err < 0 && errno != ENOENT && !clearFail) {
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 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001448 }
1449 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001450 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001451 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001452 }
1453
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001454 if (setLogSize) {
1455 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001456 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001457 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001458 }
1459
Joe Onorato6fa09a02010-02-26 10:04:23 -08001460 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001461 long size = android_logger_get_log_size(dev->logger);
1462 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001463
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001464 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001465 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001466 } else {
Wei Wangc27d4812018-09-05 11:05:57 -07001467 auto size_format = format_of_size(size);
1468 auto readable_format = format_of_size(readable);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001469 std::string str = android::base::StringPrintf(
Wei Wangc27d4812018-09-05 11:05:57 -07001470 "%s: ring buffer is %lu %sB (%lu %sB consumed),"
1471 " max entry is %d B, max payload is %d B\n",
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001472 dev->device,
Wei Wangc27d4812018-09-05 11:05:57 -07001473 size_format.first, size_format.second,
1474 readable_format.first, readable_format.second,
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001475 (int)LOGGER_ENTRY_MAX_LEN,
1476 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1477 TEMP_FAILURE_RETRY(write(context->output_fd,
1478 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001479 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001480 }
1481
1482 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001483 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001484
1485 context->retval = EXIT_SUCCESS;
1486
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001487 // report any errors in the above loop and exit
1488 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001489 logcat_panic(context, HELP_FALSE,
1490 "Unable to open log device '%s'\n", openDeviceFail);
1491 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001492 }
1493 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001494 logcat_panic(context, HELP_FALSE,
1495 "failed to clear the '%s' log\n", clearFail);
1496 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001497 }
1498 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001499 logcat_panic(context, HELP_FALSE,
1500 "failed to set the '%s' log size\n", setSizeFail);
1501 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001502 }
1503 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001504 logcat_panic(context, HELP_FALSE,
1505 "failed to get the readable '%s' log size", getSizeFail);
1506 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001507 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001508
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001509 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001510 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001511 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001512 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001513 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001514 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1515 buf[len] = '\0';
1516 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001517 logcat_panic(context, HELP_FALSE,
1518 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001519 }
1520 free(buf);
1521 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001522 logcat_panic(context, HELP_FALSE,
1523 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001524 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001525 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001526 }
1527
Mark Salyzyn1c950472014-04-01 17:19:47 -07001528 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001529 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001530 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001531
Mark Salyzyn5f606602017-02-10 13:09:07 -08001532 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001533 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001534 if (getPruneList) {
1535 android_logger_get_prune_list(logger_list, buf, len);
1536 } else {
1537 android_logger_get_statistics(logger_list, buf, len);
1538 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001539 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001540 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001541 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001542 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001543 break;
1544 }
Traian Schiau59763032015-04-10 15:51:39 +03001545 size_t ret = atol(buf) + 1;
1546 if (ret <= len) {
1547 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001548 break;
1549 }
Traian Schiau59763032015-04-10 15:51:39 +03001550 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001551 }
1552
1553 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001554 logcat_panic(context, HELP_FALSE, "failed to read data");
1555 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001556 }
1557
1558 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001559 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001560 *cp = '\0';
1561 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001562 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001563
1564 // squash out the byte count
1565 cp = buf;
1566 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001567 while (isdigit(*cp)) ++cp;
1568 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001569 }
1570
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001571 len = strlen(cp);
1572 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001573 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001574 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001575 }
1576
Mark Salyzynde022a82017-03-01 08:30:06 -08001577 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001578
Mark Salyzynde022a82017-03-01 08:30:06 -08001579 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001580 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001581
Mark Salyzyn5f606602017-02-10 13:09:07 -08001582 // LOG_EVENT_INT(10, 12345);
1583 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1584 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001585
Mark Salyzynde022a82017-03-01 08:30:06 -08001586 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001587
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001588 while (!context->stop &&
1589 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001590 struct log_msg log_msg;
1591 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001592 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001593 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1594 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001595 }
1596
1597 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001598 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001599
1600 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001601 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1602 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001603 }
1604 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001605 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1606 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001607 }
Luca Stefani08705142017-07-08 17:48:00 +02001608 logcat_panic(context, HELP_FALSE, "logcat read failure\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001609 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001610 }
1611
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001612 log_device_t* d;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001613 for (d = context->devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001614 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001615 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001616 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001617 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001618 d = &unexpected;
1619 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001620 }
1621
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001622 if (dev != d) {
1623 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001624 maybePrintStart(context, dev, printDividers);
1625 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001626 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001627 if (context->printBinary) {
1628 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001629 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001630 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001631 }
1632 }
1633
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001634close:
Mark Salyzyn13e47352017-03-06 14:56:04 -08001635 // Short and sweet. Implemented generic version in android_logcat_destroy.
1636 while (!!(dev = context->devices)) {
1637 context->devices = dev->next;
1638 delete dev;
1639 }
Mark Salyzyn95132e92013-11-22 10:55:48 -08001640 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001641
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001642exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001643 // close write end of pipe to help things along
1644 if (context->output_fd == context->fds[1]) {
1645 android::close_output(context);
1646 }
1647 if (context->error_fd == context->fds[1]) {
1648 android::close_error(context);
1649 }
1650 if (context->fds[1] >= 0) {
1651 // NB: should be closed by the above
1652 int save_errno = errno;
1653 close(context->fds[1]);
1654 errno = save_errno;
1655 context->fds[1] = -1;
1656 }
1657 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001658 return context->retval;
1659}
1660
1661// Can block
1662int android_logcat_run_command(android_logcat_context ctx,
1663 int output, int error,
1664 int argc, char* const* argv,
1665 char* const* envp) {
1666 android_logcat_context_internal* context = ctx;
1667
1668 context->output_fd = output;
1669 context->error_fd = error;
1670 context->argc = argc;
1671 context->argv = argv;
1672 context->envp = envp;
1673 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001674 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001675 return __logcat(context);
1676}
1677
1678// Finished with context
1679int android_logcat_destroy(android_logcat_context* ctx) {
1680 android_logcat_context_internal* context = *ctx;
1681
Mark Salyzynde022a82017-03-01 08:30:06 -08001682 if (!context) return -EBADF;
1683
1684 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001685
1686 context->stop = true;
1687
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001688 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001689 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001690 sched_yield();
1691 }
1692
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001693 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001694 context->argv_hold.clear();
1695 context->args.clear();
1696 context->envp_hold.clear();
1697 context->envs.clear();
1698 if (context->fds[0] >= 0) {
1699 close(context->fds[0]);
1700 context->fds[0] = -1;
1701 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001702 android::close_output(context);
1703 android::close_error(context);
Josh Gao03d055d2017-10-18 15:42:00 -07001704
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001705 if (context->fds[1] >= 0) {
Josh Gao03d055d2017-10-18 15:42:00 -07001706 // NB: this should be closed by close_output, but just in case...
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001707 close(context->fds[1]);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001708 context->fds[1] = -1;
1709 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001710
1711 android_closeEventTagMap(context->eventTagMap);
1712
Mark Salyzyn13e47352017-03-06 14:56:04 -08001713 // generic cleanup of devices list to handle all possible dirty cases
1714 log_device_t* dev;
1715 while (!!(dev = context->devices)) {
1716 struct logger_list* logger_list = dev->logger_list;
1717 if (logger_list) {
1718 for (log_device_t* d = dev; d; d = d->next) {
1719 if (d->logger_list == logger_list) d->logger_list = nullptr;
1720 }
1721 android_logger_list_free(logger_list);
1722 }
1723 context->devices = dev->next;
1724 delete dev;
1725 }
1726
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001727 int retval = context->retval;
1728
1729 free(context);
1730
1731 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001732}