blob: 3c73fea1a63fb9bb0e1e24fba4c859fbfeca0eed [file] [log] [blame]
Dan Albert58310b42015-03-13 23:06:01 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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 */
16
Elliott Hughes7bc87a52016-08-04 16:09:39 -070017#if defined(_WIN32)
Spencer Lowac3f7d92015-05-19 22:12:06 -070018#include <windows.h>
19#endif
20
Elliott Hughes4f713192015-12-04 22:00:26 -080021#include "android-base/logging.h"
Dan Albert58310b42015-03-13 23:06:01 -070022
Elliott Hughes7bc87a52016-08-04 16:09:39 -070023#include <fcntl.h>
Josh Gao5791e212018-03-16 14:25:42 -070024#include <inttypes.h>
Dan Albert7a87d052015-04-03 11:28:46 -070025#include <libgen.h>
Elliott Hughes4e5fd112016-06-21 14:25:44 -070026#include <time.h>
Dan Albert7a87d052015-04-03 11:28:46 -070027
28// For getprogname(3) or program_invocation_short_name.
29#if defined(__ANDROID__) || defined(__APPLE__)
30#include <stdlib.h>
31#elif defined(__GLIBC__)
32#include <errno.h>
33#endif
34
Elliott Hughes7bc87a52016-08-04 16:09:39 -070035#if defined(__linux__)
36#include <sys/uio.h>
37#endif
38
Tom Cherry349b0c42020-01-08 14:47:42 -080039#include <atomic>
Dan Albert58310b42015-03-13 23:06:01 -070040#include <iostream>
41#include <limits>
Josh Gao63bdcb52016-09-13 14:57:12 -070042#include <mutex>
Tom Cherry349b0c42020-01-08 14:47:42 -080043#include <optional>
Dan Albert58310b42015-03-13 23:06:01 -070044#include <sstream>
45#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070046#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070047#include <vector>
48
Andreas Gampeaf05f3b2018-02-15 11:40:30 -080049#include <android/log.h>
Tom Cherry99216302020-01-08 13:41:56 -080050#ifdef __ANDROID__
Dan Albert58310b42015-03-13 23:06:01 -070051#include <android/set_abort_message.h>
Dan Albert58310b42015-03-13 23:06:01 -070052#else
53#include <sys/types.h>
54#include <unistd.h>
55#endif
56
Elliott Hughes4679a392018-10-19 13:59:44 -070057#include <android-base/file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070058#include <android-base/macros.h>
Mark Salyzyn2507a042018-04-06 09:40:26 -070059#include <android-base/parseint.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070060#include <android-base/strings.h>
Josh Gao5791e212018-03-16 14:25:42 -070061#include <android-base/threads.h>
Elliott Hughesc1fd4922015-11-11 18:02:29 +000062
Tom Cherry349b0c42020-01-08 14:47:42 -080063#include "liblog_symbols.h"
64
Elliott Hughes11a64eb2018-06-06 12:54:41 -070065namespace android {
66namespace base {
67
68// BSD-based systems like Android/macOS have getprogname(). Others need us to provide one.
69#if defined(__GLIBC__) || defined(_WIN32)
70static const char* getprogname() {
Dan Albert5c190402015-04-29 11:32:23 -070071#if defined(__GLIBC__)
Dan Albert5c190402015-04-29 11:32:23 -070072 return program_invocation_short_name;
Josh Gao63bdcb52016-09-13 14:57:12 -070073#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070074 static bool first = true;
75 static char progname[MAX_PATH] = {};
76
77 if (first) {
Elliott Hughes4679a392018-10-19 13:59:44 -070078 snprintf(progname, sizeof(progname), "%s",
79 android::base::Basename(android::base::GetExecutablePath()).c_str());
Dan Albert5c190402015-04-29 11:32:23 -070080 first = false;
81 }
82
83 return progname;
Elliott Hughes11a64eb2018-06-06 12:54:41 -070084#endif
Dan Albert5c190402015-04-29 11:32:23 -070085}
Dan Albert5c190402015-04-29 11:32:23 -070086#endif
Mark Salyzyn2507a042018-04-06 09:40:26 -070087
Elliott Hughes11a64eb2018-06-06 12:54:41 -070088static const char* GetFileBasename(const char* file) {
89 // We can't use basename(3) even on Unix because the Mac doesn't
90 // have a non-modifying basename.
91 const char* last_slash = strrchr(file, '/');
92 if (last_slash != nullptr) {
93 return last_slash + 1;
94 }
95#if defined(_WIN32)
96 const char* last_backslash = strrchr(file, '\\');
97 if (last_backslash != nullptr) {
98 return last_backslash + 1;
99 }
100#endif
101 return file;
102}
103
Mark Salyzyn2507a042018-04-06 09:40:26 -0700104#if defined(__linux__)
Elliott Hughes11a64eb2018-06-06 12:54:41 -0700105static int OpenKmsg() {
Mark Salyzyn2507a042018-04-06 09:40:26 -0700106#if defined(__ANDROID__)
107 // pick up 'file w /dev/kmsg' environment from daemon's init rc file
108 const auto val = getenv("ANDROID_FILE__dev_kmsg");
109 if (val != nullptr) {
110 int fd;
111 if (android::base::ParseInt(val, &fd, 0)) {
112 auto flags = fcntl(fd, F_GETFL);
113 if ((flags != -1) && ((flags & O_ACCMODE) == O_WRONLY)) return fd;
114 }
115 }
116#endif
117 return TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
118}
119#endif
Dan Albert58310b42015-03-13 23:06:01 -0700120
Tom Cherrya9a6d492020-03-12 11:07:07 -0700121static LogId log_id_tToLogId(int32_t buffer_id) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800122 switch (buffer_id) {
123 case LOG_ID_MAIN:
124 return MAIN;
125 case LOG_ID_SYSTEM:
126 return SYSTEM;
127 case LOG_ID_RADIO:
128 return RADIO;
129 case LOG_ID_CRASH:
130 return CRASH;
131 case LOG_ID_DEFAULT:
132 default:
133 return DEFAULT;
134 }
135}
136
Tom Cherrya9a6d492020-03-12 11:07:07 -0700137static int32_t LogIdTolog_id_t(LogId log_id) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800138 switch (log_id) {
139 case MAIN:
140 return LOG_ID_MAIN;
141 case SYSTEM:
142 return LOG_ID_SYSTEM;
143 case RADIO:
144 return LOG_ID_RADIO;
145 case CRASH:
146 return LOG_ID_CRASH;
147 case DEFAULT:
148 default:
149 return LOG_ID_DEFAULT;
150 }
151}
152
153static LogSeverity PriorityToLogSeverity(int priority) {
154 switch (priority) {
Tom Cherry0391a872020-01-16 15:58:02 -0800155 case ANDROID_LOG_DEFAULT:
156 return INFO;
Tom Cherry349b0c42020-01-08 14:47:42 -0800157 case ANDROID_LOG_VERBOSE:
158 return VERBOSE;
159 case ANDROID_LOG_DEBUG:
160 return DEBUG;
161 case ANDROID_LOG_INFO:
162 return INFO;
163 case ANDROID_LOG_WARN:
164 return WARNING;
165 case ANDROID_LOG_ERROR:
166 return ERROR;
167 case ANDROID_LOG_FATAL:
168 return FATAL;
169 default:
170 return FATAL;
171 }
172}
173
Tom Cherrya9a6d492020-03-12 11:07:07 -0700174static int32_t LogSeverityToPriority(LogSeverity severity) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800175 switch (severity) {
176 case VERBOSE:
177 return ANDROID_LOG_VERBOSE;
178 case DEBUG:
179 return ANDROID_LOG_DEBUG;
180 case INFO:
181 return ANDROID_LOG_INFO;
182 case WARNING:
183 return ANDROID_LOG_WARN;
184 case ERROR:
185 return ANDROID_LOG_ERROR;
186 case FATAL_WITHOUT_ABORT:
187 case FATAL:
188 default:
189 return ANDROID_LOG_FATAL;
190 }
191}
192
Yabin Cui0c689532017-01-23 10:29:23 -0800193static std::mutex& LoggingLock() {
194 static auto& logging_lock = *new std::mutex();
195 return logging_lock;
196}
Dan Albert58310b42015-03-13 23:06:01 -0700197
Yabin Cui0c689532017-01-23 10:29:23 -0800198static LogFunction& Logger() {
Dan Albertb547c852015-03-27 11:20:14 -0700199#ifdef __ANDROID__
Yabin Cui0c689532017-01-23 10:29:23 -0800200 static auto& logger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700201#else
Yabin Cui0c689532017-01-23 10:29:23 -0800202 static auto& logger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700203#endif
Yabin Cui0c689532017-01-23 10:29:23 -0800204 return logger;
205}
Dan Albertb547c852015-03-27 11:20:14 -0700206
Yabin Cui0c689532017-01-23 10:29:23 -0800207static AbortFunction& Aborter() {
208 static auto& aborter = *new AbortFunction(DefaultAborter);
209 return aborter;
210}
211
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800212// Only used for Q fallback.
Andreas Gampe1923e762018-03-05 10:00:19 -0800213static std::recursive_mutex& TagLock() {
214 static auto& tag_lock = *new std::recursive_mutex();
215 return tag_lock;
216}
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800217// Only used for Q fallback.
Andreas Gampe1923e762018-03-05 10:00:19 -0800218static std::string* gDefaultTag;
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800219
Andreas Gampe1923e762018-03-05 10:00:19 -0800220void SetDefaultTag(const std::string& tag) {
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800221 static auto& liblog_functions = GetLibLogFunctions();
222 if (liblog_functions) {
223 liblog_functions->__android_log_set_default_tag(tag.c_str());
224 } else {
225 std::lock_guard<std::recursive_mutex> lock(TagLock());
226 if (gDefaultTag != nullptr) {
227 delete gDefaultTag;
228 gDefaultTag = nullptr;
229 }
230 if (!tag.empty()) {
231 gDefaultTag = new std::string(tag);
232 }
Andreas Gampe1923e762018-03-05 10:00:19 -0800233 }
Yabin Cui0c689532017-01-23 10:29:23 -0800234}
Andreas Gampe2691e332016-09-08 11:03:58 -0700235
Dan Albert7a87d052015-04-03 11:28:46 -0700236static bool gInitialized = false;
Tom Cherry0391a872020-01-16 15:58:02 -0800237
238// Only used for Q fallback.
Dan Albert58310b42015-03-13 23:06:01 -0700239static LogSeverity gMinimumLogSeverity = INFO;
Dan Albert58310b42015-03-13 23:06:01 -0700240
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700241#if defined(__linux__)
242void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
243 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700244 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700245 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700246 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
247 // level)
248 [android::base::DEBUG] = 7, // KERN_DEBUG
249 [android::base::INFO] = 6, // KERN_INFO
250 [android::base::WARNING] = 4, // KERN_WARNING
251 [android::base::ERROR] = 3, // KERN_ERROR
252 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
253 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700254 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700255 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700256 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
257 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
258
Mark Salyzyn2507a042018-04-06 09:40:26 -0700259 static int klog_fd = OpenKmsg();
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700260 if (klog_fd == -1) return;
261
262 int level = kLogSeverityToKernelLogLevel[severity];
263
264 // The kernel's printk buffer is only 1024 bytes.
265 // TODO: should we automatically break up long lines into multiple lines?
266 // Or we could log but with something like "..." at the end?
267 char buf[1024];
268 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
269 if (size > sizeof(buf)) {
270 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
271 level, tag, size);
272 }
273
274 iovec iov[1];
275 iov[0].iov_base = buf;
276 iov[0].iov_len = size;
277 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
278}
279#endif
280
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800281void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
282 const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700283 struct tm now;
284 time_t t = time(nullptr);
285
286#if defined(_WIN32)
287 localtime_s(&now, &t);
288#else
289 localtime_r(&t, &now);
290#endif
291
292 char timestamp[32];
293 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
294
Andreas Gampe550829d2016-09-07 10:10:50 -0700295 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700296 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
297 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700298 char severity_char = log_characters[severity];
Tom Cherry349b0c42020-01-08 14:47:42 -0800299 if (file != nullptr) {
300 fprintf(stderr, "%s %c %s %5d %5" PRIu64 " %s:%u] %s\n", tag ? tag : "nullptr", severity_char,
301 timestamp, getpid(), GetThreadId(), file, line, message);
302 } else {
303 fprintf(stderr, "%s %c %s %5d %5" PRIu64 " %s\n", tag ? tag : "nullptr", severity_char,
304 timestamp, getpid(), GetThreadId(), message);
305 }
Dan Albertb547c852015-03-27 11:20:14 -0700306}
307
Elliott Hughes1be0d142018-05-23 09:16:46 -0700308void StdioLogger(LogId, LogSeverity severity, const char* /*tag*/, const char* /*file*/,
309 unsigned int /*line*/, const char* message) {
310 if (severity >= WARNING) {
311 fflush(stdout);
Elliott Hughes11a64eb2018-06-06 12:54:41 -0700312 fprintf(stderr, "%s: %s\n", GetFileBasename(getprogname()), message);
Elliott Hughes1be0d142018-05-23 09:16:46 -0700313 } else {
314 fprintf(stdout, "%s\n", message);
315 }
316}
317
Andreas Gampe2691e332016-09-08 11:03:58 -0700318void DefaultAborter(const char* abort_message) {
319#ifdef __ANDROID__
320 android_set_abort_message(abort_message);
321#else
322 UNUSED(abort_message);
323#endif
324 abort();
325}
326
Dan Albertb547c852015-03-27 11:20:14 -0700327
Dan Albertb547c852015-03-27 11:20:14 -0700328LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
329}
330
Dan Albertb547c852015-03-27 11:20:14 -0700331void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
332 const char* file, unsigned int line,
333 const char* message) {
Tom Cherrya9a6d492020-03-12 11:07:07 -0700334 int32_t priority = LogSeverityToPriority(severity);
Dan Albertb547c852015-03-27 11:20:14 -0700335 if (id == DEFAULT) {
336 id = default_log_id_;
337 }
338
Tom Cherrya9a6d492020-03-12 11:07:07 -0700339 int32_t lg_id = LogIdTolog_id_t(id);
Dan Albertb547c852015-03-27 11:20:14 -0700340
Tom Cherry42ee2e42020-01-31 09:03:05 -0800341 char log_message_with_file[4068]; // LOGGER_ENTRY_MAX_PAYLOAD, not available in the NDK.
Tom Cherry349b0c42020-01-08 14:47:42 -0800342 if (priority == ANDROID_LOG_FATAL && file != nullptr) {
Tom Cherry42ee2e42020-01-31 09:03:05 -0800343 snprintf(log_message_with_file, sizeof(log_message_with_file), "%s:%u] %s", file, line,
344 message);
345 message = log_message_with_file;
Tom Cherry349b0c42020-01-08 14:47:42 -0800346 }
347
348 static auto& liblog_functions = GetLibLogFunctions();
349 if (liblog_functions) {
Tom Cherryd6699b62020-03-11 11:07:13 -0700350 __android_log_message log_message = {sizeof(__android_log_message), lg_id, priority, tag,
351 static_cast<const char*>(nullptr), 0, message};
352 liblog_functions->__android_log_logd_logger(&log_message);
Dan Albertb547c852015-03-27 11:20:14 -0700353 } else {
354 __android_log_buf_print(lg_id, priority, tag, "%s", message);
355 }
356}
Dan Albertb547c852015-03-27 11:20:14 -0700357
Andreas Gampe2691e332016-09-08 11:03:58 -0700358void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700359 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700360 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700361
Dan Albert7a87d052015-04-03 11:28:46 -0700362 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700363 return;
364 }
365
Dan Albert7a87d052015-04-03 11:28:46 -0700366 gInitialized = true;
367
Dan Albert58310b42015-03-13 23:06:01 -0700368 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800369 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
370 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700371 if (argv != nullptr) {
Andreas Gampe1923e762018-03-05 10:00:19 -0800372 SetDefaultTag(basename(argv[0]));
Dan Albert58310b42015-03-13 23:06:01 -0700373 }
Dan Albert7a87d052015-04-03 11:28:46 -0700374
Dan Albert58310b42015-03-13 23:06:01 -0700375 const char* tags = getenv("ANDROID_LOG_TAGS");
376 if (tags == nullptr) {
377 return;
378 }
379
Dan Albert47328c92015-03-19 13:24:26 -0700380 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700381 for (size_t i = 0; i < specs.size(); ++i) {
382 // "tag-pattern:[vdiwefs]"
383 std::string spec(specs[i]);
384 if (spec.size() == 3 && StartsWith(spec, "*:")) {
385 switch (spec[2]) {
386 case 'v':
Tom Cherry0391a872020-01-16 15:58:02 -0800387 SetMinimumLogSeverity(VERBOSE);
Dan Albert58310b42015-03-13 23:06:01 -0700388 continue;
389 case 'd':
Tom Cherry0391a872020-01-16 15:58:02 -0800390 SetMinimumLogSeverity(DEBUG);
Dan Albert58310b42015-03-13 23:06:01 -0700391 continue;
392 case 'i':
Tom Cherry0391a872020-01-16 15:58:02 -0800393 SetMinimumLogSeverity(INFO);
Dan Albert58310b42015-03-13 23:06:01 -0700394 continue;
395 case 'w':
Tom Cherry0391a872020-01-16 15:58:02 -0800396 SetMinimumLogSeverity(WARNING);
Dan Albert58310b42015-03-13 23:06:01 -0700397 continue;
398 case 'e':
Tom Cherry0391a872020-01-16 15:58:02 -0800399 SetMinimumLogSeverity(ERROR);
Dan Albert58310b42015-03-13 23:06:01 -0700400 continue;
401 case 'f':
Tom Cherry0391a872020-01-16 15:58:02 -0800402 SetMinimumLogSeverity(FATAL_WITHOUT_ABORT);
Dan Albert58310b42015-03-13 23:06:01 -0700403 continue;
404 // liblog will even suppress FATAL if you say 's' for silent, but that's
405 // crazy!
406 case 's':
Tom Cherry0391a872020-01-16 15:58:02 -0800407 SetMinimumLogSeverity(FATAL_WITHOUT_ABORT);
Dan Albert58310b42015-03-13 23:06:01 -0700408 continue;
409 }
410 }
411 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
412 << ")";
413 }
414}
415
Dan Albertb547c852015-03-27 11:20:14 -0700416void SetLogger(LogFunction&& logger) {
Tom Cherry2ae56062020-04-22 11:37:26 -0700417 Logger() = std::move(logger);
418
Tom Cherry349b0c42020-01-08 14:47:42 -0800419 static auto& liblog_functions = GetLibLogFunctions();
420 if (liblog_functions) {
Tom Cherryd6699b62020-03-11 11:07:13 -0700421 liblog_functions->__android_log_set_logger([](const struct __android_log_message* log_message) {
422 auto log_id = log_id_tToLogId(log_message->buffer_id);
423 auto severity = PriorityToLogSeverity(log_message->priority);
Tom Cherry349b0c42020-01-08 14:47:42 -0800424
Tom Cherry2ae56062020-04-22 11:37:26 -0700425 Logger()(log_id, severity, log_message->tag, log_message->file, log_message->line,
Tom Cherryd6699b62020-03-11 11:07:13 -0700426 log_message->message);
Tom Cherry349b0c42020-01-08 14:47:42 -0800427 });
Tom Cherry349b0c42020-01-08 14:47:42 -0800428 }
Dan Albertb547c852015-03-27 11:20:14 -0700429}
430
Andreas Gampe2691e332016-09-08 11:03:58 -0700431void SetAborter(AbortFunction&& aborter) {
Tom Cherry2ae56062020-04-22 11:37:26 -0700432 Aborter() = std::move(aborter);
433
Tom Cherry349b0c42020-01-08 14:47:42 -0800434 static auto& liblog_functions = GetLibLogFunctions();
435 if (liblog_functions) {
Tom Cherry2ae56062020-04-22 11:37:26 -0700436 liblog_functions->__android_log_set_aborter(
437 [](const char* abort_message) { Aborter()(abort_message); });
Tom Cherry349b0c42020-01-08 14:47:42 -0800438 }
Andreas Gampe2691e332016-09-08 11:03:58 -0700439}
440
Dan Albert58310b42015-03-13 23:06:01 -0700441// This indirection greatly reduces the stack impact of having lots of
442// checks/logging in a function.
443class LogMessageData {
444 public:
Tom Cherryd044eaa2020-01-10 17:18:55 -0800445 LogMessageData(const char* file, unsigned int line, LogSeverity severity, const char* tag,
446 int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700447 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700448 line_number_(line),
Dan Albert0c055862015-03-27 11:20:14 -0700449 severity_(severity),
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800450 tag_(tag),
451 error_(error) {}
Dan Albert58310b42015-03-13 23:06:01 -0700452
453 const char* GetFile() const {
454 return file_;
455 }
456
457 unsigned int GetLineNumber() const {
458 return line_number_;
459 }
460
461 LogSeverity GetSeverity() const {
462 return severity_;
463 }
464
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800465 const char* GetTag() const { return tag_; }
466
Dan Albert58310b42015-03-13 23:06:01 -0700467 int GetError() const {
468 return error_;
469 }
470
471 std::ostream& GetBuffer() {
472 return buffer_;
473 }
474
475 std::string ToString() const {
476 return buffer_.str();
477 }
478
479 private:
480 std::ostringstream buffer_;
481 const char* const file_;
482 const unsigned int line_number_;
483 const LogSeverity severity_;
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800484 const char* const tag_;
Dan Albert58310b42015-03-13 23:06:01 -0700485 const int error_;
486
487 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
488};
489
Tom Cherryd044eaa2020-01-10 17:18:55 -0800490LogMessage::LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity,
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800491 const char* tag, int error)
Tom Cherryd044eaa2020-01-10 17:18:55 -0800492 : LogMessage(file, line, severity, tag, error) {}
493
494LogMessage::LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag,
495 int error)
496 : data_(new LogMessageData(file, line, severity, tag, error)) {}
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800497
Dan Albert58310b42015-03-13 23:06:01 -0700498LogMessage::~LogMessage() {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700499 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampe1f5fb432016-09-23 16:37:12 -0700500 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700501 return;
502 }
503
Dan Albert58310b42015-03-13 23:06:01 -0700504 // Finish constructing the message.
505 if (data_->GetError() != -1) {
506 data_->GetBuffer() << ": " << strerror(data_->GetError());
507 }
508 std::string msg(data_->ToString());
509
Andreas Gampe2819c0b2018-12-05 11:26:14 -0800510 if (data_->GetSeverity() == FATAL) {
511#ifdef __ANDROID__
512 // Set the bionic abort message early to avoid liblog doing it
513 // with the individual lines, so that we get the whole message.
514 android_set_abort_message(msg.c_str());
515#endif
516 }
517
Spencer Low765ae6b2015-09-17 19:36:10 -0700518 {
519 // Do the actual logging with the lock held.
Yabin Cui0c689532017-01-23 10:29:23 -0800520 std::lock_guard<std::mutex> lock(LoggingLock());
Spencer Low765ae6b2015-09-17 19:36:10 -0700521 if (msg.find('\n') == std::string::npos) {
Tom Cherryd044eaa2020-01-10 17:18:55 -0800522 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(), data_->GetTag(),
523 msg.c_str());
Spencer Low765ae6b2015-09-17 19:36:10 -0700524 } else {
525 msg += '\n';
526 size_t i = 0;
527 while (i < msg.size()) {
528 size_t nl = msg.find('\n', i);
529 msg[nl] = '\0';
Tom Cherryd044eaa2020-01-10 17:18:55 -0800530 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(), data_->GetTag(),
531 &msg[i]);
Andreas Gampeb4e32f32016-10-04 19:17:07 -0700532 // Undo the zero-termination so we can give the complete message to the aborter.
533 msg[nl] = '\n';
Spencer Low765ae6b2015-09-17 19:36:10 -0700534 i = nl + 1;
535 }
Dan Albert58310b42015-03-13 23:06:01 -0700536 }
537 }
538
539 // Abort if necessary.
540 if (data_->GetSeverity() == FATAL) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800541 static auto& liblog_functions = GetLibLogFunctions();
542 if (liblog_functions) {
543 liblog_functions->__android_log_call_aborter(msg.c_str());
544 } else {
545 Aborter()(msg.c_str());
546 }
Dan Albert58310b42015-03-13 23:06:01 -0700547 }
548}
549
550std::ostream& LogMessage::stream() {
551 return data_->GetBuffer();
552}
553
Tom Cherryd044eaa2020-01-10 17:18:55 -0800554void LogMessage::LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
555 const char* message) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800556 static auto& liblog_functions = GetLibLogFunctions();
Tom Cherrya9a6d492020-03-12 11:07:07 -0700557 int32_t priority = LogSeverityToPriority(severity);
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800558 if (liblog_functions) {
Tom Cherryd6699b62020-03-11 11:07:13 -0700559 __android_log_message log_message = {
560 sizeof(__android_log_message), LOG_ID_DEFAULT, priority, tag, file, line, message};
561 liblog_functions->__android_log_write_log_message(&log_message);
Andreas Gampe1923e762018-03-05 10:00:19 -0800562 } else {
Tom Cherry69ee5dd2020-01-22 07:48:42 -0800563 if (tag == nullptr) {
564 std::lock_guard<std::recursive_mutex> lock(TagLock());
565 if (gDefaultTag == nullptr) {
566 gDefaultTag = new std::string(getprogname());
567 }
568
569 Logger()(DEFAULT, severity, gDefaultTag->c_str(), file, line, message);
Tom Cherry349b0c42020-01-08 14:47:42 -0800570 } else {
571 Logger()(DEFAULT, severity, tag, file, line, message);
572 }
Andreas Gampe1923e762018-03-05 10:00:19 -0800573 }
Dan Albert58310b42015-03-13 23:06:01 -0700574}
575
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700576LogSeverity GetMinimumLogSeverity() {
Tom Cherry0391a872020-01-16 15:58:02 -0800577 static auto& liblog_functions = GetLibLogFunctions();
578 if (liblog_functions) {
579 return PriorityToLogSeverity(liblog_functions->__android_log_get_minimum_priority());
580 } else {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700581 return gMinimumLogSeverity;
Tom Cherry0391a872020-01-16 15:58:02 -0800582 }
583}
584
585bool ShouldLog(LogSeverity severity, const char* tag) {
586 static auto& liblog_functions = GetLibLogFunctions();
587 // Even though we're not using the R liblog functions in this function, if we're running on Q,
588 // we need to fall back to using gMinimumLogSeverity, since __android_log_is_loggable() will not
589 // take into consideration the value from SetMinimumLogSeverity().
590 if (liblog_functions) {
Tom Cherrya9a6d492020-03-12 11:07:07 -0700591 int32_t priority = LogSeverityToPriority(severity);
Tom Cherry0391a872020-01-16 15:58:02 -0800592 return __android_log_is_loggable(priority, tag, ANDROID_LOG_INFO);
593 } else {
594 return severity >= gMinimumLogSeverity;
595 }
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700596}
597
598LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
Tom Cherry0391a872020-01-16 15:58:02 -0800599 static auto& liblog_functions = GetLibLogFunctions();
600 if (liblog_functions) {
Tom Cherrya9a6d492020-03-12 11:07:07 -0700601 int32_t priority = LogSeverityToPriority(new_severity);
Tom Cherry0391a872020-01-16 15:58:02 -0800602 return PriorityToLogSeverity(liblog_functions->__android_log_set_minimum_priority(priority));
603 } else {
604 LogSeverity old_severity = gMinimumLogSeverity;
605 gMinimumLogSeverity = new_severity;
606 return old_severity;
607 }
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700608}
609
610ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
611 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700612}
613
614ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700615 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700616}
617
618} // namespace base
619} // namespace android