/* * Copyright (C) 2006-2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define DEFAULT_MAX_ROTATED_LOGS 4 using android::base::Join; using android::base::ParseByteCount; using android::base::ParseUint; using android::base::Split; using android::base::StringPrintf; class Logcat { public: int Run(int argc, char** argv); private: void RotateLogs(); void ProcessBuffer(struct log_msg* buf); void PrintDividers(log_id_t log_id, bool print_dividers); void SetupOutputAndSchedulingPolicy(bool blocking); int SetLogFormat(const char* format_string); // Used for all options android::base::unique_fd output_fd_{dup(STDOUT_FILENO)}; std::unique_ptr logformat_{ android_log_format_new(), &android_log_format_free}; // For logging to a file and log rotation const char* output_file_name_ = nullptr; size_t log_rotate_size_kb_ = 0; // 0 means "no log rotation" size_t max_rotated_logs_ = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded" size_t out_byte_count_ = 0; // For binary log buffers int print_binary_ = 0; std::unique_ptr event_tag_map_{ nullptr, &android_closeEventTagMap}; bool has_opened_event_tag_map_ = false; // For the related --regex, --max-count, --print std::unique_ptr regex_; size_t max_count_ = 0; // 0 means "infinite" size_t print_count_ = 0; bool print_it_anyways_ = false; // For PrintDividers() log_id_t last_printed_id_ = LOG_ID_MAX; bool printed_start_[LOG_ID_MAX] = {}; bool debug_ = false; }; // logd prefixes records with a length field #define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t) enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT }; // if show_help is set, newline required in fmt statement to transition to usage static void LogcatPanic(enum helpType showHelp, const char* fmt, ...) __printflike(2, 3) __attribute__((__noreturn__)); #ifndef F2FS_IOC_SET_PIN_FILE #define F2FS_IOCTL_MAGIC 0xf5 #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) #endif static int openLogFile(const char* pathname, size_t sizeKB) { int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR); if (fd < 0) { return fd; } // no need to check errors __u32 set = 1; ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set); fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, (sizeKB << 10)); return fd; } void Logcat::RotateLogs() { // Can't rotate logs if we're not outputting to a file if (!output_file_name_) return; output_fd_.reset(); // Compute the maximum number of digits needed to count up to // maxRotatedLogs in decimal. eg: // maxRotatedLogs == 30 // -> log10(30) == 1.477 // -> maxRotationCountDigits == 2 int max_rotation_count_digits = max_rotated_logs_ > 0 ? (int)(floor(log10(max_rotated_logs_) + 1)) : 0; for (int i = max_rotated_logs_; i > 0; i--) { std::string file1 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i); std::string file0; if (!(i - 1)) { file0 = output_file_name_; } else { file0 = StringPrintf("%s.%.*d", output_file_name_, max_rotation_count_digits, i - 1); } if (!file0.length() || !file1.length()) { perror("while rotating log files"); break; } int err = rename(file0.c_str(), file1.c_str()); if (err < 0 && errno != ENOENT) { perror("while rotating log files"); } } output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_)); if (!output_fd_.ok()) { LogcatPanic(HELP_FALSE, "couldn't open output file"); } out_byte_count_ = 0; } void Logcat::ProcessBuffer(struct log_msg* buf) { int bytesWritten = 0; int err; AndroidLogEntry entry; char binaryMsgBuf[1024]; bool is_binary = buf->id() == LOG_ID_EVENTS || buf->id() == LOG_ID_STATS || buf->id() == LOG_ID_SECURITY; if (is_binary) { if (!event_tag_map_ && !has_opened_event_tag_map_) { event_tag_map_.reset(android_openEventTagMap(nullptr)); has_opened_event_tag_map_ = true; } err = android_log_processBinaryLogBuffer(&buf->entry, &entry, event_tag_map_.get(), binaryMsgBuf, sizeof(binaryMsgBuf)); // printf(">>> pri=%d len=%d msg='%s'\n", // entry.priority, entry.messageLen, entry.message); } else { err = android_log_processLogBuffer(&buf->entry, &entry); } if (err < 0 && !debug_) return; if (android_log_shouldPrintLine(logformat_.get(), std::string(entry.tag, entry.tagLen).c_str(), entry.priority)) { bool match = !regex_ || std::regex_search(entry.message, entry.message + entry.messageLen, *regex_); print_count_ += match; if (match || print_it_anyways_) { bytesWritten = android_log_printLogLine(logformat_.get(), output_fd_.get(), &entry); if (bytesWritten < 0) { LogcatPanic(HELP_FALSE, "output error"); } } } out_byte_count_ += bytesWritten; if (log_rotate_size_kb_ > 0 && (out_byte_count_ / 1024) >= log_rotate_size_kb_) { RotateLogs(); } } void Logcat::PrintDividers(log_id_t log_id, bool print_dividers) { if (log_id == last_printed_id_ || print_binary_) { return; } if (!printed_start_[log_id] || print_dividers) { if (dprintf(output_fd_.get(), "--------- %s %s\n", printed_start_[log_id] ? "switch to" : "beginning of", android_log_id_to_name(log_id)) < 0) { LogcatPanic(HELP_FALSE, "output error"); } } last_printed_id_ = log_id; printed_start_[log_id] = true; } void Logcat::SetupOutputAndSchedulingPolicy(bool blocking) { if (!output_file_name_) return; if (blocking) { // Lower priority and set to batch scheduling if we are saving // the logs into files and taking continuous content. if (set_sched_policy(0, SP_BACKGROUND) < 0) { fprintf(stderr, "failed to set background scheduling policy\n"); } struct sched_param param = {}; if (sched_setscheduler((pid_t)0, SCHED_BATCH, ¶m) < 0) { fprintf(stderr, "failed to set to batch scheduler\n"); } if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) { fprintf(stderr, "failed set to priority\n"); } } output_fd_.reset(openLogFile(output_file_name_, log_rotate_size_kb_)); if (!output_fd_.ok()) { LogcatPanic(HELP_FALSE, "couldn't open output file"); } struct stat statbuf; if (fstat(output_fd_.get(), &statbuf) == -1) { output_fd_.reset(); LogcatPanic(HELP_FALSE, "couldn't get output file stat\n"); } if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) { output_fd_.reset(); LogcatPanic(HELP_FALSE, "invalid output file stat\n"); } out_byte_count_ = statbuf.st_size; } // clang-format off static void show_help() { const char* cmd = getprogname(); fprintf(stderr, "Usage: %s [options] [filterspecs]\n", cmd); fprintf(stderr, "options include:\n" " -s Set default filter to silent. Equivalent to filterspec '*:S'\n" " -f , --file= Log to file. Default is stdout\n" " -r , --rotate-kbytes=\n" " Rotate log every kbytes. Requires -f option\n" " -n , --rotate-count=\n" " Sets max number of rotated logs to , default 4\n" " --id= If the signature id for logging to file changes, then clear\n" " the fileset and continue\n" " -v , --format=\n" " Sets log print format verb and adverbs, where is:\n" " brief help long process raw tag thread threadtime time\n" " and individually flagged modifying adverbs can be added:\n" " color descriptive epoch monotonic printable uid\n" " usec UTC year zone\n" " Multiple -v parameters or comma separated list of format and\n" " format modifiers are allowed.\n" // private and undocumented nsec, no signal, too much noise // useful for -T or -t accurate testing though. " -D, --dividers Print dividers between each log buffer\n" " -c, --clear Clear (flush) the entire log and exit\n" " if Log to File specified, clear fileset instead\n" " -d Dump the log and then exit (don't block)\n" " -e , --regex=\n" " Only print lines where the log message matches \n" " where is a regular expression\n" // Leave --head undocumented as alias for -m " -m , --max-count=\n" " Quit after printing lines. This is meant to be\n" " paired with --regex, but will work on its own.\n" " --print Paired with --regex and --max-count to let content bypass\n" " regex filter but still stop at number of matches.\n" // Leave --tail undocumented as alias for -t " -t Print only the most recent lines (implies -d)\n" " -t '