blob: 2dec987c6003387d7a4a3bee08d7fa73090be22e [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)
thestig75f87352014-12-03 21:42:2722#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0823#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)
brettw6ee6fd62015-06-09 18:05:2462#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0463#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
thestig3e4787d2015-05-19 19:31:5273VlogInfo* g_vlog_info = nullptr;
74VlogInfo* g_vlog_info_prev = nullptr;
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
thestig75f87352014-12-03 21:42:2779const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:1980 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
81 return log_severity_names[severity];
82 return "UNKNOWN";
83}
84
thestig3e4787d2015-05-19 19:31:5285int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3286
thestig3e4787d2015-05-19 19:31:5287LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:3888
[email protected]a33c9892008-08-25 20:10:3189// For LOG_ERROR and above, always print to stderr.
90const int kAlwaysPrintErrorLevel = LOG_ERROR;
91
[email protected]614e9fa2008-08-11 22:52:5992// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3893// will be lazily initialized to the default value when it is
94// first needed.
[email protected]f6abeba2008-08-08 13:27:2895#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5996typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2897#else
[email protected]614e9fa2008-08-11 22:52:5998typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:2899#endif
thestig3e4787d2015-05-19 19:31:52100PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38101
thestig3e4787d2015-05-19 19:31:52102// This file is lazily opened and the handle may be nullptr
103FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38104
thestig3e4787d2015-05-19 19:31:52105// What should be prepended to each message?
106bool g_log_process_id = false;
107bool g_log_thread_id = false;
108bool g_log_timestamp = true;
109bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38110
[email protected]81e0a852010-08-17 00:38:12111// Should we pop up fatal debug messages in a dialog?
112bool show_error_dialogs = false;
113
initial.commitd7cae122008-07-26 21:49:38114// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05115// the debug message dialog and process termination.
thestig3e4787d2015-05-19 19:31:52116LogAssertHandlerFunction log_assert_handler = nullptr;
[email protected]2b07b8412009-11-25 15:26:34117// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52118LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38119
[email protected]f6abeba2008-08-08 13:27:28120// Helper functions to wrap platform differences.
121
[email protected]f8588472008-11-05 23:17:24122int32 CurrentProcessId() {
123#if defined(OS_WIN)
124 return GetCurrentProcessId();
125#elif defined(OS_POSIX)
126 return getpid();
127#endif
128}
129
[email protected]f8588472008-11-05 23:17:24130uint64 TickCount() {
131#if defined(OS_WIN)
132 return GetTickCount();
133#elif defined(OS_MACOSX)
134 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08135#elif defined(OS_NACL)
136 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
137 // So we have to use clock() for now.
138 return clock();
[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]614e9fa2008-08-11 22:52:59151void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28152#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59153 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27154#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45155 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28156#else
[email protected]614e9fa2008-08-11 22:52:59157 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28158#endif
159}
initial.commitd7cae122008-07-26 21:49:38160
[email protected]5f95d532010-10-01 17:16:58161PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55162#if defined(OS_WIN)
163 // On Windows we use the same path as the exe.
164 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52165 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58166
scottmgfc5b7072015-01-27 21:46:28167 PathString log_name = module_name;
168 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58169 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28170 log_name.erase(last_backslash + 1);
171 log_name += L"debug.log";
172 return log_name;
[email protected]5b84fe32010-09-14 22:24:55173#elif defined(OS_POSIX)
174 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58175 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55176#endif
177}
178
179// This class acts as a wrapper for locking the logging files.
180// LoggingLock::Init() should be called from the main thread before any logging
181// is done. Then whenever logging, be sure to have a local LoggingLock
182// instance on the stack. This will ensure that the lock is unlocked upon
183// exiting the frame.
184// LoggingLocks can not be nested.
185class LoggingLock {
186 public:
187 LoggingLock() {
188 LockLogging();
189 }
190
191 ~LoggingLock() {
192 UnlockLogging();
193 }
194
195 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
196 if (initialized)
197 return;
198 lock_log_file = lock_log;
199 if (lock_log_file == LOCK_LOG_FILE) {
200#if defined(OS_WIN)
201 if (!log_mutex) {
202 std::wstring safe_name;
203 if (new_log_file)
204 safe_name = new_log_file;
205 else
[email protected]5f95d532010-10-01 17:16:58206 safe_name = GetDefaultLogFile();
[email protected]5b84fe32010-09-14 22:24:55207 // \ is not a legal character in mutex names so we replace \ with /
208 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
209 std::wstring t(L"Global\\");
210 t.append(safe_name);
thestig3e4787d2015-05-19 19:31:52211 log_mutex = ::CreateMutex(nullptr, FALSE, t.c_str());
[email protected]5f95d532010-10-01 17:16:58212
thestig3e4787d2015-05-19 19:31:52213 if (log_mutex == nullptr) {
[email protected]5f95d532010-10-01 17:16:58214#if DEBUG
215 // Keep the error code for debugging
216 int error = GetLastError(); // NOLINT
[email protected]58580352010-10-26 04:07:50217 base::debug::BreakDebugger();
[email protected]5f95d532010-10-01 17:16:58218#endif
219 // Return nicely without putting initialized to true.
220 return;
221 }
[email protected]5b84fe32010-09-14 22:24:55222 }
223#endif
224 } else {
[email protected]bc581a682011-01-01 23:16:20225 log_lock = new base::internal::LockImpl();
[email protected]5b84fe32010-09-14 22:24:55226 }
227 initialized = true;
228 }
229
230 private:
231 static void LockLogging() {
232 if (lock_log_file == LOCK_LOG_FILE) {
233#if defined(OS_WIN)
234 ::WaitForSingleObject(log_mutex, INFINITE);
235 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
236 // abort the process here. UI tests might be crashy sometimes,
237 // and aborting the test binary only makes the problem worse.
238 // We also don't use LOG macros because that might lead to an infinite
239 // loop. For more info see http://crbug.com/18028.
240#elif defined(OS_POSIX)
241 pthread_mutex_lock(&log_mutex);
242#endif
243 } else {
244 // use the lock
245 log_lock->Lock();
246 }
247 }
248
249 static void UnlockLogging() {
250 if (lock_log_file == LOCK_LOG_FILE) {
251#if defined(OS_WIN)
252 ReleaseMutex(log_mutex);
253#elif defined(OS_POSIX)
254 pthread_mutex_unlock(&log_mutex);
255#endif
256 } else {
257 log_lock->Unlock();
258 }
259 }
260
261 // The lock is used if log file locking is false. It helps us avoid problems
262 // with multiple threads writing to the log file at the same time. Use
263 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20264 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55265
266 // When we don't use a lock, we are using a global mutex. We need to do this
267 // because LockFileEx is not thread safe.
268#if defined(OS_WIN)
269 static MutexHandle log_mutex;
270#elif defined(OS_POSIX)
271 static pthread_mutex_t log_mutex;
272#endif
273
274 static bool initialized;
275 static LogLockingState lock_log_file;
276};
277
278// static
279bool LoggingLock::initialized = false;
280// static
thestig3e4787d2015-05-19 19:31:52281base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55282// static
283LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
284
285#if defined(OS_WIN)
286// static
thestig3e4787d2015-05-19 19:31:52287MutexHandle LoggingLock::log_mutex = nullptr;
[email protected]5b84fe32010-09-14 22:24:55288#elif defined(OS_POSIX)
289pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
290#endif
291
thestig3e4787d2015-05-19 19:31:52292// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38293// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52294// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38295bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52296 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38297 return true;
298
thestig3e4787d2015-05-19 19:31:52299 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59300 // Nobody has called InitLogging to specify a debug log file, so here we
301 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52302 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38303 }
304
thestig3e4787d2015-05-19 19:31:52305 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59306#if defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52307 g_log_file = CreateFile(g_log_file_name->c_str(), GENERIC_WRITE,
308 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
309 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
310 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
[email protected]1d8c2702008-08-19 23:39:32311 // try the current directory
thestig3e4787d2015-05-19 19:31:52312 g_log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
313 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
314 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
315 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
316 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32317 return false;
318 }
initial.commitd7cae122008-07-26 21:49:38319 }
thestig3e4787d2015-05-19 19:31:52320 SetFilePointer(g_log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11321#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52322 g_log_file = fopen(g_log_file_name->c_str(), "a");
323 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11324 return false;
[email protected]f6abeba2008-08-08 13:27:28325#endif
[email protected]1d8c2702008-08-19 23:39:32326 }
327
initial.commitd7cae122008-07-26 21:49:38328 return true;
329}
330
[email protected]17dcf752013-07-15 21:47:09331void CloseFile(FileHandle log) {
332#if defined(OS_WIN)
333 CloseHandle(log);
334#else
335 fclose(log);
336#endif
337}
338
339void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52340 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09341 return;
342
thestig3e4787d2015-05-19 19:31:52343 CloseFile(g_log_file);
344 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09345}
346
[email protected]064aa162011-12-03 00:30:08347} // namespace
348
[email protected]5e3f7c22013-06-21 21:15:33349LoggingSettings::LoggingSettings()
350 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52351 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33352 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38353 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08354
[email protected]5e3f7c22013-06-21 21:15:33355bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45356#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33357 // Can log only to the system debug log.
358 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45359#endif
pgal.u-szeged421dddb2014-11-25 12:55:02360 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52361 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36362 // vlog switches.
363 if (command_line->HasSwitch(switches::kV) ||
364 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52365 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08366 // by another thread. Don't delete the old VLogInfo, just create a second
367 // one. We keep track of both to avoid memory leak warnings.
368 CHECK(!g_vlog_info_prev);
369 g_vlog_info_prev = g_vlog_info;
370
[email protected]99b7c57f2010-09-29 19:26:36371 g_vlog_info =
372 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49373 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52374 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36375 }
376
thestig3e4787d2015-05-19 19:31:52377 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38378
[email protected]5e3f7c22013-06-21 21:15:33379 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52380 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21381 return true;
initial.commitd7cae122008-07-26 21:49:38382
[email protected]17dcf752013-07-15 21:47:09383 LoggingLock::Init(settings.lock_log, settings.log_file);
384 LoggingLock logging_lock;
385
386 // Calling InitLogging twice or after some log call has already opened the
387 // default log file will re-initialize to the new options.
388 CloseLogFileUnlocked();
389
thestig3e4787d2015-05-19 19:31:52390 if (!g_log_file_name)
391 g_log_file_name = new PathString();
392 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33393 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52394 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38395
[email protected]c7d5da992010-10-28 00:20:21396 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38397}
398
399void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52400 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38401}
402
403int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52404 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38405}
406
[email protected]162ac0f2010-11-04 15:50:49407int GetVlogVerbosity() {
408 return std::max(-1, LOG_INFO - GetMinLogLevel());
409}
410
[email protected]99b7c57f2010-09-29 19:26:36411int GetVlogLevelHelper(const char* file, size_t N) {
412 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52413 // Note: |g_vlog_info| may change on a different thread during startup
414 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08415 VlogInfo* vlog_info = g_vlog_info;
416 return vlog_info ?
417 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49418 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36419}
420
initial.commitd7cae122008-07-26 21:49:38421void SetLogItems(bool enable_process_id, bool enable_thread_id,
422 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52423 g_log_process_id = enable_process_id;
424 g_log_thread_id = enable_thread_id;
425 g_log_timestamp = enable_timestamp;
426 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38427}
428
[email protected]81e0a852010-08-17 00:38:12429void SetShowErrorDialogs(bool enable_dialogs) {
430 show_error_dialogs = enable_dialogs;
431}
432
initial.commitd7cae122008-07-26 21:49:38433void SetLogAssertHandler(LogAssertHandlerFunction handler) {
434 log_assert_handler = handler;
435}
436
[email protected]2b07b8412009-11-25 15:26:34437void SetLogMessageHandler(LogMessageHandlerFunction handler) {
438 log_message_handler = handler;
439}
440
[email protected]64e5cc02010-11-03 19:20:27441LogMessageHandlerFunction GetLogMessageHandler() {
442 return log_message_handler;
443}
444
[email protected]6d445d32010-09-30 19:10:03445// Explicit instantiations for commonly used comparisons.
446template std::string* MakeCheckOpString<int, int>(
447 const int&, const int&, const char* names);
448template std::string* MakeCheckOpString<unsigned long, unsigned long>(
449 const unsigned long&, const unsigned long&, const char* names);
450template std::string* MakeCheckOpString<unsigned long, unsigned int>(
451 const unsigned long&, const unsigned int&, const char* names);
452template std::string* MakeCheckOpString<unsigned int, unsigned long>(
453 const unsigned int&, const unsigned long&, const char* names);
454template std::string* MakeCheckOpString<std::string, std::string>(
455 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34456
[email protected]f2c05492014-06-17 12:04:23457#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22458// Displays a message box to the user with the error message in it.
459// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25460// This is for developers only; we don't use this in circumstances
461// (like release builds) where users could see it, since users don't
462// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22463void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38464 if (str.empty())
465 return;
466
[email protected]81e0a852010-08-17 00:38:12467 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44468 return;
469
[email protected]f6abeba2008-08-08 13:27:28470#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22471 // For Windows programs, it's possible that the message loop is
472 // messed up on a fatal error, and creating a MessageBox will cause
473 // that message loop to be run. Instead, we try to spawn another
474 // process that displays its command line. We look for "Debug
475 // Message.exe" in the same directory as the application. If it
476 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38477 wchar_t prog_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52478 GetModuleFileNameW(nullptr, prog_name, MAX_PATH);
initial.commitd7cae122008-07-26 21:49:38479 wchar_t* backslash = wcsrchr(prog_name, '\\');
480 if (backslash)
481 backslash[1] = 0;
482 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
483
[email protected]f729d7a2013-12-26 07:07:56484 std::wstring cmdline = base::UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02485 if (cmdline.empty())
486 return;
initial.commitd7cae122008-07-26 21:49:38487
488 STARTUPINFO startup_info;
489 memset(&startup_info, 0, sizeof(startup_info));
490 startup_info.cb = sizeof(startup_info);
491
492 PROCESS_INFORMATION process_info;
thestig3e4787d2015-05-19 19:31:52493 if (CreateProcessW(prog_name, &cmdline[0], nullptr, nullptr, false, 0,
494 nullptr, nullptr, &startup_info, &process_info)) {
initial.commitd7cae122008-07-26 21:49:38495 WaitForSingleObject(process_info.hProcess, INFINITE);
496 CloseHandle(process_info.hThread);
497 CloseHandle(process_info.hProcess);
498 } else {
499 // debug process broken, let's just do a message box
thestig3e4787d2015-05-19 19:31:52500 MessageBoxW(nullptr, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38501 MB_OK | MB_ICONHAND | MB_TOPMOST);
502 }
[email protected]f6abeba2008-08-08 13:27:28503#else
[email protected]561513f2010-12-16 23:29:25504 // We intentionally don't implement a dialog on other platforms.
505 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52506#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38507}
[email protected]f2c05492014-06-17 12:04:23508#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38509
[email protected]3f85caa2009-04-14 16:52:11510#if defined(OS_WIN)
511LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
512}
513
514LogMessage::SaveLastError::~SaveLastError() {
515 ::SetLastError(last_error_);
516}
517#endif // defined(OS_WIN)
518
[email protected]eae9c062011-01-11 00:50:59519LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
520 : severity_(severity), file_(file), line_(line) {
521 Init(file, line);
522}
523
tnagel4a045d3f2015-07-12 14:19:28524LogMessage::LogMessage(const char* file, int line, const char* condition)
525 : severity_(LOG_FATAL), file_(file), line_(line) {
526 Init(file, line);
527 stream_ << "Check failed: " << condition << ". ";
528}
529
[email protected]9c7132e2011-02-08 07:39:08530LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49531 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38532 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08533 stream_ << "Check failed: " << *result;
534 delete result;
initial.commitd7cae122008-07-26 21:49:38535}
536
[email protected]fb62a532009-02-12 01:19:05537LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08538 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49539 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05540 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08541 stream_ << "Check failed: " << *result;
542 delete result;
[email protected]fb62a532009-02-12 01:19:05543}
544
initial.commitd7cae122008-07-26 21:49:38545LogMessage::~LogMessage() {
jam79dc59a2015-08-17 03:38:16546#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__)
brucedawson7c559eb2015-09-05 00:34:42547 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
548 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50549 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24550 stream_ << std::endl; // Newline to separate from log message.
551 trace.OutputToStream(&stream_);
552 }
[email protected]1d8c2702008-08-19 23:39:32553#endif
[email protected]d1ccc35a2010-03-24 05:03:24554 stream_ << std::endl;
555 std::string str_newline(stream_.str());
556
[email protected]2b07b8412009-11-25 15:26:34557 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33558 if (log_message_handler &&
559 log_message_handler(severity_, file_, line_,
560 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49561 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34562 return;
[email protected]162ac0f2010-11-04 15:50:49563 }
initial.commitd7cae122008-07-26 21:49:38564
thestig3e4787d2015-05-19 19:31:52565 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28566#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38567 OutputDebugStringA(str_newline.c_str());
[email protected]3132e35c2011-07-07 20:46:50568#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25569 android_LogPriority priority =
570 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50571 switch (severity_) {
572 case LOG_INFO:
573 priority = ANDROID_LOG_INFO;
574 break;
575 case LOG_WARNING:
576 priority = ANDROID_LOG_WARN;
577 break;
578 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50579 priority = ANDROID_LOG_ERROR;
580 break;
581 case LOG_FATAL:
582 priority = ANDROID_LOG_FATAL;
583 break;
584 }
585 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18586#endif
[email protected]51105382014-03-14 17:02:15587 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06588 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31589 } else if (severity_ >= kAlwaysPrintErrorLevel) {
590 // When we're only outputting to a log file, above a certain log level, we
591 // should still output to stderr so that we can better detect and diagnose
592 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15593 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02594 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28595 }
[email protected]52a261f2009-03-03 15:01:12596
initial.commitd7cae122008-07-26 21:49:38597 // write to log file
thestig3e4787d2015-05-19 19:31:52598 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09599 // We can have multiple threads and/or processes, so try to prevent them
600 // from clobbering each other's writes.
601 // If the client app did not call InitLogging, and the lock has not
602 // been created do it now. We do this on demand, but if two threads try
603 // to do this at the same time, there will be a race condition to create
604 // the lock. This is why InitLogging should be called from the main
605 // thread at the beginning of execution.
thestig3e4787d2015-05-19 19:31:52606 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55607 LoggingLock logging_lock;
608 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28609#if defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52610 SetFilePointer(g_log_file, 0, 0, SEEK_END);
[email protected]5b84fe32010-09-14 22:24:55611 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52612 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55613 static_cast<const void*>(str_newline.c_str()),
614 static_cast<DWORD>(str_newline.length()),
615 &num_written,
thestig3e4787d2015-05-19 19:31:52616 nullptr);
[email protected]cba21962010-08-31 22:35:55617#else
[email protected]51105382014-03-14 17:02:15618 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52619 str_newline.data(), str_newline.size(), 1, g_log_file));
620 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55621#endif
initial.commitd7cae122008-07-26 21:49:38622 }
623 }
624
625 if (severity_ == LOG_FATAL) {
[email protected]eb4c4d032012-04-03 18:45:05626 // Ensure the first characters of the string are on the stack so they
627 // are contained in minidumps for diagnostic purposes.
628 char str_stack[1024];
629 str_newline.copy(str_stack, arraysize(str_stack));
630 base::debug::Alias(str_stack);
631
[email protected]82d89ab2014-02-28 18:25:34632 if (log_assert_handler) {
633 // Make a copy of the string for the handler out of paranoia.
634 log_assert_handler(std::string(stream_.str()));
[email protected]1ffe08c12008-08-13 11:15:11635 } else {
[email protected]82d89ab2014-02-28 18:25:34636 // Don't use the string with the newline, get a fresh version to send to
637 // the debug message process. We also don't display assertions to the
638 // user in release mode. The enduser can't do anything with this
639 // information, and displaying message boxes when the application is
640 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50641#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42642 if (!base::debug::BeingDebugged()) {
643 // Displaying a dialog is unnecessary when debugging and can complicate
644 // debugging.
645 DisplayDebugMessageInDialog(stream_.str());
646 }
[email protected]4d5901272008-11-06 00:33:50647#endif
[email protected]82d89ab2014-02-28 18:25:34648 // Crash the process to generate a dump.
649 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38650 }
651 }
652}
653
[email protected]eae9c062011-01-11 00:50:59654// writes the common header info to the stream
655void LogMessage::Init(const char* file, int line) {
656 base::StringPiece filename(file);
657 size_t last_slash_pos = filename.find_last_of("\\/");
658 if (last_slash_pos != base::StringPiece::npos)
659 filename.remove_prefix(last_slash_pos + 1);
660
661 // TODO(darin): It might be nice if the columns were fixed width.
662
663 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52664 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59665 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52666 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09667 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52668 if (g_log_timestamp) {
669 time_t t = time(nullptr);
[email protected]eae9c062011-01-11 00:50:59670 struct tm local_time = {0};
mostynb7e42a8f2014-12-19 12:47:46671#ifdef _MSC_VER
[email protected]eae9c062011-01-11 00:50:59672 localtime_s(&local_time, &t);
673#else
674 localtime_r(&t, &local_time);
675#endif
676 struct tm* tm_time = &local_time;
677 stream_ << std::setfill('0')
678 << std::setw(2) << 1 + tm_time->tm_mon
679 << std::setw(2) << tm_time->tm_mday
680 << '/'
681 << std::setw(2) << tm_time->tm_hour
682 << std::setw(2) << tm_time->tm_min
683 << std::setw(2) << tm_time->tm_sec
684 << ':';
685 }
thestig3e4787d2015-05-19 19:31:52686 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59687 stream_ << TickCount() << ':';
688 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19689 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59690 else
691 stream_ << "VERBOSE" << -severity_;
692
693 stream_ << ":" << filename << "(" << line << ")] ";
694
pkasting9cf9b94a2014-10-01 22:18:43695 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59696}
697
[email protected]d8617a62009-10-09 23:52:20698#if defined(OS_WIN)
699// This has already been defined in the header, but defining it again as DWORD
700// ensures that the type used in the header is equivalent to DWORD. If not,
701// the redefinition is a compile error.
702typedef DWORD SystemErrorCode;
703#endif
704
705SystemErrorCode GetLastSystemErrorCode() {
706#if defined(OS_WIN)
707 return ::GetLastError();
708#elif defined(OS_POSIX)
709 return errno;
710#else
711#error Not implemented
712#endif
713}
714
715#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01716BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27717 const int kErrorMessageBufferSize = 256;
718 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01719 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52720 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
721 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01722 if (len) {
723 // Messages returned by system end with line breaks.
724 return base::CollapseWhitespaceASCII(msgbuf, true) +
725 base::StringPrintf(" (0x%X)", error_code);
726 }
727 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
728 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20729}
[email protected]c914d8a2014-04-23 01:11:01730#elif defined(OS_POSIX)
731BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
brettw6ee6fd62015-06-09 18:05:24732 return base::safe_strerror(error_code);
[email protected]c914d8a2014-04-23 01:11:01733}
734#else
735#error Not implemented
thestig3e4787d2015-05-19 19:31:52736#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20737
[email protected]c914d8a2014-04-23 01:11:01738
739#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20740Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
741 int line,
742 LogSeverity severity,
743 SystemErrorCode err)
744 : err_(err),
[email protected]d8617a62009-10-09 23:52:20745 log_message_(file, line, severity) {
746}
747
748Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01749 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06750 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
751 // field) and use Alias in hopes that it makes it into crash dumps.
752 DWORD last_error = err_;
753 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20754}
755#elif defined(OS_POSIX)
756ErrnoLogMessage::ErrnoLogMessage(const char* file,
757 int line,
758 LogSeverity severity,
759 SystemErrorCode err)
760 : err_(err),
761 log_message_(file, line, severity) {
762}
763
764ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01765 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20766}
thestig3e4787d2015-05-19 19:31:52767#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20768
initial.commitd7cae122008-07-26 21:49:38769void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55770 LoggingLock logging_lock;
[email protected]17dcf752013-07-15 21:47:09771 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38772}
773
[email protected]e36ddc82009-12-08 04:22:50774void RawLog(int level, const char* message) {
thestig3e4787d2015-05-19 19:31:52775 if (level >= g_min_log_level) {
[email protected]e36ddc82009-12-08 04:22:50776 size_t bytes_written = 0;
777 const size_t message_len = strlen(message);
778 int rv;
779 while (bytes_written < message_len) {
780 rv = HANDLE_EINTR(
781 write(STDERR_FILENO, message + bytes_written,
782 message_len - bytes_written));
783 if (rv < 0) {
784 // Give up, nothing we can do now.
785 break;
786 }
787 bytes_written += rv;
788 }
789
790 if (message_len > 0 && message[message_len - 1] != '\n') {
791 do {
792 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
793 if (rv < 0) {
794 // Give up, nothing we can do now.
795 break;
796 }
797 } while (rv != 1);
798 }
799 }
800
801 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50802 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50803}
804
[email protected]34a907732012-01-20 06:33:27805// This was defined at the beginning of this file.
806#undef write
807
[email protected]f01b88a2013-02-27 22:04:00808#if defined(OS_WIN)
809std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52810 if (g_log_file_name)
811 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00812 return std::wstring();
813}
814#endif
815
tnagel80388e682015-05-26 13:27:56816BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14817 LogMessage(file, line, LOG_ERROR).stream()
818 << "NOTREACHED() hit.";
819}
820
[email protected]96fd0032009-04-24 00:13:08821} // namespace logging
initial.commitd7cae122008-07-26 21:49:38822
[email protected]81411c62014-07-08 23:03:06823std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
thestig75f87352014-12-03 21:42:27824 return out << base::WideToUTF8(wstr);
initial.commitd7cae122008-07-26 21:49:38825}