blob: e78b1a4819bff5e2a6e5c4b7beeccaf01f88dd1a [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),
354 command_line->GetSwitchValueASCII(switches::kVModule));
355 }
356
[email protected]5b84fe32010-09-14 22:24:55357 LoggingLock::Init(lock_log, new_log_file);
358
359 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38360
361 if (log_file) {
362 // calling InitLogging twice or after some log call has already opened the
363 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28364 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38365 log_file = NULL;
366 }
367
initial.commitd7cae122008-07-26 21:49:38368 logging_destination = logging_dest;
369
370 // ignore file options if logging is disabled or only to system
371 if (logging_destination == LOG_NONE ||
372 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
[email protected]c7d5da992010-10-28 00:20:21373 return true;
initial.commitd7cae122008-07-26 21:49:38374
[email protected]614e9fa2008-08-11 22:52:59375 if (!log_file_name)
376 log_file_name = new PathString();
377 *log_file_name = new_log_file;
initial.commitd7cae122008-07-26 21:49:38378 if (delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59379 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38380
[email protected]c7d5da992010-10-28 00:20:21381 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38382}
383
384void SetMinLogLevel(int level) {
385 min_log_level = level;
386}
387
388int GetMinLogLevel() {
389 return min_log_level;
390}
391
[email protected]99b7c57f2010-09-29 19:26:36392int GetVlogLevelHelper(const char* file, size_t N) {
393 DCHECK_GT(N, 0U);
394 return g_vlog_info ?
395 g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
396 VlogInfo::kDefaultVlogLevel;
397}
398
initial.commitd7cae122008-07-26 21:49:38399void SetLogItems(bool enable_process_id, bool enable_thread_id,
400 bool enable_timestamp, bool enable_tickcount) {
401 log_process_id = enable_process_id;
402 log_thread_id = enable_thread_id;
403 log_timestamp = enable_timestamp;
404 log_tickcount = enable_tickcount;
405}
406
[email protected]81e0a852010-08-17 00:38:12407void SetShowErrorDialogs(bool enable_dialogs) {
408 show_error_dialogs = enable_dialogs;
409}
410
initial.commitd7cae122008-07-26 21:49:38411void SetLogAssertHandler(LogAssertHandlerFunction handler) {
412 log_assert_handler = handler;
413}
414
[email protected]fb62a532009-02-12 01:19:05415void SetLogReportHandler(LogReportHandlerFunction handler) {
416 log_report_handler = handler;
417}
418
[email protected]2b07b8412009-11-25 15:26:34419void SetLogMessageHandler(LogMessageHandlerFunction handler) {
420 log_message_handler = handler;
421}
422
[email protected]6d445d32010-09-30 19:10:03423// MSVC doesn't like complex extern templates and DLLs.
424#if !defined(COMPILER_MSVC)
425// Explicit instantiations for commonly used comparisons.
426template std::string* MakeCheckOpString<int, int>(
427 const int&, const int&, const char* names);
428template std::string* MakeCheckOpString<unsigned long, unsigned long>(
429 const unsigned long&, const unsigned long&, const char* names);
430template std::string* MakeCheckOpString<unsigned long, unsigned int>(
431 const unsigned long&, const unsigned int&, const char* names);
432template std::string* MakeCheckOpString<unsigned int, unsigned long>(
433 const unsigned int&, const unsigned long&, const char* names);
434template std::string* MakeCheckOpString<std::string, std::string>(
435 const std::string&, const std::string&, const char* name);
436#endif
[email protected]2b07b8412009-11-25 15:26:34437
[email protected]d81baca42010-03-01 13:10:22438// Displays a message box to the user with the error message in it.
439// Used for fatal messages, where we close the app simultaneously.
440void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38441 if (str.empty())
442 return;
443
[email protected]81e0a852010-08-17 00:38:12444 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44445 return;
446
[email protected]f6abeba2008-08-08 13:27:28447#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22448 // For Windows programs, it's possible that the message loop is
449 // messed up on a fatal error, and creating a MessageBox will cause
450 // that message loop to be run. Instead, we try to spawn another
451 // process that displays its command line. We look for "Debug
452 // Message.exe" in the same directory as the application. If it
453 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38454 wchar_t prog_name[MAX_PATH];
455 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
456 wchar_t* backslash = wcsrchr(prog_name, '\\');
457 if (backslash)
458 backslash[1] = 0;
459 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
460
[email protected]047a03f2009-10-07 02:10:20461 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02462 if (cmdline.empty())
463 return;
initial.commitd7cae122008-07-26 21:49:38464
465 STARTUPINFO startup_info;
466 memset(&startup_info, 0, sizeof(startup_info));
467 startup_info.cb = sizeof(startup_info);
468
469 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02470 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38471 NULL, &startup_info, &process_info)) {
472 WaitForSingleObject(process_info.hProcess, INFINITE);
473 CloseHandle(process_info.hThread);
474 CloseHandle(process_info.hProcess);
475 } else {
476 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02477 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38478 MB_OK | MB_ICONHAND | MB_TOPMOST);
479 }
[email protected]81e0a852010-08-17 00:38:12480#elif defined(USE_X11) && !defined(OS_CHROMEOS)
[email protected]d81baca42010-03-01 13:10:22481 // Shell out to xmessage, which behaves like debug_message.exe, but is
482 // way more retro. We could use zenity/kdialog but then we're starting
483 // to get into needing to check the desktop env and this dialog should
484 // only be coming up in Very Bad situations.
485 std::vector<std::string> argv;
486 argv.push_back("xmessage");
487 argv.push_back(str);
488 base::LaunchApp(argv, base::file_handle_mapping_vector(), true /* wait */,
489 NULL);
[email protected]f6abeba2008-08-08 13:27:28490#else
[email protected]d81baca42010-03-01 13:10:22491 // http://code.google.com/p/chromium/issues/detail?id=37026
492 NOTIMPLEMENTED();
[email protected]f6abeba2008-08-08 13:27:28493#endif
initial.commitd7cae122008-07-26 21:49:38494}
495
[email protected]3f85caa2009-04-14 16:52:11496#if defined(OS_WIN)
497LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
498}
499
500LogMessage::SaveLastError::~SaveLastError() {
501 ::SetLastError(last_error_);
502}
503#endif // defined(OS_WIN)
504
initial.commitd7cae122008-07-26 21:49:38505LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
506 int ctr)
507 : severity_(severity) {
508 Init(file, line);
509}
510
511LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
512 : severity_(LOG_FATAL) {
513 Init(file, line);
514 stream_ << "Check failed: " << (*result.str_);
515}
516
[email protected]fb62a532009-02-12 01:19:05517LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
518 const CheckOpString& result)
519 : severity_(severity) {
520 Init(file, line);
521 stream_ << "Check failed: " << (*result.str_);
522}
523
initial.commitd7cae122008-07-26 21:49:38524LogMessage::LogMessage(const char* file, int line)
525 : severity_(LOG_INFO) {
526 Init(file, line);
527}
528
529LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
530 : severity_(severity) {
531 Init(file, line);
532}
533
534// writes the common header info to the stream
535void LogMessage::Init(const char* file, int line) {
536 // log only the filename
537 const char* last_slash = strrchr(file, '\\');
538 if (last_slash)
539 file = last_slash + 1;
540
541 // TODO(darin): It might be nice if the columns were fixed width.
542
543 stream_ << '[';
544 if (log_process_id)
[email protected]f8588472008-11-05 23:17:24545 stream_ << CurrentProcessId() << ':';
initial.commitd7cae122008-07-26 21:49:38546 if (log_thread_id)
[email protected]f8588472008-11-05 23:17:24547 stream_ << CurrentThreadId() << ':';
initial.commitd7cae122008-07-26 21:49:38548 if (log_timestamp) {
[email protected]defcd8f32009-05-13 00:03:43549 time_t t = time(NULL);
initial.commitd7cae122008-07-26 21:49:38550 struct tm local_time = {0};
[email protected]defcd8f32009-05-13 00:03:43551#if _MSC_VER >= 1400
initial.commitd7cae122008-07-26 21:49:38552 localtime_s(&local_time, &t);
initial.commitd7cae122008-07-26 21:49:38553#else
[email protected]defcd8f32009-05-13 00:03:43554 localtime_r(&t, &local_time);
initial.commitd7cae122008-07-26 21:49:38555#endif
[email protected]defcd8f32009-05-13 00:03:43556 struct tm* tm_time = &local_time;
initial.commitd7cae122008-07-26 21:49:38557 stream_ << std::setfill('0')
558 << std::setw(2) << 1 + tm_time->tm_mon
559 << std::setw(2) << tm_time->tm_mday
560 << '/'
561 << std::setw(2) << tm_time->tm_hour
562 << std::setw(2) << tm_time->tm_min
563 << std::setw(2) << tm_time->tm_sec
564 << ':';
565 }
566 if (log_tickcount)
[email protected]f8588472008-11-05 23:17:24567 stream_ << TickCount() << ':';
[email protected]52a261f2009-03-03 15:01:12568 stream_ << log_severity_names[severity_] << ":" << file <<
569 "(" << line << ")] ";
initial.commitd7cae122008-07-26 21:49:38570
571 message_start_ = stream_.tellp();
572}
573
574LogMessage::~LogMessage() {
[email protected]521b0c42010-10-01 23:02:36575 // The macros in logging.h should already avoid creating LogMessages
576 // when this holds, but it's possible that users create LogMessages
577 // directly (e.g., using LOG_STREAM() directly).
initial.commitd7cae122008-07-26 21:49:38578 if (severity_ < min_log_level)
579 return;
580
[email protected]d1ccc35a2010-03-24 05:03:24581#ifndef NDEBUG
582 if (severity_ == LOG_FATAL) {
583 // Include a stack trace on a fatal.
[email protected]58580352010-10-26 04:07:50584 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24585 stream_ << std::endl; // Newline to separate from log message.
586 trace.OutputToStream(&stream_);
587 }
[email protected]1d8c2702008-08-19 23:39:32588#endif
[email protected]d1ccc35a2010-03-24 05:03:24589 stream_ << std::endl;
590 std::string str_newline(stream_.str());
591
[email protected]2b07b8412009-11-25 15:26:34592 // Give any log message handler first dibs on the message.
593 if (log_message_handler && log_message_handler(severity_, str_newline))
594 return;
initial.commitd7cae122008-07-26 21:49:38595
initial.commitd7cae122008-07-26 21:49:38596 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
[email protected]f6abeba2008-08-08 13:27:28597 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
598#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38599 OutputDebugStringA(str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18600#endif
[email protected]469006c2010-09-24 15:43:06601 fprintf(stderr, "%s", str_newline.c_str());
602 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31603 } else if (severity_ >= kAlwaysPrintErrorLevel) {
604 // When we're only outputting to a log file, above a certain log level, we
605 // should still output to stderr so that we can better detect and diagnose
606 // problems with unit tests, especially on the buildbots.
607 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02608 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28609 }
[email protected]52a261f2009-03-03 15:01:12610
[email protected]5b84fe32010-09-14 22:24:55611 // We can have multiple threads and/or processes, so try to prevent them
612 // from clobbering each other's writes.
613 // If the client app did not call InitLogging, and the lock has not
614 // been created do it now. We do this on demand, but if two threads try
615 // to do this at the same time, there will be a race condition to create
616 // the lock. This is why InitLogging should be called from the main
617 // thread at the beginning of execution.
618 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38619 // write to log file
620 if (logging_destination != LOG_NONE &&
[email protected]5b84fe32010-09-14 22:24:55621 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
622 LoggingLock logging_lock;
623 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28624#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55625 SetFilePointer(log_file, 0, 0, SEEK_END);
626 DWORD num_written;
627 WriteFile(log_file,
628 static_cast<const void*>(str_newline.c_str()),
629 static_cast<DWORD>(str_newline.length()),
630 &num_written,
631 NULL);
[email protected]cba21962010-08-31 22:35:55632#else
[email protected]5b84fe32010-09-14 22:24:55633 fprintf(log_file, "%s", str_newline.c_str());
634 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55635#endif
initial.commitd7cae122008-07-26 21:49:38636 }
637 }
638
639 if (severity_ == LOG_FATAL) {
640 // display a message or break into the debugger on a fatal error
[email protected]58580352010-10-26 04:07:50641 if (base::debug::BeingDebugged()) {
642 base::debug::BreakDebugger();
[email protected]1ffe08c12008-08-13 11:15:11643 } else {
initial.commitd7cae122008-07-26 21:49:38644 if (log_assert_handler) {
645 // make a copy of the string for the handler out of paranoia
646 log_assert_handler(std::string(stream_.str()));
647 } else {
[email protected]4d5901272008-11-06 00:33:50648 // Don't use the string with the newline, get a fresh version to send to
649 // the debug message process. We also don't display assertions to the
650 // user in release mode. The enduser can't do anything with this
651 // information, and displaying message boxes when the application is
652 // hosed can cause additional problems.
653#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22654 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50655#endif
initial.commitd7cae122008-07-26 21:49:38656 // Crash the process to generate a dump.
[email protected]58580352010-10-26 04:07:50657 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38658 }
659 }
[email protected]fb62a532009-02-12 01:19:05660 } else if (severity_ == LOG_ERROR_REPORT) {
661 // We are here only if the user runs with --enable-dcheck in release mode.
662 if (log_report_handler) {
663 log_report_handler(std::string(stream_.str()));
664 } else {
[email protected]d81baca42010-03-01 13:10:22665 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05666 }
initial.commitd7cae122008-07-26 21:49:38667 }
668}
669
[email protected]d8617a62009-10-09 23:52:20670#if defined(OS_WIN)
671// This has already been defined in the header, but defining it again as DWORD
672// ensures that the type used in the header is equivalent to DWORD. If not,
673// the redefinition is a compile error.
674typedef DWORD SystemErrorCode;
675#endif
676
677SystemErrorCode GetLastSystemErrorCode() {
678#if defined(OS_WIN)
679 return ::GetLastError();
680#elif defined(OS_POSIX)
681 return errno;
682#else
683#error Not implemented
684#endif
685}
686
687#if defined(OS_WIN)
688Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
689 int line,
690 LogSeverity severity,
691 SystemErrorCode err,
692 const char* module)
693 : err_(err),
694 module_(module),
695 log_message_(file, line, severity) {
696}
697
698Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
699 int line,
700 LogSeverity severity,
701 SystemErrorCode err)
702 : err_(err),
703 module_(NULL),
704 log_message_(file, line, severity) {
705}
706
707Win32ErrorLogMessage::~Win32ErrorLogMessage() {
708 const int error_message_buffer_size = 256;
709 char msgbuf[error_message_buffer_size];
[email protected]6ac3df52010-10-20 01:33:32710 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
[email protected]d8617a62009-10-09 23:52:20711 HMODULE hmod;
712 if (module_) {
713 hmod = GetModuleHandleA(module_);
714 if (hmod) {
715 flags |= FORMAT_MESSAGE_FROM_HMODULE;
716 } else {
717 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
718 // so it will not call GetModuleHandle, so recursive errors are
719 // impossible.
720 DPLOG(WARNING) << "Couldn't open module " << module_
721 << " for error message query";
722 }
723 } else {
724 hmod = NULL;
725 }
726 DWORD len = FormatMessageA(flags,
727 hmod,
728 err_,
[email protected]6ac3df52010-10-20 01:33:32729 0,
[email protected]d8617a62009-10-09 23:52:20730 msgbuf,
731 sizeof(msgbuf) / sizeof(msgbuf[0]),
732 NULL);
733 if (len) {
734 while ((len > 0) &&
735 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
736 msgbuf[--len] = 0;
737 }
738 stream() << ": " << msgbuf;
739 } else {
740 stream() << ": Error " << GetLastError() << " while retrieving error "
741 << err_;
742 }
743}
744#elif defined(OS_POSIX)
745ErrnoLogMessage::ErrnoLogMessage(const char* file,
746 int line,
747 LogSeverity severity,
748 SystemErrorCode err)
749 : err_(err),
750 log_message_(file, line, severity) {
751}
752
753ErrnoLogMessage::~ErrnoLogMessage() {
754 stream() << ": " << safe_strerror(err_);
755}
756#endif // OS_WIN
757
initial.commitd7cae122008-07-26 21:49:38758void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55759 LoggingLock logging_lock;
760
initial.commitd7cae122008-07-26 21:49:38761 if (!log_file)
762 return;
763
[email protected]f6abeba2008-08-08 13:27:28764 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38765 log_file = NULL;
766}
767
[email protected]e36ddc82009-12-08 04:22:50768void RawLog(int level, const char* message) {
769 if (level >= min_log_level) {
770 size_t bytes_written = 0;
771 const size_t message_len = strlen(message);
772 int rv;
773 while (bytes_written < message_len) {
774 rv = HANDLE_EINTR(
775 write(STDERR_FILENO, message + bytes_written,
776 message_len - bytes_written));
777 if (rv < 0) {
778 // Give up, nothing we can do now.
779 break;
780 }
781 bytes_written += rv;
782 }
783
784 if (message_len > 0 && message[message_len - 1] != '\n') {
785 do {
786 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
787 if (rv < 0) {
788 // Give up, nothing we can do now.
789 break;
790 }
791 } while (rv != 1);
792 }
793 }
794
795 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50796 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50797}
798
[email protected]96fd0032009-04-24 00:13:08799} // namespace logging
initial.commitd7cae122008-07-26 21:49:38800
801std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20802 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38803}