michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/logging.h" michael@0: michael@0: #if defined(OS_WIN) michael@0: #include michael@0: #include michael@0: typedef HANDLE FileHandle; michael@0: typedef HANDLE MutexHandle; michael@0: // Windows warns on using write(). It prefers _write(). michael@0: #define write(fd, buf, count) _write(fd, buf, static_cast(count)) michael@0: // Windows doesn't define STDERR_FILENO. Define it here. michael@0: #define STDERR_FILENO 2 michael@0: #elif defined(OS_MACOSX) michael@0: #include michael@0: #include michael@0: #include michael@0: #elif defined(OS_POSIX) michael@0: #if defined(OS_NACL) michael@0: #include // timespec doesn't seem to be in michael@0: #else michael@0: #include michael@0: #endif michael@0: #include michael@0: #endif michael@0: michael@0: #if defined(OS_POSIX) michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #define MAX_PATH PATH_MAX michael@0: typedef FILE* FileHandle; michael@0: typedef pthread_mutex_t* MutexHandle; michael@0: #endif michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "base/base_switches.h" michael@0: #include "base/command_line.h" michael@0: #include "base/debug/alias.h" michael@0: #include "base/debug/debugger.h" michael@0: #include "base/debug/stack_trace.h" michael@0: #include "base/posix/eintr_wrapper.h" michael@0: #include "base/strings/string_piece.h" michael@0: #include "base/strings/utf_string_conversions.h" michael@0: #include "base/synchronization/lock_impl.h" michael@0: #include "base/threading/platform_thread.h" michael@0: #include "base/vlog.h" michael@0: #if defined(OS_POSIX) michael@0: #include "base/safe_strerror_posix.h" michael@0: #endif michael@0: michael@0: #if defined(OS_ANDROID) michael@0: #include michael@0: #endif michael@0: michael@0: namespace logging { michael@0: michael@0: DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS; michael@0: michael@0: DcheckState get_dcheck_state() { michael@0: return g_dcheck_state; michael@0: } michael@0: michael@0: void set_dcheck_state(DcheckState state) { michael@0: g_dcheck_state = state; michael@0: } michael@0: michael@0: namespace { michael@0: michael@0: VlogInfo* g_vlog_info = NULL; michael@0: VlogInfo* g_vlog_info_prev = NULL; michael@0: michael@0: const char* const log_severity_names[LOG_NUM_SEVERITIES] = { michael@0: "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" }; michael@0: michael@0: int min_log_level = 0; michael@0: michael@0: LoggingDestination logging_destination = LOG_DEFAULT; michael@0: michael@0: // For LOG_ERROR and above, always print to stderr. michael@0: const int kAlwaysPrintErrorLevel = LOG_ERROR; michael@0: michael@0: // Which log file to use? This is initialized by InitLogging or michael@0: // will be lazily initialized to the default value when it is michael@0: // first needed. michael@0: #if defined(OS_WIN) michael@0: typedef std::wstring PathString; michael@0: #else michael@0: typedef std::string PathString; michael@0: #endif michael@0: PathString* log_file_name = NULL; michael@0: michael@0: // this file is lazily opened and the handle may be NULL michael@0: FileHandle log_file = NULL; michael@0: michael@0: // what should be prepended to each message? michael@0: bool log_process_id = false; michael@0: bool log_thread_id = false; michael@0: bool log_timestamp = true; michael@0: bool log_tickcount = false; michael@0: michael@0: // Should we pop up fatal debug messages in a dialog? michael@0: bool show_error_dialogs = false; michael@0: michael@0: // An assert handler override specified by the client to be called instead of michael@0: // the debug message dialog and process termination. michael@0: LogAssertHandlerFunction log_assert_handler = NULL; michael@0: // An report handler override specified by the client to be called instead of michael@0: // the debug message dialog. michael@0: LogReportHandlerFunction log_report_handler = NULL; michael@0: // A log message handler that gets notified of every log message we process. michael@0: LogMessageHandlerFunction log_message_handler = NULL; michael@0: michael@0: // Helper functions to wrap platform differences. michael@0: michael@0: int32 CurrentProcessId() { michael@0: #if defined(OS_WIN) michael@0: return GetCurrentProcessId(); michael@0: #elif defined(OS_POSIX) michael@0: return getpid(); michael@0: #endif michael@0: } michael@0: michael@0: uint64 TickCount() { michael@0: #if defined(OS_WIN) michael@0: return GetTickCount(); michael@0: #elif defined(OS_MACOSX) michael@0: return mach_absolute_time(); michael@0: #elif defined(OS_NACL) michael@0: // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h michael@0: // So we have to use clock() for now. michael@0: return clock(); michael@0: #elif defined(OS_POSIX) michael@0: struct timespec ts; michael@0: clock_gettime(CLOCK_MONOTONIC, &ts); michael@0: michael@0: uint64 absolute_micro = michael@0: static_cast(ts.tv_sec) * 1000000 + michael@0: static_cast(ts.tv_nsec) / 1000; michael@0: michael@0: return absolute_micro; michael@0: #endif michael@0: } michael@0: michael@0: void DeleteFilePath(const PathString& log_name) { michael@0: #if defined(OS_WIN) michael@0: DeleteFile(log_name.c_str()); michael@0: #elif defined (OS_NACL) michael@0: // Do nothing; unlink() isn't supported on NaCl. michael@0: #else michael@0: unlink(log_name.c_str()); michael@0: #endif michael@0: } michael@0: michael@0: PathString GetDefaultLogFile() { michael@0: #if defined(OS_WIN) michael@0: // On Windows we use the same path as the exe. michael@0: wchar_t module_name[MAX_PATH]; michael@0: GetModuleFileName(NULL, module_name, MAX_PATH); michael@0: michael@0: PathString log_file = module_name; michael@0: PathString::size_type last_backslash = michael@0: log_file.rfind('\\', log_file.size()); michael@0: if (last_backslash != PathString::npos) michael@0: log_file.erase(last_backslash + 1); michael@0: log_file += L"debug.log"; michael@0: return log_file; michael@0: #elif defined(OS_POSIX) michael@0: // On other platforms we just use the current directory. michael@0: return PathString("debug.log"); michael@0: #endif michael@0: } michael@0: michael@0: // This class acts as a wrapper for locking the logging files. michael@0: // LoggingLock::Init() should be called from the main thread before any logging michael@0: // is done. Then whenever logging, be sure to have a local LoggingLock michael@0: // instance on the stack. This will ensure that the lock is unlocked upon michael@0: // exiting the frame. michael@0: // LoggingLocks can not be nested. michael@0: class LoggingLock { michael@0: public: michael@0: LoggingLock() { michael@0: LockLogging(); michael@0: } michael@0: michael@0: ~LoggingLock() { michael@0: UnlockLogging(); michael@0: } michael@0: michael@0: static void Init(LogLockingState lock_log, const PathChar* new_log_file) { michael@0: if (initialized) michael@0: return; michael@0: lock_log_file = lock_log; michael@0: if (lock_log_file == LOCK_LOG_FILE) { michael@0: #if defined(OS_WIN) michael@0: if (!log_mutex) { michael@0: std::wstring safe_name; michael@0: if (new_log_file) michael@0: safe_name = new_log_file; michael@0: else michael@0: safe_name = GetDefaultLogFile(); michael@0: // \ is not a legal character in mutex names so we replace \ with / michael@0: std::replace(safe_name.begin(), safe_name.end(), '\\', '/'); michael@0: std::wstring t(L"Global\\"); michael@0: t.append(safe_name); michael@0: log_mutex = ::CreateMutex(NULL, FALSE, t.c_str()); michael@0: michael@0: if (log_mutex == NULL) { michael@0: #if DEBUG michael@0: // Keep the error code for debugging michael@0: int error = GetLastError(); // NOLINT michael@0: base::debug::BreakDebugger(); michael@0: #endif michael@0: // Return nicely without putting initialized to true. michael@0: return; michael@0: } michael@0: } michael@0: #endif michael@0: } else { michael@0: log_lock = new base::internal::LockImpl(); michael@0: } michael@0: initialized = true; michael@0: } michael@0: michael@0: private: michael@0: static void LockLogging() { michael@0: if (lock_log_file == LOCK_LOG_FILE) { michael@0: #if defined(OS_WIN) michael@0: ::WaitForSingleObject(log_mutex, INFINITE); michael@0: // WaitForSingleObject could have returned WAIT_ABANDONED. We don't michael@0: // abort the process here. UI tests might be crashy sometimes, michael@0: // and aborting the test binary only makes the problem worse. michael@0: // We also don't use LOG macros because that might lead to an infinite michael@0: // loop. For more info see http://crbug.com/18028. michael@0: #elif defined(OS_POSIX) michael@0: pthread_mutex_lock(&log_mutex); michael@0: #endif michael@0: } else { michael@0: // use the lock michael@0: log_lock->Lock(); michael@0: } michael@0: } michael@0: michael@0: static void UnlockLogging() { michael@0: if (lock_log_file == LOCK_LOG_FILE) { michael@0: #if defined(OS_WIN) michael@0: ReleaseMutex(log_mutex); michael@0: #elif defined(OS_POSIX) michael@0: pthread_mutex_unlock(&log_mutex); michael@0: #endif michael@0: } else { michael@0: log_lock->Unlock(); michael@0: } michael@0: } michael@0: michael@0: // The lock is used if log file locking is false. It helps us avoid problems michael@0: // with multiple threads writing to the log file at the same time. Use michael@0: // LockImpl directly instead of using Lock, because Lock makes logging calls. michael@0: static base::internal::LockImpl* log_lock; michael@0: michael@0: // When we don't use a lock, we are using a global mutex. We need to do this michael@0: // because LockFileEx is not thread safe. michael@0: #if defined(OS_WIN) michael@0: static MutexHandle log_mutex; michael@0: #elif defined(OS_POSIX) michael@0: static pthread_mutex_t log_mutex; michael@0: #endif michael@0: michael@0: static bool initialized; michael@0: static LogLockingState lock_log_file; michael@0: }; michael@0: michael@0: // static michael@0: bool LoggingLock::initialized = false; michael@0: // static michael@0: base::internal::LockImpl* LoggingLock::log_lock = NULL; michael@0: // static michael@0: LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE; michael@0: michael@0: #if defined(OS_WIN) michael@0: // static michael@0: MutexHandle LoggingLock::log_mutex = NULL; michael@0: #elif defined(OS_POSIX) michael@0: pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER; michael@0: #endif michael@0: michael@0: // Called by logging functions to ensure that debug_file is initialized michael@0: // and can be used for writing. Returns false if the file could not be michael@0: // initialized. debug_file will be NULL in this case. michael@0: bool InitializeLogFileHandle() { michael@0: if (log_file) michael@0: return true; michael@0: michael@0: if (!log_file_name) { michael@0: // Nobody has called InitLogging to specify a debug log file, so here we michael@0: // initialize the log file name to a default. michael@0: log_file_name = new PathString(GetDefaultLogFile()); michael@0: } michael@0: michael@0: if ((logging_destination & LOG_TO_FILE) != 0) { michael@0: #if defined(OS_WIN) michael@0: log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE, michael@0: FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, michael@0: OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); michael@0: if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) { michael@0: // try the current directory michael@0: log_file = CreateFile(L".\\debug.log", GENERIC_WRITE, michael@0: FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, michael@0: OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); michael@0: if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) { michael@0: log_file = NULL; michael@0: return false; michael@0: } michael@0: } michael@0: SetFilePointer(log_file, 0, 0, FILE_END); michael@0: #elif defined(OS_POSIX) michael@0: log_file = fopen(log_file_name->c_str(), "a"); michael@0: if (log_file == NULL) michael@0: return false; michael@0: #endif michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: void CloseFile(FileHandle log) { michael@0: #if defined(OS_WIN) michael@0: CloseHandle(log); michael@0: #else michael@0: fclose(log); michael@0: #endif michael@0: } michael@0: michael@0: void CloseLogFileUnlocked() { michael@0: if (!log_file) michael@0: return; michael@0: michael@0: CloseFile(log_file); michael@0: log_file = NULL; michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: LoggingSettings::LoggingSettings() michael@0: : logging_dest(LOG_DEFAULT), michael@0: log_file(NULL), michael@0: lock_log(LOCK_LOG_FILE), michael@0: delete_old(APPEND_TO_OLD_LOG_FILE), michael@0: dcheck_state(DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) {} michael@0: michael@0: bool BaseInitLoggingImpl(const LoggingSettings& settings) { michael@0: #if defined(OS_NACL) michael@0: // Can log only to the system debug log. michael@0: CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0); michael@0: #endif michael@0: g_dcheck_state = settings.dcheck_state; michael@0: CommandLine* command_line = CommandLine::ForCurrentProcess(); michael@0: // Don't bother initializing g_vlog_info unless we use one of the michael@0: // vlog switches. michael@0: if (command_line->HasSwitch(switches::kV) || michael@0: command_line->HasSwitch(switches::kVModule)) { michael@0: // NOTE: If g_vlog_info has already been initialized, it might be in use michael@0: // by another thread. Don't delete the old VLogInfo, just create a second michael@0: // one. We keep track of both to avoid memory leak warnings. michael@0: CHECK(!g_vlog_info_prev); michael@0: g_vlog_info_prev = g_vlog_info; michael@0: michael@0: g_vlog_info = michael@0: new VlogInfo(command_line->GetSwitchValueASCII(switches::kV), michael@0: command_line->GetSwitchValueASCII(switches::kVModule), michael@0: &min_log_level); michael@0: } michael@0: michael@0: logging_destination = settings.logging_dest; michael@0: michael@0: // ignore file options unless logging to file is set. michael@0: if ((logging_destination & LOG_TO_FILE) == 0) michael@0: return true; michael@0: michael@0: LoggingLock::Init(settings.lock_log, settings.log_file); michael@0: LoggingLock logging_lock; michael@0: michael@0: // Calling InitLogging twice or after some log call has already opened the michael@0: // default log file will re-initialize to the new options. michael@0: CloseLogFileUnlocked(); michael@0: michael@0: if (!log_file_name) michael@0: log_file_name = new PathString(); michael@0: *log_file_name = settings.log_file; michael@0: if (settings.delete_old == DELETE_OLD_LOG_FILE) michael@0: DeleteFilePath(*log_file_name); michael@0: michael@0: return InitializeLogFileHandle(); michael@0: } michael@0: michael@0: void SetMinLogLevel(int level) { michael@0: min_log_level = std::min(LOG_ERROR_REPORT, level); michael@0: } michael@0: michael@0: int GetMinLogLevel() { michael@0: return min_log_level; michael@0: } michael@0: michael@0: int GetVlogVerbosity() { michael@0: return std::max(-1, LOG_INFO - GetMinLogLevel()); michael@0: } michael@0: michael@0: int GetVlogLevelHelper(const char* file, size_t N) { michael@0: DCHECK_GT(N, 0U); michael@0: // Note: g_vlog_info may change on a different thread during startup michael@0: // (but will always be valid or NULL). michael@0: VlogInfo* vlog_info = g_vlog_info; michael@0: return vlog_info ? michael@0: vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) : michael@0: GetVlogVerbosity(); michael@0: } michael@0: michael@0: void SetLogItems(bool enable_process_id, bool enable_thread_id, michael@0: bool enable_timestamp, bool enable_tickcount) { michael@0: log_process_id = enable_process_id; michael@0: log_thread_id = enable_thread_id; michael@0: log_timestamp = enable_timestamp; michael@0: log_tickcount = enable_tickcount; michael@0: } michael@0: michael@0: void SetShowErrorDialogs(bool enable_dialogs) { michael@0: show_error_dialogs = enable_dialogs; michael@0: } michael@0: michael@0: void SetLogAssertHandler(LogAssertHandlerFunction handler) { michael@0: log_assert_handler = handler; michael@0: } michael@0: michael@0: void SetLogReportHandler(LogReportHandlerFunction handler) { michael@0: log_report_handler = handler; michael@0: } michael@0: michael@0: void SetLogMessageHandler(LogMessageHandlerFunction handler) { michael@0: log_message_handler = handler; michael@0: } michael@0: michael@0: LogMessageHandlerFunction GetLogMessageHandler() { michael@0: return log_message_handler; michael@0: } michael@0: michael@0: // MSVC doesn't like complex extern templates and DLLs. michael@0: #if !defined(COMPILER_MSVC) michael@0: // Explicit instantiations for commonly used comparisons. michael@0: template std::string* MakeCheckOpString( michael@0: const int&, const int&, const char* names); michael@0: template std::string* MakeCheckOpString( michael@0: const unsigned long&, const unsigned long&, const char* names); michael@0: template std::string* MakeCheckOpString( michael@0: const unsigned long&, const unsigned int&, const char* names); michael@0: template std::string* MakeCheckOpString( michael@0: const unsigned int&, const unsigned long&, const char* names); michael@0: template std::string* MakeCheckOpString( michael@0: const std::string&, const std::string&, const char* name); michael@0: #endif michael@0: michael@0: // Displays a message box to the user with the error message in it. michael@0: // Used for fatal messages, where we close the app simultaneously. michael@0: // This is for developers only; we don't use this in circumstances michael@0: // (like release builds) where users could see it, since users don't michael@0: // understand these messages anyway. michael@0: void DisplayDebugMessageInDialog(const std::string& str) { michael@0: if (str.empty()) michael@0: return; michael@0: michael@0: if (!show_error_dialogs) michael@0: return; michael@0: michael@0: #if defined(OS_WIN) michael@0: // For Windows programs, it's possible that the message loop is michael@0: // messed up on a fatal error, and creating a MessageBox will cause michael@0: // that message loop to be run. Instead, we try to spawn another michael@0: // process that displays its command line. We look for "Debug michael@0: // Message.exe" in the same directory as the application. If it michael@0: // exists, we use it, otherwise, we use a regular message box. michael@0: wchar_t prog_name[MAX_PATH]; michael@0: GetModuleFileNameW(NULL, prog_name, MAX_PATH); michael@0: wchar_t* backslash = wcsrchr(prog_name, '\\'); michael@0: if (backslash) michael@0: backslash[1] = 0; michael@0: wcscat_s(prog_name, MAX_PATH, L"debug_message.exe"); michael@0: michael@0: std::wstring cmdline = UTF8ToWide(str); michael@0: if (cmdline.empty()) michael@0: return; michael@0: michael@0: STARTUPINFO startup_info; michael@0: memset(&startup_info, 0, sizeof(startup_info)); michael@0: startup_info.cb = sizeof(startup_info); michael@0: michael@0: PROCESS_INFORMATION process_info; michael@0: if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL, michael@0: NULL, &startup_info, &process_info)) { michael@0: WaitForSingleObject(process_info.hProcess, INFINITE); michael@0: CloseHandle(process_info.hThread); michael@0: CloseHandle(process_info.hProcess); michael@0: } else { michael@0: // debug process broken, let's just do a message box michael@0: MessageBoxW(NULL, &cmdline[0], L"Fatal error", michael@0: MB_OK | MB_ICONHAND | MB_TOPMOST); michael@0: } michael@0: #else michael@0: // We intentionally don't implement a dialog on other platforms. michael@0: // You can just look at stderr. michael@0: #endif michael@0: } michael@0: michael@0: #if defined(OS_WIN) michael@0: LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) { michael@0: } michael@0: michael@0: LogMessage::SaveLastError::~SaveLastError() { michael@0: ::SetLastError(last_error_); michael@0: } michael@0: #endif // defined(OS_WIN) michael@0: michael@0: LogMessage::LogMessage(const char* file, int line, LogSeverity severity, michael@0: int ctr) michael@0: : severity_(severity), file_(file), line_(line) { michael@0: Init(file, line); michael@0: } michael@0: michael@0: LogMessage::LogMessage(const char* file, int line) michael@0: : severity_(LOG_INFO), file_(file), line_(line) { michael@0: Init(file, line); michael@0: } michael@0: michael@0: LogMessage::LogMessage(const char* file, int line, LogSeverity severity) michael@0: : severity_(severity), file_(file), line_(line) { michael@0: Init(file, line); michael@0: } michael@0: michael@0: LogMessage::LogMessage(const char* file, int line, std::string* result) michael@0: : severity_(LOG_FATAL), file_(file), line_(line) { michael@0: Init(file, line); michael@0: stream_ << "Check failed: " << *result; michael@0: delete result; michael@0: } michael@0: michael@0: LogMessage::LogMessage(const char* file, int line, LogSeverity severity, michael@0: std::string* result) michael@0: : severity_(severity), file_(file), line_(line) { michael@0: Init(file, line); michael@0: stream_ << "Check failed: " << *result; michael@0: delete result; michael@0: } michael@0: michael@0: LogMessage::~LogMessage() { michael@0: #if !defined(NDEBUG) && !defined(OS_NACL) michael@0: if (severity_ == LOG_FATAL) { michael@0: // Include a stack trace on a fatal. michael@0: base::debug::StackTrace trace; michael@0: stream_ << std::endl; // Newline to separate from log message. michael@0: trace.OutputToStream(&stream_); michael@0: } michael@0: #endif michael@0: stream_ << std::endl; michael@0: std::string str_newline(stream_.str()); michael@0: michael@0: // Give any log message handler first dibs on the message. michael@0: if (log_message_handler && michael@0: log_message_handler(severity_, file_, line_, michael@0: message_start_, str_newline)) { michael@0: // The handler took care of it, no further processing. michael@0: return; michael@0: } michael@0: michael@0: if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { michael@0: #if defined(OS_WIN) michael@0: OutputDebugStringA(str_newline.c_str()); michael@0: #elif defined(OS_ANDROID) michael@0: android_LogPriority priority = michael@0: (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN; michael@0: switch (severity_) { michael@0: case LOG_INFO: michael@0: priority = ANDROID_LOG_INFO; michael@0: break; michael@0: case LOG_WARNING: michael@0: priority = ANDROID_LOG_WARN; michael@0: break; michael@0: case LOG_ERROR: michael@0: case LOG_ERROR_REPORT: michael@0: priority = ANDROID_LOG_ERROR; michael@0: break; michael@0: case LOG_FATAL: michael@0: priority = ANDROID_LOG_FATAL; michael@0: break; michael@0: } michael@0: __android_log_write(priority, "chromium", str_newline.c_str()); michael@0: #endif michael@0: fprintf(stderr, "%s", str_newline.c_str()); michael@0: fflush(stderr); michael@0: } else if (severity_ >= kAlwaysPrintErrorLevel) { michael@0: // When we're only outputting to a log file, above a certain log level, we michael@0: // should still output to stderr so that we can better detect and diagnose michael@0: // problems with unit tests, especially on the buildbots. michael@0: fprintf(stderr, "%s", str_newline.c_str()); michael@0: fflush(stderr); michael@0: } michael@0: michael@0: // write to log file michael@0: if ((logging_destination & LOG_TO_FILE) != 0) { michael@0: // We can have multiple threads and/or processes, so try to prevent them michael@0: // from clobbering each other's writes. michael@0: // If the client app did not call InitLogging, and the lock has not michael@0: // been created do it now. We do this on demand, but if two threads try michael@0: // to do this at the same time, there will be a race condition to create michael@0: // the lock. This is why InitLogging should be called from the main michael@0: // thread at the beginning of execution. michael@0: LoggingLock::Init(LOCK_LOG_FILE, NULL); michael@0: LoggingLock logging_lock; michael@0: if (InitializeLogFileHandle()) { michael@0: #if defined(OS_WIN) michael@0: SetFilePointer(log_file, 0, 0, SEEK_END); michael@0: DWORD num_written; michael@0: WriteFile(log_file, michael@0: static_cast(str_newline.c_str()), michael@0: static_cast(str_newline.length()), michael@0: &num_written, michael@0: NULL); michael@0: #else michael@0: fprintf(log_file, "%s", str_newline.c_str()); michael@0: fflush(log_file); michael@0: #endif michael@0: } michael@0: } michael@0: michael@0: if (severity_ == LOG_FATAL) { michael@0: // Ensure the first characters of the string are on the stack so they michael@0: // are contained in minidumps for diagnostic purposes. michael@0: char str_stack[1024]; michael@0: str_newline.copy(str_stack, arraysize(str_stack)); michael@0: base::debug::Alias(str_stack); michael@0: michael@0: // display a message or break into the debugger on a fatal error michael@0: if (base::debug::BeingDebugged()) { michael@0: base::debug::BreakDebugger(); michael@0: } else { michael@0: if (log_assert_handler) { michael@0: // make a copy of the string for the handler out of paranoia michael@0: log_assert_handler(std::string(stream_.str())); michael@0: } else { michael@0: // Don't use the string with the newline, get a fresh version to send to michael@0: // the debug message process. We also don't display assertions to the michael@0: // user in release mode. The enduser can't do anything with this michael@0: // information, and displaying message boxes when the application is michael@0: // hosed can cause additional problems. michael@0: #ifndef NDEBUG michael@0: DisplayDebugMessageInDialog(stream_.str()); michael@0: #endif michael@0: // Crash the process to generate a dump. michael@0: base::debug::BreakDebugger(); michael@0: } michael@0: } michael@0: } else if (severity_ == LOG_ERROR_REPORT) { michael@0: // We are here only if the user runs with --enable-dcheck in release mode. michael@0: if (log_report_handler) { michael@0: log_report_handler(std::string(stream_.str())); michael@0: } else { michael@0: DisplayDebugMessageInDialog(stream_.str()); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // writes the common header info to the stream michael@0: void LogMessage::Init(const char* file, int line) { michael@0: base::StringPiece filename(file); michael@0: size_t last_slash_pos = filename.find_last_of("\\/"); michael@0: if (last_slash_pos != base::StringPiece::npos) michael@0: filename.remove_prefix(last_slash_pos + 1); michael@0: michael@0: // TODO(darin): It might be nice if the columns were fixed width. michael@0: michael@0: stream_ << '['; michael@0: if (log_process_id) michael@0: stream_ << CurrentProcessId() << ':'; michael@0: if (log_thread_id) michael@0: stream_ << base::PlatformThread::CurrentId() << ':'; michael@0: if (log_timestamp) { michael@0: time_t t = time(NULL); michael@0: struct tm local_time = {0}; michael@0: #if _MSC_VER >= 1400 michael@0: localtime_s(&local_time, &t); michael@0: #else michael@0: localtime_r(&t, &local_time); michael@0: #endif michael@0: struct tm* tm_time = &local_time; michael@0: stream_ << std::setfill('0') michael@0: << std::setw(2) << 1 + tm_time->tm_mon michael@0: << std::setw(2) << tm_time->tm_mday michael@0: << '/' michael@0: << std::setw(2) << tm_time->tm_hour michael@0: << std::setw(2) << tm_time->tm_min michael@0: << std::setw(2) << tm_time->tm_sec michael@0: << ':'; michael@0: } michael@0: if (log_tickcount) michael@0: stream_ << TickCount() << ':'; michael@0: if (severity_ >= 0) michael@0: stream_ << log_severity_names[severity_]; michael@0: else michael@0: stream_ << "VERBOSE" << -severity_; michael@0: michael@0: stream_ << ":" << filename << "(" << line << ")] "; michael@0: michael@0: message_start_ = stream_.tellp(); michael@0: } michael@0: michael@0: #if defined(OS_WIN) michael@0: // This has already been defined in the header, but defining it again as DWORD michael@0: // ensures that the type used in the header is equivalent to DWORD. If not, michael@0: // the redefinition is a compile error. michael@0: typedef DWORD SystemErrorCode; michael@0: #endif michael@0: michael@0: SystemErrorCode GetLastSystemErrorCode() { michael@0: #if defined(OS_WIN) michael@0: return ::GetLastError(); michael@0: #elif defined(OS_POSIX) michael@0: return errno; michael@0: #else michael@0: #error Not implemented michael@0: #endif michael@0: } michael@0: michael@0: #if defined(OS_WIN) michael@0: Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, michael@0: int line, michael@0: LogSeverity severity, michael@0: SystemErrorCode err, michael@0: const char* module) michael@0: : err_(err), michael@0: module_(module), michael@0: log_message_(file, line, severity) { michael@0: } michael@0: michael@0: Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, michael@0: int line, michael@0: LogSeverity severity, michael@0: SystemErrorCode err) michael@0: : err_(err), michael@0: module_(NULL), michael@0: log_message_(file, line, severity) { michael@0: } michael@0: michael@0: Win32ErrorLogMessage::~Win32ErrorLogMessage() { michael@0: const int error_message_buffer_size = 256; michael@0: char msgbuf[error_message_buffer_size]; michael@0: DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; michael@0: HMODULE hmod; michael@0: if (module_) { michael@0: hmod = GetModuleHandleA(module_); michael@0: if (hmod) { michael@0: flags |= FORMAT_MESSAGE_FROM_HMODULE; michael@0: } else { michael@0: // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL michael@0: // so it will not call GetModuleHandle, so recursive errors are michael@0: // impossible. michael@0: DPLOG(WARNING) << "Couldn't open module " << module_ michael@0: << " for error message query"; michael@0: } michael@0: } else { michael@0: hmod = NULL; michael@0: } michael@0: DWORD len = FormatMessageA(flags, michael@0: hmod, michael@0: err_, michael@0: 0, michael@0: msgbuf, michael@0: sizeof(msgbuf) / sizeof(msgbuf[0]), michael@0: NULL); michael@0: if (len) { michael@0: while ((len > 0) && michael@0: isspace(static_cast(msgbuf[len - 1]))) { michael@0: msgbuf[--len] = 0; michael@0: } michael@0: stream() << ": " << msgbuf; michael@0: } else { michael@0: stream() << ": Error " << GetLastError() << " while retrieving error " michael@0: << err_; michael@0: } michael@0: // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a michael@0: // field) and use Alias in hopes that it makes it into crash dumps. michael@0: DWORD last_error = err_; michael@0: base::debug::Alias(&last_error); michael@0: } michael@0: #elif defined(OS_POSIX) michael@0: ErrnoLogMessage::ErrnoLogMessage(const char* file, michael@0: int line, michael@0: LogSeverity severity, michael@0: SystemErrorCode err) michael@0: : err_(err), michael@0: log_message_(file, line, severity) { michael@0: } michael@0: michael@0: ErrnoLogMessage::~ErrnoLogMessage() { michael@0: stream() << ": " << safe_strerror(err_); michael@0: } michael@0: #endif // OS_WIN michael@0: michael@0: void CloseLogFile() { michael@0: LoggingLock logging_lock; michael@0: CloseLogFileUnlocked(); michael@0: } michael@0: michael@0: void RawLog(int level, const char* message) { michael@0: if (level >= min_log_level) { michael@0: size_t bytes_written = 0; michael@0: const size_t message_len = strlen(message); michael@0: int rv; michael@0: while (bytes_written < message_len) { michael@0: rv = HANDLE_EINTR( michael@0: write(STDERR_FILENO, message + bytes_written, michael@0: message_len - bytes_written)); michael@0: if (rv < 0) { michael@0: // Give up, nothing we can do now. michael@0: break; michael@0: } michael@0: bytes_written += rv; michael@0: } michael@0: michael@0: if (message_len > 0 && message[message_len - 1] != '\n') { michael@0: do { michael@0: rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1)); michael@0: if (rv < 0) { michael@0: // Give up, nothing we can do now. michael@0: break; michael@0: } michael@0: } while (rv != 1); michael@0: } michael@0: } michael@0: michael@0: if (level == LOG_FATAL) michael@0: base::debug::BreakDebugger(); michael@0: } michael@0: michael@0: // This was defined at the beginning of this file. michael@0: #undef write michael@0: michael@0: #if defined(OS_WIN) michael@0: std::wstring GetLogFileFullPath() { michael@0: if (log_file_name) michael@0: return *log_file_name; michael@0: return std::wstring(); michael@0: } michael@0: #endif michael@0: michael@0: } // namespace logging michael@0: michael@0: std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) { michael@0: return out << WideToUTF8(std::wstring(wstr)); michael@0: }