blob: 1f47a9fa39e6bc17f1632c39e3d4611cf9ed7bae [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) {
191 static constexpr int kLogSeverityToKernelLogLevel[] = {
192 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log level)
193 [android::base::DEBUG] = 7, // KERN_DEBUG
194 [android::base::INFO] = 6, // KERN_INFO
195 [android::base::WARNING] = 4, // KERN_WARNING
196 [android::base::ERROR] = 3, // KERN_ERROR
197 [android::base::FATAL] = 2, // KERN_CRIT
198 };
199 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
200 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
201
202 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
203 if (klog_fd == -1) return;
204
205 int level = kLogSeverityToKernelLogLevel[severity];
206
207 // The kernel's printk buffer is only 1024 bytes.
208 // TODO: should we automatically break up long lines into multiple lines?
209 // Or we could log but with something like "..." at the end?
210 char buf[1024];
211 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
212 if (size > sizeof(buf)) {
213 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
214 level, tag, size);
215 }
216
217 iovec iov[1];
218 iov[0].iov_base = buf;
219 iov[0].iov_len = size;
220 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
221}
222#endif
223
Dan Albertb547c852015-03-27 11:20:14 -0700224void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
225 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700226 struct tm now;
227 time_t t = time(nullptr);
228
229#if defined(_WIN32)
230 localtime_s(&now, &t);
231#else
232 localtime_r(&t, &now);
233#endif
234
235 char timestamp[32];
236 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
237
Spencer Lowbdab59a2015-08-11 16:00:13 -0700238 static const char log_characters[] = "VDIWEF";
239 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
240 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700241 char severity_char = log_characters[severity];
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700242 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
243 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700244}
245
246
247#ifdef __ANDROID__
248LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
249}
250
Dan Albertb547c852015-03-27 11:20:14 -0700251void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
252 const char* file, unsigned int line,
253 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700254 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
255 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
256 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
257 };
258 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
259 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
260
Dan Albertb547c852015-03-27 11:20:14 -0700261 int priority = kLogSeverityToAndroidLogPriority[severity];
262 if (id == DEFAULT) {
263 id = default_log_id_;
264 }
265
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700266 static constexpr log_id kLogIdToAndroidLogId[] = {
267 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
268 };
269 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
270 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700271 log_id lg_id = kLogIdToAndroidLogId[id];
272
273 if (priority == ANDROID_LOG_FATAL) {
274 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
275 message);
276 } else {
277 __android_log_buf_print(lg_id, priority, tag, "%s", message);
278 }
279}
280#endif
281
282void InitLogging(char* argv[], LogFunction&& logger) {
283 SetLogger(std::forward<LogFunction>(logger));
284 InitLogging(argv);
285}
286
Dan Albert58310b42015-03-13 23:06:01 -0700287void InitLogging(char* argv[]) {
Dan Albert7a87d052015-04-03 11:28:46 -0700288 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700289 return;
290 }
291
Dan Albert7a87d052015-04-03 11:28:46 -0700292 gInitialized = true;
293
Dan Albert58310b42015-03-13 23:06:01 -0700294 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800295 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
296 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700297 if (argv != nullptr) {
Dan Albert7a87d052015-04-03 11:28:46 -0700298 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Albert58310b42015-03-13 23:06:01 -0700299 }
Dan Albert7a87d052015-04-03 11:28:46 -0700300
Dan Albert58310b42015-03-13 23:06:01 -0700301 const char* tags = getenv("ANDROID_LOG_TAGS");
302 if (tags == nullptr) {
303 return;
304 }
305
Dan Albert47328c92015-03-19 13:24:26 -0700306 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700307 for (size_t i = 0; i < specs.size(); ++i) {
308 // "tag-pattern:[vdiwefs]"
309 std::string spec(specs[i]);
310 if (spec.size() == 3 && StartsWith(spec, "*:")) {
311 switch (spec[2]) {
312 case 'v':
313 gMinimumLogSeverity = VERBOSE;
314 continue;
315 case 'd':
316 gMinimumLogSeverity = DEBUG;
317 continue;
318 case 'i':
319 gMinimumLogSeverity = INFO;
320 continue;
321 case 'w':
322 gMinimumLogSeverity = WARNING;
323 continue;
324 case 'e':
325 gMinimumLogSeverity = ERROR;
326 continue;
327 case 'f':
328 gMinimumLogSeverity = FATAL;
329 continue;
330 // liblog will even suppress FATAL if you say 's' for silent, but that's
331 // crazy!
332 case 's':
333 gMinimumLogSeverity = FATAL;
334 continue;
335 }
336 }
337 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
338 << ")";
339 }
340}
341
Dan Albertb547c852015-03-27 11:20:14 -0700342void SetLogger(LogFunction&& logger) {
Dan Albert5c190402015-04-29 11:32:23 -0700343 lock_guard<mutex> lock(logging_lock);
Dan Albertb547c852015-03-27 11:20:14 -0700344 gLogger = std::move(logger);
345}
346
Spencer Lowbdab59a2015-08-11 16:00:13 -0700347static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800348 // We can't use basename(3) even on Unix because the Mac doesn't
349 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700350 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800351 if (last_slash != nullptr) {
352 return last_slash + 1;
353 }
354#if defined(_WIN32)
355 const char* last_backslash = strrchr(file, '\\');
356 if (last_backslash != nullptr) {
357 return last_backslash + 1;
358 }
359#endif
360 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700361}
362
Dan Albert58310b42015-03-13 23:06:01 -0700363// This indirection greatly reduces the stack impact of having lots of
364// checks/logging in a function.
365class LogMessageData {
366 public:
Dan Albert0c055862015-03-27 11:20:14 -0700367 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700368 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700369 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700370 line_number_(line),
371 id_(id),
372 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700373 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700374 }
375
376 const char* GetFile() const {
377 return file_;
378 }
379
380 unsigned int GetLineNumber() const {
381 return line_number_;
382 }
383
384 LogSeverity GetSeverity() const {
385 return severity_;
386 }
387
Dan Albert0c055862015-03-27 11:20:14 -0700388 LogId GetId() const {
389 return id_;
390 }
391
Dan Albert58310b42015-03-13 23:06:01 -0700392 int GetError() const {
393 return error_;
394 }
395
396 std::ostream& GetBuffer() {
397 return buffer_;
398 }
399
400 std::string ToString() const {
401 return buffer_.str();
402 }
403
404 private:
405 std::ostringstream buffer_;
406 const char* const file_;
407 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700408 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700409 const LogSeverity severity_;
410 const int error_;
411
412 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
413};
414
Dan Albert0c055862015-03-27 11:20:14 -0700415LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700416 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700417 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700418}
419
420LogMessage::~LogMessage() {
Dan Albert58310b42015-03-13 23:06:01 -0700421 // Finish constructing the message.
422 if (data_->GetError() != -1) {
423 data_->GetBuffer() << ": " << strerror(data_->GetError());
424 }
425 std::string msg(data_->ToString());
426
Spencer Low765ae6b2015-09-17 19:36:10 -0700427 {
428 // Do the actual logging with the lock held.
429 lock_guard<mutex> lock(logging_lock);
430 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700431 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700432 data_->GetSeverity(), msg.c_str());
433 } else {
434 msg += '\n';
435 size_t i = 0;
436 while (i < msg.size()) {
437 size_t nl = msg.find('\n', i);
438 msg[nl] = '\0';
439 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
440 data_->GetSeverity(), &msg[i]);
441 i = nl + 1;
442 }
Dan Albert58310b42015-03-13 23:06:01 -0700443 }
444 }
445
446 // Abort if necessary.
447 if (data_->GetSeverity() == FATAL) {
448#ifdef __ANDROID__
449 android_set_abort_message(msg.c_str());
450#endif
451 abort();
452 }
453}
454
455std::ostream& LogMessage::stream() {
456 return data_->GetBuffer();
457}
458
Dan Albert0c055862015-03-27 11:20:14 -0700459void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700460 LogSeverity severity, const char* message) {
Dan Albert7a87d052015-04-03 11:28:46 -0700461 const char* tag = ProgramInvocationName();
Dan Albertb547c852015-03-27 11:20:14 -0700462 gLogger(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700463}
464
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700465LogSeverity GetMinimumLogSeverity() {
466 return gMinimumLogSeverity;
467}
468
469LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
470 LogSeverity old_severity = gMinimumLogSeverity;
471 gMinimumLogSeverity = new_severity;
472 return old_severity;
473}
474
475ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
476 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700477}
478
479ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700480 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700481}
482
483} // namespace base
484} // namespace android