blob: 9a060239380e7c4ea34f35394e2397c380d6ba86 [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>
Tom Cherryc5c6d7d2020-04-17 09:38:55 -070053#include <log/log_read.h>
Colin Cross9227bd32013-07-23 16:59:20 -070054#include <log/logprint.h>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070055#include <private/android_logger.h>
Suren Baghdasaryan02843332018-12-21 12:30:16 -080056#include <processgroup/sched_policy.h>
Elliott Hughesb9e53b42016-02-17 11:58:01 -080057#include <system/thread_defs.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059#define DEFAULT_MAX_ROTATED_LOGS 4
60
Tom Cherry6f061e82019-10-29 07:05:24 -070061using android::base::Join;
62using android::base::ParseByteCount;
63using android::base::ParseUint;
64using android::base::Split;
Tom Cherryd162f142019-10-24 17:35:26 -070065using android::base::StringPrintf;
66
Tom Cherryd162f142019-10-24 17:35:26 -070067class Logcat {
68 public:
Tom Cherryd162f142019-10-24 17:35:26 -070069 int Run(int argc, char** argv);
Mark Salyzync0cf90d2017-02-10 13:09:07 -080070
Tom Cherryd162f142019-10-24 17:35:26 -070071 private:
72 void RotateLogs();
Tom Cherry6f061e82019-10-29 07:05:24 -070073 void ProcessBuffer(struct log_msg* buf);
74 void PrintDividers(log_id_t log_id, bool print_dividers);
Tom Cherryd162f142019-10-24 17:35:26 -070075 void SetupOutputAndSchedulingPolicy(bool blocking);
76 int SetLogFormat(const char* format_string);
77
Tom Cherry6f061e82019-10-29 07:05:24 -070078 // Used for all options
Tom Cherryd162f142019-10-24 17:35:26 -070079 android::base::unique_fd output_fd_{dup(STDOUT_FILENO)};
80 std::unique_ptr<AndroidLogFormat, decltype(&android_log_format_free)> logformat_{
81 android_log_format_new(), &android_log_format_free};
Tom Cherry6f061e82019-10-29 07:05:24 -070082
83 // For logging to a file and log rotation
Tom Cherryd162f142019-10-24 17:35:26 -070084 const char* output_file_name_ = nullptr;
Tom Cherry6f061e82019-10-29 07:05:24 -070085 size_t log_rotate_size_kb_ = 0; // 0 means "no log rotation"
86 size_t max_rotated_logs_ = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded"
Tom Cherryd162f142019-10-24 17:35:26 -070087 size_t out_byte_count_ = 0;
Tom Cherry6f061e82019-10-29 07:05:24 -070088
89 // For binary log buffers
Tom Cherryd162f142019-10-24 17:35:26 -070090 int print_binary_ = 0;
Tom Cherryd162f142019-10-24 17:35:26 -070091 std::unique_ptr<EventTagMap, decltype(&android_closeEventTagMap)> event_tag_map_{
92 nullptr, &android_closeEventTagMap};
Tom Cherryd162f142019-10-24 17:35:26 -070093 bool has_opened_event_tag_map_ = false;
Tom Cherry6f061e82019-10-29 07:05:24 -070094
95 // For the related --regex, --max-count, --print
96 std::unique_ptr<std::regex> regex_;
97 size_t max_count_ = 0; // 0 means "infinite"
98 size_t print_count_ = 0;
99 bool print_it_anyways_ = false;
100
101 // For PrintDividers()
102 log_id_t last_printed_id_ = LOG_ID_MAX;
103 bool printed_start_[LOG_ID_MAX] = {};
104
105 bool debug_ = false;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800106};
107
Jaegeuk Kim5327d932019-07-04 18:09:38 -0700108#ifndef F2FS_IOC_SET_PIN_FILE
109#define F2FS_IOCTL_MAGIC 0xf5
110#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
111#endif
112
113static int openLogFile(const char* pathname, size_t sizeKB) {
Mike Maa7fb0952020-01-17 18:01:03 -0800114 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 -0700115 if (fd < 0) {
116 return fd;
117 }
118
119 // no need to check errors
120 __u32 set = 1;
121 ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
122 fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, (sizeKB << 10));
123 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800124}
125
Tom Cherryd162f142019-10-24 17:35:26 -0700126void Logcat::RotateLogs() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800127 // Can't rotate logs if we're not outputting to a file
Tom Cherryd162f142019-10-24 17:35:26 -0700128 if (!output_file_name_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800129
Tom Cherryd162f142019-10-24 17:35:26 -0700130 output_fd_.reset();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800131
Mark Salyzyn5f606602017-02-10 13:09:07 -0800132 // Compute the maximum number of digits needed to count up to
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800133 // maxRotatedLogs in decimal. eg:
134 // maxRotatedLogs == 30
Mark Salyzyn5f606602017-02-10 13:09:07 -0800135 // -> log10(30) == 1.477
136 // -> maxRotationCountDigits == 2
Tom Cherryd162f142019-10-24 17:35:26 -0700137 int max_rotation_count_digits =
138 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
Aristidis Papaioannoueba73442014-10-16 22:19:55 -0700139
Tom Cherryd162f142019-10-24 17:35:26 -0700140 for (int i = max_rotated_logs_; i > 0; i--) {
141 std::string file1 =
142 StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800143
Mark Salyzyn5b1a5382016-08-03 14:20:41 -0700144 std::string file0;
Mark Salyzynde022a82017-03-01 08:30:06 -0800145 if (!(i - 1)) {
Tom Cherryd162f142019-10-24 17:35:26 -0700146 file0 = output_file_name_;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147 } else {
Tom Cherryd162f142019-10-24 17:35:26 -0700148 file0 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i - 1);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149 }
150
Mark Salyzynde022a82017-03-01 08:30:06 -0800151 if (!file0.length() || !file1.length()) {
Traian Schiau59763032015-04-10 15:51:39 +0300152 perror("while rotating log files");
153 break;
154 }
155
Tom Cherryd162f142019-10-24 17:35:26 -0700156 int err = rename(file0.c_str(), file1.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800157
158 if (err < 0 && errno != ENOENT) {
159 perror("while rotating log files");
160 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800161 }
162
Tom Cherryd162f142019-10-24 17:35:26 -0700163 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800164
Tom Cherryd162f142019-10-24 17:35:26 -0700165 if (!output_fd_.ok()) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800166 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzyne3d0c962017-02-17 13:15:51 -0800167 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800168
Tom Cherryd162f142019-10-24 17:35:26 -0700169 out_byte_count_ = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800170}
171
Tom Cherry6f061e82019-10-29 07:05:24 -0700172void Logcat::ProcessBuffer(struct log_msg* buf) {
Mathias Agopian50844522010-03-17 16:10:26 -0700173 int bytesWritten = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800174 int err;
175 AndroidLogEntry entry;
176 char binaryMsgBuf[1024];
177
Tom Cherry6f061e82019-10-29 07:05:24 -0700178 bool is_binary =
179 buf->id() == LOG_ID_EVENTS || buf->id() == LOG_ID_STATS || buf->id() == LOG_ID_SECURITY;
180
181 if (is_binary) {
Tom Cherryd162f142019-10-24 17:35:26 -0700182 if (!event_tag_map_ && !has_opened_event_tag_map_) {
183 event_tag_map_.reset(android_openEventTagMap(nullptr));
184 has_opened_event_tag_map_ = true;
Mark Salyzyn9421b0c2015-02-26 14:33:35 -0800185 }
Tom Cherryd162f142019-10-24 17:35:26 -0700186 err = android_log_processBinaryLogBuffer(&buf->entry, &entry, event_tag_map_.get(),
Tom Cherry441054a2019-10-15 16:53:11 -0700187 binaryMsgBuf, sizeof(binaryMsgBuf));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800188 // printf(">>> pri=%d len=%d msg='%s'\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 // entry.priority, entry.messageLen, entry.message);
190 } else {
Tom Cherry441054a2019-10-15 16:53:11 -0700191 err = android_log_processLogBuffer(&buf->entry, &entry);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192 }
Tom Cherryd162f142019-10-24 17:35:26 -0700193 if (err < 0 && !debug_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800194
Tom Cherryd162f142019-10-24 17:35:26 -0700195 if (android_log_shouldPrintLine(logformat_.get(), std::string(entry.tag, entry.tagLen).c_str(),
196 entry.priority)) {
197 bool match = !regex_ ||
198 std::regex_search(entry.message, entry.message + entry.messageLen, *regex_);
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800199
Tom Cherryd162f142019-10-24 17:35:26 -0700200 print_count_ += match;
201 if (match || print_it_anyways_) {
202 bytesWritten = android_log_printLogLine(logformat_.get(), output_fd_.get(), &entry);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700203
Mark Salyzync9202772016-03-30 09:38:31 -0700204 if (bytesWritten < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800205 error(EXIT_FAILURE, 0, "Output error.");
Mark Salyzync9202772016-03-30 09:38:31 -0700206 }
Joe Onoratoe2bf2ea2010-03-01 09:11:54 -0800207 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800208 }
209
Tom Cherryd162f142019-10-24 17:35:26 -0700210 out_byte_count_ += bytesWritten;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800211
Tom Cherryd162f142019-10-24 17:35:26 -0700212 if (log_rotate_size_kb_ > 0 && (out_byte_count_ / 1024) >= log_rotate_size_kb_) {
213 RotateLogs();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800215}
216
Tom Cherry6f061e82019-10-29 07:05:24 -0700217void Logcat::PrintDividers(log_id_t log_id, bool print_dividers) {
218 if (log_id == last_printed_id_ || print_binary_) {
219 return;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800220 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700221 if (!printed_start_[log_id] || print_dividers) {
222 if (dprintf(output_fd_.get(), "--------- %s %s\n",
223 printed_start_[log_id] ? "switch to" : "beginning of",
224 android_log_id_to_name(log_id)) < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800225 error(EXIT_FAILURE, errno, "Output error");
Tom Cherry6f061e82019-10-29 07:05:24 -0700226 }
227 }
228 last_printed_id_ = log_id;
229 printed_start_[log_id] = true;
Joe Onorato6fa09a02010-02-26 10:04:23 -0800230}
231
Tom Cherryd162f142019-10-24 17:35:26 -0700232void Logcat::SetupOutputAndSchedulingPolicy(bool blocking) {
233 if (!output_file_name_) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234
Mark Salyzynad5e4112016-08-04 07:53:52 -0700235 if (blocking) {
236 // Lower priority and set to batch scheduling if we are saving
237 // the logs into files and taking continuous content.
Tom Cherryd162f142019-10-24 17:35:26 -0700238 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
239 fprintf(stderr, "failed to set background scheduling policy\n");
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700240 }
241
Tom Cherryd162f142019-10-24 17:35:26 -0700242 struct sched_param param = {};
Mark Salyzyn5f606602017-02-10 13:09:07 -0800243 if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
Mark Salyzyn3ef730c2015-06-02 07:57:16 -0700244 fprintf(stderr, "failed to set to batch scheduler\n");
245 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800246
Tom Cherryd162f142019-10-24 17:35:26 -0700247 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
248 fprintf(stderr, "failed set to priority\n");
Riley Andrewsaede9892015-06-08 23:36:34 -0700249 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800250 }
Mark Salyzynad5e4112016-08-04 07:53:52 -0700251
Tom Cherryd162f142019-10-24 17:35:26 -0700252 output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_));
Mark Salyzynad5e4112016-08-04 07:53:52 -0700253
Tom Cherryd162f142019-10-24 17:35:26 -0700254 if (!output_fd_.ok()) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800255 error(EXIT_FAILURE, errno, "Couldn't open output file");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700256 }
257
258 struct stat statbuf;
Tom Cherryd162f142019-10-24 17:35:26 -0700259 if (fstat(output_fd_.get(), &statbuf) == -1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800260 error(EXIT_FAILURE, errno, "Couldn't get output file stat");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700261 }
262
Mark Salyzyn5f606602017-02-10 13:09:07 -0800263 if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800264 error(EXIT_FAILURE, 0, "Invalid output file stat.");
Mark Salyzynad5e4112016-08-04 07:53:52 -0700265 }
266
Tom Cherryd162f142019-10-24 17:35:26 -0700267 out_byte_count_ = statbuf.st_size;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268}
269
Mark Salyzyn5f606602017-02-10 13:09:07 -0800270// clang-format off
Tom Cherryd162f142019-10-24 17:35:26 -0700271static void show_help() {
272 const char* cmd = getprogname();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800273
Tom Cherryd162f142019-10-24 17:35:26 -0700274 fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd);
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800275
Tom Cherry41697322019-11-21 10:31:06 -0800276 fprintf(stderr, R"init(
277General options:
278 -b, --buffer=<buffer> Request alternate ring buffer(s):
279 main system radio events crash default all
280 Additionally, 'kernel' for userdebug and eng builds, and
281 'security' for Device Owner installations.
282 Multiple -b parameters or comma separated list of buffers are
283 allowed. Buffers are interleaved.
284 Default -b main,system,crash,kernel.
285 -L, --last Dump logs from prior to last reboot from pstore.
286 -c, --clear Clear (flush) the entire log and exit.
287 if -f is specified, clear the specified file and its related rotated
288 log files instead.
289 if -L is specified, clear pstore log instead.
290 -d Dump the log and then exit (don't block).
291 --pid=<pid> Only print logs from the given pid.
292 --wrap Sleep for 2 hours or when buffer about to wrap whichever
293 comes first. Improves efficiency of polling by providing
294 an about-to-wrap wakeup.
295
296Formatting:
297 -v, --format=<format> Sets log print format verb and adverbs, where <format> is one of:
298 brief help long process raw tag thread threadtime time
299 Modifying adverbs can be added:
300 color descriptive epoch monotonic printable uid usec UTC year zone
301 Multiple -v parameters or comma separated list of format and format
302 modifiers are allowed.
303 -D, --dividers Print dividers between each log buffer.
304 -B, --binary Output the log in binary.
305
306Outfile files:
307 -f, --file=<file> Log to file instead of stdout.
308 -r, --rotate-kbytes=<n> Rotate log every <n> kbytes. Requires -f option.
309 -n, --rotate-count=<count> Sets max number of rotated logs to <count>, default 4.
310 --id=<id> If the signature <id> for logging to file changes, then clear the
311 associated files and continue.
312
313Logd control:
314 These options send a control message to the logd daemon on device, print its return message if
315 applicable, then exit. They are incompatible with -L, as these attributes do not apply to pstore.
316 -g, --buffer-size Get the size of the ring buffers within logd.
317 -G, --buffer-size=<size> Set size of a ring buffer in logd. May suffix with K or M.
318 This can individually control each buffer's size with -b.
319 -S, --statistics Output statistics.
320 --pid can be used to provide pid specific stats.
321 -p, --prune Print prune white and ~black list. Service is specified as UID,
322 UID/PID or /PID. Weighed for quicker pruning if prefix with ~,
323 otherwise weighed for longevity if unadorned. All other pruning
324 activity is oldest first. Special case ~! represents an automatic
325 quicker pruning for the noisiest UID as determined by the current
326 statistics.
327 -P, --prune='<list> ...' Set prune white and ~black list, using same format as listed above.
328 Must be quoted.
329
330Filtering:
331 -s Set default filter to silent. Equivalent to filterspec '*:S'
332 -e, --regex=<expr> Only print lines where the log message matches <expr> where <expr> is
333 an ECMAScript regular expression.
334 -m, --max-count=<count> Quit after printing <count> lines. This is meant to be paired with
335 --regex, but will work on its own.
336 --print This option is only applicable when --regex is set and only useful if
337 --max-count is also provided.
338 With --print, logcat will print all messages even if they do not
339 match the regex. Logcat will quit after printing the max-count number
340 of lines that match the regex.
341 -t <count> Print only the most recent <count> lines (implies -d).
342 -t '<time>' Print the lines since specified time (implies -d).
343 -T <count> Print only the most recent <count> lines (does not imply -d).
344 -T '<time>' Print the lines since specified time (not imply -d).
345 count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'
346 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format.
347)init");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348
Tom Cherryd162f142019-10-24 17:35:26 -0700349 fprintf(stderr, "\nfilterspecs are a series of \n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350 " <tag>[:priority]\n\n"
351 "where <tag> is a log component tag (or * for all) and priority is:\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700352 " V Verbose (default for <tag>)\n"
353 " D Debug (default for '*')\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354 " I Info\n"
355 " W Warn\n"
356 " E Error\n"
357 " F Fatal\n"
Mark Salyzynbba894a2015-03-09 09:32:56 -0700358 " S Silent (suppress all output)\n"
359 "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
360 "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
361 "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
362 "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
363 "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
Mark Salyzyn649fc602014-09-16 09:15:15 -0700364 "or defaults to \"threadtime\"\n\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800365}
366
Tom Cherryd162f142019-10-24 17:35:26 -0700367static void show_format_help() {
368 fprintf(stderr,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700369 "-v <format>, --format=<format> options:\n"
370 " Sets log print format verb and adverbs, where <format> is:\n"
371 " brief long process raw tag thread threadtime time\n"
372 " and individually flagged modifying adverbs can be added:\n"
373 " color descriptive epoch monotonic printable uid usec UTC year zone\n"
374 "\nSingle format verbs:\n"
375 " brief — Display priority/tag and PID of the process issuing the message.\n"
376 " long — Display all metadata fields, separate messages with blank lines.\n"
377 " process — Display PID only.\n"
378 " raw — Display the raw log message, with no other metadata fields.\n"
379 " tag — Display the priority/tag only.\n"
Mark Salyzync74f8d92017-05-15 13:40:33 -0700380 " thread — Display priority, PID and TID of process issuing the message.\n"
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700381 " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
382 " and TID of the thread issuing the message. (the default format).\n"
383 " time — Display the date, invocation time, priority/tag, and PID of the\n"
384 " process issuing the message.\n"
385 "\nAdverb modifiers can be used in combination:\n"
386 " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
387 " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
388 " descriptive — events logs only, descriptions from event-log-tags database.\n"
389 " epoch — Display time as seconds since Jan 1 1970.\n"
390 " monotonic — Display time as cpu seconds since last boot.\n"
391 " printable — Ensure that any binary logging content is escaped.\n"
392 " uid — If permitted, display the UID or Android ID of logged process.\n"
393 " usec — Display time down the microsecond precision.\n"
394 " UTC — Display time as UTC.\n"
395 " year — Add the year to the displayed time.\n"
396 " zone — Add the local timezone to the displayed time.\n"
397 " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
398 );
399}
Mark Salyzyn5f606602017-02-10 13:09:07 -0800400// clang-format on
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700401
Tom Cherryd162f142019-10-24 17:35:26 -0700402int Logcat::SetLogFormat(const char* format_string) {
403 AndroidLogPrintFormat format = android_log_formatFromString(format_string);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404
Mark Salyzynde022a82017-03-01 08:30:06 -0800405 // invalid string?
406 if (format == FORMAT_OFF) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407
Tom Cherryd162f142019-10-24 17:35:26 -0700408 return android_log_setPrintFormat(logformat_.get(), format);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409}
410
Wei Wangc27d4812018-09-05 11:05:57 -0700411static std::pair<unsigned long, const char*> format_of_size(unsigned long value) {
412 static const char multipliers[][3] = {{""}, {"Ki"}, {"Mi"}, {"Gi"}};
413 size_t i;
Mark Salyzyn671e3432014-05-06 07:34:59 -0700414 for (i = 0;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800415 (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
416 value /= 1024, ++i)
417 ;
Wei Wangc27d4812018-09-05 11:05:57 -0700418 return std::make_pair(value, multipliers[i]);
Mark Salyzyn671e3432014-05-06 07:34:59 -0700419}
420
Mark Salyzyn5f606602017-02-10 13:09:07 -0800421static char* parseTime(log_time& t, const char* cp) {
422 char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800423 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700424 ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
Mark Salyzynde022a82017-03-01 08:30:06 -0800425 if (ep) return ep;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700426 return t.strptime(cp, "%s.%q");
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700427}
Mark Salyzynf3555d92015-05-27 07:39:56 -0700428
Mark Salyzyn31961062016-08-04 07:43:46 -0700429// Find last logged line in <outputFileName>, or <outputFileName>.1
Mark Salyzyne9ade172017-03-02 15:09:41 -0800430static log_time lastLogTime(const char* outputFileName) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700431 log_time retval(log_time::EPOCH);
Mark Salyzynde022a82017-03-01 08:30:06 -0800432 if (!outputFileName) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700433
Mark Salyzynf3555d92015-05-27 07:39:56 -0700434 std::string directory;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800435 const char* file = strrchr(outputFileName, '/');
Mark Salyzynf3555d92015-05-27 07:39:56 -0700436 if (!file) {
437 directory = ".";
438 file = outputFileName;
439 } else {
Mark Salyzyne9ade172017-03-02 15:09:41 -0800440 directory = std::string(outputFileName, file - outputFileName);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700441 ++file;
442 }
Mark Salyzync18c2132016-04-01 07:52:20 -0700443
Mark Salyzyn5f606602017-02-10 13:09:07 -0800444 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
445 closedir);
Mark Salyzynde022a82017-03-01 08:30:06 -0800446 if (!dir.get()) return retval;
Mark Salyzync18c2132016-04-01 07:52:20 -0700447
Mark Salyzyn31961062016-08-04 07:43:46 -0700448 log_time now(android_log_clockid());
Mark Salyzync18c2132016-04-01 07:52:20 -0700449
Mark Salyzynf3555d92015-05-27 07:39:56 -0700450 size_t len = strlen(file);
451 log_time modulo(0, NS_PER_SEC);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800452 struct dirent* dp;
Mark Salyzync18c2132016-04-01 07:52:20 -0700453
Mark Salyzynde022a82017-03-01 08:30:06 -0800454 while (!!(dp = readdir(dir.get()))) {
455 if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
Mark Salyzyn5f606602017-02-10 13:09:07 -0800456 (dp->d_name[len] && ((dp->d_name[len] != '.') ||
Mark Salyzynde022a82017-03-01 08:30:06 -0800457 (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
Mark Salyzynf3555d92015-05-27 07:39:56 -0700458 continue;
459 }
460
461 std::string file_name = directory;
462 file_name += "/";
463 file_name += dp->d_name;
464 std::string file;
Mark Salyzynde022a82017-03-01 08:30:06 -0800465 if (!android::base::ReadFileToString(file_name, &file)) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700466
467 bool found = false;
468 for (const auto& line : android::base::Split(file, "\n")) {
469 log_time t(log_time::EPOCH);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800470 char* ep = parseTime(t, line.c_str());
Mark Salyzynde022a82017-03-01 08:30:06 -0800471 if (!ep || (*ep != ' ')) continue;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700472 // determine the time precision of the logs (eg: msec or usec)
473 for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
474 if (t.tv_nsec % (mod * 10)) {
475 modulo.tv_nsec = mod;
476 break;
477 }
478 }
479 // We filter any times later than current as we may not have the
480 // year stored with each log entry. Also, since it is possible for
481 // entries to be recorded out of order (very rare) we select the
482 // maximum we find just in case.
483 if ((t < now) && (t > retval)) {
484 retval = t;
485 found = true;
486 }
487 }
488 // We count on the basename file to be the definitive end, so stop here.
Mark Salyzynde022a82017-03-01 08:30:06 -0800489 if (!dp->d_name[len] && found) break;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700490 }
Mark Salyzynde022a82017-03-01 08:30:06 -0800491 if (retval == log_time::EPOCH) return retval;
Mark Salyzynf3555d92015-05-27 07:39:56 -0700492 // tail_time prints matching or higher, round up by the modulo to prevent
493 // a replay of the last entry we have just checked.
494 retval += modulo;
495 return retval;
496}
497
Tom Cherry6f061e82019-10-29 07:05:24 -0700498void ReportErrorName(const std::string& name, bool allow_security,
499 std::vector<std::string>* errors) {
500 if (allow_security || name != "security") {
501 errors->emplace_back(name);
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800502 }
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800503}
Traian Schiau59763032015-04-10 15:51:39 +0300504
Tom Cherryd162f142019-10-24 17:35:26 -0700505int Logcat::Run(int argc, char** argv) {
Mark Salyzynb45a1752017-02-28 09:20:31 -0800506 bool hasSetLogFormat = false;
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800507 bool clearLog = false;
Tom Cherry6f061e82019-10-29 07:05:24 -0700508 bool security_buffer_selected =
509 false; // Do not report errors on the security buffer unless it is explicitly named.
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800510 bool getLogSize = false;
511 bool getPruneList = false;
512 bool printStatistics = false;
513 bool printDividers = false;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800514 unsigned long setLogSize = 0;
Mark Salyzyne9ade172017-03-02 15:09:41 -0800515 const char* setPruneList = nullptr;
516 const char* setId = nullptr;
Tom Cherry907b2d02020-03-23 13:40:10 -0700517 int mode = 0;
Mark Salyzynf3290292017-02-10 13:09:07 -0800518 std::string forceFilters;
Traian Schiau59763032015-04-10 15:51:39 +0300519 size_t tail_lines = 0;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800520 log_time tail_time(log_time::EPOCH);
Kristian Monsen562e5132015-06-05 14:10:12 -0700521 size_t pid = 0;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700522 bool got_t = false;
Tom Cherry6f061e82019-10-29 07:05:24 -0700523 unsigned id_mask = 0;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800524
Mark Salyzynde022a82017-03-01 08:30:06 -0800525 if (argc == 2 && !strcmp(argv[1], "--help")) {
Tom Cherryd162f142019-10-24 17:35:26 -0700526 show_help();
527 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800528 }
529
Mark Salyzynb45a1752017-02-28 09:20:31 -0800530 // meant to catch comma-delimited values, but cast a wider
531 // net for stability dealing with possible mistaken inputs.
532 static const char delimiters[] = ",:; \t\n\r\f";
533
Elliott Hughes61b580e2018-06-15 15:16:20 -0700534 optind = 0;
535 while (true) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700536 int option_index = 0;
Mark Salyzync9202772016-03-30 09:38:31 -0700537 // list of long-argument only strings for later comparison
Kristian Monsen562e5132015-06-05 14:10:12 -0700538 static const char pid_str[] = "pid";
Mark Salyzyn538bc122016-11-16 15:28:31 -0800539 static const char debug_str[] = "debug";
Mark Salyzyn02687e72016-08-03 14:20:41 -0700540 static const char id_str[] = "id";
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800541 static const char wrap_str[] = "wrap";
Mark Salyzync9202772016-03-30 09:38:31 -0700542 static const char print_str[] = "print";
Mark Salyzyn5f606602017-02-10 13:09:07 -0800543 // clang-format off
Kristian Monsen562e5132015-06-05 14:10:12 -0700544 static const struct option long_options[] = {
Mark Salyzynde022a82017-03-01 08:30:06 -0800545 { "binary", no_argument, nullptr, 'B' },
546 { "buffer", required_argument, nullptr, 'b' },
547 { "buffer-size", optional_argument, nullptr, 'g' },
548 { "clear", no_argument, nullptr, 'c' },
549 { debug_str, no_argument, nullptr, 0 },
550 { "dividers", no_argument, nullptr, 'D' },
551 { "file", required_argument, nullptr, 'f' },
552 { "format", required_argument, nullptr, 'v' },
Mark Salyzync18c2132016-04-01 07:52:20 -0700553 // hidden and undocumented reserved alias for --regex
Mark Salyzynde022a82017-03-01 08:30:06 -0800554 { "grep", required_argument, nullptr, 'e' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700555 // hidden and undocumented reserved alias for --max-count
Mark Salyzynde022a82017-03-01 08:30:06 -0800556 { "head", required_argument, nullptr, 'm' },
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700557 { "help", no_argument, nullptr, 'h' },
Mark Salyzynde022a82017-03-01 08:30:06 -0800558 { id_str, required_argument, nullptr, 0 },
559 { "last", no_argument, nullptr, 'L' },
560 { "max-count", required_argument, nullptr, 'm' },
561 { pid_str, required_argument, nullptr, 0 },
562 { print_str, no_argument, nullptr, 0 },
563 { "prune", optional_argument, nullptr, 'p' },
564 { "regex", required_argument, nullptr, 'e' },
565 { "rotate-count", required_argument, nullptr, 'n' },
566 { "rotate-kbytes", required_argument, nullptr, 'r' },
567 { "statistics", no_argument, nullptr, 'S' },
Mark Salyzynd85f6462016-03-30 09:15:09 -0700568 // hidden and undocumented reserved alias for -t
Mark Salyzynde022a82017-03-01 08:30:06 -0800569 { "tail", required_argument, nullptr, 't' },
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800570 // support, but ignore and do not document, the optional argument
Mark Salyzynde022a82017-03-01 08:30:06 -0800571 { wrap_str, optional_argument, nullptr, 0 },
572 { nullptr, 0, nullptr, 0 }
Kristian Monsen562e5132015-06-05 14:10:12 -0700573 };
Mark Salyzyn5f606602017-02-10 13:09:07 -0800574 // clang-format on
Kristian Monsen562e5132015-06-05 14:10:12 -0700575
Elliott Hughes61b580e2018-06-15 15:16:20 -0700576 int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
577 &option_index);
578 if (c == -1) break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800579
Elliott Hughes61b580e2018-06-15 15:16:20 -0700580 switch (c) {
Kristian Monsen562e5132015-06-05 14:10:12 -0700581 case 0:
Mark Salyzyn02687e72016-08-03 14:20:41 -0700582 // only long options
Kristian Monsen562e5132015-06-05 14:10:12 -0700583 if (long_options[option_index].name == pid_str) {
Steven Morelandb0e867a2019-08-02 10:13:57 -0700584 if (pid != 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800585 error(EXIT_FAILURE, 0, "Only one --pid argument can be provided.");
Steven Morelandb0e867a2019-08-02 10:13:57 -0700586 }
587
Tom Cherry6f061e82019-10-29 07:05:24 -0700588 if (!ParseUint(optarg, &pid) || pid < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800589 error(EXIT_FAILURE, 0, "%s %s out of range.",
590 long_options[option_index].name, optarg);
Kristian Monsen562e5132015-06-05 14:10:12 -0700591 }
592 break;
593 }
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800594 if (long_options[option_index].name == wrap_str) {
Tom Cherry907b2d02020-03-23 13:40:10 -0700595 mode |= ANDROID_LOG_WRAP | ANDROID_LOG_NONBLOCK;
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800596 // ToDo: implement API that supports setting a wrap timeout
597 size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
Tom Cherry6f061e82019-10-29 07:05:24 -0700598 if (optarg && (!ParseUint(optarg, &dummy) || dummy < 1)) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800599 error(EXIT_FAILURE, 0, "%s %s out of range.",
600 long_options[option_index].name, optarg);
Mark Salyzyn41ba25f2015-11-30 13:48:56 -0800601 }
Tom Cherryd162f142019-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 Salyzyn41ba25f2015-11-30 13:48:56 -0800606 }
607 break;
608 }
Mark Salyzync9202772016-03-30 09:38:31 -0700609 if (long_options[option_index].name == print_str) {
Tom Cherryd162f142019-10-24 17:35:26 -0700610 print_it_anyways_ = true;
Mark Salyzync9202772016-03-30 09:38:31 -0700611 break;
612 }
Mark Salyzyn538bc122016-11-16 15:28:31 -0800613 if (long_options[option_index].name == debug_str) {
Tom Cherryd162f142019-10-24 17:35:26 -0700614 debug_ = true;
Mark Salyzyn538bc122016-11-16 15:28:31 -0800615 break;
616 }
Mark Salyzyn02687e72016-08-03 14:20:41 -0700617 if (long_options[option_index].name == id_str) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700618 setId = (optarg && optarg[0]) ? optarg : nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700619 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800620 break;
Kristian Monsen562e5132015-06-05 14:10:12 -0700621
Mark Salyzyn95132e92013-11-22 10:55:48 -0800622 case 's':
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623 // default to all silent
Tom Cherryd162f142019-10-24 17:35:26 -0700624 android_log_addFilterRule(logformat_.get(), "*:s");
Mark Salyzyn5f606602017-02-10 13:09:07 -0800625 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626
627 case 'c':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800628 clearLog = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800629 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800631 case 'L':
Tom Cherry907b2d02020-03-23 13:40:10 -0700632 mode |= ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800633 break;
Mark Salyzyn7c975ac2014-12-15 10:01:31 -0800634
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635 case 'd':
Tom Cherry907b2d02020-03-23 13:40:10 -0700636 mode |= ANDROID_LOG_NONBLOCK;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800637 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800639 case 't':
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700640 got_t = true;
Tom Cherry907b2d02020-03-23 13:40:10 -0700641 mode |= ANDROID_LOG_NONBLOCK;
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700642 FALLTHROUGH_INTENDED;
Mark Salyzyn5d3d1f12013-12-09 13:47:00 -0800643 case 'T':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700644 if (strspn(optarg, "0123456789") != strlen(optarg)) {
645 char* cp = parseTime(tail_time, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800646 if (!cp) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800647 error(EXIT_FAILURE, 0, "-%c '%s' not in time format.", c, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800648 }
649 if (*cp) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700650 char ch = *cp;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800651 *cp = '\0';
Tom Cherry72a4e082019-12-06 10:25:37 -0800652 fprintf(stderr, "WARNING: -%c '%s' '%c%s' time truncated\n", c, optarg, ch,
653 cp + 1);
Elliott Hughes61b580e2018-06-15 15:16:20 -0700654 *cp = ch;
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800655 }
656 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -0700657 if (!ParseUint(optarg, &tail_lines) || tail_lines < 1) {
Tom Cherryd162f142019-10-24 17:35:26 -0700658 fprintf(stderr, "WARNING: -%c %s invalid, setting to 1\n", c, optarg);
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800659 tail_lines = 1;
660 }
661 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800662 break;
Dan Egnord1d3b6d2010-03-11 20:32:17 -0800663
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800664 case 'D':
665 printDividers = true;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800666 break;
Mark Salyzyn7b30ff82015-01-26 13:41:33 -0800667
Casey Dahlindc42a872016-03-17 16:18:55 -0700668 case 'e':
Tom Cherryd162f142019-10-24 17:35:26 -0700669 regex_.reset(new std::regex(optarg));
Mark Salyzyn5f606602017-02-10 13:09:07 -0800670 break;
Casey Dahlindc42a872016-03-17 16:18:55 -0700671
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700672 case 'm': {
Tom Cherry6f061e82019-10-29 07:05:24 -0700673 if (!ParseUint(optarg, &max_count_) || max_count_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800674 error(EXIT_FAILURE, 0, "-%c '%s' isn't an integer greater than zero.", c,
675 optarg);
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700676 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800677 } break;
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700678
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 case 'g':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700680 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800681 getLogSize = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -0800682 break;
683 }
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700684 FALLTHROUGH_INTENDED;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800685
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800686 case 'G': {
Tom Cherry6f061e82019-10-29 07:05:24 -0700687 if (!ParseByteCount(optarg, &setLogSize) || setLogSize < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800688 error(EXIT_FAILURE, 0, "-G must be specified as <num><multiplier>.");
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800689 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800690 } break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800691
692 case 'p':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700693 if (!optarg) {
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800694 getPruneList = true;
Mark Salyzynf8bff872015-11-30 12:57:56 -0800695 break;
696 }
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -0700697 FALLTHROUGH_INTENDED;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800698
699 case 'P':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700700 setPruneList = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800701 break;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800702
Tom Cherry6f061e82019-10-29 07:05:24 -0700703 case 'b':
704 for (const auto& buffer : Split(optarg, delimiters)) {
705 if (buffer == "default") {
706 id_mask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH);
707 } else if (buffer == "all") {
708 id_mask = -1;
Mark Salyzyn45177732016-04-11 14:03:48 -0700709 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -0700710 log_id_t log_id = android_name_to_log_id(buffer.c_str());
711 if (log_id >= LOG_ID_MAX) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800712 error(EXIT_FAILURE, 0, "Unknown buffer '%s' listed for -b.",
713 buffer.c_str());
Mark Salyzyn34facab2014-02-06 14:48:50 -0800714 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700715 if (log_id == LOG_ID_SECURITY) {
716 security_buffer_selected = true;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800717 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700718 id_mask |= (1 << log_id);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800719 }
Joe Onorato6fa09a02010-02-26 10:04:23 -0800720 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700721 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722
723 case 'B':
Tom Cherryd162f142019-10-24 17:35:26 -0700724 print_binary_ = 1;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800725 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726
727 case 'f':
Mark Salyzynde022a82017-03-01 08:30:06 -0800728 if ((tail_time == log_time::EPOCH) && !tail_lines) {
Elliott Hughes61b580e2018-06-15 15:16:20 -0700729 tail_time = lastLogTime(optarg);
Mark Salyzynf3555d92015-05-27 07:39:56 -0700730 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731 // redirect output to a file
Tom Cherryd162f142019-10-24 17:35:26 -0700732 output_file_name_ = optarg;
Mark Salyzyn5f606602017-02-10 13:09:07 -0800733 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700735 case 'r':
Tom Cherry6f061e82019-10-29 07:05:24 -0700736 if (!ParseUint(optarg, &log_rotate_size_kb_) || log_rotate_size_kb_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800737 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -r.", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800739 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740
Mark Salyzyn1325ebf2016-06-07 13:03:10 -0700741 case 'n':
Tom Cherry6f061e82019-10-29 07:05:24 -0700742 if (!ParseUint(optarg, &max_rotated_logs_) || max_rotated_logs_ < 1) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800743 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -n.", optarg);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800744 }
Mark Salyzyn5f606602017-02-10 13:09:07 -0800745 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800746
Tom Cherry6f061e82019-10-29 07:05:24 -0700747 case 'v':
Elliott Hughes61b580e2018-06-15 15:16:20 -0700748 if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
Tom Cherryd162f142019-10-24 17:35:26 -0700749 show_format_help();
750 return EXIT_SUCCESS;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700751 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700752 for (const auto& arg : Split(optarg, delimiters)) {
753 int err = SetLogFormat(arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800754 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800755 error(EXIT_FAILURE, 0, "Invalid parameter '%s' to -v.", arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800756 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800757 if (err) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800758 }
Tom Cherry6f061e82019-10-29 07:05:24 -0700759 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800760
761 case 'Q':
bohu94aab862017-02-21 14:31:19 -0800762#define LOGCAT_FILTER "androidboot.logcat="
763#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
Mark Salyzyn5f606602017-02-10 13:09:07 -0800764#define CONSOLE_OPTION "androidboot.console="
bohu94aab862017-02-21 14:31:19 -0800765#define QEMU_PROPERTY "ro.kernel.qemu"
766#define QEMU_CMDLINE "qemu.cmdline"
Mark Salyzyn5f606602017-02-10 13:09:07 -0800767 // This is a *hidden* option used to start a version of logcat
768 // in an emulated device only. It basically looks for
769 // androidboot.logcat= on the kernel command line. If
770 // something is found, it extracts a log filter and uses it to
bohu94aab862017-02-21 14:31:19 -0800771 // run the program. The logcat output will go to consolepipe if
772 // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
773 // it goes to androidboot.console (e.g. tty)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774 {
bohu94aab862017-02-21 14:31:19 -0800775 // if not in emulator, exit quietly
776 if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
Tom Cherryd162f142019-10-24 17:35:26 -0700777 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800778 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800779
bohu94aab862017-02-21 14:31:19 -0800780 std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
781 if (cmdline.empty()) {
782 android::base::ReadFileToString("/proc/cmdline", &cmdline);
783 }
784
785 const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
786 // if nothing found or invalid filters, exit quietly
787 if (!logcatFilter) {
Tom Cherryd162f142019-10-24 17:35:26 -0700788 return EXIT_SUCCESS;
bohu94aab862017-02-21 14:31:19 -0800789 }
790
791 const char* p = logcatFilter + strlen(LOGCAT_FILTER);
Mark Salyzynf3290292017-02-10 13:09:07 -0800792 const char* q = strpbrk(p, " \t\n\r");
793 if (!q) q = p + strlen(p);
794 forceFilters = std::string(p, q);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800795
bohu94aab862017-02-21 14:31:19 -0800796 // redirect our output to the emulator console pipe or console
797 const char* consolePipe =
798 strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
Mark Salyzynf3290292017-02-10 13:09:07 -0800799 const char* console =
800 strstr(cmdline.c_str(), CONSOLE_OPTION);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800801
bohu94aab862017-02-21 14:31:19 -0800802 if (consolePipe) {
803 p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
804 } else if (console) {
805 p = console + strlen(CONSOLE_OPTION);
806 } else {
Tom Cherryd162f142019-10-24 17:35:26 -0700807 return EXIT_FAILURE;
bohu94aab862017-02-21 14:31:19 -0800808 }
809
Mark Salyzynf3290292017-02-10 13:09:07 -0800810 q = strpbrk(p, " \t\n\r");
811 int len = q ? q - p : strlen(p);
812 std::string devname = "/dev/" + std::string(p, len);
bohu94aab862017-02-21 14:31:19 -0800813 std::string pipePurpose("pipe:logcat");
814 if (consolePipe) {
815 // example: "qemu_pipe,pipe:logcat"
816 // upon opening of /dev/qemu_pipe, the "pipe:logcat"
817 // string with trailing '\0' should be written to the fd
Chih-Hung Hsiehe5d975c2017-08-03 13:56:49 -0700818 size_t pos = devname.find(',');
bohu94aab862017-02-21 14:31:19 -0800819 if (pos != std::string::npos) {
820 pipePurpose = devname.substr(pos + 1);
821 devname = devname.substr(0, pos);
822 }
823 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824
Tom Cherryd162f142019-10-24 17:35:26 -0700825 fprintf(stderr, "logcat using %s\n", devname.c_str());
826
827 int fd = open(devname.c_str(), O_WRONLY | O_CLOEXEC);
828 if (fd < 0) {
829 break;
Mark Salyzync0cf90d2017-02-10 13:09:07 -0800830 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800831
bohu94aab862017-02-21 14:31:19 -0800832 if (consolePipe) {
833 // need the trailing '\0'
Tom Cherryd162f142019-10-24 17:35:26 -0700834 if (!android::base::WriteFully(fd, pipePurpose.c_str(),
835 pipePurpose.size() + 1)) {
836 close(fd);
837 return EXIT_FAILURE;
bohu94aab862017-02-21 14:31:19 -0800838 }
839 }
Mark Salyzynf3290292017-02-10 13:09:07 -0800840 // close output and error channels, replace with console
Erwin Jansen4f138b22019-11-27 12:58:58 -0800841 dup2(fd, output_fd_.get());
Tom Cherryd162f142019-10-24 17:35:26 -0700842 dup2(fd, STDERR_FILENO);
843 close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 }
845 break;
846
Mark Salyzyn34facab2014-02-06 14:48:50 -0800847 case 'S':
Mark Salyzyn26a1fac2017-01-20 14:07:29 -0800848 printStatistics = true;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800849 break;
850
Traian Schiau59763032015-04-10 15:51:39 +0300851 case ':':
Tom Cherry72a4e082019-12-06 10:25:37 -0800852 error(EXIT_FAILURE, 0, "Option '%s' needs an argument.", argv[optind - 1]);
853 break;
Traian Schiau59763032015-04-10 15:51:39 +0300854
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700855 case 'h':
Tom Cherryd162f142019-10-24 17:35:26 -0700856 show_help();
857 show_format_help();
858 return EXIT_SUCCESS;
Mark Salyzyne74e51d2017-04-03 09:30:20 -0700859
Tom Cherry72a4e082019-12-06 10:25:37 -0800860 case '?':
861 error(EXIT_FAILURE, 0, "Unknown option '%s'.", argv[optind - 1]);
862 break;
863
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800864 default:
Tom Cherry72a4e082019-12-06 10:25:37 -0800865 error(EXIT_FAILURE, 0, "Unknown getopt_long() result '%c'.", c);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866 }
867 }
868
Tom Cherryd162f142019-10-24 17:35:26 -0700869 if (max_count_ && got_t) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800870 error(EXIT_FAILURE, 0, "Cannot use -m (--max-count) and -t together.");
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700871 }
Tom Cherryd162f142019-10-24 17:35:26 -0700872 if (print_it_anyways_ && (!regex_ || !max_count_)) {
Mark Salyzync9202772016-03-30 09:38:31 -0700873 // One day it would be nice if --print -v color and --regex <expr>
874 // could play with each other and show regex highlighted content.
Tom Cherryd162f142019-10-24 17:35:26 -0700875 fprintf(stderr,
876 "WARNING: "
877 "--print ignored, to be used in combination with\n"
878 " "
879 "--regex <expr> and --max-count <N>\n");
880 print_it_anyways_ = false;
Mark Salyzync9202772016-03-30 09:38:31 -0700881 }
Casey Dahlin6ac498d2016-03-17 14:04:52 -0700882
Tom Cherry6f061e82019-10-29 07:05:24 -0700883 // If no buffers are specified, default to using these buffers.
884 if (id_mask == 0) {
885 id_mask = (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) | (1 << LOG_ID_CRASH) |
886 (1 << LOG_ID_KERNEL);
Joe Onorato6fa09a02010-02-26 10:04:23 -0800887 }
888
Tom Cherryd162f142019-10-24 17:35:26 -0700889 if (log_rotate_size_kb_ != 0 && !output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800890 error(EXIT_FAILURE, 0, "-r requires -f as well.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800891 }
892
Tom Cherryd162f142019-10-24 17:35:26 -0700893 if (setId != 0) {
894 if (!output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800895 error(EXIT_FAILURE, 0, "--id='%s' requires -f as well.", setId);
Mark Salyzyn02687e72016-08-03 14:20:41 -0700896 }
897
Tom Cherryd162f142019-10-24 17:35:26 -0700898 std::string file_name = StringPrintf("%s.id", output_file_name_);
Mark Salyzyn02687e72016-08-03 14:20:41 -0700899 std::string file;
900 bool file_ok = android::base::ReadFileToString(file_name, &file);
Mark Salyzyn5f606602017-02-10 13:09:07 -0800901 android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
902 getuid(), getgid());
Mark Salyzynde022a82017-03-01 08:30:06 -0800903 if (!file_ok || !file.compare(setId)) setId = nullptr;
Mark Salyzyn02687e72016-08-03 14:20:41 -0700904 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800905
Mark Salyzynde022a82017-03-01 08:30:06 -0800906 if (!hasSetLogFormat) {
Tom Cherryd162f142019-10-24 17:35:26 -0700907 const char* logFormat = getenv("ANDROID_PRINTF_LOG");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908
Mark Salyzynde022a82017-03-01 08:30:06 -0800909 if (!!logFormat) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700910 for (const auto& arg : Split(logFormat, delimiters)) {
911 int err = SetLogFormat(arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800912 // environment should not cause crash of logcat
Tom Cherryd162f142019-10-24 17:35:26 -0700913 if (err < 0) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700914 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg.c_str());
Mark Salyzynb45a1752017-02-28 09:20:31 -0800915 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800916 if (err > 0) hasSetLogFormat = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800917 }
Mark Salyzynb45a1752017-02-28 09:20:31 -0800918 }
919 if (!hasSetLogFormat) {
Tom Cherryd162f142019-10-24 17:35:26 -0700920 SetLogFormat("threadtime");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800921 }
922 }
923
Mark Salyzynf3290292017-02-10 13:09:07 -0800924 if (forceFilters.size()) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700925 int err = android_log_addFilterString(logformat_.get(), forceFilters.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800926 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800927 error(EXIT_FAILURE, 0, "Invalid filter expression in logcat args.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800928 }
Elliott Hughes61b580e2018-06-15 15:16:20 -0700929 } else if (argc == optind) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800930 // Add from environment variable
Tom Cherryd162f142019-10-24 17:35:26 -0700931 const char* env_tags_orig = getenv("ANDROID_LOG_TAGS");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800932
Mark Salyzynde022a82017-03-01 08:30:06 -0800933 if (!!env_tags_orig) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700934 int err = android_log_addFilterString(logformat_.get(), env_tags_orig);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800935
Mark Salyzyn95132e92013-11-22 10:55:48 -0800936 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800937 error(EXIT_FAILURE, 0, "Invalid filter expression in ANDROID_LOG_TAGS.");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800938 }
939 }
940 } else {
941 // Add from commandline
Elliott Hughes61b580e2018-06-15 15:16:20 -0700942 for (int i = optind ; i < argc ; i++) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700943 int err = android_log_addFilterString(logformat_.get(), argv[i]);
Mark Salyzyn95132e92013-11-22 10:55:48 -0800944 if (err < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800945 error(EXIT_FAILURE, 0, "Invalid filter expression '%s'.", argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800946 }
947 }
948 }
949
Tom Cherry9156c532019-11-14 08:56:39 -0800950 if (mode & ANDROID_LOG_PSTORE) {
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800951 if (output_file_name_) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800952 error(EXIT_FAILURE, 0, "-c is ambiguous with both -f and -L specified.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800953 }
954 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800955 error(EXIT_FAILURE, 0, "-L is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800956 }
Tom Cherry9156c532019-11-14 08:56:39 -0800957 if (clearLog) {
958 unlink("/sys/fs/pstore/pmsg-ramoops-0");
959 return EXIT_SUCCESS;
960 }
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800961 }
962
963 if (output_file_name_) {
Tom Cherry9156c532019-11-14 08:56:39 -0800964 if (setLogSize || getLogSize || printStatistics || getPruneList || setPruneList) {
Tom Cherry72a4e082019-12-06 10:25:37 -0800965 error(EXIT_FAILURE, 0, "-f is incompatible with -g/-G, -S, and -p/-P.");
Tom Cherryc30a3ee2019-12-04 14:37:38 -0800966 }
967
968 if (clearLog || setId) {
969 int max_rotation_count_digits =
970 max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0;
971
972 for (int i = max_rotated_logs_; i >= 0; --i) {
973 std::string file;
974
975 if (!i) {
976 file = output_file_name_;
977 } else {
978 file = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i);
979 }
980
981 int err = unlink(file.c_str());
982
983 if (err < 0 && errno != ENOENT) {
984 fprintf(stderr, "failed to delete log file '%s': %s\n", file.c_str(),
985 strerror(errno));
986 }
987 }
988 }
989
990 if (clearLog) {
991 return EXIT_SUCCESS;
Tom Cherry9156c532019-11-14 08:56:39 -0800992 }
993 }
994
Tom Cherry6f061e82019-10-29 07:05:24 -0700995 std::unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{
996 nullptr, &android_logger_list_free};
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800997 if (tail_time != log_time::EPOCH) {
Tom Cherry6f061e82019-10-29 07:05:24 -0700998 logger_list.reset(android_logger_list_alloc_time(mode, tail_time, pid));
Mark Salyzynfa3716b2014-02-14 16:05:05 -0800999 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -07001000 logger_list.reset(android_logger_list_alloc(mode, tail_lines, pid));
Mark Salyzynfa3716b2014-02-14 16:05:05 -08001001 }
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001002 // We have three orthogonal actions below to clear, set log size and
1003 // get log size. All sharing the same iteration loop.
Tom Cherry6f061e82019-10-29 07:05:24 -07001004 std::vector<std::string> open_device_failures;
1005 std::vector<std::string> clear_failures;
1006 std::vector<std::string> set_size_failures;
1007 std::vector<std::string> get_size_failures;
1008
1009 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
1010 if (!(id_mask & (1 << i))) continue;
1011 const char* buffer_name = android_log_id_to_name(static_cast<log_id_t>(i));
1012
1013 auto logger = android_logger_open(logger_list.get(), static_cast<log_id_t>(i));
1014 if (logger == nullptr) {
1015 ReportErrorName(buffer_name, security_buffer_selected, &open_device_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001016 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001017 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001018
Tom Cherryc30a3ee2019-12-04 14:37:38 -08001019 if (clearLog) {
1020 if (android_logger_clear(logger)) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001021 ReportErrorName(buffer_name, security_buffer_selected, &clear_failures);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001022 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001023 }
1024
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001025 if (setLogSize) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001026 if (android_logger_set_log_size(logger, setLogSize)) {
1027 ReportErrorName(buffer_name, security_buffer_selected, &set_size_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001028 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001029 }
1030
Joe Onorato6fa09a02010-02-26 10:04:23 -08001031 if (getLogSize) {
Tom Cherry6f061e82019-10-29 07:05:24 -07001032 long size = android_logger_get_log_size(logger);
1033 long readable = android_logger_get_log_readable_size(logger);
Joe Onorato6fa09a02010-02-26 10:04:23 -08001034
Tom Cherry6f061e82019-10-29 07:05:24 -07001035 if (size < 0 || readable < 0) {
1036 ReportErrorName(buffer_name, security_buffer_selected, &get_size_failures);
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001037 } else {
Wei Wangc27d4812018-09-05 11:05:57 -07001038 auto size_format = format_of_size(size);
1039 auto readable_format = format_of_size(readable);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001040 std::string str = android::base::StringPrintf(
Tom Cherry6f061e82019-10-29 07:05:24 -07001041 "%s: ring buffer is %lu %sB (%lu %sB consumed),"
1042 " max entry is %d B, max payload is %d B\n",
1043 buffer_name, size_format.first, size_format.second, readable_format.first,
1044 readable_format.second, (int)LOGGER_ENTRY_MAX_LEN,
1045 (int)LOGGER_ENTRY_MAX_PAYLOAD);
Tom Cherryd162f142019-10-24 17:35:26 -07001046 TEMP_FAILURE_RETRY(write(output_fd_.get(), str.data(), str.length()));
Joe Onorato6fa09a02010-02-26 10:04:23 -08001047 }
Joe Onorato6fa09a02010-02-26 10:04:23 -08001048 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001049 }
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001050
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001051 // report any errors in the above loop and exit
Tom Cherry6f061e82019-10-29 07:05:24 -07001052 if (!open_device_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001053 error(EXIT_FAILURE, 0, "Unable to open log device%s '%s'.",
1054 open_device_failures.size() > 1 ? "s" : "", Join(open_device_failures, ",").c_str());
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001055 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001056 if (!clear_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001057 error(EXIT_FAILURE, 0, "failed to clear the '%s' log%s.", Join(clear_failures, ",").c_str(),
1058 clear_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001059 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001060 if (!set_size_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001061 error(EXIT_FAILURE, 0, "failed to set the '%s' log size%s.",
1062 Join(set_size_failures, ",").c_str(), set_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001063 }
Tom Cherry6f061e82019-10-29 07:05:24 -07001064 if (!get_size_failures.empty()) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001065 error(EXIT_FAILURE, 0, "failed to get the readable '%s' log size%s.",
1066 Join(get_size_failures, ",").c_str(), get_size_failures.size() > 1 ? "s" : "");
Mark Salyzyn603b8e52015-09-16 15:34:00 -07001067 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001068
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001069 if (setPruneList) {
Traian Schiau59763032015-04-10 15:51:39 +03001070 size_t len = strlen(setPruneList);
Tom Cherryed860ff2019-12-06 11:01:51 -08001071 if (android_logger_set_prune_list(logger_list.get(), setPruneList, len)) {
1072 error(EXIT_FAILURE, 0, "Failed to set the prune list.");
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001073 }
Tom Cherryd162f142019-10-24 17:35:26 -07001074 return EXIT_SUCCESS;
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001075 }
1076
Mark Salyzyn1c950472014-04-01 17:19:47 -07001077 if (printStatistics || getPruneList) {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001078 std::string buf(8192, '\0');
1079 size_t ret_length = 0;
1080 int retry = 32;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001081
Tom Cherrye17b4f62019-12-06 13:33:11 -08001082 for (; retry >= 0; --retry) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001083 if (getPruneList) {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001084 android_logger_get_prune_list(logger_list.get(), buf.data(), buf.size());
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001085 } else {
Tom Cherrye17b4f62019-12-06 13:33:11 -08001086 android_logger_get_statistics(logger_list.get(), buf.data(), buf.size());
Mark Salyzyndfa7a072014-02-11 12:29:31 -08001087 }
Tom Cherrye17b4f62019-12-06 13:33:11 -08001088
1089 ret_length = atol(buf.c_str());
1090 if (ret_length < 3) {
1091 error(EXIT_FAILURE, 0, "Failed to read data.");
1092 }
1093
1094 if (ret_length < buf.size()) {
Mark Salyzyn34facab2014-02-06 14:48:50 -08001095 break;
1096 }
Tom Cherrye17b4f62019-12-06 13:33:11 -08001097
1098 buf.resize(ret_length + 1);
Mark Salyzyn34facab2014-02-06 14:48:50 -08001099 }
1100
Tom Cherrye17b4f62019-12-06 13:33:11 -08001101 if (retry < 0) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001102 error(EXIT_FAILURE, 0, "Failed to read data.");
Mark Salyzyn34facab2014-02-06 14:48:50 -08001103 }
1104
Tom Cherrye17b4f62019-12-06 13:33:11 -08001105 buf.resize(ret_length);
1106 if (buf.back() == '\f') {
1107 buf.pop_back();
Mark Salyzyn34facab2014-02-06 14:48:50 -08001108 }
1109
Tom Cherrye17b4f62019-12-06 13:33:11 -08001110 // Remove the byte count prefix
1111 const char* cp = buf.c_str();
1112 while (isdigit(*cp)) ++cp;
1113 if (*cp == '\n') ++cp;
1114
1115 size_t len = strlen(cp);
Tom Cherryd162f142019-10-24 17:35:26 -07001116 TEMP_FAILURE_RETRY(write(output_fd_.get(), cp, len));
Tom Cherryd162f142019-10-24 17:35:26 -07001117 return EXIT_SUCCESS;
Mark Salyzyn34facab2014-02-06 14:48:50 -08001118 }
1119
Tom Cherryd162f142019-10-24 17:35:26 -07001120 if (getLogSize || setLogSize || clearLog) return EXIT_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121
Tom Cherryd162f142019-10-24 17:35:26 -07001122 SetupOutputAndSchedulingPolicy(!(mode & ANDROID_LOG_NONBLOCK));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001123
Tom Cherryd162f142019-10-24 17:35:26 -07001124 while (!max_count_ || print_count_ < max_count_) {
Mark Salyzyn95132e92013-11-22 10:55:48 -08001125 struct log_msg log_msg;
Tom Cherry6f061e82019-10-29 07:05:24 -07001126 int ret = android_logger_list_read(logger_list.get(), &log_msg);
Mark Salyzynde022a82017-03-01 08:30:06 -08001127 if (!ret) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001128 error(EXIT_FAILURE, 0, R"init(Unexpected EOF!
Tom Cherry41697322019-11-21 10:31:06 -08001129
Tom Cherry26d712e2020-02-14 10:01:57 -08001130This 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 -08001131messages as quickly as they were being produced.
1132
Tom Cherry72a4e082019-12-06 10:25:37 -08001133If you have enabled significant logging, look into using the -G option to increase log buffer sizes.)init");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001134 }
1135
1136 if (ret < 0) {
Mark Salyzynde022a82017-03-01 08:30:06 -08001137 if (ret == -EAGAIN) break;
Mark Salyzyn95132e92013-11-22 10:55:48 -08001138
1139 if (ret == -EIO) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001140 error(EXIT_FAILURE, 0, "Unexpected EOF!");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001141 }
1142 if (ret == -EINVAL) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001143 error(EXIT_FAILURE, 0, "Unexpected length.");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001144 }
Tom Cherry72a4e082019-12-06 10:25:37 -08001145 error(EXIT_FAILURE, errno, "Logcat read failure");
Mark Salyzyn95132e92013-11-22 10:55:48 -08001146 }
1147
Tom Cherry6f061e82019-10-29 07:05:24 -07001148 if (log_msg.id() > LOG_ID_MAX) {
Tom Cherry72a4e082019-12-06 10:25:37 -08001149 error(EXIT_FAILURE, 0, "Unexpected log id (%d) over LOG_ID_MAX (%d).", log_msg.id(),
1150 LOG_ID_MAX);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001151 }
1152
Tom Cherry6f061e82019-10-29 07:05:24 -07001153 PrintDividers(log_msg.id(), printDividers);
1154
Tom Cherryd162f142019-10-24 17:35:26 -07001155 if (print_binary_) {
1156 TEMP_FAILURE_RETRY(write(output_fd_.get(), &log_msg, log_msg.len()));
Mark Salyzyn95132e92013-11-22 10:55:48 -08001157 } else {
Tom Cherry6f061e82019-10-29 07:05:24 -07001158 ProcessBuffer(&log_msg);
Mark Salyzyn95132e92013-11-22 10:55:48 -08001159 }
1160 }
Tom Cherryd162f142019-10-24 17:35:26 -07001161 return EXIT_SUCCESS;
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001162}
1163
Tom Cherry98c6c332019-10-30 13:51:03 -07001164int main(int argc, char** argv) {
Tom Cherryd162f142019-10-24 17:35:26 -07001165 Logcat logcat;
1166 return logcat.Run(argc, argv);
Mark Salyzync0cf90d2017-02-10 13:09:07 -08001167}