blob: 3ce0db3776eed35a1bf41ceac78f845f748ec85a [file] [log] [blame]
Mark Salyzyn5f606602017-02-10 13:09:07 -08001/*
Mark Salyzync0cf90d2017-02-10 13:09:07 -08002 * Copyright (C) 2006-2017 The Android Open Source Project
Mark Salyzyn5f606602017-02-10 13:09:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080016
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070017#include <arpa/inet.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080018#include <assert.h>
19#include <ctype.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070020#include <dirent.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080021#include <errno.h>
22#include <fcntl.h>
Kristian Monsen562e5132015-06-05 14:10:12 -070023#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070024#include <math.h>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080025#include <pthread.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070026#include <sched.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070027#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080028#include <stdio.h>
29#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080030#include <string.h>
Traian Schiau59763032015-04-10 15:51:39 +030031#include <sys/cdefs.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070032#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080033#include <sys/socket.h>
34#include <sys/stat.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070035#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070036#include <time.h>
37#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080038
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080039#include <atomic>
Mark Salyzynf3555d92015-05-27 07:39:56 -070040#include <memory>
41#include <string>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080042#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070043
Elliott Hughes4f713192015-12-04 22:00:26 -080044#include <android-base/file.h>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070045#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080046#include <android-base/strings.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070047#include <cutils/sched_policy.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080048#include <cutils/sockets.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070049#include <log/event_tag_map.h>
Mark Salyzync0cf90d2017-02-10 13:09:07 -080050#include <log/logcat.h>
Colin Cross9227bd32013-07-23 16:59:20 -070051#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070052#include <private/android_logger.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080053#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Casey Dahlindc42a872016-03-17 16:18:55 -070055#include <pcrecpp.h>
56
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057#define DEFAULT_MAX_ROTATED_LOGS 4
58
Mark Salyzync0cf90d2017-02-10 13:09:07 -080059struct android_logcat_context_internal {
60 // status
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080061 volatile std::atomic_int retval; // valid if thread_stopped set
62 // Arguments passed in, or copies and storage thereof if a thread.
Mark Salyzync0cf90d2017-02-10 13:09:07 -080063 int argc;
64 char* const* argv;
65 char* const* envp;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080066 std::vector<std::string> args;
67 std::vector<const char*> argv_hold;
68 std::vector<std::string> envs;
69 std::vector<const char*> envp_hold;
Mark Salyzynde022a82017-03-01 08:30:06 -080070 int output_fd; // duplication of fileno(output) (below)
71 int error_fd; // duplication of fileno(error) (below)
Mark Salyzync0cf90d2017-02-10 13:09:07 -080072
73 // library
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080074 int fds[2]; // From popen call
75 FILE* output; // everything writes to fileno(output), buffer unused
76 FILE* error; // unless error == output.
77 pthread_t thr;
78 volatile std::atomic_bool stop; // quick exit flag
79 volatile std::atomic_bool thread_stopped;
Mark Salyzync0cf90d2017-02-10 13:09:07 -080080 bool stderr_null; // shell "2>/dev/null"
81 bool stderr_stdout; // shell "2>&1"
82
83 // global variables
84 AndroidLogFormat* logformat;
85 const char* outputFileName;
86 // 0 means "no log rotation"
87 size_t logRotateSizeKBytes;
88 // 0 means "unbounded"
89 size_t maxRotatedLogs;
90 size_t outByteCount;
91 int printBinary;
92 int devCount; // >1 means multiple
93 pcrecpp::RE* regex;
94 // 0 means "infinite"
95 size_t maxCount;
96 size_t printCount;
97 bool printItAnyways;
98 bool debug;
99
100 // static variables
101 bool hasOpenedEventTagMap;
102 EventTagMap* eventTagMap;
103};
104
105// Creates a context associated with this logcat instance
106android_logcat_context create_android_logcat() {
107 android_logcat_context_internal* context;
108
109 context = (android_logcat_context_internal*)calloc(
110 1, sizeof(android_logcat_context_internal));
Mark Salyzynde022a82017-03-01 08:30:06 -0800111 if (!context) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800112
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800113 context->fds[0] = -1;
114 context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800115 context->output_fd = -1;
116 context->error_fd = -1;
117 context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
118
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800119 context->argv_hold.clear();
120 context->args.clear();
121 context->envp_hold.clear();
122 context->envs.clear();
123
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800124 return (android_logcat_context)context;
125}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126
Mark Salyzyn5f606602017-02-10 13:09:07 -0800127// logd prefixes records with a length field
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
129
Joe Onorato6fa09a02010-02-26 10:04:23 -0800130struct log_device_t {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800131 const char* device;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800132 bool binary;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800133 struct logger* logger;
134 struct logger_list* logger_list;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800135 bool printed;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800136
Joe Onorato6fa09a02010-02-26 10:04:23 -0800137 log_device_t* next;
138
Mark Salyzyn5f6738a2015-02-27 13:41:34 -0800139 log_device_t(const char* d, bool b) {
Joe Onorato6fa09a02010-02-26 10:04:23 -0800140 device = d;
141 binary = b;
Mark Salyzynde022a82017-03-01 08:30:06 -0800142 next = nullptr;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800143 printed = false;
Mark Salyzynde022a82017-03-01 08:30:06 -0800144 logger = nullptr;
145 logger_list = nullptr;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800146 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800147};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
149namespace android {
150
Mark Salyzyn5f606602017-02-10 13:09:07 -0800151enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700152
Mark Salyzynaa730c12016-03-30 12:38:29 -0700153// if showHelp is set, newline required in fmt statement to transition to usage
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800154static void logcat_panic(android_logcat_context_internal* context,
155 enum helpType showHelp, const char* fmt, ...)
156 __printflike(3, 4);
Traian Schiau59763032015-04-10 15:51:39 +0300157
Mark Salyzyn5f606602017-02-10 13:09:07 -0800158static int openLogFile(const char* pathname) {
Edwin Vane80b221c2012-08-13 12:55:07 -0400159 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160}
161
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800162static void close_output(android_logcat_context_internal* context) {
163 // split output_from_error
164 if (context->error == context->output) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800165 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800166 context->output_fd = -1;
167 }
168 if (context->error && (context->output_fd == fileno(context->error))) {
169 context->output_fd = -1;
170 }
171 if (context->output_fd == context->error_fd) {
172 context->output_fd = -1;
173 }
174 // close output channel
175 if (context->output) {
176 if (context->output != stdout) {
177 if (context->output_fd == fileno(context->output)) {
178 context->output_fd = -1;
179 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800180 if (context->fds[1] == fileno(context->output)) {
181 context->fds[1] = -1;
182 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800183 fclose(context->output);
184 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800185 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800186 }
187 if (context->output_fd >= 0) {
188 if (context->output_fd != fileno(stdout)) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800189 if (context->fds[1] == context->output_fd) {
190 context->fds[1] = -1;
191 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800192 close(context->output_fd);
193 }
194 context->output_fd = -1;
195 }
196}
197
198static void close_error(android_logcat_context_internal* context) {
199 // split error_from_output
200 if (context->output == context->error) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800201 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800202 context->error_fd = -1;
203 }
204 if (context->output && (context->error_fd == fileno(context->output))) {
205 context->error_fd = -1;
206 }
207 if (context->error_fd == context->output_fd) {
208 context->error_fd = -1;
209 }
210 // close error channel
211 if (context->error) {
212 if ((context->error != stderr) && (context->error != stdout)) {
213 if (context->error_fd == fileno(context->error)) {
214 context->error_fd = -1;
215 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800216 if (context->fds[1] == fileno(context->error)) {
217 context->fds[1] = -1;
218 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800219 fclose(context->error);
220 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800221 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800222 }
223 if (context->error_fd >= 0) {
224 if ((context->error_fd != fileno(stdout)) &&
225 (context->error_fd != fileno(stderr))) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800226 if (context->fds[1] == context->error_fd) context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800227 close(context->error_fd);
228 }
229 context->error_fd = -1;
230 }
231}
232
233static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234 int err;
235
236 // Can't rotate logs if we're not outputting to a file
Mark Salyzynde022a82017-03-01 08:30:06 -0800237 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800238
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800239 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240
Mark Salyzyn5f606602017-02-10 13:09:07 -0800241 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800242 // maxRotatedLogs in decimal. eg:
243 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800244 // -> log10(30) == 1.477
245 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700246 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800247 (context->maxRotatedLogs > 0)
248 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
249 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700250
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800251 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700252 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800253 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700255 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800256 if (!(i - 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800257 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800259 file0 =
260 android::base::StringPrintf("%s.%.*d", context->outputFileName,
261 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 }
263
Mark Salyzynde022a82017-03-01 08:30:06 -0800264 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300265 perror("while rotating log files");
266 break;
267 }
268
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700269 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270
271 if (err < 0 && errno != ENOENT) {
272 perror("while rotating log files");
273 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274 }
275
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800276 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800278 if (context->output_fd < 0) {
279 logcat_panic(context, HELP_FALSE, "couldn't open output file");
280 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800282 context->output = fdopen(context->output_fd, "web");
Mark Salyzynde022a82017-03-01 08:30:06 -0800283 if (!context->output) {
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800284 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
285 return;
286 }
287 if (context->stderr_stdout) {
288 close_error(context);
289 context->error = context->output;
290 context->error_fd = context->output_fd;
291 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800292
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800293 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294}
295
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800296void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800297 size_t size = buf->len();
298
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800299 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800300}
301
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800302static bool regexOk(android_logcat_context_internal* context,
303 const AndroidLogEntry& entry) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800304 if (!context->regex) return true;
Casey Dahlindc42a872016-03-17 16:18:55 -0700305
Casey Dahlindc42a872016-03-17 16:18:55 -0700306 std::string messageString(entry.message, entry.messageLen);
307
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800308 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700309}
310
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800311static void processBuffer(android_logcat_context_internal* context,
312 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700313 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800314 int err;
315 AndroidLogEntry entry;
316 char binaryMsgBuf[1024];
317
Joe Onorato6fa09a02010-02-26 10:04:23 -0800318 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800319 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800320 context->eventTagMap = android_openEventTagMap(nullptr);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800321 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800322 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800323 err = android_log_processBinaryLogBuffer(
324 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
325 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800326 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800327 // entry.priority, entry.messageLen, entry.message);
328 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800329 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800331 if ((err < 0) && !context->debug) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800332
Mark Salyzyn5f606602017-02-10 13:09:07 -0800333 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800334 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800335 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800336 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800337
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800338 context->printCount += match;
339 if (match || context->printItAnyways) {
340 bytesWritten = android_log_printLogLine(context->logformat,
341 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700342
Mark Salyzync9202772016-03-30 09:38:31 -0700343 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800344 logcat_panic(context, HELP_FALSE, "output error");
345 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700346 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800347 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348 }
349
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800350 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800352 if (context->logRotateSizeKBytes > 0 &&
353 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
354 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356}
357
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800358static void maybePrintStart(android_logcat_context_internal* context,
359 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800360 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800361 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800362 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800363 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800364 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800365 if (write(context->output_fd, buf, strlen(buf)) < 0) {
366 logcat_panic(context, HELP_FALSE, "output error");
367 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800368 }
369 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800370 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800371 }
372}
373
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800374static void setupOutputAndSchedulingPolicy(
375 android_logcat_context_internal* context, bool blocking) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800376 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377
Mark Salyzynad5e4112016-08-04 07:53:52 -0700378 if (blocking) {
379 // Lower priority and set to batch scheduling if we are saving
380 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800381 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
382 fprintf(context->error,
383 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700384 }
385
386 struct sched_param param;
387 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800388 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700389 fprintf(stderr, "failed to set to batch scheduler\n");
390 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800392 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
393 context->error) {
394 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700395 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800396 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700397
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800398 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700399
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800400 context->output_fd = openLogFile(context->outputFileName);
401
402 if (context->output_fd < 0) {
403 logcat_panic(context, HELP_FALSE, "couldn't open output file");
404 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700405 }
406
407 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800408 if (fstat(context->output_fd, &statbuf) == -1) {
409 close_output(context);
410 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
411 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700412 }
413
Mark Salyzyn5f606602017-02-10 13:09:07 -0800414 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800415 close_output(context);
416 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
417 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700418 }
419
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800420 context->output = fdopen(context->output_fd, "web");
421
422 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423}
424
Mark Salyzyn5f606602017-02-10 13:09:07 -0800425// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800426static void show_help(android_logcat_context_internal* context) {
427 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800428
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800429 const char* cmd = strrchr(context->argv[0], '/');
430 cmd = cmd ? cmd + 1 : context->argv[0];
431
432 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
433
434 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700435 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
436 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700437 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
438 " Rotate log every kbytes. Requires -f option\n"
439 " -n <count>, --rotate-count=<count>\n"
440 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700441 " --id=<id> If the signature id for logging to file changes, then clear\n"
442 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700443 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700444 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700445 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700446 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700447 " color descriptive epoch monotonic printable uid\n"
448 " usec UTC year zone\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800449 // private and undocumented nsec, no signal, too much noise
450 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700451 " -D, --dividers Print dividers between each log buffer\n"
452 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700453 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700454 " -d Dump the log and then exit (don't block)\n"
455 " -e <expr>, --regex=<expr>\n"
456 " Only print lines where the log message matches <expr>\n"
457 " where <expr> is a regular expression\n"
458 // Leave --head undocumented as alias for -m
459 " -m <count>, --max-count=<count>\n"
460 " Quit after printing <count> lines. This is meant to be\n"
461 " paired with --regex, but will work on its own.\n"
462 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700463 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700464 // Leave --tail undocumented as alias for -t
465 " -t <count> Print only the most recent <count> lines (implies -d)\n"
466 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
467 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
468 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700469 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700470 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700471 " -g, --buffer-size Get the size of the ring buffer.\n"
472 " -G <size>, --buffer-size=<size>\n"
473 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100474 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800475 // Leave security (Device Owner only installations) and
476 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700477 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
478 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700479 " Multiple -b parameters or comma separated list of buffers are\n"
480 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700481 " -B, --binary Output the log in binary.\n"
482 " -S, --statistics Output statistics.\n"
483 " -p, --prune Print prune white and ~black list. Service is specified as\n"
484 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700485 " with ~, otherwise weighed for longevity if unadorned. All\n"
486 " other pruning activity is oldest first. Special case ~!\n"
487 " represents an automatic quicker pruning for the noisiest\n"
488 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700489 " -P '<list> ...', --prune='<list> ...'\n"
490 " Set prune white and ~black list, using same format as\n"
491 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800492 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700493 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800494 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
495 " comes first. Improves efficiency of polling by providing\n"
496 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800498 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499 " <tag>[:priority]\n\n"
500 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700501 " V Verbose (default for <tag>)\n"
502 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 " I Info\n"
504 " W Warn\n"
505 " E Error\n"
506 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700507 " S Silent (suppress all output)\n"
508 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
509 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
510 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
511 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
512 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700513 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514}
515
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800516static void show_format_help(android_logcat_context_internal* context) {
517 if (!context->error) return;
518 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700519 "-v <format>, --format=<format> options:\n"
520 " Sets log print format verb and adverbs, where <format> is:\n"
521 " brief long process raw tag thread threadtime time\n"
522 " and individually flagged modifying adverbs can be added:\n"
523 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
524 "\nSingle format verbs:\n"
525 " brief — Display priority/tag and PID of the process issuing the message.\n"
526 " long — Display all metadata fields, separate messages with blank lines.\n"
527 " process — Display PID only.\n"
528 " raw — Display the raw log message, with no other metadata fields.\n"
529 " tag — Display the priority/tag only.\n"
530 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
531 " and TID of the thread issuing the message. (the default format).\n"
532 " time — Display the date, invocation time, priority/tag, and PID of the\n"
533 " process issuing the message.\n"
534 "\nAdverb modifiers can be used in combination:\n"
535 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
536 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
537 " descriptive — events logs only, descriptions from event-log-tags database.\n"
538 " epoch — Display time as seconds since Jan 1 1970.\n"
539 " monotonic — Display time as cpu seconds since last boot.\n"
540 " printable — Ensure that any binary logging content is escaped.\n"
541 " uid — If permitted, display the UID or Android ID of logged process.\n"
542 " usec — Display time down the microsecond precision.\n"
543 " UTC — Display time as UTC.\n"
544 " year — Add the year to the displayed time.\n"
545 " zone — Add the local timezone to the displayed time.\n"
546 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
547 );
548}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800549// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700550
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800551static int setLogFormat(android_logcat_context_internal* context,
552 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800553 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554
555 format = android_log_formatFromString(formatString);
556
Mark Salyzynde022a82017-03-01 08:30:06 -0800557 // invalid string?
558 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800560 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561}
562
Mark Salyzyn5f606602017-02-10 13:09:07 -0800563static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700564
Mark Salyzyn5f606602017-02-10 13:09:07 -0800565static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700566 for (unsigned i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800567 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
568 value /= 1024, ++i)
569 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700570 return value;
571}
572
Mark Salyzyn5f606602017-02-10 13:09:07 -0800573static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700574 unsigned i;
575 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800576 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
577 value /= 1024, ++i)
578 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700579 return multipliers[i];
580}
581
Mark Salyzyn5f606602017-02-10 13:09:07 -0800582// String to unsigned int, returns -1 if it fails
583static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
584 size_t max = SIZE_MAX) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800585 if (!ptr) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300586
Mark Salyzyn5f606602017-02-10 13:09:07 -0800587 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700588 errno = 0;
589 size_t ret = (size_t)strtoll(ptr, &endp, 0);
590
Mark Salyzynde022a82017-03-01 08:30:06 -0800591 if (endp[0] || errno) return false;
Kristian Monsen562e5132015-06-05 14:10:12 -0700592
Mark Salyzynde022a82017-03-01 08:30:06 -0800593 if ((ret > max) || (ret < min)) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300594
595 *val = ret;
596 return true;
597}
598
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800599static void logcat_panic(android_logcat_context_internal* context,
600 enum helpType showHelp, const char* fmt, ...) {
601 context->retval = EXIT_FAILURE;
602 if (!context->error) {
603 context->stop = true;
604 return;
605 }
606
Mark Salyzyn5f606602017-02-10 13:09:07 -0800607 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700608 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800609 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700610 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300611
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700612 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800613 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800614 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800615 break;
616 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800617 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800618 break;
619 case HELP_FALSE:
620 default:
621 break;
Traian Schiau59763032015-04-10 15:51:39 +0300622 }
623
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800624 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300625}
626
Mark Salyzyn5f606602017-02-10 13:09:07 -0800627static char* parseTime(log_time& t, const char* cp) {
628 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800629 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700630 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800631 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700632 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700633}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700634
Mark Salyzyn31961062016-08-04 07:43:46 -0700635// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn5f606602017-02-10 13:09:07 -0800636static log_time lastLogTime(char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700637 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800638 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700639
Mark Salyzynf3555d92015-05-27 07:39:56 -0700640 std::string directory;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800641 char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700642 if (!file) {
643 directory = ".";
644 file = outputFileName;
645 } else {
646 *file = '\0';
647 directory = outputFileName;
648 *file = '/';
649 ++file;
650 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700651
Mark Salyzyn5f606602017-02-10 13:09:07 -0800652 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
653 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800654 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700655
Mark Salyzyn31961062016-08-04 07:43:46 -0700656 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700657
Mark Salyzynf3555d92015-05-27 07:39:56 -0700658 size_t len = strlen(file);
659 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800660 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700661
Mark Salyzynde022a82017-03-01 08:30:06 -0800662 while (!!(dp = readdir(dir.get()))) {
663 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800664 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800665 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700666 continue;
667 }
668
669 std::string file_name = directory;
670 file_name += "/";
671 file_name += dp->d_name;
672 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800673 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700674
675 bool found = false;
676 for (const auto& line : android::base::Split(file, "\n")) {
677 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800678 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800679 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700680 // determine the time precision of the logs (eg: msec or usec)
681 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
682 if (t.tv_nsec % (mod * 10)) {
683 modulo.tv_nsec = mod;
684 break;
685 }
686 }
687 // We filter any times later than current as we may not have the
688 // year stored with each log entry. Also, since it is possible for
689 // entries to be recorded out of order (very rare) we select the
690 // maximum we find just in case.
691 if ((t < now) && (t > retval)) {
692 retval = t;
693 found = true;
694 }
695 }
696 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800697 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700698 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800699 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700700 // tail_time prints matching or higher, round up by the modulo to prevent
701 // a replay of the last entry we have just checked.
702 retval += modulo;
703 return retval;
704}
705
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800706const char* getenv(android_logcat_context_internal* context, const char* name) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800707 if (!context->envp || !name || !*name) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800708
709 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
710 if (strncmp(context->envp[i], name, len)) continue;
711 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
712 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800713 return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800714}
715
Mark Salyzyn5f606602017-02-10 13:09:07 -0800716} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300717
Mark Salyzyn5f606602017-02-10 13:09:07 -0800718void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800719 bool blockSecurity) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800720 if (*current) return;
721 if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
722 *current = name;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800723 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800724}
Traian Schiau59763032015-04-10 15:51:39 +0300725
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800726static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300727 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728 int err;
729 int hasSetLogFormat = 0;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800730 bool clearLog = false;
731 bool allSelected = false;
732 bool getLogSize = false;
733 bool getPruneList = false;
734 bool printStatistics = false;
735 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800736 unsigned long setLogSize = 0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800737 char* setPruneList = nullptr;
738 char* setId = nullptr;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800739 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800740 std::string forceFilters;
Mark Salyzynde022a82017-03-01 08:30:06 -0800741 log_device_t* devices = nullptr;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800742 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800743 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300744 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800745 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700746 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700747 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800748
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800749 // object instantiations before goto's can happen
750 log_device_t unexpected("unexpected", false);
Mark Salyzynde022a82017-03-01 08:30:06 -0800751 const char* openDeviceFail = nullptr;
752 const char* clearFail = nullptr;
753 const char* setSizeFail = nullptr;
754 const char* getSizeFail = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800755 int argc = context->argc;
756 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800757
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800758 context->output = stdout;
759 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800760
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800761 for (int i = 0; i < argc; ++i) {
762 // Simulate shell stderr redirect parsing
763 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
764
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800765 // Append to file not implemented, just open file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800766 size_t skip = (argv[i][2] == '>') + 2;
767 if (!strcmp(&argv[i][skip], "/dev/null")) {
768 context->stderr_null = true;
769 } else if (!strcmp(&argv[i][skip], "&1")) {
770 context->stderr_stdout = true;
771 } else {
772 // stderr file redirections are not supported
773 fprintf(context->stderr_stdout ? stdout : stderr,
774 "stderr redirection to file %s unsupported, skipping\n",
775 &argv[i][skip]);
776 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800777 // Only the first one
778 break;
779 }
780
Mark Salyzynde022a82017-03-01 08:30:06 -0800781 const char* filename = nullptr;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800782 for (int i = 0; i < argc; ++i) {
783 // Simulate shell stdout redirect parsing
784 if (argv[i][0] != '>') continue;
785
786 // Append to file not implemented, just open file
787 filename = &argv[i][(argv[i][1] == '>') + 1];
788 // Only the first one
789 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800790 }
791
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800792 // Deal with setting up file descriptors and FILE pointers
Mark Salyzynde022a82017-03-01 08:30:06 -0800793 if (context->error_fd >= 0) { // Is an error file descriptor supplied?
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800794 if (context->error_fd == context->output_fd) {
795 context->stderr_stdout = true;
Mark Salyzynde022a82017-03-01 08:30:06 -0800796 } else if (context->stderr_null) { // redirection told us to close it
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800797 close(context->error_fd);
798 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800799 } else { // All Ok, convert error to a FILE pointer
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800800 context->error = fdopen(context->error_fd, "web");
801 if (!context->error) {
802 context->retval = -errno;
803 fprintf(context->stderr_stdout ? stdout : stderr,
804 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
805 strerror(errno));
806 goto exit;
807 }
808 }
809 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800810 if (context->output_fd >= 0) { // Is an output file descriptor supplied?
811 if (filename) { // redirect to file, close supplied file descriptor.
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800812 close(context->output_fd);
813 context->output_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800814 } else { // All Ok, convert output to a FILE pointer
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800815 context->output = fdopen(context->output_fd, "web");
816 if (!context->output) {
817 context->retval = -errno;
818 fprintf(context->stderr_stdout ? stdout : context->error,
819 "Failed to fdopen(output_fd=%d) %s\n",
820 context->output_fd, strerror(errno));
821 goto exit;
822 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800823 }
824 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800825 if (filename) { // We supplied an output file redirected in command line
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800826 context->output = fopen(filename, "web");
827 }
828 // Deal with 2>&1
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800829 if (context->stderr_stdout) context->error = context->output;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800830 // Deal with 2>/dev/null
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800831 if (context->stderr_null) {
832 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800833 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800834 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800835 // Only happens if output=stdout or output=filename
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800836 if ((context->output_fd < 0) && context->output) {
837 context->output_fd = fileno(context->output);
838 }
839 // Only happens if error=stdout || error=stderr
840 if ((context->error_fd < 0) && context->error) {
841 context->error_fd = fileno(context->error);
842 }
843
844 context->logformat = android_log_format_new();
845
Mark Salyzynde022a82017-03-01 08:30:06 -0800846 if (argc == 2 && !strcmp(argv[1], "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800847 show_help(context);
848 context->retval = EXIT_SUCCESS;
849 goto exit;
850 }
851
852 // danger: getopt is _not_ reentrant
853 optind = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800854 for (;;) {
855 int ret;
856
Kristian Monsen562e5132015-06-05 14:10:12 -0700857 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700858 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700859 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800860 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700861 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800862 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700863 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800864 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700865 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800866 { "binary", no_argument, nullptr, 'B' },
867 { "buffer", required_argument, nullptr, 'b' },
868 { "buffer-size", optional_argument, nullptr, 'g' },
869 { "clear", no_argument, nullptr, 'c' },
870 { debug_str, no_argument, nullptr, 0 },
871 { "dividers", no_argument, nullptr, 'D' },
872 { "file", required_argument, nullptr, 'f' },
873 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700874 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800875 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700876 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800877 { "head", required_argument, nullptr, 'm' },
878 { id_str, required_argument, nullptr, 0 },
879 { "last", no_argument, nullptr, 'L' },
880 { "max-count", required_argument, nullptr, 'm' },
881 { pid_str, required_argument, nullptr, 0 },
882 { print_str, no_argument, nullptr, 0 },
883 { "prune", optional_argument, nullptr, 'p' },
884 { "regex", required_argument, nullptr, 'e' },
885 { "rotate-count", required_argument, nullptr, 'n' },
886 { "rotate-kbytes", required_argument, nullptr, 'r' },
887 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700888 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800889 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800890 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800891 { wrap_str, optional_argument, nullptr, 0 },
892 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700893 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800894 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700895
Mark Salyzyn5f606602017-02-10 13:09:07 -0800896 ret = getopt_long(argc, argv,
897 ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
898 &option_index);
Mark Salyzynde022a82017-03-01 08:30:06 -0800899 if (ret < 0) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900
Kristian Monsen562e5132015-06-05 14:10:12 -0700901 switch (ret) {
902 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700903 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700904 if (long_options[option_index].name == pid_str) {
905 // ToDo: determine runtime PID_MAX?
906 if (!getSizeTArg(optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800907 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Kristian Monsen562e5132015-06-05 14:10:12 -0700908 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800909 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700910 }
911 break;
912 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800913 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800914 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800915 ANDROID_LOG_NONBLOCK;
916 // ToDo: implement API that supports setting a wrap timeout
917 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
918 if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800919 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800920 long_options[option_index].name, optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800921 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800922 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800923 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
924 context->error) {
925 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800926 "WARNING: %s %u seconds, ignoring %zu\n",
927 long_options[option_index].name,
928 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
929 }
930 break;
931 }
Mark Salyzync9202772016-03-30 09:38:31 -0700932 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800933 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700934 break;
935 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800936 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800937 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800938 break;
939 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700940 if (long_options[option_index].name == id_str) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800941 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700942 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800943 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700944
Mark Salyzyn95132e92013-11-22 10:55:48 -0800945 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800946 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800947 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800948 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949
950 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800951 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800952 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800953 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800955 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800956 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
957 ANDROID_LOG_NONBLOCK;
958 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800959
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800960 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800961 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800962 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800964 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700965 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800966 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800967 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800968 case 'T':
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800969 if (strspn(optarg, "0123456789") != strlen(optarg)) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800970 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800971 if (!cp) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800972 logcat_panic(context, HELP_FALSE,
Mark Salyzyn5f606602017-02-10 13:09:07 -0800973 "-%c \"%s\" not in time format\n", ret,
974 optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800975 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800976 }
977 if (*cp) {
978 char c = *cp;
979 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800980 if (context->error) {
981 fprintf(
982 context->error,
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800983 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
984 ret, optarg, c, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800985 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800986 *cp = c;
987 }
988 } else {
Traian Schiau59763032015-04-10 15:51:39 +0300989 if (!getSizeTArg(optarg, &tail_lines, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800990 if (context->error) {
991 fprintf(context->error,
992 "WARNING: -%c %s invalid, setting to 1\n",
993 ret, optarg);
994 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800995 tail_lines = 1;
996 }
997 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800998 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800999
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001000 case 'D':
1001 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001002 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001003
Casey Dahlindc42a872016-03-17 16:18:55 -07001004 case 'e':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001005 context->regex = new pcrecpp::RE(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001006 break;
Casey Dahlindc42a872016-03-17 16:18:55 -07001007
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001008 case 'm': {
Mark Salyzynde022a82017-03-01 08:30:06 -08001009 char* end = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001010 if (!getSizeTArg(optarg, &context->maxCount)) {
1011 logcat_panic(context, HELP_FALSE,
1012 "-%c \"%s\" isn't an "
1013 "integer greater than zero\n",
1014 ret, optarg);
1015 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001016 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001017 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001019 case 'g':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001020 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001021 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001022 break;
1023 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001024 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001026 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001027 char* cp;
Traian Schiau59763032015-04-10 15:51:39 +03001028 if (strtoll(optarg, &cp, 0) > 0) {
1029 setLogSize = strtoll(optarg, &cp, 0);
1030 } else {
1031 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001032 }
1033
Mark Salyzyn5f606602017-02-10 13:09:07 -08001034 switch (*cp) {
1035 case 'g':
1036 case 'G':
1037 setLogSize *= 1024;
1038 // FALLTHRU
1039 case 'm':
1040 case 'M':
1041 setLogSize *= 1024;
1042 // FALLTHRU
1043 case 'k':
1044 case 'K':
1045 setLogSize *= 1024;
1046 // FALLTHRU
1047 case '\0':
1048 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001049
Mark Salyzyn5f606602017-02-10 13:09:07 -08001050 default:
1051 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001052 }
1053
1054 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001055 logcat_panic(context, HELP_FALSE,
1056 "ERROR: -G <num><multiplier>\n");
1057 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001058 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001059 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001060
1061 case 'p':
Mark Salyzynf8bff872015-11-30 12:57:56 -08001062 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001063 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001064 break;
1065 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001066 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001067
1068 case 'P':
1069 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001070 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001071
Joe Onorato6fa09a02010-02-26 10:04:23 -08001072 case 'b': {
Mark Salyzyn45177732016-04-11 14:03:48 -07001073 unsigned idMask = 0;
Mark Salyzynde022a82017-03-01 08:30:06 -08001074 while (!!(optarg = strtok(optarg, ",:; \t\n\r\f"))) {
1075 if (!strcmp(optarg, "default")) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001076 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001077 (1 << LOG_ID_CRASH);
Mark Salyzynde022a82017-03-01 08:30:06 -08001078 } else if (!strcmp(optarg, "all")) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001079 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001080 idMask = (unsigned)-1;
1081 } else {
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001082 log_id_t log_id = android_name_to_log_id(optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001083 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001084
Mark Salyzynde022a82017-03-01 08:30:06 -08001085 if (!!strcmp(name, optarg)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001086 logcat_panic(context, HELP_TRUE,
1087 "unknown buffer %s\n", optarg);
1088 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001089 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001090 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001091 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001092 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001093 optarg = nullptr;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001094 }
1095
Mark Salyzyn45177732016-04-11 14:03:48 -07001096 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001097 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001098 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001099
Mark Salyzynde022a82017-03-01 08:30:06 -08001100 if (log_id != (log_id_t)i) continue;
1101 if (!(idMask & (1 << i))) continue;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001102
Mark Salyzyn45177732016-04-11 14:03:48 -07001103 bool found = false;
1104 for (dev = devices; dev; dev = dev->next) {
1105 if (!strcmp(name, dev->device)) {
1106 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001107 break;
1108 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001109 if (!dev->next) break;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001110 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001111 if (found) continue;
Mark Salyzyn45177732016-04-11 14:03:48 -07001112
Mark Salyzyn5f606602017-02-10 13:09:07 -08001113 bool binary =
1114 !strcmp(name, "events") || !strcmp(name, "security");
Mark Salyzyn45177732016-04-11 14:03:48 -07001115 log_device_t* d = new log_device_t(name, binary);
1116
Mark Salyzyn083b0372015-12-04 10:59:45 -08001117 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001118 dev->next = d;
1119 dev = d;
1120 } else {
1121 devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001122 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001123 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001124 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001125 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001126
1127 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001128 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001129 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130
1131 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001132 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Mark Salyzynf3555d92015-05-27 07:39:56 -07001133 tail_time = lastLogTime(optarg);
1134 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135 // redirect output to a file
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001136 context->outputFileName = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001137 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001138
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001139 case 'r':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001140 if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
1141 logcat_panic(context, HELP_TRUE,
1142 "Invalid parameter \"%s\" to -r\n", optarg);
1143 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001144 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001145 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001146
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001147 case 'n':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001148 if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
1149 logcat_panic(context, HELP_TRUE,
1150 "Invalid parameter \"%s\" to -n\n", optarg);
1151 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001153 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154
1155 case 'v':
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001156 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001157 show_format_help(context);
1158 context->retval = EXIT_SUCCESS;
1159 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001160 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001161 err = setLogFormat(context, optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001163 logcat_panic(context, HELP_FORMAT,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001164 "Invalid parameter \"%s\" to -v\n", optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001165 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001167 hasSetLogFormat |= err;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001168 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001169
1170 case 'Q':
Mark Salyzyn5f606602017-02-10 13:09:07 -08001171#define KERNEL_OPTION "androidboot.logcat="
1172#define CONSOLE_OPTION "androidboot.console="
1173 // This is a *hidden* option used to start a version of logcat
1174 // in an emulated device only. It basically looks for
1175 // androidboot.logcat= on the kernel command line. If
1176 // something is found, it extracts a log filter and uses it to
1177 // run the program. If nothing is found, the program should
1178 // quit immediately.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001179 {
Mark Salyzynf3290292017-02-10 13:09:07 -08001180 std::string cmdline;
1181 android::base::ReadFileToString("/proc/cmdline", &cmdline);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001182
Mark Salyzynf3290292017-02-10 13:09:07 -08001183 const char* logcat = strstr(cmdline.c_str(), KERNEL_OPTION);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001184 // if nothing found or invalid filters, exit quietly
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001185 if (!logcat) {
1186 context->retval = EXIT_SUCCESS;
1187 goto exit;
1188 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001189
1190 const char* p = logcat + strlen(KERNEL_OPTION);
1191 const char* q = strpbrk(p, " \t\n\r");
1192 if (!q) q = p + strlen(p);
1193 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001194
Mark Salyzyn5f606602017-02-10 13:09:07 -08001195 // redirect our output to the emulator console
Mark Salyzynf3290292017-02-10 13:09:07 -08001196 const char* console =
1197 strstr(cmdline.c_str(), CONSOLE_OPTION);
1198 if (!console) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001199
Mark Salyzynf3290292017-02-10 13:09:07 -08001200 p = console + strlen(CONSOLE_OPTION);
1201 q = strpbrk(p, " \t\n\r");
1202 int len = q ? q - p : strlen(p);
1203 std::string devname = "/dev/" + std::string(p, len);
1204 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001205
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001206 if (context->error) {
1207 fprintf(context->error, "logcat using %s\n",
1208 devname.c_str());
1209 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001210
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001211 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001212 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001213 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001214
1215 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001216 android::close_output(context);
1217 android::close_error(context);
1218 context->stderr_stdout = true;
1219 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001220 context->output_fd = fileno(fp);
1221 if (context->stderr_null) break;
1222 context->stderr_stdout = true;
1223 context->error = fp;
1224 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001225 }
1226 break;
1227
Mark Salyzyn34facab2014-02-06 14:48:50 -08001228 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001229 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001230 break;
1231
Traian Schiau59763032015-04-10 15:51:39 +03001232 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001233 logcat_panic(context, HELP_TRUE,
1234 "Option -%c needs an argument\n", optopt);
1235 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001236
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001237 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001238 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
1239 optopt);
1240 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001241 }
1242 }
1243
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001244 if (context->maxCount && got_t) {
1245 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001246 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001247 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001248 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001249 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001250 // One day it would be nice if --print -v color and --regex <expr>
1251 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001252 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001253 if (context->error) {
1254 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001255 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001256 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001257 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001258 }
1259 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001260 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001261
Joe Onorato6fa09a02010-02-26 10:04:23 -08001262 if (!devices) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001263 dev = devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001264 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001265 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001266 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001267 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001268 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001269 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001270 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001271 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001272 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001273 }
1274
Mark Salyzynde022a82017-03-01 08:30:06 -08001275 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001276 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1277 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001278 }
1279
Mark Salyzynde022a82017-03-01 08:30:06 -08001280 if (!!setId) {
1281 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001282 logcat_panic(context, HELP_TRUE,
1283 "--id='%s' requires -f as well\n", setId);
1284 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001285 }
1286
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001287 std::string file_name = android::base::StringPrintf(
1288 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001289 std::string file;
1290 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001291 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1292 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001293 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001294 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001295
Mark Salyzynde022a82017-03-01 08:30:06 -08001296 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001297 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001298
Mark Salyzynde022a82017-03-01 08:30:06 -08001299 if (!!logFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001300 err = setLogFormat(context, logFormat);
1301 if ((err < 0) && context->error) {
1302 fprintf(context->error,
1303 "invalid format in ANDROID_PRINTF_LOG '%s'\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -08001304 logFormat);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001305 }
Mark Salyzyn649fc602014-09-16 09:15:15 -07001306 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001307 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001308 }
1309 }
1310
Mark Salyzynf3290292017-02-10 13:09:07 -08001311 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001312 err = android_log_addFilterString(context->logformat,
1313 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001314 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001315 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001316 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001317 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001318 }
1319 } else if (argc == optind) {
1320 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001321 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001322
Mark Salyzynde022a82017-03-01 08:30:06 -08001323 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001324 err = android_log_addFilterString(context->logformat,
1325 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001326
Mark Salyzyn95132e92013-11-22 10:55:48 -08001327 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001328 logcat_panic(context, HELP_TRUE,
1329 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1330 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001331 }
1332 }
1333 } else {
1334 // Add from commandline
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001335 for (int i = optind ; i < argc ; i++) {
1336 // skip stderr redirections of _all_ kinds
1337 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001338 // skip stdout redirections of _all_ kinds
1339 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001340
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001341 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001342 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001343 logcat_panic(context, HELP_TRUE,
1344 "Invalid filter expression '%s'\n", argv[i]);
1345 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001346 }
1347 }
1348 }
1349
Joe Onorato6fa09a02010-02-26 10:04:23 -08001350 dev = devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001351 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001352 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001353 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001354 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001355 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001356 // We have three orthogonal actions below to clear, set log size and
1357 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001358 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001359 dev->logger_list = logger_list;
1360 dev->logger = android_logger_open(logger_list,
1361 android_name_to_log_id(dev->device));
1362 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001363 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001364 dev = dev->next;
1365 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001366 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001367
Mark Salyzyn02687e72016-08-03 14:20:41 -07001368 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001369 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001370 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001371 (context->maxRotatedLogs > 0) ?
1372 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1373 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001374
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001375 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001376 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001377
Mark Salyzynde022a82017-03-01 08:30:06 -08001378 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001379 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001380 "%s", context->outputFileName);
1381 } else {
1382 file = android::base::StringPrintf("%s.%.*d",
1383 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001384 }
1385
Mark Salyzynde022a82017-03-01 08:30:06 -08001386 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001387 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001388 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001389 break;
1390 }
1391
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001392 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001393
Mark Salyzynde022a82017-03-01 08:30:06 -08001394 if (err < 0 && errno != ENOENT && !clearFail) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001395 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001396 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001397 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001398 }
1399 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001400 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001401 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001402 }
1403
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001404 if (setLogSize) {
1405 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001406 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001407 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001408 }
1409
Joe Onorato6fa09a02010-02-26 10:04:23 -08001410 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001411 long size = android_logger_get_log_size(dev->logger);
1412 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001413
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001414 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001415 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001416 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001417 std::string str = android::base::StringPrintf(
1418 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1419 " max entry is %db, max payload is %db\n",
1420 dev->device,
1421 value_of_size(size), multiplier_of_size(size),
1422 value_of_size(readable), multiplier_of_size(readable),
1423 (int)LOGGER_ENTRY_MAX_LEN,
1424 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1425 TEMP_FAILURE_RETRY(write(context->output_fd,
1426 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001427 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001428 }
1429
1430 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001431 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001432
1433 context->retval = EXIT_SUCCESS;
1434
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001435 // report any errors in the above loop and exit
1436 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001437 logcat_panic(context, HELP_FALSE,
1438 "Unable to open log device '%s'\n", openDeviceFail);
1439 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001440 }
1441 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001442 logcat_panic(context, HELP_FALSE,
1443 "failed to clear the '%s' log\n", clearFail);
1444 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001445 }
1446 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001447 logcat_panic(context, HELP_FALSE,
1448 "failed to set the '%s' log size\n", setSizeFail);
1449 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001450 }
1451 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001452 logcat_panic(context, HELP_FALSE,
1453 "failed to get the readable '%s' log size", getSizeFail);
1454 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001455 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001456
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001457 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001458 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001459 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001460 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001461 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001462 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1463 buf[len] = '\0';
1464 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001465 logcat_panic(context, HELP_FALSE,
1466 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001467 }
1468 free(buf);
1469 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001470 logcat_panic(context, HELP_FALSE,
1471 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001472 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001473 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001474 }
1475
Mark Salyzyn1c950472014-04-01 17:19:47 -07001476 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001477 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001478 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001479
Mark Salyzyn5f606602017-02-10 13:09:07 -08001480 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001481 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001482 if (getPruneList) {
1483 android_logger_get_prune_list(logger_list, buf, len);
1484 } else {
1485 android_logger_get_statistics(logger_list, buf, len);
1486 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001487 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001488 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001489 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001490 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001491 break;
1492 }
Traian Schiau59763032015-04-10 15:51:39 +03001493 size_t ret = atol(buf) + 1;
1494 if (ret <= len) {
1495 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001496 break;
1497 }
Traian Schiau59763032015-04-10 15:51:39 +03001498 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001499 }
1500
1501 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001502 logcat_panic(context, HELP_FALSE, "failed to read data");
1503 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001504 }
1505
1506 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001507 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001508 *cp = '\0';
1509 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001510 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001511
1512 // squash out the byte count
1513 cp = buf;
1514 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001515 while (isdigit(*cp)) ++cp;
1516 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001517 }
1518
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001519 len = strlen(cp);
1520 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001521 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001522 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001523 }
1524
Mark Salyzynde022a82017-03-01 08:30:06 -08001525 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001526
Mark Salyzynde022a82017-03-01 08:30:06 -08001527 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001528 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001529
Mark Salyzyn5f606602017-02-10 13:09:07 -08001530 // LOG_EVENT_INT(10, 12345);
1531 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1532 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001533
Mark Salyzynde022a82017-03-01 08:30:06 -08001534 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001535
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001536 while (!context->stop &&
1537 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001538 struct log_msg log_msg;
1539 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001540 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001541 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1542 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001543 }
1544
1545 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001546 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001547
1548 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001549 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1550 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001551 }
1552 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001553 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1554 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001555 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001556 logcat_panic(context, HELP_FALSE, "logcat read failure");
1557 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001558 }
1559
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001560 log_device_t* d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001561 for (d = devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001562 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001563 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001564 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001565 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001566 d = &unexpected;
1567 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001568 }
1569
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001570 if (dev != d) {
1571 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001572 maybePrintStart(context, dev, printDividers);
1573 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001574 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001575 if (context->printBinary) {
1576 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001577 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001578 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001579 }
1580 }
1581
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001582close:
Mark Salyzyn95132e92013-11-22 10:55:48 -08001583 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001584
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001585exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001586 // close write end of pipe to help things along
1587 if (context->output_fd == context->fds[1]) {
1588 android::close_output(context);
1589 }
1590 if (context->error_fd == context->fds[1]) {
1591 android::close_error(context);
1592 }
1593 if (context->fds[1] >= 0) {
1594 // NB: should be closed by the above
1595 int save_errno = errno;
1596 close(context->fds[1]);
1597 errno = save_errno;
1598 context->fds[1] = -1;
1599 }
1600 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001601 return context->retval;
1602}
1603
1604// Can block
1605int android_logcat_run_command(android_logcat_context ctx,
1606 int output, int error,
1607 int argc, char* const* argv,
1608 char* const* envp) {
1609 android_logcat_context_internal* context = ctx;
1610
1611 context->output_fd = output;
1612 context->error_fd = error;
1613 context->argc = argc;
1614 context->argv = argv;
1615 context->envp = envp;
1616 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001617 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001618 return __logcat(context);
1619}
1620
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001621// starts a thread, opens a pipe, returns reading end.
1622int android_logcat_run_command_thread(android_logcat_context ctx,
1623 int argc, char* const* argv,
1624 char* const* envp) {
1625 android_logcat_context_internal* context = ctx;
1626
1627 int save_errno = EBUSY;
Mark Salyzynde022a82017-03-01 08:30:06 -08001628 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001629
1630 if (pipe(context->fds) < 0) {
1631 save_errno = errno;
1632 goto exit;
1633 }
1634
1635 pthread_attr_t attr;
1636 if (pthread_attr_init(&attr)) {
1637 save_errno = errno;
1638 goto close_exit;
1639 }
1640
1641 struct sched_param param;
1642 memset(&param, 0, sizeof(param));
1643 pthread_attr_setschedparam(&attr, &param);
1644 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1645 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1646 int save_errno = errno;
1647 goto pthread_attr_exit;
1648 }
1649
1650 context->stop = false;
1651 context->thread_stopped = false;
1652 context->output_fd = context->fds[1];
1653 // save off arguments so they remain while thread is active.
1654 for (int i = 0; i < argc; ++i) {
1655 context->args.push_back(std::string(argv[i]));
1656 }
1657 // save off environment so they remain while thread is active.
1658 if (envp) for (size_t i = 0; envp[i]; ++i) {
1659 context->envs.push_back(std::string(envp[i]));
1660 }
1661
1662 for (auto& str : context->args) {
1663 context->argv_hold.push_back(str.c_str());
1664 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001665 context->argv_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001666 for (auto& str : context->envs) {
1667 context->envp_hold.push_back(str.c_str());
1668 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001669 context->envp_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001670
1671 context->argc = context->argv_hold.size() - 1;
1672 context->argv = (char* const*)&context->argv_hold[0];
1673 context->envp = (char* const*)&context->envp_hold[0];
1674
1675#ifdef DEBUG
1676 fprintf(stderr, "argv[%d] = {", context->argc);
1677 for (auto str : context->argv_hold) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001678 fprintf(stderr, " \"%s\"", str ?: "nullptr");
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001679 }
1680 fprintf(stderr, " }\n");
1681 fflush(stderr);
1682#endif
1683 context->retval = EXIT_SUCCESS;
1684 if (pthread_create(&context->thr, &attr,
1685 (void*(*)(void*))__logcat, context)) {
1686 int save_errno = errno;
1687 goto argv_exit;
1688 }
1689 pthread_attr_destroy(&attr);
1690
1691 return context->fds[0];
1692
1693argv_exit:
1694 context->argv_hold.clear();
1695 context->args.clear();
1696 context->envp_hold.clear();
1697 context->envs.clear();
1698pthread_attr_exit:
1699 pthread_attr_destroy(&attr);
1700close_exit:
1701 close(context->fds[0]);
1702 context->fds[0] = -1;
1703 close(context->fds[1]);
1704 context->fds[1] = -1;
1705exit:
1706 errno = save_errno;
1707 context->stop = true;
1708 context->thread_stopped = true;
1709 context->retval = EXIT_FAILURE;
1710 return -1;
1711}
1712
1713// test if the thread is still doing 'stuff'
1714int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1715 android_logcat_context_internal* context = ctx;
1716
1717 return context->thread_stopped == false;
1718}
1719
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001720// Finished with context
1721int android_logcat_destroy(android_logcat_context* ctx) {
1722 android_logcat_context_internal* context = *ctx;
1723
Mark Salyzynde022a82017-03-01 08:30:06 -08001724 if (!context) return -EBADF;
1725
1726 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001727
1728 context->stop = true;
1729
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001730 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001731 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001732 sched_yield();
1733 }
1734
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001735 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001736 context->argv_hold.clear();
1737 context->args.clear();
1738 context->envp_hold.clear();
1739 context->envs.clear();
1740 if (context->fds[0] >= 0) {
1741 close(context->fds[0]);
1742 context->fds[0] = -1;
1743 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001744 android::close_output(context);
1745 android::close_error(context);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001746 if (context->fds[1] >= 0) {
1747 // NB: could be closed by the above fclose(s), ignore error.
1748 int save_errno = errno;
1749 close(context->fds[1]);
1750 errno = save_errno;
1751 context->fds[1] = -1;
1752 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001753
1754 android_closeEventTagMap(context->eventTagMap);
1755
1756 int retval = context->retval;
1757
1758 free(context);
1759
1760 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001761}