blob: b065855c53bb1fcef64bd4ffcf39a347bf06f5e2 [file] [log] [blame]
Mark Salyzyn5f606602017-02-10 13:09:07 -08001/*
Mark Salyzync0cf90d2017-02-10 13:09:07 -08002 * Copyright (C) 2006-2017 The Android Open Source Project
Mark Salyzyn5f606602017-02-10 13:09:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080016
Mark Salyzyn65772ca2013-12-13 11:10:11 -080017#include <ctype.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070018#include <dirent.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080019#include <errno.h>
Tom Cherry72a4e082019-12-06 10:25:37 -080020#include <error.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080021#include <fcntl.h>
Elliott Hughes61b580e2018-06-15 15:16:20 -070022#include <getopt.h>
Aristidis Papaioannoueba73442014-10-16 22:19:55 -070023#include <math.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070024#include <sched.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070025#include <stdarg.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080026#include <stdio.h>
27#include <stdlib.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080028#include <string.h>
Traian Schiau59763032015-04-10 15:51:39 +030029#include <sys/cdefs.h>
Jaegeuk Kim5327d932019-07-04 18:09:38 -070030#include <sys/ioctl.h>
Riley Andrewsaede9892015-06-08 23:36:34 -070031#include <sys/resource.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080032#include <sys/stat.h>
Mark Salyzynf3555d92015-05-27 07:39:56 -070033#include <sys/types.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070034#include <time.h>
35#include <unistd.h>
Mark Salyzyn65772ca2013-12-13 11:10:11 -080036
Mark Salyzynf3555d92015-05-27 07:39:56 -070037#include <memory>
Elliott Hughesaddd8522019-08-08 08:53:59 -070038#include <regex>
Mark Salyzynf3555d92015-05-27 07:39:56 -070039#include <string>
Wei Wangc27d4812018-09-05 11:05:57 -070040#include <utility>
Mark Salyzyn1d6928b2017-02-10 13:09:07 -080041#include <vector>
Mark Salyzynf3555d92015-05-27 07:39:56 -070042
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/file.h>
Tom Cherryd162f142019-10-24 17:35:26 -070044#include <android-base/macros.h>
Tom Cherry6f061e82019-10-29 07:05:24 -070045#include <android-base/parseint.h>
bohu94aab862017-02-21 14:31:19 -080046#include <android-base/properties.h>
Mark Salyzyn5b1a5382016-08-03 14:20:41 -070047#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080048#include <android-base/strings.h>
Tom Cherryd162f142019-10-24 17:35:26 -070049#include <android-base/unique_fd.h>
Tom Cherry6f061e82019-10-29 07:05:24 -070050#include <android/log.h>
Mark Salyzyn3ef730c2015-06-02 07:57:16 -070051#include <log/event_tag_map.h>
Tom Cherry6f061e82019-10-29 07:05:24 -070052#include <log/log_id.h>
Colin Cross9227bd32013-07-23 16:59:20 -070053#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070054#include <private/android_logger.h>
Suren Baghdasaryan02843332018-12-21 12:30:16 -080055#include <processgroup/sched_policy.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080056#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058#define DEFAULT_MAX_ROTATED_LOGS 4
59
Tom Cherry6f061e82019-10-29 07:05:24 -070060using android::base::Join;
61using android::base::ParseByteCount;
62using android::base::ParseUint;
63using android::base::Split;
Tom Cherryd162f142019-10-24 17:35:26 -070064using android::base::StringPrintf;
65
Tom Cherryd162f142019-10-24 17:35:26 -070066class Logcat {
67 public:
Tom Cherryd162f142019-10-24 17:35:26 -070068 int Run(int argc, char** argv);
Mark Salyzync0cf90d2017-02-10 13:09:07 -080069
Tom Cherryd162f142019-10-24 17:35:26 -070070 private:
71 void RotateLogs();
Tom Cherry6f061e82019-10-29 07:05:24 -070072 void ProcessBuffer(struct log_msg* buf);
73 void PrintDividers(log_id_t log_id, bool print_dividers);
Tom Cherryd162f142019-10-24 17:35:26 -070074 void SetupOutputAndSchedulingPolicy(bool blocking);
75 int SetLogFormat(const char* format_string);
76
Tom Cherry6f061e82019-10-29 07:05:24 -070077 // Used for all options
Tom Cherryd162f142019-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 Cherry6f061e82019-10-29 07:05:24 -070081
82 // For logging to a file and log rotation
Tom Cherryd162f142019-10-24 17:35:26 -070083 const char* output_file_name_ = nullptr;
Tom Cherry6f061e82019-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 Cherryd162f142019-10-24 17:35:26 -070086 size_t out_byte_count_ = 0;
Tom Cherry6f061e82019-10-29 07:05:24 -070087
88 // For binary log buffers
Tom Cherryd162f142019-10-24 17:35:26 -070089 int print_binary_ = 0;
Tom Cherryd162f142019-10-24 17:35:26 -070090 std::unique_ptr<EventTagMap, decltype(&android_closeEventTagMap)> event_tag_map_{
91 nullptr, &android_closeEventTagMap};
Tom Cherryd162f142019-10-24 17:35:26 -070092 bool has_opened_event_tag_map_ = false;
Tom Cherry6f061e82019-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 Salyzync0cf90d2017-02-10 13:09:07 -0800105};
106
Jaegeuk Kim5327d932019-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) {
Mike Maa7fb0952020-01-17 18:01:03 -0800113 int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP);
Jaegeuk Kim5327d932019-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 Projectdd7bc332009-03-03 19:32:55 -0800123}
124
Tom Cherryd162f142019-10-24 17:35:26 -0700125void Logcat::RotateLogs() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126 // Can't rotate logs if we're not outputting to a file
Tom Cherryd162f142019-10-24 17:35:26 -0700127 if (!output_file_name_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128
Tom Cherryd162f142019-10-24 17:35:26 -0700129 output_fd_.reset();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800130
Mark Salyzyn5f606602017-02-10 13:09:07 -0800131 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800132 // maxRotatedLogs in decimal. eg:
133 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800134 // -> log10(30) == 1.477
135 // -> maxRotationCountDigits == 2
Tom Cherryd162f142019-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 Papaioannoueba73442014-10-16 22:19:55 -0700138
Tom Cherryd162f142019-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 Projectdd7bc332009-03-03 19:32:55 -0800142
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700143 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800144 if (!(i - 1)) {
Tom Cherryd162f142019-10-24 17:35:26 -0700145 file0 = output_file_name_;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146 } else {
Tom Cherryd162f142019-10-24 17:35:26 -0700147 file0 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148 }
149
Mark Salyzynde022a82017-03-01 08:30:06 -0800150 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300151 perror("while rotating log files");
152 break;
153 }
154
Tom Cherryd162f142019-10-24 17:35:26 -0700155 int err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800156
157 if (err < 0 && errno != ENOENT) {
158 perror("while rotating log files");
159 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160 }
161
Tom Cherryd162f142019-10-24 17:35:26 -0700162 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163
Tom Cherryd162f142019-10-24 17:35:26 -0700164 if (!output_fd_.ok()) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800165 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800166 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167
Tom Cherryd162f142019-10-24 17:35:26 -0700168 out_byte_count_ = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800169}
170
Tom Cherry6f061e82019-10-29 07:05:24 -0700171void Logcat::ProcessBuffer(struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700172 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800173 int err;
174 AndroidLogEntry entry;
175 char binaryMsgBuf[1024];
176
Tom Cherry6f061e82019-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 Cherryd162f142019-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 Salyzyn9421b0c2015-02-26 14:33:35 -0800184 }
Tom Cherryd162f142019-10-24 17:35:26 -0700185 err = android_log_processBinaryLogBuffer(&buf->entry, &entry, event_tag_map_.get(),
Tom Cherry441054a2019-10-15 16:53:11 -0700186 binaryMsgBuf, sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800187 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188 // entry.priority, entry.messageLen, entry.message);
189 } else {
Tom Cherry441054a2019-10-15 16:53:11 -0700190 err = android_log_processLogBuffer(&buf->entry, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800191 }
Tom Cherryd162f142019-10-24 17:35:26 -0700192 if (err < 0 && !debug_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800193
Tom Cherryd162f142019-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 Onoratoe2bf2ea2010-03-01 09:11:54 -0800198
Tom Cherryd162f142019-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 Dahlin6ac498d2016-03-17 14:04:52 -0700202
Mark Salyzync9202772016-03-30 09:38:31 -0700203 if (bytesWritten < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800204 error(EXIT_FAILURE, 0, "Output error.");
Mark Salyzync9202772016-03-30 09:38:31 -0700205 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800206 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207 }
208
Tom Cherryd162f142019-10-24 17:35:26 -0700209 out_byte_count_ += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210
Tom Cherryd162f142019-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 Projectdd7bc332009-03-03 19:32:55 -0800213 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214}
215
Tom Cherry6f061e82019-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 Onorato6fa09a02010-02-26 10:04:23 -0800219 }
Tom Cherry6f061e82019-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 Cherry72a4e082019-12-06 10:25:37 -0800224 error(EXIT_FAILURE, errno, "Output error");
Tom Cherry6f061e82019-10-29 07:05:24 -0700225 }
226 }
227 last_printed_id_ = log_id;
228 printed_start_[log_id] = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800229}
230
Tom Cherryd162f142019-10-24 17:35:26 -0700231void Logcat::SetupOutputAndSchedulingPolicy(bool blocking) {
232 if (!output_file_name_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233
Mark Salyzynad5e4112016-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 Cherryd162f142019-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 Salyzyn3ef730c2015-06-02 07:57:16 -0700239 }
240
Tom Cherryd162f142019-10-24 17:35:26 -0700241 struct sched_param param = {};
Mark Salyzyn5f606602017-02-10 13:09:07 -0800242 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700243 fprintf(stderr, "failed to set to batch scheduler\n");
244 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800245
Tom Cherryd162f142019-10-24 17:35:26 -0700246 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
247 fprintf(stderr, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700248 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700250
Tom Cherryd162f142019-10-24 17:35:26 -0700251 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
Mark Salyzynad5e4112016-08-04 07:53:52 -0700252
Tom Cherryd162f142019-10-24 17:35:26 -0700253 if (!output_fd_.ok()) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800254 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700255 }
256
257 struct stat statbuf;
Tom Cherryd162f142019-10-24 17:35:26 -0700258 if (fstat(output_fd_.get(), &statbuf) == -1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800259 error(EXIT_FAILURE, errno, "Couldn't get output file stat");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700260 }
261
Mark Salyzyn5f606602017-02-10 13:09:07 -0800262 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800263 error(EXIT_FAILURE, 0, "Invalid output file stat.");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700264 }
265
Tom Cherryd162f142019-10-24 17:35:26 -0700266 out_byte_count_ = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800267}
268
Mark Salyzyn5f606602017-02-10 13:09:07 -0800269// clang-format off
Tom Cherryd162f142019-10-24 17:35:26 -0700270static void show_help() {
271 const char* cmd = getprogname();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272
Tom Cherryd162f142019-10-24 17:35:26 -0700273 fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800274
Tom Cherry41697322019-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 Projectdd7bc332009-03-03 19:32:55 -0800347
Tom Cherryd162f142019-10-24 17:35:26 -0700348 fprintf(stderr, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-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 Salyzynbba894a2015-03-09 09:32:56 -0700351 " V Verbose (default for <tag>)\n"
352 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800353 " I Info\n"
354 " W Warn\n"
355 " E Error\n"
356 " F Fatal\n"
Mark Salyzynbba894a2015-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 Salyzyn649fc602014-09-16 09:15:15 -0700363 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364}
365
Tom Cherryd162f142019-10-24 17:35:26 -0700366static void show_format_help() {
367 fprintf(stderr,
Mark Salyzyn4fd05072016-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 Salyzync74f8d92017-05-15 13:40:33 -0700379 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn4fd05072016-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 Salyzyn5f606602017-02-10 13:09:07 -0800399// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700400
Tom Cherryd162f142019-10-24 17:35:26 -0700401int Logcat::SetLogFormat(const char* format_string) {
402 AndroidLogPrintFormat format = android_log_formatFromString(format_string);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800403
Mark Salyzynde022a82017-03-01 08:30:06 -0800404 // invalid string?
405 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406
Tom Cherryd162f142019-10-24 17:35:26 -0700407 return android_log_setPrintFormat(logformat_.get(), format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800408}
409
Wei Wangc27d4812018-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 Salyzyn671e3432014-05-06 07:34:59 -0700413 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800414 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
415 value /= 1024, ++i)
416 ;
Wei Wangc27d4812018-09-05 11:05:57 -0700417 return std::make_pair(value, multipliers[i]);
Mark Salyzyn671e3432014-05-06 07:34:59 -0700418}
419
Mark Salyzyn5f606602017-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 Salyzynde022a82017-03-01 08:30:06 -0800422 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700423 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800424 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700425 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700426}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700427
Mark Salyzyn31961062016-08-04 07:43:46 -0700428// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyne9ade172017-03-02 15:09:41 -0800429static log_time lastLogTime(const char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700430 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800431 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700432
Mark Salyzynf3555d92015-05-27 07:39:56 -0700433 std::string directory;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800434 const char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700435 if (!file) {
436 directory = ".";
437 file = outputFileName;
438 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800439 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700440 ++file;
441 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700442
Mark Salyzyn5f606602017-02-10 13:09:07 -0800443 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
444 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800445 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700446
Mark Salyzyn31961062016-08-04 07:43:46 -0700447 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700448
Mark Salyzynf3555d92015-05-27 07:39:56 -0700449 size_t len = strlen(file);
450 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800451 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700452
Mark Salyzynde022a82017-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 Salyzyn5f606602017-02-10 13:09:07 -0800455 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800456 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-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 Salyzynde022a82017-03-01 08:30:06 -0800464 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-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 Salyzyn5f606602017-02-10 13:09:07 -0800469 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800470 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-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 Salyzynde022a82017-03-01 08:30:06 -0800488 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700489 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800490 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-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 Cherry6f061e82019-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 Salyzyn26a1fac2017-01-20 14:07:29 -0800501 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800502}
Traian Schiau59763032015-04-10 15:51:39 +0300503
Tom Cherryd162f142019-10-24 17:35:26 -0700504int Logcat::Run(int argc, char** argv) {
Mark Salyzynb45a1752017-02-28 09:20:31 -0800505 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800506 bool clearLog = false;
Tom Cherry6f061e82019-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 Salyzyn26a1fac2017-01-20 14:07:29 -0800509 bool getLogSize = false;
510 bool getPruneList = false;
511 bool printStatistics = false;
512 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800513 unsigned long setLogSize = 0;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800514 const char* setPruneList = nullptr;
515 const char* setId = nullptr;
Tom Cherry907b2d02020-03-23 13:40:10 -0700516 int mode = 0;
Mark Salyzynf3290292017-02-10 13:09:07 -0800517 std::string forceFilters;
Traian Schiau59763032015-04-10 15:51:39 +0300518 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800519 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700520 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700521 bool got_t = false;
Tom Cherry6f061e82019-10-29 07:05:24 -0700522 unsigned id_mask = 0;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800523
Mark Salyzynde022a82017-03-01 08:30:06 -0800524 if (argc == 2 && !strcmp(argv[1], "--help")) {
Tom Cherryd162f142019-10-24 17:35:26 -0700525 show_help();
526 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800527 }
528
Mark Salyzynb45a1752017-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 Hughes61b580e2018-06-15 15:16:20 -0700533 optind = 0;
534 while (true) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700535 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700536 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700537 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800538 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700539 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800540 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700541 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800542 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700543 static const struct option long_options[] = {
Mark Salyzynde022a82017-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 Salyzync18c2132016-04-01 07:52:20 -0700552 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800553 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700554 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800555 { "head", required_argument, nullptr, 'm' },
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700556 { "help", no_argument, nullptr, 'h' },
Mark Salyzynde022a82017-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 Salyzynd85f6462016-03-30 09:15:09 -0700567 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800568 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800569 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800570 { wrap_str, optional_argument, nullptr, 0 },
571 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700572 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800573 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700574
Elliott Hughes61b580e2018-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 Projectdd7bc332009-03-03 19:32:55 -0800578
Elliott Hughes61b580e2018-06-15 15:16:20 -0700579 switch (c) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700580 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700581 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700582 if (long_options[option_index].name == pid_str) {
Steven Morelandb0e867a2019-08-02 10:13:57 -0700583 if (pid != 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800584 error(EXIT_FAILURE, 0, "Only one --pid argument can be provided.");
Steven Morelandb0e867a2019-08-02 10:13:57 -0700585 }
586
Tom Cherry6f061e82019-10-29 07:05:24 -0700587 if (!ParseUint(optarg, &pid) || pid < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800588 error(EXIT_FAILURE, 0, "%s %s out of range.",
589 long_options[option_index].name, optarg);
Kristian Monsen562e5132015-06-05 14:10:12 -0700590 }
591 break;
592 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800593 if (long_options[option_index].name == wrap_str) {
Tom Cherry907b2d02020-03-23 13:40:10 -0700594 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_NONBLOCK;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800595 // ToDo: implement API that supports setting a wrap timeout
596 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Tom Cherry6f061e82019-10-29 07:05:24 -0700597 if (optarg && (!ParseUint(optarg, &dummy) || dummy < 1)) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800598 error(EXIT_FAILURE, 0, "%s %s out of range.",
599 long_options[option_index].name, optarg);
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800600 }
Tom Cherryd162f142019-10-24 17:35:26 -0700601 if (dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) {
602 fprintf(stderr, "WARNING: %s %u seconds, ignoring %zu\n",
603 long_options[option_index].name, ANDROID_LOG_WRAP_DEFAULT_TIMEOUT,
604 dummy);
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800605 }
606 break;
607 }
Mark Salyzync9202772016-03-30 09:38:31 -0700608 if (long_options[option_index].name == print_str) {
Tom Cherryd162f142019-10-24 17:35:26 -0700609 print_it_anyways_ = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700610 break;
611 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800612 if (long_options[option_index].name == debug_str) {
Tom Cherryd162f142019-10-24 17:35:26 -0700613 debug_ = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800614 break;
615 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700616 if (long_options[option_index].name == id_str) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700617 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700618 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800619 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700620
Mark Salyzyn95132e92013-11-22 10:55:48 -0800621 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 // default to all silent
Tom Cherryd162f142019-10-24 17:35:26 -0700623 android_log_addFilterRule(logformat_.get(), "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800624 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800625
626 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800627 clearLog = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800628 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800630 case 'L':
Tom Cherry907b2d02020-03-23 13:40:10 -0700631 mode |= ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800632 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800633
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800634 case 'd':
Tom Cherry907b2d02020-03-23 13:40:10 -0700635 mode |= ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800636 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800638 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700639 got_t = true;
Tom Cherry907b2d02020-03-23 13:40:10 -0700640 mode |= ANDROID_LOG_NONBLOCK;
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700641 FALLTHROUGH_INTENDED;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800642 case 'T':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700643 if (strspn(optarg, "0123456789") != strlen(optarg)) {
644 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800645 if (!cp) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800646 error(EXIT_FAILURE, 0, "-%c '%s' not in time format.", c, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800647 }
648 if (*cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700649 char ch = *cp;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800650 *cp = '\0';
Tom Cherry72a4e082019-12-06 10:25:37 -0800651 fprintf(stderr, "WARNING: -%c '%s' '%c%s' time truncated\n", c, optarg, ch,
652 cp + 1);
Elliott Hughes61b580e2018-06-15 15:16:20 -0700653 *cp = ch;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800654 }
655 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -0700656 if (!ParseUint(optarg, &tail_lines) || tail_lines < 1) {
Tom Cherryd162f142019-10-24 17:35:26 -0700657 fprintf(stderr, "WARNING: -%c %s invalid, setting to 1\n", c, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800658 tail_lines = 1;
659 }
660 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800661 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800662
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800663 case 'D':
664 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800665 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800666
Casey Dahlindc42a872016-03-17 16:18:55 -0700667 case 'e':
Tom Cherryd162f142019-10-24 17:35:26 -0700668 regex_.reset(new std::regex(optarg));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800669 break;
Casey Dahlindc42a872016-03-17 16:18:55 -0700670
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700671 case 'm': {
Tom Cherry6f061e82019-10-29 07:05:24 -0700672 if (!ParseUint(optarg, &max_count_) || max_count_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800673 error(EXIT_FAILURE, 0, "-%c '%s' isn't an integer greater than zero.", c,
674 optarg);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700675 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800676 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700677
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678 case 'g':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700679 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800680 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -0800681 break;
682 }
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700683 FALLTHROUGH_INTENDED;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800684
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800685 case 'G': {
Tom Cherry6f061e82019-10-29 07:05:24 -0700686 if (!ParseByteCount(optarg, &setLogSize) || setLogSize < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800687 error(EXIT_FAILURE, 0, "-G must be specified as <num><multiplier>.");
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800688 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800689 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800690
691 case 'p':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700692 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800693 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -0800694 break;
695 }
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700696 FALLTHROUGH_INTENDED;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800697
698 case 'P':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700699 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800700 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800701
Tom Cherry6f061e82019-10-29 07:05:24 -0700702 case 'b':
703 for (const auto& buffer : Split(optarg, delimiters)) {
704 if (buffer == "default") {
705 id_mask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH);
706 } else if (buffer == "all") {
707 id_mask = -1;
Mark Salyzyn45177732016-04-11 14:03:48 -0700708 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -0700709 log_id_t log_id = android_name_to_log_id(buffer.c_str());
710 if (log_id >= LOG_ID_MAX) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800711 error(EXIT_FAILURE, 0, "Unknown buffer '%s' listed for -b.",
712 buffer.c_str());
Mark Salyzyn34facab2014-02-06 14:48:50 -0800713 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700714 if (log_id == LOG_ID_SECURITY) {
715 security_buffer_selected = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800716 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700717 id_mask |= (1 << log_id);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800718 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800719 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700720 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721
722 case 'B':
Tom Cherryd162f142019-10-24 17:35:26 -0700723 print_binary_ = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800724 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800725
726 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -0800727 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700728 tail_time = lastLogTime(optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700729 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730 // redirect output to a file
Tom Cherryd162f142019-10-24 17:35:26 -0700731 output_file_name_ = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800732 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700734 case 'r':
Tom Cherry6f061e82019-10-29 07:05:24 -0700735 if (!ParseUint(optarg, &log_rotate_size_kb_) || log_rotate_size_kb_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800736 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -r.", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800737 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800738 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700740 case 'n':
Tom Cherry6f061e82019-10-29 07:05:24 -0700741 if (!ParseUint(optarg, &max_rotated_logs_) || max_rotated_logs_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800742 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -n.", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800744 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745
Tom Cherry6f061e82019-10-29 07:05:24 -0700746 case 'v':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700747 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Tom Cherryd162f142019-10-24 17:35:26 -0700748 show_format_help();
749 return EXIT_SUCCESS;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700750 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700751 for (const auto& arg : Split(optarg, delimiters)) {
752 int err = SetLogFormat(arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800753 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800754 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -v.", arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800755 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800756 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700758 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800759
760 case 'Q':
bohu94aab862017-02-21 14:31:19 -0800761#define LOGCAT_FILTER "androidboot.logcat="
762#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -0800763#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -0800764#define QEMU_PROPERTY "ro.kernel.qemu"
765#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -0800766 // This is a *hidden* option used to start a version of logcat
767 // in an emulated device only. It basically looks for
768 // androidboot.logcat= on the kernel command line. If
769 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -0800770 // run the program. The logcat output will go to consolepipe if
771 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
772 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800773 {
bohu94aab862017-02-21 14:31:19 -0800774 // if not in emulator, exit quietly
775 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Tom Cherryd162f142019-10-24 17:35:26 -0700776 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800777 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800778
bohu94aab862017-02-21 14:31:19 -0800779 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
780 if (cmdline.empty()) {
781 android::base::ReadFileToString("/proc/cmdline", &cmdline);
782 }
783
784 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
785 // if nothing found or invalid filters, exit quietly
786 if (!logcatFilter) {
Tom Cherryd162f142019-10-24 17:35:26 -0700787 return EXIT_SUCCESS;
bohu94aab862017-02-21 14:31:19 -0800788 }
789
790 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -0800791 const char* q = strpbrk(p, " \t\n\r");
792 if (!q) q = p + strlen(p);
793 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794
bohu94aab862017-02-21 14:31:19 -0800795 // redirect our output to the emulator console pipe or console
796 const char* consolePipe =
797 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -0800798 const char* console =
799 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800800
bohu94aab862017-02-21 14:31:19 -0800801 if (consolePipe) {
802 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
803 } else if (console) {
804 p = console + strlen(CONSOLE_OPTION);
805 } else {
Tom Cherryd162f142019-10-24 17:35:26 -0700806 return EXIT_FAILURE;
bohu94aab862017-02-21 14:31:19 -0800807 }
808
Mark Salyzynf3290292017-02-10 13:09:07 -0800809 q = strpbrk(p, " \t\n\r");
810 int len = q ? q - p : strlen(p);
811 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -0800812 std::string pipePurpose("pipe:logcat");
813 if (consolePipe) {
814 // example: "qemu_pipe,pipe:logcat"
815 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
816 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -0700817 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -0800818 if (pos != std::string::npos) {
819 pipePurpose = devname.substr(pos + 1);
820 devname = devname.substr(0, pos);
821 }
822 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800823
Tom Cherryd162f142019-10-24 17:35:26 -0700824 fprintf(stderr, "logcat using %s\n", devname.c_str());
825
826 int fd = open(devname.c_str(), O_WRONLY | O_CLOEXEC);
827 if (fd < 0) {
828 break;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800829 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800830
bohu94aab862017-02-21 14:31:19 -0800831 if (consolePipe) {
832 // need the trailing '\0'
Tom Cherryd162f142019-10-24 17:35:26 -0700833 if (!android::base::WriteFully(fd, pipePurpose.c_str(),
834 pipePurpose.size() + 1)) {
835 close(fd);
836 return EXIT_FAILURE;
bohu94aab862017-02-21 14:31:19 -0800837 }
838 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800839 // close output and error channels, replace with console
Erwin Jansen4f138b22019-11-27 12:58:58 -0800840 dup2(fd, output_fd_.get());
Tom Cherryd162f142019-10-24 17:35:26 -0700841 dup2(fd, STDERR_FILENO);
842 close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843 }
844 break;
845
Mark Salyzyn34facab2014-02-06 14:48:50 -0800846 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800847 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800848 break;
849
Traian Schiau59763032015-04-10 15:51:39 +0300850 case ':':
Tom Cherry72a4e082019-12-06 10:25:37 -0800851 error(EXIT_FAILURE, 0, "Option '%s' needs an argument.", argv[optind - 1]);
852 break;
Traian Schiau59763032015-04-10 15:51:39 +0300853
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700854 case 'h':
Tom Cherryd162f142019-10-24 17:35:26 -0700855 show_help();
856 show_format_help();
857 return EXIT_SUCCESS;
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700858
Tom Cherry72a4e082019-12-06 10:25:37 -0800859 case '?':
860 error(EXIT_FAILURE, 0, "Unknown option '%s'.", argv[optind - 1]);
861 break;
862
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 default:
Tom Cherry72a4e082019-12-06 10:25:37 -0800864 error(EXIT_FAILURE, 0, "Unknown getopt_long() result '%c'.", c);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 }
866 }
867
Tom Cherryd162f142019-10-24 17:35:26 -0700868 if (max_count_ && got_t) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800869 error(EXIT_FAILURE, 0, "Cannot use -m (--max-count) and -t together.");
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700870 }
Tom Cherryd162f142019-10-24 17:35:26 -0700871 if (print_it_anyways_ && (!regex_ || !max_count_)) {
Mark Salyzync9202772016-03-30 09:38:31 -0700872 // One day it would be nice if --print -v color and --regex <expr>
873 // could play with each other and show regex highlighted content.
Tom Cherryd162f142019-10-24 17:35:26 -0700874 fprintf(stderr,
875 "WARNING: "
876 "--print ignored, to be used in combination with\n"
877 " "
878 "--regex <expr> and --max-count <N>\n");
879 print_it_anyways_ = false;
Mark Salyzync9202772016-03-30 09:38:31 -0700880 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700881
Tom Cherry6f061e82019-10-29 07:05:24 -0700882 // If no buffers are specified, default to using these buffers.
883 if (id_mask == 0) {
884 id_mask = (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH) |
885 (1 << LOG_ID_KERNEL);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800886 }
887
Tom Cherryd162f142019-10-24 17:35:26 -0700888 if (log_rotate_size_kb_ != 0 && !output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800889 error(EXIT_FAILURE, 0, "-r requires -f as well.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800890 }
891
Tom Cherryd162f142019-10-24 17:35:26 -0700892 if (setId != 0) {
893 if (!output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800894 error(EXIT_FAILURE, 0, "--id='%s' requires -f as well.", setId);
Mark Salyzyn02687e72016-08-03 14:20:41 -0700895 }
896
Tom Cherryd162f142019-10-24 17:35:26 -0700897 std::string file_name = StringPrintf("%s.id", output_file_name_);
Mark Salyzyn02687e72016-08-03 14:20:41 -0700898 std::string file;
899 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800900 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
901 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -0800902 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700903 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904
Mark Salyzynde022a82017-03-01 08:30:06 -0800905 if (!hasSetLogFormat) {
Tom Cherryd162f142019-10-24 17:35:26 -0700906 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800907
Mark Salyzynde022a82017-03-01 08:30:06 -0800908 if (!!logFormat) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700909 for (const auto& arg : Split(logFormat, delimiters)) {
910 int err = SetLogFormat(arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800911 // environment should not cause crash of logcat
Tom Cherryd162f142019-10-24 17:35:26 -0700912 if (err < 0) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700913 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800914 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800915 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800916 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800917 }
918 if (!hasSetLogFormat) {
Tom Cherryd162f142019-10-24 17:35:26 -0700919 SetLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800920 }
921 }
922
Mark Salyzynf3290292017-02-10 13:09:07 -0800923 if (forceFilters.size()) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700924 int err = android_log_addFilterString(logformat_.get(), forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800925 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800926 error(EXIT_FAILURE, 0, "Invalid filter expression in logcat args.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800927 }
Elliott Hughes61b580e2018-06-15 15:16:20 -0700928 } else if (argc == optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800929 // Add from environment variable
Tom Cherryd162f142019-10-24 17:35:26 -0700930 const char* env_tags_orig = getenv("ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800931
Mark Salyzynde022a82017-03-01 08:30:06 -0800932 if (!!env_tags_orig) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700933 int err = android_log_addFilterString(logformat_.get(), env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800934
Mark Salyzyn95132e92013-11-22 10:55:48 -0800935 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800936 error(EXIT_FAILURE, 0, "Invalid filter expression in ANDROID_LOG_TAGS.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937 }
938 }
939 } else {
940 // Add from commandline
Elliott Hughes61b580e2018-06-15 15:16:20 -0700941 for (int i = optind ; i < argc ; i++) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700942 int err = android_log_addFilterString(logformat_.get(), argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -0800943 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800944 error(EXIT_FAILURE, 0, "Invalid filter expression '%s'.", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800945 }
946 }
947 }
948
Tom Cherry9156c532019-11-14 08:56:39 -0800949 if (mode & ANDROID_LOG_PSTORE) {
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800950 if (output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800951 error(EXIT_FAILURE, 0, "-c is ambiguous with both -f and -L specified.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800952 }
953 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800954 error(EXIT_FAILURE, 0, "-L is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800955 }
Tom Cherry9156c532019-11-14 08:56:39 -0800956 if (clearLog) {
957 unlink("/sys/fs/pstore/pmsg-ramoops-0");
958 return EXIT_SUCCESS;
959 }
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800960 }
961
962 if (output_file_name_) {
Tom Cherry9156c532019-11-14 08:56:39 -0800963 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800964 error(EXIT_FAILURE, 0, "-f is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800965 }
966
967 if (clearLog || setId) {
968 int max_rotation_count_digits =
969 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
970
971 for (int i = max_rotated_logs_; i >= 0; --i) {
972 std::string file;
973
974 if (!i) {
975 file = output_file_name_;
976 } else {
977 file = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
978 }
979
980 int err = unlink(file.c_str());
981
982 if (err < 0 && errno != ENOENT) {
983 fprintf(stderr, "failed to delete log file '%s': %s\n", file.c_str(),
984 strerror(errno));
985 }
986 }
987 }
988
989 if (clearLog) {
990 return EXIT_SUCCESS;
Tom Cherry9156c532019-11-14 08:56:39 -0800991 }
992 }
993
Tom Cherry6f061e82019-10-29 07:05:24 -0700994 std::unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{
995 nullptr, &android_logger_list_free};
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800996 if (tail_time != log_time::EPOCH) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700997 logger_list.reset(android_logger_list_alloc_time(mode, tail_time, pid));
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800998 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -0700999 logger_list.reset(android_logger_list_alloc(mode, tail_lines, pid));
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001000 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001001 // We have three orthogonal actions below to clear, set log size and
1002 // get log size. All sharing the same iteration loop.
Tom Cherry6f061e82019-10-29 07:05:24 -07001003 std::vector<std::string> open_device_failures;
1004 std::vector<std::string> clear_failures;
1005 std::vector<std::string> set_size_failures;
1006 std::vector<std::string> get_size_failures;
1007
1008 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
1009 if (!(id_mask & (1 << i))) continue;
1010 const char* buffer_name = android_log_id_to_name(static_cast<log_id_t>(i));
1011
1012 auto logger = android_logger_open(logger_list.get(), static_cast<log_id_t>(i));
1013 if (logger == nullptr) {
1014 ReportErrorName(buffer_name, security_buffer_selected, &open_device_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001015 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001016 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001017
Tom Cherryc30a3ee2019-12-04 14:37:38 -08001018 if (clearLog) {
1019 if (android_logger_clear(logger)) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001020 ReportErrorName(buffer_name, security_buffer_selected, &clear_failures);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001021 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001022 }
1023
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001024 if (setLogSize) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001025 if (android_logger_set_log_size(logger, setLogSize)) {
1026 ReportErrorName(buffer_name, security_buffer_selected, &set_size_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001027 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001028 }
1029
Joe Onorato6fa09a02010-02-26 10:04:23 -08001030 if (getLogSize) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001031 long size = android_logger_get_log_size(logger);
1032 long readable = android_logger_get_log_readable_size(logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001033
Tom Cherry6f061e82019-10-29 07:05:24 -07001034 if (size < 0 || readable < 0) {
1035 ReportErrorName(buffer_name, security_buffer_selected, &get_size_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001036 } else {
Wei Wangc27d4812018-09-05 11:05:57 -07001037 auto size_format = format_of_size(size);
1038 auto readable_format = format_of_size(readable);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001039 std::string str = android::base::StringPrintf(
Tom Cherry6f061e82019-10-29 07:05:24 -07001040 "%s: ring buffer is %lu %sB (%lu %sB consumed),"
1041 " max entry is %d B, max payload is %d B\n",
1042 buffer_name, size_format.first, size_format.second, readable_format.first,
1043 readable_format.second, (int)LOGGER_ENTRY_MAX_LEN,
1044 (int)LOGGER_ENTRY_MAX_PAYLOAD);
Tom Cherryd162f142019-10-24 17:35:26 -07001045 TEMP_FAILURE_RETRY(write(output_fd_.get(), str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001046 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001047 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001048 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001049
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001050 // report any errors in the above loop and exit
Tom Cherry6f061e82019-10-29 07:05:24 -07001051 if (!open_device_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001052 error(EXIT_FAILURE, 0, "Unable to open log device%s '%s'.",
1053 open_device_failures.size() > 1 ? "s" : "", Join(open_device_failures, ",").c_str());
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001054 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001055 if (!clear_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001056 error(EXIT_FAILURE, 0, "failed to clear the '%s' log%s.", Join(clear_failures, ",").c_str(),
1057 clear_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001058 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001059 if (!set_size_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001060 error(EXIT_FAILURE, 0, "failed to set the '%s' log size%s.",
1061 Join(set_size_failures, ",").c_str(), set_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001062 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001063 if (!get_size_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001064 error(EXIT_FAILURE, 0, "failed to get the readable '%s' log size%s.",
1065 Join(get_size_failures, ",").c_str(), get_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001066 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001067
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001068 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001069 size_t len = strlen(setPruneList);
Tom Cherryed860ff2019-12-06 11:01:51 -08001070 if (android_logger_set_prune_list(logger_list.get(), setPruneList, len)) {
1071 error(EXIT_FAILURE, 0, "Failed to set the prune list.");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001072 }
Tom Cherryd162f142019-10-24 17:35:26 -07001073 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001074 }
1075
Mark Salyzyn1c950472014-04-01 17:19:47 -07001076 if (printStatistics || getPruneList) {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001077 std::string buf(8192, '\0');
1078 size_t ret_length = 0;
1079 int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001080
Tom Cherrye17b4f62019-12-06 13:33:11 -08001081 for (; retry >= 0; --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001082 if (getPruneList) {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001083 android_logger_get_prune_list(logger_list.get(), buf.data(), buf.size());
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001084 } else {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001085 android_logger_get_statistics(logger_list.get(), buf.data(), buf.size());
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001086 }
Tom Cherrye17b4f62019-12-06 13:33:11 -08001087
1088 ret_length = atol(buf.c_str());
1089 if (ret_length < 3) {
1090 error(EXIT_FAILURE, 0, "Failed to read data.");
1091 }
1092
1093 if (ret_length < buf.size()) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001094 break;
1095 }
Tom Cherrye17b4f62019-12-06 13:33:11 -08001096
1097 buf.resize(ret_length + 1);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001098 }
1099
Tom Cherrye17b4f62019-12-06 13:33:11 -08001100 if (retry < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001101 error(EXIT_FAILURE, 0, "Failed to read data.");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001102 }
1103
Tom Cherrye17b4f62019-12-06 13:33:11 -08001104 buf.resize(ret_length);
1105 if (buf.back() == '\f') {
1106 buf.pop_back();
Mark Salyzyn34facab2014-02-06 14:48:50 -08001107 }
1108
Tom Cherrye17b4f62019-12-06 13:33:11 -08001109 // Remove the byte count prefix
1110 const char* cp = buf.c_str();
1111 while (isdigit(*cp)) ++cp;
1112 if (*cp == '\n') ++cp;
1113
1114 size_t len = strlen(cp);
Tom Cherryd162f142019-10-24 17:35:26 -07001115 TEMP_FAILURE_RETRY(write(output_fd_.get(), cp, len));
Tom Cherryd162f142019-10-24 17:35:26 -07001116 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001117 }
1118
Tom Cherryd162f142019-10-24 17:35:26 -07001119 if (getLogSize || setLogSize || clearLog) return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001120
Tom Cherryd162f142019-10-24 17:35:26 -07001121 SetupOutputAndSchedulingPolicy(!(mode & ANDROID_LOG_NONBLOCK));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001122
Tom Cherryd162f142019-10-24 17:35:26 -07001123 while (!max_count_ || print_count_ < max_count_) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001124 struct log_msg log_msg;
Tom Cherry6f061e82019-10-29 07:05:24 -07001125 int ret = android_logger_list_read(logger_list.get(), &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001126 if (!ret) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001127 error(EXIT_FAILURE, 0, R"init(Unexpected EOF!
Tom Cherry41697322019-11-21 10:31:06 -08001128
Tom Cherry26d712e2020-02-14 10:01:57 -08001129This means that either the device shut down, logd crashed, or this instance of logcat was unable to read log
Tom Cherry41697322019-11-21 10:31:06 -08001130messages as quickly as they were being produced.
1131
Tom Cherry72a4e082019-12-06 10:25:37 -08001132If you have enabled significant logging, look into using the -G option to increase log buffer sizes.)init");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001133 }
1134
1135 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001136 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001137
1138 if (ret == -EIO) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001139 error(EXIT_FAILURE, 0, "Unexpected EOF!");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001140 }
1141 if (ret == -EINVAL) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001142 error(EXIT_FAILURE, 0, "Unexpected length.");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001143 }
Tom Cherry72a4e082019-12-06 10:25:37 -08001144 error(EXIT_FAILURE, errno, "Logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001145 }
1146
Tom Cherry6f061e82019-10-29 07:05:24 -07001147 if (log_msg.id() > LOG_ID_MAX) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001148 error(EXIT_FAILURE, 0, "Unexpected log id (%d) over LOG_ID_MAX (%d).", log_msg.id(),
1149 LOG_ID_MAX);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001150 }
1151
Tom Cherry6f061e82019-10-29 07:05:24 -07001152 PrintDividers(log_msg.id(), printDividers);
1153
Tom Cherryd162f142019-10-24 17:35:26 -07001154 if (print_binary_) {
1155 TEMP_FAILURE_RETRY(write(output_fd_.get(), &log_msg, log_msg.len()));
Mark Salyzyn95132e92013-11-22 10:55:48 -08001156 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -07001157 ProcessBuffer(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001158 }
1159 }
Tom Cherryd162f142019-10-24 17:35:26 -07001160 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001161}
1162
Tom Cherry98c6c332019-10-30 13:51:03 -07001163int main(int argc, char** argv) {
Tom Cherryd162f142019-10-24 17:35:26 -07001164 Logcat logcat;
1165 return logcat.Run(argc, argv);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001166}