1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/logging.h"
6
7 #include <limits.h>
8 #include <stdint.h>
9
10 #include "base/debug/activity_tracker.h"
11 #include "base/macros.h"
12 #include "build/build_config.h"
13
14 #if defined(OS_WIN)
15 #include <io.h>
16 typedef HANDLE FileHandle;
17 typedef HANDLE MutexHandle;
18 // Windows warns on using write(). It prefers _write().
19 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
20 // Windows doesn't define STDERR_FILENO. Define it here.
21 #define STDERR_FILENO 2
22 #elif defined(OS_MACOSX)
23 #include <asl.h>
24 #include <CoreFoundation/CoreFoundation.h>
25 #include <mach/mach.h>
26 #include <mach/mach_time.h>
27 #include <mach-o/dyld.h>
28 #elif defined(OS_POSIX)
29 #if defined(OS_NACL)
30 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
31 #endif
32 #include <time.h>
33 #endif
34
35 #if defined(OS_POSIX)
36 #include <errno.h>
37 #include <paths.h>
38 #include <pthread.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #define MAX_PATH PATH_MAX
45 typedef FILE* FileHandle;
46 typedef pthread_mutex_t* MutexHandle;
47 #endif
48
49 #include <algorithm>
50 #include <cstring>
51 #include <ctime>
52 #include <iomanip>
53 #include <ostream>
54 #include <string>
55
56 #include "base/base_switches.h"
57 #include "base/command_line.h"
58 #include "base/debug/alias.h"
59 #include "base/debug/debugger.h"
60 #include "base/debug/stack_trace.h"
61 #include "base/posix/eintr_wrapper.h"
62 #include "base/strings/string_piece.h"
63 #include "base/strings/string_util.h"
64 #include "base/strings/stringprintf.h"
65 #include "base/strings/sys_string_conversions.h"
66 #include "base/strings/utf_string_conversions.h"
67 #include "base/synchronization/lock_impl.h"
68 #include "base/threading/platform_thread.h"
69 #include "base/vlog.h"
70 #if defined(OS_POSIX)
71 #include "base/posix/safe_strerror.h"
72 #endif
73
74 #if !defined(OS_ANDROID)
75 #include "base/files/file_path.h"
76 #endif
77
78 #if defined(OS_ANDROID) || defined(__ANDROID__)
79 #include <android/log.h>
80 #endif
81
82 namespace logging {
83
84 namespace {
85
86 VlogInfo* g_vlog_info = nullptr;
87 VlogInfo* g_vlog_info_prev = nullptr;
88
89 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
90 "INFO", "WARNING", "ERROR", "FATAL" };
91
log_severity_name(int severity)92 const char* log_severity_name(int severity) {
93 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
94 return log_severity_names[severity];
95 return "UNKNOWN";
96 }
97
98 int g_min_log_level = 0;
99
100 LoggingDestination g_logging_destination = LOG_DEFAULT;
101
102 // For LOG_ERROR and above, always print to stderr.
103 const int kAlwaysPrintErrorLevel = LOG_ERROR;
104
105 // Which log file to use? This is initialized by InitLogging or
106 // will be lazily initialized to the default value when it is
107 // first needed.
108 #if defined(OS_WIN)
109 typedef std::wstring PathString;
110 #else
111 typedef std::string PathString;
112 #endif
113 PathString* g_log_file_name = nullptr;
114
115 // This file is lazily opened and the handle may be nullptr
116 FileHandle g_log_file = nullptr;
117
118 // What should be prepended to each message?
119 bool g_log_process_id = false;
120 bool g_log_thread_id = false;
121 bool g_log_timestamp = true;
122 bool g_log_tickcount = false;
123
124 // Should we pop up fatal debug messages in a dialog?
125 bool show_error_dialogs = false;
126
127 // An assert handler override specified by the client to be called instead of
128 // the debug message dialog and process termination.
129 LogAssertHandlerFunction log_assert_handler = nullptr;
130 // A log message handler that gets notified of every log message we process.
131 LogMessageHandlerFunction log_message_handler = nullptr;
132
133 // Helper functions to wrap platform differences.
134
CurrentProcessId()135 int32_t CurrentProcessId() {
136 #if defined(OS_WIN)
137 return GetCurrentProcessId();
138 #elif defined(OS_POSIX)
139 return getpid();
140 #endif
141 }
142
TickCount()143 uint64_t TickCount() {
144 #if defined(OS_WIN)
145 return GetTickCount();
146 #elif defined(OS_MACOSX)
147 return mach_absolute_time();
148 #elif defined(OS_NACL)
149 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
150 // So we have to use clock() for now.
151 return clock();
152 #elif defined(OS_POSIX)
153 struct timespec ts;
154 clock_gettime(CLOCK_MONOTONIC, &ts);
155
156 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
157 static_cast<int64_t>(ts.tv_nsec) / 1000;
158
159 return absolute_micro;
160 #endif
161 }
162
DeleteFilePath(const PathString & log_name)163 void DeleteFilePath(const PathString& log_name) {
164 #if defined(OS_WIN)
165 DeleteFile(log_name.c_str());
166 #elif defined(OS_NACL)
167 // Do nothing; unlink() isn't supported on NaCl.
168 #else
169 unlink(log_name.c_str());
170 #endif
171 }
172
GetDefaultLogFile()173 PathString GetDefaultLogFile() {
174 #if defined(OS_WIN)
175 // On Windows we use the same path as the exe.
176 wchar_t module_name[MAX_PATH];
177 GetModuleFileName(nullptr, module_name, MAX_PATH);
178
179 PathString log_name = module_name;
180 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
181 if (last_backslash != PathString::npos)
182 log_name.erase(last_backslash + 1);
183 log_name += L"debug.log";
184 return log_name;
185 #elif defined(OS_POSIX)
186 // On other platforms we just use the current directory.
187 return PathString("debug.log");
188 #endif
189 }
190
191 // We don't need locks on Windows for atomically appending to files. The OS
192 // provides this functionality.
193 #if !defined(OS_WIN)
194 // This class acts as a wrapper for locking the logging files.
195 // LoggingLock::Init() should be called from the main thread before any logging
196 // is done. Then whenever logging, be sure to have a local LoggingLock
197 // instance on the stack. This will ensure that the lock is unlocked upon
198 // exiting the frame.
199 // LoggingLocks can not be nested.
200 class LoggingLock {
201 public:
LoggingLock()202 LoggingLock() {
203 LockLogging();
204 }
205
~LoggingLock()206 ~LoggingLock() {
207 UnlockLogging();
208 }
209
Init(LogLockingState lock_log,const PathChar * new_log_file)210 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
211 if (initialized)
212 return;
213 lock_log_file = lock_log;
214
215 if (lock_log_file != LOCK_LOG_FILE)
216 log_lock = new base::internal::LockImpl();
217
218 initialized = true;
219 }
220
221 private:
LockLogging()222 static void LockLogging() {
223 if (lock_log_file == LOCK_LOG_FILE) {
224 #if defined(OS_POSIX)
225 pthread_mutex_lock(&log_mutex);
226 #endif
227 } else {
228 // use the lock
229 log_lock->Lock();
230 }
231 }
232
UnlockLogging()233 static void UnlockLogging() {
234 if (lock_log_file == LOCK_LOG_FILE) {
235 #if defined(OS_POSIX)
236 pthread_mutex_unlock(&log_mutex);
237 #endif
238 } else {
239 log_lock->Unlock();
240 }
241 }
242
243 // The lock is used if log file locking is false. It helps us avoid problems
244 // with multiple threads writing to the log file at the same time. Use
245 // LockImpl directly instead of using Lock, because Lock makes logging calls.
246 static base::internal::LockImpl* log_lock;
247
248 // When we don't use a lock, we are using a global mutex. We need to do this
249 // because LockFileEx is not thread safe.
250 #if defined(OS_POSIX)
251 static pthread_mutex_t log_mutex;
252 #endif
253
254 static bool initialized;
255 static LogLockingState lock_log_file;
256 };
257
258 // static
259 bool LoggingLock::initialized = false;
260 // static
261 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
262 // static
263 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
264
265 #if defined(OS_POSIX)
266 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
267 #endif
268
269 #endif // OS_WIN
270
271 // Called by logging functions to ensure that |g_log_file| is initialized
272 // and can be used for writing. Returns false if the file could not be
273 // initialized. |g_log_file| will be nullptr in this case.
InitializeLogFileHandle()274 bool InitializeLogFileHandle() {
275 if (g_log_file)
276 return true;
277
278 if (!g_log_file_name) {
279 // Nobody has called InitLogging to specify a debug log file, so here we
280 // initialize the log file name to a default.
281 g_log_file_name = new PathString(GetDefaultLogFile());
282 }
283
284 if ((g_logging_destination & LOG_TO_FILE) != 0) {
285 #if defined(OS_WIN)
286 // The FILE_APPEND_DATA access mask ensures that the file is atomically
287 // appended to across accesses from multiple threads.
288 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
289 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
290 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
291 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
292 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
293 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
294 // We are intentionally not using FilePath or FileUtil here to reduce the
295 // dependencies of the logging implementation. For e.g. FilePath and
296 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
297 // some consumers of base logging like chrome_elf, etc.
298 // Please don't change the code below to use FilePath.
299 // try the current directory
300 wchar_t system_buffer[MAX_PATH];
301 system_buffer[0] = 0;
302 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
303 system_buffer);
304 if (len == 0 || len > arraysize(system_buffer))
305 return false;
306
307 *g_log_file_name = system_buffer;
308 // Append a trailing backslash if needed.
309 if (g_log_file_name->back() != L'\\')
310 *g_log_file_name += L"\\";
311 *g_log_file_name += L"debug.log";
312
313 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
314 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
315 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
316 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
317 g_log_file = nullptr;
318 return false;
319 }
320 }
321 #elif defined(OS_POSIX)
322 g_log_file = fopen(g_log_file_name->c_str(), "a");
323 if (g_log_file == nullptr)
324 return false;
325 #endif
326 }
327
328 return true;
329 }
330
CloseFile(FileHandle log)331 void CloseFile(FileHandle log) {
332 #if defined(OS_WIN)
333 CloseHandle(log);
334 #else
335 fclose(log);
336 #endif
337 }
338
CloseLogFileUnlocked()339 void CloseLogFileUnlocked() {
340 if (!g_log_file)
341 return;
342
343 CloseFile(g_log_file);
344 g_log_file = nullptr;
345 }
346
347 } // namespace
348
349 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
350 // an object of the correct type on the LHS of the unused part of the ternary
351 // operator.
352 std::ostream* g_swallow_stream;
353
LoggingSettings()354 LoggingSettings::LoggingSettings()
355 : logging_dest(LOG_DEFAULT),
356 log_file(nullptr),
357 lock_log(LOCK_LOG_FILE),
358 delete_old(APPEND_TO_OLD_LOG_FILE) {}
359
BaseInitLoggingImpl(const LoggingSettings & settings)360 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
361 #if defined(OS_NACL)
362 // Can log only to the system debug log.
363 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
364 #endif
365 if (base::CommandLine::InitializedForCurrentProcess()) {
366 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
367 // Don't bother initializing |g_vlog_info| unless we use one of the
368 // vlog switches.
369 if (command_line->HasSwitch(switches::kV) ||
370 command_line->HasSwitch(switches::kVModule)) {
371 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
372 // by another thread. Don't delete the old VLogInfo, just create a second
373 // one. We keep track of both to avoid memory leak warnings.
374 CHECK(!g_vlog_info_prev);
375 g_vlog_info_prev = g_vlog_info;
376
377 g_vlog_info =
378 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
379 command_line->GetSwitchValueASCII(switches::kVModule),
380 &g_min_log_level);
381 }
382 }
383
384 g_logging_destination = settings.logging_dest;
385
386 // ignore file options unless logging to file is set.
387 if ((g_logging_destination & LOG_TO_FILE) == 0)
388 return true;
389
390 #if !defined(OS_WIN)
391 LoggingLock::Init(settings.lock_log, settings.log_file);
392 LoggingLock logging_lock;
393 #endif
394
395 // Calling InitLogging twice or after some log call has already opened the
396 // default log file will re-initialize to the new options.
397 CloseLogFileUnlocked();
398
399 if (!g_log_file_name)
400 g_log_file_name = new PathString();
401 *g_log_file_name = settings.log_file;
402 if (settings.delete_old == DELETE_OLD_LOG_FILE)
403 DeleteFilePath(*g_log_file_name);
404
405 return InitializeLogFileHandle();
406 }
407
SetMinLogLevel(int level)408 void SetMinLogLevel(int level) {
409 g_min_log_level = std::min(LOG_FATAL, level);
410 }
411
GetMinLogLevel()412 int GetMinLogLevel() {
413 return g_min_log_level;
414 }
415
ShouldCreateLogMessage(int severity)416 bool ShouldCreateLogMessage(int severity) {
417 if (severity < g_min_log_level)
418 return false;
419
420 // Return true here unless we know ~LogMessage won't do anything. Note that
421 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
422 // when g_logging_destination is LOG_NONE.
423 return g_logging_destination != LOG_NONE || log_message_handler ||
424 severity >= kAlwaysPrintErrorLevel;
425 }
426
GetVlogVerbosity()427 int GetVlogVerbosity() {
428 return std::max(-1, LOG_INFO - GetMinLogLevel());
429 }
430
GetVlogLevelHelper(const char * file,size_t N)431 int GetVlogLevelHelper(const char* file, size_t N) {
432 DCHECK_GT(N, 0U);
433 // Note: |g_vlog_info| may change on a different thread during startup
434 // (but will always be valid or nullptr).
435 VlogInfo* vlog_info = g_vlog_info;
436 return vlog_info ?
437 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
438 GetVlogVerbosity();
439 }
440
SetLogItems(bool enable_process_id,bool enable_thread_id,bool enable_timestamp,bool enable_tickcount)441 void SetLogItems(bool enable_process_id, bool enable_thread_id,
442 bool enable_timestamp, bool enable_tickcount) {
443 g_log_process_id = enable_process_id;
444 g_log_thread_id = enable_thread_id;
445 g_log_timestamp = enable_timestamp;
446 g_log_tickcount = enable_tickcount;
447 }
448
SetShowErrorDialogs(bool enable_dialogs)449 void SetShowErrorDialogs(bool enable_dialogs) {
450 show_error_dialogs = enable_dialogs;
451 }
452
SetLogAssertHandler(LogAssertHandlerFunction handler)453 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
454 log_assert_handler = handler;
455 }
456
SetLogMessageHandler(LogMessageHandlerFunction handler)457 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
458 log_message_handler = handler;
459 }
460
GetLogMessageHandler()461 LogMessageHandlerFunction GetLogMessageHandler() {
462 return log_message_handler;
463 }
464
465 // Explicit instantiations for commonly used comparisons.
466 template std::string* MakeCheckOpString<int, int>(
467 const int&, const int&, const char* names);
468 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
469 const unsigned long&, const unsigned long&, const char* names);
470 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
471 const unsigned long&, const unsigned int&, const char* names);
472 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
473 const unsigned int&, const unsigned long&, const char* names);
474 template std::string* MakeCheckOpString<std::string, std::string>(
475 const std::string&, const std::string&, const char* name);
476
MakeCheckOpValueString(std::ostream * os,std::nullptr_t p)477 void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
478 (*os) << "nullptr";
479 }
480
481 #if !defined(NDEBUG)
482 // Displays a message box to the user with the error message in it.
483 // Used for fatal messages, where we close the app simultaneously.
484 // This is for developers only; we don't use this in circumstances
485 // (like release builds) where users could see it, since users don't
486 // understand these messages anyway.
DisplayDebugMessageInDialog(const std::string & str)487 void DisplayDebugMessageInDialog(const std::string& str) {
488 if (str.empty())
489 return;
490
491 if (!show_error_dialogs)
492 return;
493
494 #if defined(OS_WIN)
495 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
496 MB_OK | MB_ICONHAND | MB_TOPMOST);
497 #else
498 // We intentionally don't implement a dialog on other platforms.
499 // You can just look at stderr.
500 #endif // defined(OS_WIN)
501 }
502 #endif // !defined(NDEBUG)
503
504 #if defined(OS_WIN)
SaveLastError()505 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
506 }
507
~SaveLastError()508 LogMessage::SaveLastError::~SaveLastError() {
509 ::SetLastError(last_error_);
510 }
511 #endif // defined(OS_WIN)
512
LogMessage(const char * file,int line,LogSeverity severity)513 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
514 : severity_(severity), file_(file), line_(line) {
515 Init(file, line);
516 }
517
LogMessage(const char * file,int line,const char * condition)518 LogMessage::LogMessage(const char* file, int line, const char* condition)
519 : severity_(LOG_FATAL), file_(file), line_(line) {
520 Init(file, line);
521 stream_ << "Check failed: " << condition << ". ";
522 }
523
LogMessage(const char * file,int line,std::string * result)524 LogMessage::LogMessage(const char* file, int line, std::string* result)
525 : severity_(LOG_FATAL), file_(file), line_(line) {
526 Init(file, line);
527 stream_ << "Check failed: " << *result;
528 delete result;
529 }
530
LogMessage(const char * file,int line,LogSeverity severity,std::string * result)531 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
532 std::string* result)
533 : severity_(severity), file_(file), line_(line) {
534 Init(file, line);
535 stream_ << "Check failed: " << *result;
536 delete result;
537 }
538
~LogMessage()539 LogMessage::~LogMessage() {
540 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__)
541 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
542 // Include a stack trace on a fatal, unless a debugger is attached.
543 base::debug::StackTrace trace;
544 stream_ << std::endl; // Newline to separate from log message.
545 trace.OutputToStream(&stream_);
546 }
547 #endif
548 stream_ << std::endl;
549 std::string str_newline(stream_.str());
550
551 // Give any log message handler first dibs on the message.
552 if (log_message_handler &&
553 log_message_handler(severity_, file_, line_,
554 message_start_, str_newline)) {
555 // The handler took care of it, no further processing.
556 return;
557 }
558
559 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
560 #if defined(OS_WIN)
561 OutputDebugStringA(str_newline.c_str());
562 #elif defined(OS_MACOSX)
563 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
564 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log). If
565 // there's something weird about stderr, assume that log messages are going
566 // nowhere and log via ASL too. Messages logged via ASL show up in
567 // Console.app.
568 //
569 // Programs started by launchd, as UI applications normally are, have had
570 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
571 // a pipe to launchd, which logged what it received (see log_redirect_fd in
572 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
573 //
574 // Another alternative would be to determine whether stderr is a pipe to
575 // launchd and avoid logging via ASL only in that case. See 10.7.5
576 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
577 // both stderr and ASL even in tests, where it's undesirable to log to the
578 // system log at all.
579 //
580 // Note that the ASL client by default discards messages whose levels are
581 // below ASL_LEVEL_NOTICE. It's possible to change that with
582 // asl_set_filter(), but this is pointless because syslogd normally applies
583 // the same filter.
584 const bool log_via_asl = []() {
585 struct stat stderr_stat;
586 if (fstat(fileno(stderr), &stderr_stat) == -1) {
587 return true;
588 }
589 if (!S_ISCHR(stderr_stat.st_mode)) {
590 return false;
591 }
592
593 struct stat dev_null_stat;
594 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
595 return true;
596 }
597
598 return !S_ISCHR(dev_null_stat.st_mode) ||
599 stderr_stat.st_rdev == dev_null_stat.st_rdev;
600 }();
601
602 if (log_via_asl) {
603 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
604 // CF-1153.18/CFUtilities.c __CFLogCString().
605 //
606 // The ASL facility is set to the main bundle ID if available. Otherwise,
607 // "com.apple.console" is used.
608 CFBundleRef main_bundle = CFBundleGetMainBundle();
609 CFStringRef main_bundle_id_cf =
610 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
611 std::string asl_facility =
612 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
613 : std::string("com.apple.console");
614
615 class ASLClient {
616 public:
617 explicit ASLClient(const std::string& asl_facility)
618 : client_(asl_open(nullptr,
619 asl_facility.c_str(),
620 ASL_OPT_NO_DELAY)) {}
621 ~ASLClient() { asl_close(client_); }
622
623 aslclient get() const { return client_; }
624
625 private:
626 aslclient client_;
627 DISALLOW_COPY_AND_ASSIGN(ASLClient);
628 } asl_client(asl_facility);
629
630 class ASLMessage {
631 public:
632 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
633 ~ASLMessage() { asl_free(message_); }
634
635 aslmsg get() const { return message_; }
636
637 private:
638 aslmsg message_;
639 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
640 } asl_message;
641
642 // By default, messages are only readable by the admin group. Explicitly
643 // make them readable by the user generating the messages.
644 char euid_string[12];
645 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
646 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
647
648 // Map Chrome log severities to ASL log levels.
649 const char* const asl_level_string = [](LogSeverity severity) {
650 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
651 // non-obvious two-step macro trick achieves what's needed.
652 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
653 #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
654 #define ASL_LEVEL_STR_X(level) #level
655 switch (severity) {
656 case LOG_INFO:
657 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
658 case LOG_WARNING:
659 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
660 case LOG_ERROR:
661 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
662 case LOG_FATAL:
663 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
664 default:
665 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
666 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
667 }
668 #undef ASL_LEVEL_STR
669 #undef ASL_LEVEL_STR_X
670 }(severity_);
671 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
672
673 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
674
675 asl_send(asl_client.get(), asl_message.get());
676 }
677 #elif defined(OS_ANDROID) || defined(__ANDROID__)
678 android_LogPriority priority =
679 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
680 switch (severity_) {
681 case LOG_INFO:
682 priority = ANDROID_LOG_INFO;
683 break;
684 case LOG_WARNING:
685 priority = ANDROID_LOG_WARN;
686 break;
687 case LOG_ERROR:
688 priority = ANDROID_LOG_ERROR;
689 break;
690 case LOG_FATAL:
691 priority = ANDROID_LOG_FATAL;
692 break;
693 }
694 #if defined(OS_ANDROID)
695 __android_log_write(priority, "chromium", str_newline.c_str());
696 #else
697 __android_log_write(
698 priority,
699 base::CommandLine::InitializedForCurrentProcess() ?
700 base::CommandLine::ForCurrentProcess()->
701 GetProgram().BaseName().value().c_str() : nullptr,
702 str_newline.c_str());
703 #endif // defined(OS_ANDROID)
704 #endif
705 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
706 fflush(stderr);
707 } else if (severity_ >= kAlwaysPrintErrorLevel) {
708 // When we're only outputting to a log file, above a certain log level, we
709 // should still output to stderr so that we can better detect and diagnose
710 // problems with unit tests, especially on the buildbots.
711 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
712 fflush(stderr);
713 }
714
715 // write to log file
716 if ((g_logging_destination & LOG_TO_FILE) != 0) {
717 // We can have multiple threads and/or processes, so try to prevent them
718 // from clobbering each other's writes.
719 // If the client app did not call InitLogging, and the lock has not
720 // been created do it now. We do this on demand, but if two threads try
721 // to do this at the same time, there will be a race condition to create
722 // the lock. This is why InitLogging should be called from the main
723 // thread at the beginning of execution.
724 #if !defined(OS_WIN)
725 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
726 LoggingLock logging_lock;
727 #endif
728 if (InitializeLogFileHandle()) {
729 #if defined(OS_WIN)
730 DWORD num_written;
731 WriteFile(g_log_file,
732 static_cast<const void*>(str_newline.c_str()),
733 static_cast<DWORD>(str_newline.length()),
734 &num_written,
735 nullptr);
736 #else
737 ignore_result(fwrite(
738 str_newline.data(), str_newline.size(), 1, g_log_file));
739 fflush(g_log_file);
740 #endif
741 }
742 }
743
744 if (severity_ == LOG_FATAL) {
745 // Write the log message to the global activity tracker, if running.
746 base::debug::GlobalActivityTracker* tracker =
747 base::debug::GlobalActivityTracker::Get();
748 if (tracker)
749 tracker->RecordLogMessage(str_newline);
750
751 // Ensure the first characters of the string are on the stack so they
752 // are contained in minidumps for diagnostic purposes.
753 char str_stack[1024];
754 str_newline.copy(str_stack, arraysize(str_stack));
755 base::debug::Alias(str_stack);
756
757 if (log_assert_handler) {
758 // Make a copy of the string for the handler out of paranoia.
759 log_assert_handler(std::string(stream_.str()));
760 } else {
761 // Don't use the string with the newline, get a fresh version to send to
762 // the debug message process. We also don't display assertions to the
763 // user in release mode. The enduser can't do anything with this
764 // information, and displaying message boxes when the application is
765 // hosed can cause additional problems.
766 #ifndef NDEBUG
767 if (!base::debug::BeingDebugged()) {
768 // Displaying a dialog is unnecessary when debugging and can complicate
769 // debugging.
770 DisplayDebugMessageInDialog(stream_.str());
771 }
772 #endif
773 // Crash the process to generate a dump.
774 base::debug::BreakDebugger();
775 }
776 }
777 }
778
779 // writes the common header info to the stream
Init(const char * file,int line)780 void LogMessage::Init(const char* file, int line) {
781 base::StringPiece filename(file);
782 size_t last_slash_pos = filename.find_last_of("\\/");
783 if (last_slash_pos != base::StringPiece::npos)
784 filename.remove_prefix(last_slash_pos + 1);
785
786 // TODO(darin): It might be nice if the columns were fixed width.
787
788 stream_ << '[';
789 if (g_log_process_id)
790 stream_ << CurrentProcessId() << ':';
791 if (g_log_thread_id)
792 stream_ << base::PlatformThread::CurrentId() << ':';
793 if (g_log_timestamp) {
794 #if defined(OS_POSIX)
795 timeval tv;
796 gettimeofday(&tv, nullptr);
797 time_t t = tv.tv_sec;
798 struct tm local_time;
799 localtime_r(&t, &local_time);
800 struct tm* tm_time = &local_time;
801 stream_ << std::setfill('0')
802 << std::setw(2) << 1 + tm_time->tm_mon
803 << std::setw(2) << tm_time->tm_mday
804 << '/'
805 << std::setw(2) << tm_time->tm_hour
806 << std::setw(2) << tm_time->tm_min
807 << std::setw(2) << tm_time->tm_sec
808 << '.'
809 << std::setw(6) << tv.tv_usec
810 << ':';
811 #elif defined(OS_WIN)
812 SYSTEMTIME local_time;
813 GetLocalTime(&local_time);
814 stream_ << std::setfill('0')
815 << std::setw(2) << local_time.wMonth
816 << std::setw(2) << local_time.wDay
817 << '/'
818 << std::setw(2) << local_time.wHour
819 << std::setw(2) << local_time.wMinute
820 << std::setw(2) << local_time.wSecond
821 << '.'
822 << std::setw(3) << local_time.wMilliseconds
823 << ':';
824 #endif
825 }
826 if (g_log_tickcount)
827 stream_ << TickCount() << ':';
828 if (severity_ >= 0)
829 stream_ << log_severity_name(severity_);
830 else
831 stream_ << "VERBOSE" << -severity_;
832
833 stream_ << ":" << filename << "(" << line << ")] ";
834
835 message_start_ = stream_.str().length();
836 }
837
838 #if defined(OS_WIN)
839 // This has already been defined in the header, but defining it again as DWORD
840 // ensures that the type used in the header is equivalent to DWORD. If not,
841 // the redefinition is a compile error.
842 typedef DWORD SystemErrorCode;
843 #endif
844
GetLastSystemErrorCode()845 SystemErrorCode GetLastSystemErrorCode() {
846 #if defined(OS_WIN)
847 return ::GetLastError();
848 #elif defined(OS_POSIX)
849 return errno;
850 #else
851 #error Not implemented
852 #endif
853 }
854
855 #if defined(OS_WIN)
SystemErrorCodeToString(SystemErrorCode error_code)856 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
857 const int kErrorMessageBufferSize = 256;
858 char msgbuf[kErrorMessageBufferSize];
859 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
860 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
861 arraysize(msgbuf), nullptr);
862 if (len) {
863 // Messages returned by system end with line breaks.
864 return base::CollapseWhitespaceASCII(msgbuf, true) +
865 base::StringPrintf(" (0x%X)", error_code);
866 }
867 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
868 GetLastError(), error_code);
869 }
870 #elif defined(OS_POSIX)
SystemErrorCodeToString(SystemErrorCode error_code)871 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
872 return base::safe_strerror(error_code);
873 }
874 #else
875 #error Not implemented
876 #endif // defined(OS_WIN)
877
878
879 #if defined(OS_WIN)
Win32ErrorLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)880 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
881 int line,
882 LogSeverity severity,
883 SystemErrorCode err)
884 : err_(err),
885 log_message_(file, line, severity) {
886 }
887
~Win32ErrorLogMessage()888 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
889 stream() << ": " << SystemErrorCodeToString(err_);
890 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
891 // field) and use Alias in hopes that it makes it into crash dumps.
892 DWORD last_error = err_;
893 base::debug::Alias(&last_error);
894 }
895 #elif defined(OS_POSIX)
ErrnoLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)896 ErrnoLogMessage::ErrnoLogMessage(const char* file,
897 int line,
898 LogSeverity severity,
899 SystemErrorCode err)
900 : err_(err),
901 log_message_(file, line, severity) {
902 }
903
~ErrnoLogMessage()904 ErrnoLogMessage::~ErrnoLogMessage() {
905 stream() << ": " << SystemErrorCodeToString(err_);
906 }
907 #endif // defined(OS_WIN)
908
CloseLogFile()909 void CloseLogFile() {
910 #if !defined(OS_WIN)
911 LoggingLock logging_lock;
912 #endif
913 CloseLogFileUnlocked();
914 }
915
RawLog(int level,const char * message)916 void RawLog(int level, const char* message) {
917 if (level >= g_min_log_level && message) {
918 size_t bytes_written = 0;
919 const size_t message_len = strlen(message);
920 int rv;
921 while (bytes_written < message_len) {
922 rv = HANDLE_EINTR(
923 write(STDERR_FILENO, message + bytes_written,
924 message_len - bytes_written));
925 if (rv < 0) {
926 // Give up, nothing we can do now.
927 break;
928 }
929 bytes_written += rv;
930 }
931
932 if (message_len > 0 && message[message_len - 1] != '\n') {
933 do {
934 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
935 if (rv < 0) {
936 // Give up, nothing we can do now.
937 break;
938 }
939 } while (rv != 1);
940 }
941 }
942
943 if (level == LOG_FATAL)
944 base::debug::BreakDebugger();
945 }
946
947 // This was defined at the beginning of this file.
948 #undef write
949
950 #if defined(OS_WIN)
IsLoggingToFileEnabled()951 bool IsLoggingToFileEnabled() {
952 return g_logging_destination & LOG_TO_FILE;
953 }
954
GetLogFileFullPath()955 std::wstring GetLogFileFullPath() {
956 if (g_log_file_name)
957 return *g_log_file_name;
958 return std::wstring();
959 }
960 #endif
961
LogErrorNotReached(const char * file,int line)962 BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
963 LogMessage(file, line, LOG_ERROR).stream()
964 << "NOTREACHED() hit.";
965 }
966
967 } // namespace logging
968
operator <<(std::ostream & out,const wchar_t * wstr)969 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
970 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
971 }
972