blob: 7b1843880eabce78fde361bf7d987de418e6ac35 [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
Jaegeuk Kim64352f22019-07-04 18:09:38 -0700107#ifndef F2FS_IOC_SET_PIN_FILE
108#define F2FS_IOCTL_MAGIC 0xf5
109#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
110#endif
111
112static int openLogFile(const char* pathname, size_t sizeKB) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700113 int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
Jaegeuk Kim64352f22019-07-04 18:09:38 -0700114 if (fd < 0) {
115 return fd;
116 }
117
118 // no need to check errors
119 __u32 set = 1;
120 ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
121 fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, (sizeKB << 10));
122 return fd;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800123}
124
Tom Cherryb1cf4282019-10-24 17:35:26 -0700125void Logcat::RotateLogs() {
The Android Open Source Project190995d2009-03-03 19:32:55 -0800126 // Can't rotate logs if we're not outputting to a file
Tom Cherryb1cf4282019-10-24 17:35:26 -0700127 if (!output_file_name_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800128
Tom Cherryb1cf4282019-10-24 17:35:26 -0700129 output_fd_.reset();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800130
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800131 // Compute the maximum number of digits needed to count up to
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800132 // maxRotatedLogs in decimal. eg:
133 // maxRotatedLogs == 30
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800134 // -> log10(30) == 1.477
135 // -> maxRotationCountDigits == 2
Tom Cherryb1cf4282019-10-24 17:35:26 -0700136 int max_rotation_count_digits =
137 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
Aristidis Papaioannouf7cc6622014-10-16 22:19:55 -0700138
Tom Cherryb1cf4282019-10-24 17:35:26 -0700139 for (int i = max_rotated_logs_; i > 0; i--) {
140 std::string file1 =
141 StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800142
Mark Salyzyn2a1233e2016-08-03 14:20:41 -0700143 std::string file0;
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800144 if (!(i - 1)) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700145 file0 = output_file_name_;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800146 } else {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700147 file0 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i - 1);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800148 }
149
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800150 if (!file0.length() || !file1.length()) {
Traian Schiau9f978602015-04-10 15:51:39 +0300151 perror("while rotating log files");
152 break;
153 }
154
Tom Cherryb1cf4282019-10-24 17:35:26 -0700155 int err = rename(file0.c_str(), file1.c_str());
The Android Open Source Project190995d2009-03-03 19:32:55 -0800156
157 if (err < 0 && errno != ENOENT) {
158 perror("while rotating log files");
159 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800160 }
161
Tom Cherryb1cf4282019-10-24 17:35:26 -0700162 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
The Android Open Source Project190995d2009-03-03 19:32:55 -0800163
Tom Cherryb1cf4282019-10-24 17:35:26 -0700164 if (!output_fd_.ok()) {
Tom Cherry96840882019-12-06 10:25:37 -0800165 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyn7e0bbab2017-02-17 13:15:51 -0800166 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800167
Tom Cherryb1cf4282019-10-24 17:35:26 -0700168 out_byte_count_ = 0;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800169}
170
Tom Cherryfb1373a2019-10-29 07:05:24 -0700171void Logcat::ProcessBuffer(struct log_msg* buf) {
Mathias Agopianb9218fb2010-03-17 16:10:26 -0700172 int bytesWritten = 0;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800173 int err;
174 AndroidLogEntry entry;
175 char binaryMsgBuf[1024];
176
Tom Cherryfb1373a2019-10-29 07:05:24 -0700177 bool is_binary =
178 buf->id() == LOG_ID_EVENTS || buf->id() == LOG_ID_STATS || buf->id() == LOG_ID_SECURITY;
179
180 if (is_binary) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700181 if (!event_tag_map_ && !has_opened_event_tag_map_) {
182 event_tag_map_.reset(android_openEventTagMap(nullptr));
183 has_opened_event_tag_map_ = true;
Mark Salyzyn784d64f2015-02-26 14:33:35 -0800184 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700185 err = android_log_processBinaryLogBuffer(&buf->entry, &entry, event_tag_map_.get(),
Tom Cherry47856dd2019-10-15 16:53:11 -0700186 binaryMsgBuf, sizeof(binaryMsgBuf));
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800187 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Project190995d2009-03-03 19:32:55 -0800188 // entry.priority, entry.messageLen, entry.message);
189 } else {
Tom Cherry47856dd2019-10-15 16:53:11 -0700190 err = android_log_processLogBuffer(&buf->entry, &entry);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800191 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700192 if (err < 0 && !debug_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800193
Tom Cherryb1cf4282019-10-24 17:35:26 -0700194 if (android_log_shouldPrintLine(logformat_.get(), std::string(entry.tag, entry.tagLen).c_str(),
195 entry.priority)) {
196 bool match = !regex_ ||
197 std::regex_search(entry.message, entry.message + entry.messageLen, *regex_);
Joe Onorato400da4a2010-03-01 09:11:54 -0800198
Tom Cherryb1cf4282019-10-24 17:35:26 -0700199 print_count_ += match;
200 if (match || print_it_anyways_) {
201 bytesWritten = android_log_printLogLine(logformat_.get(), output_fd_.get(), &entry);
Casey Dahlined028f92016-03-17 14:04:52 -0700202
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700203 if (bytesWritten < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800204 error(EXIT_FAILURE, 0, "Output error.");
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700205 }
Joe Onorato400da4a2010-03-01 09:11:54 -0800206 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800207 }
208
Tom Cherryb1cf4282019-10-24 17:35:26 -0700209 out_byte_count_ += bytesWritten;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800210
Tom Cherryb1cf4282019-10-24 17:35:26 -0700211 if (log_rotate_size_kb_ > 0 && (out_byte_count_ / 1024) >= log_rotate_size_kb_) {
212 RotateLogs();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800213 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800214}
215
Tom Cherryfb1373a2019-10-29 07:05:24 -0700216void Logcat::PrintDividers(log_id_t log_id, bool print_dividers) {
217 if (log_id == last_printed_id_ || print_binary_) {
218 return;
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800219 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700220 if (!printed_start_[log_id] || print_dividers) {
221 if (dprintf(output_fd_.get(), "--------- %s %s\n",
222 printed_start_[log_id] ? "switch to" : "beginning of",
223 android_log_id_to_name(log_id)) < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800224 error(EXIT_FAILURE, errno, "Output error");
Tom Cherryfb1373a2019-10-29 07:05:24 -0700225 }
226 }
227 last_printed_id_ = log_id;
228 printed_start_[log_id] = true;
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800229}
230
Tom Cherryb1cf4282019-10-24 17:35:26 -0700231void Logcat::SetupOutputAndSchedulingPolicy(bool blocking) {
232 if (!output_file_name_) return;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800233
Mark Salyzyn60231da2016-08-04 07:53:52 -0700234 if (blocking) {
235 // Lower priority and set to batch scheduling if we are saving
236 // the logs into files and taking continuous content.
Tom Cherryb1cf4282019-10-24 17:35:26 -0700237 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
238 fprintf(stderr, "failed to set background scheduling policy\n");
Mark Salyzyn38fc72c2015-06-02 07:57:16 -0700239 }
240
Tom Cherryb1cf4282019-10-24 17:35:26 -0700241 struct sched_param param = {};
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800242 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn38fc72c2015-06-02 07:57:16 -0700243 fprintf(stderr, "failed to set to batch scheduler\n");
244 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800245
Tom Cherryb1cf4282019-10-24 17:35:26 -0700246 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
247 fprintf(stderr, "failed set to priority\n");
Riley Andrews53fe1b02015-06-08 23:36:34 -0700248 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800249 }
Mark Salyzyn60231da2016-08-04 07:53:52 -0700250
Tom Cherryb1cf4282019-10-24 17:35:26 -0700251 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
Mark Salyzyn60231da2016-08-04 07:53:52 -0700252
Tom Cherryb1cf4282019-10-24 17:35:26 -0700253 if (!output_fd_.ok()) {
Tom Cherry96840882019-12-06 10:25:37 -0800254 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700255 }
256
257 struct stat statbuf;
Tom Cherryb1cf4282019-10-24 17:35:26 -0700258 if (fstat(output_fd_.get(), &statbuf) == -1) {
Tom Cherry96840882019-12-06 10:25:37 -0800259 error(EXIT_FAILURE, errno, "Couldn't get output file stat");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700260 }
261
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800262 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800263 error(EXIT_FAILURE, 0, "Invalid output file stat.");
Mark Salyzyn60231da2016-08-04 07:53:52 -0700264 }
265
Tom Cherryb1cf4282019-10-24 17:35:26 -0700266 out_byte_count_ = statbuf.st_size;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800267}
268
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800269// clang-format off
Tom Cherryb1cf4282019-10-24 17:35:26 -0700270static void show_help() {
271 const char* cmd = getprogname();
The Android Open Source Project190995d2009-03-03 19:32:55 -0800272
Tom Cherryb1cf4282019-10-24 17:35:26 -0700273 fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800274
Tom Cherrya59bde42019-11-21 10:31:06 -0800275 fprintf(stderr, R"init(
276General options:
277 -b, --buffer=<buffer> Request alternate ring buffer(s):
278 main system radio events crash default all
279 Additionally, 'kernel' for userdebug and eng builds, and
280 'security' for Device Owner installations.
281 Multiple -b parameters or comma separated list of buffers are
282 allowed. Buffers are interleaved.
283 Default -b main,system,crash,kernel.
284 -L, --last Dump logs from prior to last reboot from pstore.
285 -c, --clear Clear (flush) the entire log and exit.
286 if -f is specified, clear the specified file and its related rotated
287 log files instead.
288 if -L is specified, clear pstore log instead.
289 -d Dump the log and then exit (don't block).
290 --pid=<pid> Only print logs from the given pid.
291 --wrap Sleep for 2 hours or when buffer about to wrap whichever
292 comes first. Improves efficiency of polling by providing
293 an about-to-wrap wakeup.
294
295Formatting:
296 -v, --format=<format> Sets log print format verb and adverbs, where <format> is one of:
297 brief help long process raw tag thread threadtime time
298 Modifying adverbs can be added:
299 color descriptive epoch monotonic printable uid usec UTC year zone
300 Multiple -v parameters or comma separated list of format and format
301 modifiers are allowed.
302 -D, --dividers Print dividers between each log buffer.
303 -B, --binary Output the log in binary.
304
305Outfile files:
306 -f, --file=<file> Log to file instead of stdout.
307 -r, --rotate-kbytes=<n> Rotate log every <n> kbytes. Requires -f option.
308 -n, --rotate-count=<count> Sets max number of rotated logs to <count>, default 4.
309 --id=<id> If the signature <id> for logging to file changes, then clear the
310 associated files and continue.
311
312Logd control:
313 These options send a control message to the logd daemon on device, print its return message if
314 applicable, then exit. They are incompatible with -L, as these attributes do not apply to pstore.
315 -g, --buffer-size Get the size of the ring buffers within logd.
316 -G, --buffer-size=<size> Set size of a ring buffer in logd. May suffix with K or M.
317 This can individually control each buffer's size with -b.
318 -S, --statistics Output statistics.
319 --pid can be used to provide pid specific stats.
320 -p, --prune Print prune white and ~black list. Service is specified as UID,
321 UID/PID or /PID. Weighed for quicker pruning if prefix with ~,
322 otherwise weighed for longevity if unadorned. All other pruning
323 activity is oldest first. Special case ~! represents an automatic
324 quicker pruning for the noisiest UID as determined by the current
325 statistics.
326 -P, --prune='<list> ...' Set prune white and ~black list, using same format as listed above.
327 Must be quoted.
328
329Filtering:
330 -s Set default filter to silent. Equivalent to filterspec '*:S'
331 -e, --regex=<expr> Only print lines where the log message matches <expr> where <expr> is
332 an ECMAScript regular expression.
333 -m, --max-count=<count> Quit after printing <count> lines. This is meant to be paired with
334 --regex, but will work on its own.
335 --print This option is only applicable when --regex is set and only useful if
336 --max-count is also provided.
337 With --print, logcat will print all messages even if they do not
338 match the regex. Logcat will quit after printing the max-count number
339 of lines that match the regex.
340 -t <count> Print only the most recent <count> lines (implies -d).
341 -t '<time>' Print the lines since specified time (implies -d).
342 -T <count> Print only the most recent <count> lines (does not imply -d).
343 -T '<time>' Print the lines since specified time (not imply -d).
344 count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'
345 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format.
346)init");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800347
Tom Cherryb1cf4282019-10-24 17:35:26 -0700348 fprintf(stderr, "\nfilterspecs are a series of \n"
The Android Open Source Project190995d2009-03-03 19:32:55 -0800349 " <tag>[:priority]\n\n"
350 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzyn438b8222015-03-09 09:32:56 -0700351 " V Verbose (default for <tag>)\n"
352 " D Debug (default for '*')\n"
The Android Open Source Project190995d2009-03-03 19:32:55 -0800353 " I Info\n"
354 " W Warn\n"
355 " E Error\n"
356 " F Fatal\n"
Mark Salyzyn438b8222015-03-09 09:32:56 -0700357 " S Silent (suppress all output)\n"
358 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
359 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
360 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
361 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
362 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyndd569af2014-09-16 09:15:15 -0700363 "or defaults to \"threadtime\"\n\n");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800364}
365
Tom Cherryb1cf4282019-10-24 17:35:26 -0700366static void show_format_help() {
367 fprintf(stderr,
Mark Salyzyn604679a2016-10-18 11:30:11 -0700368 "-v <format>, --format=<format> options:\n"
369 " Sets log print format verb and adverbs, where <format> is:\n"
370 " brief long process raw tag thread threadtime time\n"
371 " and individually flagged modifying adverbs can be added:\n"
372 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
373 "\nSingle format verbs:\n"
374 " brief — Display priority/tag and PID of the process issuing the message.\n"
375 " long — Display all metadata fields, separate messages with blank lines.\n"
376 " process — Display PID only.\n"
377 " raw — Display the raw log message, with no other metadata fields.\n"
378 " tag — Display the priority/tag only.\n"
Mark Salyzyn56ff3fa2017-05-15 13:40:33 -0700379 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn604679a2016-10-18 11:30:11 -0700380 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
381 " and TID of the thread issuing the message. (the default format).\n"
382 " time — Display the date, invocation time, priority/tag, and PID of the\n"
383 " process issuing the message.\n"
384 "\nAdverb modifiers can be used in combination:\n"
385 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
386 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
387 " descriptive — events logs only, descriptions from event-log-tags database.\n"
388 " epoch — Display time as seconds since Jan 1 1970.\n"
389 " monotonic — Display time as cpu seconds since last boot.\n"
390 " printable — Ensure that any binary logging content is escaped.\n"
391 " uid — If permitted, display the UID or Android ID of logged process.\n"
392 " usec — Display time down the microsecond precision.\n"
393 " UTC — Display time as UTC.\n"
394 " year — Add the year to the displayed time.\n"
395 " zone — Add the local timezone to the displayed time.\n"
396 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
397 );
398}
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800399// clang-format on
Mark Salyzyn604679a2016-10-18 11:30:11 -0700400
Tom Cherryb1cf4282019-10-24 17:35:26 -0700401int Logcat::SetLogFormat(const char* format_string) {
402 AndroidLogPrintFormat format = android_log_formatFromString(format_string);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800403
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800404 // invalid string?
405 if (format == FORMAT_OFF) return -1;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800406
Tom Cherryb1cf4282019-10-24 17:35:26 -0700407 return android_log_setPrintFormat(logformat_.get(), format);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800408}
409
Wei Wang8b584172018-09-05 11:05:57 -0700410static std::pair<unsigned long, const char*> format_of_size(unsigned long value) {
411 static const char multipliers[][3] = {{""}, {"Ki"}, {"Mi"}, {"Gi"}};
412 size_t i;
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700413 for (i = 0;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800414 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
415 value /= 1024, ++i)
416 ;
Wei Wang8b584172018-09-05 11:05:57 -0700417 return std::make_pair(value, multipliers[i]);
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700418}
419
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800420static char* parseTime(log_time& t, const char* cp) {
421 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800422 if (ep) return ep;
Mark Salyzyn4d0473f2015-08-31 15:53:41 -0700423 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800424 if (ep) return ep;
Mark Salyzyn4d0473f2015-08-31 15:53:41 -0700425 return t.strptime(cp, "%s.%q");
Mark Salyzyneb0456d2015-08-31 08:01:33 -0700426}
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700427
Mark Salyzyn05b88232016-08-04 07:43:46 -0700428// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800429static log_time lastLogTime(const char* outputFileName) {
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700430 log_time retval(log_time::EPOCH);
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800431 if (!outputFileName) return retval;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700432
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700433 std::string directory;
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800434 const char* file = strrchr(outputFileName, '/');
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700435 if (!file) {
436 directory = ".";
437 file = outputFileName;
438 } else {
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800439 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700440 ++file;
441 }
Mark Salyzyn17475732016-04-01 07:52:20 -0700442
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800443 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
444 closedir);
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800445 if (!dir.get()) return retval;
Mark Salyzyn17475732016-04-01 07:52:20 -0700446
Mark Salyzyn05b88232016-08-04 07:43:46 -0700447 log_time now(android_log_clockid());
Mark Salyzyn17475732016-04-01 07:52:20 -0700448
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700449 size_t len = strlen(file);
450 log_time modulo(0, NS_PER_SEC);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800451 struct dirent* dp;
Mark Salyzyn17475732016-04-01 07:52:20 -0700452
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800453 while (!!(dp = readdir(dir.get()))) {
454 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800455 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800456 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700457 continue;
458 }
459
460 std::string file_name = directory;
461 file_name += "/";
462 file_name += dp->d_name;
463 std::string file;
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800464 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700465
466 bool found = false;
467 for (const auto& line : android::base::Split(file, "\n")) {
468 log_time t(log_time::EPOCH);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800469 char* ep = parseTime(t, line.c_str());
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800470 if (!ep || (*ep != ' ')) continue;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700471 // determine the time precision of the logs (eg: msec or usec)
472 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
473 if (t.tv_nsec % (mod * 10)) {
474 modulo.tv_nsec = mod;
475 break;
476 }
477 }
478 // We filter any times later than current as we may not have the
479 // year stored with each log entry. Also, since it is possible for
480 // entries to be recorded out of order (very rare) we select the
481 // maximum we find just in case.
482 if ((t < now) && (t > retval)) {
483 retval = t;
484 found = true;
485 }
486 }
487 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800488 if (!dp->d_name[len] && found) break;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700489 }
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800490 if (retval == log_time::EPOCH) return retval;
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700491 // tail_time prints matching or higher, round up by the modulo to prevent
492 // a replay of the last entry we have just checked.
493 retval += modulo;
494 return retval;
495}
496
Tom Cherryfb1373a2019-10-29 07:05:24 -0700497void ReportErrorName(const std::string& name, bool allow_security,
498 std::vector<std::string>* errors) {
499 if (allow_security || name != "security") {
500 errors->emplace_back(name);
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800501 }
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800502}
Traian Schiau9f978602015-04-10 15:51:39 +0300503
Tom Cherryb1cf4282019-10-24 17:35:26 -0700504int Logcat::Run(int argc, char** argv) {
Mark Salyzynd5920022017-02-28 09:20:31 -0800505 bool hasSetLogFormat = false;
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800506 bool clearLog = false;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700507 bool security_buffer_selected =
508 false; // Do not report errors on the security buffer unless it is explicitly named.
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800509 bool getLogSize = false;
510 bool getPruneList = false;
511 bool printStatistics = false;
512 bool printDividers = false;
Mark Salyzync89839a2014-02-11 12:29:31 -0800513 unsigned long setLogSize = 0;
Mark Salyzyn79b0a152017-03-02 15:09:41 -0800514 const char* setPruneList = nullptr;
515 const char* setId = nullptr;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800516 int mode = ANDROID_LOG_RDONLY;
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800517 std::string forceFilters;
Traian Schiau9f978602015-04-10 15:51:39 +0300518 size_t tail_lines = 0;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800519 log_time tail_time(log_time::EPOCH);
Kristian Monsen694cdf62015-06-05 14:10:12 -0700520 size_t pid = 0;
Casey Dahlined028f92016-03-17 14:04:52 -0700521 bool got_t = false;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700522 unsigned id_mask = 0;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800523
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800524 if (argc == 2 && !strcmp(argv[1], "--help")) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700525 show_help();
526 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800527 }
528
Mark Salyzynd5920022017-02-28 09:20:31 -0800529 // meant to catch comma-delimited values, but cast a wider
530 // net for stability dealing with possible mistaken inputs.
531 static const char delimiters[] = ",:; \t\n\r\f";
532
Elliott Hughes442d8582018-06-15 15:16:20 -0700533 optind = 0;
534 while (true) {
Kristian Monsen694cdf62015-06-05 14:10:12 -0700535 int option_index = 0;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700536 // list of long-argument only strings for later comparison
Kristian Monsen694cdf62015-06-05 14:10:12 -0700537 static const char pid_str[] = "pid";
Mark Salyzyn14369232016-11-16 15:28:31 -0800538 static const char debug_str[] = "debug";
Mark Salyzyn175773d2016-08-03 14:20:41 -0700539 static const char id_str[] = "id";
Mark Salyzyn712caab2015-11-30 13:48:56 -0800540 static const char wrap_str[] = "wrap";
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700541 static const char print_str[] = "print";
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800542 // clang-format off
Kristian Monsen694cdf62015-06-05 14:10:12 -0700543 static const struct option long_options[] = {
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800544 { "binary", no_argument, nullptr, 'B' },
545 { "buffer", required_argument, nullptr, 'b' },
546 { "buffer-size", optional_argument, nullptr, 'g' },
547 { "clear", no_argument, nullptr, 'c' },
548 { debug_str, no_argument, nullptr, 0 },
549 { "dividers", no_argument, nullptr, 'D' },
550 { "file", required_argument, nullptr, 'f' },
551 { "format", required_argument, nullptr, 'v' },
Mark Salyzyn17475732016-04-01 07:52:20 -0700552 // hidden and undocumented reserved alias for --regex
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800553 { "grep", required_argument, nullptr, 'e' },
Mark Salyzyn12d83062016-03-30 09:15:09 -0700554 // hidden and undocumented reserved alias for --max-count
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800555 { "head", required_argument, nullptr, 'm' },
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700556 { "help", no_argument, nullptr, 'h' },
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800557 { id_str, required_argument, nullptr, 0 },
558 { "last", no_argument, nullptr, 'L' },
559 { "max-count", required_argument, nullptr, 'm' },
560 { pid_str, required_argument, nullptr, 0 },
561 { print_str, no_argument, nullptr, 0 },
562 { "prune", optional_argument, nullptr, 'p' },
563 { "regex", required_argument, nullptr, 'e' },
564 { "rotate-count", required_argument, nullptr, 'n' },
565 { "rotate-kbytes", required_argument, nullptr, 'r' },
566 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzyn12d83062016-03-30 09:15:09 -0700567 // hidden and undocumented reserved alias for -t
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800568 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn712caab2015-11-30 13:48:56 -0800569 // support, but ignore and do not document, the optional argument
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800570 { wrap_str, optional_argument, nullptr, 0 },
571 { nullptr, 0, nullptr, 0 }
Kristian Monsen694cdf62015-06-05 14:10:12 -0700572 };
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800573 // clang-format on
Kristian Monsen694cdf62015-06-05 14:10:12 -0700574
Elliott Hughes442d8582018-06-15 15:16:20 -0700575 int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
576 &option_index);
577 if (c == -1) break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800578
Elliott Hughes442d8582018-06-15 15:16:20 -0700579 switch (c) {
Kristian Monsen694cdf62015-06-05 14:10:12 -0700580 case 0:
Mark Salyzyn175773d2016-08-03 14:20:41 -0700581 // only long options
Kristian Monsen694cdf62015-06-05 14:10:12 -0700582 if (long_options[option_index].name == pid_str) {
Steven Moreland36f05952019-08-02 10:13:57 -0700583 if (pid != 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800584 error(EXIT_FAILURE, 0, "Only one --pid argument can be provided.");
Steven Moreland36f05952019-08-02 10:13:57 -0700585 }
586
Tom Cherryfb1373a2019-10-29 07:05:24 -0700587 if (!ParseUint(optarg, &pid) || pid < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800588 error(EXIT_FAILURE, 0, "%s %s out of range.",
589 long_options[option_index].name, optarg);
Kristian Monsen694cdf62015-06-05 14:10:12 -0700590 }
591 break;
592 }
Mark Salyzyn712caab2015-11-30 13:48:56 -0800593 if (long_options[option_index].name == wrap_str) {
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800594 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
Mark Salyzyn712caab2015-11-30 13:48:56 -0800595 ANDROID_LOG_NONBLOCK;
596 // ToDo: implement API that supports setting a wrap timeout
597 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Tom Cherryfb1373a2019-10-29 07:05:24 -0700598 if (optarg && (!ParseUint(optarg, &dummy) || dummy < 1)) {
Tom Cherry96840882019-12-06 10:25:37 -0800599 error(EXIT_FAILURE, 0, "%s %s out of range.",
600 long_options[option_index].name, optarg);
Mark Salyzyn712caab2015-11-30 13:48:56 -0800601 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700602 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
603 fprintf(stderr, "WARNING: %s %u seconds, ignoring %zu\n",
604 long_options[option_index].name, ANDROID_LOG_WRAP_DEFAULT_TIMEOUT,
605 dummy);
Mark Salyzyn712caab2015-11-30 13:48:56 -0800606 }
607 break;
608 }
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700609 if (long_options[option_index].name == print_str) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700610 print_it_anyways_ = true;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700611 break;
612 }
Mark Salyzyn14369232016-11-16 15:28:31 -0800613 if (long_options[option_index].name == debug_str) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700614 debug_ = true;
Mark Salyzyn14369232016-11-16 15:28:31 -0800615 break;
616 }
Mark Salyzyn175773d2016-08-03 14:20:41 -0700617 if (long_options[option_index].name == id_str) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700618 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn175773d2016-08-03 14:20:41 -0700619 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800620 break;
Kristian Monsen694cdf62015-06-05 14:10:12 -0700621
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800622 case 's':
The Android Open Source Project190995d2009-03-03 19:32:55 -0800623 // default to all silent
Tom Cherryb1cf4282019-10-24 17:35:26 -0700624 android_log_addFilterRule(logformat_.get(), "*:s");
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800625 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800626
627 case 'c':
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800628 clearLog = true;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800629 mode |= ANDROID_LOG_WRONLY;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800630 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800631
Mark Salyzyn66460fc2014-12-15 10:01:31 -0800632 case 'L':
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800633 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
634 ANDROID_LOG_NONBLOCK;
635 break;
Mark Salyzyn66460fc2014-12-15 10:01:31 -0800636
The Android Open Source Project190995d2009-03-03 19:32:55 -0800637 case 'd':
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800638 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800639 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800640
Dan Egnorcce2b082010-03-11 20:32:17 -0800641 case 't':
Casey Dahlined028f92016-03-17 14:04:52 -0700642 got_t = true;
Mark Salyzyn4bdf2532015-01-26 10:46:44 -0800643 mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700644 FALLTHROUGH_INTENDED;
Mark Salyzyn2256e2f2013-12-09 13:47:00 -0800645 case 'T':
Elliott Hughes442d8582018-06-15 15:16:20 -0700646 if (strspn(optarg, "0123456789") != strlen(optarg)) {
647 char* cp = parseTime(tail_time, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800648 if (!cp) {
Tom Cherry96840882019-12-06 10:25:37 -0800649 error(EXIT_FAILURE, 0, "-%c '%s' not in time format.", c, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800650 }
651 if (*cp) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700652 char ch = *cp;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800653 *cp = '\0';
Tom Cherry96840882019-12-06 10:25:37 -0800654 fprintf(stderr, "WARNING: -%c '%s' '%c%s' time truncated\n", c, optarg, ch,
655 cp + 1);
Elliott Hughes442d8582018-06-15 15:16:20 -0700656 *cp = ch;
Mark Salyzyn9addf592014-02-14 16:05:05 -0800657 }
658 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700659 if (!ParseUint(optarg, &tail_lines) || tail_lines < 1) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700660 fprintf(stderr, "WARNING: -%c %s invalid, setting to 1\n", c, optarg);
Mark Salyzyn9addf592014-02-14 16:05:05 -0800661 tail_lines = 1;
662 }
663 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800664 break;
Dan Egnorcce2b082010-03-11 20:32:17 -0800665
Mark Salyzyn1ff18092015-01-26 13:41:33 -0800666 case 'D':
667 printDividers = true;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800668 break;
Mark Salyzyn1ff18092015-01-26 13:41:33 -0800669
Casey Dahlin4cf025a2016-03-17 16:18:55 -0700670 case 'e':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700671 regex_.reset(new std::regex(optarg));
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800672 break;
Casey Dahlin4cf025a2016-03-17 16:18:55 -0700673
Casey Dahlined028f92016-03-17 14:04:52 -0700674 case 'm': {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700675 if (!ParseUint(optarg, &max_count_) || max_count_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800676 error(EXIT_FAILURE, 0, "-%c '%s' isn't an integer greater than zero.", c,
677 optarg);
Casey Dahlined028f92016-03-17 14:04:52 -0700678 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800679 } break;
Casey Dahlined028f92016-03-17 14:04:52 -0700680
The Android Open Source Project190995d2009-03-03 19:32:55 -0800681 case 'g':
Elliott Hughes442d8582018-06-15 15:16:20 -0700682 if (!optarg) {
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800683 getLogSize = true;
Mark Salyzynaef4c7e2015-11-30 12:57:56 -0800684 break;
685 }
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700686 FALLTHROUGH_INTENDED;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800687
Mark Salyzync89839a2014-02-11 12:29:31 -0800688 case 'G': {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700689 if (!ParseByteCount(optarg, &setLogSize) || setLogSize < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800690 error(EXIT_FAILURE, 0, "-G must be specified as <num><multiplier>.");
Mark Salyzync89839a2014-02-11 12:29:31 -0800691 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800692 } break;
Mark Salyzync89839a2014-02-11 12:29:31 -0800693
694 case 'p':
Elliott Hughes442d8582018-06-15 15:16:20 -0700695 if (!optarg) {
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800696 getPruneList = true;
Mark Salyzynaef4c7e2015-11-30 12:57:56 -0800697 break;
698 }
Chih-Hung Hsieh6d461422018-09-13 11:08:41 -0700699 FALLTHROUGH_INTENDED;
Mark Salyzync89839a2014-02-11 12:29:31 -0800700
701 case 'P':
Elliott Hughes442d8582018-06-15 15:16:20 -0700702 setPruneList = optarg;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800703 break;
Mark Salyzync89839a2014-02-11 12:29:31 -0800704
Tom Cherryfb1373a2019-10-29 07:05:24 -0700705 case 'b':
706 for (const auto& buffer : Split(optarg, delimiters)) {
707 if (buffer == "default") {
708 id_mask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH);
709 } else if (buffer == "all") {
710 id_mask = -1;
Mark Salyzyn9ca3be32016-04-11 14:03:48 -0700711 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700712 log_id_t log_id = android_name_to_log_id(buffer.c_str());
713 if (log_id >= LOG_ID_MAX) {
Tom Cherry96840882019-12-06 10:25:37 -0800714 error(EXIT_FAILURE, 0, "Unknown buffer '%s' listed for -b.",
715 buffer.c_str());
Mark Salyzynd774bce2014-02-06 14:48:50 -0800716 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700717 if (log_id == LOG_ID_SECURITY) {
718 security_buffer_selected = true;
Mark Salyzync9690862015-12-04 10:59:45 -0800719 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700720 id_mask |= (1 << log_id);
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800721 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800722 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700723 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800724
725 case 'B':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700726 print_binary_ = 1;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800727 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800728
729 case 'f':
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800730 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes442d8582018-06-15 15:16:20 -0700731 tail_time = lastLogTime(optarg);
Mark Salyzyn3fa657e2015-05-27 07:39:56 -0700732 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800733 // redirect output to a file
Tom Cherryb1cf4282019-10-24 17:35:26 -0700734 output_file_name_ = optarg;
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800735 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800736
Mark Salyzynff5f4b12016-06-07 13:03:10 -0700737 case 'r':
Tom Cherryfb1373a2019-10-29 07:05:24 -0700738 if (!ParseUint(optarg, &log_rotate_size_kb_) || log_rotate_size_kb_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800739 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -r.", optarg);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800740 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800741 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800742
Mark Salyzynff5f4b12016-06-07 13:03:10 -0700743 case 'n':
Tom Cherryfb1373a2019-10-29 07:05:24 -0700744 if (!ParseUint(optarg, &max_rotated_logs_) || max_rotated_logs_ < 1) {
Tom Cherry96840882019-12-06 10:25:37 -0800745 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -n.", optarg);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800746 }
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800747 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800748
Tom Cherryfb1373a2019-10-29 07:05:24 -0700749 case 'v':
Elliott Hughes442d8582018-06-15 15:16:20 -0700750 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700751 show_format_help();
752 return EXIT_SUCCESS;
Mark Salyzyn604679a2016-10-18 11:30:11 -0700753 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700754 for (const auto& arg : Split(optarg, delimiters)) {
755 int err = SetLogFormat(arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800756 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800757 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -v.", arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800758 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800759 if (err) hasSetLogFormat = true;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800760 }
Tom Cherryfb1373a2019-10-29 07:05:24 -0700761 break;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800762
763 case 'Q':
bohu25889532017-02-21 14:31:19 -0800764#define LOGCAT_FILTER "androidboot.logcat="
765#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800766#define CONSOLE_OPTION "androidboot.console="
bohu25889532017-02-21 14:31:19 -0800767#define QEMU_PROPERTY "ro.kernel.qemu"
768#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800769 // This is a *hidden* option used to start a version of logcat
770 // in an emulated device only. It basically looks for
771 // androidboot.logcat= on the kernel command line. If
772 // something is found, it extracts a log filter and uses it to
bohu25889532017-02-21 14:31:19 -0800773 // run the program. The logcat output will go to consolepipe if
774 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
775 // it goes to androidboot.console (e.g. tty)
The Android Open Source Project190995d2009-03-03 19:32:55 -0800776 {
bohu25889532017-02-21 14:31:19 -0800777 // if not in emulator, exit quietly
778 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700779 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800780 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800781
bohu25889532017-02-21 14:31:19 -0800782 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
783 if (cmdline.empty()) {
784 android::base::ReadFileToString("/proc/cmdline", &cmdline);
785 }
786
787 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
788 // if nothing found or invalid filters, exit quietly
789 if (!logcatFilter) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700790 return EXIT_SUCCESS;
bohu25889532017-02-21 14:31:19 -0800791 }
792
793 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800794 const char* q = strpbrk(p, " \t\n\r");
795 if (!q) q = p + strlen(p);
796 forceFilters = std::string(p, q);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800797
bohu25889532017-02-21 14:31:19 -0800798 // redirect our output to the emulator console pipe or console
799 const char* consolePipe =
800 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800801 const char* console =
802 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800803
bohu25889532017-02-21 14:31:19 -0800804 if (consolePipe) {
805 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
806 } else if (console) {
807 p = console + strlen(CONSOLE_OPTION);
808 } else {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700809 return EXIT_FAILURE;
bohu25889532017-02-21 14:31:19 -0800810 }
811
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800812 q = strpbrk(p, " \t\n\r");
813 int len = q ? q - p : strlen(p);
814 std::string devname = "/dev/" + std::string(p, len);
bohu25889532017-02-21 14:31:19 -0800815 std::string pipePurpose("pipe:logcat");
816 if (consolePipe) {
817 // example: "qemu_pipe,pipe:logcat"
818 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
819 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehdd8aae62017-08-03 13:56:49 -0700820 size_t pos = devname.find(',');
bohu25889532017-02-21 14:31:19 -0800821 if (pos != std::string::npos) {
822 pipePurpose = devname.substr(pos + 1);
823 devname = devname.substr(0, pos);
824 }
825 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800826
Tom Cherryb1cf4282019-10-24 17:35:26 -0700827 fprintf(stderr, "logcat using %s\n", devname.c_str());
828
829 int fd = open(devname.c_str(), O_WRONLY | O_CLOEXEC);
830 if (fd < 0) {
831 break;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -0800832 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800833
bohu25889532017-02-21 14:31:19 -0800834 if (consolePipe) {
835 // need the trailing '\0'
Tom Cherryb1cf4282019-10-24 17:35:26 -0700836 if (!android::base::WriteFully(fd, pipePurpose.c_str(),
837 pipePurpose.size() + 1)) {
838 close(fd);
839 return EXIT_FAILURE;
bohu25889532017-02-21 14:31:19 -0800840 }
841 }
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800842 // close output and error channels, replace with console
Erwin Jansen613c7d42019-11-27 12:58:58 -0800843 dup2(fd, output_fd_.get());
Tom Cherryb1cf4282019-10-24 17:35:26 -0700844 dup2(fd, STDERR_FILENO);
845 close(fd);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800846 }
847 break;
848
Mark Salyzynd774bce2014-02-06 14:48:50 -0800849 case 'S':
Mark Salyzyn70cf66d2017-01-20 14:07:29 -0800850 printStatistics = true;
Mark Salyzynd774bce2014-02-06 14:48:50 -0800851 break;
852
Traian Schiau9f978602015-04-10 15:51:39 +0300853 case ':':
Tom Cherry96840882019-12-06 10:25:37 -0800854 error(EXIT_FAILURE, 0, "Option '%s' needs an argument.", argv[optind - 1]);
855 break;
Traian Schiau9f978602015-04-10 15:51:39 +0300856
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700857 case 'h':
Tom Cherryb1cf4282019-10-24 17:35:26 -0700858 show_help();
859 show_format_help();
860 return EXIT_SUCCESS;
Mark Salyzyn6a3d5492017-04-03 09:30:20 -0700861
Tom Cherry96840882019-12-06 10:25:37 -0800862 case '?':
863 error(EXIT_FAILURE, 0, "Unknown option '%s'.", argv[optind - 1]);
864 break;
865
The Android Open Source Project190995d2009-03-03 19:32:55 -0800866 default:
Tom Cherry96840882019-12-06 10:25:37 -0800867 error(EXIT_FAILURE, 0, "Unknown getopt_long() result '%c'.", c);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800868 }
869 }
870
Tom Cherryb1cf4282019-10-24 17:35:26 -0700871 if (max_count_ && got_t) {
Tom Cherry96840882019-12-06 10:25:37 -0800872 error(EXIT_FAILURE, 0, "Cannot use -m (--max-count) and -t together.");
Casey Dahlined028f92016-03-17 14:04:52 -0700873 }
Tom Cherryb1cf4282019-10-24 17:35:26 -0700874 if (print_it_anyways_ && (!regex_ || !max_count_)) {
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700875 // One day it would be nice if --print -v color and --regex <expr>
876 // could play with each other and show regex highlighted content.
Tom Cherryb1cf4282019-10-24 17:35:26 -0700877 fprintf(stderr,
878 "WARNING: "
879 "--print ignored, to be used in combination with\n"
880 " "
881 "--regex <expr> and --max-count <N>\n");
882 print_it_anyways_ = false;
Mark Salyzyn1181ec02016-03-30 09:38:31 -0700883 }
Casey Dahlined028f92016-03-17 14:04:52 -0700884
Tom Cherryfb1373a2019-10-29 07:05:24 -0700885 // If no buffers are specified, default to using these buffers.
886 if (id_mask == 0) {
887 id_mask = (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH) |
888 (1 << LOG_ID_KERNEL);
Joe Onoratod23b9cf2010-02-26 10:04:23 -0800889 }
890
Tom Cherryb1cf4282019-10-24 17:35:26 -0700891 if (log_rotate_size_kb_ != 0 && !output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800892 error(EXIT_FAILURE, 0, "-r requires -f as well.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800893 }
894
Tom Cherryb1cf4282019-10-24 17:35:26 -0700895 if (setId != 0) {
896 if (!output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800897 error(EXIT_FAILURE, 0, "--id='%s' requires -f as well.", setId);
Mark Salyzyn175773d2016-08-03 14:20:41 -0700898 }
899
Tom Cherryb1cf4282019-10-24 17:35:26 -0700900 std::string file_name = StringPrintf("%s.id", output_file_name_);
Mark Salyzyn175773d2016-08-03 14:20:41 -0700901 std::string file;
902 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzynd8b454f2017-02-10 13:09:07 -0800903 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
904 getuid(), getgid());
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800905 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn175773d2016-08-03 14:20:41 -0700906 }
The Android Open Source Project190995d2009-03-03 19:32:55 -0800907
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800908 if (!hasSetLogFormat) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700909 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800910
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800911 if (!!logFormat) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700912 for (const auto& arg : Split(logFormat, delimiters)) {
913 int err = SetLogFormat(arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800914 // environment should not cause crash of logcat
Tom Cherryb1cf4282019-10-24 17:35:26 -0700915 if (err < 0) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700916 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg.c_str());
Mark Salyzynd5920022017-02-28 09:20:31 -0800917 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800918 if (err > 0) hasSetLogFormat = true;
The Android Open Source Project190995d2009-03-03 19:32:55 -0800919 }
Mark Salyzynd5920022017-02-28 09:20:31 -0800920 }
921 if (!hasSetLogFormat) {
Tom Cherryb1cf4282019-10-24 17:35:26 -0700922 SetLogFormat("threadtime");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800923 }
924 }
925
Mark Salyzynd2a03b52017-02-10 13:09:07 -0800926 if (forceFilters.size()) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700927 int err = android_log_addFilterString(logformat_.get(), forceFilters.c_str());
The Android Open Source Project190995d2009-03-03 19:32:55 -0800928 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800929 error(EXIT_FAILURE, 0, "Invalid filter expression in logcat args.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800930 }
Elliott Hughes442d8582018-06-15 15:16:20 -0700931 } else if (argc == optind) {
The Android Open Source Project190995d2009-03-03 19:32:55 -0800932 // Add from environment variable
Tom Cherryb1cf4282019-10-24 17:35:26 -0700933 const char* env_tags_orig = getenv("ANDROID_LOG_TAGS");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800934
Mark Salyzyne5f043c2017-03-01 08:30:06 -0800935 if (!!env_tags_orig) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700936 int err = android_log_addFilterString(logformat_.get(), env_tags_orig);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800937
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800938 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800939 error(EXIT_FAILURE, 0, "Invalid filter expression in ANDROID_LOG_TAGS.");
The Android Open Source Project190995d2009-03-03 19:32:55 -0800940 }
941 }
942 } else {
943 // Add from commandline
Elliott Hughes442d8582018-06-15 15:16:20 -0700944 for (int i = optind ; i < argc ; i++) {
Tom Cherryfb1373a2019-10-29 07:05:24 -0700945 int err = android_log_addFilterString(logformat_.get(), argv[i]);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -0800946 if (err < 0) {
Tom Cherry96840882019-12-06 10:25:37 -0800947 error(EXIT_FAILURE, 0, "Invalid filter expression '%s'.", argv[i]);
The Android Open Source Project190995d2009-03-03 19:32:55 -0800948 }
949 }
950 }
951
Tom Cherryf459c582019-11-14 08:56:39 -0800952 if (mode & ANDROID_LOG_PSTORE) {
Tom Cherryeb2258a2019-12-04 14:37:38 -0800953 if (output_file_name_) {
Tom Cherry96840882019-12-06 10:25:37 -0800954 error(EXIT_FAILURE, 0, "-c is ambiguous with both -f and -L specified.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800955 }
956 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry96840882019-12-06 10:25:37 -0800957 error(EXIT_FAILURE, 0, "-L is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800958 }
Tom Cherryf459c582019-11-14 08:56:39 -0800959 if (clearLog) {
960 unlink("/sys/fs/pstore/pmsg-ramoops-0");
961 return EXIT_SUCCESS;
962 }
Tom Cherryeb2258a2019-12-04 14:37:38 -0800963 }
964
965 if (output_file_name_) {
Tom Cherryf459c582019-11-14 08:56:39 -0800966 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry96840882019-12-06 10:25:37 -0800967 error(EXIT_FAILURE, 0, "-f is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryeb2258a2019-12-04 14:37:38 -0800968 }
969
970 if (clearLog || setId) {
971 int max_rotation_count_digits =
972 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
973
974 for (int i = max_rotated_logs_; i >= 0; --i) {
975 std::string file;
976
977 if (!i) {
978 file = output_file_name_;
979 } else {
980 file = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
981 }
982
983 int err = unlink(file.c_str());
984
985 if (err < 0 && errno != ENOENT) {
986 fprintf(stderr, "failed to delete log file '%s': %s\n", file.c_str(),
987 strerror(errno));
988 }
989 }
990 }
991
992 if (clearLog) {
993 return EXIT_SUCCESS;
Tom Cherryf459c582019-11-14 08:56:39 -0800994 }
995 }
996
Tom Cherryfb1373a2019-10-29 07:05:24 -0700997 std::unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{
998 nullptr, &android_logger_list_free};
Mark Salyzyn9addf592014-02-14 16:05:05 -0800999 if (tail_time != log_time::EPOCH) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001000 logger_list.reset(android_logger_list_alloc_time(mode, tail_time, pid));
Mark Salyzyn9addf592014-02-14 16:05:05 -08001001 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001002 logger_list.reset(android_logger_list_alloc(mode, tail_lines, pid));
Mark Salyzyn9addf592014-02-14 16:05:05 -08001003 }
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001004 // We have three orthogonal actions below to clear, set log size and
1005 // get log size. All sharing the same iteration loop.
Tom Cherryfb1373a2019-10-29 07:05:24 -07001006 std::vector<std::string> open_device_failures;
1007 std::vector<std::string> clear_failures;
1008 std::vector<std::string> set_size_failures;
1009 std::vector<std::string> get_size_failures;
1010
1011 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
1012 if (!(id_mask & (1 << i))) continue;
1013 const char* buffer_name = android_log_id_to_name(static_cast<log_id_t>(i));
1014
1015 auto logger = android_logger_open(logger_list.get(), static_cast<log_id_t>(i));
1016 if (logger == nullptr) {
1017 ReportErrorName(buffer_name, security_buffer_selected, &open_device_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001018 continue;
The Android Open Source Project190995d2009-03-03 19:32:55 -08001019 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001020
Tom Cherryeb2258a2019-12-04 14:37:38 -08001021 if (clearLog) {
1022 if (android_logger_clear(logger)) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001023 ReportErrorName(buffer_name, security_buffer_selected, &clear_failures);
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001024 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001025 }
1026
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001027 if (setLogSize) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001028 if (android_logger_set_log_size(logger, setLogSize)) {
1029 ReportErrorName(buffer_name, security_buffer_selected, &set_size_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001030 }
Mark Salyzync89839a2014-02-11 12:29:31 -08001031 }
1032
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001033 if (getLogSize) {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001034 long size = android_logger_get_log_size(logger);
1035 long readable = android_logger_get_log_readable_size(logger);
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001036
Tom Cherryfb1373a2019-10-29 07:05:24 -07001037 if (size < 0 || readable < 0) {
1038 ReportErrorName(buffer_name, security_buffer_selected, &get_size_failures);
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001039 } else {
Wei Wang8b584172018-09-05 11:05:57 -07001040 auto size_format = format_of_size(size);
1041 auto readable_format = format_of_size(readable);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001042 std::string str = android::base::StringPrintf(
Tom Cherryfb1373a2019-10-29 07:05:24 -07001043 "%s: ring buffer is %lu %sB (%lu %sB consumed),"
1044 " max entry is %d B, max payload is %d B\n",
1045 buffer_name, size_format.first, size_format.second, readable_format.first,
1046 readable_format.second, (int)LOGGER_ENTRY_MAX_LEN,
1047 (int)LOGGER_ENTRY_MAX_PAYLOAD);
Tom Cherryb1cf4282019-10-24 17:35:26 -07001048 TEMP_FAILURE_RETRY(write(output_fd_.get(), str.data(), str.length()));
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001049 }
Joe Onoratod23b9cf2010-02-26 10:04:23 -08001050 }
The Android Open Source Project190995d2009-03-03 19:32:55 -08001051 }
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001052
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001053 // report any errors in the above loop and exit
Tom Cherryfb1373a2019-10-29 07:05:24 -07001054 if (!open_device_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001055 error(EXIT_FAILURE, 0, "Unable to open log device%s '%s'.",
1056 open_device_failures.size() > 1 ? "s" : "", Join(open_device_failures, ",").c_str());
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001057 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001058 if (!clear_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001059 error(EXIT_FAILURE, 0, "failed to clear the '%s' log%s.", Join(clear_failures, ",").c_str(),
1060 clear_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001061 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001062 if (!set_size_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001063 error(EXIT_FAILURE, 0, "failed to set the '%s' log size%s.",
1064 Join(set_size_failures, ",").c_str(), set_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001065 }
Tom Cherryfb1373a2019-10-29 07:05:24 -07001066 if (!get_size_failures.empty()) {
Tom Cherry96840882019-12-06 10:25:37 -08001067 error(EXIT_FAILURE, 0, "failed to get the readable '%s' log size%s.",
1068 Join(get_size_failures, ",").c_str(), get_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn7ccdb902015-09-16 15:34:00 -07001069 }
The Android Open Source Project190995d2009-03-03 19:32:55 -08001070
Mark Salyzync89839a2014-02-11 12:29:31 -08001071 if (setPruneList) {
Traian Schiau9f978602015-04-10 15:51:39 +03001072 size_t len = strlen(setPruneList);
Tom Cherryc8c906e2019-12-06 11:01:51 -08001073 if (android_logger_set_prune_list(logger_list.get(), setPruneList, len)) {
1074 error(EXIT_FAILURE, 0, "Failed to set the prune list.");
Mark Salyzync89839a2014-02-11 12:29:31 -08001075 }
Tom Cherryb1cf4282019-10-24 17:35:26 -07001076 return EXIT_SUCCESS;
Mark Salyzync89839a2014-02-11 12:29:31 -08001077 }
1078
Mark Salyzync402bc72014-04-01 17:19:47 -07001079 if (printStatistics || getPruneList) {
Tom Cherryf30875b2019-12-06 13:33:11 -08001080 std::string buf(8192, '\0');
1081 size_t ret_length = 0;
1082 int retry = 32;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001083
Tom Cherryf30875b2019-12-06 13:33:11 -08001084 for (; retry >= 0; --retry) {
Mark Salyzync89839a2014-02-11 12:29:31 -08001085 if (getPruneList) {
Tom Cherryf30875b2019-12-06 13:33:11 -08001086 android_logger_get_prune_list(logger_list.get(), buf.data(), buf.size());
Mark Salyzync89839a2014-02-11 12:29:31 -08001087 } else {
Tom Cherryf30875b2019-12-06 13:33:11 -08001088 android_logger_get_statistics(logger_list.get(), buf.data(), buf.size());
Mark Salyzync89839a2014-02-11 12:29:31 -08001089 }
Tom Cherryf30875b2019-12-06 13:33:11 -08001090
1091 ret_length = atol(buf.c_str());
1092 if (ret_length < 3) {
1093 error(EXIT_FAILURE, 0, "Failed to read data.");
1094 }
1095
1096 if (ret_length < buf.size()) {
Mark Salyzynd774bce2014-02-06 14:48:50 -08001097 break;
1098 }
Tom Cherryf30875b2019-12-06 13:33:11 -08001099
1100 buf.resize(ret_length + 1);
Mark Salyzynd774bce2014-02-06 14:48:50 -08001101 }
1102
Tom Cherryf30875b2019-12-06 13:33:11 -08001103 if (retry < 0) {
Tom Cherry96840882019-12-06 10:25:37 -08001104 error(EXIT_FAILURE, 0, "Failed to read data.");
Mark Salyzynd774bce2014-02-06 14:48:50 -08001105 }
1106
Tom Cherryf30875b2019-12-06 13:33:11 -08001107 buf.resize(ret_length);
1108 if (buf.back() == '\f') {
1109 buf.pop_back();
Mark Salyzynd774bce2014-02-06 14:48:50 -08001110 }
1111
Tom Cherryf30875b2019-12-06 13:33:11 -08001112 // Remove the byte count prefix
1113 const char* cp = buf.c_str();
1114 while (isdigit(*cp)) ++cp;
1115 if (*cp == '\n') ++cp;
1116
1117 size_t len = strlen(cp);
Tom Cherryb1cf4282019-10-24 17:35:26 -07001118 TEMP_FAILURE_RETRY(write(output_fd_.get(), cp, len));
Tom Cherryb1cf4282019-10-24 17:35:26 -07001119 return EXIT_SUCCESS;
Mark Salyzynd774bce2014-02-06 14:48:50 -08001120 }
1121
Tom Cherryb1cf4282019-10-24 17:35:26 -07001122 if (getLogSize || setLogSize || clearLog) return EXIT_SUCCESS;
The Android Open Source Project190995d2009-03-03 19:32:55 -08001123
Tom Cherryb1cf4282019-10-24 17:35:26 -07001124 SetupOutputAndSchedulingPolicy(!(mode & ANDROID_LOG_NONBLOCK));
The Android Open Source Project190995d2009-03-03 19:32:55 -08001125
Tom Cherryb1cf4282019-10-24 17:35:26 -07001126 while (!max_count_ || print_count_ < max_count_) {
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001127 struct log_msg log_msg;
Tom Cherryfb1373a2019-10-29 07:05:24 -07001128 int ret = android_logger_list_read(logger_list.get(), &log_msg);
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001129 if (!ret) {
Tom Cherry96840882019-12-06 10:25:37 -08001130 error(EXIT_FAILURE, 0, R"init(Unexpected EOF!
Tom Cherrya59bde42019-11-21 10:31:06 -08001131
1132This means that either logd crashed, or more likely, this instance of logcat was unable to read log
1133messages as quickly as they were being produced.
1134
Tom Cherry96840882019-12-06 10:25:37 -08001135If you have enabled significant logging, look into using the -G option to increase log buffer sizes.)init");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001136 }
1137
1138 if (ret < 0) {
Mark Salyzyne5f043c2017-03-01 08:30:06 -08001139 if (ret == -EAGAIN) break;
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001140
1141 if (ret == -EIO) {
Tom Cherry96840882019-12-06 10:25:37 -08001142 error(EXIT_FAILURE, 0, "Unexpected EOF!");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001143 }
1144 if (ret == -EINVAL) {
Tom Cherry96840882019-12-06 10:25:37 -08001145 error(EXIT_FAILURE, 0, "Unexpected length.");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001146 }
Tom Cherry96840882019-12-06 10:25:37 -08001147 error(EXIT_FAILURE, errno, "Logcat read failure");
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001148 }
1149
Tom Cherryfb1373a2019-10-29 07:05:24 -07001150 if (log_msg.id() > LOG_ID_MAX) {
Tom Cherry96840882019-12-06 10:25:37 -08001151 error(EXIT_FAILURE, 0, "Unexpected log id (%d) over LOG_ID_MAX (%d).", log_msg.id(),
1152 LOG_ID_MAX);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001153 }
1154
Tom Cherryfb1373a2019-10-29 07:05:24 -07001155 PrintDividers(log_msg.id(), printDividers);
1156
Tom Cherryb1cf4282019-10-24 17:35:26 -07001157 if (print_binary_) {
1158 TEMP_FAILURE_RETRY(write(output_fd_.get(), &log_msg, log_msg.len()));
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001159 } else {
Tom Cherryfb1373a2019-10-29 07:05:24 -07001160 ProcessBuffer(&log_msg);
Mark Salyzyn2a8a6aa2013-11-22 10:55:48 -08001161 }
1162 }
Tom Cherryb1cf4282019-10-24 17:35:26 -07001163 return EXIT_SUCCESS;
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001164}
1165
Tom Cherryd8ea11f2019-10-30 13:51:03 -07001166int main(int argc, char** argv) {
Tom Cherryb1cf4282019-10-24 17:35:26 -07001167 Logcat logcat;
1168 return logcat.Run(argc, argv);
Mark Salyzyn2f1a9a42017-02-10 13:09:07 -08001169}