blob: 86d3b4d267559170e66d14ba29ba1cce7b0078a7 [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>
40#include <sstream>
41#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070042#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070043#include <vector>
44
Dan Albert5c190402015-04-29 11:32:23 -070045#ifndef _WIN32
46#include <mutex>
Dan Albert5c190402015-04-29 11:32:23 -070047#endif
48
Elliott Hughes4f713192015-12-04 22:00:26 -080049#include "android-base/macros.h"
50#include "android-base/strings.h"
Dan Albert58310b42015-03-13 23:06:01 -070051
52// Headers for LogMessage::LogLine.
53#ifdef __ANDROID__
54#include <android/set_abort_message.h>
Elliott Hughese5dd71a2016-07-28 15:15:28 -070055#include "log/log.h"
Dan Albert58310b42015-03-13 23:06:01 -070056#else
57#include <sys/types.h>
58#include <unistd.h>
59#endif
60
Elliott Hughesc1fd4922015-11-11 18:02:29 +000061// For gettid.
62#if defined(__APPLE__)
63#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
64#include <stdint.h>
65#include <stdlib.h>
66#include <sys/syscall.h>
67#include <sys/time.h>
68#include <unistd.h>
69#elif defined(__linux__) && !defined(__ANDROID__)
70#include <syscall.h>
71#include <unistd.h>
72#elif defined(_WIN32)
73#include <windows.h>
74#endif
75
Dan Willemsen86cf9412016-02-03 23:29:32 -080076#if defined(_WIN32)
77typedef uint32_t thread_id;
78#else
79typedef pid_t thread_id;
80#endif
81
82static thread_id GetThreadId() {
Elliott Hughesc1fd4922015-11-11 18:02:29 +000083#if defined(__BIONIC__)
84 return gettid();
85#elif defined(__APPLE__)
86 return syscall(SYS_thread_selfid);
87#elif defined(__linux__)
88 return syscall(__NR_gettid);
89#elif defined(_WIN32)
90 return GetCurrentThreadId();
91#endif
92}
93
Dan Albert5c190402015-04-29 11:32:23 -070094namespace {
95#ifndef _WIN32
96using std::mutex;
97using std::lock_guard;
98
99#if defined(__GLIBC__)
100const char* getprogname() {
101 return program_invocation_short_name;
102}
103#endif
104
105#else
106const char* getprogname() {
107 static bool first = true;
108 static char progname[MAX_PATH] = {};
109
110 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700111 CHAR longname[MAX_PATH];
112 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
113 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
114 // String truncation or some other error.
115 strcpy(progname, "<unknown>");
116 } else {
117 strcpy(progname, basename(longname));
118 }
Dan Albert5c190402015-04-29 11:32:23 -0700119 first = false;
120 }
121
122 return progname;
123}
124
125class mutex {
126 public:
127 mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700128 InitializeCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700129 }
130 ~mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700131 DeleteCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700132 }
133
134 void lock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700135 EnterCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700136 }
137
138 void unlock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700139 LeaveCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700140 }
141
142 private:
Spencer Lowbdab59a2015-08-11 16:00:13 -0700143 CRITICAL_SECTION critical_section_;
Dan Albert5c190402015-04-29 11:32:23 -0700144};
145
146template <typename LockT>
147class lock_guard {
148 public:
149 explicit lock_guard(LockT& lock) : lock_(lock) {
150 lock_.lock();
151 }
152
153 ~lock_guard() {
154 lock_.unlock();
155 }
156
157 private:
158 LockT& lock_;
159
160 DISALLOW_COPY_AND_ASSIGN(lock_guard);
161};
162#endif
163} // namespace
164
Dan Albert58310b42015-03-13 23:06:01 -0700165namespace android {
166namespace base {
167
Josh Gao7df6b5f2015-11-12 11:54:47 -0800168static auto& logging_lock = *new mutex();
Dan Albert58310b42015-03-13 23:06:01 -0700169
Dan Albertb547c852015-03-27 11:20:14 -0700170#ifdef __ANDROID__
Josh Gao7df6b5f2015-11-12 11:54:47 -0800171static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700172#else
Josh Gao7df6b5f2015-11-12 11:54:47 -0800173static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700174#endif
175
Dan Albert7a87d052015-04-03 11:28:46 -0700176static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700177static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7df6b5f2015-11-12 11:54:47 -0800178static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Albert58310b42015-03-13 23:06:01 -0700179
Dan Albert7a87d052015-04-03 11:28:46 -0700180static const char* ProgramInvocationName() {
181 if (gProgramInvocationName == nullptr) {
182 gProgramInvocationName.reset(new std::string(getprogname()));
183 }
Dan Albert58310b42015-03-13 23:06:01 -0700184
Dan Albert7a87d052015-04-03 11:28:46 -0700185 return gProgramInvocationName->c_str();
Dan Albert58310b42015-03-13 23:06:01 -0700186}
187
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700188#if defined(__linux__)
189void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
190 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700191 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700192 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700193 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
194 // level)
195 [android::base::DEBUG] = 7, // KERN_DEBUG
196 [android::base::INFO] = 6, // KERN_INFO
197 [android::base::WARNING] = 4, // KERN_WARNING
198 [android::base::ERROR] = 3, // KERN_ERROR
199 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
200 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700201 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700202 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700203 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
204 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
205
206 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
207 if (klog_fd == -1) return;
208
209 int level = kLogSeverityToKernelLogLevel[severity];
210
211 // The kernel's printk buffer is only 1024 bytes.
212 // TODO: should we automatically break up long lines into multiple lines?
213 // Or we could log but with something like "..." at the end?
214 char buf[1024];
215 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
216 if (size > sizeof(buf)) {
217 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
218 level, tag, size);
219 }
220
221 iovec iov[1];
222 iov[0].iov_base = buf;
223 iov[0].iov_len = size;
224 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
225}
226#endif
227
Dan Albertb547c852015-03-27 11:20:14 -0700228void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
229 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700230 struct tm now;
231 time_t t = time(nullptr);
232
233#if defined(_WIN32)
234 localtime_s(&now, &t);
235#else
236 localtime_r(&t, &now);
237#endif
238
239 char timestamp[32];
240 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
241
Andreas Gampe550829d2016-09-07 10:10:50 -0700242 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700243 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
244 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700245 char severity_char = log_characters[severity];
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700246 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
247 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700248}
249
250
251#ifdef __ANDROID__
252LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
253}
254
Dan Albertb547c852015-03-27 11:20:14 -0700255void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
256 const char* file, unsigned int line,
257 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700258 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700259 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
260 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
261 ANDROID_LOG_FATAL,
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700262 };
263 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
264 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
265
Dan Albertb547c852015-03-27 11:20:14 -0700266 int priority = kLogSeverityToAndroidLogPriority[severity];
267 if (id == DEFAULT) {
268 id = default_log_id_;
269 }
270
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700271 static constexpr log_id kLogIdToAndroidLogId[] = {
272 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
273 };
274 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
275 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700276 log_id lg_id = kLogIdToAndroidLogId[id];
277
278 if (priority == ANDROID_LOG_FATAL) {
279 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
280 message);
281 } else {
282 __android_log_buf_print(lg_id, priority, tag, "%s", message);
283 }
284}
285#endif
286
287void InitLogging(char* argv[], LogFunction&& logger) {
288 SetLogger(std::forward<LogFunction>(logger));
289 InitLogging(argv);
290}
291
Dan Albert58310b42015-03-13 23:06:01 -0700292void InitLogging(char* argv[]) {
Dan Albert7a87d052015-04-03 11:28:46 -0700293 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700294 return;
295 }
296
Dan Albert7a87d052015-04-03 11:28:46 -0700297 gInitialized = true;
298
Dan Albert58310b42015-03-13 23:06:01 -0700299 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800300 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
301 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700302 if (argv != nullptr) {
Dan Albert7a87d052015-04-03 11:28:46 -0700303 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Albert58310b42015-03-13 23:06:01 -0700304 }
Dan Albert7a87d052015-04-03 11:28:46 -0700305
Dan Albert58310b42015-03-13 23:06:01 -0700306 const char* tags = getenv("ANDROID_LOG_TAGS");
307 if (tags == nullptr) {
308 return;
309 }
310
Dan Albert47328c92015-03-19 13:24:26 -0700311 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700312 for (size_t i = 0; i < specs.size(); ++i) {
313 // "tag-pattern:[vdiwefs]"
314 std::string spec(specs[i]);
315 if (spec.size() == 3 && StartsWith(spec, "*:")) {
316 switch (spec[2]) {
317 case 'v':
318 gMinimumLogSeverity = VERBOSE;
319 continue;
320 case 'd':
321 gMinimumLogSeverity = DEBUG;
322 continue;
323 case 'i':
324 gMinimumLogSeverity = INFO;
325 continue;
326 case 'w':
327 gMinimumLogSeverity = WARNING;
328 continue;
329 case 'e':
330 gMinimumLogSeverity = ERROR;
331 continue;
332 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700333 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700334 continue;
335 // liblog will even suppress FATAL if you say 's' for silent, but that's
336 // crazy!
337 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700338 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700339 continue;
340 }
341 }
342 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
343 << ")";
344 }
345}
346
Dan Albertb547c852015-03-27 11:20:14 -0700347void SetLogger(LogFunction&& logger) {
Dan Albert5c190402015-04-29 11:32:23 -0700348 lock_guard<mutex> lock(logging_lock);
Dan Albertb547c852015-03-27 11:20:14 -0700349 gLogger = std::move(logger);
350}
351
Spencer Lowbdab59a2015-08-11 16:00:13 -0700352static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800353 // We can't use basename(3) even on Unix because the Mac doesn't
354 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700355 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800356 if (last_slash != nullptr) {
357 return last_slash + 1;
358 }
359#if defined(_WIN32)
360 const char* last_backslash = strrchr(file, '\\');
361 if (last_backslash != nullptr) {
362 return last_backslash + 1;
363 }
364#endif
365 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700366}
367
Dan Albert58310b42015-03-13 23:06:01 -0700368// This indirection greatly reduces the stack impact of having lots of
369// checks/logging in a function.
370class LogMessageData {
371 public:
Dan Albert0c055862015-03-27 11:20:14 -0700372 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700373 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700374 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700375 line_number_(line),
376 id_(id),
377 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700378 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700379 }
380
381 const char* GetFile() const {
382 return file_;
383 }
384
385 unsigned int GetLineNumber() const {
386 return line_number_;
387 }
388
389 LogSeverity GetSeverity() const {
390 return severity_;
391 }
392
Dan Albert0c055862015-03-27 11:20:14 -0700393 LogId GetId() const {
394 return id_;
395 }
396
Dan Albert58310b42015-03-13 23:06:01 -0700397 int GetError() const {
398 return error_;
399 }
400
401 std::ostream& GetBuffer() {
402 return buffer_;
403 }
404
405 std::string ToString() const {
406 return buffer_.str();
407 }
408
409 private:
410 std::ostringstream buffer_;
411 const char* const file_;
412 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700413 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700414 const LogSeverity severity_;
415 const int error_;
416
417 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
418};
419
Dan Albert0c055862015-03-27 11:20:14 -0700420LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700421 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700422 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700423}
424
425LogMessage::~LogMessage() {
Dan Albert58310b42015-03-13 23:06:01 -0700426 // Finish constructing the message.
427 if (data_->GetError() != -1) {
428 data_->GetBuffer() << ": " << strerror(data_->GetError());
429 }
430 std::string msg(data_->ToString());
431
Spencer Low765ae6b2015-09-17 19:36:10 -0700432 {
433 // Do the actual logging with the lock held.
434 lock_guard<mutex> lock(logging_lock);
435 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700436 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700437 data_->GetSeverity(), msg.c_str());
438 } else {
439 msg += '\n';
440 size_t i = 0;
441 while (i < msg.size()) {
442 size_t nl = msg.find('\n', i);
443 msg[nl] = '\0';
444 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
445 data_->GetSeverity(), &msg[i]);
446 i = nl + 1;
447 }
Dan Albert58310b42015-03-13 23:06:01 -0700448 }
449 }
450
451 // Abort if necessary.
452 if (data_->GetSeverity() == FATAL) {
453#ifdef __ANDROID__
454 android_set_abort_message(msg.c_str());
455#endif
456 abort();
457 }
458}
459
460std::ostream& LogMessage::stream() {
461 return data_->GetBuffer();
462}
463
Dan Albert0c055862015-03-27 11:20:14 -0700464void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700465 LogSeverity severity, const char* message) {
Dan Albert7a87d052015-04-03 11:28:46 -0700466 const char* tag = ProgramInvocationName();
Dan Albertb547c852015-03-27 11:20:14 -0700467 gLogger(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700468}
469
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700470LogSeverity GetMinimumLogSeverity() {
471 return gMinimumLogSeverity;
472}
473
474LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
475 LogSeverity old_severity = gMinimumLogSeverity;
476 gMinimumLogSeverity = new_severity;
477 return old_severity;
478}
479
480ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
481 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700482}
483
484ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700485 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700486}
487
488} // namespace base
489} // namespace android