blob: a0dd5f954c763198fc7cbd8cd93f6f7802cb3d6e [file] [log] [blame]
Dan Alberte3ea0582015-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 Hughes8cf75f02016-08-04 16:09:39 -070017#if defined(_WIN32)
Spencer Low47590522015-05-19 22:12:06 -070018#include <windows.h>
19#endif
20
Elliott Hughesb6351622015-12-04 22:00:26 -080021#include "android-base/logging.h"
Dan Alberte3ea0582015-03-13 23:06:01 -070022
Elliott Hughes8cf75f02016-08-04 16:09:39 -070023#include <fcntl.h>
Josh Gaoef102be2018-03-16 14:25:42 -070024#include <inttypes.h>
Dan Albert1be4dec2015-04-03 11:28:46 -070025#include <libgen.h>
Elliott Hughes6522eb52016-06-21 14:25:44 -070026#include <time.h>
Dan Albert1be4dec2015-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 Hughes8cf75f02016-08-04 16:09:39 -070035#if defined(__linux__)
36#include <sys/uio.h>
37#endif
38
Tom Cherry1bfa8ab2020-01-08 14:47:42 -080039#include <atomic>
Dan Alberte3ea0582015-03-13 23:06:01 -070040#include <iostream>
41#include <limits>
Josh Gaob08de452016-09-13 14:57:12 -070042#include <mutex>
Tom Cherry1bfa8ab2020-01-08 14:47:42 -080043#include <optional>
Dan Alberte3ea0582015-03-13 23:06:01 -070044#include <sstream>
45#include <string>
Dan Albert1f65c492015-03-27 11:20:14 -070046#include <utility>
Dan Alberte3ea0582015-03-13 23:06:01 -070047#include <vector>
48
Andreas Gampeed917072018-02-15 11:40:30 -080049#include <android/log.h>
Tom Cherry17e85802020-01-08 13:41:56 -080050#ifdef __ANDROID__
Dan Alberte3ea0582015-03-13 23:06:01 -070051#include <android/set_abort_message.h>
Dan Alberte3ea0582015-03-13 23:06:01 -070052#else
53#include <sys/types.h>
54#include <unistd.h>
55#endif
56
Elliott Hughes397961e2018-10-19 13:59:44 -070057#include <android-base/file.h>
Mark Salyzyn5cbb2512016-09-28 15:54:45 -070058#include <android-base/macros.h>
Mark Salyzyn504d8ed2018-04-06 09:40:26 -070059#include <android-base/parseint.h>
Mark Salyzyn5cbb2512016-09-28 15:54:45 -070060#include <android-base/strings.h>
Josh Gaoef102be2018-03-16 14:25:42 -070061#include <android-base/threads.h>
Elliott Hughes774d7f62015-11-11 18:02:29 +000062
Tom Cherry1bfa8ab2020-01-08 14:47:42 -080063#include "liblog_symbols.h"
Tom Cherrya6872422020-04-17 13:05:11 -070064#include "logging_splitters.h"
Tom Cherry1bfa8ab2020-01-08 14:47:42 -080065
Elliott Hughes462a45e2018-06-06 12:54:41 -070066namespace android {
67namespace base {
68
69// BSD-based systems like Android/macOS have getprogname(). Others need us to provide one.
70#if defined(__GLIBC__) || defined(_WIN32)
71static const char* getprogname() {
Dan Albertdc15ffd2015-04-29 11:32:23 -070072#if defined(__GLIBC__)
Dan Albertdc15ffd2015-04-29 11:32:23 -070073 return program_invocation_short_name;
Josh Gaob08de452016-09-13 14:57:12 -070074#elif defined(_WIN32)
Dan Albertdc15ffd2015-04-29 11:32:23 -070075 static bool first = true;
76 static char progname[MAX_PATH] = {};
77
78 if (first) {
Elliott Hughes397961e2018-10-19 13:59:44 -070079 snprintf(progname, sizeof(progname), "%s",
80 android::base::Basename(android::base::GetExecutablePath()).c_str());
Dan Albertdc15ffd2015-04-29 11:32:23 -070081 first = false;
82 }
83
84 return progname;
Elliott Hughes462a45e2018-06-06 12:54:41 -070085#endif
Dan Albertdc15ffd2015-04-29 11:32:23 -070086}
Dan Albertdc15ffd2015-04-29 11:32:23 -070087#endif
Mark Salyzyn504d8ed2018-04-06 09:40:26 -070088
Elliott Hughes462a45e2018-06-06 12:54:41 -070089static const char* GetFileBasename(const char* file) {
90 // We can't use basename(3) even on Unix because the Mac doesn't
91 // have a non-modifying basename.
92 const char* last_slash = strrchr(file, '/');
93 if (last_slash != nullptr) {
94 return last_slash + 1;
95 }
96#if defined(_WIN32)
97 const char* last_backslash = strrchr(file, '\\');
98 if (last_backslash != nullptr) {
99 return last_backslash + 1;
100 }
101#endif
102 return file;
103}
104
Mark Salyzyn504d8ed2018-04-06 09:40:26 -0700105#if defined(__linux__)
Elliott Hughes462a45e2018-06-06 12:54:41 -0700106static int OpenKmsg() {
Mark Salyzyn504d8ed2018-04-06 09:40:26 -0700107#if defined(__ANDROID__)
108 // pick up 'file w /dev/kmsg' environment from daemon's init rc file
109 const auto val = getenv("ANDROID_FILE__dev_kmsg");
110 if (val != nullptr) {
111 int fd;
112 if (android::base::ParseInt(val, &fd, 0)) {
113 auto flags = fcntl(fd, F_GETFL);
114 if ((flags != -1) && ((flags & O_ACCMODE) == O_WRONLY)) return fd;
115 }
116 }
117#endif
118 return TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
119}
120#endif
Dan Alberte3ea0582015-03-13 23:06:01 -0700121
Tom Cherry784ba9a2020-03-12 11:07:07 -0700122static LogId log_id_tToLogId(int32_t buffer_id) {
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800123 switch (buffer_id) {
124 case LOG_ID_MAIN:
125 return MAIN;
126 case LOG_ID_SYSTEM:
127 return SYSTEM;
128 case LOG_ID_RADIO:
129 return RADIO;
130 case LOG_ID_CRASH:
131 return CRASH;
132 case LOG_ID_DEFAULT:
133 default:
134 return DEFAULT;
135 }
136}
137
Tom Cherry784ba9a2020-03-12 11:07:07 -0700138static int32_t LogIdTolog_id_t(LogId log_id) {
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800139 switch (log_id) {
140 case MAIN:
141 return LOG_ID_MAIN;
142 case SYSTEM:
143 return LOG_ID_SYSTEM;
144 case RADIO:
145 return LOG_ID_RADIO;
146 case CRASH:
147 return LOG_ID_CRASH;
148 case DEFAULT:
149 default:
150 return LOG_ID_DEFAULT;
151 }
152}
153
154static LogSeverity PriorityToLogSeverity(int priority) {
155 switch (priority) {
Tom Cherry4916e092020-01-16 15:58:02 -0800156 case ANDROID_LOG_DEFAULT:
157 return INFO;
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800158 case ANDROID_LOG_VERBOSE:
159 return VERBOSE;
160 case ANDROID_LOG_DEBUG:
161 return DEBUG;
162 case ANDROID_LOG_INFO:
163 return INFO;
164 case ANDROID_LOG_WARN:
165 return WARNING;
166 case ANDROID_LOG_ERROR:
167 return ERROR;
168 case ANDROID_LOG_FATAL:
169 return FATAL;
170 default:
171 return FATAL;
172 }
173}
174
Tom Cherry784ba9a2020-03-12 11:07:07 -0700175static int32_t LogSeverityToPriority(LogSeverity severity) {
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800176 switch (severity) {
177 case VERBOSE:
178 return ANDROID_LOG_VERBOSE;
179 case DEBUG:
180 return ANDROID_LOG_DEBUG;
181 case INFO:
182 return ANDROID_LOG_INFO;
183 case WARNING:
184 return ANDROID_LOG_WARN;
185 case ERROR:
186 return ANDROID_LOG_ERROR;
187 case FATAL_WITHOUT_ABORT:
188 case FATAL:
189 default:
190 return ANDROID_LOG_FATAL;
191 }
192}
193
Yabin Cui7ff958a2017-01-23 10:29:23 -0800194static LogFunction& Logger() {
Dan Albert1f65c492015-03-27 11:20:14 -0700195#ifdef __ANDROID__
Yabin Cui7ff958a2017-01-23 10:29:23 -0800196 static auto& logger = *new LogFunction(LogdLogger());
Dan Albert1f65c492015-03-27 11:20:14 -0700197#else
Yabin Cui7ff958a2017-01-23 10:29:23 -0800198 static auto& logger = *new LogFunction(StderrLogger);
Dan Albert1f65c492015-03-27 11:20:14 -0700199#endif
Yabin Cui7ff958a2017-01-23 10:29:23 -0800200 return logger;
201}
Dan Albert1f65c492015-03-27 11:20:14 -0700202
Yabin Cui7ff958a2017-01-23 10:29:23 -0800203static AbortFunction& Aborter() {
204 static auto& aborter = *new AbortFunction(DefaultAborter);
205 return aborter;
206}
207
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800208// Only used for Q fallback.
Andreas Gampefec5b092018-03-05 10:00:19 -0800209static std::recursive_mutex& TagLock() {
210 static auto& tag_lock = *new std::recursive_mutex();
211 return tag_lock;
212}
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800213// Only used for Q fallback.
Andreas Gampefec5b092018-03-05 10:00:19 -0800214static std::string* gDefaultTag;
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800215
Andreas Gampefec5b092018-03-05 10:00:19 -0800216void SetDefaultTag(const std::string& tag) {
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800217 static auto& liblog_functions = GetLibLogFunctions();
218 if (liblog_functions) {
219 liblog_functions->__android_log_set_default_tag(tag.c_str());
220 } else {
221 std::lock_guard<std::recursive_mutex> lock(TagLock());
222 if (gDefaultTag != nullptr) {
223 delete gDefaultTag;
224 gDefaultTag = nullptr;
225 }
226 if (!tag.empty()) {
227 gDefaultTag = new std::string(tag);
228 }
Andreas Gampefec5b092018-03-05 10:00:19 -0800229 }
Yabin Cui7ff958a2017-01-23 10:29:23 -0800230}
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700231
Dan Albert1be4dec2015-04-03 11:28:46 -0700232static bool gInitialized = false;
Tom Cherry4916e092020-01-16 15:58:02 -0800233
234// Only used for Q fallback.
Dan Alberte3ea0582015-03-13 23:06:01 -0700235static LogSeverity gMinimumLogSeverity = INFO;
Dan Alberte3ea0582015-03-13 23:06:01 -0700236
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700237#if defined(__linux__)
Tom Cherrya6872422020-04-17 13:05:11 -0700238static void KernelLogLine(const char* msg, int length, android::base::LogSeverity severity,
239 const char* tag) {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700240 // clang-format off
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700241 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700242 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
243 // level)
244 [android::base::DEBUG] = 7, // KERN_DEBUG
245 [android::base::INFO] = 6, // KERN_INFO
246 [android::base::WARNING] = 4, // KERN_WARNING
247 [android::base::ERROR] = 3, // KERN_ERROR
248 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
249 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700250 };
Andreas Gamped2a4f212016-09-07 10:10:50 -0700251 // clang-format on
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700252 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
253 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
254
Mark Salyzyn504d8ed2018-04-06 09:40:26 -0700255 static int klog_fd = OpenKmsg();
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700256 if (klog_fd == -1) return;
257
258 int level = kLogSeverityToKernelLogLevel[severity];
259
260 // The kernel's printk buffer is only 1024 bytes.
261 // TODO: should we automatically break up long lines into multiple lines?
262 // Or we could log but with something like "..." at the end?
Elliott Hughes18880332020-04-29 14:10:12 -0700263 char buf[1024] __attribute__((__uninitialized__));
Tom Cherrya6872422020-04-17 13:05:11 -0700264 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %.*s\n", level, tag, length, msg);
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700265 if (size > sizeof(buf)) {
266 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
267 level, tag, size);
268 }
269
270 iovec iov[1];
271 iov[0].iov_base = buf;
272 iov[0].iov_len = size;
273 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
274}
Tom Cherrya6872422020-04-17 13:05:11 -0700275
276void KernelLogger(android::base::LogId, android::base::LogSeverity severity, const char* tag,
277 const char*, unsigned int, const char* full_message) {
278 SplitByLines(full_message, KernelLogLine, severity, tag);
279}
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700280#endif
281
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800282void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
283 const char* message) {
Elliott Hughes6522eb52016-06-21 14:25:44 -0700284 struct tm now;
285 time_t t = time(nullptr);
286
287#if defined(_WIN32)
288 localtime_s(&now, &t);
289#else
290 localtime_r(&t, &now);
291#endif
Tom Cherrya6872422020-04-17 13:05:11 -0700292 auto output_string =
293 StderrOutputGenerator(now, getpid(), GetThreadId(), severity, tag, file, line, message);
Elliott Hughes6522eb52016-06-21 14:25:44 -0700294
Tom Cherrya6872422020-04-17 13:05:11 -0700295 fputs(output_string.c_str(), stderr);
Dan Albert1f65c492015-03-27 11:20:14 -0700296}
297
Elliott Hughes1c1409f2018-05-23 09:16:46 -0700298void StdioLogger(LogId, LogSeverity severity, const char* /*tag*/, const char* /*file*/,
299 unsigned int /*line*/, const char* message) {
300 if (severity >= WARNING) {
301 fflush(stdout);
Elliott Hughes462a45e2018-06-06 12:54:41 -0700302 fprintf(stderr, "%s: %s\n", GetFileBasename(getprogname()), message);
Elliott Hughes1c1409f2018-05-23 09:16:46 -0700303 } else {
304 fprintf(stdout, "%s\n", message);
305 }
306}
307
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700308void DefaultAborter(const char* abort_message) {
309#ifdef __ANDROID__
310 android_set_abort_message(abort_message);
311#else
312 UNUSED(abort_message);
313#endif
314 abort();
315}
316
Tom Cherrya6872422020-04-17 13:05:11 -0700317static void LogdLogChunk(LogId id, LogSeverity severity, const char* tag, const char* message) {
Tom Cherry784ba9a2020-03-12 11:07:07 -0700318 int32_t lg_id = LogIdTolog_id_t(id);
Tom Cherrya6872422020-04-17 13:05:11 -0700319 int32_t priority = LogSeverityToPriority(severity);
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800320
321 static auto& liblog_functions = GetLibLogFunctions();
322 if (liblog_functions) {
Tom Cherry228eff12020-03-11 11:07:13 -0700323 __android_log_message log_message = {sizeof(__android_log_message), lg_id, priority, tag,
324 static_cast<const char*>(nullptr), 0, message};
325 liblog_functions->__android_log_logd_logger(&log_message);
Dan Albert1f65c492015-03-27 11:20:14 -0700326 } else {
327 __android_log_buf_print(lg_id, priority, tag, "%s", message);
328 }
329}
Dan Albert1f65c492015-03-27 11:20:14 -0700330
Tom Cherrya6872422020-04-17 13:05:11 -0700331LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {}
332
333void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag, const char* file,
334 unsigned int line, const char* message) {
335 if (id == DEFAULT) {
336 id = default_log_id_;
337 }
338
339 SplitByLogdChunks(id, severity, tag, file, line, message, LogdLogChunk);
340}
341
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700342void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albert1f65c492015-03-27 11:20:14 -0700343 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700344 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albert1f65c492015-03-27 11:20:14 -0700345
Dan Albert1be4dec2015-04-03 11:28:46 -0700346 if (gInitialized) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700347 return;
348 }
349
Dan Albert1be4dec2015-04-03 11:28:46 -0700350 gInitialized = true;
351
Dan Alberte3ea0582015-03-13 23:06:01 -0700352 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Lowbec78622015-11-07 18:51:54 -0800353 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
354 // and there are a couple of argv[0] variants that are commonly used.
Dan Alberte3ea0582015-03-13 23:06:01 -0700355 if (argv != nullptr) {
Andreas Gampefec5b092018-03-05 10:00:19 -0800356 SetDefaultTag(basename(argv[0]));
Dan Alberte3ea0582015-03-13 23:06:01 -0700357 }
Dan Albert1be4dec2015-04-03 11:28:46 -0700358
Dan Alberte3ea0582015-03-13 23:06:01 -0700359 const char* tags = getenv("ANDROID_LOG_TAGS");
360 if (tags == nullptr) {
361 return;
362 }
363
Dan Albert0d716d02015-03-19 13:24:26 -0700364 std::vector<std::string> specs = Split(tags, " ");
Dan Alberte3ea0582015-03-13 23:06:01 -0700365 for (size_t i = 0; i < specs.size(); ++i) {
366 // "tag-pattern:[vdiwefs]"
367 std::string spec(specs[i]);
368 if (spec.size() == 3 && StartsWith(spec, "*:")) {
369 switch (spec[2]) {
370 case 'v':
Tom Cherry4916e092020-01-16 15:58:02 -0800371 SetMinimumLogSeverity(VERBOSE);
Dan Alberte3ea0582015-03-13 23:06:01 -0700372 continue;
373 case 'd':
Tom Cherry4916e092020-01-16 15:58:02 -0800374 SetMinimumLogSeverity(DEBUG);
Dan Alberte3ea0582015-03-13 23:06:01 -0700375 continue;
376 case 'i':
Tom Cherry4916e092020-01-16 15:58:02 -0800377 SetMinimumLogSeverity(INFO);
Dan Alberte3ea0582015-03-13 23:06:01 -0700378 continue;
379 case 'w':
Tom Cherry4916e092020-01-16 15:58:02 -0800380 SetMinimumLogSeverity(WARNING);
Dan Alberte3ea0582015-03-13 23:06:01 -0700381 continue;
382 case 'e':
Tom Cherry4916e092020-01-16 15:58:02 -0800383 SetMinimumLogSeverity(ERROR);
Dan Alberte3ea0582015-03-13 23:06:01 -0700384 continue;
385 case 'f':
Tom Cherry4916e092020-01-16 15:58:02 -0800386 SetMinimumLogSeverity(FATAL_WITHOUT_ABORT);
Dan Alberte3ea0582015-03-13 23:06:01 -0700387 continue;
Luke Huang317728b2020-07-30 03:04:39 +0800388 // liblog will even suppress FATAL if you say 's' for silent, but fatal should
389 // never be suppressed.
Dan Alberte3ea0582015-03-13 23:06:01 -0700390 case 's':
Tom Cherry4916e092020-01-16 15:58:02 -0800391 SetMinimumLogSeverity(FATAL_WITHOUT_ABORT);
Dan Alberte3ea0582015-03-13 23:06:01 -0700392 continue;
393 }
394 }
395 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
396 << ")";
397 }
398}
399
Dan Albert1f65c492015-03-27 11:20:14 -0700400void SetLogger(LogFunction&& logger) {
Tom Cherry8a06da82020-04-22 11:37:26 -0700401 Logger() = std::move(logger);
402
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800403 static auto& liblog_functions = GetLibLogFunctions();
404 if (liblog_functions) {
Tom Cherry228eff12020-03-11 11:07:13 -0700405 liblog_functions->__android_log_set_logger([](const struct __android_log_message* log_message) {
406 auto log_id = log_id_tToLogId(log_message->buffer_id);
407 auto severity = PriorityToLogSeverity(log_message->priority);
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800408
Tom Cherry8a06da82020-04-22 11:37:26 -0700409 Logger()(log_id, severity, log_message->tag, log_message->file, log_message->line,
Tom Cherry228eff12020-03-11 11:07:13 -0700410 log_message->message);
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800411 });
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800412 }
Dan Albert1f65c492015-03-27 11:20:14 -0700413}
414
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700415void SetAborter(AbortFunction&& aborter) {
Tom Cherry8a06da82020-04-22 11:37:26 -0700416 Aborter() = std::move(aborter);
417
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800418 static auto& liblog_functions = GetLibLogFunctions();
419 if (liblog_functions) {
Tom Cherry8a06da82020-04-22 11:37:26 -0700420 liblog_functions->__android_log_set_aborter(
421 [](const char* abort_message) { Aborter()(abort_message); });
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800422 }
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700423}
424
Dan Alberte3ea0582015-03-13 23:06:01 -0700425// This indirection greatly reduces the stack impact of having lots of
426// checks/logging in a function.
427class LogMessageData {
428 public:
Tom Cherry46a2e0e2020-01-10 17:18:55 -0800429 LogMessageData(const char* file, unsigned int line, LogSeverity severity, const char* tag,
430 int error)
Spencer Low55853a92015-08-11 16:00:13 -0700431 : file_(GetFileBasename(file)),
Dan Albertab5c8822015-03-27 11:20:14 -0700432 line_number_(line),
Dan Albertab5c8822015-03-27 11:20:14 -0700433 severity_(severity),
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800434 tag_(tag),
435 error_(error) {}
Dan Alberte3ea0582015-03-13 23:06:01 -0700436
437 const char* GetFile() const {
438 return file_;
439 }
440
441 unsigned int GetLineNumber() const {
442 return line_number_;
443 }
444
445 LogSeverity GetSeverity() const {
446 return severity_;
447 }
448
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800449 const char* GetTag() const { return tag_; }
450
Dan Alberte3ea0582015-03-13 23:06:01 -0700451 int GetError() const {
452 return error_;
453 }
454
455 std::ostream& GetBuffer() {
456 return buffer_;
457 }
458
459 std::string ToString() const {
460 return buffer_.str();
461 }
462
463 private:
464 std::ostringstream buffer_;
465 const char* const file_;
466 const unsigned int line_number_;
467 const LogSeverity severity_;
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800468 const char* const tag_;
Dan Alberte3ea0582015-03-13 23:06:01 -0700469 const int error_;
470
471 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
472};
473
Tom Cherry46a2e0e2020-01-10 17:18:55 -0800474LogMessage::LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity,
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800475 const char* tag, int error)
Tom Cherry46a2e0e2020-01-10 17:18:55 -0800476 : LogMessage(file, line, severity, tag, error) {}
477
478LogMessage::LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag,
479 int error)
480 : data_(new LogMessageData(file, line, severity, tag, error)) {}
Tomasz Wasilczyka419de22017-12-18 06:30:17 -0800481
Dan Alberte3ea0582015-03-13 23:06:01 -0700482LogMessage::~LogMessage() {
Andreas Gampec65ea942016-09-23 13:31:52 -0700483 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampecb35a4a2016-09-23 16:37:12 -0700484 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampec65ea942016-09-23 13:31:52 -0700485 return;
486 }
487
Dan Alberte3ea0582015-03-13 23:06:01 -0700488 // Finish constructing the message.
489 if (data_->GetError() != -1) {
490 data_->GetBuffer() << ": " << strerror(data_->GetError());
491 }
492 std::string msg(data_->ToString());
493
Andreas Gampe2f9e49f2018-12-05 11:26:14 -0800494 if (data_->GetSeverity() == FATAL) {
495#ifdef __ANDROID__
496 // Set the bionic abort message early to avoid liblog doing it
497 // with the individual lines, so that we get the whole message.
498 android_set_abort_message(msg.c_str());
499#endif
500 }
501
Tom Cherrya6872422020-04-17 13:05:11 -0700502 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(), data_->GetTag(),
503 msg.c_str());
Dan Alberte3ea0582015-03-13 23:06:01 -0700504
505 // Abort if necessary.
506 if (data_->GetSeverity() == FATAL) {
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800507 static auto& liblog_functions = GetLibLogFunctions();
508 if (liblog_functions) {
509 liblog_functions->__android_log_call_aborter(msg.c_str());
510 } else {
511 Aborter()(msg.c_str());
512 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700513 }
514}
515
516std::ostream& LogMessage::stream() {
517 return data_->GetBuffer();
518}
519
Tom Cherry46a2e0e2020-01-10 17:18:55 -0800520void LogMessage::LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
521 const char* message) {
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800522 static auto& liblog_functions = GetLibLogFunctions();
Tom Cherry784ba9a2020-03-12 11:07:07 -0700523 int32_t priority = LogSeverityToPriority(severity);
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800524 if (liblog_functions) {
Tom Cherry228eff12020-03-11 11:07:13 -0700525 __android_log_message log_message = {
526 sizeof(__android_log_message), LOG_ID_DEFAULT, priority, tag, file, line, message};
527 liblog_functions->__android_log_write_log_message(&log_message);
Andreas Gampefec5b092018-03-05 10:00:19 -0800528 } else {
Tom Cherrydbc07ce2020-01-22 07:48:42 -0800529 if (tag == nullptr) {
530 std::lock_guard<std::recursive_mutex> lock(TagLock());
531 if (gDefaultTag == nullptr) {
532 gDefaultTag = new std::string(getprogname());
533 }
534
535 Logger()(DEFAULT, severity, gDefaultTag->c_str(), file, line, message);
Tom Cherry1bfa8ab2020-01-08 14:47:42 -0800536 } else {
537 Logger()(DEFAULT, severity, tag, file, line, message);
538 }
Andreas Gampefec5b092018-03-05 10:00:19 -0800539 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700540}
541
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700542LogSeverity GetMinimumLogSeverity() {
Tom Cherry4916e092020-01-16 15:58:02 -0800543 static auto& liblog_functions = GetLibLogFunctions();
544 if (liblog_functions) {
545 return PriorityToLogSeverity(liblog_functions->__android_log_get_minimum_priority());
546 } else {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700547 return gMinimumLogSeverity;
Tom Cherry4916e092020-01-16 15:58:02 -0800548 }
549}
550
551bool ShouldLog(LogSeverity severity, const char* tag) {
552 static auto& liblog_functions = GetLibLogFunctions();
553 // Even though we're not using the R liblog functions in this function, if we're running on Q,
554 // we need to fall back to using gMinimumLogSeverity, since __android_log_is_loggable() will not
555 // take into consideration the value from SetMinimumLogSeverity().
556 if (liblog_functions) {
Tom Cherry784ba9a2020-03-12 11:07:07 -0700557 int32_t priority = LogSeverityToPriority(severity);
Tom Cherry4916e092020-01-16 15:58:02 -0800558 return __android_log_is_loggable(priority, tag, ANDROID_LOG_INFO);
559 } else {
560 return severity >= gMinimumLogSeverity;
561 }
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700562}
563
564LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
Tom Cherry4916e092020-01-16 15:58:02 -0800565 static auto& liblog_functions = GetLibLogFunctions();
566 if (liblog_functions) {
Tom Cherry784ba9a2020-03-12 11:07:07 -0700567 int32_t priority = LogSeverityToPriority(new_severity);
Tom Cherry4916e092020-01-16 15:58:02 -0800568 return PriorityToLogSeverity(liblog_functions->__android_log_set_minimum_priority(priority));
569 } else {
570 LogSeverity old_severity = gMinimumLogSeverity;
571 gMinimumLogSeverity = new_severity;
572 return old_severity;
573 }
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700574}
575
576ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
577 old_ = SetMinimumLogSeverity(new_severity);
Dan Alberte3ea0582015-03-13 23:06:01 -0700578}
579
580ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700581 SetMinimumLogSeverity(old_);
Dan Alberte3ea0582015-03-13 23:06:01 -0700582}
583
584} // namespace base
585} // namespace android