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.
5 #include "base/logging.h"
10 typedef HANDLE FileHandle
;
11 typedef HANDLE MutexHandle
;
12 // Windows warns on using write(). It prefers _write().
13 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
14 // Windows doesn't define STDERR_FILENO. Define it here.
15 #define STDERR_FILENO 2
16 #elif defined(OS_MACOSX)
17 #include <mach/mach.h>
18 #include <mach/mach_time.h>
19 #include <mach-o/dyld.h>
20 #elif defined(OS_POSIX)
22 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
24 #include <sys/syscall.h>
36 #define MAX_PATH PATH_MAX
37 typedef FILE* FileHandle
;
38 typedef pthread_mutex_t
* MutexHandle
;
48 #include "base/base_switches.h"
49 #include "base/command_line.h"
50 #include "base/debug/alias.h"
51 #include "base/debug/debugger.h"
52 #include "base/debug/stack_trace.h"
53 #include "base/posix/eintr_wrapper.h"
54 #include "base/strings/string_piece.h"
55 #include "base/strings/string_util.h"
56 #include "base/strings/stringprintf.h"
57 #include "base/strings/utf_string_conversions.h"
58 #include "base/synchronization/lock_impl.h"
59 #include "base/threading/platform_thread.h"
60 #include "base/vlog.h"
62 #include "base/safe_strerror_posix.h"
65 #if defined(OS_ANDROID)
66 #include <android/log.h>
73 VlogInfo
* g_vlog_info
= NULL
;
74 VlogInfo
* g_vlog_info_prev
= NULL
;
76 const char* const log_severity_names
[LOG_NUM_SEVERITIES
] = {
77 "INFO", "WARNING", "ERROR", "FATAL" };
79 const char* log_severity_name(int severity
) {
80 if (severity
>= 0 && severity
< LOG_NUM_SEVERITIES
)
81 return log_severity_names
[severity
];
85 int min_log_level
= 0;
87 LoggingDestination logging_destination
= LOG_DEFAULT
;
89 // For LOG_ERROR and above, always print to stderr.
90 const int kAlwaysPrintErrorLevel
= LOG_ERROR
;
92 // Which log file to use? This is initialized by InitLogging or
93 // will be lazily initialized to the default value when it is
96 typedef std::wstring PathString
;
98 typedef std::string PathString
;
100 PathString
* log_file_name
= NULL
;
102 // this file is lazily opened and the handle may be NULL
103 FileHandle log_file
= NULL
;
105 // what should be prepended to each message?
106 bool log_process_id
= false;
107 bool log_thread_id
= false;
108 bool log_timestamp
= true;
109 bool log_tickcount
= false;
111 // Should we pop up fatal debug messages in a dialog?
112 bool show_error_dialogs
= false;
114 // An assert handler override specified by the client to be called instead of
115 // the debug message dialog and process termination.
116 LogAssertHandlerFunction log_assert_handler
= NULL
;
117 // A log message handler that gets notified of every log message we process.
118 LogMessageHandlerFunction log_message_handler
= NULL
;
120 // Helper functions to wrap platform differences.
122 int32
CurrentProcessId() {
124 return GetCurrentProcessId();
125 #elif defined(OS_POSIX)
132 return GetTickCount();
133 #elif defined(OS_MACOSX)
134 return mach_absolute_time();
135 #elif defined(OS_NACL)
136 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
137 // So we have to use clock() for now.
139 #elif defined(OS_POSIX)
141 clock_gettime(CLOCK_MONOTONIC
, &ts
);
143 uint64 absolute_micro
=
144 static_cast<int64
>(ts
.tv_sec
) * 1000000 +
145 static_cast<int64
>(ts
.tv_nsec
) / 1000;
147 return absolute_micro
;
151 void DeleteFilePath(const PathString
& log_name
) {
153 DeleteFile(log_name
.c_str());
154 #elif defined(OS_NACL)
155 // Do nothing; unlink() isn't supported on NaCl.
157 unlink(log_name
.c_str());
161 PathString
GetDefaultLogFile() {
163 // On Windows we use the same path as the exe.
164 wchar_t module_name
[MAX_PATH
];
165 GetModuleFileName(NULL
, module_name
, MAX_PATH
);
167 PathString log_file
= module_name
;
168 PathString::size_type last_backslash
=
169 log_file
.rfind('\\', log_file
.size());
170 if (last_backslash
!= PathString::npos
)
171 log_file
.erase(last_backslash
+ 1);
172 log_file
+= L
"debug.log";
174 #elif defined(OS_POSIX)
175 // On other platforms we just use the current directory.
176 return PathString("debug.log");
180 // This class acts as a wrapper for locking the logging files.
181 // LoggingLock::Init() should be called from the main thread before any logging
182 // is done. Then whenever logging, be sure to have a local LoggingLock
183 // instance on the stack. This will ensure that the lock is unlocked upon
184 // exiting the frame.
185 // LoggingLocks can not be nested.
196 static void Init(LogLockingState lock_log
, const PathChar
* new_log_file
) {
199 lock_log_file
= lock_log
;
200 if (lock_log_file
== LOCK_LOG_FILE
) {
203 std::wstring safe_name
;
205 safe_name
= new_log_file
;
207 safe_name
= GetDefaultLogFile();
208 // \ is not a legal character in mutex names so we replace \ with /
209 std::replace(safe_name
.begin(), safe_name
.end(), '\\', '/');
210 std::wstring
t(L
"Global\\");
212 log_mutex
= ::CreateMutex(NULL
, FALSE
, t
.c_str());
214 if (log_mutex
== NULL
) {
216 // Keep the error code for debugging
217 int error
= GetLastError(); // NOLINT
218 base::debug::BreakDebugger();
220 // Return nicely without putting initialized to true.
226 log_lock
= new base::internal::LockImpl();
232 static void LockLogging() {
233 if (lock_log_file
== LOCK_LOG_FILE
) {
235 ::WaitForSingleObject(log_mutex
, INFINITE
);
236 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
237 // abort the process here. UI tests might be crashy sometimes,
238 // and aborting the test binary only makes the problem worse.
239 // We also don't use LOG macros because that might lead to an infinite
240 // loop. For more info see http://crbug.com/18028.
241 #elif defined(OS_POSIX)
242 pthread_mutex_lock(&log_mutex
);
250 static void UnlockLogging() {
251 if (lock_log_file
== LOCK_LOG_FILE
) {
253 ReleaseMutex(log_mutex
);
254 #elif defined(OS_POSIX)
255 pthread_mutex_unlock(&log_mutex
);
262 // The lock is used if log file locking is false. It helps us avoid problems
263 // with multiple threads writing to the log file at the same time. Use
264 // LockImpl directly instead of using Lock, because Lock makes logging calls.
265 static base::internal::LockImpl
* log_lock
;
267 // When we don't use a lock, we are using a global mutex. We need to do this
268 // because LockFileEx is not thread safe.
270 static MutexHandle log_mutex
;
271 #elif defined(OS_POSIX)
272 static pthread_mutex_t log_mutex
;
275 static bool initialized
;
276 static LogLockingState lock_log_file
;
280 bool LoggingLock::initialized
= false;
282 base::internal::LockImpl
* LoggingLock::log_lock
= NULL
;
284 LogLockingState
LoggingLock::lock_log_file
= LOCK_LOG_FILE
;
288 MutexHandle
LoggingLock::log_mutex
= NULL
;
289 #elif defined(OS_POSIX)
290 pthread_mutex_t
LoggingLock::log_mutex
= PTHREAD_MUTEX_INITIALIZER
;
293 // Called by logging functions to ensure that debug_file is initialized
294 // and can be used for writing. Returns false if the file could not be
295 // initialized. debug_file will be NULL in this case.
296 bool InitializeLogFileHandle() {
300 if (!log_file_name
) {
301 // Nobody has called InitLogging to specify a debug log file, so here we
302 // initialize the log file name to a default.
303 log_file_name
= new PathString(GetDefaultLogFile());
306 if ((logging_destination
& LOG_TO_FILE
) != 0) {
308 log_file
= CreateFile(log_file_name
->c_str(), GENERIC_WRITE
,
309 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
310 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
311 if (log_file
== INVALID_HANDLE_VALUE
|| log_file
== NULL
) {
312 // try the current directory
313 log_file
= CreateFile(L
".\\debug.log", GENERIC_WRITE
,
314 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
315 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
316 if (log_file
== INVALID_HANDLE_VALUE
|| log_file
== NULL
) {
321 SetFilePointer(log_file
, 0, 0, FILE_END
);
322 #elif defined(OS_POSIX)
323 log_file
= fopen(log_file_name
->c_str(), "a");
324 if (log_file
== NULL
)
332 void CloseFile(FileHandle log
) {
340 void CloseLogFileUnlocked() {
350 LoggingSettings::LoggingSettings()
351 : logging_dest(LOG_DEFAULT
),
353 lock_log(LOCK_LOG_FILE
),
354 delete_old(APPEND_TO_OLD_LOG_FILE
) {}
356 bool BaseInitLoggingImpl(const LoggingSettings
& settings
) {
358 // Can log only to the system debug log.
359 CHECK_EQ(settings
.logging_dest
& ~LOG_TO_SYSTEM_DEBUG_LOG
, 0);
361 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
362 // Don't bother initializing g_vlog_info unless we use one of the
364 if (command_line
->HasSwitch(switches::kV
) ||
365 command_line
->HasSwitch(switches::kVModule
)) {
366 // NOTE: If g_vlog_info has already been initialized, it might be in use
367 // by another thread. Don't delete the old VLogInfo, just create a second
368 // one. We keep track of both to avoid memory leak warnings.
369 CHECK(!g_vlog_info_prev
);
370 g_vlog_info_prev
= g_vlog_info
;
373 new VlogInfo(command_line
->GetSwitchValueASCII(switches::kV
),
374 command_line
->GetSwitchValueASCII(switches::kVModule
),
378 logging_destination
= settings
.logging_dest
;
380 // ignore file options unless logging to file is set.
381 if ((logging_destination
& LOG_TO_FILE
) == 0)
384 LoggingLock::Init(settings
.lock_log
, settings
.log_file
);
385 LoggingLock logging_lock
;
387 // Calling InitLogging twice or after some log call has already opened the
388 // default log file will re-initialize to the new options.
389 CloseLogFileUnlocked();
392 log_file_name
= new PathString();
393 *log_file_name
= settings
.log_file
;
394 if (settings
.delete_old
== DELETE_OLD_LOG_FILE
)
395 DeleteFilePath(*log_file_name
);
397 return InitializeLogFileHandle();
400 void SetMinLogLevel(int level
) {
401 min_log_level
= std::min(LOG_FATAL
, level
);
404 int GetMinLogLevel() {
405 return min_log_level
;
408 int GetVlogVerbosity() {
409 return std::max(-1, LOG_INFO
- GetMinLogLevel());
412 int GetVlogLevelHelper(const char* file
, size_t N
) {
414 // Note: g_vlog_info may change on a different thread during startup
415 // (but will always be valid or NULL).
416 VlogInfo
* vlog_info
= g_vlog_info
;
418 vlog_info
->GetVlogLevel(base::StringPiece(file
, N
- 1)) :
422 void SetLogItems(bool enable_process_id
, bool enable_thread_id
,
423 bool enable_timestamp
, bool enable_tickcount
) {
424 log_process_id
= enable_process_id
;
425 log_thread_id
= enable_thread_id
;
426 log_timestamp
= enable_timestamp
;
427 log_tickcount
= enable_tickcount
;
430 void SetShowErrorDialogs(bool enable_dialogs
) {
431 show_error_dialogs
= enable_dialogs
;
434 void SetLogAssertHandler(LogAssertHandlerFunction handler
) {
435 log_assert_handler
= handler
;
438 void SetLogMessageHandler(LogMessageHandlerFunction handler
) {
439 log_message_handler
= handler
;
442 LogMessageHandlerFunction
GetLogMessageHandler() {
443 return log_message_handler
;
446 // Explicit instantiations for commonly used comparisons.
447 template std::string
* MakeCheckOpString
<int, int>(
448 const int&, const int&, const char* names
);
449 template std::string
* MakeCheckOpString
<unsigned long, unsigned long>(
450 const unsigned long&, const unsigned long&, const char* names
);
451 template std::string
* MakeCheckOpString
<unsigned long, unsigned int>(
452 const unsigned long&, const unsigned int&, const char* names
);
453 template std::string
* MakeCheckOpString
<unsigned int, unsigned long>(
454 const unsigned int&, const unsigned long&, const char* names
);
455 template std::string
* MakeCheckOpString
<std::string
, std::string
>(
456 const std::string
&, const std::string
&, const char* name
);
459 // Displays a message box to the user with the error message in it.
460 // Used for fatal messages, where we close the app simultaneously.
461 // This is for developers only; we don't use this in circumstances
462 // (like release builds) where users could see it, since users don't
463 // understand these messages anyway.
464 void DisplayDebugMessageInDialog(const std::string
& str
) {
468 if (!show_error_dialogs
)
472 // For Windows programs, it's possible that the message loop is
473 // messed up on a fatal error, and creating a MessageBox will cause
474 // that message loop to be run. Instead, we try to spawn another
475 // process that displays its command line. We look for "Debug
476 // Message.exe" in the same directory as the application. If it
477 // exists, we use it, otherwise, we use a regular message box.
478 wchar_t prog_name
[MAX_PATH
];
479 GetModuleFileNameW(NULL
, prog_name
, MAX_PATH
);
480 wchar_t* backslash
= wcsrchr(prog_name
, '\\');
483 wcscat_s(prog_name
, MAX_PATH
, L
"debug_message.exe");
485 std::wstring cmdline
= base::UTF8ToWide(str
);
489 STARTUPINFO startup_info
;
490 memset(&startup_info
, 0, sizeof(startup_info
));
491 startup_info
.cb
= sizeof(startup_info
);
493 PROCESS_INFORMATION process_info
;
494 if (CreateProcessW(prog_name
, &cmdline
[0], NULL
, NULL
, false, 0, NULL
,
495 NULL
, &startup_info
, &process_info
)) {
496 WaitForSingleObject(process_info
.hProcess
, INFINITE
);
497 CloseHandle(process_info
.hThread
);
498 CloseHandle(process_info
.hProcess
);
500 // debug process broken, let's just do a message box
501 MessageBoxW(NULL
, &cmdline
[0], L
"Fatal error",
502 MB_OK
| MB_ICONHAND
| MB_TOPMOST
);
505 // We intentionally don't implement a dialog on other platforms.
506 // You can just look at stderr.
509 #endif // !defined(NDEBUG)
512 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
515 LogMessage::SaveLastError::~SaveLastError() {
516 ::SetLastError(last_error_
);
518 #endif // defined(OS_WIN)
520 LogMessage::LogMessage(const char* file
, int line
, LogSeverity severity
)
521 : severity_(severity
), file_(file
), line_(line
) {
525 LogMessage::LogMessage(const char* file
, int line
, std::string
* result
)
526 : severity_(LOG_FATAL
), file_(file
), line_(line
) {
528 stream_
<< "Check failed: " << *result
;
532 LogMessage::LogMessage(const char* file
, int line
, LogSeverity severity
,
534 : severity_(severity
), file_(file
), line_(line
) {
536 stream_
<< "Check failed: " << *result
;
540 LogMessage::~LogMessage() {
541 #if !defined(NDEBUG) && !defined(OS_NACL) && !defined(__UCLIBC__)
542 if (severity_
== LOG_FATAL
) {
543 // Include a stack trace on a fatal.
544 base::debug::StackTrace trace
;
545 stream_
<< std::endl
; // Newline to separate from log message.
546 trace
.OutputToStream(&stream_
);
549 stream_
<< std::endl
;
550 std::string
str_newline(stream_
.str());
552 // Give any log message handler first dibs on the message.
553 if (log_message_handler
&&
554 log_message_handler(severity_
, file_
, line_
,
555 message_start_
, str_newline
)) {
556 // The handler took care of it, no further processing.
560 if ((logging_destination
& LOG_TO_SYSTEM_DEBUG_LOG
) != 0) {
562 OutputDebugStringA(str_newline
.c_str());
563 #elif defined(OS_ANDROID)
564 android_LogPriority priority
=
565 (severity_
< 0) ? ANDROID_LOG_VERBOSE
: ANDROID_LOG_UNKNOWN
;
568 priority
= ANDROID_LOG_INFO
;
571 priority
= ANDROID_LOG_WARN
;
574 priority
= ANDROID_LOG_ERROR
;
577 priority
= ANDROID_LOG_FATAL
;
580 __android_log_write(priority
, "chromium", str_newline
.c_str());
582 ignore_result(fwrite(str_newline
.data(), str_newline
.size(), 1, stderr
));
584 } else if (severity_
>= kAlwaysPrintErrorLevel
) {
585 // When we're only outputting to a log file, above a certain log level, we
586 // should still output to stderr so that we can better detect and diagnose
587 // problems with unit tests, especially on the buildbots.
588 ignore_result(fwrite(str_newline
.data(), str_newline
.size(), 1, stderr
));
593 if ((logging_destination
& LOG_TO_FILE
) != 0) {
594 // We can have multiple threads and/or processes, so try to prevent them
595 // from clobbering each other's writes.
596 // If the client app did not call InitLogging, and the lock has not
597 // been created do it now. We do this on demand, but if two threads try
598 // to do this at the same time, there will be a race condition to create
599 // the lock. This is why InitLogging should be called from the main
600 // thread at the beginning of execution.
601 LoggingLock::Init(LOCK_LOG_FILE
, NULL
);
602 LoggingLock logging_lock
;
603 if (InitializeLogFileHandle()) {
605 SetFilePointer(log_file
, 0, 0, SEEK_END
);
608 static_cast<const void*>(str_newline
.c_str()),
609 static_cast<DWORD
>(str_newline
.length()),
613 ignore_result(fwrite(
614 str_newline
.data(), str_newline
.size(), 1, log_file
));
620 if (severity_
== LOG_FATAL
) {
621 // Ensure the first characters of the string are on the stack so they
622 // are contained in minidumps for diagnostic purposes.
623 char str_stack
[1024];
624 str_newline
.copy(str_stack
, arraysize(str_stack
));
625 base::debug::Alias(str_stack
);
627 if (log_assert_handler
) {
628 // Make a copy of the string for the handler out of paranoia.
629 log_assert_handler(std::string(stream_
.str()));
631 // Don't use the string with the newline, get a fresh version to send to
632 // the debug message process. We also don't display assertions to the
633 // user in release mode. The enduser can't do anything with this
634 // information, and displaying message boxes when the application is
635 // hosed can cause additional problems.
637 DisplayDebugMessageInDialog(stream_
.str());
639 // Crash the process to generate a dump.
640 base::debug::BreakDebugger();
645 // writes the common header info to the stream
646 void LogMessage::Init(const char* file
, int line
) {
647 base::StringPiece
filename(file
);
648 size_t last_slash_pos
= filename
.find_last_of("\\/");
649 if (last_slash_pos
!= base::StringPiece::npos
)
650 filename
.remove_prefix(last_slash_pos
+ 1);
652 // TODO(darin): It might be nice if the columns were fixed width.
656 stream_
<< CurrentProcessId() << ':';
658 stream_
<< base::PlatformThread::CurrentId() << ':';
660 time_t t
= time(NULL
);
661 struct tm local_time
= {0};
663 localtime_s(&local_time
, &t
);
665 localtime_r(&t
, &local_time
);
667 struct tm
* tm_time
= &local_time
;
668 stream_
<< std::setfill('0')
669 << std::setw(2) << 1 + tm_time
->tm_mon
670 << std::setw(2) << tm_time
->tm_mday
672 << std::setw(2) << tm_time
->tm_hour
673 << std::setw(2) << tm_time
->tm_min
674 << std::setw(2) << tm_time
->tm_sec
678 stream_
<< TickCount() << ':';
680 stream_
<< log_severity_name(severity_
);
682 stream_
<< "VERBOSE" << -severity_
;
684 stream_
<< ":" << filename
<< "(" << line
<< ")] ";
686 message_start_
= stream_
.str().length();
690 // This has already been defined in the header, but defining it again as DWORD
691 // ensures that the type used in the header is equivalent to DWORD. If not,
692 // the redefinition is a compile error.
693 typedef DWORD SystemErrorCode
;
696 SystemErrorCode
GetLastSystemErrorCode() {
698 return ::GetLastError();
699 #elif defined(OS_POSIX)
702 #error Not implemented
707 BASE_EXPORT
std::string
SystemErrorCodeToString(SystemErrorCode error_code
) {
708 const int kErrorMessageBufferSize
= 256;
709 char msgbuf
[kErrorMessageBufferSize
];
710 DWORD flags
= FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
;
711 DWORD len
= FormatMessageA(flags
, NULL
, error_code
, 0, msgbuf
,
712 arraysize(msgbuf
), NULL
);
714 // Messages returned by system end with line breaks.
715 return base::CollapseWhitespaceASCII(msgbuf
, true) +
716 base::StringPrintf(" (0x%X)", error_code
);
718 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
719 GetLastError(), error_code
);
721 #elif defined(OS_POSIX)
722 BASE_EXPORT
std::string
SystemErrorCodeToString(SystemErrorCode error_code
) {
723 return safe_strerror(error_code
);
726 #error Not implemented
731 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file
,
733 LogSeverity severity
,
736 log_message_(file
, line
, severity
) {
739 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
740 stream() << ": " << SystemErrorCodeToString(err_
);
741 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
742 // field) and use Alias in hopes that it makes it into crash dumps.
743 DWORD last_error
= err_
;
744 base::debug::Alias(&last_error
);
746 #elif defined(OS_POSIX)
747 ErrnoLogMessage::ErrnoLogMessage(const char* file
,
749 LogSeverity severity
,
752 log_message_(file
, line
, severity
) {
755 ErrnoLogMessage::~ErrnoLogMessage() {
756 stream() << ": " << SystemErrorCodeToString(err_
);
760 void CloseLogFile() {
761 LoggingLock logging_lock
;
762 CloseLogFileUnlocked();
765 void RawLog(int level
, const char* message
) {
766 if (level
>= min_log_level
) {
767 size_t bytes_written
= 0;
768 const size_t message_len
= strlen(message
);
770 while (bytes_written
< message_len
) {
772 write(STDERR_FILENO
, message
+ bytes_written
,
773 message_len
- bytes_written
));
775 // Give up, nothing we can do now.
781 if (message_len
> 0 && message
[message_len
- 1] != '\n') {
783 rv
= HANDLE_EINTR(write(STDERR_FILENO
, "\n", 1));
785 // Give up, nothing we can do now.
792 if (level
== LOG_FATAL
)
793 base::debug::BreakDebugger();
796 // This was defined at the beginning of this file.
800 std::wstring
GetLogFileFullPath() {
802 return *log_file_name
;
803 return std::wstring();
807 } // namespace logging
809 std::ostream
& std::operator<<(std::ostream
& out
, const wchar_t* wstr
) {
810 return out
<< base::WideToUTF8(wstr
);