blob: a1ba1b322e0aec6ca28443b91d7a2f2fb1a606c6 [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]c914d8a2014-04-23 01:11:0146#include <string>
[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]eb4c4d032012-04-03 18:45:0550#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5051#include "base/debug/debugger.h"
52#include "base/debug/stack_trace.h"
[email protected]2025d002012-11-14 20:54:3553#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0054#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0155#include "base/strings/string_util.h"
56#include "base/strings/stringprintf.h"
[email protected]a4ea1f12013-06-07 18:37:0757#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2058#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0959#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3660#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0461#if defined(OS_POSIX)
62#include "base/safe_strerror_posix.h"
63#endif
[email protected]52a261f2009-03-03 15:01:1264
[email protected]3132e35c2011-07-07 20:46:5065#if defined(OS_ANDROID)
66#include <android/log.h>
67#endif
68
initial.commitd7cae122008-07-26 21:49:3869namespace logging {
70
[email protected]064aa162011-12-03 00:30:0871namespace {
72
[email protected]99b7c57f2010-09-29 19:26:3673VlogInfo* g_vlog_info = NULL;
[email protected]064aa162011-12-03 00:30:0874VlogInfo* g_vlog_info_prev = NULL;
initial.commitd7cae122008-07-26 21:49:3875
76const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]f2c05492014-06-17 12:04:2377 "INFO", "WARNING", "ERROR", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3878
[email protected]80f360a2014-01-23 01:36:1979const char* log_severity_name(int severity)
80{
81 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
82 return log_severity_names[severity];
83 return "UNKNOWN";
84}
85
initial.commitd7cae122008-07-26 21:49:3886int 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]2b07b8412009-11-25 15:26:34118// A log message handler that gets notified of every log message we process.
119LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38120
[email protected]f6abeba2008-08-08 13:27:28121// Helper functions to wrap platform differences.
122
[email protected]f8588472008-11-05 23:17:24123int32 CurrentProcessId() {
124#if defined(OS_WIN)
125 return GetCurrentProcessId();
126#elif defined(OS_POSIX)
127 return getpid();
128#endif
129}
130
[email protected]f8588472008-11-05 23:17:24131uint64 TickCount() {
132#if defined(OS_WIN)
133 return GetTickCount();
134#elif defined(OS_MACOSX)
135 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08136#elif defined(OS_NACL)
137 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
138 // So we have to use clock() for now.
139 return clock();
[email protected]e43eddf12009-12-29 00:32:52140#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07141 struct timespec ts;
142 clock_gettime(CLOCK_MONOTONIC, &ts);
143
144 uint64 absolute_micro =
145 static_cast<int64>(ts.tv_sec) * 1000000 +
146 static_cast<int64>(ts.tv_nsec) / 1000;
147
148 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24149#endif
150}
151
[email protected]614e9fa2008-08-11 22:52:59152void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28153#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59154 DeleteFile(log_name.c_str());
[email protected]ac07ec52013-04-22 17:32:45155#elif defined (OS_NACL)
156 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28157#else
[email protected]614e9fa2008-08-11 22:52:59158 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28159#endif
160}
initial.commitd7cae122008-07-26 21:49:38161
[email protected]5f95d532010-10-01 17:16:58162PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55163#if defined(OS_WIN)
164 // On Windows we use the same path as the exe.
165 wchar_t module_name[MAX_PATH];
166 GetModuleFileName(NULL, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58167
168 PathString log_file = module_name;
169 PathString::size_type last_backslash =
170 log_file.rfind('\\', log_file.size());
171 if (last_backslash != PathString::npos)
172 log_file.erase(last_backslash + 1);
173 log_file += L"debug.log";
174 return log_file;
[email protected]5b84fe32010-09-14 22:24:55175#elif defined(OS_POSIX)
176 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58177 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55178#endif
179}
180
181// This class acts as a wrapper for locking the logging files.
182// LoggingLock::Init() should be called from the main thread before any logging
183// is done. Then whenever logging, be sure to have a local LoggingLock
184// instance on the stack. This will ensure that the lock is unlocked upon
185// exiting the frame.
186// LoggingLocks can not be nested.
187class LoggingLock {
188 public:
189 LoggingLock() {
190 LockLogging();
191 }
192
193 ~LoggingLock() {
194 UnlockLogging();
195 }
196
197 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
198 if (initialized)
199 return;
200 lock_log_file = lock_log;
201 if (lock_log_file == LOCK_LOG_FILE) {
202#if defined(OS_WIN)
203 if (!log_mutex) {
204 std::wstring safe_name;
205 if (new_log_file)
206 safe_name = new_log_file;
207 else
[email protected]5f95d532010-10-01 17:16:58208 safe_name = GetDefaultLogFile();
[email protected]5b84fe32010-09-14 22:24:55209 // \ is not a legal character in mutex names so we replace \ with /
210 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
211 std::wstring t(L"Global\\");
212 t.append(safe_name);
213 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
[email protected]5f95d532010-10-01 17:16:58214
215 if (log_mutex == NULL) {
216#if DEBUG
217 // Keep the error code for debugging
218 int error = GetLastError(); // NOLINT
[email protected]58580352010-10-26 04:07:50219 base::debug::BreakDebugger();
[email protected]5f95d532010-10-01 17:16:58220#endif
221 // Return nicely without putting initialized to true.
222 return;
223 }
[email protected]5b84fe32010-09-14 22:24:55224 }
225#endif
226 } else {
[email protected]bc581a682011-01-01 23:16:20227 log_lock = new base::internal::LockImpl();
[email protected]5b84fe32010-09-14 22:24:55228 }
229 initialized = true;
230 }
231
232 private:
233 static void LockLogging() {
234 if (lock_log_file == LOCK_LOG_FILE) {
235#if defined(OS_WIN)
236 ::WaitForSingleObject(log_mutex, INFINITE);
237 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
238 // abort the process here. UI tests might be crashy sometimes,
239 // and aborting the test binary only makes the problem worse.
240 // We also don't use LOG macros because that might lead to an infinite
241 // loop. For more info see http://crbug.com/18028.
242#elif defined(OS_POSIX)
243 pthread_mutex_lock(&log_mutex);
244#endif
245 } else {
246 // use the lock
247 log_lock->Lock();
248 }
249 }
250
251 static void UnlockLogging() {
252 if (lock_log_file == LOCK_LOG_FILE) {
253#if defined(OS_WIN)
254 ReleaseMutex(log_mutex);
255#elif defined(OS_POSIX)
256 pthread_mutex_unlock(&log_mutex);
257#endif
258 } else {
259 log_lock->Unlock();
260 }
261 }
262
263 // The lock is used if log file locking is false. It helps us avoid problems
264 // with multiple threads writing to the log file at the same time. Use
265 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20266 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55267
268 // When we don't use a lock, we are using a global mutex. We need to do this
269 // because LockFileEx is not thread safe.
270#if defined(OS_WIN)
271 static MutexHandle log_mutex;
272#elif defined(OS_POSIX)
273 static pthread_mutex_t log_mutex;
274#endif
275
276 static bool initialized;
277 static LogLockingState lock_log_file;
278};
279
280// static
281bool LoggingLock::initialized = false;
282// static
[email protected]bc581a682011-01-01 23:16:20283base::internal::LockImpl* LoggingLock::log_lock = NULL;
[email protected]5b84fe32010-09-14 22:24:55284// static
285LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
286
287#if defined(OS_WIN)
288// static
289MutexHandle LoggingLock::log_mutex = NULL;
290#elif defined(OS_POSIX)
291pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
292#endif
293
initial.commitd7cae122008-07-26 21:49:38294// Called by logging functions to ensure that debug_file is initialized
295// and can be used for writing. Returns false if the file could not be
296// initialized. debug_file will be NULL in this case.
297bool InitializeLogFileHandle() {
298 if (log_file)
299 return true;
300
[email protected]614e9fa2008-08-11 22:52:59301 if (!log_file_name) {
302 // Nobody has called InitLogging to specify a debug log file, so here we
303 // initialize the log file name to a default.
[email protected]5f95d532010-10-01 17:16:58304 log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38305 }
306
[email protected]5e3f7c22013-06-21 21:15:33307 if ((logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59308#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32309 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38310 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
311 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
312 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32313 // try the current directory
314 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
315 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
316 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
317 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
318 log_file = NULL;
319 return false;
320 }
initial.commitd7cae122008-07-26 21:49:38321 }
[email protected]1d8c2702008-08-19 23:39:32322 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11323#elif defined(OS_POSIX)
324 log_file = fopen(log_file_name->c_str(), "a");
325 if (log_file == NULL)
326 return false;
[email protected]f6abeba2008-08-08 13:27:28327#endif
[email protected]1d8c2702008-08-19 23:39:32328 }
329
initial.commitd7cae122008-07-26 21:49:38330 return true;
331}
332
[email protected]17dcf752013-07-15 21:47:09333void CloseFile(FileHandle log) {
334#if defined(OS_WIN)
335 CloseHandle(log);
336#else
337 fclose(log);
338#endif
339}
340
341void CloseLogFileUnlocked() {
342 if (!log_file)
343 return;
344
345 CloseFile(log_file);
346 log_file = NULL;
347}
348
[email protected]064aa162011-12-03 00:30:08349} // namespace
350
[email protected]5e3f7c22013-06-21 21:15:33351LoggingSettings::LoggingSettings()
352 : logging_dest(LOG_DEFAULT),
353 log_file(NULL),
354 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38355 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08356
[email protected]5e3f7c22013-06-21 21:15:33357bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45358#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33359 // Can log only to the system debug log.
360 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45361#endif
[email protected]380d8322012-02-28 21:35:44362 CommandLine* command_line = CommandLine::ForCurrentProcess();
[email protected]99b7c57f2010-09-29 19:26:36363 // Don't bother initializing g_vlog_info unless we use one of the
364 // vlog switches.
365 if (command_line->HasSwitch(switches::kV) ||
366 command_line->HasSwitch(switches::kVModule)) {
[email protected]064aa162011-12-03 00:30:08367 // NOTE: If g_vlog_info has already been initialized, it might be in use
368 // by another thread. Don't delete the old VLogInfo, just create a second
369 // one. We keep track of both to avoid memory leak warnings.
370 CHECK(!g_vlog_info_prev);
371 g_vlog_info_prev = g_vlog_info;
372
[email protected]99b7c57f2010-09-29 19:26:36373 g_vlog_info =
374 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49375 command_line->GetSwitchValueASCII(switches::kVModule),
376 &min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36377 }
378
[email protected]5e3f7c22013-06-21 21:15:33379 logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38380
[email protected]5e3f7c22013-06-21 21:15:33381 // ignore file options unless logging to file is set.
382 if ((logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21383 return true;
initial.commitd7cae122008-07-26 21:49:38384
[email protected]17dcf752013-07-15 21:47:09385 LoggingLock::Init(settings.lock_log, settings.log_file);
386 LoggingLock logging_lock;
387
388 // Calling InitLogging twice or after some log call has already opened the
389 // default log file will re-initialize to the new options.
390 CloseLogFileUnlocked();
391
[email protected]614e9fa2008-08-11 22:52:59392 if (!log_file_name)
393 log_file_name = new PathString();
[email protected]5e3f7c22013-06-21 21:15:33394 *log_file_name = settings.log_file;
395 if (settings.delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59396 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38397
[email protected]c7d5da992010-10-28 00:20:21398 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38399}
400
401void SetMinLogLevel(int level) {
[email protected]f2c05492014-06-17 12:04:23402 min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38403}
404
405int GetMinLogLevel() {
406 return min_log_level;
407}
408
[email protected]162ac0f2010-11-04 15:50:49409int GetVlogVerbosity() {
410 return std::max(-1, LOG_INFO - GetMinLogLevel());
411}
412
[email protected]99b7c57f2010-09-29 19:26:36413int GetVlogLevelHelper(const char* file, size_t N) {
414 DCHECK_GT(N, 0U);
[email protected]064aa162011-12-03 00:30:08415 // Note: g_vlog_info may change on a different thread during startup
416 // (but will always be valid or NULL).
417 VlogInfo* vlog_info = g_vlog_info;
418 return vlog_info ?
419 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49420 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36421}
422
initial.commitd7cae122008-07-26 21:49:38423void SetLogItems(bool enable_process_id, bool enable_thread_id,
424 bool enable_timestamp, bool enable_tickcount) {
425 log_process_id = enable_process_id;
426 log_thread_id = enable_thread_id;
427 log_timestamp = enable_timestamp;
428 log_tickcount = enable_tickcount;
429}
430
[email protected]81e0a852010-08-17 00:38:12431void SetShowErrorDialogs(bool enable_dialogs) {
432 show_error_dialogs = enable_dialogs;
433}
434
initial.commitd7cae122008-07-26 21:49:38435void SetLogAssertHandler(LogAssertHandlerFunction handler) {
436 log_assert_handler = handler;
437}
438
[email protected]2b07b8412009-11-25 15:26:34439void SetLogMessageHandler(LogMessageHandlerFunction handler) {
440 log_message_handler = handler;
441}
442
[email protected]64e5cc02010-11-03 19:20:27443LogMessageHandlerFunction GetLogMessageHandler() {
444 return log_message_handler;
445}
446
[email protected]6d445d32010-09-30 19:10:03447// MSVC doesn't like complex extern templates and DLLs.
448#if !defined(COMPILER_MSVC)
449// Explicit instantiations for commonly used comparisons.
450template std::string* MakeCheckOpString<int, int>(
451 const int&, const int&, const char* names);
452template std::string* MakeCheckOpString<unsigned long, unsigned long>(
453 const unsigned long&, const unsigned long&, const char* names);
454template std::string* MakeCheckOpString<unsigned long, unsigned int>(
455 const unsigned long&, const unsigned int&, const char* names);
456template std::string* MakeCheckOpString<unsigned int, unsigned long>(
457 const unsigned int&, const unsigned long&, const char* names);
458template std::string* MakeCheckOpString<std::string, std::string>(
459 const std::string&, const std::string&, const char* name);
460#endif
[email protected]2b07b8412009-11-25 15:26:34461
[email protected]f2c05492014-06-17 12:04:23462#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22463// Displays a message box to the user with the error message in it.
464// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25465// This is for developers only; we don't use this in circumstances
466// (like release builds) where users could see it, since users don't
467// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22468void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38469 if (str.empty())
470 return;
471
[email protected]81e0a852010-08-17 00:38:12472 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44473 return;
474
[email protected]f6abeba2008-08-08 13:27:28475#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22476 // For Windows programs, it's possible that the message loop is
477 // messed up on a fatal error, and creating a MessageBox will cause
478 // that message loop to be run. Instead, we try to spawn another
479 // process that displays its command line. We look for "Debug
480 // Message.exe" in the same directory as the application. If it
481 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38482 wchar_t prog_name[MAX_PATH];
483 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
484 wchar_t* backslash = wcsrchr(prog_name, '\\');
485 if (backslash)
486 backslash[1] = 0;
487 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
488
[email protected]f729d7a2013-12-26 07:07:56489 std::wstring cmdline = base::UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02490 if (cmdline.empty())
491 return;
initial.commitd7cae122008-07-26 21:49:38492
493 STARTUPINFO startup_info;
494 memset(&startup_info, 0, sizeof(startup_info));
495 startup_info.cb = sizeof(startup_info);
496
497 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02498 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38499 NULL, &startup_info, &process_info)) {
500 WaitForSingleObject(process_info.hProcess, INFINITE);
501 CloseHandle(process_info.hThread);
502 CloseHandle(process_info.hProcess);
503 } else {
504 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02505 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38506 MB_OK | MB_ICONHAND | MB_TOPMOST);
507 }
[email protected]f6abeba2008-08-08 13:27:28508#else
[email protected]561513f2010-12-16 23:29:25509 // We intentionally don't implement a dialog on other platforms.
510 // You can just look at stderr.
[email protected]f6abeba2008-08-08 13:27:28511#endif
initial.commitd7cae122008-07-26 21:49:38512}
[email protected]f2c05492014-06-17 12:04:23513#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38514
[email protected]3f85caa2009-04-14 16:52:11515#if defined(OS_WIN)
516LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
517}
518
519LogMessage::SaveLastError::~SaveLastError() {
520 ::SetLastError(last_error_);
521}
522#endif // defined(OS_WIN)
523
initial.commitd7cae122008-07-26 21:49:38524LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
525 int ctr)
[email protected]162ac0f2010-11-04 15:50:49526 : severity_(severity), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38527 Init(file, line);
528}
529
[email protected]eae9c062011-01-11 00:50:59530LogMessage::LogMessage(const char* file, int line)
531 : severity_(LOG_INFO), file_(file), line_(line) {
532 Init(file, line);
533}
534
535LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
536 : severity_(severity), file_(file), line_(line) {
537 Init(file, line);
538}
539
[email protected]9c7132e2011-02-08 07:39:08540LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49541 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38542 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08543 stream_ << "Check failed: " << *result;
544 delete result;
initial.commitd7cae122008-07-26 21:49:38545}
546
[email protected]fb62a532009-02-12 01:19:05547LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08548 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49549 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05550 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08551 stream_ << "Check failed: " << *result;
552 delete result;
[email protected]fb62a532009-02-12 01:19:05553}
554
initial.commitd7cae122008-07-26 21:49:38555LogMessage::~LogMessage() {
[email protected]145c7052014-04-18 23:40:16556#if !defined(NDEBUG) && !defined(OS_NACL) && !defined(__UCLIBC__)
[email protected]d1ccc35a2010-03-24 05:03:24557 if (severity_ == LOG_FATAL) {
558 // Include a stack trace on a fatal.
[email protected]58580352010-10-26 04:07:50559 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24560 stream_ << std::endl; // Newline to separate from log message.
561 trace.OutputToStream(&stream_);
562 }
[email protected]1d8c2702008-08-19 23:39:32563#endif
[email protected]d1ccc35a2010-03-24 05:03:24564 stream_ << std::endl;
565 std::string str_newline(stream_.str());
566
[email protected]2b07b8412009-11-25 15:26:34567 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33568 if (log_message_handler &&
569 log_message_handler(severity_, file_, line_,
570 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49571 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34572 return;
[email protected]162ac0f2010-11-04 15:50:49573 }
initial.commitd7cae122008-07-26 21:49:38574
[email protected]5e3f7c22013-06-21 21:15:33575 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28576#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38577 OutputDebugStringA(str_newline.c_str());
[email protected]3132e35c2011-07-07 20:46:50578#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25579 android_LogPriority priority =
580 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50581 switch (severity_) {
582 case LOG_INFO:
583 priority = ANDROID_LOG_INFO;
584 break;
585 case LOG_WARNING:
586 priority = ANDROID_LOG_WARN;
587 break;
588 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50589 priority = ANDROID_LOG_ERROR;
590 break;
591 case LOG_FATAL:
592 priority = ANDROID_LOG_FATAL;
593 break;
594 }
595 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18596#endif
[email protected]51105382014-03-14 17:02:15597 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06598 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31599 } else if (severity_ >= kAlwaysPrintErrorLevel) {
600 // When we're only outputting to a log file, above a certain log level, we
601 // should still output to stderr so that we can better detect and diagnose
602 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15603 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02604 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28605 }
[email protected]52a261f2009-03-03 15:01:12606
initial.commitd7cae122008-07-26 21:49:38607 // write to log file
[email protected]5e3f7c22013-06-21 21:15:33608 if ((logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09609 // We can have multiple threads and/or processes, so try to prevent them
610 // from clobbering each other's writes.
611 // If the client app did not call InitLogging, and the lock has not
612 // been created do it now. We do this on demand, but if two threads try
613 // to do this at the same time, there will be a race condition to create
614 // the lock. This is why InitLogging should be called from the main
615 // thread at the beginning of execution.
616 LoggingLock::Init(LOCK_LOG_FILE, NULL);
[email protected]5b84fe32010-09-14 22:24:55617 LoggingLock logging_lock;
618 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28619#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55620 SetFilePointer(log_file, 0, 0, SEEK_END);
621 DWORD num_written;
622 WriteFile(log_file,
623 static_cast<const void*>(str_newline.c_str()),
624 static_cast<DWORD>(str_newline.length()),
625 &num_written,
626 NULL);
[email protected]cba21962010-08-31 22:35:55627#else
[email protected]51105382014-03-14 17:02:15628 ignore_result(fwrite(
629 str_newline.data(), str_newline.size(), 1, log_file));
[email protected]5b84fe32010-09-14 22:24:55630 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55631#endif
initial.commitd7cae122008-07-26 21:49:38632 }
633 }
634
635 if (severity_ == LOG_FATAL) {
[email protected]eb4c4d032012-04-03 18:45:05636 // Ensure the first characters of the string are on the stack so they
637 // are contained in minidumps for diagnostic purposes.
638 char str_stack[1024];
639 str_newline.copy(str_stack, arraysize(str_stack));
640 base::debug::Alias(str_stack);
641
[email protected]82d89ab2014-02-28 18:25:34642 if (log_assert_handler) {
643 // Make a copy of the string for the handler out of paranoia.
644 log_assert_handler(std::string(stream_.str()));
[email protected]1ffe08c12008-08-13 11:15:11645 } else {
[email protected]82d89ab2014-02-28 18:25:34646 // Don't use the string with the newline, get a fresh version to send to
647 // the debug message process. We also don't display assertions to the
648 // user in release mode. The enduser can't do anything with this
649 // information, and displaying message boxes when the application is
650 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50651#ifndef NDEBUG
[email protected]82d89ab2014-02-28 18:25:34652 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50653#endif
[email protected]82d89ab2014-02-28 18:25:34654 // Crash the process to generate a dump.
655 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38656 }
initial.commitd7cae122008-07-26 21:49:38657 }
658}
659
[email protected]eae9c062011-01-11 00:50:59660// writes the common header info to the stream
661void LogMessage::Init(const char* file, int line) {
662 base::StringPiece filename(file);
663 size_t last_slash_pos = filename.find_last_of("\\/");
664 if (last_slash_pos != base::StringPiece::npos)
665 filename.remove_prefix(last_slash_pos + 1);
666
667 // TODO(darin): It might be nice if the columns were fixed width.
668
669 stream_ << '[';
670 if (log_process_id)
671 stream_ << CurrentProcessId() << ':';
672 if (log_thread_id)
[email protected]63e66802012-01-18 21:21:09673 stream_ << base::PlatformThread::CurrentId() << ':';
[email protected]eae9c062011-01-11 00:50:59674 if (log_timestamp) {
675 time_t t = time(NULL);
676 struct tm local_time = {0};
677#if _MSC_VER >= 1400
678 localtime_s(&local_time, &t);
679#else
680 localtime_r(&t, &local_time);
681#endif
682 struct tm* tm_time = &local_time;
683 stream_ << std::setfill('0')
684 << std::setw(2) << 1 + tm_time->tm_mon
685 << std::setw(2) << tm_time->tm_mday
686 << '/'
687 << std::setw(2) << tm_time->tm_hour
688 << std::setw(2) << tm_time->tm_min
689 << std::setw(2) << tm_time->tm_sec
690 << ':';
691 }
692 if (log_tickcount)
693 stream_ << TickCount() << ':';
694 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19695 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59696 else
697 stream_ << "VERBOSE" << -severity_;
698
699 stream_ << ":" << filename << "(" << line << ")] ";
700
701 message_start_ = stream_.tellp();
702}
703
[email protected]d8617a62009-10-09 23:52:20704#if defined(OS_WIN)
705// This has already been defined in the header, but defining it again as DWORD
706// ensures that the type used in the header is equivalent to DWORD. If not,
707// the redefinition is a compile error.
708typedef DWORD SystemErrorCode;
709#endif
710
711SystemErrorCode GetLastSystemErrorCode() {
712#if defined(OS_WIN)
713 return ::GetLastError();
714#elif defined(OS_POSIX)
715 return errno;
716#else
717#error Not implemented
718#endif
719}
720
721#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01722BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
723 const int error_message_buffer_size = 256;
724 char msgbuf[error_message_buffer_size];
725 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
726 DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf,
727 arraysize(msgbuf), NULL);
728 if (len) {
729 // Messages returned by system end with line breaks.
730 return base::CollapseWhitespaceASCII(msgbuf, true) +
731 base::StringPrintf(" (0x%X)", error_code);
732 }
733 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
734 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20735}
[email protected]c914d8a2014-04-23 01:11:01736#elif defined(OS_POSIX)
737BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
738 return safe_strerror(error_code);
739}
740#else
741#error Not implemented
742#endif
[email protected]d8617a62009-10-09 23:52:20743
[email protected]c914d8a2014-04-23 01:11:01744
745#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20746Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
747 int line,
748 LogSeverity severity,
749 SystemErrorCode err)
750 : err_(err),
[email protected]d8617a62009-10-09 23:52:20751 log_message_(file, line, severity) {
752}
753
754Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01755 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06756 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
757 // field) and use Alias in hopes that it makes it into crash dumps.
758 DWORD last_error = err_;
759 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20760}
761#elif defined(OS_POSIX)
762ErrnoLogMessage::ErrnoLogMessage(const char* file,
763 int line,
764 LogSeverity severity,
765 SystemErrorCode err)
766 : err_(err),
767 log_message_(file, line, severity) {
768}
769
770ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01771 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20772}
773#endif // OS_WIN
774
initial.commitd7cae122008-07-26 21:49:38775void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55776 LoggingLock logging_lock;
[email protected]17dcf752013-07-15 21:47:09777 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38778}
779
[email protected]e36ddc82009-12-08 04:22:50780void RawLog(int level, const char* message) {
781 if (level >= min_log_level) {
782 size_t bytes_written = 0;
783 const size_t message_len = strlen(message);
784 int rv;
785 while (bytes_written < message_len) {
786 rv = HANDLE_EINTR(
787 write(STDERR_FILENO, message + bytes_written,
788 message_len - bytes_written));
789 if (rv < 0) {
790 // Give up, nothing we can do now.
791 break;
792 }
793 bytes_written += rv;
794 }
795
796 if (message_len > 0 && message[message_len - 1] != '\n') {
797 do {
798 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
799 if (rv < 0) {
800 // Give up, nothing we can do now.
801 break;
802 }
803 } while (rv != 1);
804 }
805 }
806
807 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50808 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50809}
810
[email protected]34a907732012-01-20 06:33:27811// This was defined at the beginning of this file.
812#undef write
813
[email protected]f01b88a2013-02-27 22:04:00814#if defined(OS_WIN)
815std::wstring GetLogFileFullPath() {
816 if (log_file_name)
817 return *log_file_name;
818 return std::wstring();
819}
820#endif
821
[email protected]96fd0032009-04-24 00:13:08822} // namespace logging
initial.commitd7cae122008-07-26 21:49:38823
824std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]f729d7a2013-12-26 07:07:56825 return out << base::WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38826}