blob: 3d56472318ad8a24d8265655353d69c7aaa1513f [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>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070023#include <math.h>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080024#include <pthread.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070025#include <sched.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070026#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080027#include <stdio.h>
28#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080029#include <string.h>
Traian Schiau59763032015-04-10 15:51:39 +030030#include <sys/cdefs.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070031#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080032#include <sys/socket.h>
33#include <sys/stat.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070034#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070035#include <time.h>
36#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080037
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080038#include <atomic>
Mark Salyzynf3555d92015-05-27 07:39:56 -070039#include <memory>
40#include <string>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080041#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070042
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/file.h>
bohu94aab862017-02-21 14:31:19 -080044#include <android-base/properties.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 Salyzyne9ade172017-03-02 15:09:41 -080050#include <log/getopt.h>
Mark Salyzync0cf90d2017-02-10 13:09:07 -080051#include <log/logcat.h>
Colin Cross9227bd32013-07-23 16:59:20 -070052#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070053#include <private/android_logger.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080054#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080055
Casey Dahlindc42a872016-03-17 16:18:55 -070056#include <pcrecpp.h>
57
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058#define DEFAULT_MAX_ROTATED_LOGS 4
59
Mark Salyzyn13e47352017-03-06 14:56:04 -080060struct log_device_t {
61 const char* device;
62 bool binary;
63 struct logger* logger;
64 struct logger_list* logger_list;
65 bool printed;
66
67 log_device_t* next;
68
69 log_device_t(const char* d, bool b) {
70 device = d;
71 binary = b;
72 next = nullptr;
73 printed = false;
74 logger = nullptr;
75 logger_list = nullptr;
76 }
77};
78
Mark Salyzync0cf90d2017-02-10 13:09:07 -080079struct android_logcat_context_internal {
80 // status
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080081 volatile std::atomic_int retval; // valid if thread_stopped set
82 // Arguments passed in, or copies and storage thereof if a thread.
Mark Salyzync0cf90d2017-02-10 13:09:07 -080083 int argc;
84 char* const* argv;
85 char* const* envp;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080086 std::vector<std::string> args;
87 std::vector<const char*> argv_hold;
88 std::vector<std::string> envs;
89 std::vector<const char*> envp_hold;
Mark Salyzynde022a82017-03-01 08:30:06 -080090 int output_fd; // duplication of fileno(output) (below)
91 int error_fd; // duplication of fileno(error) (below)
Mark Salyzync0cf90d2017-02-10 13:09:07 -080092
93 // library
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080094 int fds[2]; // From popen call
95 FILE* output; // everything writes to fileno(output), buffer unused
96 FILE* error; // unless error == output.
97 pthread_t thr;
98 volatile std::atomic_bool stop; // quick exit flag
99 volatile std::atomic_bool thread_stopped;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800100 bool stderr_null; // shell "2>/dev/null"
101 bool stderr_stdout; // shell "2>&1"
102
103 // global variables
104 AndroidLogFormat* logformat;
105 const char* outputFileName;
106 // 0 means "no log rotation"
107 size_t logRotateSizeKBytes;
108 // 0 means "unbounded"
109 size_t maxRotatedLogs;
110 size_t outByteCount;
111 int printBinary;
112 int devCount; // >1 means multiple
113 pcrecpp::RE* regex;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800114 log_device_t* devices;
115 EventTagMap* eventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800116 // 0 means "infinite"
117 size_t maxCount;
118 size_t printCount;
Mark Salyzyn13e47352017-03-06 14:56:04 -0800119
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800120 bool printItAnyways;
121 bool debug;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800122 bool hasOpenedEventTagMap;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800123};
124
125// Creates a context associated with this logcat instance
126android_logcat_context create_android_logcat() {
127 android_logcat_context_internal* context;
128
129 context = (android_logcat_context_internal*)calloc(
130 1, sizeof(android_logcat_context_internal));
Mark Salyzynde022a82017-03-01 08:30:06 -0800131 if (!context) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800132
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800133 context->fds[0] = -1;
134 context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800135 context->output_fd = -1;
136 context->error_fd = -1;
137 context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
138
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800139 context->argv_hold.clear();
140 context->args.clear();
141 context->envp_hold.clear();
142 context->envs.clear();
143
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800144 return (android_logcat_context)context;
145}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146
Mark Salyzyn5f606602017-02-10 13:09:07 -0800147// logd prefixes records with a length field
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
149
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800150namespace android {
151
Mark Salyzyn5f606602017-02-10 13:09:07 -0800152enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700153
Mark Salyzynaa730c12016-03-30 12:38:29 -0700154// if showHelp is set, newline required in fmt statement to transition to usage
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800155static void logcat_panic(android_logcat_context_internal* context,
156 enum helpType showHelp, const char* fmt, ...)
157 __printflike(3, 4);
Traian Schiau59763032015-04-10 15:51:39 +0300158
Mark Salyzyn5f606602017-02-10 13:09:07 -0800159static int openLogFile(const char* pathname) {
Edwin Vane80b221c2012-08-13 12:55:07 -0400160 return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800161}
162
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800163static void close_output(android_logcat_context_internal* context) {
164 // split output_from_error
165 if (context->error == context->output) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800166 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800167 context->output_fd = -1;
168 }
169 if (context->error && (context->output_fd == fileno(context->error))) {
170 context->output_fd = -1;
171 }
172 if (context->output_fd == context->error_fd) {
173 context->output_fd = -1;
174 }
175 // close output channel
176 if (context->output) {
177 if (context->output != stdout) {
178 if (context->output_fd == fileno(context->output)) {
179 context->output_fd = -1;
180 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800181 if (context->fds[1] == fileno(context->output)) {
182 context->fds[1] = -1;
183 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800184 fclose(context->output);
185 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800186 context->output = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800187 }
188 if (context->output_fd >= 0) {
189 if (context->output_fd != fileno(stdout)) {
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800190 if (context->fds[1] == context->output_fd) {
191 context->fds[1] = -1;
192 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800193 close(context->output_fd);
194 }
195 context->output_fd = -1;
196 }
197}
198
199static void close_error(android_logcat_context_internal* context) {
200 // split error_from_output
201 if (context->output == context->error) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800202 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800203 context->error_fd = -1;
204 }
205 if (context->output && (context->error_fd == fileno(context->output))) {
206 context->error_fd = -1;
207 }
208 if (context->error_fd == context->output_fd) {
209 context->error_fd = -1;
210 }
211 // close error channel
212 if (context->error) {
213 if ((context->error != stderr) && (context->error != stdout)) {
214 if (context->error_fd == fileno(context->error)) {
215 context->error_fd = -1;
216 }
Mark Salyzyn1d6928b2017-02-10 13:09:07 -0800217 if (context->fds[1] == fileno(context->error)) {
218 context->fds[1] = -1;
219 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800220 fclose(context->error);
221 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800222 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800223 }
224 if (context->error_fd >= 0) {
225 if ((context->error_fd != fileno(stdout)) &&
226 (context->error_fd != fileno(stderr))) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800227 if (context->fds[1] == context->error_fd) context->fds[1] = -1;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800228 close(context->error_fd);
229 }
230 context->error_fd = -1;
231 }
232}
233
234static void rotateLogs(android_logcat_context_internal* context) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235 int err;
236
237 // Can't rotate logs if we're not outputting to a file
Mark Salyzynde022a82017-03-01 08:30:06 -0800238 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800239
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800240 close_output(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800241
Mark Salyzyn5f606602017-02-10 13:09:07 -0800242 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800243 // maxRotatedLogs in decimal. eg:
244 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800245 // -> log10(30) == 1.477
246 // -> maxRotationCountDigits == 2
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700247 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800248 (context->maxRotatedLogs > 0)
249 ? (int)(floor(log10(context->maxRotatedLogs) + 1))
250 : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700251
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800252 for (int i = context->maxRotatedLogs; i > 0; i--) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700253 std::string file1 = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800254 "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800255
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700256 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800257 if (!(i - 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800258 file0 = android::base::StringPrintf("%s", context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800259 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800260 file0 =
261 android::base::StringPrintf("%s.%.*d", context->outputFileName,
262 maxRotationCountDigits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263 }
264
Mark Salyzynde022a82017-03-01 08:30:06 -0800265 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300266 perror("while rotating log files");
267 break;
268 }
269
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700270 err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800271
272 if (err < 0 && errno != ENOENT) {
273 perror("while rotating log files");
274 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275 }
276
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800277 context->output_fd = openLogFile(context->outputFileName);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800278
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800279 if (context->output_fd < 0) {
280 logcat_panic(context, HELP_FALSE, "couldn't open output file");
281 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800282 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800283 context->output = fdopen(context->output_fd, "web");
Mark Salyzynde022a82017-03-01 08:30:06 -0800284 if (!context->output) {
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800285 logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
286 return;
287 }
288 if (context->stderr_stdout) {
289 close_error(context);
290 context->error = context->output;
291 context->error_fd = context->output_fd;
292 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800293
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800294 context->outByteCount = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295}
296
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800297void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800298 size_t size = buf->len();
299
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800300 TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800301}
302
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800303static bool regexOk(android_logcat_context_internal* context,
304 const AndroidLogEntry& entry) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800305 if (!context->regex) return true;
Casey Dahlindc42a872016-03-17 16:18:55 -0700306
Casey Dahlindc42a872016-03-17 16:18:55 -0700307 std::string messageString(entry.message, entry.messageLen);
308
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800309 return context->regex->PartialMatch(messageString);
Casey Dahlindc42a872016-03-17 16:18:55 -0700310}
311
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800312static void processBuffer(android_logcat_context_internal* context,
313 log_device_t* dev, struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700314 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800315 int err;
316 AndroidLogEntry entry;
317 char binaryMsgBuf[1024];
318
Joe Onorato6fa09a02010-02-26 10:04:23 -0800319 if (dev->binary) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800320 if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800321 context->eventTagMap = android_openEventTagMap(nullptr);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800322 context->hasOpenedEventTagMap = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800323 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800324 err = android_log_processBinaryLogBuffer(
325 &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
326 sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800327 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800328 // entry.priority, entry.messageLen, entry.message);
329 } else {
Mark Salyzyn95132e92013-11-22 10:55:48 -0800330 err = android_log_processLogBuffer(&buf->entry_v1, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800331 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800332 if ((err < 0) && !context->debug) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333
Mark Salyzyn5f606602017-02-10 13:09:07 -0800334 if (android_log_shouldPrintLine(
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800335 context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
Mark Salyzyn5f606602017-02-10 13:09:07 -0800336 entry.priority)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800337 bool match = regexOk(context, entry);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800338
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800339 context->printCount += match;
340 if (match || context->printItAnyways) {
341 bytesWritten = android_log_printLogLine(context->logformat,
342 context->output_fd, &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700343
Mark Salyzync9202772016-03-30 09:38:31 -0700344 if (bytesWritten < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800345 logcat_panic(context, HELP_FALSE, "output error");
346 return;
Mark Salyzync9202772016-03-30 09:38:31 -0700347 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800348 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800349 }
350
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800351 context->outByteCount += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800352
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800353 if (context->logRotateSizeKBytes > 0 &&
354 (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
355 rotateLogs(context);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800357}
358
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800359static void maybePrintStart(android_logcat_context_internal* context,
360 log_device_t* dev, bool printDividers) {
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800361 if (!dev->printed || printDividers) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800362 if (context->devCount > 1 && !context->printBinary) {
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800363 char buf[1024];
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800364 snprintf(buf, sizeof(buf), "--------- %s %s\n",
Mark Salyzyn5f606602017-02-10 13:09:07 -0800365 dev->printed ? "switch to" : "beginning of", dev->device);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800366 if (write(context->output_fd, buf, strlen(buf)) < 0) {
367 logcat_panic(context, HELP_FALSE, "output error");
368 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800369 }
370 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800371 dev->printed = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800372 }
373}
374
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800375static void setupOutputAndSchedulingPolicy(
376 android_logcat_context_internal* context, bool blocking) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800377 if (!context->outputFileName) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378
Mark Salyzynad5e4112016-08-04 07:53:52 -0700379 if (blocking) {
380 // Lower priority and set to batch scheduling if we are saving
381 // the logs into files and taking continuous content.
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800382 if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
383 fprintf(context->error,
384 "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700385 }
386
387 struct sched_param param;
388 memset(&param, 0, sizeof(param));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800389 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700390 fprintf(stderr, "failed to set to batch scheduler\n");
391 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800392
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800393 if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
394 context->error) {
395 fprintf(context->error, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700396 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800397 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700398
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800399 close_output(context);
Mark Salyzynad5e4112016-08-04 07:53:52 -0700400
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800401 context->output_fd = openLogFile(context->outputFileName);
402
403 if (context->output_fd < 0) {
404 logcat_panic(context, HELP_FALSE, "couldn't open output file");
405 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700406 }
407
408 struct stat statbuf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800409 if (fstat(context->output_fd, &statbuf) == -1) {
410 close_output(context);
411 logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
412 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700413 }
414
Mark Salyzyn5f606602017-02-10 13:09:07 -0800415 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800416 close_output(context);
417 logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
418 return;
Mark Salyzynad5e4112016-08-04 07:53:52 -0700419 }
420
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800421 context->output = fdopen(context->output_fd, "web");
422
423 context->outByteCount = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424}
425
Mark Salyzyn5f606602017-02-10 13:09:07 -0800426// clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800427static void show_help(android_logcat_context_internal* context) {
428 if (!context->error) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800430 const char* cmd = strrchr(context->argv[0], '/');
431 cmd = cmd ? cmd + 1 : context->argv[0];
432
433 fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
434
435 fprintf(context->error, "options include:\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700436 " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
437 " -f <file>, --file=<file> Log to file. Default is stdout\n"
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700438 " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
439 " Rotate log every kbytes. Requires -f option\n"
440 " -n <count>, --rotate-count=<count>\n"
441 " Sets max number of rotated logs to <count>, default 4\n"
Mark Salyzyn02687e72016-08-03 14:20:41 -0700442 " --id=<id> If the signature id for logging to file changes, then clear\n"
443 " the fileset and continue\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700444 " -v <format>, --format=<format>\n"
Mark Salyzyn9cfd1c62016-07-06 11:12:14 -0700445 " Sets log print format verb and adverbs, where <format> is:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700446 " brief help long process raw tag thread threadtime time\n"
Mark Salyzyne735a732016-07-06 13:30:40 -0700447 " and individually flagged modifying adverbs can be added:\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700448 " color descriptive epoch monotonic printable uid\n"
449 " usec UTC year zone\n"
Mark Salyzynb45a1752017-02-28 09:20:31 -0800450 " Multiple -v parameters or comma separated list of format and\n"
451 " format modifiers are allowed.\n"
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800452 // private and undocumented nsec, no signal, too much noise
453 // useful for -T or -t <timestamp> accurate testing though.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700454 " -D, --dividers Print dividers between each log buffer\n"
455 " -c, --clear Clear (flush) the entire log and exit\n"
Mark Salyzynb7d059b2016-06-06 14:56:00 -0700456 " if Log to File specified, clear fileset instead\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700457 " -d Dump the log and then exit (don't block)\n"
458 " -e <expr>, --regex=<expr>\n"
459 " Only print lines where the log message matches <expr>\n"
460 " where <expr> is a regular expression\n"
461 // Leave --head undocumented as alias for -m
462 " -m <count>, --max-count=<count>\n"
463 " Quit after printing <count> lines. This is meant to be\n"
464 " paired with --regex, but will work on its own.\n"
465 " --print Paired with --regex and --max-count to let content bypass\n"
Mark Salyzync9202772016-03-30 09:38:31 -0700466 " regex filter but still stop at number of matches.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700467 // Leave --tail undocumented as alias for -t
468 " -t <count> Print only the most recent <count> lines (implies -d)\n"
469 " -t '<time>' Print most recent lines since specified time (implies -d)\n"
470 " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
471 " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700472 " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700473 " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700474 " -g, --buffer-size Get the size of the ring buffer.\n"
475 " -G <size>, --buffer-size=<size>\n"
476 " Set size of log ring buffer, may suffix with K or M.\n"
Oleksiy Avramchenko39e2d222016-11-29 12:48:11 +0100477 " -L, --last Dump logs from prior to last reboot\n"
Mark Salyzyn083b0372015-12-04 10:59:45 -0800478 // Leave security (Device Owner only installations) and
479 // kernel (userdebug and eng) buffers undocumented.
Mark Salyzyn378f4742016-04-12 09:11:46 -0700480 " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
481 " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
Mark Salyzyn45177732016-04-11 14:03:48 -0700482 " Multiple -b parameters or comma separated list of buffers are\n"
483 " allowed. Buffers interleaved. Default -b main,system,crash.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700484 " -B, --binary Output the log in binary.\n"
485 " -S, --statistics Output statistics.\n"
486 " -p, --prune Print prune white and ~black list. Service is specified as\n"
487 " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
Mark Salyzynbbbe14f2014-04-11 13:49:43 -0700488 " with ~, otherwise weighed for longevity if unadorned. All\n"
489 " other pruning activity is oldest first. Special case ~!\n"
490 " represents an automatic quicker pruning for the noisiest\n"
491 " UID as determined by the current statistics.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700492 " -P '<list> ...', --prune='<list> ...'\n"
493 " Set prune white and ~black list, using same format as\n"
494 " listed above. Must be quoted.\n"
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800495 " --pid=<pid> Only prints logs from the given pid.\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700496 // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800497 " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
498 " comes first. Improves efficiency of polling by providing\n"
499 " an about-to-wrap wakeup.\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800501 fprintf(context->error, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502 " <tag>[:priority]\n\n"
503 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700504 " V Verbose (default for <tag>)\n"
505 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506 " I Info\n"
507 " W Warn\n"
508 " E Error\n"
509 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700510 " S Silent (suppress all output)\n"
511 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
512 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
513 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
514 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
515 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700516 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517}
518
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800519static void show_format_help(android_logcat_context_internal* context) {
520 if (!context->error) return;
521 fprintf(context->error,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700522 "-v <format>, --format=<format> options:\n"
523 " Sets log print format verb and adverbs, where <format> is:\n"
524 " brief long process raw tag thread threadtime time\n"
525 " and individually flagged modifying adverbs can be added:\n"
526 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
527 "\nSingle format verbs:\n"
528 " brief — Display priority/tag and PID of the process issuing the message.\n"
529 " long — Display all metadata fields, separate messages with blank lines.\n"
530 " process — Display PID only.\n"
531 " raw — Display the raw log message, with no other metadata fields.\n"
532 " tag — Display the priority/tag only.\n"
Mark Salyzync74f8d92017-05-15 13:40:33 -0700533 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700534 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
535 " and TID of the thread issuing the message. (the default format).\n"
536 " time — Display the date, invocation time, priority/tag, and PID of the\n"
537 " process issuing the message.\n"
538 "\nAdverb modifiers can be used in combination:\n"
539 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
540 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
541 " descriptive — events logs only, descriptions from event-log-tags database.\n"
542 " epoch — Display time as seconds since Jan 1 1970.\n"
543 " monotonic — Display time as cpu seconds since last boot.\n"
544 " printable — Ensure that any binary logging content is escaped.\n"
545 " uid — If permitted, display the UID or Android ID of logged process.\n"
546 " usec — Display time down the microsecond precision.\n"
547 " UTC — Display time as UTC.\n"
548 " year — Add the year to the displayed time.\n"
549 " zone — Add the local timezone to the displayed time.\n"
550 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
551 );
552}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800553// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700554
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800555static int setLogFormat(android_logcat_context_internal* context,
556 const char* formatString) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800557 AndroidLogPrintFormat format;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558
559 format = android_log_formatFromString(formatString);
560
Mark Salyzynde022a82017-03-01 08:30:06 -0800561 // invalid string?
562 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800564 return android_log_setPrintFormat(context->logformat, format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565}
566
Mark Salyzyn5f606602017-02-10 13:09:07 -0800567static const char multipliers[][2] = { { "" }, { "K" }, { "M" }, { "G" } };
Mark Salyzyn671e3432014-05-06 07:34:59 -0700568
Mark Salyzyn5f606602017-02-10 13:09:07 -0800569static unsigned long value_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700570 for (unsigned i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800571 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
572 value /= 1024, ++i)
573 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700574 return value;
575}
576
Mark Salyzyn5f606602017-02-10 13:09:07 -0800577static const char* multiplier_of_size(unsigned long value) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700578 unsigned i;
579 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800580 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
581 value /= 1024, ++i)
582 ;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700583 return multipliers[i];
584}
585
Mark Salyzyn5f606602017-02-10 13:09:07 -0800586// String to unsigned int, returns -1 if it fails
587static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
588 size_t max = SIZE_MAX) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800589 if (!ptr) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300590
Mark Salyzyn5f606602017-02-10 13:09:07 -0800591 char* endp;
Kristian Monsen562e5132015-06-05 14:10:12 -0700592 errno = 0;
593 size_t ret = (size_t)strtoll(ptr, &endp, 0);
594
Mark Salyzynde022a82017-03-01 08:30:06 -0800595 if (endp[0] || errno) return false;
Kristian Monsen562e5132015-06-05 14:10:12 -0700596
Mark Salyzynde022a82017-03-01 08:30:06 -0800597 if ((ret > max) || (ret < min)) return false;
Traian Schiau59763032015-04-10 15:51:39 +0300598
599 *val = ret;
600 return true;
601}
602
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800603static void logcat_panic(android_logcat_context_internal* context,
604 enum helpType showHelp, const char* fmt, ...) {
605 context->retval = EXIT_FAILURE;
606 if (!context->error) {
607 context->stop = true;
608 return;
609 }
610
Mark Salyzyn5f606602017-02-10 13:09:07 -0800611 va_list args;
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700612 va_start(args, fmt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800613 vfprintf(context->error, fmt, args);
Mark Salyzyn77d7e812015-04-13 09:27:57 -0700614 va_end(args);
Traian Schiau59763032015-04-10 15:51:39 +0300615
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700616 switch (showHelp) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800617 case HELP_TRUE:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800618 show_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800619 break;
620 case HELP_FORMAT:
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800621 show_format_help(context);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800622 break;
623 case HELP_FALSE:
624 default:
625 break;
Traian Schiau59763032015-04-10 15:51:39 +0300626 }
627
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800628 context->stop = true;
Traian Schiau59763032015-04-10 15:51:39 +0300629}
630
Mark Salyzyn5f606602017-02-10 13:09:07 -0800631static char* parseTime(log_time& t, const char* cp) {
632 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800633 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700634 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800635 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700636 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700637}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700638
Mark Salyzyn31961062016-08-04 07:43:46 -0700639// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyne9ade172017-03-02 15:09:41 -0800640static log_time lastLogTime(const char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700641 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800642 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700643
Mark Salyzynf3555d92015-05-27 07:39:56 -0700644 std::string directory;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800645 const char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700646 if (!file) {
647 directory = ".";
648 file = outputFileName;
649 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800650 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700651 ++file;
652 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700653
Mark Salyzyn5f606602017-02-10 13:09:07 -0800654 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
655 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800656 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700657
Mark Salyzyn31961062016-08-04 07:43:46 -0700658 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700659
Mark Salyzynf3555d92015-05-27 07:39:56 -0700660 size_t len = strlen(file);
661 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800662 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700663
Mark Salyzynde022a82017-03-01 08:30:06 -0800664 while (!!(dp = readdir(dir.get()))) {
665 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800666 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800667 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700668 continue;
669 }
670
671 std::string file_name = directory;
672 file_name += "/";
673 file_name += dp->d_name;
674 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800675 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700676
677 bool found = false;
678 for (const auto& line : android::base::Split(file, "\n")) {
679 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800680 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800681 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700682 // determine the time precision of the logs (eg: msec or usec)
683 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
684 if (t.tv_nsec % (mod * 10)) {
685 modulo.tv_nsec = mod;
686 break;
687 }
688 }
689 // We filter any times later than current as we may not have the
690 // year stored with each log entry. Also, since it is possible for
691 // entries to be recorded out of order (very rare) we select the
692 // maximum we find just in case.
693 if ((t < now) && (t > retval)) {
694 retval = t;
695 found = true;
696 }
697 }
698 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800699 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700700 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800701 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700702 // tail_time prints matching or higher, round up by the modulo to prevent
703 // a replay of the last entry we have just checked.
704 retval += modulo;
705 return retval;
706}
707
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800708const char* getenv(android_logcat_context_internal* context, const char* name) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800709 if (!context->envp || !name || !*name) return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800710
711 for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
712 if (strncmp(context->envp[i], name, len)) continue;
713 if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
714 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800715 return nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800716}
717
Mark Salyzyn5f606602017-02-10 13:09:07 -0800718} // namespace android
Traian Schiau59763032015-04-10 15:51:39 +0300719
Mark Salyzyn5f606602017-02-10 13:09:07 -0800720void reportErrorName(const char** current, const char* name,
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800721 bool blockSecurity) {
Mark Salyzynde022a82017-03-01 08:30:06 -0800722 if (*current) return;
723 if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
724 *current = name;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800725 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800726}
Traian Schiau59763032015-04-10 15:51:39 +0300727
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800728static int __logcat(android_logcat_context_internal* context) {
Traian Schiau59763032015-04-10 15:51:39 +0300729 using namespace android;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730 int err;
Mark Salyzynb45a1752017-02-28 09:20:31 -0800731 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800732 bool clearLog = false;
733 bool allSelected = false;
734 bool getLogSize = false;
735 bool getPruneList = false;
736 bool printStatistics = false;
737 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800738 unsigned long setLogSize = 0;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800739 const char* setPruneList = nullptr;
740 const char* setId = nullptr;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800741 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynf3290292017-02-10 13:09:07 -0800742 std::string forceFilters;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800743 log_device_t* dev;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800744 struct logger_list* logger_list;
Traian Schiau59763032015-04-10 15:51:39 +0300745 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800746 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700747 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700748 bool got_t = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800750 // object instantiations before goto's can happen
751 log_device_t unexpected("unexpected", false);
Mark Salyzynde022a82017-03-01 08:30:06 -0800752 const char* openDeviceFail = nullptr;
753 const char* clearFail = nullptr;
754 const char* setSizeFail = nullptr;
755 const char* getSizeFail = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800756 int argc = context->argc;
757 char* const* argv = context->argv;
Mark Salyzyn65772ca2013-12-13 11:10:11 -0800758
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800759 context->output = stdout;
760 context->error = stderr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800761
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800762 for (int i = 0; i < argc; ++i) {
763 // Simulate shell stderr redirect parsing
764 if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
765
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800766 // Append to file not implemented, just open file
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800767 size_t skip = (argv[i][2] == '>') + 2;
768 if (!strcmp(&argv[i][skip], "/dev/null")) {
769 context->stderr_null = true;
770 } else if (!strcmp(&argv[i][skip], "&1")) {
771 context->stderr_stdout = true;
772 } else {
773 // stderr file redirections are not supported
774 fprintf(context->stderr_stdout ? stdout : stderr,
775 "stderr redirection to file %s unsupported, skipping\n",
776 &argv[i][skip]);
777 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800778 // Only the first one
779 break;
780 }
781
Mark Salyzynde022a82017-03-01 08:30:06 -0800782 const char* filename = nullptr;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800783 for (int i = 0; i < argc; ++i) {
784 // Simulate shell stdout redirect parsing
785 if (argv[i][0] != '>') continue;
786
787 // Append to file not implemented, just open file
788 filename = &argv[i][(argv[i][1] == '>') + 1];
789 // Only the first one
790 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800791 }
792
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800793 // Deal with setting up file descriptors and FILE pointers
Mark Salyzynde022a82017-03-01 08:30:06 -0800794 if (context->error_fd >= 0) { // Is an error file descriptor supplied?
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800795 if (context->error_fd == context->output_fd) {
796 context->stderr_stdout = true;
Mark Salyzynde022a82017-03-01 08:30:06 -0800797 } else if (context->stderr_null) { // redirection told us to close it
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800798 close(context->error_fd);
799 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800800 } else { // All Ok, convert error to a FILE pointer
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800801 context->error = fdopen(context->error_fd, "web");
802 if (!context->error) {
803 context->retval = -errno;
804 fprintf(context->stderr_stdout ? stdout : stderr,
805 "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
806 strerror(errno));
807 goto exit;
808 }
809 }
810 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800811 if (context->output_fd >= 0) { // Is an output file descriptor supplied?
812 if (filename) { // redirect to file, close supplied file descriptor.
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800813 close(context->output_fd);
814 context->output_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800815 } else { // All Ok, convert output to a FILE pointer
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800816 context->output = fdopen(context->output_fd, "web");
817 if (!context->output) {
818 context->retval = -errno;
819 fprintf(context->stderr_stdout ? stdout : context->error,
820 "Failed to fdopen(output_fd=%d) %s\n",
821 context->output_fd, strerror(errno));
822 goto exit;
823 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800824 }
825 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800826 if (filename) { // We supplied an output file redirected in command line
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800827 context->output = fopen(filename, "web");
828 }
829 // Deal with 2>&1
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800830 if (context->stderr_stdout) context->error = context->output;
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800831 // Deal with 2>/dev/null
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800832 if (context->stderr_null) {
833 context->error_fd = -1;
Mark Salyzynde022a82017-03-01 08:30:06 -0800834 context->error = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800835 }
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800836 // Only happens if output=stdout or output=filename
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800837 if ((context->output_fd < 0) && context->output) {
838 context->output_fd = fileno(context->output);
839 }
840 // Only happens if error=stdout || error=stderr
841 if ((context->error_fd < 0) && context->error) {
842 context->error_fd = fileno(context->error);
843 }
844
845 context->logformat = android_log_format_new();
846
Mark Salyzynde022a82017-03-01 08:30:06 -0800847 if (argc == 2 && !strcmp(argv[1], "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800848 show_help(context);
849 context->retval = EXIT_SUCCESS;
850 goto exit;
851 }
852
Mark Salyzynb45a1752017-02-28 09:20:31 -0800853 // meant to catch comma-delimited values, but cast a wider
854 // net for stability dealing with possible mistaken inputs.
855 static const char delimiters[] = ",:; \t\n\r\f";
856
Mark Salyzyne9ade172017-03-02 15:09:41 -0800857 struct getopt_context optctx;
858 INIT_GETOPT_CONTEXT(optctx);
859 optctx.opterr = !!context->error;
860 optctx.optstderr = context->error;
861
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800862 for (;;) {
863 int ret;
864
Kristian Monsen562e5132015-06-05 14:10:12 -0700865 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700866 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700867 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800868 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700869 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800870 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700871 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800872 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700873 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800874 { "binary", no_argument, nullptr, 'B' },
875 { "buffer", required_argument, nullptr, 'b' },
876 { "buffer-size", optional_argument, nullptr, 'g' },
877 { "clear", no_argument, nullptr, 'c' },
878 { debug_str, no_argument, nullptr, 0 },
879 { "dividers", no_argument, nullptr, 'D' },
880 { "file", required_argument, nullptr, 'f' },
881 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700882 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800883 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700884 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800885 { "head", required_argument, nullptr, 'm' },
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700886 { "help", no_argument, nullptr, 'h' },
Mark Salyzynde022a82017-03-01 08:30:06 -0800887 { id_str, required_argument, nullptr, 0 },
888 { "last", no_argument, nullptr, 'L' },
889 { "max-count", required_argument, nullptr, 'm' },
890 { pid_str, required_argument, nullptr, 0 },
891 { print_str, no_argument, nullptr, 0 },
892 { "prune", optional_argument, nullptr, 'p' },
893 { "regex", required_argument, nullptr, 'e' },
894 { "rotate-count", required_argument, nullptr, 'n' },
895 { "rotate-kbytes", required_argument, nullptr, 'r' },
896 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700897 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800898 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800899 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800900 { wrap_str, optional_argument, nullptr, 0 },
901 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700902 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800903 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700904
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700905 ret = getopt_long_r(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
906 long_options, &option_index, &optctx);
Mark Salyzynde022a82017-03-01 08:30:06 -0800907 if (ret < 0) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908
Kristian Monsen562e5132015-06-05 14:10:12 -0700909 switch (ret) {
910 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700911 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700912 if (long_options[option_index].name == pid_str) {
913 // ToDo: determine runtime PID_MAX?
Mark Salyzyne9ade172017-03-02 15:09:41 -0800914 if (!getSizeTArg(optctx.optarg, &pid, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800915 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -0800916 long_options[option_index].name,
917 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800918 goto exit;
Kristian Monsen562e5132015-06-05 14:10:12 -0700919 }
920 break;
921 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800922 if (long_options[option_index].name == wrap_str) {
Mark Salyzyn5f606602017-02-10 13:09:07 -0800923 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800924 ANDROID_LOG_NONBLOCK;
925 // ToDo: implement API that supports setting a wrap timeout
926 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800927 if (optctx.optarg &&
928 !getSizeTArg(optctx.optarg, &dummy, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800929 logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -0800930 long_options[option_index].name,
931 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800932 goto exit;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800933 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800934 if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
935 context->error) {
936 fprintf(context->error,
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800937 "WARNING: %s %u seconds, ignoring %zu\n",
938 long_options[option_index].name,
939 ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
940 }
941 break;
942 }
Mark Salyzync9202772016-03-30 09:38:31 -0700943 if (long_options[option_index].name == print_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800944 context->printItAnyways = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700945 break;
946 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800947 if (long_options[option_index].name == debug_str) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800948 context->debug = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800949 break;
950 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700951 if (long_options[option_index].name == id_str) {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800952 setId = (optctx.optarg && optctx.optarg[0]) ? optctx.optarg
953 : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700954 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800955 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700956
Mark Salyzyn95132e92013-11-22 10:55:48 -0800957 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800958 // default to all silent
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800959 android_log_addFilterRule(context->logformat, "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800960 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800961
962 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800963 clearLog = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800964 mode |= ANDROID_LOG_WRONLY;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800965 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800967 case 'L':
Mark Salyzyn5f606602017-02-10 13:09:07 -0800968 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
969 ANDROID_LOG_NONBLOCK;
970 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800971
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800972 case 'd':
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800973 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800974 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800975
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800976 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700977 got_t = true;
Mark Salyzyn2d3f38a2015-01-26 10:46:44 -0800978 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800979 // FALLTHRU
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800980 case 'T':
Mark Salyzyne9ade172017-03-02 15:09:41 -0800981 if (strspn(optctx.optarg, "0123456789") !=
982 strlen(optctx.optarg)) {
983 char* cp = parseTime(tail_time, optctx.optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800984 if (!cp) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800985 logcat_panic(context, HELP_FALSE,
Mark Salyzyn5f606602017-02-10 13:09:07 -0800986 "-%c \"%s\" not in time format\n", ret,
Mark Salyzyne9ade172017-03-02 15:09:41 -0800987 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800988 goto exit;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800989 }
990 if (*cp) {
991 char c = *cp;
992 *cp = '\0';
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800993 if (context->error) {
994 fprintf(
995 context->error,
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800996 "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -0800997 ret, optctx.optarg, c, cp + 1);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800998 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800999 *cp = c;
1000 }
1001 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001002 if (!getSizeTArg(optctx.optarg, &tail_lines, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001003 if (context->error) {
1004 fprintf(context->error,
1005 "WARNING: -%c %s invalid, setting to 1\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -08001006 ret, optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001007 }
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001008 tail_lines = 1;
1009 }
1010 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001011 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -08001012
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001013 case 'D':
1014 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001015 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001016
Casey Dahlindc42a872016-03-17 16:18:55 -07001017 case 'e':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001018 context->regex = new pcrecpp::RE(optctx.optarg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001019 break;
Casey Dahlindc42a872016-03-17 16:18:55 -07001020
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001021 case 'm': {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001022 if (!getSizeTArg(optctx.optarg, &context->maxCount)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001023 logcat_panic(context, HELP_FALSE,
1024 "-%c \"%s\" isn't an "
1025 "integer greater than zero\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -08001026 ret, optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001027 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001028 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001029 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001030
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001031 case 'g':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001032 if (!optctx.optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001033 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001034 break;
1035 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001036 // FALLTHRU
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001037
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001038 case 'G': {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001039 char* cp;
Mark Salyzyne9ade172017-03-02 15:09:41 -08001040 if (strtoll(optctx.optarg, &cp, 0) > 0) {
1041 setLogSize = strtoll(optctx.optarg, &cp, 0);
Traian Schiau59763032015-04-10 15:51:39 +03001042 } else {
1043 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001044 }
1045
Mark Salyzyn5f606602017-02-10 13:09:07 -08001046 switch (*cp) {
1047 case 'g':
1048 case 'G':
1049 setLogSize *= 1024;
1050 // FALLTHRU
1051 case 'm':
1052 case 'M':
1053 setLogSize *= 1024;
1054 // FALLTHRU
1055 case 'k':
1056 case 'K':
1057 setLogSize *= 1024;
1058 // FALLTHRU
1059 case '\0':
1060 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001061
Mark Salyzyn5f606602017-02-10 13:09:07 -08001062 default:
1063 setLogSize = 0;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001064 }
1065
1066 if (!setLogSize) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001067 logcat_panic(context, HELP_FALSE,
1068 "ERROR: -G <num><multiplier>\n");
1069 goto exit;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001070 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001071 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001072
1073 case 'p':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001074 if (!optctx.optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001075 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -08001076 break;
1077 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001078 // FALLTHRU
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001079
1080 case 'P':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001081 setPruneList = optctx.optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001082 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001083
Joe Onorato6fa09a02010-02-26 10:04:23 -08001084 case 'b': {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001085 std::unique_ptr<char, void (*)(void*)> buffers(
1086 strdup(optctx.optarg), free);
1087 char* arg = buffers.get();
Mark Salyzyn45177732016-04-11 14:03:48 -07001088 unsigned idMask = 0;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001089 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001090 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1091 if (!strcmp(arg, "default")) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001092 idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
Mark Salyzyn45177732016-04-11 14:03:48 -07001093 (1 << LOG_ID_CRASH);
Mark Salyzyne9ade172017-03-02 15:09:41 -08001094 } else if (!strcmp(arg, "all")) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001095 allSelected = true;
Mark Salyzyn45177732016-04-11 14:03:48 -07001096 idMask = (unsigned)-1;
1097 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001098 log_id_t log_id = android_name_to_log_id(arg);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001099 const char* name = android_log_id_to_name(log_id);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001100
Mark Salyzyne9ade172017-03-02 15:09:41 -08001101 if (!!strcmp(name, arg)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001102 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001103 "unknown buffer %s\n", arg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001104 goto exit;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001105 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001106 if (log_id == LOG_ID_SECURITY) allSelected = false;
Mark Salyzyn45177732016-04-11 14:03:48 -07001107 idMask |= (1 << log_id);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001108 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001109 arg = nullptr;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001110 }
1111
Mark Salyzyn45177732016-04-11 14:03:48 -07001112 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001113 const char* name = android_log_id_to_name((log_id_t)i);
Mark Salyzyn45177732016-04-11 14:03:48 -07001114 log_id_t log_id = android_name_to_log_id(name);
Mark Salyzyn083b0372015-12-04 10:59:45 -08001115
Mark Salyzynde022a82017-03-01 08:30:06 -08001116 if (log_id != (log_id_t)i) continue;
1117 if (!(idMask & (1 << i))) continue;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001118
Mark Salyzyn45177732016-04-11 14:03:48 -07001119 bool found = false;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001120 for (dev = context->devices; dev; dev = dev->next) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001121 if (!strcmp(name, dev->device)) {
1122 found = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001123 break;
1124 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001125 if (!dev->next) break;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001126 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001127 if (found) continue;
Mark Salyzyn45177732016-04-11 14:03:48 -07001128
Mark Salyzyn5f606602017-02-10 13:09:07 -08001129 bool binary =
1130 !strcmp(name, "events") || !strcmp(name, "security");
Mark Salyzyn45177732016-04-11 14:03:48 -07001131 log_device_t* d = new log_device_t(name, binary);
1132
Mark Salyzyn083b0372015-12-04 10:59:45 -08001133 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001134 dev->next = d;
1135 dev = d;
1136 } else {
Mark Salyzyn13e47352017-03-06 14:56:04 -08001137 context->devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001138 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001139 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001140 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001141 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001142
1143 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001144 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001145 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001146
1147 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001148 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001149 tail_time = lastLogTime(optctx.optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -07001150 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001151 // redirect output to a file
Mark Salyzyne9ade172017-03-02 15:09:41 -08001152 context->outputFileName = optctx.optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001153 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001155 case 'r':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001156 if (!getSizeTArg(optctx.optarg, &context->logRotateSizeKBytes,
1157 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001158 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001159 "Invalid parameter \"%s\" to -r\n",
1160 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001161 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001163 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001164
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001165 case 'n':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001166 if (!getSizeTArg(optctx.optarg, &context->maxRotatedLogs, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001167 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001168 "Invalid parameter \"%s\" to -n\n",
1169 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001170 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001172 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001173
Mark Salyzynb45a1752017-02-28 09:20:31 -08001174 case 'v': {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001175 if (!strcmp(optctx.optarg, "help") ||
1176 !strcmp(optctx.optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001177 show_format_help(context);
1178 context->retval = EXIT_SUCCESS;
1179 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001180 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001181 std::unique_ptr<char, void (*)(void*)> formats(
1182 strdup(optctx.optarg), free);
1183 char* arg = formats.get();
Mark Salyzynb45a1752017-02-28 09:20:31 -08001184 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001185 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1186 err = setLogFormat(context, arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001187 if (err < 0) {
1188 logcat_panic(context, HELP_FORMAT,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001189 "Invalid parameter \"%s\" to -v\n", arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001190 goto exit;
1191 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001192 arg = nullptr;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001193 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001194 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001195 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196
1197 case 'Q':
bohu94aab862017-02-21 14:31:19 -08001198#define LOGCAT_FILTER "androidboot.logcat="
1199#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -08001200#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -08001201#define QEMU_PROPERTY "ro.kernel.qemu"
1202#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -08001203 // This is a *hidden* option used to start a version of logcat
1204 // in an emulated device only. It basically looks for
1205 // androidboot.logcat= on the kernel command line. If
1206 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -08001207 // run the program. The logcat output will go to consolepipe if
1208 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
1209 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001210 {
bohu94aab862017-02-21 14:31:19 -08001211 // if not in emulator, exit quietly
1212 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001213 context->retval = EXIT_SUCCESS;
1214 goto exit;
1215 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001216
bohu94aab862017-02-21 14:31:19 -08001217 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
1218 if (cmdline.empty()) {
1219 android::base::ReadFileToString("/proc/cmdline", &cmdline);
1220 }
1221
1222 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
1223 // if nothing found or invalid filters, exit quietly
1224 if (!logcatFilter) {
1225 context->retval = EXIT_SUCCESS;
1226 goto exit;
1227 }
1228
1229 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -08001230 const char* q = strpbrk(p, " \t\n\r");
1231 if (!q) q = p + strlen(p);
1232 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001233
bohu94aab862017-02-21 14:31:19 -08001234 // redirect our output to the emulator console pipe or console
1235 const char* consolePipe =
1236 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -08001237 const char* console =
1238 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001239
bohu94aab862017-02-21 14:31:19 -08001240 if (consolePipe) {
1241 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
1242 } else if (console) {
1243 p = console + strlen(CONSOLE_OPTION);
1244 } else {
1245 context->retval = EXIT_FAILURE;
1246 goto exit;
1247 }
1248
Mark Salyzynf3290292017-02-10 13:09:07 -08001249 q = strpbrk(p, " \t\n\r");
1250 int len = q ? q - p : strlen(p);
1251 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -08001252 std::string pipePurpose("pipe:logcat");
1253 if (consolePipe) {
1254 // example: "qemu_pipe,pipe:logcat"
1255 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
1256 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -07001257 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -08001258 if (pos != std::string::npos) {
1259 pipePurpose = devname.substr(pos + 1);
1260 devname = devname.substr(0, pos);
1261 }
1262 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001263 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001264
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001265 if (context->error) {
1266 fprintf(context->error, "logcat using %s\n",
1267 devname.c_str());
1268 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001269
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001270 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001271 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001272 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001273
bohu94aab862017-02-21 14:31:19 -08001274 if (consolePipe) {
1275 // need the trailing '\0'
1276 if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
1277 pipePurpose.size() + 1)) {
1278 fclose(fp);
1279 context->retval = EXIT_FAILURE;
1280 goto exit;
1281 }
1282 }
1283
Mark Salyzynf3290292017-02-10 13:09:07 -08001284 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001285 android::close_output(context);
1286 android::close_error(context);
1287 context->stderr_stdout = true;
1288 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001289 context->output_fd = fileno(fp);
1290 if (context->stderr_null) break;
1291 context->stderr_stdout = true;
1292 context->error = fp;
1293 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001294 }
1295 break;
1296
Mark Salyzyn34facab2014-02-06 14:48:50 -08001297 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001298 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001299 break;
1300
Traian Schiau59763032015-04-10 15:51:39 +03001301 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001302 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001303 "Option -%c needs an argument\n", optctx.optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001304 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001305
Mark Salyzyne74e51d2017-04-03 09:30:20 -07001306 case 'h':
1307 show_help(context);
1308 show_format_help(context);
1309 goto exit;
1310
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001311 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001312 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -08001313 optctx.optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001314 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001315 }
1316 }
1317
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001318 if (context->maxCount && got_t) {
1319 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001320 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001321 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001322 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001323 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001324 // One day it would be nice if --print -v color and --regex <expr>
1325 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001326 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001327 if (context->error) {
1328 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001329 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001330 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001331 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001332 }
1333 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001334 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001335
Mark Salyzyn13e47352017-03-06 14:56:04 -08001336 if (!context->devices) {
1337 dev = context->devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001338 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001339 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001340 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001341 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001342 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001343 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001344 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001345 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001346 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001347 }
1348
Mark Salyzynde022a82017-03-01 08:30:06 -08001349 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001350 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1351 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001352 }
1353
Mark Salyzynde022a82017-03-01 08:30:06 -08001354 if (!!setId) {
1355 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001356 logcat_panic(context, HELP_TRUE,
1357 "--id='%s' requires -f as well\n", setId);
1358 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001359 }
1360
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001361 std::string file_name = android::base::StringPrintf(
1362 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001363 std::string file;
1364 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001365 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1366 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001367 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001368 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001369
Mark Salyzynde022a82017-03-01 08:30:06 -08001370 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001371 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001372
Mark Salyzynde022a82017-03-01 08:30:06 -08001373 if (!!logFormat) {
Mark Salyzynb45a1752017-02-28 09:20:31 -08001374 std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
1375 free);
1376 char* sv = nullptr; // protect against -ENOMEM above
1377 char* arg = formats.get();
1378 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1379 err = setLogFormat(context, arg);
1380 // environment should not cause crash of logcat
1381 if ((err < 0) && context->error) {
1382 fprintf(context->error,
1383 "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
1384 }
1385 arg = nullptr;
1386 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001387 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001388 }
1389 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001390 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001391 }
1392 }
1393
Mark Salyzynf3290292017-02-10 13:09:07 -08001394 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001395 err = android_log_addFilterString(context->logformat,
1396 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001397 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001398 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001399 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001400 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001401 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001402 } else if (argc == optctx.optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001403 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001404 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001405
Mark Salyzynde022a82017-03-01 08:30:06 -08001406 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001407 err = android_log_addFilterString(context->logformat,
1408 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001409
Mark Salyzyn95132e92013-11-22 10:55:48 -08001410 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001411 logcat_panic(context, HELP_TRUE,
1412 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1413 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001414 }
1415 }
1416 } else {
1417 // Add from commandline
Mark Salyzyne9ade172017-03-02 15:09:41 -08001418 for (int i = optctx.optind ; i < argc ; i++) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001419 // skip stderr redirections of _all_ kinds
1420 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001421 // skip stdout redirections of _all_ kinds
1422 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001423
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001424 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001425 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001426 logcat_panic(context, HELP_TRUE,
1427 "Invalid filter expression '%s'\n", argv[i]);
1428 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001429 }
1430 }
1431 }
1432
Mark Salyzyn13e47352017-03-06 14:56:04 -08001433 dev = context->devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001434 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001435 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001436 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001437 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001438 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001439 // We have three orthogonal actions below to clear, set log size and
1440 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001441 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001442 dev->logger_list = logger_list;
1443 dev->logger = android_logger_open(logger_list,
1444 android_name_to_log_id(dev->device));
1445 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001446 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001447 dev = dev->next;
1448 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001449 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001450
Mark Salyzyn02687e72016-08-03 14:20:41 -07001451 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001452 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001453 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001454 (context->maxRotatedLogs > 0) ?
1455 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1456 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001457
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001458 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001459 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001460
Mark Salyzynde022a82017-03-01 08:30:06 -08001461 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001462 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001463 "%s", context->outputFileName);
1464 } else {
1465 file = android::base::StringPrintf("%s.%.*d",
1466 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001467 }
1468
Mark Salyzynde022a82017-03-01 08:30:06 -08001469 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001470 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001471 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001472 break;
1473 }
1474
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001475 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001476
Mark Salyzynde022a82017-03-01 08:30:06 -08001477 if (err < 0 && errno != ENOENT && !clearFail) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001478 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001479 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001480 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001481 }
1482 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001483 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001484 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001485 }
1486
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001487 if (setLogSize) {
1488 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001489 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001490 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001491 }
1492
Joe Onorato6fa09a02010-02-26 10:04:23 -08001493 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001494 long size = android_logger_get_log_size(dev->logger);
1495 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001496
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001497 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001498 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001499 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001500 std::string str = android::base::StringPrintf(
1501 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1502 " max entry is %db, max payload is %db\n",
1503 dev->device,
1504 value_of_size(size), multiplier_of_size(size),
1505 value_of_size(readable), multiplier_of_size(readable),
1506 (int)LOGGER_ENTRY_MAX_LEN,
1507 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1508 TEMP_FAILURE_RETRY(write(context->output_fd,
1509 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001510 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001511 }
1512
1513 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001514 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001515
1516 context->retval = EXIT_SUCCESS;
1517
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001518 // report any errors in the above loop and exit
1519 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001520 logcat_panic(context, HELP_FALSE,
1521 "Unable to open log device '%s'\n", openDeviceFail);
1522 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001523 }
1524 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001525 logcat_panic(context, HELP_FALSE,
1526 "failed to clear the '%s' log\n", clearFail);
1527 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001528 }
1529 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001530 logcat_panic(context, HELP_FALSE,
1531 "failed to set the '%s' log size\n", setSizeFail);
1532 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001533 }
1534 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001535 logcat_panic(context, HELP_FALSE,
1536 "failed to get the readable '%s' log size", getSizeFail);
1537 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001538 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001539
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001540 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001541 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001542 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001543 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001544 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001545 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1546 buf[len] = '\0';
1547 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001548 logcat_panic(context, HELP_FALSE,
1549 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001550 }
1551 free(buf);
1552 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001553 logcat_panic(context, HELP_FALSE,
1554 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001555 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001556 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001557 }
1558
Mark Salyzyn1c950472014-04-01 17:19:47 -07001559 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001560 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001561 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001562
Mark Salyzyn5f606602017-02-10 13:09:07 -08001563 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001564 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001565 if (getPruneList) {
1566 android_logger_get_prune_list(logger_list, buf, len);
1567 } else {
1568 android_logger_get_statistics(logger_list, buf, len);
1569 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001570 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001571 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001572 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001573 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001574 break;
1575 }
Traian Schiau59763032015-04-10 15:51:39 +03001576 size_t ret = atol(buf) + 1;
1577 if (ret <= len) {
1578 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001579 break;
1580 }
Traian Schiau59763032015-04-10 15:51:39 +03001581 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001582 }
1583
1584 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001585 logcat_panic(context, HELP_FALSE, "failed to read data");
1586 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001587 }
1588
1589 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001590 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001591 *cp = '\0';
1592 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001593 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001594
1595 // squash out the byte count
1596 cp = buf;
1597 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001598 while (isdigit(*cp)) ++cp;
1599 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001600 }
1601
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001602 len = strlen(cp);
1603 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001604 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001605 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001606 }
1607
Mark Salyzynde022a82017-03-01 08:30:06 -08001608 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001609
Mark Salyzynde022a82017-03-01 08:30:06 -08001610 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001611 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001612
Mark Salyzyn5f606602017-02-10 13:09:07 -08001613 // LOG_EVENT_INT(10, 12345);
1614 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1615 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001616
Mark Salyzynde022a82017-03-01 08:30:06 -08001617 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001618
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001619 while (!context->stop &&
1620 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001621 struct log_msg log_msg;
1622 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001623 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001624 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1625 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001626 }
1627
1628 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001629 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001630
1631 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001632 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1633 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001634 }
1635 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001636 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1637 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001638 }
Luca Stefani08705142017-07-08 17:48:00 +02001639 logcat_panic(context, HELP_FALSE, "logcat read failure\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001640 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001641 }
1642
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001643 log_device_t* d;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001644 for (d = context->devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001645 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001646 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001647 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001648 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001649 d = &unexpected;
1650 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001651 }
1652
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001653 if (dev != d) {
1654 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001655 maybePrintStart(context, dev, printDividers);
1656 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001657 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001658 if (context->printBinary) {
1659 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001660 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001661 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001662 }
1663 }
1664
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001665close:
Mark Salyzyn13e47352017-03-06 14:56:04 -08001666 // Short and sweet. Implemented generic version in android_logcat_destroy.
1667 while (!!(dev = context->devices)) {
1668 context->devices = dev->next;
1669 delete dev;
1670 }
Mark Salyzyn95132e92013-11-22 10:55:48 -08001671 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001672
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001673exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001674 // close write end of pipe to help things along
1675 if (context->output_fd == context->fds[1]) {
1676 android::close_output(context);
1677 }
1678 if (context->error_fd == context->fds[1]) {
1679 android::close_error(context);
1680 }
1681 if (context->fds[1] >= 0) {
1682 // NB: should be closed by the above
1683 int save_errno = errno;
1684 close(context->fds[1]);
1685 errno = save_errno;
1686 context->fds[1] = -1;
1687 }
1688 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001689 return context->retval;
1690}
1691
1692// Can block
1693int android_logcat_run_command(android_logcat_context ctx,
1694 int output, int error,
1695 int argc, char* const* argv,
1696 char* const* envp) {
1697 android_logcat_context_internal* context = ctx;
1698
1699 context->output_fd = output;
1700 context->error_fd = error;
1701 context->argc = argc;
1702 context->argv = argv;
1703 context->envp = envp;
1704 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001705 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001706 return __logcat(context);
1707}
1708
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001709// starts a thread, opens a pipe, returns reading end.
1710int android_logcat_run_command_thread(android_logcat_context ctx,
1711 int argc, char* const* argv,
1712 char* const* envp) {
1713 android_logcat_context_internal* context = ctx;
1714
1715 int save_errno = EBUSY;
Mark Salyzynde022a82017-03-01 08:30:06 -08001716 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001717
1718 if (pipe(context->fds) < 0) {
1719 save_errno = errno;
1720 goto exit;
1721 }
1722
1723 pthread_attr_t attr;
1724 if (pthread_attr_init(&attr)) {
1725 save_errno = errno;
1726 goto close_exit;
1727 }
1728
1729 struct sched_param param;
1730 memset(&param, 0, sizeof(param));
1731 pthread_attr_setschedparam(&attr, &param);
1732 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1733 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
Mark Salyzyn210e43c2017-08-04 16:28:47 -07001734 save_errno = errno;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001735 goto pthread_attr_exit;
1736 }
1737
1738 context->stop = false;
1739 context->thread_stopped = false;
1740 context->output_fd = context->fds[1];
1741 // save off arguments so they remain while thread is active.
1742 for (int i = 0; i < argc; ++i) {
1743 context->args.push_back(std::string(argv[i]));
1744 }
1745 // save off environment so they remain while thread is active.
1746 if (envp) for (size_t i = 0; envp[i]; ++i) {
1747 context->envs.push_back(std::string(envp[i]));
1748 }
1749
1750 for (auto& str : context->args) {
1751 context->argv_hold.push_back(str.c_str());
1752 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001753 context->argv_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001754 for (auto& str : context->envs) {
1755 context->envp_hold.push_back(str.c_str());
1756 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001757 context->envp_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001758
1759 context->argc = context->argv_hold.size() - 1;
1760 context->argv = (char* const*)&context->argv_hold[0];
1761 context->envp = (char* const*)&context->envp_hold[0];
1762
1763#ifdef DEBUG
1764 fprintf(stderr, "argv[%d] = {", context->argc);
1765 for (auto str : context->argv_hold) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001766 fprintf(stderr, " \"%s\"", str ?: "nullptr");
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001767 }
1768 fprintf(stderr, " }\n");
1769 fflush(stderr);
1770#endif
1771 context->retval = EXIT_SUCCESS;
1772 if (pthread_create(&context->thr, &attr,
1773 (void*(*)(void*))__logcat, context)) {
Mark Salyzyn210e43c2017-08-04 16:28:47 -07001774 save_errno = errno;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001775 goto argv_exit;
1776 }
1777 pthread_attr_destroy(&attr);
1778
1779 return context->fds[0];
1780
1781argv_exit:
1782 context->argv_hold.clear();
1783 context->args.clear();
1784 context->envp_hold.clear();
1785 context->envs.clear();
1786pthread_attr_exit:
1787 pthread_attr_destroy(&attr);
1788close_exit:
1789 close(context->fds[0]);
1790 context->fds[0] = -1;
1791 close(context->fds[1]);
1792 context->fds[1] = -1;
1793exit:
1794 errno = save_errno;
1795 context->stop = true;
1796 context->thread_stopped = true;
1797 context->retval = EXIT_FAILURE;
1798 return -1;
1799}
1800
1801// test if the thread is still doing 'stuff'
1802int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1803 android_logcat_context_internal* context = ctx;
1804
1805 return context->thread_stopped == false;
1806}
1807
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001808// Finished with context
1809int android_logcat_destroy(android_logcat_context* ctx) {
1810 android_logcat_context_internal* context = *ctx;
1811
Mark Salyzynde022a82017-03-01 08:30:06 -08001812 if (!context) return -EBADF;
1813
1814 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001815
1816 context->stop = true;
1817
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001818 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001819 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001820 sched_yield();
1821 }
1822
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001823 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001824 context->argv_hold.clear();
1825 context->args.clear();
1826 context->envp_hold.clear();
1827 context->envs.clear();
1828 if (context->fds[0] >= 0) {
1829 close(context->fds[0]);
1830 context->fds[0] = -1;
1831 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001832 android::close_output(context);
1833 android::close_error(context);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001834 if (context->fds[1] >= 0) {
1835 // NB: could be closed by the above fclose(s), ignore error.
1836 int save_errno = errno;
1837 close(context->fds[1]);
1838 errno = save_errno;
1839 context->fds[1] = -1;
1840 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001841
1842 android_closeEventTagMap(context->eventTagMap);
1843
Mark Salyzyn13e47352017-03-06 14:56:04 -08001844 // generic cleanup of devices list to handle all possible dirty cases
1845 log_device_t* dev;
1846 while (!!(dev = context->devices)) {
1847 struct logger_list* logger_list = dev->logger_list;
1848 if (logger_list) {
1849 for (log_device_t* d = dev; d; d = d->next) {
1850 if (d->logger_list == logger_list) d->logger_list = nullptr;
1851 }
1852 android_logger_list_free(logger_list);
1853 }
1854 context->devices = dev->next;
1855 delete dev;
1856 }
1857
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001858 int retval = context->retval;
1859
1860 free(context);
1861
1862 return retval;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001863}