blob: 6357b4ba7320cb5ba7b46dcc1bbe506fabd36b07 [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
Dan Albert58310b42015-03-13 23:06:01 -070046// Headers for LogMessage::LogLine.
47#ifdef __ANDROID__
Mark Salyzyncfd5b082016-10-17 14:28:00 -070048#include <log/log.h>
Dan Albert58310b42015-03-13 23:06:01 -070049#include <android/set_abort_message.h>
Dan Albert58310b42015-03-13 23:06:01 -070050#else
51#include <sys/types.h>
52#include <unistd.h>
53#endif
54
Mark Salyzynff2dcd92016-09-28 15:54:45 -070055#include <android-base/macros.h>
56#include <android-base/strings.h>
57
Elliott Hughesc1fd4922015-11-11 18:02:29 +000058// For gettid.
59#if defined(__APPLE__)
60#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
61#include <stdint.h>
62#include <stdlib.h>
63#include <sys/syscall.h>
64#include <sys/time.h>
65#include <unistd.h>
66#elif defined(__linux__) && !defined(__ANDROID__)
67#include <syscall.h>
68#include <unistd.h>
69#elif defined(_WIN32)
70#include <windows.h>
71#endif
72
Dan Willemsen86cf9412016-02-03 23:29:32 -080073#if defined(_WIN32)
74typedef uint32_t thread_id;
75#else
76typedef pid_t thread_id;
77#endif
78
79static thread_id GetThreadId() {
Elliott Hughesc1fd4922015-11-11 18:02:29 +000080#if defined(__BIONIC__)
81 return gettid();
82#elif defined(__APPLE__)
83 return syscall(SYS_thread_selfid);
84#elif defined(__linux__)
85 return syscall(__NR_gettid);
86#elif defined(_WIN32)
87 return GetCurrentThreadId();
88#endif
89}
90
Dan Albert5c190402015-04-29 11:32:23 -070091namespace {
Dan Albert5c190402015-04-29 11:32:23 -070092#if defined(__GLIBC__)
93const char* getprogname() {
94 return program_invocation_short_name;
95}
Josh Gao63bdcb52016-09-13 14:57:12 -070096#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070097const char* getprogname() {
98 static bool first = true;
99 static char progname[MAX_PATH] = {};
100
101 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700102 CHAR longname[MAX_PATH];
103 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
104 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
105 // String truncation or some other error.
106 strcpy(progname, "<unknown>");
107 } else {
108 strcpy(progname, basename(longname));
109 }
Dan Albert5c190402015-04-29 11:32:23 -0700110 first = false;
111 }
112
113 return progname;
114}
Dan Albert5c190402015-04-29 11:32:23 -0700115#endif
116} // namespace
117
Dan Albert58310b42015-03-13 23:06:01 -0700118namespace android {
119namespace base {
120
Yabin Cui0c689532017-01-23 10:29:23 -0800121static std::mutex& LoggingLock() {
122 static auto& logging_lock = *new std::mutex();
123 return logging_lock;
124}
Dan Albert58310b42015-03-13 23:06:01 -0700125
Yabin Cui0c689532017-01-23 10:29:23 -0800126static LogFunction& Logger() {
Dan Albertb547c852015-03-27 11:20:14 -0700127#ifdef __ANDROID__
Yabin Cui0c689532017-01-23 10:29:23 -0800128 static auto& logger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700129#else
Yabin Cui0c689532017-01-23 10:29:23 -0800130 static auto& logger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700131#endif
Yabin Cui0c689532017-01-23 10:29:23 -0800132 return logger;
133}
Dan Albertb547c852015-03-27 11:20:14 -0700134
Yabin Cui0c689532017-01-23 10:29:23 -0800135static AbortFunction& Aborter() {
136 static auto& aborter = *new AbortFunction(DefaultAborter);
137 return aborter;
138}
139
140static std::string& ProgramInvocationName() {
141 static auto& programInvocationName = *new std::string(getprogname());
142 return programInvocationName;
143}
Andreas Gampe2691e332016-09-08 11:03:58 -0700144
Dan Albert7a87d052015-04-03 11:28:46 -0700145static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700146static LogSeverity gMinimumLogSeverity = INFO;
Dan Albert58310b42015-03-13 23:06:01 -0700147
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700148#if defined(__linux__)
149void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
150 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700151 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700152 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700153 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
154 // level)
155 [android::base::DEBUG] = 7, // KERN_DEBUG
156 [android::base::INFO] = 6, // KERN_INFO
157 [android::base::WARNING] = 4, // KERN_WARNING
158 [android::base::ERROR] = 3, // KERN_ERROR
159 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
160 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700161 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700162 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700163 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
164 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
165
166 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
167 if (klog_fd == -1) return;
168
169 int level = kLogSeverityToKernelLogLevel[severity];
170
171 // The kernel's printk buffer is only 1024 bytes.
172 // TODO: should we automatically break up long lines into multiple lines?
173 // Or we could log but with something like "..." at the end?
174 char buf[1024];
175 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
176 if (size > sizeof(buf)) {
177 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
178 level, tag, size);
179 }
180
181 iovec iov[1];
182 iov[0].iov_base = buf;
183 iov[0].iov_len = size;
184 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
185}
186#endif
187
Dan Albertb547c852015-03-27 11:20:14 -0700188void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
189 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700190 struct tm now;
191 time_t t = time(nullptr);
192
193#if defined(_WIN32)
194 localtime_s(&now, &t);
195#else
196 localtime_r(&t, &now);
197#endif
198
199 char timestamp[32];
200 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
201
Andreas Gampe550829d2016-09-07 10:10:50 -0700202 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700203 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
204 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700205 char severity_char = log_characters[severity];
Yabin Cui0c689532017-01-23 10:29:23 -0800206 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700207 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700208}
209
Andreas Gampe2691e332016-09-08 11:03:58 -0700210void DefaultAborter(const char* abort_message) {
211#ifdef __ANDROID__
212 android_set_abort_message(abort_message);
213#else
214 UNUSED(abort_message);
215#endif
216 abort();
217}
218
Dan Albertb547c852015-03-27 11:20:14 -0700219
220#ifdef __ANDROID__
221LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
222}
223
Dan Albertb547c852015-03-27 11:20:14 -0700224void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
225 const char* file, unsigned int line,
226 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700227 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700228 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
229 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
230 ANDROID_LOG_FATAL,
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700231 };
232 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
233 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
234
Dan Albertb547c852015-03-27 11:20:14 -0700235 int priority = kLogSeverityToAndroidLogPriority[severity];
236 if (id == DEFAULT) {
237 id = default_log_id_;
238 }
239
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700240 static constexpr log_id kLogIdToAndroidLogId[] = {
241 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
242 };
243 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
244 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700245 log_id lg_id = kLogIdToAndroidLogId[id];
246
247 if (priority == ANDROID_LOG_FATAL) {
248 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
249 message);
250 } else {
251 __android_log_buf_print(lg_id, priority, tag, "%s", message);
252 }
253}
254#endif
255
Andreas Gampe2691e332016-09-08 11:03:58 -0700256void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700257 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700258 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700259
Dan Albert7a87d052015-04-03 11:28:46 -0700260 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700261 return;
262 }
263
Dan Albert7a87d052015-04-03 11:28:46 -0700264 gInitialized = true;
265
Dan Albert58310b42015-03-13 23:06:01 -0700266 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800267 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
268 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700269 if (argv != nullptr) {
Yabin Cui0c689532017-01-23 10:29:23 -0800270 std::lock_guard<std::mutex> lock(LoggingLock());
271 ProgramInvocationName() = basename(argv[0]);
Dan Albert58310b42015-03-13 23:06:01 -0700272 }
Dan Albert7a87d052015-04-03 11:28:46 -0700273
Dan Albert58310b42015-03-13 23:06:01 -0700274 const char* tags = getenv("ANDROID_LOG_TAGS");
275 if (tags == nullptr) {
276 return;
277 }
278
Dan Albert47328c92015-03-19 13:24:26 -0700279 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700280 for (size_t i = 0; i < specs.size(); ++i) {
281 // "tag-pattern:[vdiwefs]"
282 std::string spec(specs[i]);
283 if (spec.size() == 3 && StartsWith(spec, "*:")) {
284 switch (spec[2]) {
285 case 'v':
286 gMinimumLogSeverity = VERBOSE;
287 continue;
288 case 'd':
289 gMinimumLogSeverity = DEBUG;
290 continue;
291 case 'i':
292 gMinimumLogSeverity = INFO;
293 continue;
294 case 'w':
295 gMinimumLogSeverity = WARNING;
296 continue;
297 case 'e':
298 gMinimumLogSeverity = ERROR;
299 continue;
300 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700301 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700302 continue;
303 // liblog will even suppress FATAL if you say 's' for silent, but that's
304 // crazy!
305 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700306 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700307 continue;
308 }
309 }
310 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
311 << ")";
312 }
313}
314
Dan Albertb547c852015-03-27 11:20:14 -0700315void SetLogger(LogFunction&& logger) {
Yabin Cui0c689532017-01-23 10:29:23 -0800316 std::lock_guard<std::mutex> lock(LoggingLock());
317 Logger() = std::move(logger);
Dan Albertb547c852015-03-27 11:20:14 -0700318}
319
Andreas Gampe2691e332016-09-08 11:03:58 -0700320void SetAborter(AbortFunction&& aborter) {
Yabin Cui0c689532017-01-23 10:29:23 -0800321 std::lock_guard<std::mutex> lock(LoggingLock());
322 Aborter() = std::move(aborter);
Andreas Gampe2691e332016-09-08 11:03:58 -0700323}
324
Spencer Lowbdab59a2015-08-11 16:00:13 -0700325static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800326 // We can't use basename(3) even on Unix because the Mac doesn't
327 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700328 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800329 if (last_slash != nullptr) {
330 return last_slash + 1;
331 }
332#if defined(_WIN32)
333 const char* last_backslash = strrchr(file, '\\');
334 if (last_backslash != nullptr) {
335 return last_backslash + 1;
336 }
337#endif
338 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700339}
340
Dan Albert58310b42015-03-13 23:06:01 -0700341// This indirection greatly reduces the stack impact of having lots of
342// checks/logging in a function.
343class LogMessageData {
344 public:
Dan Albert0c055862015-03-27 11:20:14 -0700345 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700346 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700347 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700348 line_number_(line),
349 id_(id),
350 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700351 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700352 }
353
354 const char* GetFile() const {
355 return file_;
356 }
357
358 unsigned int GetLineNumber() const {
359 return line_number_;
360 }
361
362 LogSeverity GetSeverity() const {
363 return severity_;
364 }
365
Dan Albert0c055862015-03-27 11:20:14 -0700366 LogId GetId() const {
367 return id_;
368 }
369
Dan Albert58310b42015-03-13 23:06:01 -0700370 int GetError() const {
371 return error_;
372 }
373
374 std::ostream& GetBuffer() {
375 return buffer_;
376 }
377
378 std::string ToString() const {
379 return buffer_.str();
380 }
381
382 private:
383 std::ostringstream buffer_;
384 const char* const file_;
385 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700386 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700387 const LogSeverity severity_;
388 const int error_;
389
390 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
391};
392
Dan Albert0c055862015-03-27 11:20:14 -0700393LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700394 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700395 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700396}
397
398LogMessage::~LogMessage() {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700399 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampe1f5fb432016-09-23 16:37:12 -0700400 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700401 return;
402 }
403
Dan Albert58310b42015-03-13 23:06:01 -0700404 // Finish constructing the message.
405 if (data_->GetError() != -1) {
406 data_->GetBuffer() << ": " << strerror(data_->GetError());
407 }
408 std::string msg(data_->ToString());
409
Spencer Low765ae6b2015-09-17 19:36:10 -0700410 {
411 // Do the actual logging with the lock held.
Yabin Cui0c689532017-01-23 10:29:23 -0800412 std::lock_guard<std::mutex> lock(LoggingLock());
Spencer Low765ae6b2015-09-17 19:36:10 -0700413 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700414 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700415 data_->GetSeverity(), msg.c_str());
416 } else {
417 msg += '\n';
418 size_t i = 0;
419 while (i < msg.size()) {
420 size_t nl = msg.find('\n', i);
421 msg[nl] = '\0';
422 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
423 data_->GetSeverity(), &msg[i]);
Andreas Gampeb4e32f32016-10-04 19:17:07 -0700424 // Undo the zero-termination so we can give the complete message to the aborter.
425 msg[nl] = '\n';
Spencer Low765ae6b2015-09-17 19:36:10 -0700426 i = nl + 1;
427 }
Dan Albert58310b42015-03-13 23:06:01 -0700428 }
429 }
430
431 // Abort if necessary.
432 if (data_->GetSeverity() == FATAL) {
Yabin Cui0c689532017-01-23 10:29:23 -0800433 Aborter()(msg.c_str());
Dan Albert58310b42015-03-13 23:06:01 -0700434 }
435}
436
437std::ostream& LogMessage::stream() {
438 return data_->GetBuffer();
439}
440
Dan Albert0c055862015-03-27 11:20:14 -0700441void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700442 LogSeverity severity, const char* message) {
Yabin Cui0c689532017-01-23 10:29:23 -0800443 const char* tag = ProgramInvocationName().c_str();
444 Logger()(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700445}
446
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700447LogSeverity GetMinimumLogSeverity() {
448 return gMinimumLogSeverity;
449}
450
451LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
452 LogSeverity old_severity = gMinimumLogSeverity;
453 gMinimumLogSeverity = new_severity;
454 return old_severity;
455}
456
457ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
458 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700459}
460
461ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700462 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700463}
464
465} // namespace base
466} // namespace android