blob: 6e1dd9ca344ac562903d2aafeac80842267db16b [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>
Dan Albert1be4dec2015-04-03 11:28:46 -070024#include <libgen.h>
Elliott Hughes6522eb52016-06-21 14:25:44 -070025#include <time.h>
Dan Albert1be4dec2015-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 Hughes8cf75f02016-08-04 16:09:39 -070034#if defined(__linux__)
35#include <sys/uio.h>
36#endif
37
Dan Alberte3ea0582015-03-13 23:06:01 -070038#include <iostream>
39#include <limits>
40#include <sstream>
41#include <string>
Dan Albert1f65c492015-03-27 11:20:14 -070042#include <utility>
Dan Alberte3ea0582015-03-13 23:06:01 -070043#include <vector>
44
Dan Albertdc15ffd2015-04-29 11:32:23 -070045#ifndef _WIN32
46#include <mutex>
Dan Albertdc15ffd2015-04-29 11:32:23 -070047#endif
48
Elliott Hughesb6351622015-12-04 22:00:26 -080049#include "android-base/macros.h"
50#include "android-base/strings.h"
Dan Alberte3ea0582015-03-13 23:06:01 -070051
52// Headers for LogMessage::LogLine.
53#ifdef __ANDROID__
54#include <android/set_abort_message.h>
Elliott Hughes7d9a4792016-07-28 15:15:28 -070055#include "log/log.h"
Dan Alberte3ea0582015-03-13 23:06:01 -070056#else
57#include <sys/types.h>
58#include <unistd.h>
59#endif
60
Elliott Hughes774d7f62015-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 Willemsenc4e54252016-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 Hughes774d7f62015-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 Albertdc15ffd2015-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 Low55853a92015-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 Albertdc15ffd2015-04-29 11:32:23 -0700119 first = false;
120 }
121
122 return progname;
123}
124
125class mutex {
126 public:
127 mutex() {
Spencer Low55853a92015-08-11 16:00:13 -0700128 InitializeCriticalSection(&critical_section_);
Dan Albertdc15ffd2015-04-29 11:32:23 -0700129 }
130 ~mutex() {
Spencer Low55853a92015-08-11 16:00:13 -0700131 DeleteCriticalSection(&critical_section_);
Dan Albertdc15ffd2015-04-29 11:32:23 -0700132 }
133
134 void lock() {
Spencer Low55853a92015-08-11 16:00:13 -0700135 EnterCriticalSection(&critical_section_);
Dan Albertdc15ffd2015-04-29 11:32:23 -0700136 }
137
138 void unlock() {
Spencer Low55853a92015-08-11 16:00:13 -0700139 LeaveCriticalSection(&critical_section_);
Dan Albertdc15ffd2015-04-29 11:32:23 -0700140 }
141
142 private:
Spencer Low55853a92015-08-11 16:00:13 -0700143 CRITICAL_SECTION critical_section_;
Dan Albertdc15ffd2015-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 Alberte3ea0582015-03-13 23:06:01 -0700165namespace android {
166namespace base {
167
Josh Gao7f438622015-11-12 11:54:47 -0800168static auto& logging_lock = *new mutex();
Dan Alberte3ea0582015-03-13 23:06:01 -0700169
Dan Albert1f65c492015-03-27 11:20:14 -0700170#ifdef __ANDROID__
Josh Gao7f438622015-11-12 11:54:47 -0800171static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albert1f65c492015-03-27 11:20:14 -0700172#else
Josh Gao7f438622015-11-12 11:54:47 -0800173static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albert1f65c492015-03-27 11:20:14 -0700174#endif
175
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700176static auto& gAborter = *new AbortFunction(DefaultAborter);
177
Dan Albert1be4dec2015-04-03 11:28:46 -0700178static bool gInitialized = false;
Dan Alberte3ea0582015-03-13 23:06:01 -0700179static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7f438622015-11-12 11:54:47 -0800180static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Alberte3ea0582015-03-13 23:06:01 -0700181
Dan Albert1be4dec2015-04-03 11:28:46 -0700182static const char* ProgramInvocationName() {
183 if (gProgramInvocationName == nullptr) {
184 gProgramInvocationName.reset(new std::string(getprogname()));
185 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700186
Dan Albert1be4dec2015-04-03 11:28:46 -0700187 return gProgramInvocationName->c_str();
Dan Alberte3ea0582015-03-13 23:06:01 -0700188}
189
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700190#if defined(__linux__)
191void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
192 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700193 // clang-format off
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700194 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700195 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
196 // level)
197 [android::base::DEBUG] = 7, // KERN_DEBUG
198 [android::base::INFO] = 6, // KERN_INFO
199 [android::base::WARNING] = 4, // KERN_WARNING
200 [android::base::ERROR] = 3, // KERN_ERROR
201 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
202 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700203 };
Andreas Gamped2a4f212016-09-07 10:10:50 -0700204 // clang-format on
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700205 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
206 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
207
208 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
209 if (klog_fd == -1) return;
210
211 int level = kLogSeverityToKernelLogLevel[severity];
212
213 // The kernel's printk buffer is only 1024 bytes.
214 // TODO: should we automatically break up long lines into multiple lines?
215 // Or we could log but with something like "..." at the end?
216 char buf[1024];
217 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
218 if (size > sizeof(buf)) {
219 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
220 level, tag, size);
221 }
222
223 iovec iov[1];
224 iov[0].iov_base = buf;
225 iov[0].iov_len = size;
226 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
227}
228#endif
229
Dan Albert1f65c492015-03-27 11:20:14 -0700230void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
231 unsigned int line, const char* message) {
Elliott Hughes6522eb52016-06-21 14:25:44 -0700232 struct tm now;
233 time_t t = time(nullptr);
234
235#if defined(_WIN32)
236 localtime_s(&now, &t);
237#else
238 localtime_r(&t, &now);
239#endif
240
241 char timestamp[32];
242 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
243
Andreas Gamped2a4f212016-09-07 10:10:50 -0700244 static const char log_characters[] = "VDIWEFF";
Spencer Low55853a92015-08-11 16:00:13 -0700245 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
246 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albert1f65c492015-03-27 11:20:14 -0700247 char severity_char = log_characters[severity];
Elliott Hughes6522eb52016-06-21 14:25:44 -0700248 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
249 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albert1f65c492015-03-27 11:20:14 -0700250}
251
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700252void DefaultAborter(const char* abort_message) {
253#ifdef __ANDROID__
254 android_set_abort_message(abort_message);
255#else
256 UNUSED(abort_message);
257#endif
258 abort();
259}
260
Dan Albert1f65c492015-03-27 11:20:14 -0700261
262#ifdef __ANDROID__
263LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
264}
265
Dan Albert1f65c492015-03-27 11:20:14 -0700266void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
267 const char* file, unsigned int line,
268 const char* message) {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700269 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700270 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
271 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
272 ANDROID_LOG_FATAL,
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700273 };
274 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
275 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
276
Dan Albert1f65c492015-03-27 11:20:14 -0700277 int priority = kLogSeverityToAndroidLogPriority[severity];
278 if (id == DEFAULT) {
279 id = default_log_id_;
280 }
281
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700282 static constexpr log_id kLogIdToAndroidLogId[] = {
283 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
284 };
285 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
286 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albert1f65c492015-03-27 11:20:14 -0700287 log_id lg_id = kLogIdToAndroidLogId[id];
288
289 if (priority == ANDROID_LOG_FATAL) {
290 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
291 message);
292 } else {
293 __android_log_buf_print(lg_id, priority, tag, "%s", message);
294 }
295}
296#endif
297
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700298void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albert1f65c492015-03-27 11:20:14 -0700299 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700300 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albert1f65c492015-03-27 11:20:14 -0700301
Dan Albert1be4dec2015-04-03 11:28:46 -0700302 if (gInitialized) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700303 return;
304 }
305
Dan Albert1be4dec2015-04-03 11:28:46 -0700306 gInitialized = true;
307
Dan Alberte3ea0582015-03-13 23:06:01 -0700308 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Lowbec78622015-11-07 18:51:54 -0800309 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
310 // and there are a couple of argv[0] variants that are commonly used.
Dan Alberte3ea0582015-03-13 23:06:01 -0700311 if (argv != nullptr) {
Dan Albert1be4dec2015-04-03 11:28:46 -0700312 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Alberte3ea0582015-03-13 23:06:01 -0700313 }
Dan Albert1be4dec2015-04-03 11:28:46 -0700314
Dan Alberte3ea0582015-03-13 23:06:01 -0700315 const char* tags = getenv("ANDROID_LOG_TAGS");
316 if (tags == nullptr) {
317 return;
318 }
319
Dan Albert0d716d02015-03-19 13:24:26 -0700320 std::vector<std::string> specs = Split(tags, " ");
Dan Alberte3ea0582015-03-13 23:06:01 -0700321 for (size_t i = 0; i < specs.size(); ++i) {
322 // "tag-pattern:[vdiwefs]"
323 std::string spec(specs[i]);
324 if (spec.size() == 3 && StartsWith(spec, "*:")) {
325 switch (spec[2]) {
326 case 'v':
327 gMinimumLogSeverity = VERBOSE;
328 continue;
329 case 'd':
330 gMinimumLogSeverity = DEBUG;
331 continue;
332 case 'i':
333 gMinimumLogSeverity = INFO;
334 continue;
335 case 'w':
336 gMinimumLogSeverity = WARNING;
337 continue;
338 case 'e':
339 gMinimumLogSeverity = ERROR;
340 continue;
341 case 'f':
Andreas Gamped2a4f212016-09-07 10:10:50 -0700342 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Alberte3ea0582015-03-13 23:06:01 -0700343 continue;
344 // liblog will even suppress FATAL if you say 's' for silent, but that's
345 // crazy!
346 case 's':
Andreas Gamped2a4f212016-09-07 10:10:50 -0700347 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Alberte3ea0582015-03-13 23:06:01 -0700348 continue;
349 }
350 }
351 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
352 << ")";
353 }
354}
355
Dan Albert1f65c492015-03-27 11:20:14 -0700356void SetLogger(LogFunction&& logger) {
Dan Albertdc15ffd2015-04-29 11:32:23 -0700357 lock_guard<mutex> lock(logging_lock);
Dan Albert1f65c492015-03-27 11:20:14 -0700358 gLogger = std::move(logger);
359}
360
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700361void SetAborter(AbortFunction&& aborter) {
362 lock_guard<mutex> lock(logging_lock);
363 gAborter = std::move(aborter);
364}
365
Spencer Low55853a92015-08-11 16:00:13 -0700366static const char* GetFileBasename(const char* file) {
Spencer Lowbec78622015-11-07 18:51:54 -0800367 // We can't use basename(3) even on Unix because the Mac doesn't
368 // have a non-modifying basename.
Spencer Low55853a92015-08-11 16:00:13 -0700369 const char* last_slash = strrchr(file, '/');
Spencer Lowbec78622015-11-07 18:51:54 -0800370 if (last_slash != nullptr) {
371 return last_slash + 1;
372 }
373#if defined(_WIN32)
374 const char* last_backslash = strrchr(file, '\\');
375 if (last_backslash != nullptr) {
376 return last_backslash + 1;
377 }
378#endif
379 return file;
Spencer Low55853a92015-08-11 16:00:13 -0700380}
381
Dan Alberte3ea0582015-03-13 23:06:01 -0700382// This indirection greatly reduces the stack impact of having lots of
383// checks/logging in a function.
384class LogMessageData {
385 public:
Dan Albertab5c8822015-03-27 11:20:14 -0700386 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Lowe0671d62015-09-17 19:36:10 -0700387 LogSeverity severity, int error)
Spencer Low55853a92015-08-11 16:00:13 -0700388 : file_(GetFileBasename(file)),
Dan Albertab5c8822015-03-27 11:20:14 -0700389 line_number_(line),
390 id_(id),
391 severity_(severity),
Spencer Lowe0671d62015-09-17 19:36:10 -0700392 error_(error) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700393 }
394
395 const char* GetFile() const {
396 return file_;
397 }
398
399 unsigned int GetLineNumber() const {
400 return line_number_;
401 }
402
403 LogSeverity GetSeverity() const {
404 return severity_;
405 }
406
Dan Albertab5c8822015-03-27 11:20:14 -0700407 LogId GetId() const {
408 return id_;
409 }
410
Dan Alberte3ea0582015-03-13 23:06:01 -0700411 int GetError() const {
412 return error_;
413 }
414
415 std::ostream& GetBuffer() {
416 return buffer_;
417 }
418
419 std::string ToString() const {
420 return buffer_.str();
421 }
422
423 private:
424 std::ostringstream buffer_;
425 const char* const file_;
426 const unsigned int line_number_;
Dan Albertab5c8822015-03-27 11:20:14 -0700427 const LogId id_;
Dan Alberte3ea0582015-03-13 23:06:01 -0700428 const LogSeverity severity_;
429 const int error_;
430
431 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
432};
433
Dan Albertab5c8822015-03-27 11:20:14 -0700434LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Alberte3ea0582015-03-13 23:06:01 -0700435 LogSeverity severity, int error)
Spencer Lowe0671d62015-09-17 19:36:10 -0700436 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700437}
438
439LogMessage::~LogMessage() {
Dan Alberte3ea0582015-03-13 23:06:01 -0700440 // Finish constructing the message.
441 if (data_->GetError() != -1) {
442 data_->GetBuffer() << ": " << strerror(data_->GetError());
443 }
444 std::string msg(data_->ToString());
445
Spencer Lowe0671d62015-09-17 19:36:10 -0700446 {
447 // Do the actual logging with the lock held.
448 lock_guard<mutex> lock(logging_lock);
449 if (msg.find('\n') == std::string::npos) {
Dan Albertab5c8822015-03-27 11:20:14 -0700450 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Lowe0671d62015-09-17 19:36:10 -0700451 data_->GetSeverity(), msg.c_str());
452 } else {
453 msg += '\n';
454 size_t i = 0;
455 while (i < msg.size()) {
456 size_t nl = msg.find('\n', i);
457 msg[nl] = '\0';
458 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
459 data_->GetSeverity(), &msg[i]);
460 i = nl + 1;
461 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700462 }
463 }
464
465 // Abort if necessary.
466 if (data_->GetSeverity() == FATAL) {
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700467 gAborter(msg.c_str());
Dan Alberte3ea0582015-03-13 23:06:01 -0700468 }
469}
470
471std::ostream& LogMessage::stream() {
472 return data_->GetBuffer();
473}
474
Dan Albertab5c8822015-03-27 11:20:14 -0700475void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albert1f65c492015-03-27 11:20:14 -0700476 LogSeverity severity, const char* message) {
Dan Albert1be4dec2015-04-03 11:28:46 -0700477 const char* tag = ProgramInvocationName();
Dan Albert1f65c492015-03-27 11:20:14 -0700478 gLogger(id, severity, tag, file, line, message);
Dan Alberte3ea0582015-03-13 23:06:01 -0700479}
480
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700481LogSeverity GetMinimumLogSeverity() {
482 return gMinimumLogSeverity;
483}
484
485LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
486 LogSeverity old_severity = gMinimumLogSeverity;
487 gMinimumLogSeverity = new_severity;
488 return old_severity;
489}
490
491ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
492 old_ = SetMinimumLogSeverity(new_severity);
Dan Alberte3ea0582015-03-13 23:06:01 -0700493}
494
495ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700496 SetMinimumLogSeverity(old_);
Dan Alberte3ea0582015-03-13 23:06:01 -0700497}
498
499} // namespace base
500} // namespace android