blob: 75078e50e92b70166d545094f8af5986003e5876 [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__)
Christopher N. Hesse684b4422016-09-17 18:29:03 +020083 uint64_t tid;
84 pthread_threadid_np(NULL, &tid);
85 return tid;
Elliott Hughesc1fd4922015-11-11 18:02:29 +000086#elif defined(__linux__)
87 return syscall(__NR_gettid);
88#elif defined(_WIN32)
89 return GetCurrentThreadId();
90#endif
91}
92
Dan Albert5c190402015-04-29 11:32:23 -070093namespace {
Dan Albert5c190402015-04-29 11:32:23 -070094#if defined(__GLIBC__)
95const char* getprogname() {
96 return program_invocation_short_name;
97}
Josh Gao63bdcb52016-09-13 14:57:12 -070098#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070099const char* getprogname() {
100 static bool first = true;
101 static char progname[MAX_PATH] = {};
102
103 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700104 CHAR longname[MAX_PATH];
105 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
106 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
107 // String truncation or some other error.
108 strcpy(progname, "<unknown>");
109 } else {
110 strcpy(progname, basename(longname));
111 }
Dan Albert5c190402015-04-29 11:32:23 -0700112 first = false;
113 }
114
115 return progname;
116}
Dan Albert5c190402015-04-29 11:32:23 -0700117#endif
118} // namespace
119
Dan Albert58310b42015-03-13 23:06:01 -0700120namespace android {
121namespace base {
122
Yabin Cui0c689532017-01-23 10:29:23 -0800123static std::mutex& LoggingLock() {
124 static auto& logging_lock = *new std::mutex();
125 return logging_lock;
126}
Dan Albert58310b42015-03-13 23:06:01 -0700127
Yabin Cui0c689532017-01-23 10:29:23 -0800128static LogFunction& Logger() {
Dan Albertb547c852015-03-27 11:20:14 -0700129#ifdef __ANDROID__
Yabin Cui0c689532017-01-23 10:29:23 -0800130 static auto& logger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700131#else
Yabin Cui0c689532017-01-23 10:29:23 -0800132 static auto& logger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700133#endif
Yabin Cui0c689532017-01-23 10:29:23 -0800134 return logger;
135}
Dan Albertb547c852015-03-27 11:20:14 -0700136
Yabin Cui0c689532017-01-23 10:29:23 -0800137static AbortFunction& Aborter() {
138 static auto& aborter = *new AbortFunction(DefaultAborter);
139 return aborter;
140}
141
142static std::string& ProgramInvocationName() {
143 static auto& programInvocationName = *new std::string(getprogname());
144 return programInvocationName;
145}
Andreas Gampe2691e332016-09-08 11:03:58 -0700146
Dan Albert7a87d052015-04-03 11:28:46 -0700147static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700148static LogSeverity gMinimumLogSeverity = INFO;
Dan Albert58310b42015-03-13 23:06:01 -0700149
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700150#if defined(__linux__)
151void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
152 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700153 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700154 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700155 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
156 // level)
157 [android::base::DEBUG] = 7, // KERN_DEBUG
158 [android::base::INFO] = 6, // KERN_INFO
159 [android::base::WARNING] = 4, // KERN_WARNING
160 [android::base::ERROR] = 3, // KERN_ERROR
161 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
162 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700163 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700164 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700165 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
166 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
167
168 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
169 if (klog_fd == -1) return;
170
171 int level = kLogSeverityToKernelLogLevel[severity];
172
173 // The kernel's printk buffer is only 1024 bytes.
174 // TODO: should we automatically break up long lines into multiple lines?
175 // Or we could log but with something like "..." at the end?
176 char buf[1024];
177 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
178 if (size > sizeof(buf)) {
179 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
180 level, tag, size);
181 }
182
183 iovec iov[1];
184 iov[0].iov_base = buf;
185 iov[0].iov_len = size;
186 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
187}
188#endif
189
Dan Albertb547c852015-03-27 11:20:14 -0700190void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
191 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700192 struct tm now;
193 time_t t = time(nullptr);
194
195#if defined(_WIN32)
196 localtime_s(&now, &t);
197#else
198 localtime_r(&t, &now);
199#endif
200
201 char timestamp[32];
202 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
203
Andreas Gampe550829d2016-09-07 10:10:50 -0700204 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700205 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
206 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700207 char severity_char = log_characters[severity];
Yabin Cui0c689532017-01-23 10:29:23 -0800208 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700209 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700210}
211
Andreas Gampe2691e332016-09-08 11:03:58 -0700212void DefaultAborter(const char* abort_message) {
213#ifdef __ANDROID__
214 android_set_abort_message(abort_message);
215#else
216 UNUSED(abort_message);
217#endif
218 abort();
219}
220
Dan Albertb547c852015-03-27 11:20:14 -0700221
222#ifdef __ANDROID__
223LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
224}
225
Dan Albertb547c852015-03-27 11:20:14 -0700226void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
227 const char* file, unsigned int line,
228 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700229 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700230 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
231 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
232 ANDROID_LOG_FATAL,
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700233 };
234 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
235 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
236
Dan Albertb547c852015-03-27 11:20:14 -0700237 int priority = kLogSeverityToAndroidLogPriority[severity];
238 if (id == DEFAULT) {
239 id = default_log_id_;
240 }
241
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700242 static constexpr log_id kLogIdToAndroidLogId[] = {
243 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
244 };
245 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
246 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700247 log_id lg_id = kLogIdToAndroidLogId[id];
248
249 if (priority == ANDROID_LOG_FATAL) {
250 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
251 message);
252 } else {
253 __android_log_buf_print(lg_id, priority, tag, "%s", message);
254 }
255}
256#endif
257
Andreas Gampe2691e332016-09-08 11:03:58 -0700258void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700259 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700260 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700261
Dan Albert7a87d052015-04-03 11:28:46 -0700262 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700263 return;
264 }
265
Dan Albert7a87d052015-04-03 11:28:46 -0700266 gInitialized = true;
267
Dan Albert58310b42015-03-13 23:06:01 -0700268 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800269 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
270 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700271 if (argv != nullptr) {
Yabin Cui0c689532017-01-23 10:29:23 -0800272 std::lock_guard<std::mutex> lock(LoggingLock());
273 ProgramInvocationName() = basename(argv[0]);
Dan Albert58310b42015-03-13 23:06:01 -0700274 }
Dan Albert7a87d052015-04-03 11:28:46 -0700275
Dan Albert58310b42015-03-13 23:06:01 -0700276 const char* tags = getenv("ANDROID_LOG_TAGS");
277 if (tags == nullptr) {
278 return;
279 }
280
Dan Albert47328c92015-03-19 13:24:26 -0700281 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700282 for (size_t i = 0; i < specs.size(); ++i) {
283 // "tag-pattern:[vdiwefs]"
284 std::string spec(specs[i]);
285 if (spec.size() == 3 && StartsWith(spec, "*:")) {
286 switch (spec[2]) {
287 case 'v':
288 gMinimumLogSeverity = VERBOSE;
289 continue;
290 case 'd':
291 gMinimumLogSeverity = DEBUG;
292 continue;
293 case 'i':
294 gMinimumLogSeverity = INFO;
295 continue;
296 case 'w':
297 gMinimumLogSeverity = WARNING;
298 continue;
299 case 'e':
300 gMinimumLogSeverity = ERROR;
301 continue;
302 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700303 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700304 continue;
305 // liblog will even suppress FATAL if you say 's' for silent, but that's
306 // crazy!
307 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700308 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700309 continue;
310 }
311 }
312 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
313 << ")";
314 }
315}
316
Dan Albertb547c852015-03-27 11:20:14 -0700317void SetLogger(LogFunction&& logger) {
Yabin Cui0c689532017-01-23 10:29:23 -0800318 std::lock_guard<std::mutex> lock(LoggingLock());
319 Logger() = std::move(logger);
Dan Albertb547c852015-03-27 11:20:14 -0700320}
321
Andreas Gampe2691e332016-09-08 11:03:58 -0700322void SetAborter(AbortFunction&& aborter) {
Yabin Cui0c689532017-01-23 10:29:23 -0800323 std::lock_guard<std::mutex> lock(LoggingLock());
324 Aborter() = std::move(aborter);
Andreas Gampe2691e332016-09-08 11:03:58 -0700325}
326
Spencer Lowbdab59a2015-08-11 16:00:13 -0700327static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800328 // We can't use basename(3) even on Unix because the Mac doesn't
329 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700330 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800331 if (last_slash != nullptr) {
332 return last_slash + 1;
333 }
334#if defined(_WIN32)
335 const char* last_backslash = strrchr(file, '\\');
336 if (last_backslash != nullptr) {
337 return last_backslash + 1;
338 }
339#endif
340 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700341}
342
Dan Albert58310b42015-03-13 23:06:01 -0700343// This indirection greatly reduces the stack impact of having lots of
344// checks/logging in a function.
345class LogMessageData {
346 public:
Dan Albert0c055862015-03-27 11:20:14 -0700347 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700348 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700349 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700350 line_number_(line),
351 id_(id),
352 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700353 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700354 }
355
356 const char* GetFile() const {
357 return file_;
358 }
359
360 unsigned int GetLineNumber() const {
361 return line_number_;
362 }
363
364 LogSeverity GetSeverity() const {
365 return severity_;
366 }
367
Dan Albert0c055862015-03-27 11:20:14 -0700368 LogId GetId() const {
369 return id_;
370 }
371
Dan Albert58310b42015-03-13 23:06:01 -0700372 int GetError() const {
373 return error_;
374 }
375
376 std::ostream& GetBuffer() {
377 return buffer_;
378 }
379
380 std::string ToString() const {
381 return buffer_.str();
382 }
383
384 private:
385 std::ostringstream buffer_;
386 const char* const file_;
387 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700388 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700389 const LogSeverity severity_;
390 const int error_;
391
392 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
393};
394
Dan Albert0c055862015-03-27 11:20:14 -0700395LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700396 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700397 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700398}
399
400LogMessage::~LogMessage() {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700401 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampe1f5fb432016-09-23 16:37:12 -0700402 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700403 return;
404 }
405
Dan Albert58310b42015-03-13 23:06:01 -0700406 // Finish constructing the message.
407 if (data_->GetError() != -1) {
408 data_->GetBuffer() << ": " << strerror(data_->GetError());
409 }
410 std::string msg(data_->ToString());
411
Spencer Low765ae6b2015-09-17 19:36:10 -0700412 {
413 // Do the actual logging with the lock held.
Yabin Cui0c689532017-01-23 10:29:23 -0800414 std::lock_guard<std::mutex> lock(LoggingLock());
Spencer Low765ae6b2015-09-17 19:36:10 -0700415 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700416 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700417 data_->GetSeverity(), msg.c_str());
418 } else {
419 msg += '\n';
420 size_t i = 0;
421 while (i < msg.size()) {
422 size_t nl = msg.find('\n', i);
423 msg[nl] = '\0';
424 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
425 data_->GetSeverity(), &msg[i]);
Andreas Gampeb4e32f32016-10-04 19:17:07 -0700426 // Undo the zero-termination so we can give the complete message to the aborter.
427 msg[nl] = '\n';
Spencer Low765ae6b2015-09-17 19:36:10 -0700428 i = nl + 1;
429 }
Dan Albert58310b42015-03-13 23:06:01 -0700430 }
431 }
432
433 // Abort if necessary.
434 if (data_->GetSeverity() == FATAL) {
Yabin Cui0c689532017-01-23 10:29:23 -0800435 Aborter()(msg.c_str());
Dan Albert58310b42015-03-13 23:06:01 -0700436 }
437}
438
439std::ostream& LogMessage::stream() {
440 return data_->GetBuffer();
441}
442
Dan Albert0c055862015-03-27 11:20:14 -0700443void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700444 LogSeverity severity, const char* message) {
Yabin Cui0c689532017-01-23 10:29:23 -0800445 const char* tag = ProgramInvocationName().c_str();
446 Logger()(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700447}
448
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700449LogSeverity GetMinimumLogSeverity() {
450 return gMinimumLogSeverity;
451}
452
453LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
454 LogSeverity old_severity = gMinimumLogSeverity;
455 gMinimumLogSeverity = new_severity;
456 return old_severity;
457}
458
459ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
460 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700461}
462
463ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700464 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700465}
466
467} // namespace base
468} // namespace android