blob: 2658519d89917b25137f0177beeee39a411669bd [file] [log] [blame]
[email protected]f1633932010-08-17 23:05:281// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]b16ef312008-08-19 18:36:235#include "base/logging.h"
[email protected]f6abeba2008-08-08 13:27:286
[email protected]b16ef312008-08-19 18:36:237#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:508#include <io.h>
[email protected]f6abeba2008-08-08 13:27:289#include <windows.h>
10typedef HANDLE FileHandle;
11typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5012// 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
[email protected]052f1b52008-11-06 21:43:0716#elif defined(OS_MACOSX)
[email protected]f6abeba2008-08-08 13:27:2817#include <CoreFoundation/CoreFoundation.h>
18#include <mach/mach.h>
19#include <mach/mach_time.h>
20#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5221#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:0722#include <sys/syscall.h>
23#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5924#endif
25
26#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2027#include <errno.h>
[email protected]166326c62010-08-05 15:50:2328#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2829#include <stdlib.h>
30#include <stdio.h>
31#include <string.h>
32#include <unistd.h>
33#define MAX_PATH PATH_MAX
34typedef FILE* FileHandle;
35typedef pthread_mutex_t* MutexHandle;
36#endif
37
initial.commitd7cae122008-07-26 21:49:3838#include <ctime>
39#include <iomanip>
40#include <cstring>
initial.commitd7cae122008-07-26 21:49:3841#include <algorithm>
[email protected]b16ef312008-08-19 18:36:2342
initial.commitd7cae122008-07-26 21:49:3843#include "base/base_switches.h"
44#include "base/command_line.h"
[email protected]58580352010-10-26 04:07:5045#include "base/debug/debugger.h"
46#include "base/debug/stack_trace.h"
[email protected]e36ddc82009-12-08 04:22:5047#include "base/eintr_wrapper.h"
initial.commitd7cae122008-07-26 21:49:3848#include "base/lock_impl.h"
[email protected]d8617a62009-10-09 23:52:2049#if defined(OS_POSIX)
50#include "base/safe_strerror_posix.h"
51#endif
[email protected]d81baca42010-03-01 13:10:2252#include "base/process_util.h"
[email protected]4bdaceb42008-08-19 13:19:2453#include "base/string_piece.h"
[email protected]047a03f2009-10-07 02:10:2054#include "base/utf_string_conversions.h"
[email protected]99b7c57f2010-09-29 19:26:3655#include "base/vlog.h"
[email protected]52a261f2009-03-03 15:01:1256
initial.commitd7cae122008-07-26 21:49:3857namespace logging {
58
59bool g_enable_dcheck = false;
[email protected]99b7c57f2010-09-29 19:26:3660VlogInfo* g_vlog_info = NULL;
initial.commitd7cae122008-07-26 21:49:3861
62const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]fb62a532009-02-12 01:19:0563 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3864
65int min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3266
67// The default set here for logging_destination will only be used if
68// InitLogging is not called. On Windows, use a file next to the exe;
69// on POSIX platforms, where it may not even be possible to locate the
70// executable on disk, use stderr.
[email protected]4c0040c2008-08-15 01:04:1171#if defined(OS_WIN)
[email protected]fe613522008-08-22 17:09:3472LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
[email protected]4c0040c2008-08-15 01:04:1173#elif defined(OS_POSIX)
[email protected]1d8c2702008-08-19 23:39:3274LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
[email protected]4c0040c2008-08-15 01:04:1175#endif
initial.commitd7cae122008-07-26 21:49:3876
[email protected]a33c9892008-08-25 20:10:3177// For LOG_ERROR and above, always print to stderr.
78const int kAlwaysPrintErrorLevel = LOG_ERROR;
79
[email protected]614e9fa2008-08-11 22:52:5980// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3881// will be lazily initialized to the default value when it is
82// first needed.
[email protected]f6abeba2008-08-08 13:27:2883#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5984typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2885#else
[email protected]614e9fa2008-08-11 22:52:5986typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:2887#endif
[email protected]614e9fa2008-08-11 22:52:5988PathString* log_file_name = NULL;
initial.commitd7cae122008-07-26 21:49:3889
90// this file is lazily opened and the handle may be NULL
[email protected]f6abeba2008-08-08 13:27:2891FileHandle log_file = NULL;
initial.commitd7cae122008-07-26 21:49:3892
93// what should be prepended to each message?
94bool log_process_id = false;
95bool log_thread_id = false;
96bool log_timestamp = true;
97bool log_tickcount = false;
98
[email protected]81e0a852010-08-17 00:38:1299// Should we pop up fatal debug messages in a dialog?
100bool show_error_dialogs = false;
101
initial.commitd7cae122008-07-26 21:49:38102// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05103// the debug message dialog and process termination.
initial.commitd7cae122008-07-26 21:49:38104LogAssertHandlerFunction log_assert_handler = NULL;
[email protected]fb62a532009-02-12 01:19:05105// An report handler override specified by the client to be called instead of
106// the debug message dialog.
107LogReportHandlerFunction log_report_handler = NULL;
[email protected]2b07b8412009-11-25 15:26:34108// A log message handler that gets notified of every log message we process.
109LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38110
[email protected]f6abeba2008-08-08 13:27:28111// Helper functions to wrap platform differences.
112
[email protected]f8588472008-11-05 23:17:24113int32 CurrentProcessId() {
114#if defined(OS_WIN)
115 return GetCurrentProcessId();
116#elif defined(OS_POSIX)
117 return getpid();
118#endif
119}
120
121int32 CurrentThreadId() {
122#if defined(OS_WIN)
123 return GetCurrentThreadId();
124#elif defined(OS_MACOSX)
125 return mach_thread_self();
[email protected]052f1b52008-11-06 21:43:07126#elif defined(OS_LINUX)
127 return syscall(__NR_gettid);
[email protected]e43eddf12009-12-29 00:32:52128#elif defined(OS_FREEBSD)
129 // TODO(BSD): find a better thread ID
130 return reinterpret_cast<int64>(pthread_self());
[email protected]f8588472008-11-05 23:17:24131#endif
132}
133
134uint64 TickCount() {
135#if defined(OS_WIN)
136 return GetTickCount();
137#elif defined(OS_MACOSX)
138 return mach_absolute_time();
[email protected]e43eddf12009-12-29 00:32:52139#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07140 struct timespec ts;
141 clock_gettime(CLOCK_MONOTONIC, &ts);
142
143 uint64 absolute_micro =
144 static_cast<int64>(ts.tv_sec) * 1000000 +
145 static_cast<int64>(ts.tv_nsec) / 1000;
146
147 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24148#endif
149}
150
[email protected]f6abeba2008-08-08 13:27:28151void CloseFile(FileHandle log) {
152#if defined(OS_WIN)
153 CloseHandle(log);
154#else
155 fclose(log);
156#endif
157}
158
[email protected]614e9fa2008-08-11 22:52:59159void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28160#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59161 DeleteFile(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28162#else
[email protected]614e9fa2008-08-11 22:52:59163 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28164#endif
165}
initial.commitd7cae122008-07-26 21:49:38166
[email protected]5f95d532010-10-01 17:16:58167PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55168#if defined(OS_WIN)
169 // On Windows we use the same path as the exe.
170 wchar_t module_name[MAX_PATH];
171 GetModuleFileName(NULL, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58172
173 PathString log_file = module_name;
174 PathString::size_type last_backslash =
175 log_file.rfind('\\', log_file.size());
176 if (last_backslash != PathString::npos)
177 log_file.erase(last_backslash + 1);
178 log_file += L"debug.log";
179 return log_file;
[email protected]5b84fe32010-09-14 22:24:55180#elif defined(OS_POSIX)
181 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58182 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55183#endif
184}
185
186// This class acts as a wrapper for locking the logging files.
187// LoggingLock::Init() should be called from the main thread before any logging
188// is done. Then whenever logging, be sure to have a local LoggingLock
189// instance on the stack. This will ensure that the lock is unlocked upon
190// exiting the frame.
191// LoggingLocks can not be nested.
192class LoggingLock {
193 public:
194 LoggingLock() {
195 LockLogging();
196 }
197
198 ~LoggingLock() {
199 UnlockLogging();
200 }
201
202 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
203 if (initialized)
204 return;
205 lock_log_file = lock_log;
206 if (lock_log_file == LOCK_LOG_FILE) {
207#if defined(OS_WIN)
208 if (!log_mutex) {
209 std::wstring safe_name;
210 if (new_log_file)
211 safe_name = new_log_file;
212 else
[email protected]5f95d532010-10-01 17:16:58213 safe_name = GetDefaultLogFile();
[email protected]5b84fe32010-09-14 22:24:55214 // \ is not a legal character in mutex names so we replace \ with /
215 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
216 std::wstring t(L"Global\\");
217 t.append(safe_name);
218 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
[email protected]5f95d532010-10-01 17:16:58219
220 if (log_mutex == NULL) {
221#if DEBUG
222 // Keep the error code for debugging
223 int error = GetLastError(); // NOLINT
[email protected]58580352010-10-26 04:07:50224 base::debug::BreakDebugger();
[email protected]5f95d532010-10-01 17:16:58225#endif
226 // Return nicely without putting initialized to true.
227 return;
228 }
[email protected]5b84fe32010-09-14 22:24:55229 }
230#endif
231 } else {
232 log_lock = new LockImpl();
233 }
234 initialized = true;
235 }
236
237 private:
238 static void LockLogging() {
239 if (lock_log_file == LOCK_LOG_FILE) {
240#if defined(OS_WIN)
241 ::WaitForSingleObject(log_mutex, INFINITE);
242 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
243 // abort the process here. UI tests might be crashy sometimes,
244 // and aborting the test binary only makes the problem worse.
245 // We also don't use LOG macros because that might lead to an infinite
246 // loop. For more info see http://crbug.com/18028.
247#elif defined(OS_POSIX)
248 pthread_mutex_lock(&log_mutex);
249#endif
250 } else {
251 // use the lock
252 log_lock->Lock();
253 }
254 }
255
256 static void UnlockLogging() {
257 if (lock_log_file == LOCK_LOG_FILE) {
258#if defined(OS_WIN)
259 ReleaseMutex(log_mutex);
260#elif defined(OS_POSIX)
261 pthread_mutex_unlock(&log_mutex);
262#endif
263 } else {
264 log_lock->Unlock();
265 }
266 }
267
268 // The lock is used if log file locking is false. It helps us avoid problems
269 // with multiple threads writing to the log file at the same time. Use
270 // LockImpl directly instead of using Lock, because Lock makes logging calls.
271 static LockImpl* log_lock;
272
273 // When we don't use a lock, we are using a global mutex. We need to do this
274 // because LockFileEx is not thread safe.
275#if defined(OS_WIN)
276 static MutexHandle log_mutex;
277#elif defined(OS_POSIX)
278 static pthread_mutex_t log_mutex;
279#endif
280
281 static bool initialized;
282 static LogLockingState lock_log_file;
283};
284
285// static
286bool LoggingLock::initialized = false;
287// static
288LockImpl* LoggingLock::log_lock = NULL;
289// static
290LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
291
292#if defined(OS_WIN)
293// static
294MutexHandle LoggingLock::log_mutex = NULL;
295#elif defined(OS_POSIX)
296pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
297#endif
298
initial.commitd7cae122008-07-26 21:49:38299// Called by logging functions to ensure that debug_file is initialized
300// and can be used for writing. Returns false if the file could not be
301// initialized. debug_file will be NULL in this case.
302bool InitializeLogFileHandle() {
303 if (log_file)
304 return true;
305
[email protected]614e9fa2008-08-11 22:52:59306 if (!log_file_name) {
307 // Nobody has called InitLogging to specify a debug log file, so here we
308 // initialize the log file name to a default.
[email protected]5f95d532010-10-01 17:16:58309 log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38310 }
311
[email protected]1d8c2702008-08-19 23:39:32312 if (logging_destination == LOG_ONLY_TO_FILE ||
313 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
[email protected]614e9fa2008-08-11 22:52:59314#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32315 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38316 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
317 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
318 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32319 // try the current directory
320 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
321 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
322 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
323 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
324 log_file = NULL;
325 return false;
326 }
initial.commitd7cae122008-07-26 21:49:38327 }
[email protected]1d8c2702008-08-19 23:39:32328 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11329#elif defined(OS_POSIX)
330 log_file = fopen(log_file_name->c_str(), "a");
331 if (log_file == NULL)
332 return false;
[email protected]f6abeba2008-08-08 13:27:28333#endif
[email protected]1d8c2702008-08-19 23:39:32334 }
335
initial.commitd7cae122008-07-26 21:49:38336 return true;
337}
338
[email protected]c7d5da992010-10-28 00:20:21339bool BaseInitLoggingImpl(const PathChar* new_log_file,
[email protected]ff3d0c32010-08-23 19:57:46340 LoggingDestination logging_dest,
341 LogLockingState lock_log,
342 OldFileDeletionState delete_old) {
[email protected]99b7c57f2010-09-29 19:26:36343 CommandLine* command_line = CommandLine::ForCurrentProcess();
[email protected]bb975362009-01-21 01:00:22344 g_enable_dcheck =
[email protected]99b7c57f2010-09-29 19:26:36345 command_line->HasSwitch(switches::kEnableDCHECK);
346 delete g_vlog_info;
347 g_vlog_info = NULL;
348 // Don't bother initializing g_vlog_info unless we use one of the
349 // vlog switches.
350 if (command_line->HasSwitch(switches::kV) ||
351 command_line->HasSwitch(switches::kVModule)) {
352 g_vlog_info =
353 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49354 command_line->GetSwitchValueASCII(switches::kVModule),
355 &min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36356 }
357
[email protected]5b84fe32010-09-14 22:24:55358 LoggingLock::Init(lock_log, new_log_file);
359
360 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38361
362 if (log_file) {
363 // calling InitLogging twice or after some log call has already opened the
364 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28365 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38366 log_file = NULL;
367 }
368
initial.commitd7cae122008-07-26 21:49:38369 logging_destination = logging_dest;
370
371 // ignore file options if logging is disabled or only to system
372 if (logging_destination == LOG_NONE ||
373 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
[email protected]c7d5da992010-10-28 00:20:21374 return true;
initial.commitd7cae122008-07-26 21:49:38375
[email protected]614e9fa2008-08-11 22:52:59376 if (!log_file_name)
377 log_file_name = new PathString();
378 *log_file_name = new_log_file;
initial.commitd7cae122008-07-26 21:49:38379 if (delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59380 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38381
[email protected]c7d5da992010-10-28 00:20:21382 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38383}
384
385void SetMinLogLevel(int level) {
[email protected]deba0ff2010-11-03 05:30:14386 min_log_level = std::min(LOG_ERROR_REPORT, level);
initial.commitd7cae122008-07-26 21:49:38387}
388
389int GetMinLogLevel() {
390 return min_log_level;
391}
392
[email protected]162ac0f2010-11-04 15:50:49393int GetVlogVerbosity() {
394 return std::max(-1, LOG_INFO - GetMinLogLevel());
395}
396
[email protected]99b7c57f2010-09-29 19:26:36397int GetVlogLevelHelper(const char* file, size_t N) {
398 DCHECK_GT(N, 0U);
399 return g_vlog_info ?
400 g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49401 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36402}
403
initial.commitd7cae122008-07-26 21:49:38404void SetLogItems(bool enable_process_id, bool enable_thread_id,
405 bool enable_timestamp, bool enable_tickcount) {
406 log_process_id = enable_process_id;
407 log_thread_id = enable_thread_id;
408 log_timestamp = enable_timestamp;
409 log_tickcount = enable_tickcount;
410}
411
[email protected]81e0a852010-08-17 00:38:12412void SetShowErrorDialogs(bool enable_dialogs) {
413 show_error_dialogs = enable_dialogs;
414}
415
initial.commitd7cae122008-07-26 21:49:38416void SetLogAssertHandler(LogAssertHandlerFunction handler) {
417 log_assert_handler = handler;
418}
419
[email protected]fb62a532009-02-12 01:19:05420void SetLogReportHandler(LogReportHandlerFunction handler) {
421 log_report_handler = handler;
422}
423
[email protected]2b07b8412009-11-25 15:26:34424void SetLogMessageHandler(LogMessageHandlerFunction handler) {
425 log_message_handler = handler;
426}
427
[email protected]64e5cc02010-11-03 19:20:27428LogMessageHandlerFunction GetLogMessageHandler() {
429 return log_message_handler;
430}
431
[email protected]6d445d32010-09-30 19:10:03432// MSVC doesn't like complex extern templates and DLLs.
433#if !defined(COMPILER_MSVC)
434// Explicit instantiations for commonly used comparisons.
435template std::string* MakeCheckOpString<int, int>(
436 const int&, const int&, const char* names);
437template std::string* MakeCheckOpString<unsigned long, unsigned long>(
438 const unsigned long&, const unsigned long&, const char* names);
439template std::string* MakeCheckOpString<unsigned long, unsigned int>(
440 const unsigned long&, const unsigned int&, const char* names);
441template std::string* MakeCheckOpString<unsigned int, unsigned long>(
442 const unsigned int&, const unsigned long&, const char* names);
443template std::string* MakeCheckOpString<std::string, std::string>(
444 const std::string&, const std::string&, const char* name);
445#endif
[email protected]2b07b8412009-11-25 15:26:34446
[email protected]d81baca42010-03-01 13:10:22447// Displays a message box to the user with the error message in it.
448// Used for fatal messages, where we close the app simultaneously.
449void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38450 if (str.empty())
451 return;
452
[email protected]81e0a852010-08-17 00:38:12453 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44454 return;
455
[email protected]f6abeba2008-08-08 13:27:28456#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22457 // For Windows programs, it's possible that the message loop is
458 // messed up on a fatal error, and creating a MessageBox will cause
459 // that message loop to be run. Instead, we try to spawn another
460 // process that displays its command line. We look for "Debug
461 // Message.exe" in the same directory as the application. If it
462 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38463 wchar_t prog_name[MAX_PATH];
464 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
465 wchar_t* backslash = wcsrchr(prog_name, '\\');
466 if (backslash)
467 backslash[1] = 0;
468 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
469
[email protected]047a03f2009-10-07 02:10:20470 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02471 if (cmdline.empty())
472 return;
initial.commitd7cae122008-07-26 21:49:38473
474 STARTUPINFO startup_info;
475 memset(&startup_info, 0, sizeof(startup_info));
476 startup_info.cb = sizeof(startup_info);
477
478 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02479 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38480 NULL, &startup_info, &process_info)) {
481 WaitForSingleObject(process_info.hProcess, INFINITE);
482 CloseHandle(process_info.hThread);
483 CloseHandle(process_info.hProcess);
484 } else {
485 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02486 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38487 MB_OK | MB_ICONHAND | MB_TOPMOST);
488 }
[email protected]81e0a852010-08-17 00:38:12489#elif defined(USE_X11) && !defined(OS_CHROMEOS)
[email protected]d81baca42010-03-01 13:10:22490 // Shell out to xmessage, which behaves like debug_message.exe, but is
491 // way more retro. We could use zenity/kdialog but then we're starting
492 // to get into needing to check the desktop env and this dialog should
493 // only be coming up in Very Bad situations.
494 std::vector<std::string> argv;
495 argv.push_back("xmessage");
496 argv.push_back(str);
497 base::LaunchApp(argv, base::file_handle_mapping_vector(), true /* wait */,
498 NULL);
[email protected]f6abeba2008-08-08 13:27:28499#else
[email protected]d81baca42010-03-01 13:10:22500 // http://code.google.com/p/chromium/issues/detail?id=37026
501 NOTIMPLEMENTED();
[email protected]f6abeba2008-08-08 13:27:28502#endif
initial.commitd7cae122008-07-26 21:49:38503}
504
[email protected]3f85caa2009-04-14 16:52:11505#if defined(OS_WIN)
506LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
507}
508
509LogMessage::SaveLastError::~SaveLastError() {
510 ::SetLastError(last_error_);
511}
512#endif // defined(OS_WIN)
513
initial.commitd7cae122008-07-26 21:49:38514LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
515 int ctr)
[email protected]162ac0f2010-11-04 15:50:49516 : severity_(severity), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38517 Init(file, line);
518}
519
520LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
[email protected]162ac0f2010-11-04 15:50:49521 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38522 Init(file, line);
523 stream_ << "Check failed: " << (*result.str_);
524}
525
[email protected]fb62a532009-02-12 01:19:05526LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
527 const CheckOpString& result)
[email protected]162ac0f2010-11-04 15:50:49528 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05529 Init(file, line);
530 stream_ << "Check failed: " << (*result.str_);
531}
532
initial.commitd7cae122008-07-26 21:49:38533LogMessage::LogMessage(const char* file, int line)
[email protected]162ac0f2010-11-04 15:50:49534 : severity_(LOG_INFO), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38535 Init(file, line);
536}
537
538LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
[email protected]162ac0f2010-11-04 15:50:49539 : severity_(severity), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38540 Init(file, line);
541}
542
543// writes the common header info to the stream
544void LogMessage::Init(const char* file, int line) {
[email protected]41703f72010-10-29 00:34:27545 base::StringPiece filename(file);
546 size_t last_slash_pos = filename.find_last_of("\\/");
547 if (last_slash_pos != base::StringPiece::npos)
548 filename.remove_prefix(last_slash_pos + 1);
initial.commitd7cae122008-07-26 21:49:38549
550 // TODO(darin): It might be nice if the columns were fixed width.
551
552 stream_ << '[';
553 if (log_process_id)
[email protected]f8588472008-11-05 23:17:24554 stream_ << CurrentProcessId() << ':';
initial.commitd7cae122008-07-26 21:49:38555 if (log_thread_id)
[email protected]f8588472008-11-05 23:17:24556 stream_ << CurrentThreadId() << ':';
initial.commitd7cae122008-07-26 21:49:38557 if (log_timestamp) {
[email protected]defcd8f32009-05-13 00:03:43558 time_t t = time(NULL);
initial.commitd7cae122008-07-26 21:49:38559 struct tm local_time = {0};
[email protected]defcd8f32009-05-13 00:03:43560#if _MSC_VER >= 1400
initial.commitd7cae122008-07-26 21:49:38561 localtime_s(&local_time, &t);
initial.commitd7cae122008-07-26 21:49:38562#else
[email protected]defcd8f32009-05-13 00:03:43563 localtime_r(&t, &local_time);
initial.commitd7cae122008-07-26 21:49:38564#endif
[email protected]defcd8f32009-05-13 00:03:43565 struct tm* tm_time = &local_time;
initial.commitd7cae122008-07-26 21:49:38566 stream_ << std::setfill('0')
567 << std::setw(2) << 1 + tm_time->tm_mon
568 << std::setw(2) << tm_time->tm_mday
569 << '/'
570 << std::setw(2) << tm_time->tm_hour
571 << std::setw(2) << tm_time->tm_min
572 << std::setw(2) << tm_time->tm_sec
573 << ':';
574 }
575 if (log_tickcount)
[email protected]f8588472008-11-05 23:17:24576 stream_ << TickCount() << ':';
[email protected]162ac0f2010-11-04 15:50:49577 if (severity_ >= 0)
578 stream_ << log_severity_names[severity_];
579 else
580 stream_ << "VERBOSE" << -severity_;
581
582 stream_ << ":" << file << "(" << line << ")] ";
initial.commitd7cae122008-07-26 21:49:38583
584 message_start_ = stream_.tellp();
585}
586
587LogMessage::~LogMessage() {
[email protected]521b0c42010-10-01 23:02:36588 // The macros in logging.h should already avoid creating LogMessages
589 // when this holds, but it's possible that users create LogMessages
590 // directly (e.g., using LOG_STREAM() directly).
initial.commitd7cae122008-07-26 21:49:38591 if (severity_ < min_log_level)
592 return;
593
[email protected]d1ccc35a2010-03-24 05:03:24594#ifndef NDEBUG
595 if (severity_ == LOG_FATAL) {
596 // Include a stack trace on a fatal.
[email protected]58580352010-10-26 04:07:50597 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24598 stream_ << std::endl; // Newline to separate from log message.
599 trace.OutputToStream(&stream_);
600 }
[email protected]1d8c2702008-08-19 23:39:32601#endif
[email protected]d1ccc35a2010-03-24 05:03:24602 stream_ << std::endl;
603 std::string str_newline(stream_.str());
604
[email protected]2b07b8412009-11-25 15:26:34605 // Give any log message handler first dibs on the message.
[email protected]162ac0f2010-11-04 15:50:49606 if (log_message_handler && log_message_handler(severity_, file_, line_,
607 message_start_, str_newline)) {
608 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34609 return;
[email protected]162ac0f2010-11-04 15:50:49610 }
initial.commitd7cae122008-07-26 21:49:38611
initial.commitd7cae122008-07-26 21:49:38612 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
[email protected]f6abeba2008-08-08 13:27:28613 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
614#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38615 OutputDebugStringA(str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18616#endif
[email protected]469006c2010-09-24 15:43:06617 fprintf(stderr, "%s", str_newline.c_str());
618 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31619 } else if (severity_ >= kAlwaysPrintErrorLevel) {
620 // When we're only outputting to a log file, above a certain log level, we
621 // should still output to stderr so that we can better detect and diagnose
622 // problems with unit tests, especially on the buildbots.
623 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02624 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28625 }
[email protected]52a261f2009-03-03 15:01:12626
[email protected]5b84fe32010-09-14 22:24:55627 // We can have multiple threads and/or processes, so try to prevent them
628 // from clobbering each other's writes.
629 // If the client app did not call InitLogging, and the lock has not
630 // been created do it now. We do this on demand, but if two threads try
631 // to do this at the same time, there will be a race condition to create
632 // the lock. This is why InitLogging should be called from the main
633 // thread at the beginning of execution.
634 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38635 // write to log file
636 if (logging_destination != LOG_NONE &&
[email protected]5b84fe32010-09-14 22:24:55637 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
638 LoggingLock logging_lock;
639 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28640#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55641 SetFilePointer(log_file, 0, 0, SEEK_END);
642 DWORD num_written;
643 WriteFile(log_file,
644 static_cast<const void*>(str_newline.c_str()),
645 static_cast<DWORD>(str_newline.length()),
646 &num_written,
647 NULL);
[email protected]cba21962010-08-31 22:35:55648#else
[email protected]5b84fe32010-09-14 22:24:55649 fprintf(log_file, "%s", str_newline.c_str());
650 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55651#endif
initial.commitd7cae122008-07-26 21:49:38652 }
653 }
654
655 if (severity_ == LOG_FATAL) {
656 // display a message or break into the debugger on a fatal error
[email protected]58580352010-10-26 04:07:50657 if (base::debug::BeingDebugged()) {
658 base::debug::BreakDebugger();
[email protected]1ffe08c12008-08-13 11:15:11659 } else {
initial.commitd7cae122008-07-26 21:49:38660 if (log_assert_handler) {
661 // make a copy of the string for the handler out of paranoia
662 log_assert_handler(std::string(stream_.str()));
663 } else {
[email protected]4d5901272008-11-06 00:33:50664 // Don't use the string with the newline, get a fresh version to send to
665 // the debug message process. We also don't display assertions to the
666 // user in release mode. The enduser can't do anything with this
667 // information, and displaying message boxes when the application is
668 // hosed can cause additional problems.
669#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22670 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50671#endif
initial.commitd7cae122008-07-26 21:49:38672 // Crash the process to generate a dump.
[email protected]58580352010-10-26 04:07:50673 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38674 }
675 }
[email protected]fb62a532009-02-12 01:19:05676 } else if (severity_ == LOG_ERROR_REPORT) {
677 // We are here only if the user runs with --enable-dcheck in release mode.
678 if (log_report_handler) {
679 log_report_handler(std::string(stream_.str()));
680 } else {
[email protected]d81baca42010-03-01 13:10:22681 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05682 }
initial.commitd7cae122008-07-26 21:49:38683 }
684}
685
[email protected]d8617a62009-10-09 23:52:20686#if defined(OS_WIN)
687// This has already been defined in the header, but defining it again as DWORD
688// ensures that the type used in the header is equivalent to DWORD. If not,
689// the redefinition is a compile error.
690typedef DWORD SystemErrorCode;
691#endif
692
693SystemErrorCode GetLastSystemErrorCode() {
694#if defined(OS_WIN)
695 return ::GetLastError();
696#elif defined(OS_POSIX)
697 return errno;
698#else
699#error Not implemented
700#endif
701}
702
703#if defined(OS_WIN)
704Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
705 int line,
706 LogSeverity severity,
707 SystemErrorCode err,
708 const char* module)
709 : err_(err),
710 module_(module),
711 log_message_(file, line, severity) {
712}
713
714Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
715 int line,
716 LogSeverity severity,
717 SystemErrorCode err)
718 : err_(err),
719 module_(NULL),
720 log_message_(file, line, severity) {
721}
722
723Win32ErrorLogMessage::~Win32ErrorLogMessage() {
724 const int error_message_buffer_size = 256;
725 char msgbuf[error_message_buffer_size];
[email protected]6ac3df52010-10-20 01:33:32726 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
[email protected]d8617a62009-10-09 23:52:20727 HMODULE hmod;
728 if (module_) {
729 hmod = GetModuleHandleA(module_);
730 if (hmod) {
731 flags |= FORMAT_MESSAGE_FROM_HMODULE;
732 } else {
733 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
734 // so it will not call GetModuleHandle, so recursive errors are
735 // impossible.
736 DPLOG(WARNING) << "Couldn't open module " << module_
737 << " for error message query";
738 }
739 } else {
740 hmod = NULL;
741 }
742 DWORD len = FormatMessageA(flags,
743 hmod,
744 err_,
[email protected]6ac3df52010-10-20 01:33:32745 0,
[email protected]d8617a62009-10-09 23:52:20746 msgbuf,
747 sizeof(msgbuf) / sizeof(msgbuf[0]),
748 NULL);
749 if (len) {
750 while ((len > 0) &&
751 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
752 msgbuf[--len] = 0;
753 }
754 stream() << ": " << msgbuf;
755 } else {
756 stream() << ": Error " << GetLastError() << " while retrieving error "
757 << err_;
758 }
759}
760#elif defined(OS_POSIX)
761ErrnoLogMessage::ErrnoLogMessage(const char* file,
762 int line,
763 LogSeverity severity,
764 SystemErrorCode err)
765 : err_(err),
766 log_message_(file, line, severity) {
767}
768
769ErrnoLogMessage::~ErrnoLogMessage() {
770 stream() << ": " << safe_strerror(err_);
771}
772#endif // OS_WIN
773
initial.commitd7cae122008-07-26 21:49:38774void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55775 LoggingLock logging_lock;
776
initial.commitd7cae122008-07-26 21:49:38777 if (!log_file)
778 return;
779
[email protected]f6abeba2008-08-08 13:27:28780 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38781 log_file = NULL;
782}
783
[email protected]e36ddc82009-12-08 04:22:50784void RawLog(int level, const char* message) {
785 if (level >= min_log_level) {
786 size_t bytes_written = 0;
787 const size_t message_len = strlen(message);
788 int rv;
789 while (bytes_written < message_len) {
790 rv = HANDLE_EINTR(
791 write(STDERR_FILENO, message + bytes_written,
792 message_len - bytes_written));
793 if (rv < 0) {
794 // Give up, nothing we can do now.
795 break;
796 }
797 bytes_written += rv;
798 }
799
800 if (message_len > 0 && message[message_len - 1] != '\n') {
801 do {
802 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
803 if (rv < 0) {
804 // Give up, nothing we can do now.
805 break;
806 }
807 } while (rv != 1);
808 }
809 }
810
811 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50812 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50813}
814
[email protected]96fd0032009-04-24 00:13:08815} // namespace logging
initial.commitd7cae122008-07-26 21:49:38816
817std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20818 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38819}