blob: 16cd2f8b26d32f406e75b9c04c632674ce1ce708 [file] [log] [blame]
[email protected]63e66802012-01-18 21:21:091// Copyright (c) 2012 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)
[email protected]19ea84ca2010-11-12 08:37:0822#include <sys/time.h> // timespec doesn't seem to be in <time.h>
23#else
[email protected]052f1b52008-11-06 21:43:0724#include <sys/syscall.h>
[email protected]19ea84ca2010-11-12 08:37:0825#endif
[email protected]052f1b52008-11-06 21:43:0726#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5927#endif
28
29#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2030#include <errno.h>
[email protected]166326c62010-08-05 15:50:2331#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2832#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0033#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2834#include <string.h>
35#include <unistd.h>
36#define MAX_PATH PATH_MAX
37typedef FILE* FileHandle;
38typedef pthread_mutex_t* MutexHandle;
39#endif
40
[email protected]1f88b5162011-04-01 00:02:2941#include <algorithm>
42#include <cstring>
initial.commitd7cae122008-07-26 21:49:3843#include <ctime>
44#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2945#include <ostream>
[email protected]b16ef312008-08-19 18:36:2346
initial.commitd7cae122008-07-26 21:49:3847#include "base/base_switches.h"
48#include "base/command_line.h"
[email protected]eb4c4d032012-04-03 18:45:0549#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5050#include "base/debug/debugger.h"
51#include "base/debug/stack_trace.h"
[email protected]2025d002012-11-14 20:54:3552#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0053#include "base/strings/string_piece.h"
[email protected]a4ea1f12013-06-07 18:37:0754#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2055#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0956#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3657#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0458#if defined(OS_POSIX)
59#include "base/safe_strerror_posix.h"
60#endif
[email protected]52a261f2009-03-03 15:01:1261
[email protected]3132e35c2011-07-07 20:46:5062#if defined(OS_ANDROID)
63#include <android/log.h>
64#endif
65
initial.commitd7cae122008-07-26 21:49:3866namespace logging {
67
[email protected]7c10f7552011-01-11 01:03:3668DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
[email protected]064aa162011-12-03 00:30:0869
[email protected]f12e596a2013-05-21 01:42:1070DcheckState get_dcheck_state() {
71 return g_dcheck_state;
72}
73
74void set_dcheck_state(DcheckState state) {
75 g_dcheck_state = state;
76}
77
[email protected]064aa162011-12-03 00:30:0878namespace {
79
[email protected]99b7c57f2010-09-29 19:26:3680VlogInfo* g_vlog_info = NULL;
[email protected]064aa162011-12-03 00:30:0881VlogInfo* g_vlog_info_prev = NULL;
initial.commitd7cae122008-07-26 21:49:3882
83const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]fb62a532009-02-12 01:19:0584 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3885
86int min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3287
[email protected]5e3f7c22013-06-21 21:15:3388LoggingDestination logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:3889
[email protected]a33c9892008-08-25 20:10:3190// For LOG_ERROR and above, always print to stderr.
91const int kAlwaysPrintErrorLevel = LOG_ERROR;
92
[email protected]614e9fa2008-08-11 22:52:5993// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3894// will be lazily initialized to the default value when it is
95// first needed.
[email protected]f6abeba2008-08-08 13:27:2896#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5997typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2898#else
[email protected]614e9fa2008-08-11 22:52:5999typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28100#endif
[email protected]614e9fa2008-08-11 22:52:59101PathString* log_file_name = NULL;
initial.commitd7cae122008-07-26 21:49:38102
103// this file is lazily opened and the handle may be NULL
[email protected]f6abeba2008-08-08 13:27:28104FileHandle log_file = NULL;
initial.commitd7cae122008-07-26 21:49:38105
106// what should be prepended to each message?
107bool log_process_id = false;
108bool log_thread_id = false;
109bool log_timestamp = true;
110bool log_tickcount = false;
111
[email protected]81e0a852010-08-17 00:38:12112// Should we pop up fatal debug messages in a dialog?
113bool show_error_dialogs = false;
114
initial.commitd7cae122008-07-26 21:49:38115// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05116// the debug message dialog and process termination.
initial.commitd7cae122008-07-26 21:49:38117LogAssertHandlerFunction log_assert_handler = NULL;
[email protected]fb62a532009-02-12 01:19:05118// An report handler override specified by the client to be called instead of
119// the debug message dialog.
120LogReportHandlerFunction log_report_handler = NULL;
[email protected]2b07b8412009-11-25 15:26:34121// A log message handler that gets notified of every log message we process.
122LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38123
[email protected]f6abeba2008-08-08 13:27:28124// Helper functions to wrap platform differences.
125
[email protected]f8588472008-11-05 23:17:24126int32 CurrentProcessId() {
127#if defined(OS_WIN)
128 return GetCurrentProcessId();
129#elif defined(OS_POSIX)
130 return getpid();
131#endif
132}
133
[email protected]f8588472008-11-05 23:17:24134uint64 TickCount() {
135#if defined(OS_WIN)
136 return GetTickCount();
137#elif defined(OS_MACOSX)
138 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08139#elif defined(OS_NACL)
140 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
141 // So we have to use clock() for now.
142 return clock();
[email protected]e43eddf12009-12-29 00:32:52143#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07144 struct timespec ts;
145 clock_gettime(CLOCK_MONOTONIC, &ts);
146
147 uint64 absolute_micro =
148 static_cast<int64>(ts.tv_sec) * 1000000 +
149 static_cast<int64>(ts.tv_nsec) / 1000;
150
151 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24152#endif
153}
154
[email protected]f6abeba2008-08-08 13:27:28155void CloseFile(FileHandle log) {
156#if defined(OS_WIN)
157 CloseHandle(log);
158#else
159 fclose(log);
160#endif
161}
162
[email protected]614e9fa2008-08-11 22:52:59163void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28164#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59165 DeleteFile(log_name.c_str());
[email protected]ac07ec52013-04-22 17:32:45166#elif defined (OS_NACL)
167 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28168#else
[email protected]614e9fa2008-08-11 22:52:59169 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28170#endif
171}
initial.commitd7cae122008-07-26 21:49:38172
[email protected]5f95d532010-10-01 17:16:58173PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55174#if defined(OS_WIN)
175 // On Windows we use the same path as the exe.
176 wchar_t module_name[MAX_PATH];
177 GetModuleFileName(NULL, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58178
179 PathString log_file = module_name;
180 PathString::size_type last_backslash =
181 log_file.rfind('\\', log_file.size());
182 if (last_backslash != PathString::npos)
183 log_file.erase(last_backslash + 1);
184 log_file += L"debug.log";
185 return log_file;
[email protected]5b84fe32010-09-14 22:24:55186#elif defined(OS_POSIX)
187 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58188 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55189#endif
190}
191
192// This class acts as a wrapper for locking the logging files.
193// LoggingLock::Init() should be called from the main thread before any logging
194// is done. Then whenever logging, be sure to have a local LoggingLock
195// instance on the stack. This will ensure that the lock is unlocked upon
196// exiting the frame.
197// LoggingLocks can not be nested.
198class LoggingLock {
199 public:
200 LoggingLock() {
201 LockLogging();
202 }
203
204 ~LoggingLock() {
205 UnlockLogging();
206 }
207
208 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
209 if (initialized)
210 return;
211 lock_log_file = lock_log;
212 if (lock_log_file == LOCK_LOG_FILE) {
213#if defined(OS_WIN)
214 if (!log_mutex) {
215 std::wstring safe_name;
216 if (new_log_file)
217 safe_name = new_log_file;
218 else
[email protected]5f95d532010-10-01 17:16:58219 safe_name = GetDefaultLogFile();
[email protected]5b84fe32010-09-14 22:24:55220 // \ is not a legal character in mutex names so we replace \ with /
221 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
222 std::wstring t(L"Global\\");
223 t.append(safe_name);
224 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
[email protected]5f95d532010-10-01 17:16:58225
226 if (log_mutex == NULL) {
227#if DEBUG
228 // Keep the error code for debugging
229 int error = GetLastError(); // NOLINT
[email protected]58580352010-10-26 04:07:50230 base::debug::BreakDebugger();
[email protected]5f95d532010-10-01 17:16:58231#endif
232 // Return nicely without putting initialized to true.
233 return;
234 }
[email protected]5b84fe32010-09-14 22:24:55235 }
236#endif
237 } else {
[email protected]bc581a682011-01-01 23:16:20238 log_lock = new base::internal::LockImpl();
[email protected]5b84fe32010-09-14 22:24:55239 }
240 initialized = true;
241 }
242
243 private:
244 static void LockLogging() {
245 if (lock_log_file == LOCK_LOG_FILE) {
246#if defined(OS_WIN)
247 ::WaitForSingleObject(log_mutex, INFINITE);
248 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
249 // abort the process here. UI tests might be crashy sometimes,
250 // and aborting the test binary only makes the problem worse.
251 // We also don't use LOG macros because that might lead to an infinite
252 // loop. For more info see http://crbug.com/18028.
253#elif defined(OS_POSIX)
254 pthread_mutex_lock(&log_mutex);
255#endif
256 } else {
257 // use the lock
258 log_lock->Lock();
259 }
260 }
261
262 static void UnlockLogging() {
263 if (lock_log_file == LOCK_LOG_FILE) {
264#if defined(OS_WIN)
265 ReleaseMutex(log_mutex);
266#elif defined(OS_POSIX)
267 pthread_mutex_unlock(&log_mutex);
268#endif
269 } else {
270 log_lock->Unlock();
271 }
272 }
273
274 // The lock is used if log file locking is false. It helps us avoid problems
275 // with multiple threads writing to the log file at the same time. Use
276 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20277 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55278
279 // When we don't use a lock, we are using a global mutex. We need to do this
280 // because LockFileEx is not thread safe.
281#if defined(OS_WIN)
282 static MutexHandle log_mutex;
283#elif defined(OS_POSIX)
284 static pthread_mutex_t log_mutex;
285#endif
286
287 static bool initialized;
288 static LogLockingState lock_log_file;
289};
290
291// static
292bool LoggingLock::initialized = false;
293// static
[email protected]bc581a682011-01-01 23:16:20294base::internal::LockImpl* LoggingLock::log_lock = NULL;
[email protected]5b84fe32010-09-14 22:24:55295// static
296LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
297
298#if defined(OS_WIN)
299// static
300MutexHandle LoggingLock::log_mutex = NULL;
301#elif defined(OS_POSIX)
302pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
303#endif
304
initial.commitd7cae122008-07-26 21:49:38305// Called by logging functions to ensure that debug_file is initialized
306// and can be used for writing. Returns false if the file could not be
307// initialized. debug_file will be NULL in this case.
308bool InitializeLogFileHandle() {
309 if (log_file)
310 return true;
311
[email protected]614e9fa2008-08-11 22:52:59312 if (!log_file_name) {
313 // Nobody has called InitLogging to specify a debug log file, so here we
314 // initialize the log file name to a default.
[email protected]5f95d532010-10-01 17:16:58315 log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38316 }
317
[email protected]5e3f7c22013-06-21 21:15:33318 if ((logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59319#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32320 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38321 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
322 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
323 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32324 // try the current directory
325 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
326 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
327 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
328 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
329 log_file = NULL;
330 return false;
331 }
initial.commitd7cae122008-07-26 21:49:38332 }
[email protected]1d8c2702008-08-19 23:39:32333 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11334#elif defined(OS_POSIX)
335 log_file = fopen(log_file_name->c_str(), "a");
336 if (log_file == NULL)
337 return false;
[email protected]f6abeba2008-08-08 13:27:28338#endif
[email protected]1d8c2702008-08-19 23:39:32339 }
340
initial.commitd7cae122008-07-26 21:49:38341 return true;
342}
343
[email protected]064aa162011-12-03 00:30:08344} // namespace
345
[email protected]5e3f7c22013-06-21 21:15:33346LoggingSettings::LoggingSettings()
347 : logging_dest(LOG_DEFAULT),
348 log_file(NULL),
349 lock_log(LOCK_LOG_FILE),
350 delete_old(APPEND_TO_OLD_LOG_FILE),
351 dcheck_state(DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) {}
[email protected]064aa162011-12-03 00:30:08352
[email protected]5e3f7c22013-06-21 21:15:33353bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45354#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33355 // Can log only to the system debug log.
356 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45357#endif
[email protected]5e3f7c22013-06-21 21:15:33358 g_dcheck_state = settings.dcheck_state;
[email protected]380d8322012-02-28 21:35:44359 CommandLine* command_line = CommandLine::ForCurrentProcess();
[email protected]99b7c57f2010-09-29 19:26:36360 // Don't bother initializing g_vlog_info unless we use one of the
361 // vlog switches.
362 if (command_line->HasSwitch(switches::kV) ||
363 command_line->HasSwitch(switches::kVModule)) {
[email protected]064aa162011-12-03 00:30:08364 // NOTE: If g_vlog_info has already been initialized, it might be in use
365 // by another thread. Don't delete the old VLogInfo, just create a second
366 // one. We keep track of both to avoid memory leak warnings.
367 CHECK(!g_vlog_info_prev);
368 g_vlog_info_prev = g_vlog_info;
369
[email protected]99b7c57f2010-09-29 19:26:36370 g_vlog_info =
371 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49372 command_line->GetSwitchValueASCII(switches::kVModule),
373 &min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36374 }
375
[email protected]5e3f7c22013-06-21 21:15:33376 LoggingLock::Init(settings.lock_log, settings.log_file);
[email protected]5b84fe32010-09-14 22:24:55377
378 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38379
380 if (log_file) {
381 // calling InitLogging twice or after some log call has already opened the
382 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28383 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38384 log_file = NULL;
385 }
386
[email protected]5e3f7c22013-06-21 21:15:33387 logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38388
[email protected]5e3f7c22013-06-21 21:15:33389 // ignore file options unless logging to file is set.
390 if ((logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21391 return true;
initial.commitd7cae122008-07-26 21:49:38392
[email protected]614e9fa2008-08-11 22:52:59393 if (!log_file_name)
394 log_file_name = new PathString();
[email protected]5e3f7c22013-06-21 21:15:33395 *log_file_name = settings.log_file;
396 if (settings.delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59397 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38398
[email protected]c7d5da992010-10-28 00:20:21399 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38400}
401
402void SetMinLogLevel(int level) {
[email protected]deba0ff2010-11-03 05:30:14403 min_log_level = std::min(LOG_ERROR_REPORT, level);
initial.commitd7cae122008-07-26 21:49:38404}
405
406int GetMinLogLevel() {
407 return min_log_level;
408}
409
[email protected]162ac0f2010-11-04 15:50:49410int GetVlogVerbosity() {
411 return std::max(-1, LOG_INFO - GetMinLogLevel());
412}
413
[email protected]99b7c57f2010-09-29 19:26:36414int GetVlogLevelHelper(const char* file, size_t N) {
415 DCHECK_GT(N, 0U);
[email protected]064aa162011-12-03 00:30:08416 // Note: g_vlog_info may change on a different thread during startup
417 // (but will always be valid or NULL).
418 VlogInfo* vlog_info = g_vlog_info;
419 return vlog_info ?
420 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49421 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36422}
423
initial.commitd7cae122008-07-26 21:49:38424void SetLogItems(bool enable_process_id, bool enable_thread_id,
425 bool enable_timestamp, bool enable_tickcount) {
426 log_process_id = enable_process_id;
427 log_thread_id = enable_thread_id;
428 log_timestamp = enable_timestamp;
429 log_tickcount = enable_tickcount;
430}
431
[email protected]81e0a852010-08-17 00:38:12432void SetShowErrorDialogs(bool enable_dialogs) {
433 show_error_dialogs = enable_dialogs;
434}
435
initial.commitd7cae122008-07-26 21:49:38436void SetLogAssertHandler(LogAssertHandlerFunction handler) {
437 log_assert_handler = handler;
438}
439
[email protected]fb62a532009-02-12 01:19:05440void SetLogReportHandler(LogReportHandlerFunction handler) {
441 log_report_handler = handler;
442}
443
[email protected]2b07b8412009-11-25 15:26:34444void SetLogMessageHandler(LogMessageHandlerFunction handler) {
445 log_message_handler = handler;
446}
447
[email protected]64e5cc02010-11-03 19:20:27448LogMessageHandlerFunction GetLogMessageHandler() {
449 return log_message_handler;
450}
451
[email protected]6d445d32010-09-30 19:10:03452// MSVC doesn't like complex extern templates and DLLs.
453#if !defined(COMPILER_MSVC)
454// Explicit instantiations for commonly used comparisons.
455template std::string* MakeCheckOpString<int, int>(
456 const int&, const int&, const char* names);
457template std::string* MakeCheckOpString<unsigned long, unsigned long>(
458 const unsigned long&, const unsigned long&, const char* names);
459template std::string* MakeCheckOpString<unsigned long, unsigned int>(
460 const unsigned long&, const unsigned int&, const char* names);
461template std::string* MakeCheckOpString<unsigned int, unsigned long>(
462 const unsigned int&, const unsigned long&, const char* names);
463template std::string* MakeCheckOpString<std::string, std::string>(
464 const std::string&, const std::string&, const char* name);
465#endif
[email protected]2b07b8412009-11-25 15:26:34466
[email protected]d81baca42010-03-01 13:10:22467// Displays a message box to the user with the error message in it.
468// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25469// This is for developers only; we don't use this in circumstances
470// (like release builds) where users could see it, since users don't
471// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22472void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38473 if (str.empty())
474 return;
475
[email protected]81e0a852010-08-17 00:38:12476 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44477 return;
478
[email protected]f6abeba2008-08-08 13:27:28479#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22480 // For Windows programs, it's possible that the message loop is
481 // messed up on a fatal error, and creating a MessageBox will cause
482 // that message loop to be run. Instead, we try to spawn another
483 // process that displays its command line. We look for "Debug
484 // Message.exe" in the same directory as the application. If it
485 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38486 wchar_t prog_name[MAX_PATH];
487 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
488 wchar_t* backslash = wcsrchr(prog_name, '\\');
489 if (backslash)
490 backslash[1] = 0;
491 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
492
[email protected]047a03f2009-10-07 02:10:20493 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02494 if (cmdline.empty())
495 return;
initial.commitd7cae122008-07-26 21:49:38496
497 STARTUPINFO startup_info;
498 memset(&startup_info, 0, sizeof(startup_info));
499 startup_info.cb = sizeof(startup_info);
500
501 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02502 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38503 NULL, &startup_info, &process_info)) {
504 WaitForSingleObject(process_info.hProcess, INFINITE);
505 CloseHandle(process_info.hThread);
506 CloseHandle(process_info.hProcess);
507 } else {
508 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02509 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38510 MB_OK | MB_ICONHAND | MB_TOPMOST);
511 }
[email protected]f6abeba2008-08-08 13:27:28512#else
[email protected]561513f2010-12-16 23:29:25513 // We intentionally don't implement a dialog on other platforms.
514 // You can just look at stderr.
[email protected]f6abeba2008-08-08 13:27:28515#endif
initial.commitd7cae122008-07-26 21:49:38516}
517
[email protected]3f85caa2009-04-14 16:52:11518#if defined(OS_WIN)
519LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
520}
521
522LogMessage::SaveLastError::~SaveLastError() {
523 ::SetLastError(last_error_);
524}
525#endif // defined(OS_WIN)
526
initial.commitd7cae122008-07-26 21:49:38527LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
528 int ctr)
[email protected]162ac0f2010-11-04 15:50:49529 : severity_(severity), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38530 Init(file, line);
531}
532
[email protected]eae9c062011-01-11 00:50:59533LogMessage::LogMessage(const char* file, int line)
534 : severity_(LOG_INFO), file_(file), line_(line) {
535 Init(file, line);
536}
537
538LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
539 : severity_(severity), file_(file), line_(line) {
540 Init(file, line);
541}
542
[email protected]9c7132e2011-02-08 07:39:08543LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49544 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38545 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08546 stream_ << "Check failed: " << *result;
547 delete result;
initial.commitd7cae122008-07-26 21:49:38548}
549
[email protected]fb62a532009-02-12 01:19:05550LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08551 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49552 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05553 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08554 stream_ << "Check failed: " << *result;
555 delete result;
[email protected]fb62a532009-02-12 01:19:05556}
557
initial.commitd7cae122008-07-26 21:49:38558LogMessage::~LogMessage() {
[email protected]22d955692013-07-04 06:04:46559#if !defined(NDEBUG) && !defined(OS_NACL)
[email protected]d1ccc35a2010-03-24 05:03:24560 if (severity_ == LOG_FATAL) {
561 // Include a stack trace on a fatal.
[email protected]58580352010-10-26 04:07:50562 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24563 stream_ << std::endl; // Newline to separate from log message.
564 trace.OutputToStream(&stream_);
565 }
[email protected]1d8c2702008-08-19 23:39:32566#endif
[email protected]d1ccc35a2010-03-24 05:03:24567 stream_ << std::endl;
568 std::string str_newline(stream_.str());
569
[email protected]2b07b8412009-11-25 15:26:34570 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33571 if (log_message_handler &&
572 log_message_handler(severity_, file_, line_,
573 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49574 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34575 return;
[email protected]162ac0f2010-11-04 15:50:49576 }
initial.commitd7cae122008-07-26 21:49:38577
[email protected]5e3f7c22013-06-21 21:15:33578 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28579#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38580 OutputDebugStringA(str_newline.c_str());
[email protected]3132e35c2011-07-07 20:46:50581#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25582 android_LogPriority priority =
583 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50584 switch (severity_) {
585 case LOG_INFO:
586 priority = ANDROID_LOG_INFO;
587 break;
588 case LOG_WARNING:
589 priority = ANDROID_LOG_WARN;
590 break;
591 case LOG_ERROR:
592 case LOG_ERROR_REPORT:
593 priority = ANDROID_LOG_ERROR;
594 break;
595 case LOG_FATAL:
596 priority = ANDROID_LOG_FATAL;
597 break;
598 }
599 __android_log_write(priority, "chromium", 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
[email protected]5e3f7c22013-06-21 21:15:33620 if ((logging_destination & LOG_TO_FILE) != 0) {
[email protected]5b84fe32010-09-14 22:24:55621 LoggingLock logging_lock;
622 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28623#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55624 SetFilePointer(log_file, 0, 0, SEEK_END);
625 DWORD num_written;
626 WriteFile(log_file,
627 static_cast<const void*>(str_newline.c_str()),
628 static_cast<DWORD>(str_newline.length()),
629 &num_written,
630 NULL);
[email protected]cba21962010-08-31 22:35:55631#else
[email protected]5b84fe32010-09-14 22:24:55632 fprintf(log_file, "%s", str_newline.c_str());
633 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55634#endif
initial.commitd7cae122008-07-26 21:49:38635 }
636 }
637
638 if (severity_ == LOG_FATAL) {
[email protected]eb4c4d032012-04-03 18:45:05639 // Ensure the first characters of the string are on the stack so they
640 // are contained in minidumps for diagnostic purposes.
641 char str_stack[1024];
642 str_newline.copy(str_stack, arraysize(str_stack));
643 base::debug::Alias(str_stack);
644
initial.commitd7cae122008-07-26 21:49:38645 // display a message or break into the debugger on a fatal error
[email protected]58580352010-10-26 04:07:50646 if (base::debug::BeingDebugged()) {
647 base::debug::BreakDebugger();
[email protected]1ffe08c12008-08-13 11:15:11648 } else {
initial.commitd7cae122008-07-26 21:49:38649 if (log_assert_handler) {
650 // make a copy of the string for the handler out of paranoia
651 log_assert_handler(std::string(stream_.str()));
652 } else {
[email protected]4d5901272008-11-06 00:33:50653 // Don't use the string with the newline, get a fresh version to send to
654 // the debug message process. We also don't display assertions to the
655 // user in release mode. The enduser can't do anything with this
656 // information, and displaying message boxes when the application is
657 // hosed can cause additional problems.
658#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22659 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50660#endif
initial.commitd7cae122008-07-26 21:49:38661 // Crash the process to generate a dump.
[email protected]58580352010-10-26 04:07:50662 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38663 }
664 }
[email protected]fb62a532009-02-12 01:19:05665 } else if (severity_ == LOG_ERROR_REPORT) {
666 // We are here only if the user runs with --enable-dcheck in release mode.
667 if (log_report_handler) {
668 log_report_handler(std::string(stream_.str()));
669 } else {
[email protected]d81baca42010-03-01 13:10:22670 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05671 }
initial.commitd7cae122008-07-26 21:49:38672 }
673}
674
[email protected]eae9c062011-01-11 00:50:59675// writes the common header info to the stream
676void LogMessage::Init(const char* file, int line) {
677 base::StringPiece filename(file);
678 size_t last_slash_pos = filename.find_last_of("\\/");
679 if (last_slash_pos != base::StringPiece::npos)
680 filename.remove_prefix(last_slash_pos + 1);
681
682 // TODO(darin): It might be nice if the columns were fixed width.
683
684 stream_ << '[';
685 if (log_process_id)
686 stream_ << CurrentProcessId() << ':';
687 if (log_thread_id)
[email protected]63e66802012-01-18 21:21:09688 stream_ << base::PlatformThread::CurrentId() << ':';
[email protected]eae9c062011-01-11 00:50:59689 if (log_timestamp) {
690 time_t t = time(NULL);
691 struct tm local_time = {0};
692#if _MSC_VER >= 1400
693 localtime_s(&local_time, &t);
694#else
695 localtime_r(&t, &local_time);
696#endif
697 struct tm* tm_time = &local_time;
698 stream_ << std::setfill('0')
699 << std::setw(2) << 1 + tm_time->tm_mon
700 << std::setw(2) << tm_time->tm_mday
701 << '/'
702 << std::setw(2) << tm_time->tm_hour
703 << std::setw(2) << tm_time->tm_min
704 << std::setw(2) << tm_time->tm_sec
705 << ':';
706 }
707 if (log_tickcount)
708 stream_ << TickCount() << ':';
709 if (severity_ >= 0)
710 stream_ << log_severity_names[severity_];
711 else
712 stream_ << "VERBOSE" << -severity_;
713
714 stream_ << ":" << filename << "(" << line << ")] ";
715
716 message_start_ = stream_.tellp();
717}
718
[email protected]d8617a62009-10-09 23:52:20719#if defined(OS_WIN)
720// This has already been defined in the header, but defining it again as DWORD
721// ensures that the type used in the header is equivalent to DWORD. If not,
722// the redefinition is a compile error.
723typedef DWORD SystemErrorCode;
724#endif
725
726SystemErrorCode GetLastSystemErrorCode() {
727#if defined(OS_WIN)
728 return ::GetLastError();
729#elif defined(OS_POSIX)
730 return errno;
731#else
732#error Not implemented
733#endif
734}
735
736#if defined(OS_WIN)
737Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
738 int line,
739 LogSeverity severity,
740 SystemErrorCode err,
741 const char* module)
742 : err_(err),
743 module_(module),
744 log_message_(file, line, severity) {
745}
746
747Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
748 int line,
749 LogSeverity severity,
750 SystemErrorCode err)
751 : err_(err),
752 module_(NULL),
753 log_message_(file, line, severity) {
754}
755
756Win32ErrorLogMessage::~Win32ErrorLogMessage() {
757 const int error_message_buffer_size = 256;
758 char msgbuf[error_message_buffer_size];
[email protected]6ac3df52010-10-20 01:33:32759 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
[email protected]d8617a62009-10-09 23:52:20760 HMODULE hmod;
761 if (module_) {
762 hmod = GetModuleHandleA(module_);
763 if (hmod) {
764 flags |= FORMAT_MESSAGE_FROM_HMODULE;
765 } else {
766 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
767 // so it will not call GetModuleHandle, so recursive errors are
768 // impossible.
769 DPLOG(WARNING) << "Couldn't open module " << module_
770 << " for error message query";
771 }
772 } else {
773 hmod = NULL;
774 }
775 DWORD len = FormatMessageA(flags,
776 hmod,
777 err_,
[email protected]6ac3df52010-10-20 01:33:32778 0,
[email protected]d8617a62009-10-09 23:52:20779 msgbuf,
780 sizeof(msgbuf) / sizeof(msgbuf[0]),
781 NULL);
782 if (len) {
783 while ((len > 0) &&
784 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
785 msgbuf[--len] = 0;
786 }
787 stream() << ": " << msgbuf;
788 } else {
789 stream() << ": Error " << GetLastError() << " while retrieving error "
790 << err_;
791 }
[email protected]20909e72012-04-05 16:57:06792 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
793 // field) and use Alias in hopes that it makes it into crash dumps.
794 DWORD last_error = err_;
795 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20796}
797#elif defined(OS_POSIX)
798ErrnoLogMessage::ErrnoLogMessage(const char* file,
799 int line,
800 LogSeverity severity,
801 SystemErrorCode err)
802 : err_(err),
803 log_message_(file, line, severity) {
804}
805
806ErrnoLogMessage::~ErrnoLogMessage() {
807 stream() << ": " << safe_strerror(err_);
808}
809#endif // OS_WIN
810
initial.commitd7cae122008-07-26 21:49:38811void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55812 LoggingLock logging_lock;
813
initial.commitd7cae122008-07-26 21:49:38814 if (!log_file)
815 return;
816
[email protected]f6abeba2008-08-08 13:27:28817 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38818 log_file = NULL;
819}
820
[email protected]e36ddc82009-12-08 04:22:50821void RawLog(int level, const char* message) {
822 if (level >= min_log_level) {
823 size_t bytes_written = 0;
824 const size_t message_len = strlen(message);
825 int rv;
826 while (bytes_written < message_len) {
827 rv = HANDLE_EINTR(
828 write(STDERR_FILENO, message + bytes_written,
829 message_len - bytes_written));
830 if (rv < 0) {
831 // Give up, nothing we can do now.
832 break;
833 }
834 bytes_written += rv;
835 }
836
837 if (message_len > 0 && message[message_len - 1] != '\n') {
838 do {
839 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
840 if (rv < 0) {
841 // Give up, nothing we can do now.
842 break;
843 }
844 } while (rv != 1);
845 }
846 }
847
848 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50849 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50850}
851
[email protected]34a907732012-01-20 06:33:27852// This was defined at the beginning of this file.
853#undef write
854
[email protected]f01b88a2013-02-27 22:04:00855#if defined(OS_WIN)
856std::wstring GetLogFileFullPath() {
857 if (log_file_name)
858 return *log_file_name;
859 return std::wstring();
860}
861#endif
862
[email protected]96fd0032009-04-24 00:13:08863} // namespace logging
initial.commitd7cae122008-07-26 21:49:38864
865std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20866 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38867}