blob: 33313e4a60afa14b37613671a10925342db76b57 [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>
Dan Albert7a87d052015-04-03 11:28:46 -070024#include <libgen.h>
Elliott Hughes4e5fd112016-06-21 14:25:44 -070025#include <time.h>
Dan Albert7a87d052015-04-03 11:28:46 -070026
27// For getprogname(3) or program_invocation_short_name.
28#if defined(__ANDROID__) || defined(__APPLE__)
29#include <stdlib.h>
30#elif defined(__GLIBC__)
31#include <errno.h>
32#endif
33
Elliott Hughes7bc87a52016-08-04 16:09:39 -070034#if defined(__linux__)
35#include <sys/uio.h>
36#endif
37
Dan Albert58310b42015-03-13 23:06:01 -070038#include <iostream>
39#include <limits>
Josh Gao63bdcb52016-09-13 14:57:12 -070040#include <mutex>
Dan Albert58310b42015-03-13 23:06:01 -070041#include <sstream>
42#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070043#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070044#include <vector>
45
Elliott Hughes4f713192015-12-04 22:00:26 -080046#include "android-base/macros.h"
Josh Gao63bdcb52016-09-13 14:57:12 -070047#include "android-base/mutex.h"
Elliott Hughes4f713192015-12-04 22:00:26 -080048#include "android-base/strings.h"
Dan Albert58310b42015-03-13 23:06:01 -070049
50// Headers for LogMessage::LogLine.
51#ifdef __ANDROID__
52#include <android/set_abort_message.h>
Elliott Hughese5dd71a2016-07-28 15:15:28 -070053#include "log/log.h"
Dan Albert58310b42015-03-13 23:06:01 -070054#else
55#include <sys/types.h>
56#include <unistd.h>
57#endif
58
Elliott Hughesc1fd4922015-11-11 18:02:29 +000059// For gettid.
60#if defined(__APPLE__)
61#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
62#include <stdint.h>
63#include <stdlib.h>
64#include <sys/syscall.h>
65#include <sys/time.h>
66#include <unistd.h>
67#elif defined(__linux__) && !defined(__ANDROID__)
68#include <syscall.h>
69#include <unistd.h>
70#elif defined(_WIN32)
71#include <windows.h>
72#endif
73
Dan Willemsen86cf9412016-02-03 23:29:32 -080074#if defined(_WIN32)
75typedef uint32_t thread_id;
76#else
77typedef pid_t thread_id;
78#endif
79
80static thread_id GetThreadId() {
Elliott Hughesc1fd4922015-11-11 18:02:29 +000081#if defined(__BIONIC__)
82 return gettid();
83#elif defined(__APPLE__)
84 return syscall(SYS_thread_selfid);
85#elif defined(__linux__)
86 return syscall(__NR_gettid);
87#elif defined(_WIN32)
88 return GetCurrentThreadId();
89#endif
90}
91
Dan Albert5c190402015-04-29 11:32:23 -070092namespace {
Dan Albert5c190402015-04-29 11:32:23 -070093#if defined(__GLIBC__)
94const char* getprogname() {
95 return program_invocation_short_name;
96}
Josh Gao63bdcb52016-09-13 14:57:12 -070097#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070098const char* getprogname() {
99 static bool first = true;
100 static char progname[MAX_PATH] = {};
101
102 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700103 CHAR longname[MAX_PATH];
104 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
105 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
106 // String truncation or some other error.
107 strcpy(progname, "<unknown>");
108 } else {
109 strcpy(progname, basename(longname));
110 }
Dan Albert5c190402015-04-29 11:32:23 -0700111 first = false;
112 }
113
114 return progname;
115}
Dan Albert5c190402015-04-29 11:32:23 -0700116#endif
117} // namespace
118
Dan Albert58310b42015-03-13 23:06:01 -0700119namespace android {
120namespace base {
121
Josh Gao63bdcb52016-09-13 14:57:12 -0700122static auto& logging_lock = *new std::mutex();
Dan Albert58310b42015-03-13 23:06:01 -0700123
Dan Albertb547c852015-03-27 11:20:14 -0700124#ifdef __ANDROID__
Josh Gao7df6b5f2015-11-12 11:54:47 -0800125static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700126#else
Josh Gao7df6b5f2015-11-12 11:54:47 -0800127static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700128#endif
129
Andreas Gampe2691e332016-09-08 11:03:58 -0700130static auto& gAborter = *new AbortFunction(DefaultAborter);
131
Dan Albert7a87d052015-04-03 11:28:46 -0700132static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700133static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7df6b5f2015-11-12 11:54:47 -0800134static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Albert58310b42015-03-13 23:06:01 -0700135
Dan Albert7a87d052015-04-03 11:28:46 -0700136static const char* ProgramInvocationName() {
137 if (gProgramInvocationName == nullptr) {
138 gProgramInvocationName.reset(new std::string(getprogname()));
139 }
Dan Albert58310b42015-03-13 23:06:01 -0700140
Dan Albert7a87d052015-04-03 11:28:46 -0700141 return gProgramInvocationName->c_str();
Dan Albert58310b42015-03-13 23:06:01 -0700142}
143
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700144#if defined(__linux__)
145void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
146 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700147 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700148 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700149 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
150 // level)
151 [android::base::DEBUG] = 7, // KERN_DEBUG
152 [android::base::INFO] = 6, // KERN_INFO
153 [android::base::WARNING] = 4, // KERN_WARNING
154 [android::base::ERROR] = 3, // KERN_ERROR
155 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
156 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700157 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700158 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700159 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
160 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
161
162 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
163 if (klog_fd == -1) return;
164
165 int level = kLogSeverityToKernelLogLevel[severity];
166
167 // The kernel's printk buffer is only 1024 bytes.
168 // TODO: should we automatically break up long lines into multiple lines?
169 // Or we could log but with something like "..." at the end?
170 char buf[1024];
171 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
172 if (size > sizeof(buf)) {
173 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
174 level, tag, size);
175 }
176
177 iovec iov[1];
178 iov[0].iov_base = buf;
179 iov[0].iov_len = size;
180 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
181}
182#endif
183
Dan Albertb547c852015-03-27 11:20:14 -0700184void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
185 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700186 struct tm now;
187 time_t t = time(nullptr);
188
189#if defined(_WIN32)
190 localtime_s(&now, &t);
191#else
192 localtime_r(&t, &now);
193#endif
194
195 char timestamp[32];
196 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
197
Andreas Gampe550829d2016-09-07 10:10:50 -0700198 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700199 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
200 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700201 char severity_char = log_characters[severity];
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700202 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
203 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700204}
205
Andreas Gampe2691e332016-09-08 11:03:58 -0700206void DefaultAborter(const char* abort_message) {
207#ifdef __ANDROID__
208 android_set_abort_message(abort_message);
209#else
210 UNUSED(abort_message);
211#endif
212 abort();
213}
214
Dan Albertb547c852015-03-27 11:20:14 -0700215
216#ifdef __ANDROID__
217LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
218}
219
Dan Albertb547c852015-03-27 11:20:14 -0700220void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
221 const char* file, unsigned int line,
222 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700223 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700224 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
225 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
226 ANDROID_LOG_FATAL,
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700227 };
228 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
229 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
230
Dan Albertb547c852015-03-27 11:20:14 -0700231 int priority = kLogSeverityToAndroidLogPriority[severity];
232 if (id == DEFAULT) {
233 id = default_log_id_;
234 }
235
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700236 static constexpr log_id kLogIdToAndroidLogId[] = {
237 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
238 };
239 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
240 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700241 log_id lg_id = kLogIdToAndroidLogId[id];
242
243 if (priority == ANDROID_LOG_FATAL) {
244 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
245 message);
246 } else {
247 __android_log_buf_print(lg_id, priority, tag, "%s", message);
248 }
249}
250#endif
251
Andreas Gampe2691e332016-09-08 11:03:58 -0700252void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700253 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700254 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700255
Dan Albert7a87d052015-04-03 11:28:46 -0700256 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700257 return;
258 }
259
Dan Albert7a87d052015-04-03 11:28:46 -0700260 gInitialized = true;
261
Dan Albert58310b42015-03-13 23:06:01 -0700262 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800263 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
264 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700265 if (argv != nullptr) {
Dan Albert7a87d052015-04-03 11:28:46 -0700266 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Albert58310b42015-03-13 23:06:01 -0700267 }
Dan Albert7a87d052015-04-03 11:28:46 -0700268
Dan Albert58310b42015-03-13 23:06:01 -0700269 const char* tags = getenv("ANDROID_LOG_TAGS");
270 if (tags == nullptr) {
271 return;
272 }
273
Dan Albert47328c92015-03-19 13:24:26 -0700274 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700275 for (size_t i = 0; i < specs.size(); ++i) {
276 // "tag-pattern:[vdiwefs]"
277 std::string spec(specs[i]);
278 if (spec.size() == 3 && StartsWith(spec, "*:")) {
279 switch (spec[2]) {
280 case 'v':
281 gMinimumLogSeverity = VERBOSE;
282 continue;
283 case 'd':
284 gMinimumLogSeverity = DEBUG;
285 continue;
286 case 'i':
287 gMinimumLogSeverity = INFO;
288 continue;
289 case 'w':
290 gMinimumLogSeverity = WARNING;
291 continue;
292 case 'e':
293 gMinimumLogSeverity = ERROR;
294 continue;
295 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700296 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700297 continue;
298 // liblog will even suppress FATAL if you say 's' for silent, but that's
299 // crazy!
300 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700301 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700302 continue;
303 }
304 }
305 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
306 << ")";
307 }
308}
309
Dan Albertb547c852015-03-27 11:20:14 -0700310void SetLogger(LogFunction&& logger) {
Josh Gao63bdcb52016-09-13 14:57:12 -0700311 std::lock_guard<std::mutex> lock(logging_lock);
Dan Albertb547c852015-03-27 11:20:14 -0700312 gLogger = std::move(logger);
313}
314
Andreas Gampe2691e332016-09-08 11:03:58 -0700315void SetAborter(AbortFunction&& aborter) {
Josh Gao63bdcb52016-09-13 14:57:12 -0700316 std::lock_guard<std::mutex> lock(logging_lock);
Andreas Gampe2691e332016-09-08 11:03:58 -0700317 gAborter = std::move(aborter);
318}
319
Spencer Lowbdab59a2015-08-11 16:00:13 -0700320static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800321 // We can't use basename(3) even on Unix because the Mac doesn't
322 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700323 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800324 if (last_slash != nullptr) {
325 return last_slash + 1;
326 }
327#if defined(_WIN32)
328 const char* last_backslash = strrchr(file, '\\');
329 if (last_backslash != nullptr) {
330 return last_backslash + 1;
331 }
332#endif
333 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700334}
335
Dan Albert58310b42015-03-13 23:06:01 -0700336// This indirection greatly reduces the stack impact of having lots of
337// checks/logging in a function.
338class LogMessageData {
339 public:
Dan Albert0c055862015-03-27 11:20:14 -0700340 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700341 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700342 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700343 line_number_(line),
344 id_(id),
345 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700346 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700347 }
348
349 const char* GetFile() const {
350 return file_;
351 }
352
353 unsigned int GetLineNumber() const {
354 return line_number_;
355 }
356
357 LogSeverity GetSeverity() const {
358 return severity_;
359 }
360
Dan Albert0c055862015-03-27 11:20:14 -0700361 LogId GetId() const {
362 return id_;
363 }
364
Dan Albert58310b42015-03-13 23:06:01 -0700365 int GetError() const {
366 return error_;
367 }
368
369 std::ostream& GetBuffer() {
370 return buffer_;
371 }
372
373 std::string ToString() const {
374 return buffer_.str();
375 }
376
377 private:
378 std::ostringstream buffer_;
379 const char* const file_;
380 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700381 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700382 const LogSeverity severity_;
383 const int error_;
384
385 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
386};
387
Dan Albert0c055862015-03-27 11:20:14 -0700388LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700389 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700390 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700391}
392
393LogMessage::~LogMessage() {
Dan Albert58310b42015-03-13 23:06:01 -0700394 // Finish constructing the message.
395 if (data_->GetError() != -1) {
396 data_->GetBuffer() << ": " << strerror(data_->GetError());
397 }
398 std::string msg(data_->ToString());
399
Spencer Low765ae6b2015-09-17 19:36:10 -0700400 {
401 // Do the actual logging with the lock held.
Josh Gao63bdcb52016-09-13 14:57:12 -0700402 std::lock_guard<std::mutex> lock(logging_lock);
Spencer Low765ae6b2015-09-17 19:36:10 -0700403 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700404 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700405 data_->GetSeverity(), msg.c_str());
406 } else {
407 msg += '\n';
408 size_t i = 0;
409 while (i < msg.size()) {
410 size_t nl = msg.find('\n', i);
411 msg[nl] = '\0';
412 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
413 data_->GetSeverity(), &msg[i]);
414 i = nl + 1;
415 }
Dan Albert58310b42015-03-13 23:06:01 -0700416 }
417 }
418
419 // Abort if necessary.
420 if (data_->GetSeverity() == FATAL) {
Andreas Gampe2691e332016-09-08 11:03:58 -0700421 gAborter(msg.c_str());
Dan Albert58310b42015-03-13 23:06:01 -0700422 }
423}
424
425std::ostream& LogMessage::stream() {
426 return data_->GetBuffer();
427}
428
Dan Albert0c055862015-03-27 11:20:14 -0700429void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700430 LogSeverity severity, const char* message) {
Dan Albert7a87d052015-04-03 11:28:46 -0700431 const char* tag = ProgramInvocationName();
Dan Albertb547c852015-03-27 11:20:14 -0700432 gLogger(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700433}
434
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700435LogSeverity GetMinimumLogSeverity() {
436 return gMinimumLogSeverity;
437}
438
439LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
440 LogSeverity old_severity = gMinimumLogSeverity;
441 gMinimumLogSeverity = new_severity;
442 return old_severity;
443}
444
445ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
446 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700447}
448
449ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700450 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700451}
452
453} // namespace base
454} // namespace android