blob: 831b4e34395e7e0370d614b363b55693d4ed7eb5 [file] [log] [blame]
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001/*
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08002 * Copyright (C) 2006-2017 The Android Open Source Project
Mark Salyzynd8b454f2017-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 Project190995d2009-03-03 19:32:55 -080016
Mark Salyzyn12af9652013-12-13 11:10:11 -080017#include <ctype.h>
Mark Salyzyn3fa657e2015-05-27 07:39:56 -070018#include <dirent.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080019#include <errno.h>
Tom Cherry96840882019-12-06 10:25:37 -080020#include <error.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080021#include <fcntl.h>
Elliott Hughes442d8582018-06-15 15:16:20 -070022#include <getopt.h>
Aristidis Papaioannouf7cc6622014-10-16 22:19:55 -070023#include <math.h>
Mark Salyzyn38fc72c2015-06-02 07:57:16 -070024#include <sched.h>
Mark Salyzyn38fc72c2015-06-02 07:57:16 -070025#include <stdarg.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080026#include <stdio.h>
27#include <stdlib.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080028#include <string.h>
Traian Schiau9f978602015-04-10 15:51:39 +030029#include <sys/cdefs.h>
Jaegeuk Kim64352f22019-07-04 18:09:38 -070030#include <sys/ioctl.h>
Riley Andrews53fe1b02015-06-08 23:36:34 -070031#include <sys/resource.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080032#include <sys/stat.h>
Mark Salyzyn3fa657e2015-05-27 07:39:56 -070033#include <sys/types.h>
Mark Salyzyn38fc72c2015-06-02 07:57:16 -070034#include <time.h>
35#include <unistd.h>
Mark Salyzyn12af9652013-12-13 11:10:11 -080036
Mark Salyzyn3fa657e2015-05-27 07:39:56 -070037#include <memory>
Elliott Hughesaccc1012019-08-08 08:53:59 -070038#include <regex>
Mark Salyzyn3fa657e2015-05-27 07:39:56 -070039#include <string>
Wei Wang8b584172018-09-05 11:05:57 -070040#include <utility>
Mark Salyzyna511fef2017-02-10 13:09:07 -080041#include <vector>
Mark Salyzyn3fa657e2015-05-27 07:39:56 -070042
Elliott Hughes0a7adf02015-12-04 22:00:26 -080043#include <android-base/file.h>
Tom Cherryb1cf4282019-10-24 17:35:26 -070044#include <android-base/macros.h>
Tom Cherryfb1373a2019-10-29 07:05:24 -070045#include <android-base/parseint.h>
bohu25889532017-02-21 14:31:19 -080046#include <android-base/properties.h>
Mark Salyzyn2a1233e2016-08-03 14:20:41 -070047#include <android-base/stringprintf.h>
Elliott Hughes0a7adf02015-12-04 22:00:26 -080048#include <android-base/strings.h>
Tom Cherryb1cf4282019-10-24 17:35:26 -070049#include <android-base/unique_fd.h>
Tom Cherryfb1373a2019-10-29 07:05:24 -070050#include <android/log.h>
Mark Salyzyn38fc72c2015-06-02 07:57:16 -070051#include <log/event_tag_map.h>
Tom Cherryfb1373a2019-10-29 07:05:24 -070052#include <log/log_id.h>
Colin Crosse355ded2013-07-23 16:59:20 -070053#include <log/logprint.h>
Mark Salyzyn8b8bfd22016-09-30 13:30:33 -070054#include <private/android_logger.h>
Suren Baghdasaryan3e671a52019-01-25 05:32:52 +000055#include <processgroup/sched_policy.h>
Elliott Hughes411f8632016-02-17 11:58:01 -080056#include <system/thread_defs.h>
The Android Open Source Project190995d2009-03-03 19:32:55 -080057
The Android Open Source Project190995d2009-03-03 19:32:55 -080058#define DEFAULT_MAX_ROTATED_LOGS 4
59
Tom Cherryfb1373a2019-10-29 07:05:24 -070060using android::base::Join;
61using android::base::ParseByteCount;
62using android::base::ParseUint;
63using android::base::Split;
Tom Cherryb1cf4282019-10-24 17:35:26 -070064using android::base::StringPrintf;
65
Tom Cherryb1cf4282019-10-24 17:35:26 -070066class Logcat {
67 public:
Tom Cherryb1cf4282019-10-24 17:35:26 -070068 int Run(int argc, char** argv);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -080069
Tom Cherryb1cf4282019-10-24 17:35:26 -070070 private:
71 void RotateLogs();
Tom Cherryfb1373a2019-10-29 07:05:24 -070072 void ProcessBuffer(struct log_msg* buf);
73 void PrintDividers(log_id_t log_id, bool print_dividers);
Tom Cherryb1cf4282019-10-24 17:35:26 -070074 void SetupOutputAndSchedulingPolicy(bool blocking);
75 int SetLogFormat(const char* format_string);
76
Tom Cherryfb1373a2019-10-29 07:05:24 -070077 // Used for all options
Tom Cherryb1cf4282019-10-24 17:35:26 -070078 android::base::unique_fd output_fd_{dup(STDOUT_FILENO)};
79 std::unique_ptr<AndroidLogFormat, decltype(&android_log_format_free)> logformat_{
80 android_log_format_new(), &android_log_format_free};
Tom Cherryfb1373a2019-10-29 07:05:24 -070081
82 // For logging to a file and log rotation
Tom Cherryb1cf4282019-10-24 17:35:26 -070083 const char* output_file_name_ = nullptr;
Tom Cherryfb1373a2019-10-29 07:05:24 -070084 size_t log_rotate_size_kb_ = 0; // 0 means "no log rotation"
85 size_t max_rotated_logs_ = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded"
Tom Cherryb1cf4282019-10-24 17:35:26 -070086 size_t out_byte_count_ = 0;
Tom Cherryfb1373a2019-10-29 07:05:24 -070087
88 // For binary log buffers
Tom Cherryb1cf4282019-10-24 17:35:26 -070089 int print_binary_ = 0;
Tom Cherryb1cf4282019-10-24 17:35:26 -070090 std::unique_ptr<EventTagMap, decltype(&android_closeEventTagMap)> event_tag_map_{
91 nullptr, &android_closeEventTagMap};
Tom Cherryb1cf4282019-10-24 17:35:26 -070092 bool has_opened_event_tag_map_ = false;
Tom Cherryfb1373a2019-10-29 07:05:24 -070093
94 // For the related --regex, --max-count, --print
95 std::unique_ptr<std::regex> regex_;
96 size_t max_count_ = 0; // 0 means "infinite"
97 size_t print_count_ = 0;
98 bool print_it_anyways_ = false;
99
100 // For PrintDividers()
101 log_id_t last_printed_id_ = LOG_ID_MAX;
102 bool printed_start_[LOG_ID_MAX] = {};
103
104 bool debug_ = false;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800105};
106
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800107// logd prefixes records with a length field
The Android Open Source Project190995d2009-03-03 19:32:55 -0800108#define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
109
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800110enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
Mark Salyzyn604679a2016-10-18 11:30:11 -0700111
Jaegeuk Kim64352f22019-07-04 18:09:38 -0700112#ifndef F2FS_IOC_SET_PIN_FILE
113#define F2FS_IOCTL_MAGIC 0xf5
114#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
115#endif
116
117static int openLogFile(const char* pathname, size_t sizeKB) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700118 int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
Jaegeuk Kim64352f22019-07-04 18:09:38 -0700119 if (fd < 0) {
120 return fd;
121 }
122
123 // no need to check errors
124 __u32 set = 1;
125 ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
126 fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, (sizeKB << 10));
127 return fd;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800128}
129
Tom Cherryb1cf4282019-10-24 17:35:26 -0700130void Logcat::RotateLogs() {
The Android Open Source Project190995d2009-03-03 19:32:55 -0800131 // Can't rotate logs if we're not outputting to a file
Tom Cherryb1cf4282019-10-24 17:35:26 -0700132 if (!output_file_name_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800133
Tom Cherryb1cf4282019-10-24 17:35:26 -0700134 output_fd_.reset();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800135
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800136 // Compute the maximum number of digits needed to count up to
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800137 // maxRotatedLogs in decimal. eg:
138 // maxRotatedLogs == 30
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800139 // -> log10(30) == 1.477
140 // -> maxRotationCountDigits == 2
Tom Cherryb1cf4282019-10-24 17:35:26 -0700141 int max_rotation_count_digits =
142 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
Aristidis Papaioannouf7cc6622014-10-16 22:19:55 -0700143
Tom Cherryb1cf4282019-10-24 17:35:26 -0700144 for (int i = max_rotated_logs_; i > 0; i--) {
145 std::string file1 =
146 StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800147
Mark Salyzyn2a1233e2016-08-03 14:20:41 -0700148 std::string file0;
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800149 if (!(i - 1)) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700150 file0 = output_file_name_;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800151 } else {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700152 file0 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i - 1);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800153 }
154
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800155 if (!file0.length() || !file1.length()) {
Traian Schiau9f978602015-04-10 15:51:39 +0300156 perror("while rotating log files");
157 break;
158 }
159
Tom Cherryb1cf4282019-10-24 17:35:26 -0700160 int err = rename(file0.c_str(), file1.c_str());
The Android Open Source Project190995d2009-03-03 19:32:55 -0800161
162 if (err < 0 && errno != ENOENT) {
163 perror("while rotating log files");
164 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800165 }
166
Tom Cherryb1cf4282019-10-24 17:35:26 -0700167 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
The Android Open Source Project190995d2009-03-03 19:32:55 -0800168
Tom Cherryb1cf4282019-10-24 17:35:26 -0700169 if (!output_fd_.ok()) {
Tom Cherry96840882019-12-06 10:25:37 -0800170 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyn7e0bbab2017-02-17 13:15:51 -0800171 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800172
Tom Cherryb1cf4282019-10-24 17:35:26 -0700173 out_byte_count_ = 0;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800174}
175
Tom Cherryfb1373a2019-10-29 07:05:24 -0700176void Logcat::ProcessBuffer(struct log_msg* buf) {
Mathias Agopianb9218fb2010-03-17 16:10:26 -0700177 int bytesWritten = 0;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800178 int err;
179 AndroidLogEntry entry;
180 char binaryMsgBuf[1024];
181
Tom Cherryfb1373a2019-10-29 07:05:24 -0700182 bool is_binary =
183 buf->id() == LOG_ID_EVENTS || buf->id() == LOG_ID_STATS || buf->id() == LOG_ID_SECURITY;
184
185 if (is_binary) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700186 if (!event_tag_map_ && !has_opened_event_tag_map_) {
187 event_tag_map_.reset(android_openEventTagMap(nullptr));
188 has_opened_event_tag_map_ = true;
Mark Salyzyn784d64f2015-02-26 14:33:35 -0800189 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700190 err = android_log_processBinaryLogBuffer(&buf->entry, &entry, event_tag_map_.get(),
Tom Cherry47856dd2019-10-15 16:53:11 -0700191 binaryMsgBuf, sizeof(binaryMsgBuf));
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800192 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Project190995d2009-03-03 19:32:55 -0800193 // entry.priority, entry.messageLen, entry.message);
194 } else {
Tom Cherry47856dd2019-10-15 16:53:11 -0700195 err = android_log_processLogBuffer(&buf->entry, &entry);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800196 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700197 if (err < 0 && !debug_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800198
Tom Cherryb1cf4282019-10-24 17:35:26 -0700199 if (android_log_shouldPrintLine(logformat_.get(), std::string(entry.tag, entry.tagLen).c_str(),
200 entry.priority)) {
201 bool match = !regex_ ||
202 std::regex_search(entry.message, entry.message + entry.messageLen, *regex_);
Joe Onorato400da4a2010-03-01 09:11:54 -0800203
Tom Cherryb1cf4282019-10-24 17:35:26 -0700204 print_count_ += match;
205 if (match || print_it_anyways_) {
206 bytesWritten = android_log_printLogLine(logformat_.get(), output_fd_.get(), &entry);
Casey Dahlined028f92016-03-17 14:04:52 -0700207
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700208 if (bytesWritten < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800209 error(EXIT_FAILURE, 0, "Output error.");
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700210 }
Joe Onorato400da4a2010-03-01 09:11:54 -0800211 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800212 }
213
Tom Cherryb1cf4282019-10-24 17:35:26 -0700214 out_byte_count_ += bytesWritten;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800215
Tom Cherryb1cf4282019-10-24 17:35:26 -0700216 if (log_rotate_size_kb_ > 0 && (out_byte_count_ / 1024) >= log_rotate_size_kb_) {
217 RotateLogs();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800218 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800219}
220
Tom Cherryfb1373a2019-10-29 07:05:24 -0700221void Logcat::PrintDividers(log_id_t log_id, bool print_dividers) {
222 if (log_id == last_printed_id_ || print_binary_) {
223 return;
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800224 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700225 if (!printed_start_[log_id] || print_dividers) {
226 if (dprintf(output_fd_.get(), "--------- %s %s\n",
227 printed_start_[log_id] ? "switch to" : "beginning of",
228 android_log_id_to_name(log_id)) < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800229 error(EXIT_FAILURE, errno, "Output error");
Tom Cherryfb1373a2019-10-29 07:05:24 -0700230 }
231 }
232 last_printed_id_ = log_id;
233 printed_start_[log_id] = true;
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800234}
235
Tom Cherryb1cf4282019-10-24 17:35:26 -0700236void Logcat::SetupOutputAndSchedulingPolicy(bool blocking) {
237 if (!output_file_name_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800238
Mark Salyzyn60231da2016-08-04 07:53:52 -0700239 if (blocking) {
240 // Lower priority and set to batch scheduling if we are saving
241 // the logs into files and taking continuous content.
Tom Cherryb1cf4282019-10-24 17:35:26 -0700242 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
243 fprintf(stderr, "failed to set background scheduling policy\n");
Mark Salyzyn38fc72c2015-06-02 07:57:16 -0700244 }
245
Tom Cherryb1cf4282019-10-24 17:35:26 -0700246 struct sched_param param = {};
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800247 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn38fc72c2015-06-02 07:57:16 -0700248 fprintf(stderr, "failed to set to batch scheduler\n");
249 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800250
Tom Cherryb1cf4282019-10-24 17:35:26 -0700251 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
252 fprintf(stderr, "failed set to priority\n");
Riley Andrews53fe1b02015-06-08 23:36:34 -0700253 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800254 }
Mark Salyzyn60231da2016-08-04 07:53:52 -0700255
Tom Cherryb1cf4282019-10-24 17:35:26 -0700256 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
Mark Salyzyn60231da2016-08-04 07:53:52 -0700257
Tom Cherryb1cf4282019-10-24 17:35:26 -0700258 if (!output_fd_.ok()) {
Tom Cherry96840882019-12-06 10:25:37 -0800259 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700260 }
261
262 struct stat statbuf;
Tom Cherryb1cf4282019-10-24 17:35:26 -0700263 if (fstat(output_fd_.get(), &statbuf) == -1) {
Tom Cherry96840882019-12-06 10:25:37 -0800264 error(EXIT_FAILURE, errno, "Couldn't get output file stat");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700265 }
266
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800267 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800268 error(EXIT_FAILURE, 0, "Invalid output file stat.");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700269 }
270
Tom Cherryb1cf4282019-10-24 17:35:26 -0700271 out_byte_count_ = statbuf.st_size;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800272}
273
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800274// clang-format off
Tom Cherryb1cf4282019-10-24 17:35:26 -0700275static void show_help() {
276 const char* cmd = getprogname();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800277
Tom Cherryb1cf4282019-10-24 17:35:26 -0700278 fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800279
Tom Cherrya59bde42019-11-21 10:31:06 -0800280 fprintf(stderr, R"init(
281General options:
282 -b, --buffer=<buffer> Request alternate ring buffer(s):
283 main system radio events crash default all
284 Additionally, 'kernel' for userdebug and eng builds, and
285 'security' for Device Owner installations.
286 Multiple -b parameters or comma separated list of buffers are
287 allowed. Buffers are interleaved.
288 Default -b main,system,crash,kernel.
289 -L, --last Dump logs from prior to last reboot from pstore.
290 -c, --clear Clear (flush) the entire log and exit.
291 if -f is specified, clear the specified file and its related rotated
292 log files instead.
293 if -L is specified, clear pstore log instead.
294 -d Dump the log and then exit (don't block).
295 --pid=<pid> Only print logs from the given pid.
296 --wrap Sleep for 2 hours or when buffer about to wrap whichever
297 comes first. Improves efficiency of polling by providing
298 an about-to-wrap wakeup.
299
300Formatting:
301 -v, --format=<format> Sets log print format verb and adverbs, where <format> is one of:
302 brief help long process raw tag thread threadtime time
303 Modifying adverbs can be added:
304 color descriptive epoch monotonic printable uid usec UTC year zone
305 Multiple -v parameters or comma separated list of format and format
306 modifiers are allowed.
307 -D, --dividers Print dividers between each log buffer.
308 -B, --binary Output the log in binary.
309
310Outfile files:
311 -f, --file=<file> Log to file instead of stdout.
312 -r, --rotate-kbytes=<n> Rotate log every <n> kbytes. Requires -f option.
313 -n, --rotate-count=<count> Sets max number of rotated logs to <count>, default 4.
314 --id=<id> If the signature <id> for logging to file changes, then clear the
315 associated files and continue.
316
317Logd control:
318 These options send a control message to the logd daemon on device, print its return message if
319 applicable, then exit. They are incompatible with -L, as these attributes do not apply to pstore.
320 -g, --buffer-size Get the size of the ring buffers within logd.
321 -G, --buffer-size=<size> Set size of a ring buffer in logd. May suffix with K or M.
322 This can individually control each buffer's size with -b.
323 -S, --statistics Output statistics.
324 --pid can be used to provide pid specific stats.
325 -p, --prune Print prune white and ~black list. Service is specified as UID,
326 UID/PID or /PID. Weighed for quicker pruning if prefix with ~,
327 otherwise weighed for longevity if unadorned. All other pruning
328 activity is oldest first. Special case ~! represents an automatic
329 quicker pruning for the noisiest UID as determined by the current
330 statistics.
331 -P, --prune='<list> ...' Set prune white and ~black list, using same format as listed above.
332 Must be quoted.
333
334Filtering:
335 -s Set default filter to silent. Equivalent to filterspec '*:S'
336 -e, --regex=<expr> Only print lines where the log message matches <expr> where <expr> is
337 an ECMAScript regular expression.
338 -m, --max-count=<count> Quit after printing <count> lines. This is meant to be paired with
339 --regex, but will work on its own.
340 --print This option is only applicable when --regex is set and only useful if
341 --max-count is also provided.
342 With --print, logcat will print all messages even if they do not
343 match the regex. Logcat will quit after printing the max-count number
344 of lines that match the regex.
345 -t <count> Print only the most recent <count> lines (implies -d).
346 -t '<time>' Print the lines since specified time (implies -d).
347 -T <count> Print only the most recent <count> lines (does not imply -d).
348 -T '<time>' Print the lines since specified time (not imply -d).
349 count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'
350 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format.
351)init");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800352
Tom Cherryb1cf4282019-10-24 17:35:26 -0700353 fprintf(stderr, "\nfilterspecs are a series of \n"
The Android Open Source Project190995d2009-03-03 19:32:55 -0800354 " <tag>[:priority]\n\n"
355 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzyn438b8222015-03-09 09:32:56 -0700356 " V Verbose (default for <tag>)\n"
357 " D Debug (default for '*')\n"
The Android Open Source Project190995d2009-03-03 19:32:55 -0800358 " I Info\n"
359 " W Warn\n"
360 " E Error\n"
361 " F Fatal\n"
Mark Salyzyn438b8222015-03-09 09:32:56 -0700362 " S Silent (suppress all output)\n"
363 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
364 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
365 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
366 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
367 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyndd569af2014-09-16 09:15:15 -0700368 "or defaults to \"threadtime\"\n\n");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800369}
370
Tom Cherryb1cf4282019-10-24 17:35:26 -0700371static void show_format_help() {
372 fprintf(stderr,
Mark Salyzyn604679a2016-10-18 11:30:11 -0700373 "-v <format>, --format=<format> options:\n"
374 " Sets log print format verb and adverbs, where <format> is:\n"
375 " brief long process raw tag thread threadtime time\n"
376 " and individually flagged modifying adverbs can be added:\n"
377 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
378 "\nSingle format verbs:\n"
379 " brief — Display priority/tag and PID of the process issuing the message.\n"
380 " long — Display all metadata fields, separate messages with blank lines.\n"
381 " process — Display PID only.\n"
382 " raw — Display the raw log message, with no other metadata fields.\n"
383 " tag — Display the priority/tag only.\n"
Mark Salyzyn56ff3fa2017-05-15 13:40:33 -0700384 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn604679a2016-10-18 11:30:11 -0700385 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
386 " and TID of the thread issuing the message. (the default format).\n"
387 " time — Display the date, invocation time, priority/tag, and PID of the\n"
388 " process issuing the message.\n"
389 "\nAdverb modifiers can be used in combination:\n"
390 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
391 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
392 " descriptive — events logs only, descriptions from event-log-tags database.\n"
393 " epoch — Display time as seconds since Jan 1 1970.\n"
394 " monotonic — Display time as cpu seconds since last boot.\n"
395 " printable — Ensure that any binary logging content is escaped.\n"
396 " uid — If permitted, display the UID or Android ID of logged process.\n"
397 " usec — Display time down the microsecond precision.\n"
398 " UTC — Display time as UTC.\n"
399 " year — Add the year to the displayed time.\n"
400 " zone — Add the local timezone to the displayed time.\n"
401 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
402 );
403}
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800404// clang-format on
Mark Salyzyn604679a2016-10-18 11:30:11 -0700405
Tom Cherryb1cf4282019-10-24 17:35:26 -0700406int Logcat::SetLogFormat(const char* format_string) {
407 AndroidLogPrintFormat format = android_log_formatFromString(format_string);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800408
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800409 // invalid string?
410 if (format == FORMAT_OFF) return -1;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800411
Tom Cherryb1cf4282019-10-24 17:35:26 -0700412 return android_log_setPrintFormat(logformat_.get(), format);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800413}
414
Wei Wang8b584172018-09-05 11:05:57 -0700415static std::pair<unsigned long, const char*> format_of_size(unsigned long value) {
416 static const char multipliers[][3] = {{""}, {"Ki"}, {"Mi"}, {"Gi"}};
417 size_t i;
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700418 for (i = 0;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800419 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
420 value /= 1024, ++i)
421 ;
Wei Wang8b584172018-09-05 11:05:57 -0700422 return std::make_pair(value, multipliers[i]);
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700423}
424
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800425static char* parseTime(log_time& t, const char* cp) {
426 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800427 if (ep) return ep;
Mark Salyzyn4d0473f2015-08-31 15:53:41 -0700428 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800429 if (ep) return ep;
Mark Salyzyn4d0473f2015-08-31 15:53:41 -0700430 return t.strptime(cp, "%s.%q");
Mark Salyzyneb0456d2015-08-31 08:01:33 -0700431}
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700432
Mark Salyzyn05b88232016-08-04 07:43:46 -0700433// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800434static log_time lastLogTime(const char* outputFileName) {
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700435 log_time retval(log_time::EPOCH);
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800436 if (!outputFileName) return retval;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700437
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700438 std::string directory;
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800439 const char* file = strrchr(outputFileName, '/');
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700440 if (!file) {
441 directory = ".";
442 file = outputFileName;
443 } else {
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800444 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700445 ++file;
446 }
Mark Salyzyn17475732016-04-01 07:52:20 -0700447
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800448 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
449 closedir);
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800450 if (!dir.get()) return retval;
Mark Salyzyn17475732016-04-01 07:52:20 -0700451
Mark Salyzyn05b88232016-08-04 07:43:46 -0700452 log_time now(android_log_clockid());
Mark Salyzyn17475732016-04-01 07:52:20 -0700453
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700454 size_t len = strlen(file);
455 log_time modulo(0, NS_PER_SEC);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800456 struct dirent* dp;
Mark Salyzyn17475732016-04-01 07:52:20 -0700457
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800458 while (!!(dp = readdir(dir.get()))) {
459 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800460 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800461 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700462 continue;
463 }
464
465 std::string file_name = directory;
466 file_name += "/";
467 file_name += dp->d_name;
468 std::string file;
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800469 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700470
471 bool found = false;
472 for (const auto& line : android::base::Split(file, "\n")) {
473 log_time t(log_time::EPOCH);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800474 char* ep = parseTime(t, line.c_str());
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800475 if (!ep || (*ep != ' ')) continue;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700476 // determine the time precision of the logs (eg: msec or usec)
477 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
478 if (t.tv_nsec % (mod * 10)) {
479 modulo.tv_nsec = mod;
480 break;
481 }
482 }
483 // We filter any times later than current as we may not have the
484 // year stored with each log entry. Also, since it is possible for
485 // entries to be recorded out of order (very rare) we select the
486 // maximum we find just in case.
487 if ((t < now) && (t > retval)) {
488 retval = t;
489 found = true;
490 }
491 }
492 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800493 if (!dp->d_name[len] && found) break;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700494 }
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800495 if (retval == log_time::EPOCH) return retval;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700496 // tail_time prints matching or higher, round up by the modulo to prevent
497 // a replay of the last entry we have just checked.
498 retval += modulo;
499 return retval;
500}
501
Tom Cherryfb1373a2019-10-29 07:05:24 -0700502void ReportErrorName(const std::string& name, bool allow_security,
503 std::vector<std::string>* errors) {
504 if (allow_security || name != "security") {
505 errors->emplace_back(name);
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800506 }
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800507}
Traian Schiau9f978602015-04-10 15:51:39 +0300508
Tom Cherryb1cf4282019-10-24 17:35:26 -0700509int Logcat::Run(int argc, char** argv) {
Mark Salyzynd5920022017-02-28 09:20:31 -0800510 bool hasSetLogFormat = false;
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800511 bool clearLog = false;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700512 bool security_buffer_selected =
513 false; // Do not report errors on the security buffer unless it is explicitly named.
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800514 bool getLogSize = false;
515 bool getPruneList = false;
516 bool printStatistics = false;
517 bool printDividers = false;
Mark Salyzync89839a2014-02-11 12:29:31 -0800518 unsigned long setLogSize = 0;
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800519 const char* setPruneList = nullptr;
520 const char* setId = nullptr;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800521 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800522 std::string forceFilters;
Traian Schiau9f978602015-04-10 15:51:39 +0300523 size_t tail_lines = 0;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800524 log_time tail_time(log_time::EPOCH);
Kristian Monsen694cdf62015-06-05 14:10:12 -0700525 size_t pid = 0;
Casey Dahlined028f92016-03-17 14:04:52 -0700526 bool got_t = false;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700527 unsigned id_mask = 0;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800528
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800529 if (argc == 2 && !strcmp(argv[1], "--help")) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700530 show_help();
531 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800532 }
533
Mark Salyzynd5920022017-02-28 09:20:31 -0800534 // meant to catch comma-delimited values, but cast a wider
535 // net for stability dealing with possible mistaken inputs.
536 static const char delimiters[] = ",:; \t\n\r\f";
537
Elliott Hughes442d8582018-06-15 15:16:20 -0700538 optind = 0;
539 while (true) {
Kristian Monsen694cdf62015-06-05 14:10:12 -0700540 int option_index = 0;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700541 // list of long-argument only strings for later comparison
Kristian Monsen694cdf62015-06-05 14:10:12 -0700542 static const char pid_str[] = "pid";
Mark Salyzyn14369232016-11-16 15:28:31 -0800543 static const char debug_str[] = "debug";
Mark Salyzyn175773d2016-08-03 14:20:41 -0700544 static const char id_str[] = "id";
Mark Salyzyn712caab2015-11-30 13:48:56 -0800545 static const char wrap_str[] = "wrap";
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700546 static const char print_str[] = "print";
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800547 // clang-format off
Kristian Monsen694cdf62015-06-05 14:10:12 -0700548 static const struct option long_options[] = {
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800549 { "binary", no_argument, nullptr, 'B' },
550 { "buffer", required_argument, nullptr, 'b' },
551 { "buffer-size", optional_argument, nullptr, 'g' },
552 { "clear", no_argument, nullptr, 'c' },
553 { debug_str, no_argument, nullptr, 0 },
554 { "dividers", no_argument, nullptr, 'D' },
555 { "file", required_argument, nullptr, 'f' },
556 { "format", required_argument, nullptr, 'v' },
Mark Salyzyn17475732016-04-01 07:52:20 -0700557 // hidden and undocumented reserved alias for --regex
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800558 { "grep", required_argument, nullptr, 'e' },
Mark Salyzyn12d83062016-03-30 09:15:09 -0700559 // hidden and undocumented reserved alias for --max-count
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800560 { "head", required_argument, nullptr, 'm' },
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700561 { "help", no_argument, nullptr, 'h' },
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800562 { id_str, required_argument, nullptr, 0 },
563 { "last", no_argument, nullptr, 'L' },
564 { "max-count", required_argument, nullptr, 'm' },
565 { pid_str, required_argument, nullptr, 0 },
566 { print_str, no_argument, nullptr, 0 },
567 { "prune", optional_argument, nullptr, 'p' },
568 { "regex", required_argument, nullptr, 'e' },
569 { "rotate-count", required_argument, nullptr, 'n' },
570 { "rotate-kbytes", required_argument, nullptr, 'r' },
571 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzyn12d83062016-03-30 09:15:09 -0700572 // hidden and undocumented reserved alias for -t
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800573 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn712caab2015-11-30 13:48:56 -0800574 // support, but ignore and do not document, the optional argument
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800575 { wrap_str, optional_argument, nullptr, 0 },
576 { nullptr, 0, nullptr, 0 }
Kristian Monsen694cdf62015-06-05 14:10:12 -0700577 };
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800578 // clang-format on
Kristian Monsen694cdf62015-06-05 14:10:12 -0700579
Elliott Hughes442d8582018-06-15 15:16:20 -0700580 int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
581 &option_index);
582 if (c == -1) break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800583
Elliott Hughes442d8582018-06-15 15:16:20 -0700584 switch (c) {
Kristian Monsen694cdf62015-06-05 14:10:12 -0700585 case 0:
Mark Salyzyn175773d2016-08-03 14:20:41 -0700586 // only long options
Kristian Monsen694cdf62015-06-05 14:10:12 -0700587 if (long_options[option_index].name == pid_str) {
Steven Moreland36f05952019-08-02 10:13:57 -0700588 if (pid != 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800589 error(EXIT_FAILURE, 0, "Only one --pid argument can be provided.");
Steven Moreland36f05952019-08-02 10:13:57 -0700590 }
591
Tom Cherryfb1373a2019-10-29 07:05:24 -0700592 if (!ParseUint(optarg, &pid) || pid < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800593 error(EXIT_FAILURE, 0, "%s %s out of range.",
594 long_options[option_index].name, optarg);
Kristian Monsen694cdf62015-06-05 14:10:12 -0700595 }
596 break;
597 }
Mark Salyzyn712caab2015-11-30 13:48:56 -0800598 if (long_options[option_index].name == wrap_str) {
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800599 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn712caab2015-11-30 13:48:56 -0800600 ANDROID_LOG_NONBLOCK;
601 // ToDo: implement API that supports setting a wrap timeout
602 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700603 if (optarg && (!ParseUint(optarg, &dummy) || dummy < 1)) {
Tom Cherry96840882019-12-06 10:25:37 -0800604 error(EXIT_FAILURE, 0, "%s %s out of range.",
605 long_options[option_index].name, optarg);
Mark Salyzyn712caab2015-11-30 13:48:56 -0800606 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700607 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
608 fprintf(stderr, "WARNING: %s %u seconds, ignoring %zu\n",
609 long_options[option_index].name, ANDROID_LOG_WRAP_DEFAULT_TIMEOUT,
610 dummy);
Mark Salyzyn712caab2015-11-30 13:48:56 -0800611 }
612 break;
613 }
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700614 if (long_options[option_index].name == print_str) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700615 print_it_anyways_ = true;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700616 break;
617 }
Mark Salyzyn14369232016-11-16 15:28:31 -0800618 if (long_options[option_index].name == debug_str) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700619 debug_ = true;
Mark Salyzyn14369232016-11-16 15:28:31 -0800620 break;
621 }
Mark Salyzyn175773d2016-08-03 14:20:41 -0700622 if (long_options[option_index].name == id_str) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700623 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn175773d2016-08-03 14:20:41 -0700624 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800625 break;
Kristian Monsen694cdf62015-06-05 14:10:12 -0700626
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800627 case 's':
The Android Open Source Project190995d2009-03-03 19:32:55 -0800628 // default to all silent
Tom Cherryb1cf4282019-10-24 17:35:26 -0700629 android_log_addFilterRule(logformat_.get(), "*:s");
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800630 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800631
632 case 'c':
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800633 clearLog = true;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800634 mode |= ANDROID_LOG_WRONLY;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800635 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800636
Mark Salyzyn66460fc2014-12-15 10:01:31 -0800637 case 'L':
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800638 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
639 ANDROID_LOG_NONBLOCK;
640 break;
Mark Salyzyn66460fc2014-12-15 10:01:31 -0800641
The Android Open Source Project190995d2009-03-03 19:32:55 -0800642 case 'd':
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800643 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800644 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800645
Dan Egnorcce2b082010-03-11 20:32:17 -0800646 case 't':
Casey Dahlined028f92016-03-17 14:04:52 -0700647 got_t = true;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800648 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700649 FALLTHROUGH_INTENDED;
Mark Salyzyn2256e2f2013-12-09 13:47:00 -0800650 case 'T':
Elliott Hughes442d8582018-06-15 15:16:20 -0700651 if (strspn(optarg, "0123456789") != strlen(optarg)) {
652 char* cp = parseTime(tail_time, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800653 if (!cp) {
Tom Cherry96840882019-12-06 10:25:37 -0800654 error(EXIT_FAILURE, 0, "-%c '%s' not in time format.", c, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800655 }
656 if (*cp) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700657 char ch = *cp;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800658 *cp = '\0';
Tom Cherry96840882019-12-06 10:25:37 -0800659 fprintf(stderr, "WARNING: -%c '%s' '%c%s' time truncated\n", c, optarg, ch,
660 cp + 1);
Elliott Hughes442d8582018-06-15 15:16:20 -0700661 *cp = ch;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800662 }
663 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700664 if (!ParseUint(optarg, &tail_lines) || tail_lines < 1) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700665 fprintf(stderr, "WARNING: -%c %s invalid, setting to 1\n", c, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800666 tail_lines = 1;
667 }
668 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800669 break;
Dan Egnorcce2b082010-03-11 20:32:17 -0800670
Mark Salyzyn1ff18092015-01-26 13:41:33 -0800671 case 'D':
672 printDividers = true;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800673 break;
Mark Salyzyn1ff18092015-01-26 13:41:33 -0800674
Casey Dahlin4cf025a2016-03-17 16:18:55 -0700675 case 'e':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700676 regex_.reset(new std::regex(optarg));
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800677 break;
Casey Dahlin4cf025a2016-03-17 16:18:55 -0700678
Casey Dahlined028f92016-03-17 14:04:52 -0700679 case 'm': {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700680 if (!ParseUint(optarg, &max_count_) || max_count_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800681 error(EXIT_FAILURE, 0, "-%c '%s' isn't an integer greater than zero.", c,
682 optarg);
Casey Dahlined028f92016-03-17 14:04:52 -0700683 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800684 } break;
Casey Dahlined028f92016-03-17 14:04:52 -0700685
The Android Open Source Project190995d2009-03-03 19:32:55 -0800686 case 'g':
Elliott Hughes442d8582018-06-15 15:16:20 -0700687 if (!optarg) {
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800688 getLogSize = true;
Mark Salyzynaef4c7e2015-11-30 12:57:56 -0800689 break;
690 }
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700691 FALLTHROUGH_INTENDED;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800692
Mark Salyzync89839a2014-02-11 12:29:31 -0800693 case 'G': {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700694 if (!ParseByteCount(optarg, &setLogSize) || setLogSize < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800695 error(EXIT_FAILURE, 0, "-G must be specified as <num><multiplier>.");
Mark Salyzync89839a2014-02-11 12:29:31 -0800696 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800697 } break;
Mark Salyzync89839a2014-02-11 12:29:31 -0800698
699 case 'p':
Elliott Hughes442d8582018-06-15 15:16:20 -0700700 if (!optarg) {
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800701 getPruneList = true;
Mark Salyzynaef4c7e2015-11-30 12:57:56 -0800702 break;
703 }
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700704 FALLTHROUGH_INTENDED;
Mark Salyzync89839a2014-02-11 12:29:31 -0800705
706 case 'P':
Elliott Hughes442d8582018-06-15 15:16:20 -0700707 setPruneList = optarg;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800708 break;
Mark Salyzync89839a2014-02-11 12:29:31 -0800709
Tom Cherryfb1373a2019-10-29 07:05:24 -0700710 case 'b':
711 for (const auto& buffer : Split(optarg, delimiters)) {
712 if (buffer == "default") {
713 id_mask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH);
714 } else if (buffer == "all") {
715 id_mask = -1;
Mark Salyzyn9ca3be32016-04-11 14:03:48 -0700716 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700717 log_id_t log_id = android_name_to_log_id(buffer.c_str());
718 if (log_id >= LOG_ID_MAX) {
Tom Cherry96840882019-12-06 10:25:37 -0800719 error(EXIT_FAILURE, 0, "Unknown buffer '%s' listed for -b.",
720 buffer.c_str());
Mark Salyzynd774bce2014-02-06 14:48:50 -0800721 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700722 if (log_id == LOG_ID_SECURITY) {
723 security_buffer_selected = true;
Mark Salyzync9690862015-12-04 10:59:45 -0800724 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700725 id_mask |= (1 << log_id);
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800726 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800727 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700728 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800729
730 case 'B':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700731 print_binary_ = 1;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800732 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800733
734 case 'f':
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800735 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700736 tail_time = lastLogTime(optarg);
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700737 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800738 // redirect output to a file
Tom Cherryb1cf4282019-10-24 17:35:26 -0700739 output_file_name_ = optarg;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800740 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800741
Mark Salyzynff5f4b12016-06-07 13:03:10 -0700742 case 'r':
Tom Cherryfb1373a2019-10-29 07:05:24 -0700743 if (!ParseUint(optarg, &log_rotate_size_kb_) || log_rotate_size_kb_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800744 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -r.", optarg);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800745 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800746 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800747
Mark Salyzynff5f4b12016-06-07 13:03:10 -0700748 case 'n':
Tom Cherryfb1373a2019-10-29 07:05:24 -0700749 if (!ParseUint(optarg, &max_rotated_logs_) || max_rotated_logs_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800750 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -n.", optarg);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800751 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800752 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800753
Tom Cherryfb1373a2019-10-29 07:05:24 -0700754 case 'v':
Elliott Hughes442d8582018-06-15 15:16:20 -0700755 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700756 show_format_help();
757 return EXIT_SUCCESS;
Mark Salyzyn604679a2016-10-18 11:30:11 -0700758 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700759 for (const auto& arg : Split(optarg, delimiters)) {
760 int err = SetLogFormat(arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800761 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800762 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -v.", arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800763 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800764 if (err) hasSetLogFormat = true;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800765 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700766 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800767
768 case 'Q':
bohu25889532017-02-21 14:31:19 -0800769#define LOGCAT_FILTER "androidboot.logcat="
770#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800771#define CONSOLE_OPTION "androidboot.console="
bohu25889532017-02-21 14:31:19 -0800772#define QEMU_PROPERTY "ro.kernel.qemu"
773#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800774 // This is a *hidden* option used to start a version of logcat
775 // in an emulated device only. It basically looks for
776 // androidboot.logcat= on the kernel command line. If
777 // something is found, it extracts a log filter and uses it to
bohu25889532017-02-21 14:31:19 -0800778 // run the program. The logcat output will go to consolepipe if
779 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
780 // it goes to androidboot.console (e.g. tty)
The Android Open Source Project190995d2009-03-03 19:32:55 -0800781 {
bohu25889532017-02-21 14:31:19 -0800782 // if not in emulator, exit quietly
783 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700784 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800785 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800786
bohu25889532017-02-21 14:31:19 -0800787 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
788 if (cmdline.empty()) {
789 android::base::ReadFileToString("/proc/cmdline", &cmdline);
790 }
791
792 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
793 // if nothing found or invalid filters, exit quietly
794 if (!logcatFilter) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700795 return EXIT_SUCCESS;
bohu25889532017-02-21 14:31:19 -0800796 }
797
798 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800799 const char* q = strpbrk(p, " \t\n\r");
800 if (!q) q = p + strlen(p);
801 forceFilters = std::string(p, q);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800802
bohu25889532017-02-21 14:31:19 -0800803 // redirect our output to the emulator console pipe or console
804 const char* consolePipe =
805 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800806 const char* console =
807 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800808
bohu25889532017-02-21 14:31:19 -0800809 if (consolePipe) {
810 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
811 } else if (console) {
812 p = console + strlen(CONSOLE_OPTION);
813 } else {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700814 return EXIT_FAILURE;
bohu25889532017-02-21 14:31:19 -0800815 }
816
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800817 q = strpbrk(p, " \t\n\r");
818 int len = q ? q - p : strlen(p);
819 std::string devname = "/dev/" + std::string(p, len);
bohu25889532017-02-21 14:31:19 -0800820 std::string pipePurpose("pipe:logcat");
821 if (consolePipe) {
822 // example: "qemu_pipe,pipe:logcat"
823 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
824 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehdd8aae62017-08-03 13:56:49 -0700825 size_t pos = devname.find(',');
bohu25889532017-02-21 14:31:19 -0800826 if (pos != std::string::npos) {
827 pipePurpose = devname.substr(pos + 1);
828 devname = devname.substr(0, pos);
829 }
830 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800831
Tom Cherryb1cf4282019-10-24 17:35:26 -0700832 fprintf(stderr, "logcat using %s\n", devname.c_str());
833
834 int fd = open(devname.c_str(), O_WRONLY | O_CLOEXEC);
835 if (fd < 0) {
836 break;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800837 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800838
bohu25889532017-02-21 14:31:19 -0800839 if (consolePipe) {
840 // need the trailing '\0'
Tom Cherryb1cf4282019-10-24 17:35:26 -0700841 if (!android::base::WriteFully(fd, pipePurpose.c_str(),
842 pipePurpose.size() + 1)) {
843 close(fd);
844 return EXIT_FAILURE;
bohu25889532017-02-21 14:31:19 -0800845 }
846 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800847 // close output and error channels, replace with console
Erwin Jansen613c7d42019-11-27 12:58:58 -0800848 dup2(fd, output_fd_.get());
Tom Cherryb1cf4282019-10-24 17:35:26 -0700849 dup2(fd, STDERR_FILENO);
850 close(fd);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800851 }
852 break;
853
Mark Salyzynd774bce2014-02-06 14:48:50 -0800854 case 'S':
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800855 printStatistics = true;
Mark Salyzynd774bce2014-02-06 14:48:50 -0800856 break;
857
Traian Schiau9f978602015-04-10 15:51:39 +0300858 case ':':
Tom Cherry96840882019-12-06 10:25:37 -0800859 error(EXIT_FAILURE, 0, "Option '%s' needs an argument.", argv[optind - 1]);
860 break;
Traian Schiau9f978602015-04-10 15:51:39 +0300861
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700862 case 'h':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700863 show_help();
864 show_format_help();
865 return EXIT_SUCCESS;
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700866
Tom Cherry96840882019-12-06 10:25:37 -0800867 case '?':
868 error(EXIT_FAILURE, 0, "Unknown option '%s'.", argv[optind - 1]);
869 break;
870
The Android Open Source Project190995d2009-03-03 19:32:55 -0800871 default:
Tom Cherry96840882019-12-06 10:25:37 -0800872 error(EXIT_FAILURE, 0, "Unknown getopt_long() result '%c'.", c);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800873 }
874 }
875
Tom Cherryb1cf4282019-10-24 17:35:26 -0700876 if (max_count_ && got_t) {
Tom Cherry96840882019-12-06 10:25:37 -0800877 error(EXIT_FAILURE, 0, "Cannot use -m (--max-count) and -t together.");
Casey Dahlined028f92016-03-17 14:04:52 -0700878 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700879 if (print_it_anyways_ && (!regex_ || !max_count_)) {
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700880 // One day it would be nice if --print -v color and --regex <expr>
881 // could play with each other and show regex highlighted content.
Tom Cherryb1cf4282019-10-24 17:35:26 -0700882 fprintf(stderr,
883 "WARNING: "
884 "--print ignored, to be used in combination with\n"
885 " "
886 "--regex <expr> and --max-count <N>\n");
887 print_it_anyways_ = false;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700888 }
Casey Dahlined028f92016-03-17 14:04:52 -0700889
Tom Cherryfb1373a2019-10-29 07:05:24 -0700890 // If no buffers are specified, default to using these buffers.
891 if (id_mask == 0) {
892 id_mask = (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH) |
893 (1 << LOG_ID_KERNEL);
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800894 }
895
Tom Cherryb1cf4282019-10-24 17:35:26 -0700896 if (log_rotate_size_kb_ != 0 && !output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800897 error(EXIT_FAILURE, 0, "-r requires -f as well.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800898 }
899
Tom Cherryb1cf4282019-10-24 17:35:26 -0700900 if (setId != 0) {
901 if (!output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800902 error(EXIT_FAILURE, 0, "--id='%s' requires -f as well.", setId);
Mark Salyzyn175773d2016-08-03 14:20:41 -0700903 }
904
Tom Cherryb1cf4282019-10-24 17:35:26 -0700905 std::string file_name = StringPrintf("%s.id", output_file_name_);
Mark Salyzyn175773d2016-08-03 14:20:41 -0700906 std::string file;
907 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800908 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
909 getuid(), getgid());
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800910 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn175773d2016-08-03 14:20:41 -0700911 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800912
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800913 if (!hasSetLogFormat) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700914 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800915
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800916 if (!!logFormat) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700917 for (const auto& arg : Split(logFormat, delimiters)) {
918 int err = SetLogFormat(arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800919 // environment should not cause crash of logcat
Tom Cherryb1cf4282019-10-24 17:35:26 -0700920 if (err < 0) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700921 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800922 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800923 if (err > 0) hasSetLogFormat = true;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800924 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800925 }
926 if (!hasSetLogFormat) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700927 SetLogFormat("threadtime");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800928 }
929 }
930
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800931 if (forceFilters.size()) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700932 int err = android_log_addFilterString(logformat_.get(), forceFilters.c_str());
The Android Open Source Project190995d2009-03-03 19:32:55 -0800933 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800934 error(EXIT_FAILURE, 0, "Invalid filter expression in logcat args.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800935 }
Elliott Hughes442d8582018-06-15 15:16:20 -0700936 } else if (argc == optind) {
The Android Open Source Project190995d2009-03-03 19:32:55 -0800937 // Add from environment variable
Tom Cherryb1cf4282019-10-24 17:35:26 -0700938 const char* env_tags_orig = getenv("ANDROID_LOG_TAGS");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800939
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800940 if (!!env_tags_orig) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700941 int err = android_log_addFilterString(logformat_.get(), env_tags_orig);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800942
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800943 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800944 error(EXIT_FAILURE, 0, "Invalid filter expression in ANDROID_LOG_TAGS.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800945 }
946 }
947 } else {
948 // Add from commandline
Elliott Hughes442d8582018-06-15 15:16:20 -0700949 for (int i = optind ; i < argc ; i++) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700950 int err = android_log_addFilterString(logformat_.get(), argv[i]);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800951 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800952 error(EXIT_FAILURE, 0, "Invalid filter expression '%s'.", argv[i]);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800953 }
954 }
955 }
956
Tom Cherryf459c582019-11-14 08:56:39 -0800957 if (mode & ANDROID_LOG_PSTORE) {
Tom Cherryeb2258a2019-12-04 14:37:38 -0800958 if (output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800959 error(EXIT_FAILURE, 0, "-c is ambiguous with both -f and -L specified.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800960 }
961 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry96840882019-12-06 10:25:37 -0800962 error(EXIT_FAILURE, 0, "-L is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800963 }
Tom Cherryf459c582019-11-14 08:56:39 -0800964 if (clearLog) {
965 unlink("/sys/fs/pstore/pmsg-ramoops-0");
966 return EXIT_SUCCESS;
967 }
Tom Cherryeb2258a2019-12-04 14:37:38 -0800968 }
969
970 if (output_file_name_) {
Tom Cherryf459c582019-11-14 08:56:39 -0800971 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry96840882019-12-06 10:25:37 -0800972 error(EXIT_FAILURE, 0, "-f is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800973 }
974
975 if (clearLog || setId) {
976 int max_rotation_count_digits =
977 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
978
979 for (int i = max_rotated_logs_; i >= 0; --i) {
980 std::string file;
981
982 if (!i) {
983 file = output_file_name_;
984 } else {
985 file = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
986 }
987
988 int err = unlink(file.c_str());
989
990 if (err < 0 && errno != ENOENT) {
991 fprintf(stderr, "failed to delete log file '%s': %s\n", file.c_str(),
992 strerror(errno));
993 }
994 }
995 }
996
997 if (clearLog) {
998 return EXIT_SUCCESS;
Tom Cherryf459c582019-11-14 08:56:39 -0800999 }
1000 }
1001
Tom Cherryfb1373a2019-10-29 07:05:24 -07001002 std::unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{
1003 nullptr, &android_logger_list_free};
Mark Salyzyn9addf592014-02-14 16:05:05 -08001004 if (tail_time != log_time::EPOCH) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001005 logger_list.reset(android_logger_list_alloc_time(mode, tail_time, pid));
Mark Salyzyn9addf592014-02-14 16:05:05 -08001006 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001007 logger_list.reset(android_logger_list_alloc(mode, tail_lines, pid));
Mark Salyzyn9addf592014-02-14 16:05:05 -08001008 }
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001009 // We have three orthogonal actions below to clear, set log size and
1010 // get log size. All sharing the same iteration loop.
Tom Cherryfb1373a2019-10-29 07:05:24 -07001011 std::vector<std::string> open_device_failures;
1012 std::vector<std::string> clear_failures;
1013 std::vector<std::string> set_size_failures;
1014 std::vector<std::string> get_size_failures;
1015
1016 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
1017 if (!(id_mask & (1 << i))) continue;
1018 const char* buffer_name = android_log_id_to_name(static_cast<log_id_t>(i));
1019
1020 auto logger = android_logger_open(logger_list.get(), static_cast<log_id_t>(i));
1021 if (logger == nullptr) {
1022 ReportErrorName(buffer_name, security_buffer_selected, &open_device_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001023 continue;
The Android Open Source Project190995d2009-03-03 19:32:55 -08001024 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001025
Tom Cherryeb2258a2019-12-04 14:37:38 -08001026 if (clearLog) {
1027 if (android_logger_clear(logger)) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001028 ReportErrorName(buffer_name, security_buffer_selected, &clear_failures);
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001029 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001030 }
1031
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001032 if (setLogSize) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001033 if (android_logger_set_log_size(logger, setLogSize)) {
1034 ReportErrorName(buffer_name, security_buffer_selected, &set_size_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001035 }
Mark Salyzync89839a2014-02-11 12:29:31 -08001036 }
1037
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001038 if (getLogSize) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001039 long size = android_logger_get_log_size(logger);
1040 long readable = android_logger_get_log_readable_size(logger);
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001041
Tom Cherryfb1373a2019-10-29 07:05:24 -07001042 if (size < 0 || readable < 0) {
1043 ReportErrorName(buffer_name, security_buffer_selected, &get_size_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001044 } else {
Wei Wang8b584172018-09-05 11:05:57 -07001045 auto size_format = format_of_size(size);
1046 auto readable_format = format_of_size(readable);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001047 std::string str = android::base::StringPrintf(
Tom Cherryfb1373a2019-10-29 07:05:24 -07001048 "%s: ring buffer is %lu %sB (%lu %sB consumed),"
1049 " max entry is %d B, max payload is %d B\n",
1050 buffer_name, size_format.first, size_format.second, readable_format.first,
1051 readable_format.second, (int)LOGGER_ENTRY_MAX_LEN,
1052 (int)LOGGER_ENTRY_MAX_PAYLOAD);
Tom Cherryb1cf4282019-10-24 17:35:26 -07001053 TEMP_FAILURE_RETRY(write(output_fd_.get(), str.data(), str.length()));
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001054 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001055 }
The Android Open Source Project190995d2009-03-03 19:32:55 -08001056 }
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001057
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001058 // report any errors in the above loop and exit
Tom Cherryfb1373a2019-10-29 07:05:24 -07001059 if (!open_device_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001060 error(EXIT_FAILURE, 0, "Unable to open log device%s '%s'.",
1061 open_device_failures.size() > 1 ? "s" : "", Join(open_device_failures, ",").c_str());
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001062 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001063 if (!clear_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001064 error(EXIT_FAILURE, 0, "failed to clear the '%s' log%s.", Join(clear_failures, ",").c_str(),
1065 clear_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001066 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001067 if (!set_size_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001068 error(EXIT_FAILURE, 0, "failed to set the '%s' log size%s.",
1069 Join(set_size_failures, ",").c_str(), set_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001070 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001071 if (!get_size_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001072 error(EXIT_FAILURE, 0, "failed to get the readable '%s' log size%s.",
1073 Join(get_size_failures, ",").c_str(), get_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001074 }
The Android Open Source Project190995d2009-03-03 19:32:55 -08001075
Mark Salyzync89839a2014-02-11 12:29:31 -08001076 if (setPruneList) {
Traian Schiau9f978602015-04-10 15:51:39 +03001077 size_t len = strlen(setPruneList);
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001078 // extra 32 bytes are needed by android_logger_set_prune_list
Traian Schiau9f978602015-04-10 15:51:39 +03001079 size_t bLen = len + 32;
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001080 char* buf = nullptr;
Traian Schiau9f978602015-04-10 15:51:39 +03001081 if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
1082 buf[len] = '\0';
Tom Cherryfb1373a2019-10-29 07:05:24 -07001083 if (android_logger_set_prune_list(logger_list.get(), buf, bLen)) {
Tom Cherry96840882019-12-06 10:25:37 -08001084 error(EXIT_FAILURE, 0, "Failed to set the prune list.");
Traian Schiau9f978602015-04-10 15:51:39 +03001085 }
1086 free(buf);
1087 } else {
Tom Cherry96840882019-12-06 10:25:37 -08001088 error(EXIT_FAILURE, 0, "Failed to set the prune list (alloc).");
Mark Salyzync89839a2014-02-11 12:29:31 -08001089 }
Tom Cherryb1cf4282019-10-24 17:35:26 -07001090 return EXIT_SUCCESS;
Mark Salyzync89839a2014-02-11 12:29:31 -08001091 }
1092
Mark Salyzync402bc72014-04-01 17:19:47 -07001093 if (printStatistics || getPruneList) {
Mark Salyzynd774bce2014-02-06 14:48:50 -08001094 size_t len = 8192;
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001095 char* buf;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001096
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001097 for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001098 delete[] buf, buf = nullptr, --retry) {
Mark Salyzync89839a2014-02-11 12:29:31 -08001099 if (getPruneList) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001100 android_logger_get_prune_list(logger_list.get(), buf, len);
Mark Salyzync89839a2014-02-11 12:29:31 -08001101 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001102 android_logger_get_statistics(logger_list.get(), buf, len);
Mark Salyzync89839a2014-02-11 12:29:31 -08001103 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001104 buf[len - 1] = '\0';
Traian Schiau9f978602015-04-10 15:51:39 +03001105 if (atol(buf) < 3) {
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001106 delete[] buf;
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001107 buf = nullptr;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001108 break;
1109 }
Traian Schiau9f978602015-04-10 15:51:39 +03001110 size_t ret = atol(buf) + 1;
1111 if (ret <= len) {
1112 len = ret;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001113 break;
1114 }
Traian Schiau9f978602015-04-10 15:51:39 +03001115 len = ret;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001116 }
1117
1118 if (!buf) {
Tom Cherry96840882019-12-06 10:25:37 -08001119 error(EXIT_FAILURE, 0, "Failed to read data.");
Mark Salyzynd774bce2014-02-06 14:48:50 -08001120 }
1121
1122 // remove trailing FF
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001123 char* cp = buf + len - 1;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001124 *cp = '\0';
1125 bool truncated = *--cp != '\f';
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001126 if (!truncated) *cp = '\0';
Mark Salyzynd774bce2014-02-06 14:48:50 -08001127
1128 // squash out the byte count
1129 cp = buf;
1130 if (!truncated) {
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001131 while (isdigit(*cp)) ++cp;
1132 if (*cp == '\n') ++cp;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001133 }
1134
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001135 len = strlen(cp);
Tom Cherryb1cf4282019-10-24 17:35:26 -07001136 TEMP_FAILURE_RETRY(write(output_fd_.get(), cp, len));
Mark Salyzynd8b454f2017-02-10 13:09:07 -08001137 delete[] buf;
Tom Cherryb1cf4282019-10-24 17:35:26 -07001138 return EXIT_SUCCESS;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001139 }
1140
Tom Cherryb1cf4282019-10-24 17:35:26 -07001141 if (getLogSize || setLogSize || clearLog) return EXIT_SUCCESS;
The Android Open Source Project190995d2009-03-03 19:32:55 -08001142
Tom Cherryb1cf4282019-10-24 17:35:26 -07001143 SetupOutputAndSchedulingPolicy(!(mode & ANDROID_LOG_NONBLOCK));
The Android Open Source Project190995d2009-03-03 19:32:55 -08001144
Tom Cherryb1cf4282019-10-24 17:35:26 -07001145 while (!max_count_ || print_count_ < max_count_) {
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001146 struct log_msg log_msg;
Tom Cherryfb1373a2019-10-29 07:05:24 -07001147 int ret = android_logger_list_read(logger_list.get(), &log_msg);
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001148 if (!ret) {
Tom Cherry96840882019-12-06 10:25:37 -08001149 error(EXIT_FAILURE, 0, R"init(Unexpected EOF!
Tom Cherrya59bde42019-11-21 10:31:06 -08001150
1151This means that either logd crashed, or more likely, this instance of logcat was unable to read log
1152messages as quickly as they were being produced.
1153
Tom Cherry96840882019-12-06 10:25:37 -08001154If you have enabled significant logging, look into using the -G option to increase log buffer sizes.)init");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001155 }
1156
1157 if (ret < 0) {
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001158 if (ret == -EAGAIN) break;
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001159
1160 if (ret == -EIO) {
Tom Cherry96840882019-12-06 10:25:37 -08001161 error(EXIT_FAILURE, 0, "Unexpected EOF!");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001162 }
1163 if (ret == -EINVAL) {
Tom Cherry96840882019-12-06 10:25:37 -08001164 error(EXIT_FAILURE, 0, "Unexpected length.");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001165 }
Tom Cherry96840882019-12-06 10:25:37 -08001166 error(EXIT_FAILURE, errno, "Logcat read failure");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001167 }
1168
Tom Cherryfb1373a2019-10-29 07:05:24 -07001169 if (log_msg.id() > LOG_ID_MAX) {
Tom Cherry96840882019-12-06 10:25:37 -08001170 error(EXIT_FAILURE, 0, "Unexpected log id (%d) over LOG_ID_MAX (%d).", log_msg.id(),
1171 LOG_ID_MAX);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001172 }
1173
Tom Cherryfb1373a2019-10-29 07:05:24 -07001174 PrintDividers(log_msg.id(), printDividers);
1175
Tom Cherryb1cf4282019-10-24 17:35:26 -07001176 if (print_binary_) {
1177 TEMP_FAILURE_RETRY(write(output_fd_.get(), &log_msg, log_msg.len()));
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001178 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001179 ProcessBuffer(&log_msg);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001180 }
1181 }
Tom Cherryb1cf4282019-10-24 17:35:26 -07001182 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001183}
1184
Tom Cherryd8ea11f2019-10-30 13:51:03 -07001185int main(int argc, char** argv) {
Tom Cherryb1cf4282019-10-24 17:35:26 -07001186 Logcat logcat;
1187 return logcat.Run(argc, argv);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001188}