blob: ff85f546a9e7a49e87f42b93ef147bfcb853acd4 [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"
Brendan Jackmana5141132017-10-31 12:44:54 +0000460 " where <expr> is a Perl-compatible regular expression\n"
Mark Salyzyn378f4742016-04-12 09:11:46 -0700461 // 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
Stefan Lafon701a0652017-08-24 20:14:06 -07001129 bool binary = !strcmp(name, "events") ||
1130 !strcmp(name, "security") ||
1131 !strcmp(name, "stats");
Mark Salyzyn45177732016-04-11 14:03:48 -07001132 log_device_t* d = new log_device_t(name, binary);
1133
Mark Salyzyn083b0372015-12-04 10:59:45 -08001134 if (dev) {
Mark Salyzyn45177732016-04-11 14:03:48 -07001135 dev->next = d;
1136 dev = d;
1137 } else {
Mark Salyzyn13e47352017-03-06 14:56:04 -08001138 context->devices = dev = d;
Mark Salyzyn083b0372015-12-04 10:59:45 -08001139 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001140 context->devCount++;
Joe Onorato6fa09a02010-02-26 10:04:23 -08001141 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001142 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001143
1144 case 'B':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001145 context->printBinary = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001146 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001147
1148 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -08001149 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001150 tail_time = lastLogTime(optctx.optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -07001151 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152 // redirect output to a file
Mark Salyzyne9ade172017-03-02 15:09:41 -08001153 context->outputFileName = optctx.optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001154 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001155
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001156 case 'r':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001157 if (!getSizeTArg(optctx.optarg, &context->logRotateSizeKBytes,
1158 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001159 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001160 "Invalid parameter \"%s\" to -r\n",
1161 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001162 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001163 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001164 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165
Mark Salyzyn1325ebf2016-06-07 13:03:10 -07001166 case 'n':
Mark Salyzyne9ade172017-03-02 15:09:41 -08001167 if (!getSizeTArg(optctx.optarg, &context->maxRotatedLogs, 1)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001168 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001169 "Invalid parameter \"%s\" to -n\n",
1170 optctx.optarg);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001171 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001172 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001173 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174
Mark Salyzynb45a1752017-02-28 09:20:31 -08001175 case 'v': {
Mark Salyzyne9ade172017-03-02 15:09:41 -08001176 if (!strcmp(optctx.optarg, "help") ||
1177 !strcmp(optctx.optarg, "--help")) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001178 show_format_help(context);
1179 context->retval = EXIT_SUCCESS;
1180 goto exit;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001181 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001182 std::unique_ptr<char, void (*)(void*)> formats(
1183 strdup(optctx.optarg), free);
1184 char* arg = formats.get();
Mark Salyzynb45a1752017-02-28 09:20:31 -08001185 char* sv = nullptr; // protect against -ENOMEM above
Mark Salyzyne9ade172017-03-02 15:09:41 -08001186 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1187 err = setLogFormat(context, arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001188 if (err < 0) {
1189 logcat_panic(context, HELP_FORMAT,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001190 "Invalid parameter \"%s\" to -v\n", arg);
Mark Salyzynb45a1752017-02-28 09:20:31 -08001191 goto exit;
1192 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001193 arg = nullptr;
Mark Salyzynb45a1752017-02-28 09:20:31 -08001194 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001195 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001196 } break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001197
1198 case 'Q':
bohu94aab862017-02-21 14:31:19 -08001199#define LOGCAT_FILTER "androidboot.logcat="
1200#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -08001201#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -08001202#define QEMU_PROPERTY "ro.kernel.qemu"
1203#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -08001204 // This is a *hidden* option used to start a version of logcat
1205 // in an emulated device only. It basically looks for
1206 // androidboot.logcat= on the kernel command line. If
1207 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -08001208 // run the program. The logcat output will go to consolepipe if
1209 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
1210 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001211 {
bohu94aab862017-02-21 14:31:19 -08001212 // if not in emulator, exit quietly
1213 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001214 context->retval = EXIT_SUCCESS;
1215 goto exit;
1216 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001217
bohu94aab862017-02-21 14:31:19 -08001218 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
1219 if (cmdline.empty()) {
1220 android::base::ReadFileToString("/proc/cmdline", &cmdline);
1221 }
1222
1223 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
1224 // if nothing found or invalid filters, exit quietly
1225 if (!logcatFilter) {
1226 context->retval = EXIT_SUCCESS;
1227 goto exit;
1228 }
1229
1230 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -08001231 const char* q = strpbrk(p, " \t\n\r");
1232 if (!q) q = p + strlen(p);
1233 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001234
bohu94aab862017-02-21 14:31:19 -08001235 // redirect our output to the emulator console pipe or console
1236 const char* consolePipe =
1237 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -08001238 const char* console =
1239 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001240
bohu94aab862017-02-21 14:31:19 -08001241 if (consolePipe) {
1242 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
1243 } else if (console) {
1244 p = console + strlen(CONSOLE_OPTION);
1245 } else {
1246 context->retval = EXIT_FAILURE;
1247 goto exit;
1248 }
1249
Mark Salyzynf3290292017-02-10 13:09:07 -08001250 q = strpbrk(p, " \t\n\r");
1251 int len = q ? q - p : strlen(p);
1252 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -08001253 std::string pipePurpose("pipe:logcat");
1254 if (consolePipe) {
1255 // example: "qemu_pipe,pipe:logcat"
1256 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
1257 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -07001258 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -08001259 if (pos != std::string::npos) {
1260 pipePurpose = devname.substr(pos + 1);
1261 devname = devname.substr(0, pos);
1262 }
1263 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001264 cmdline.erase();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001265
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001266 if (context->error) {
1267 fprintf(context->error, "logcat using %s\n",
1268 devname.c_str());
1269 }
Mark Salyzynf3290292017-02-10 13:09:07 -08001270
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001271 FILE* fp = fopen(devname.c_str(), "web");
Mark Salyzynf3290292017-02-10 13:09:07 -08001272 devname.erase();
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001273 if (!fp) break;
Mark Salyzynf3290292017-02-10 13:09:07 -08001274
bohu94aab862017-02-21 14:31:19 -08001275 if (consolePipe) {
1276 // need the trailing '\0'
1277 if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
1278 pipePurpose.size() + 1)) {
1279 fclose(fp);
1280 context->retval = EXIT_FAILURE;
1281 goto exit;
1282 }
1283 }
1284
Mark Salyzynf3290292017-02-10 13:09:07 -08001285 // close output and error channels, replace with console
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001286 android::close_output(context);
1287 android::close_error(context);
1288 context->stderr_stdout = true;
1289 context->output = fp;
Mark Salyzynf9dbdbc2017-02-21 14:45:58 -08001290 context->output_fd = fileno(fp);
1291 if (context->stderr_null) break;
1292 context->stderr_stdout = true;
1293 context->error = fp;
1294 context->error_fd = fileno(fp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001295 }
1296 break;
1297
Mark Salyzyn34facab2014-02-06 14:48:50 -08001298 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001299 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001300 break;
1301
Traian Schiau59763032015-04-10 15:51:39 +03001302 case ':':
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001303 logcat_panic(context, HELP_TRUE,
Mark Salyzyne9ade172017-03-02 15:09:41 -08001304 "Option -%c needs an argument\n", optctx.optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001305 goto exit;
Traian Schiau59763032015-04-10 15:51:39 +03001306
Mark Salyzyne74e51d2017-04-03 09:30:20 -07001307 case 'h':
1308 show_help(context);
1309 show_format_help(context);
1310 goto exit;
1311
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001312 default:
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001313 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
Mark Salyzyne9ade172017-03-02 15:09:41 -08001314 optctx.optopt);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001315 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001316 }
1317 }
1318
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001319 if (context->maxCount && got_t) {
1320 logcat_panic(context, HELP_TRUE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001321 "Cannot use -m (--max-count) and -t together\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001322 goto exit;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001323 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001324 if (context->printItAnyways && (!context->regex || !context->maxCount)) {
Mark Salyzync9202772016-03-30 09:38:31 -07001325 // One day it would be nice if --print -v color and --regex <expr>
1326 // could play with each other and show regex highlighted content.
Mark Salyzyn5f606602017-02-10 13:09:07 -08001327 // clang-format off
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001328 if (context->error) {
1329 fprintf(context->error, "WARNING: "
Mark Salyzync9202772016-03-30 09:38:31 -07001330 "--print ignored, to be used in combination with\n"
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001331 " "
Mark Salyzync9202772016-03-30 09:38:31 -07001332 "--regex <expr> and --max-count <N>\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001333 }
1334 context->printItAnyways = false;
Mark Salyzync9202772016-03-30 09:38:31 -07001335 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001336
Mark Salyzyn13e47352017-03-06 14:56:04 -08001337 if (!context->devices) {
1338 dev = context->devices = new log_device_t("main", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001339 context->devCount = 1;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001340 if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001341 dev = dev->next = new log_device_t("system", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001342 context->devCount++;
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -08001343 }
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001344 if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
Mark Salyzyn5f6738a2015-02-27 13:41:34 -08001345 dev = dev->next = new log_device_t("crash", false);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001346 context->devCount++;
Mark Salyzyn99f47a92014-04-07 14:58:08 -07001347 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001348 }
1349
Mark Salyzynde022a82017-03-01 08:30:06 -08001350 if (!!context->logRotateSizeKBytes && !context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001351 logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
1352 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001353 }
1354
Mark Salyzynde022a82017-03-01 08:30:06 -08001355 if (!!setId) {
1356 if (!context->outputFileName) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001357 logcat_panic(context, HELP_TRUE,
1358 "--id='%s' requires -f as well\n", setId);
1359 goto exit;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001360 }
1361
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001362 std::string file_name = android::base::StringPrintf(
1363 "%s.id", context->outputFileName);
Mark Salyzyn02687e72016-08-03 14:20:41 -07001364 std::string file;
1365 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001366 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
1367 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -08001368 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001369 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001370
Mark Salyzynde022a82017-03-01 08:30:06 -08001371 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001372 const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001373
Mark Salyzynde022a82017-03-01 08:30:06 -08001374 if (!!logFormat) {
Mark Salyzynb45a1752017-02-28 09:20:31 -08001375 std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
1376 free);
1377 char* sv = nullptr; // protect against -ENOMEM above
1378 char* arg = formats.get();
1379 while (!!(arg = strtok_r(arg, delimiters, &sv))) {
1380 err = setLogFormat(context, arg);
1381 // environment should not cause crash of logcat
1382 if ((err < 0) && context->error) {
1383 fprintf(context->error,
1384 "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
1385 }
1386 arg = nullptr;
1387 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001388 }
Mark Salyzynb45a1752017-02-28 09:20:31 -08001389 }
1390 if (!hasSetLogFormat) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001391 setLogFormat(context, "threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001392 }
1393 }
1394
Mark Salyzynf3290292017-02-10 13:09:07 -08001395 if (forceFilters.size()) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001396 err = android_log_addFilterString(context->logformat,
1397 forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001398 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001399 logcat_panic(context, HELP_FALSE,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001400 "Invalid filter expression in logcat args\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001401 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001402 }
Mark Salyzyne9ade172017-03-02 15:09:41 -08001403 } else if (argc == optctx.optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001404 // Add from environment variable
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001405 const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001406
Mark Salyzynde022a82017-03-01 08:30:06 -08001407 if (!!env_tags_orig) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001408 err = android_log_addFilterString(context->logformat,
1409 env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001410
Mark Salyzyn95132e92013-11-22 10:55:48 -08001411 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001412 logcat_panic(context, HELP_TRUE,
1413 "Invalid filter expression in ANDROID_LOG_TAGS\n");
1414 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001415 }
1416 }
1417 } else {
1418 // Add from commandline
Mark Salyzyne9ade172017-03-02 15:09:41 -08001419 for (int i = optctx.optind ; i < argc ; i++) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001420 // skip stderr redirections of _all_ kinds
1421 if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
Mark Salyzyne3d0c962017-02-17 13:15:51 -08001422 // skip stdout redirections of _all_ kinds
1423 if (argv[i][0] == '>') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001424
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001425 err = android_log_addFilterString(context->logformat, argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001426 if (err < 0) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001427 logcat_panic(context, HELP_TRUE,
1428 "Invalid filter expression '%s'\n", argv[i]);
1429 goto exit;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001430 }
1431 }
1432 }
1433
Mark Salyzyn13e47352017-03-06 14:56:04 -08001434 dev = context->devices;
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001435 if (tail_time != log_time::EPOCH) {
Kristian Monsen562e5132015-06-05 14:10:12 -07001436 logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001437 } else {
Kristian Monsen562e5132015-06-05 14:10:12 -07001438 logger_list = android_logger_list_alloc(mode, tail_lines, pid);
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001439 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001440 // We have three orthogonal actions below to clear, set log size and
1441 // get log size. All sharing the same iteration loop.
Joe Onorato6fa09a02010-02-26 10:04:23 -08001442 while (dev) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001443 dev->logger_list = logger_list;
1444 dev->logger = android_logger_open(logger_list,
1445 android_name_to_log_id(dev->device));
1446 if (!dev->logger) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001447 reportErrorName(&openDeviceFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001448 dev = dev->next;
1449 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001450 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001451
Mark Salyzyn02687e72016-08-03 14:20:41 -07001452 if (clearLog || setId) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001453 if (context->outputFileName) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001454 int maxRotationCountDigits =
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001455 (context->maxRotatedLogs > 0) ?
1456 (int)(floor(log10(context->maxRotatedLogs) + 1)) :
1457 0;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001458
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001459 for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001460 std::string file;
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001461
Mark Salyzynde022a82017-03-01 08:30:06 -08001462 if (!i) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001463 file = android::base::StringPrintf(
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001464 "%s", context->outputFileName);
1465 } else {
1466 file = android::base::StringPrintf("%s.%.*d",
1467 context->outputFileName, maxRotationCountDigits, i);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001468 }
1469
Mark Salyzynde022a82017-03-01 08:30:06 -08001470 if (!file.length()) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001471 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001472 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001473 break;
1474 }
1475
Mark Salyzyn5b1a5382016-08-03 14:20:41 -07001476 err = unlink(file.c_str());
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001477
Mark Salyzynde022a82017-03-01 08:30:06 -08001478 if (err < 0 && errno != ENOENT && !clearFail) {
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001479 perror("while clearing log files");
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001480 reportErrorName(&clearFail, dev->device, allSelected);
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001481 }
Mark Salyzynb7d059b2016-06-06 14:56:00 -07001482 }
1483 } else if (android_logger_clear(dev->logger)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001484 reportErrorName(&clearFail, dev->device, allSelected);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001485 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001486 }
1487
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001488 if (setLogSize) {
1489 if (android_logger_set_log_size(dev->logger, setLogSize)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001490 reportErrorName(&setSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001491 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001492 }
1493
Joe Onorato6fa09a02010-02-26 10:04:23 -08001494 if (getLogSize) {
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001495 long size = android_logger_get_log_size(dev->logger);
1496 long readable = android_logger_get_log_readable_size(dev->logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001497
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001498 if ((size < 0) || (readable < 0)) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -08001499 reportErrorName(&getSizeFail, dev->device, allSelected);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001500 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001501 std::string str = android::base::StringPrintf(
1502 "%s: ring buffer is %ld%sb (%ld%sb consumed),"
1503 " max entry is %db, max payload is %db\n",
1504 dev->device,
1505 value_of_size(size), multiplier_of_size(size),
1506 value_of_size(readable), multiplier_of_size(readable),
1507 (int)LOGGER_ENTRY_MAX_LEN,
1508 (int)LOGGER_ENTRY_MAX_PAYLOAD);
1509 TEMP_FAILURE_RETRY(write(context->output_fd,
1510 str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001511 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001512 }
1513
1514 dev = dev->next;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001515 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001516
1517 context->retval = EXIT_SUCCESS;
1518
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001519 // report any errors in the above loop and exit
1520 if (openDeviceFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001521 logcat_panic(context, HELP_FALSE,
1522 "Unable to open log device '%s'\n", openDeviceFail);
1523 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001524 }
1525 if (clearFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001526 logcat_panic(context, HELP_FALSE,
1527 "failed to clear the '%s' log\n", clearFail);
1528 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001529 }
1530 if (setSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001531 logcat_panic(context, HELP_FALSE,
1532 "failed to set the '%s' log size\n", setSizeFail);
1533 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001534 }
1535 if (getSizeFail) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001536 logcat_panic(context, HELP_FALSE,
1537 "failed to get the readable '%s' log size", getSizeFail);
1538 goto close;
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001539 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001540
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001541 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001542 size_t len = strlen(setPruneList);
Mark Salyzyn5f606602017-02-10 13:09:07 -08001543 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau59763032015-04-10 15:51:39 +03001544 size_t bLen = len + 32;
Mark Salyzynde022a82017-03-01 08:30:06 -08001545 char* buf = nullptr;
Traian Schiau59763032015-04-10 15:51:39 +03001546 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1547 buf[len] = '\0';
1548 if (android_logger_set_prune_list(logger_list, buf, bLen)) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001549 logcat_panic(context, HELP_FALSE,
1550 "failed to set the prune list");
Traian Schiau59763032015-04-10 15:51:39 +03001551 }
1552 free(buf);
1553 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001554 logcat_panic(context, HELP_FALSE,
1555 "failed to set the prune list (alloc)");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001556 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001557 goto close;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001558 }
1559
Mark Salyzyn1c950472014-04-01 17:19:47 -07001560 if (printStatistics || getPruneList) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001561 size_t len = 8192;
Mark Salyzyn5f606602017-02-10 13:09:07 -08001562 char* buf;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001563
Mark Salyzyn5f606602017-02-10 13:09:07 -08001564 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzynde022a82017-03-01 08:30:06 -08001565 delete[] buf, buf = nullptr, --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001566 if (getPruneList) {
1567 android_logger_get_prune_list(logger_list, buf, len);
1568 } else {
1569 android_logger_get_statistics(logger_list, buf, len);
1570 }
Mark Salyzyn5f606602017-02-10 13:09:07 -08001571 buf[len - 1] = '\0';
Traian Schiau59763032015-04-10 15:51:39 +03001572 if (atol(buf) < 3) {
Mark Salyzyn5f606602017-02-10 13:09:07 -08001573 delete[] buf;
Mark Salyzynde022a82017-03-01 08:30:06 -08001574 buf = nullptr;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001575 break;
1576 }
Traian Schiau59763032015-04-10 15:51:39 +03001577 size_t ret = atol(buf) + 1;
1578 if (ret <= len) {
1579 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001580 break;
1581 }
Traian Schiau59763032015-04-10 15:51:39 +03001582 len = ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001583 }
1584
1585 if (!buf) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001586 logcat_panic(context, HELP_FALSE, "failed to read data");
1587 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001588 }
1589
1590 // remove trailing FF
Mark Salyzyn5f606602017-02-10 13:09:07 -08001591 char* cp = buf + len - 1;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001592 *cp = '\0';
1593 bool truncated = *--cp != '\f';
Mark Salyzynde022a82017-03-01 08:30:06 -08001594 if (!truncated) *cp = '\0';
Mark Salyzyn34facab2014-02-06 14:48:50 -08001595
1596 // squash out the byte count
1597 cp = buf;
1598 if (!truncated) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001599 while (isdigit(*cp)) ++cp;
1600 if (*cp == '\n') ++cp;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001601 }
1602
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001603 len = strlen(cp);
1604 TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
Mark Salyzyn5f606602017-02-10 13:09:07 -08001605 delete[] buf;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001606 goto close;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001607 }
1608
Mark Salyzynde022a82017-03-01 08:30:06 -08001609 if (getLogSize || setLogSize || clearLog) goto close;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001610
Mark Salyzynde022a82017-03-01 08:30:06 -08001611 setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001612 if (context->stop) goto close;
Mark Salyzyn02687e72016-08-03 14:20:41 -07001613
Mark Salyzyn5f606602017-02-10 13:09:07 -08001614 // LOG_EVENT_INT(10, 12345);
1615 // LOG_EVENT_LONG(11, 0x1122334455667788LL);
1616 // LOG_EVENT_STRING(0, "whassup, doc?");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001617
Mark Salyzynde022a82017-03-01 08:30:06 -08001618 dev = nullptr;
Casey Dahlin6ac498d2016-03-17 14:04:52 -07001619
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001620 while (!context->stop &&
1621 (!context->maxCount || (context->printCount < context->maxCount))) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001622 struct log_msg log_msg;
1623 int ret = android_logger_list_read(logger_list, &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001624 if (!ret) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001625 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1626 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001627 }
1628
1629 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001630 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001631
1632 if (ret == -EIO) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001633 logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
1634 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001635 }
1636 if (ret == -EINVAL) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001637 logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
1638 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001639 }
Luca Stefani08705142017-07-08 17:48:00 +02001640 logcat_panic(context, HELP_FALSE, "logcat read failure\n");
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001641 break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001642 }
1643
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001644 log_device_t* d;
Mark Salyzyn13e47352017-03-06 14:56:04 -08001645 for (d = context->devices; d; d = d->next) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001646 if (android_name_to_log_id(d->device) == log_msg.id()) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001647 }
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001648 if (!d) {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001649 context->devCount = 2; // set to Multiple
Mark Salyzyn9421b0c2015-02-26 14:33:35 -08001650 d = &unexpected;
1651 d->binary = log_msg.id() == LOG_ID_EVENTS;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001652 }
1653
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001654 if (dev != d) {
1655 dev = d;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001656 maybePrintStart(context, dev, printDividers);
1657 if (context->stop) break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -08001658 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001659 if (context->printBinary) {
1660 printBinary(context, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001661 } else {
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001662 processBuffer(context, dev, &log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001663 }
1664 }
1665
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001666close:
Mark Salyzyn13e47352017-03-06 14:56:04 -08001667 // Short and sweet. Implemented generic version in android_logcat_destroy.
1668 while (!!(dev = context->devices)) {
1669 context->devices = dev->next;
1670 delete dev;
1671 }
Mark Salyzyn95132e92013-11-22 10:55:48 -08001672 android_logger_list_free(logger_list);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001673
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001674exit:
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001675 // close write end of pipe to help things along
1676 if (context->output_fd == context->fds[1]) {
1677 android::close_output(context);
1678 }
1679 if (context->error_fd == context->fds[1]) {
1680 android::close_error(context);
1681 }
1682 if (context->fds[1] >= 0) {
1683 // NB: should be closed by the above
1684 int save_errno = errno;
1685 close(context->fds[1]);
1686 errno = save_errno;
1687 context->fds[1] = -1;
1688 }
1689 context->thread_stopped = true;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001690 return context->retval;
1691}
1692
1693// Can block
1694int android_logcat_run_command(android_logcat_context ctx,
1695 int output, int error,
1696 int argc, char* const* argv,
1697 char* const* envp) {
1698 android_logcat_context_internal* context = ctx;
1699
1700 context->output_fd = output;
1701 context->error_fd = error;
1702 context->argc = argc;
1703 context->argv = argv;
1704 context->envp = envp;
1705 context->stop = false;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001706 context->thread_stopped = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001707 return __logcat(context);
1708}
1709
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001710// starts a thread, opens a pipe, returns reading end.
1711int android_logcat_run_command_thread(android_logcat_context ctx,
1712 int argc, char* const* argv,
1713 char* const* envp) {
1714 android_logcat_context_internal* context = ctx;
1715
1716 int save_errno = EBUSY;
Mark Salyzynde022a82017-03-01 08:30:06 -08001717 if ((context->fds[0] >= 0) || (context->fds[1] >= 0)) goto exit;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001718
1719 if (pipe(context->fds) < 0) {
1720 save_errno = errno;
1721 goto exit;
1722 }
1723
1724 pthread_attr_t attr;
1725 if (pthread_attr_init(&attr)) {
1726 save_errno = errno;
1727 goto close_exit;
1728 }
1729
1730 struct sched_param param;
1731 memset(&param, 0, sizeof(param));
1732 pthread_attr_setschedparam(&attr, &param);
1733 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1734 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
Mark Salyzyn210e43c2017-08-04 16:28:47 -07001735 save_errno = errno;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001736 goto pthread_attr_exit;
1737 }
1738
1739 context->stop = false;
1740 context->thread_stopped = false;
1741 context->output_fd = context->fds[1];
1742 // save off arguments so they remain while thread is active.
1743 for (int i = 0; i < argc; ++i) {
1744 context->args.push_back(std::string(argv[i]));
1745 }
1746 // save off environment so they remain while thread is active.
1747 if (envp) for (size_t i = 0; envp[i]; ++i) {
1748 context->envs.push_back(std::string(envp[i]));
1749 }
1750
1751 for (auto& str : context->args) {
1752 context->argv_hold.push_back(str.c_str());
1753 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001754 context->argv_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001755 for (auto& str : context->envs) {
1756 context->envp_hold.push_back(str.c_str());
1757 }
Mark Salyzynde022a82017-03-01 08:30:06 -08001758 context->envp_hold.push_back(nullptr);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001759
1760 context->argc = context->argv_hold.size() - 1;
1761 context->argv = (char* const*)&context->argv_hold[0];
1762 context->envp = (char* const*)&context->envp_hold[0];
1763
1764#ifdef DEBUG
1765 fprintf(stderr, "argv[%d] = {", context->argc);
1766 for (auto str : context->argv_hold) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001767 fprintf(stderr, " \"%s\"", str ?: "nullptr");
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001768 }
1769 fprintf(stderr, " }\n");
1770 fflush(stderr);
1771#endif
1772 context->retval = EXIT_SUCCESS;
1773 if (pthread_create(&context->thr, &attr,
1774 (void*(*)(void*))__logcat, context)) {
Mark Salyzyn210e43c2017-08-04 16:28:47 -07001775 save_errno = errno;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001776 goto argv_exit;
1777 }
1778 pthread_attr_destroy(&attr);
1779
1780 return context->fds[0];
1781
1782argv_exit:
1783 context->argv_hold.clear();
1784 context->args.clear();
1785 context->envp_hold.clear();
1786 context->envs.clear();
1787pthread_attr_exit:
1788 pthread_attr_destroy(&attr);
1789close_exit:
1790 close(context->fds[0]);
1791 context->fds[0] = -1;
1792 close(context->fds[1]);
1793 context->fds[1] = -1;
1794exit:
1795 errno = save_errno;
1796 context->stop = true;
1797 context->thread_stopped = true;
1798 context->retval = EXIT_FAILURE;
1799 return -1;
1800}
1801
1802// test if the thread is still doing 'stuff'
1803int android_logcat_run_command_thread_running(android_logcat_context ctx) {
1804 android_logcat_context_internal* context = ctx;
1805
1806 return context->thread_stopped == false;
1807}
1808
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001809// Finished with context
1810int android_logcat_destroy(android_logcat_context* ctx) {
1811 android_logcat_context_internal* context = *ctx;
1812
Mark Salyzynde022a82017-03-01 08:30:06 -08001813 if (!context) return -EBADF;
1814
1815 *ctx = nullptr;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001816
1817 context->stop = true;
1818
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001819 while (context->thread_stopped == false) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001820 // Makes me sad, replace thread_stopped with semaphore. Short lived.
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001821 sched_yield();
1822 }
1823
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001824 delete context->regex;
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001825 context->argv_hold.clear();
1826 context->args.clear();
1827 context->envp_hold.clear();
1828 context->envs.clear();
1829 if (context->fds[0] >= 0) {
1830 close(context->fds[0]);
1831 context->fds[0] = -1;
1832 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001833 android::close_output(context);
1834 android::close_error(context);
Josh Gao03d055d2017-10-18 15:42:00 -07001835
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001836 if (context->fds[1] >= 0) {
Josh Gao03d055d2017-10-18 15:42:00 -07001837 // NB: this should be closed by close_output, but just in case...
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001838 close(context->fds[1]);
Mark Salyzyn1d6928b2017-02-10 13:09:07 -08001839 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}