blob: ece10ecddcaaa48472c5034a564ffb5a3bf985b7 [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>
Josh Gaob08de452016-09-13 14:57:12 -070040#include <mutex>
Dan Alberte3ea0582015-03-13 23:06:01 -070041#include <sstream>
42#include <string>
Dan Albert1f65c492015-03-27 11:20:14 -070043#include <utility>
Dan Alberte3ea0582015-03-13 23:06:01 -070044#include <vector>
45
Dan Alberte3ea0582015-03-13 23:06:01 -070046// Headers for LogMessage::LogLine.
47#ifdef __ANDROID__
Mark Salyzyn5cbb2512016-09-28 15:54:45 -070048#include <android/log.h>
Dan Alberte3ea0582015-03-13 23:06:01 -070049#include <android/set_abort_message.h>
Dan Alberte3ea0582015-03-13 23:06:01 -070050#else
51#include <sys/types.h>
52#include <unistd.h>
53#endif
54
Mark Salyzyn5cbb2512016-09-28 15:54:45 -070055#include <android-base/macros.h>
56#include <android-base/strings.h>
57
Elliott Hughes774d7f62015-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 Willemsenc4e54252016-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 Hughes774d7f62015-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 Albertdc15ffd2015-04-29 11:32:23 -070091namespace {
Dan Albertdc15ffd2015-04-29 11:32:23 -070092#if defined(__GLIBC__)
93const char* getprogname() {
94 return program_invocation_short_name;
95}
Josh Gaob08de452016-09-13 14:57:12 -070096#elif defined(_WIN32)
Dan Albertdc15ffd2015-04-29 11:32:23 -070097const char* getprogname() {
98 static bool first = true;
99 static char progname[MAX_PATH] = {};
100
101 if (first) {
Spencer Low55853a92015-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 Albertdc15ffd2015-04-29 11:32:23 -0700110 first = false;
111 }
112
113 return progname;
114}
Dan Albertdc15ffd2015-04-29 11:32:23 -0700115#endif
116} // namespace
117
Dan Alberte3ea0582015-03-13 23:06:01 -0700118namespace android {
119namespace base {
120
Josh Gaob08de452016-09-13 14:57:12 -0700121static auto& logging_lock = *new std::mutex();
Dan Alberte3ea0582015-03-13 23:06:01 -0700122
Dan Albert1f65c492015-03-27 11:20:14 -0700123#ifdef __ANDROID__
Josh Gao7f438622015-11-12 11:54:47 -0800124static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albert1f65c492015-03-27 11:20:14 -0700125#else
Josh Gao7f438622015-11-12 11:54:47 -0800126static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albert1f65c492015-03-27 11:20:14 -0700127#endif
128
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700129static auto& gAborter = *new AbortFunction(DefaultAborter);
130
Dan Albert1be4dec2015-04-03 11:28:46 -0700131static bool gInitialized = false;
Dan Alberte3ea0582015-03-13 23:06:01 -0700132static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7f438622015-11-12 11:54:47 -0800133static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Alberte3ea0582015-03-13 23:06:01 -0700134
Dan Albert1be4dec2015-04-03 11:28:46 -0700135static const char* ProgramInvocationName() {
136 if (gProgramInvocationName == nullptr) {
137 gProgramInvocationName.reset(new std::string(getprogname()));
138 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700139
Dan Albert1be4dec2015-04-03 11:28:46 -0700140 return gProgramInvocationName->c_str();
Dan Alberte3ea0582015-03-13 23:06:01 -0700141}
142
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700143#if defined(__linux__)
144void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
145 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700146 // clang-format off
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700147 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700148 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
149 // level)
150 [android::base::DEBUG] = 7, // KERN_DEBUG
151 [android::base::INFO] = 6, // KERN_INFO
152 [android::base::WARNING] = 4, // KERN_WARNING
153 [android::base::ERROR] = 3, // KERN_ERROR
154 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
155 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700156 };
Andreas Gamped2a4f212016-09-07 10:10:50 -0700157 // clang-format on
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700158 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
159 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
160
161 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
162 if (klog_fd == -1) return;
163
164 int level = kLogSeverityToKernelLogLevel[severity];
165
166 // The kernel's printk buffer is only 1024 bytes.
167 // TODO: should we automatically break up long lines into multiple lines?
168 // Or we could log but with something like "..." at the end?
169 char buf[1024];
170 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
171 if (size > sizeof(buf)) {
172 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
173 level, tag, size);
174 }
175
176 iovec iov[1];
177 iov[0].iov_base = buf;
178 iov[0].iov_len = size;
179 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
180}
181#endif
182
Dan Albert1f65c492015-03-27 11:20:14 -0700183void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
184 unsigned int line, const char* message) {
Elliott Hughes6522eb52016-06-21 14:25:44 -0700185 struct tm now;
186 time_t t = time(nullptr);
187
188#if defined(_WIN32)
189 localtime_s(&now, &t);
190#else
191 localtime_r(&t, &now);
192#endif
193
194 char timestamp[32];
195 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
196
Andreas Gamped2a4f212016-09-07 10:10:50 -0700197 static const char log_characters[] = "VDIWEFF";
Spencer Low55853a92015-08-11 16:00:13 -0700198 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
199 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albert1f65c492015-03-27 11:20:14 -0700200 char severity_char = log_characters[severity];
Elliott Hughes6522eb52016-06-21 14:25:44 -0700201 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
202 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albert1f65c492015-03-27 11:20:14 -0700203}
204
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700205void DefaultAborter(const char* abort_message) {
206#ifdef __ANDROID__
207 android_set_abort_message(abort_message);
208#else
209 UNUSED(abort_message);
210#endif
211 abort();
212}
213
Dan Albert1f65c492015-03-27 11:20:14 -0700214
215#ifdef __ANDROID__
216LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
217}
218
Dan Albert1f65c492015-03-27 11:20:14 -0700219void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
220 const char* file, unsigned int line,
221 const char* message) {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700222 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gamped2a4f212016-09-07 10:10:50 -0700223 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
224 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
225 ANDROID_LOG_FATAL,
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700226 };
227 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
228 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
229
Dan Albert1f65c492015-03-27 11:20:14 -0700230 int priority = kLogSeverityToAndroidLogPriority[severity];
231 if (id == DEFAULT) {
232 id = default_log_id_;
233 }
234
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700235 static constexpr log_id kLogIdToAndroidLogId[] = {
236 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
237 };
238 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
239 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albert1f65c492015-03-27 11:20:14 -0700240 log_id lg_id = kLogIdToAndroidLogId[id];
241
242 if (priority == ANDROID_LOG_FATAL) {
243 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
244 message);
245 } else {
246 __android_log_buf_print(lg_id, priority, tag, "%s", message);
247 }
248}
249#endif
250
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700251void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albert1f65c492015-03-27 11:20:14 -0700252 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700253 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albert1f65c492015-03-27 11:20:14 -0700254
Dan Albert1be4dec2015-04-03 11:28:46 -0700255 if (gInitialized) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700256 return;
257 }
258
Dan Albert1be4dec2015-04-03 11:28:46 -0700259 gInitialized = true;
260
Dan Alberte3ea0582015-03-13 23:06:01 -0700261 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Lowbec78622015-11-07 18:51:54 -0800262 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
263 // and there are a couple of argv[0] variants that are commonly used.
Dan Alberte3ea0582015-03-13 23:06:01 -0700264 if (argv != nullptr) {
Dan Albert1be4dec2015-04-03 11:28:46 -0700265 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Alberte3ea0582015-03-13 23:06:01 -0700266 }
Dan Albert1be4dec2015-04-03 11:28:46 -0700267
Dan Alberte3ea0582015-03-13 23:06:01 -0700268 const char* tags = getenv("ANDROID_LOG_TAGS");
269 if (tags == nullptr) {
270 return;
271 }
272
Dan Albert0d716d02015-03-19 13:24:26 -0700273 std::vector<std::string> specs = Split(tags, " ");
Dan Alberte3ea0582015-03-13 23:06:01 -0700274 for (size_t i = 0; i < specs.size(); ++i) {
275 // "tag-pattern:[vdiwefs]"
276 std::string spec(specs[i]);
277 if (spec.size() == 3 && StartsWith(spec, "*:")) {
278 switch (spec[2]) {
279 case 'v':
280 gMinimumLogSeverity = VERBOSE;
281 continue;
282 case 'd':
283 gMinimumLogSeverity = DEBUG;
284 continue;
285 case 'i':
286 gMinimumLogSeverity = INFO;
287 continue;
288 case 'w':
289 gMinimumLogSeverity = WARNING;
290 continue;
291 case 'e':
292 gMinimumLogSeverity = ERROR;
293 continue;
294 case 'f':
Andreas Gamped2a4f212016-09-07 10:10:50 -0700295 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Alberte3ea0582015-03-13 23:06:01 -0700296 continue;
297 // liblog will even suppress FATAL if you say 's' for silent, but that's
298 // crazy!
299 case 's':
Andreas Gamped2a4f212016-09-07 10:10:50 -0700300 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Alberte3ea0582015-03-13 23:06:01 -0700301 continue;
302 }
303 }
304 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
305 << ")";
306 }
307}
308
Dan Albert1f65c492015-03-27 11:20:14 -0700309void SetLogger(LogFunction&& logger) {
Josh Gaob08de452016-09-13 14:57:12 -0700310 std::lock_guard<std::mutex> lock(logging_lock);
Dan Albert1f65c492015-03-27 11:20:14 -0700311 gLogger = std::move(logger);
312}
313
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700314void SetAborter(AbortFunction&& aborter) {
Josh Gaob08de452016-09-13 14:57:12 -0700315 std::lock_guard<std::mutex> lock(logging_lock);
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700316 gAborter = std::move(aborter);
317}
318
Spencer Low55853a92015-08-11 16:00:13 -0700319static const char* GetFileBasename(const char* file) {
Spencer Lowbec78622015-11-07 18:51:54 -0800320 // We can't use basename(3) even on Unix because the Mac doesn't
321 // have a non-modifying basename.
Spencer Low55853a92015-08-11 16:00:13 -0700322 const char* last_slash = strrchr(file, '/');
Spencer Lowbec78622015-11-07 18:51:54 -0800323 if (last_slash != nullptr) {
324 return last_slash + 1;
325 }
326#if defined(_WIN32)
327 const char* last_backslash = strrchr(file, '\\');
328 if (last_backslash != nullptr) {
329 return last_backslash + 1;
330 }
331#endif
332 return file;
Spencer Low55853a92015-08-11 16:00:13 -0700333}
334
Dan Alberte3ea0582015-03-13 23:06:01 -0700335// This indirection greatly reduces the stack impact of having lots of
336// checks/logging in a function.
337class LogMessageData {
338 public:
Dan Albertab5c8822015-03-27 11:20:14 -0700339 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Lowe0671d62015-09-17 19:36:10 -0700340 LogSeverity severity, int error)
Spencer Low55853a92015-08-11 16:00:13 -0700341 : file_(GetFileBasename(file)),
Dan Albertab5c8822015-03-27 11:20:14 -0700342 line_number_(line),
343 id_(id),
344 severity_(severity),
Spencer Lowe0671d62015-09-17 19:36:10 -0700345 error_(error) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700346 }
347
348 const char* GetFile() const {
349 return file_;
350 }
351
352 unsigned int GetLineNumber() const {
353 return line_number_;
354 }
355
356 LogSeverity GetSeverity() const {
357 return severity_;
358 }
359
Dan Albertab5c8822015-03-27 11:20:14 -0700360 LogId GetId() const {
361 return id_;
362 }
363
Dan Alberte3ea0582015-03-13 23:06:01 -0700364 int GetError() const {
365 return error_;
366 }
367
368 std::ostream& GetBuffer() {
369 return buffer_;
370 }
371
372 std::string ToString() const {
373 return buffer_.str();
374 }
375
376 private:
377 std::ostringstream buffer_;
378 const char* const file_;
379 const unsigned int line_number_;
Dan Albertab5c8822015-03-27 11:20:14 -0700380 const LogId id_;
Dan Alberte3ea0582015-03-13 23:06:01 -0700381 const LogSeverity severity_;
382 const int error_;
383
384 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
385};
386
Dan Albertab5c8822015-03-27 11:20:14 -0700387LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Alberte3ea0582015-03-13 23:06:01 -0700388 LogSeverity severity, int error)
Spencer Lowe0671d62015-09-17 19:36:10 -0700389 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700390}
391
392LogMessage::~LogMessage() {
Andreas Gampec65ea942016-09-23 13:31:52 -0700393 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampecb35a4a2016-09-23 16:37:12 -0700394 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampec65ea942016-09-23 13:31:52 -0700395 return;
396 }
397
Dan Alberte3ea0582015-03-13 23:06:01 -0700398 // Finish constructing the message.
399 if (data_->GetError() != -1) {
400 data_->GetBuffer() << ": " << strerror(data_->GetError());
401 }
402 std::string msg(data_->ToString());
403
Spencer Lowe0671d62015-09-17 19:36:10 -0700404 {
405 // Do the actual logging with the lock held.
Josh Gaob08de452016-09-13 14:57:12 -0700406 std::lock_guard<std::mutex> lock(logging_lock);
Spencer Lowe0671d62015-09-17 19:36:10 -0700407 if (msg.find('\n') == std::string::npos) {
Dan Albertab5c8822015-03-27 11:20:14 -0700408 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Lowe0671d62015-09-17 19:36:10 -0700409 data_->GetSeverity(), msg.c_str());
410 } else {
411 msg += '\n';
412 size_t i = 0;
413 while (i < msg.size()) {
414 size_t nl = msg.find('\n', i);
415 msg[nl] = '\0';
416 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
417 data_->GetSeverity(), &msg[i]);
418 i = nl + 1;
419 }
Dan Alberte3ea0582015-03-13 23:06:01 -0700420 }
421 }
422
423 // Abort if necessary.
424 if (data_->GetSeverity() == FATAL) {
Andreas Gampe9008e8d2016-09-08 11:03:58 -0700425 gAborter(msg.c_str());
Dan Alberte3ea0582015-03-13 23:06:01 -0700426 }
427}
428
429std::ostream& LogMessage::stream() {
430 return data_->GetBuffer();
431}
432
Dan Albertab5c8822015-03-27 11:20:14 -0700433void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albert1f65c492015-03-27 11:20:14 -0700434 LogSeverity severity, const char* message) {
Dan Albert1be4dec2015-04-03 11:28:46 -0700435 const char* tag = ProgramInvocationName();
Dan Albert1f65c492015-03-27 11:20:14 -0700436 gLogger(id, severity, tag, file, line, message);
Dan Alberte3ea0582015-03-13 23:06:01 -0700437}
438
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700439LogSeverity GetMinimumLogSeverity() {
440 return gMinimumLogSeverity;
441}
442
443LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
444 LogSeverity old_severity = gMinimumLogSeverity;
445 gMinimumLogSeverity = new_severity;
446 return old_severity;
447}
448
449ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
450 old_ = SetMinimumLogSeverity(new_severity);
Dan Alberte3ea0582015-03-13 23:06:01 -0700451}
452
453ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700454 SetMinimumLogSeverity(old_);
Dan Alberte3ea0582015-03-13 23:06:01 -0700455}
456
457} // namespace base
458} // namespace android