blob: e5c8c8df6dc7e1b84eaaa4e7193cfc789deb4dfc [file] [log] [blame]
[email protected]1f88b5162011-04-01 00:02:291// Copyright (c) 2011 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 <mach/mach.h>
18#include <mach/mach_time.h>
19#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5220#elif defined(OS_POSIX)
[email protected]19ea84ca2010-11-12 08:37:0821#if defined(OS_NACL)
22#include <sys/nacl_syscalls.h>
23#include <sys/time.h> // timespec doesn't seem to be in <time.h>
24#else
[email protected]052f1b52008-11-06 21:43:0725#include <sys/syscall.h>
[email protected]19ea84ca2010-11-12 08:37:0826#endif
[email protected]052f1b52008-11-06 21:43:0727#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5928#endif
29
30#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2031#include <errno.h>
[email protected]166326c62010-08-05 15:50:2332#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2833#include <stdlib.h>
34#include <stdio.h>
35#include <string.h>
36#include <unistd.h>
37#define MAX_PATH PATH_MAX
38typedef FILE* FileHandle;
39typedef pthread_mutex_t* MutexHandle;
40#endif
41
[email protected]1f88b5162011-04-01 00:02:2942#include <algorithm>
43#include <cstring>
initial.commitd7cae122008-07-26 21:49:3844#include <ctime>
45#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2946#include <ostream>
[email protected]b16ef312008-08-19 18:36:2347
initial.commitd7cae122008-07-26 21:49:3848#include "base/base_switches.h"
49#include "base/command_line.h"
[email protected]58580352010-10-26 04:07:5050#include "base/debug/debugger.h"
51#include "base/debug/stack_trace.h"
[email protected]e36ddc82009-12-08 04:22:5052#include "base/eintr_wrapper.h"
[email protected]4bdaceb42008-08-19 13:19:2453#include "base/string_piece.h"
[email protected]bc581a682011-01-01 23:16:2054#include "base/synchronization/lock_impl.h"
[email protected]047a03f2009-10-07 02:10:2055#include "base/utf_string_conversions.h"
[email protected]99b7c57f2010-09-29 19:26:3656#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0457#if defined(OS_POSIX)
58#include "base/safe_strerror_posix.h"
59#endif
[email protected]52a261f2009-03-03 15:01:1260
initial.commitd7cae122008-07-26 21:49:3861namespace logging {
62
[email protected]7c10f7552011-01-11 01:03:3663DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
[email protected]99b7c57f2010-09-29 19:26:3664VlogInfo* g_vlog_info = NULL;
initial.commitd7cae122008-07-26 21:49:3865
66const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]fb62a532009-02-12 01:19:0567 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3868
69int min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3270
71// The default set here for logging_destination will only be used if
72// InitLogging is not called. On Windows, use a file next to the exe;
73// on POSIX platforms, where it may not even be possible to locate the
74// executable on disk, use stderr.
[email protected]4c0040c2008-08-15 01:04:1175#if defined(OS_WIN)
[email protected]fe613522008-08-22 17:09:3476LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
[email protected]4c0040c2008-08-15 01:04:1177#elif defined(OS_POSIX)
[email protected]1d8c2702008-08-19 23:39:3278LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
[email protected]4c0040c2008-08-15 01:04:1179#endif
initial.commitd7cae122008-07-26 21:49:3880
[email protected]a33c9892008-08-25 20:10:3181// For LOG_ERROR and above, always print to stderr.
82const int kAlwaysPrintErrorLevel = LOG_ERROR;
83
[email protected]614e9fa2008-08-11 22:52:5984// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3885// will be lazily initialized to the default value when it is
86// first needed.
[email protected]f6abeba2008-08-08 13:27:2887#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5988typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2889#else
[email protected]614e9fa2008-08-11 22:52:5990typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:2891#endif
[email protected]614e9fa2008-08-11 22:52:5992PathString* log_file_name = NULL;
initial.commitd7cae122008-07-26 21:49:3893
94// this file is lazily opened and the handle may be NULL
[email protected]f6abeba2008-08-08 13:27:2895FileHandle log_file = NULL;
initial.commitd7cae122008-07-26 21:49:3896
97// what should be prepended to each message?
98bool log_process_id = false;
99bool log_thread_id = false;
100bool log_timestamp = true;
101bool log_tickcount = false;
102
[email protected]81e0a852010-08-17 00:38:12103// Should we pop up fatal debug messages in a dialog?
104bool show_error_dialogs = false;
105
initial.commitd7cae122008-07-26 21:49:38106// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05107// the debug message dialog and process termination.
initial.commitd7cae122008-07-26 21:49:38108LogAssertHandlerFunction log_assert_handler = NULL;
[email protected]fb62a532009-02-12 01:19:05109// An report handler override specified by the client to be called instead of
110// the debug message dialog.
111LogReportHandlerFunction log_report_handler = NULL;
[email protected]2b07b8412009-11-25 15:26:34112// A log message handler that gets notified of every log message we process.
113LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38114
[email protected]f6abeba2008-08-08 13:27:28115// Helper functions to wrap platform differences.
116
[email protected]f8588472008-11-05 23:17:24117int32 CurrentProcessId() {
118#if defined(OS_WIN)
119 return GetCurrentProcessId();
120#elif defined(OS_POSIX)
121 return getpid();
122#endif
123}
124
125int32 CurrentThreadId() {
126#if defined(OS_WIN)
127 return GetCurrentThreadId();
128#elif defined(OS_MACOSX)
129 return mach_thread_self();
[email protected]052f1b52008-11-06 21:43:07130#elif defined(OS_LINUX)
131 return syscall(__NR_gettid);
[email protected]e43eddf12009-12-29 00:32:52132#elif defined(OS_FREEBSD)
133 // TODO(BSD): find a better thread ID
134 return reinterpret_cast<int64>(pthread_self());
[email protected]19ea84ca2010-11-12 08:37:08135#elif defined(OS_NACL)
136 return pthread_self();
[email protected]f8588472008-11-05 23:17:24137#endif
138}
139
140uint64 TickCount() {
141#if defined(OS_WIN)
142 return GetTickCount();
143#elif defined(OS_MACOSX)
144 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08145#elif defined(OS_NACL)
146 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
147 // So we have to use clock() for now.
148 return clock();
[email protected]e43eddf12009-12-29 00:32:52149#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07150 struct timespec ts;
151 clock_gettime(CLOCK_MONOTONIC, &ts);
152
153 uint64 absolute_micro =
154 static_cast<int64>(ts.tv_sec) * 1000000 +
155 static_cast<int64>(ts.tv_nsec) / 1000;
156
157 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24158#endif
159}
160
[email protected]f6abeba2008-08-08 13:27:28161void CloseFile(FileHandle log) {
162#if defined(OS_WIN)
163 CloseHandle(log);
164#else
165 fclose(log);
166#endif
167}
168
[email protected]614e9fa2008-08-11 22:52:59169void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28170#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59171 DeleteFile(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28172#else
[email protected]614e9fa2008-08-11 22:52:59173 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28174#endif
175}
initial.commitd7cae122008-07-26 21:49:38176
[email protected]5f95d532010-10-01 17:16:58177PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55178#if defined(OS_WIN)
179 // On Windows we use the same path as the exe.
180 wchar_t module_name[MAX_PATH];
181 GetModuleFileName(NULL, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58182
183 PathString log_file = module_name;
184 PathString::size_type last_backslash =
185 log_file.rfind('\\', log_file.size());
186 if (last_backslash != PathString::npos)
187 log_file.erase(last_backslash + 1);
188 log_file += L"debug.log";
189 return log_file;
[email protected]5b84fe32010-09-14 22:24:55190#elif defined(OS_POSIX)
191 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58192 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55193#endif
194}
195
196// This class acts as a wrapper for locking the logging files.
197// LoggingLock::Init() should be called from the main thread before any logging
198// is done. Then whenever logging, be sure to have a local LoggingLock
199// instance on the stack. This will ensure that the lock is unlocked upon
200// exiting the frame.
201// LoggingLocks can not be nested.
202class LoggingLock {
203 public:
204 LoggingLock() {
205 LockLogging();
206 }
207
208 ~LoggingLock() {
209 UnlockLogging();
210 }
211
212 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
213 if (initialized)
214 return;
215 lock_log_file = lock_log;
216 if (lock_log_file == LOCK_LOG_FILE) {
217#if defined(OS_WIN)
218 if (!log_mutex) {
219 std::wstring safe_name;
220 if (new_log_file)
221 safe_name = new_log_file;
222 else
[email protected]5f95d532010-10-01 17:16:58223 safe_name = GetDefaultLogFile();
[email protected]5b84fe32010-09-14 22:24:55224 // \ is not a legal character in mutex names so we replace \ with /
225 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
226 std::wstring t(L"Global\\");
227 t.append(safe_name);
228 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
[email protected]5f95d532010-10-01 17:16:58229
230 if (log_mutex == NULL) {
231#if DEBUG
232 // Keep the error code for debugging
233 int error = GetLastError(); // NOLINT
[email protected]58580352010-10-26 04:07:50234 base::debug::BreakDebugger();
[email protected]5f95d532010-10-01 17:16:58235#endif
236 // Return nicely without putting initialized to true.
237 return;
238 }
[email protected]5b84fe32010-09-14 22:24:55239 }
240#endif
241 } else {
[email protected]bc581a682011-01-01 23:16:20242 log_lock = new base::internal::LockImpl();
[email protected]5b84fe32010-09-14 22:24:55243 }
244 initialized = true;
245 }
246
247 private:
248 static void LockLogging() {
249 if (lock_log_file == LOCK_LOG_FILE) {
250#if defined(OS_WIN)
251 ::WaitForSingleObject(log_mutex, INFINITE);
252 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
253 // abort the process here. UI tests might be crashy sometimes,
254 // and aborting the test binary only makes the problem worse.
255 // We also don't use LOG macros because that might lead to an infinite
256 // loop. For more info see http://crbug.com/18028.
257#elif defined(OS_POSIX)
258 pthread_mutex_lock(&log_mutex);
259#endif
260 } else {
261 // use the lock
262 log_lock->Lock();
263 }
264 }
265
266 static void UnlockLogging() {
267 if (lock_log_file == LOCK_LOG_FILE) {
268#if defined(OS_WIN)
269 ReleaseMutex(log_mutex);
270#elif defined(OS_POSIX)
271 pthread_mutex_unlock(&log_mutex);
272#endif
273 } else {
274 log_lock->Unlock();
275 }
276 }
277
278 // The lock is used if log file locking is false. It helps us avoid problems
279 // with multiple threads writing to the log file at the same time. Use
280 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20281 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55282
283 // When we don't use a lock, we are using a global mutex. We need to do this
284 // because LockFileEx is not thread safe.
285#if defined(OS_WIN)
286 static MutexHandle log_mutex;
287#elif defined(OS_POSIX)
288 static pthread_mutex_t log_mutex;
289#endif
290
291 static bool initialized;
292 static LogLockingState lock_log_file;
293};
294
295// static
296bool LoggingLock::initialized = false;
297// static
[email protected]bc581a682011-01-01 23:16:20298base::internal::LockImpl* LoggingLock::log_lock = NULL;
[email protected]5b84fe32010-09-14 22:24:55299// static
300LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
301
302#if defined(OS_WIN)
303// static
304MutexHandle LoggingLock::log_mutex = NULL;
305#elif defined(OS_POSIX)
306pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
307#endif
308
initial.commitd7cae122008-07-26 21:49:38309// Called by logging functions to ensure that debug_file is initialized
310// and can be used for writing. Returns false if the file could not be
311// initialized. debug_file will be NULL in this case.
312bool InitializeLogFileHandle() {
313 if (log_file)
314 return true;
315
[email protected]614e9fa2008-08-11 22:52:59316 if (!log_file_name) {
317 // Nobody has called InitLogging to specify a debug log file, so here we
318 // initialize the log file name to a default.
[email protected]5f95d532010-10-01 17:16:58319 log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38320 }
321
[email protected]1d8c2702008-08-19 23:39:32322 if (logging_destination == LOG_ONLY_TO_FILE ||
323 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
[email protected]614e9fa2008-08-11 22:52:59324#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32325 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38326 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
327 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
328 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32329 // try the current directory
330 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
331 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
332 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
333 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
334 log_file = NULL;
335 return false;
336 }
initial.commitd7cae122008-07-26 21:49:38337 }
[email protected]1d8c2702008-08-19 23:39:32338 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11339#elif defined(OS_POSIX)
340 log_file = fopen(log_file_name->c_str(), "a");
341 if (log_file == NULL)
342 return false;
[email protected]f6abeba2008-08-08 13:27:28343#endif
[email protected]1d8c2702008-08-19 23:39:32344 }
345
initial.commitd7cae122008-07-26 21:49:38346 return true;
347}
348
[email protected]c7d5da992010-10-28 00:20:21349bool BaseInitLoggingImpl(const PathChar* new_log_file,
[email protected]ff3d0c32010-08-23 19:57:46350 LoggingDestination logging_dest,
351 LogLockingState lock_log,
[email protected]7c10f7552011-01-11 01:03:36352 OldFileDeletionState delete_old,
353 DcheckState dcheck_state) {
[email protected]99b7c57f2010-09-29 19:26:36354 CommandLine* command_line = CommandLine::ForCurrentProcess();
[email protected]7c10f7552011-01-11 01:03:36355 g_dcheck_state = dcheck_state;
[email protected]99b7c57f2010-09-29 19:26:36356 delete g_vlog_info;
357 g_vlog_info = NULL;
358 // Don't bother initializing g_vlog_info unless we use one of the
359 // vlog switches.
360 if (command_line->HasSwitch(switches::kV) ||
361 command_line->HasSwitch(switches::kVModule)) {
362 g_vlog_info =
363 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49364 command_line->GetSwitchValueASCII(switches::kVModule),
365 &min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36366 }
367
[email protected]5b84fe32010-09-14 22:24:55368 LoggingLock::Init(lock_log, new_log_file);
369
370 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38371
372 if (log_file) {
373 // calling InitLogging twice or after some log call has already opened the
374 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28375 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38376 log_file = NULL;
377 }
378
initial.commitd7cae122008-07-26 21:49:38379 logging_destination = logging_dest;
380
381 // ignore file options if logging is disabled or only to system
382 if (logging_destination == LOG_NONE ||
383 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
[email protected]c7d5da992010-10-28 00:20:21384 return true;
initial.commitd7cae122008-07-26 21:49:38385
[email protected]614e9fa2008-08-11 22:52:59386 if (!log_file_name)
387 log_file_name = new PathString();
388 *log_file_name = new_log_file;
initial.commitd7cae122008-07-26 21:49:38389 if (delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59390 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38391
[email protected]c7d5da992010-10-28 00:20:21392 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38393}
394
395void SetMinLogLevel(int level) {
[email protected]deba0ff2010-11-03 05:30:14396 min_log_level = std::min(LOG_ERROR_REPORT, level);
initial.commitd7cae122008-07-26 21:49:38397}
398
399int GetMinLogLevel() {
400 return min_log_level;
401}
402
[email protected]162ac0f2010-11-04 15:50:49403int GetVlogVerbosity() {
404 return std::max(-1, LOG_INFO - GetMinLogLevel());
405}
406
[email protected]99b7c57f2010-09-29 19:26:36407int GetVlogLevelHelper(const char* file, size_t N) {
408 DCHECK_GT(N, 0U);
409 return g_vlog_info ?
410 g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49411 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36412}
413
initial.commitd7cae122008-07-26 21:49:38414void SetLogItems(bool enable_process_id, bool enable_thread_id,
415 bool enable_timestamp, bool enable_tickcount) {
416 log_process_id = enable_process_id;
417 log_thread_id = enable_thread_id;
418 log_timestamp = enable_timestamp;
419 log_tickcount = enable_tickcount;
420}
421
[email protected]81e0a852010-08-17 00:38:12422void SetShowErrorDialogs(bool enable_dialogs) {
423 show_error_dialogs = enable_dialogs;
424}
425
initial.commitd7cae122008-07-26 21:49:38426void SetLogAssertHandler(LogAssertHandlerFunction handler) {
427 log_assert_handler = handler;
428}
429
[email protected]fb62a532009-02-12 01:19:05430void SetLogReportHandler(LogReportHandlerFunction handler) {
431 log_report_handler = handler;
432}
433
[email protected]2b07b8412009-11-25 15:26:34434void SetLogMessageHandler(LogMessageHandlerFunction handler) {
435 log_message_handler = handler;
436}
437
[email protected]64e5cc02010-11-03 19:20:27438LogMessageHandlerFunction GetLogMessageHandler() {
439 return log_message_handler;
440}
441
[email protected]6d445d32010-09-30 19:10:03442// MSVC doesn't like complex extern templates and DLLs.
443#if !defined(COMPILER_MSVC)
444// Explicit instantiations for commonly used comparisons.
445template std::string* MakeCheckOpString<int, int>(
446 const int&, const int&, const char* names);
447template std::string* MakeCheckOpString<unsigned long, unsigned long>(
448 const unsigned long&, const unsigned long&, const char* names);
449template std::string* MakeCheckOpString<unsigned long, unsigned int>(
450 const unsigned long&, const unsigned int&, const char* names);
451template std::string* MakeCheckOpString<unsigned int, unsigned long>(
452 const unsigned int&, const unsigned long&, const char* names);
453template std::string* MakeCheckOpString<std::string, std::string>(
454 const std::string&, const std::string&, const char* name);
455#endif
[email protected]2b07b8412009-11-25 15:26:34456
[email protected]d81baca42010-03-01 13:10:22457// Displays a message box to the user with the error message in it.
458// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25459// This is for developers only; we don't use this in circumstances
460// (like release builds) where users could see it, since users don't
461// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22462void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38463 if (str.empty())
464 return;
465
[email protected]81e0a852010-08-17 00:38:12466 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44467 return;
468
[email protected]f6abeba2008-08-08 13:27:28469#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22470 // For Windows programs, it's possible that the message loop is
471 // messed up on a fatal error, and creating a MessageBox will cause
472 // that message loop to be run. Instead, we try to spawn another
473 // process that displays its command line. We look for "Debug
474 // Message.exe" in the same directory as the application. If it
475 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38476 wchar_t prog_name[MAX_PATH];
477 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
478 wchar_t* backslash = wcsrchr(prog_name, '\\');
479 if (backslash)
480 backslash[1] = 0;
481 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
482
[email protected]047a03f2009-10-07 02:10:20483 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02484 if (cmdline.empty())
485 return;
initial.commitd7cae122008-07-26 21:49:38486
487 STARTUPINFO startup_info;
488 memset(&startup_info, 0, sizeof(startup_info));
489 startup_info.cb = sizeof(startup_info);
490
491 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02492 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38493 NULL, &startup_info, &process_info)) {
494 WaitForSingleObject(process_info.hProcess, INFINITE);
495 CloseHandle(process_info.hThread);
496 CloseHandle(process_info.hProcess);
497 } else {
498 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02499 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38500 MB_OK | MB_ICONHAND | MB_TOPMOST);
501 }
[email protected]f6abeba2008-08-08 13:27:28502#else
[email protected]561513f2010-12-16 23:29:25503 // We intentionally don't implement a dialog on other platforms.
504 // You can just look at stderr.
[email protected]f6abeba2008-08-08 13:27:28505#endif
initial.commitd7cae122008-07-26 21:49:38506}
507
[email protected]3f85caa2009-04-14 16:52:11508#if defined(OS_WIN)
509LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
510}
511
512LogMessage::SaveLastError::~SaveLastError() {
513 ::SetLastError(last_error_);
514}
515#endif // defined(OS_WIN)
516
initial.commitd7cae122008-07-26 21:49:38517LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
518 int ctr)
[email protected]162ac0f2010-11-04 15:50:49519 : severity_(severity), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38520 Init(file, line);
521}
522
[email protected]eae9c062011-01-11 00:50:59523LogMessage::LogMessage(const char* file, int line)
524 : severity_(LOG_INFO), file_(file), line_(line) {
525 Init(file, line);
526}
527
528LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
529 : severity_(severity), file_(file), line_(line) {
530 Init(file, line);
531}
532
[email protected]9c7132e2011-02-08 07:39:08533LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49534 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38535 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08536 stream_ << "Check failed: " << *result;
537 delete result;
initial.commitd7cae122008-07-26 21:49:38538}
539
[email protected]fb62a532009-02-12 01:19:05540LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08541 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49542 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05543 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08544 stream_ << "Check failed: " << *result;
545 delete result;
[email protected]fb62a532009-02-12 01:19:05546}
547
initial.commitd7cae122008-07-26 21:49:38548LogMessage::~LogMessage() {
[email protected]d1ccc35a2010-03-24 05:03:24549#ifndef NDEBUG
550 if (severity_ == LOG_FATAL) {
551 // Include a stack trace on a fatal.
[email protected]58580352010-10-26 04:07:50552 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24553 stream_ << std::endl; // Newline to separate from log message.
554 trace.OutputToStream(&stream_);
555 }
[email protected]1d8c2702008-08-19 23:39:32556#endif
[email protected]d1ccc35a2010-03-24 05:03:24557 stream_ << std::endl;
558 std::string str_newline(stream_.str());
559
[email protected]2b07b8412009-11-25 15:26:34560 // Give any log message handler first dibs on the message.
[email protected]162ac0f2010-11-04 15:50:49561 if (log_message_handler && log_message_handler(severity_, file_, line_,
562 message_start_, str_newline)) {
563 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34564 return;
[email protected]162ac0f2010-11-04 15:50:49565 }
initial.commitd7cae122008-07-26 21:49:38566
initial.commitd7cae122008-07-26 21:49:38567 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
[email protected]f6abeba2008-08-08 13:27:28568 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
569#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38570 OutputDebugStringA(str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18571#endif
[email protected]469006c2010-09-24 15:43:06572 fprintf(stderr, "%s", str_newline.c_str());
573 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31574 } else if (severity_ >= kAlwaysPrintErrorLevel) {
575 // When we're only outputting to a log file, above a certain log level, we
576 // should still output to stderr so that we can better detect and diagnose
577 // problems with unit tests, especially on the buildbots.
578 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02579 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28580 }
[email protected]52a261f2009-03-03 15:01:12581
[email protected]5b84fe32010-09-14 22:24:55582 // We can have multiple threads and/or processes, so try to prevent them
583 // from clobbering each other's writes.
584 // If the client app did not call InitLogging, and the lock has not
585 // been created do it now. We do this on demand, but if two threads try
586 // to do this at the same time, there will be a race condition to create
587 // the lock. This is why InitLogging should be called from the main
588 // thread at the beginning of execution.
589 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38590 // write to log file
591 if (logging_destination != LOG_NONE &&
[email protected]5b84fe32010-09-14 22:24:55592 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
593 LoggingLock logging_lock;
594 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28595#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55596 SetFilePointer(log_file, 0, 0, SEEK_END);
597 DWORD num_written;
598 WriteFile(log_file,
599 static_cast<const void*>(str_newline.c_str()),
600 static_cast<DWORD>(str_newline.length()),
601 &num_written,
602 NULL);
[email protected]cba21962010-08-31 22:35:55603#else
[email protected]5b84fe32010-09-14 22:24:55604 fprintf(log_file, "%s", str_newline.c_str());
605 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55606#endif
initial.commitd7cae122008-07-26 21:49:38607 }
608 }
609
610 if (severity_ == LOG_FATAL) {
611 // display a message or break into the debugger on a fatal error
[email protected]58580352010-10-26 04:07:50612 if (base::debug::BeingDebugged()) {
613 base::debug::BreakDebugger();
[email protected]1ffe08c12008-08-13 11:15:11614 } else {
initial.commitd7cae122008-07-26 21:49:38615 if (log_assert_handler) {
616 // make a copy of the string for the handler out of paranoia
617 log_assert_handler(std::string(stream_.str()));
618 } else {
[email protected]4d5901272008-11-06 00:33:50619 // Don't use the string with the newline, get a fresh version to send to
620 // the debug message process. We also don't display assertions to the
621 // user in release mode. The enduser can't do anything with this
622 // information, and displaying message boxes when the application is
623 // hosed can cause additional problems.
624#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22625 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50626#endif
initial.commitd7cae122008-07-26 21:49:38627 // Crash the process to generate a dump.
[email protected]58580352010-10-26 04:07:50628 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38629 }
630 }
[email protected]fb62a532009-02-12 01:19:05631 } else if (severity_ == LOG_ERROR_REPORT) {
632 // We are here only if the user runs with --enable-dcheck in release mode.
633 if (log_report_handler) {
634 log_report_handler(std::string(stream_.str()));
635 } else {
[email protected]d81baca42010-03-01 13:10:22636 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05637 }
initial.commitd7cae122008-07-26 21:49:38638 }
639}
640
[email protected]eae9c062011-01-11 00:50:59641// writes the common header info to the stream
642void LogMessage::Init(const char* file, int line) {
643 base::StringPiece filename(file);
644 size_t last_slash_pos = filename.find_last_of("\\/");
645 if (last_slash_pos != base::StringPiece::npos)
646 filename.remove_prefix(last_slash_pos + 1);
647
648 // TODO(darin): It might be nice if the columns were fixed width.
649
650 stream_ << '[';
651 if (log_process_id)
652 stream_ << CurrentProcessId() << ':';
653 if (log_thread_id)
654 stream_ << CurrentThreadId() << ':';
655 if (log_timestamp) {
656 time_t t = time(NULL);
657 struct tm local_time = {0};
658#if _MSC_VER >= 1400
659 localtime_s(&local_time, &t);
660#else
661 localtime_r(&t, &local_time);
662#endif
663 struct tm* tm_time = &local_time;
664 stream_ << std::setfill('0')
665 << std::setw(2) << 1 + tm_time->tm_mon
666 << std::setw(2) << tm_time->tm_mday
667 << '/'
668 << std::setw(2) << tm_time->tm_hour
669 << std::setw(2) << tm_time->tm_min
670 << std::setw(2) << tm_time->tm_sec
671 << ':';
672 }
673 if (log_tickcount)
674 stream_ << TickCount() << ':';
675 if (severity_ >= 0)
676 stream_ << log_severity_names[severity_];
677 else
678 stream_ << "VERBOSE" << -severity_;
679
680 stream_ << ":" << filename << "(" << line << ")] ";
681
682 message_start_ = stream_.tellp();
683}
684
[email protected]d8617a62009-10-09 23:52:20685#if defined(OS_WIN)
686// This has already been defined in the header, but defining it again as DWORD
687// ensures that the type used in the header is equivalent to DWORD. If not,
688// the redefinition is a compile error.
689typedef DWORD SystemErrorCode;
690#endif
691
692SystemErrorCode GetLastSystemErrorCode() {
693#if defined(OS_WIN)
694 return ::GetLastError();
695#elif defined(OS_POSIX)
696 return errno;
697#else
698#error Not implemented
699#endif
700}
701
702#if defined(OS_WIN)
703Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
704 int line,
705 LogSeverity severity,
706 SystemErrorCode err,
707 const char* module)
708 : err_(err),
709 module_(module),
710 log_message_(file, line, severity) {
711}
712
713Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
714 int line,
715 LogSeverity severity,
716 SystemErrorCode err)
717 : err_(err),
718 module_(NULL),
719 log_message_(file, line, severity) {
720}
721
722Win32ErrorLogMessage::~Win32ErrorLogMessage() {
723 const int error_message_buffer_size = 256;
724 char msgbuf[error_message_buffer_size];
[email protected]6ac3df52010-10-20 01:33:32725 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
[email protected]d8617a62009-10-09 23:52:20726 HMODULE hmod;
727 if (module_) {
728 hmod = GetModuleHandleA(module_);
729 if (hmod) {
730 flags |= FORMAT_MESSAGE_FROM_HMODULE;
731 } else {
732 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
733 // so it will not call GetModuleHandle, so recursive errors are
734 // impossible.
735 DPLOG(WARNING) << "Couldn't open module " << module_
736 << " for error message query";
737 }
738 } else {
739 hmod = NULL;
740 }
741 DWORD len = FormatMessageA(flags,
742 hmod,
743 err_,
[email protected]6ac3df52010-10-20 01:33:32744 0,
[email protected]d8617a62009-10-09 23:52:20745 msgbuf,
746 sizeof(msgbuf) / sizeof(msgbuf[0]),
747 NULL);
748 if (len) {
749 while ((len > 0) &&
750 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
751 msgbuf[--len] = 0;
752 }
753 stream() << ": " << msgbuf;
754 } else {
755 stream() << ": Error " << GetLastError() << " while retrieving error "
756 << err_;
757 }
758}
759#elif defined(OS_POSIX)
760ErrnoLogMessage::ErrnoLogMessage(const char* file,
761 int line,
762 LogSeverity severity,
763 SystemErrorCode err)
764 : err_(err),
765 log_message_(file, line, severity) {
766}
767
768ErrnoLogMessage::~ErrnoLogMessage() {
769 stream() << ": " << safe_strerror(err_);
770}
771#endif // OS_WIN
772
initial.commitd7cae122008-07-26 21:49:38773void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55774 LoggingLock logging_lock;
775
initial.commitd7cae122008-07-26 21:49:38776 if (!log_file)
777 return;
778
[email protected]f6abeba2008-08-08 13:27:28779 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38780 log_file = NULL;
781}
782
[email protected]e36ddc82009-12-08 04:22:50783void RawLog(int level, const char* message) {
784 if (level >= min_log_level) {
785 size_t bytes_written = 0;
786 const size_t message_len = strlen(message);
787 int rv;
788 while (bytes_written < message_len) {
789 rv = HANDLE_EINTR(
790 write(STDERR_FILENO, message + bytes_written,
791 message_len - bytes_written));
792 if (rv < 0) {
793 // Give up, nothing we can do now.
794 break;
795 }
796 bytes_written += rv;
797 }
798
799 if (message_len > 0 && message[message_len - 1] != '\n') {
800 do {
801 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
802 if (rv < 0) {
803 // Give up, nothing we can do now.
804 break;
805 }
806 } while (rv != 1);
807 }
808 }
809
810 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50811 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50812}
813
[email protected]96fd0032009-04-24 00:13:08814} // namespace logging
initial.commitd7cae122008-07-26 21:49:38815
816std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20817 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38818}
[email protected]1f88b5162011-04-01 00:02:29819
820namespace base {
821
822// This was defined at the beginnig of this file.
823#undef write
824
825std::ostream& operator<<(std::ostream& o, const StringPiece& piece) {
826 o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
827 return o;
828}
829
830} // namespace base