blob: b9d431f3c451963e25431186915cf672e19ce33e [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>
ananta61762fb2015-09-18 01:00:0910#include "base/files/file_path.h"
11#include "base/files/file_util.h"
[email protected]f6abeba2008-08-08 13:27:2812typedef HANDLE FileHandle;
13typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5014// Windows warns on using write(). It prefers _write().
15#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
16// Windows doesn't define STDERR_FILENO. Define it here.
17#define STDERR_FILENO 2
[email protected]052f1b52008-11-06 21:43:0718#elif defined(OS_MACOSX)
[email protected]f6abeba2008-08-08 13:27:2819#include <mach/mach.h>
20#include <mach/mach_time.h>
21#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5222#elif defined(OS_POSIX)
[email protected]19ea84ca2010-11-12 08:37:0823#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2724#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0825#else
[email protected]052f1b52008-11-06 21:43:0726#include <sys/syscall.h>
[email protected]19ea84ca2010-11-12 08:37:0827#endif
[email protected]052f1b52008-11-06 21:43:0728#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5929#endif
30
31#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2032#include <errno.h>
[email protected]166326c62010-08-05 15:50:2333#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2834#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0035#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2836#include <string.h>
37#include <unistd.h>
38#define MAX_PATH PATH_MAX
39typedef FILE* FileHandle;
40typedef pthread_mutex_t* MutexHandle;
41#endif
42
[email protected]1f88b5162011-04-01 00:02:2943#include <algorithm>
44#include <cstring>
initial.commitd7cae122008-07-26 21:49:3845#include <ctime>
46#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2947#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0148#include <string>
[email protected]b16ef312008-08-19 18:36:2349
initial.commitd7cae122008-07-26 21:49:3850#include "base/base_switches.h"
51#include "base/command_line.h"
[email protected]eb4c4d032012-04-03 18:45:0552#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5053#include "base/debug/debugger.h"
54#include "base/debug/stack_trace.h"
[email protected]2025d002012-11-14 20:54:3555#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0056#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0157#include "base/strings/string_util.h"
58#include "base/strings/stringprintf.h"
[email protected]a4ea1f12013-06-07 18:37:0759#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2060#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0961#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3662#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0463#if defined(OS_POSIX)
brettw6ee6fd62015-06-09 18:05:2464#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0465#endif
[email protected]52a261f2009-03-03 15:01:1266
[email protected]3132e35c2011-07-07 20:46:5067#if defined(OS_ANDROID)
68#include <android/log.h>
69#endif
70
initial.commitd7cae122008-07-26 21:49:3871namespace logging {
72
[email protected]064aa162011-12-03 00:30:0873namespace {
74
thestig3e4787d2015-05-19 19:31:5275VlogInfo* g_vlog_info = nullptr;
76VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:3877
78const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]f2c05492014-06-17 12:04:2379 "INFO", "WARNING", "ERROR", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3880
thestig75f87352014-12-03 21:42:2781const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:1982 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
83 return log_severity_names[severity];
84 return "UNKNOWN";
85}
86
thestig3e4787d2015-05-19 19:31:5287int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3288
thestig3e4787d2015-05-19 19:31:5289LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:3890
[email protected]a33c9892008-08-25 20:10:3191// For LOG_ERROR and above, always print to stderr.
92const int kAlwaysPrintErrorLevel = LOG_ERROR;
93
[email protected]614e9fa2008-08-11 22:52:5994// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3895// will be lazily initialized to the default value when it is
96// first needed.
[email protected]f6abeba2008-08-08 13:27:2897#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5998typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2899#else
[email protected]614e9fa2008-08-11 22:52:59100typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28101#endif
thestig3e4787d2015-05-19 19:31:52102PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38103
thestig3e4787d2015-05-19 19:31:52104// This file is lazily opened and the handle may be nullptr
105FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38106
thestig3e4787d2015-05-19 19:31:52107// What should be prepended to each message?
108bool g_log_process_id = false;
109bool g_log_thread_id = false;
110bool g_log_timestamp = true;
111bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38112
[email protected]81e0a852010-08-17 00:38:12113// Should we pop up fatal debug messages in a dialog?
114bool show_error_dialogs = false;
115
initial.commitd7cae122008-07-26 21:49:38116// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05117// the debug message dialog and process termination.
thestig3e4787d2015-05-19 19:31:52118LogAssertHandlerFunction log_assert_handler = nullptr;
[email protected]2b07b8412009-11-25 15:26:34119// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52120LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38121
[email protected]f6abeba2008-08-08 13:27:28122// Helper functions to wrap platform differences.
123
[email protected]f8588472008-11-05 23:17:24124int32 CurrentProcessId() {
125#if defined(OS_WIN)
126 return GetCurrentProcessId();
127#elif defined(OS_POSIX)
128 return getpid();
129#endif
130}
131
[email protected]f8588472008-11-05 23:17:24132uint64 TickCount() {
133#if defined(OS_WIN)
134 return GetTickCount();
135#elif defined(OS_MACOSX)
136 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08137#elif defined(OS_NACL)
138 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
139 // So we have to use clock() for now.
140 return clock();
[email protected]e43eddf12009-12-29 00:32:52141#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07142 struct timespec ts;
143 clock_gettime(CLOCK_MONOTONIC, &ts);
144
145 uint64 absolute_micro =
146 static_cast<int64>(ts.tv_sec) * 1000000 +
147 static_cast<int64>(ts.tv_nsec) / 1000;
148
149 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24150#endif
151}
152
[email protected]614e9fa2008-08-11 22:52:59153void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28154#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59155 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27156#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45157 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28158#else
[email protected]614e9fa2008-08-11 22:52:59159 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28160#endif
161}
initial.commitd7cae122008-07-26 21:49:38162
[email protected]5f95d532010-10-01 17:16:58163PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55164#if defined(OS_WIN)
165 // On Windows we use the same path as the exe.
166 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52167 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58168
scottmgfc5b7072015-01-27 21:46:28169 PathString log_name = module_name;
170 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58171 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28172 log_name.erase(last_backslash + 1);
173 log_name += L"debug.log";
174 return log_name;
[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
ananta61762fb2015-09-18 01:00:09181// We don't need locks on Windows for atomically appending to files. The OS
182// provides this functionality.
183#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55184// This class acts as a wrapper for locking the logging files.
185// LoggingLock::Init() should be called from the main thread before any logging
186// is done. Then whenever logging, be sure to have a local LoggingLock
187// instance on the stack. This will ensure that the lock is unlocked upon
188// exiting the frame.
189// LoggingLocks can not be nested.
190class LoggingLock {
191 public:
192 LoggingLock() {
193 LockLogging();
194 }
195
196 ~LoggingLock() {
197 UnlockLogging();
198 }
199
200 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
201 if (initialized)
202 return;
203 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58204
ananta61762fb2015-09-18 01:00:09205 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20206 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09207
[email protected]5b84fe32010-09-14 22:24:55208 initialized = true;
209 }
210
211 private:
212 static void LockLogging() {
213 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09214#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55215 pthread_mutex_lock(&log_mutex);
216#endif
217 } else {
218 // use the lock
219 log_lock->Lock();
220 }
221 }
222
223 static void UnlockLogging() {
224 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09225#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55226 pthread_mutex_unlock(&log_mutex);
227#endif
228 } else {
229 log_lock->Unlock();
230 }
231 }
232
233 // The lock is used if log file locking is false. It helps us avoid problems
234 // with multiple threads writing to the log file at the same time. Use
235 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20236 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55237
238 // When we don't use a lock, we are using a global mutex. We need to do this
239 // because LockFileEx is not thread safe.
ananta61762fb2015-09-18 01:00:09240#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55241 static pthread_mutex_t log_mutex;
242#endif
243
244 static bool initialized;
245 static LogLockingState lock_log_file;
246};
247
248// static
249bool LoggingLock::initialized = false;
250// static
thestig3e4787d2015-05-19 19:31:52251base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55252// static
253LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
254
ananta61762fb2015-09-18 01:00:09255#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55256pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
257#endif
258
ananta61762fb2015-09-18 01:00:09259#endif // OS_WIN
260
thestig3e4787d2015-05-19 19:31:52261// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38262// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52263// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38264bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52265 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38266 return true;
267
thestig3e4787d2015-05-19 19:31:52268 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59269 // Nobody has called InitLogging to specify a debug log file, so here we
270 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52271 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38272 }
273
thestig3e4787d2015-05-19 19:31:52274 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59275#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09276 // The FILE_APPEND_DATA access mask ensures that the file is atomically
277 // appended to across accesses from multiple threads.
278 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
279 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
280 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52281 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
282 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
283 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
[email protected]1d8c2702008-08-19 23:39:32284 // try the current directory
ananta61762fb2015-09-18 01:00:09285 base::FilePath file_path;
286 if (!base::GetCurrentDirectory(&file_path))
287 return false;
288
289 *g_log_file_name = file_path.Append(
290 FILE_PATH_LITERAL("debug.log")).value();
291
292 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52293 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
294 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
295 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
296 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32297 return false;
298 }
initial.commitd7cae122008-07-26 21:49:38299 }
[email protected]78c6dd62009-06-08 23:29:11300#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52301 g_log_file = fopen(g_log_file_name->c_str(), "a");
302 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11303 return false;
[email protected]f6abeba2008-08-08 13:27:28304#endif
[email protected]1d8c2702008-08-19 23:39:32305 }
306
initial.commitd7cae122008-07-26 21:49:38307 return true;
308}
309
[email protected]17dcf752013-07-15 21:47:09310void CloseFile(FileHandle log) {
311#if defined(OS_WIN)
312 CloseHandle(log);
313#else
314 fclose(log);
315#endif
316}
317
318void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52319 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09320 return;
321
thestig3e4787d2015-05-19 19:31:52322 CloseFile(g_log_file);
323 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09324}
325
[email protected]064aa162011-12-03 00:30:08326} // namespace
327
[email protected]5e3f7c22013-06-21 21:15:33328LoggingSettings::LoggingSettings()
329 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52330 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33331 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38332 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08333
[email protected]5e3f7c22013-06-21 21:15:33334bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45335#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33336 // Can log only to the system debug log.
337 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45338#endif
pgal.u-szeged421dddb2014-11-25 12:55:02339 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52340 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36341 // vlog switches.
342 if (command_line->HasSwitch(switches::kV) ||
343 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52344 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08345 // by another thread. Don't delete the old VLogInfo, just create a second
346 // one. We keep track of both to avoid memory leak warnings.
347 CHECK(!g_vlog_info_prev);
348 g_vlog_info_prev = g_vlog_info;
349
[email protected]99b7c57f2010-09-29 19:26:36350 g_vlog_info =
351 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49352 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52353 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36354 }
355
thestig3e4787d2015-05-19 19:31:52356 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38357
[email protected]5e3f7c22013-06-21 21:15:33358 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52359 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21360 return true;
initial.commitd7cae122008-07-26 21:49:38361
ananta61762fb2015-09-18 01:00:09362#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09363 LoggingLock::Init(settings.lock_log, settings.log_file);
364 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09365#endif
[email protected]17dcf752013-07-15 21:47:09366
367 // Calling InitLogging twice or after some log call has already opened the
368 // default log file will re-initialize to the new options.
369 CloseLogFileUnlocked();
370
thestig3e4787d2015-05-19 19:31:52371 if (!g_log_file_name)
372 g_log_file_name = new PathString();
373 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33374 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52375 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38376
[email protected]c7d5da992010-10-28 00:20:21377 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38378}
379
380void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52381 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38382}
383
384int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52385 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38386}
387
[email protected]162ac0f2010-11-04 15:50:49388int GetVlogVerbosity() {
389 return std::max(-1, LOG_INFO - GetMinLogLevel());
390}
391
[email protected]99b7c57f2010-09-29 19:26:36392int GetVlogLevelHelper(const char* file, size_t N) {
393 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52394 // Note: |g_vlog_info| may change on a different thread during startup
395 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08396 VlogInfo* vlog_info = g_vlog_info;
397 return vlog_info ?
398 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49399 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36400}
401
initial.commitd7cae122008-07-26 21:49:38402void SetLogItems(bool enable_process_id, bool enable_thread_id,
403 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52404 g_log_process_id = enable_process_id;
405 g_log_thread_id = enable_thread_id;
406 g_log_timestamp = enable_timestamp;
407 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38408}
409
[email protected]81e0a852010-08-17 00:38:12410void SetShowErrorDialogs(bool enable_dialogs) {
411 show_error_dialogs = enable_dialogs;
412}
413
initial.commitd7cae122008-07-26 21:49:38414void SetLogAssertHandler(LogAssertHandlerFunction handler) {
415 log_assert_handler = handler;
416}
417
[email protected]2b07b8412009-11-25 15:26:34418void SetLogMessageHandler(LogMessageHandlerFunction handler) {
419 log_message_handler = handler;
420}
421
[email protected]64e5cc02010-11-03 19:20:27422LogMessageHandlerFunction GetLogMessageHandler() {
423 return log_message_handler;
424}
425
[email protected]6d445d32010-09-30 19:10:03426// Explicit instantiations for commonly used comparisons.
427template std::string* MakeCheckOpString<int, int>(
428 const int&, const int&, const char* names);
429template std::string* MakeCheckOpString<unsigned long, unsigned long>(
430 const unsigned long&, const unsigned long&, const char* names);
431template std::string* MakeCheckOpString<unsigned long, unsigned int>(
432 const unsigned long&, const unsigned int&, const char* names);
433template std::string* MakeCheckOpString<unsigned int, unsigned long>(
434 const unsigned int&, const unsigned long&, const char* names);
435template std::string* MakeCheckOpString<std::string, std::string>(
436 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34437
[email protected]f2c05492014-06-17 12:04:23438#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22439// Displays a message box to the user with the error message in it.
440// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25441// This is for developers only; we don't use this in circumstances
442// (like release builds) where users could see it, since users don't
443// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22444void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38445 if (str.empty())
446 return;
447
[email protected]81e0a852010-08-17 00:38:12448 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44449 return;
450
[email protected]f6abeba2008-08-08 13:27:28451#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22452 // For Windows programs, it's possible that the message loop is
453 // messed up on a fatal error, and creating a MessageBox will cause
454 // that message loop to be run. Instead, we try to spawn another
455 // process that displays its command line. We look for "Debug
456 // Message.exe" in the same directory as the application. If it
457 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38458 wchar_t prog_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52459 GetModuleFileNameW(nullptr, prog_name, MAX_PATH);
initial.commitd7cae122008-07-26 21:49:38460 wchar_t* backslash = wcsrchr(prog_name, '\\');
461 if (backslash)
462 backslash[1] = 0;
463 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
464
[email protected]f729d7a2013-12-26 07:07:56465 std::wstring cmdline = base::UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02466 if (cmdline.empty())
467 return;
initial.commitd7cae122008-07-26 21:49:38468
469 STARTUPINFO startup_info;
470 memset(&startup_info, 0, sizeof(startup_info));
471 startup_info.cb = sizeof(startup_info);
472
473 PROCESS_INFORMATION process_info;
thestig3e4787d2015-05-19 19:31:52474 if (CreateProcessW(prog_name, &cmdline[0], nullptr, nullptr, false, 0,
475 nullptr, nullptr, &startup_info, &process_info)) {
initial.commitd7cae122008-07-26 21:49:38476 WaitForSingleObject(process_info.hProcess, INFINITE);
477 CloseHandle(process_info.hThread);
478 CloseHandle(process_info.hProcess);
479 } else {
480 // debug process broken, let's just do a message box
thestig3e4787d2015-05-19 19:31:52481 MessageBoxW(nullptr, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38482 MB_OK | MB_ICONHAND | MB_TOPMOST);
483 }
[email protected]f6abeba2008-08-08 13:27:28484#else
[email protected]561513f2010-12-16 23:29:25485 // We intentionally don't implement a dialog on other platforms.
486 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52487#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38488}
[email protected]f2c05492014-06-17 12:04:23489#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38490
[email protected]3f85caa2009-04-14 16:52:11491#if defined(OS_WIN)
492LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
493}
494
495LogMessage::SaveLastError::~SaveLastError() {
496 ::SetLastError(last_error_);
497}
498#endif // defined(OS_WIN)
499
[email protected]eae9c062011-01-11 00:50:59500LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
501 : severity_(severity), file_(file), line_(line) {
502 Init(file, line);
503}
504
tnagel4a045d3f2015-07-12 14:19:28505LogMessage::LogMessage(const char* file, int line, const char* condition)
506 : severity_(LOG_FATAL), file_(file), line_(line) {
507 Init(file, line);
508 stream_ << "Check failed: " << condition << ". ";
509}
510
[email protected]9c7132e2011-02-08 07:39:08511LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49512 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38513 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08514 stream_ << "Check failed: " << *result;
515 delete result;
initial.commitd7cae122008-07-26 21:49:38516}
517
[email protected]fb62a532009-02-12 01:19:05518LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08519 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49520 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05521 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08522 stream_ << "Check failed: " << *result;
523 delete result;
[email protected]fb62a532009-02-12 01:19:05524}
525
initial.commitd7cae122008-07-26 21:49:38526LogMessage::~LogMessage() {
jam79dc59a2015-08-17 03:38:16527#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__)
brucedawson7c559eb2015-09-05 00:34:42528 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
529 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50530 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24531 stream_ << std::endl; // Newline to separate from log message.
532 trace.OutputToStream(&stream_);
533 }
[email protected]1d8c2702008-08-19 23:39:32534#endif
[email protected]d1ccc35a2010-03-24 05:03:24535 stream_ << std::endl;
536 std::string str_newline(stream_.str());
537
[email protected]2b07b8412009-11-25 15:26:34538 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33539 if (log_message_handler &&
540 log_message_handler(severity_, file_, line_,
541 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49542 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34543 return;
[email protected]162ac0f2010-11-04 15:50:49544 }
initial.commitd7cae122008-07-26 21:49:38545
thestig3e4787d2015-05-19 19:31:52546 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28547#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38548 OutputDebugStringA(str_newline.c_str());
[email protected]3132e35c2011-07-07 20:46:50549#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25550 android_LogPriority priority =
551 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50552 switch (severity_) {
553 case LOG_INFO:
554 priority = ANDROID_LOG_INFO;
555 break;
556 case LOG_WARNING:
557 priority = ANDROID_LOG_WARN;
558 break;
559 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50560 priority = ANDROID_LOG_ERROR;
561 break;
562 case LOG_FATAL:
563 priority = ANDROID_LOG_FATAL;
564 break;
565 }
566 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18567#endif
[email protected]51105382014-03-14 17:02:15568 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06569 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31570 } else if (severity_ >= kAlwaysPrintErrorLevel) {
571 // When we're only outputting to a log file, above a certain log level, we
572 // should still output to stderr so that we can better detect and diagnose
573 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15574 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02575 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28576 }
[email protected]52a261f2009-03-03 15:01:12577
initial.commitd7cae122008-07-26 21:49:38578 // write to log file
thestig3e4787d2015-05-19 19:31:52579 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09580 // We can have multiple threads and/or processes, so try to prevent them
581 // from clobbering each other's writes.
582 // If the client app did not call InitLogging, and the lock has not
583 // been created do it now. We do this on demand, but if two threads try
584 // to do this at the same time, there will be a race condition to create
585 // the lock. This is why InitLogging should be called from the main
586 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09587#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52588 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55589 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09590#endif
[email protected]5b84fe32010-09-14 22:24:55591 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28592#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55593 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52594 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55595 static_cast<const void*>(str_newline.c_str()),
596 static_cast<DWORD>(str_newline.length()),
597 &num_written,
thestig3e4787d2015-05-19 19:31:52598 nullptr);
[email protected]cba21962010-08-31 22:35:55599#else
[email protected]51105382014-03-14 17:02:15600 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52601 str_newline.data(), str_newline.size(), 1, g_log_file));
602 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55603#endif
initial.commitd7cae122008-07-26 21:49:38604 }
605 }
606
607 if (severity_ == LOG_FATAL) {
[email protected]eb4c4d032012-04-03 18:45:05608 // Ensure the first characters of the string are on the stack so they
609 // are contained in minidumps for diagnostic purposes.
610 char str_stack[1024];
611 str_newline.copy(str_stack, arraysize(str_stack));
612 base::debug::Alias(str_stack);
613
[email protected]82d89ab2014-02-28 18:25:34614 if (log_assert_handler) {
615 // Make a copy of the string for the handler out of paranoia.
616 log_assert_handler(std::string(stream_.str()));
[email protected]1ffe08c12008-08-13 11:15:11617 } else {
[email protected]82d89ab2014-02-28 18:25:34618 // Don't use the string with the newline, get a fresh version to send to
619 // the debug message process. We also don't display assertions to the
620 // user in release mode. The enduser can't do anything with this
621 // information, and displaying message boxes when the application is
622 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50623#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42624 if (!base::debug::BeingDebugged()) {
625 // Displaying a dialog is unnecessary when debugging and can complicate
626 // debugging.
627 DisplayDebugMessageInDialog(stream_.str());
628 }
[email protected]4d5901272008-11-06 00:33:50629#endif
[email protected]82d89ab2014-02-28 18:25:34630 // Crash the process to generate a dump.
631 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38632 }
633 }
634}
635
[email protected]eae9c062011-01-11 00:50:59636// writes the common header info to the stream
637void LogMessage::Init(const char* file, int line) {
638 base::StringPiece filename(file);
639 size_t last_slash_pos = filename.find_last_of("\\/");
640 if (last_slash_pos != base::StringPiece::npos)
641 filename.remove_prefix(last_slash_pos + 1);
642
643 // TODO(darin): It might be nice if the columns were fixed width.
644
645 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52646 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59647 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52648 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09649 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52650 if (g_log_timestamp) {
651 time_t t = time(nullptr);
[email protected]eae9c062011-01-11 00:50:59652 struct tm local_time = {0};
mostynb7e42a8f2014-12-19 12:47:46653#ifdef _MSC_VER
[email protected]eae9c062011-01-11 00:50:59654 localtime_s(&local_time, &t);
655#else
656 localtime_r(&t, &local_time);
657#endif
658 struct tm* tm_time = &local_time;
659 stream_ << std::setfill('0')
660 << std::setw(2) << 1 + tm_time->tm_mon
661 << std::setw(2) << tm_time->tm_mday
662 << '/'
663 << std::setw(2) << tm_time->tm_hour
664 << std::setw(2) << tm_time->tm_min
665 << std::setw(2) << tm_time->tm_sec
666 << ':';
667 }
thestig3e4787d2015-05-19 19:31:52668 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59669 stream_ << TickCount() << ':';
670 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19671 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59672 else
673 stream_ << "VERBOSE" << -severity_;
674
675 stream_ << ":" << filename << "(" << line << ")] ";
676
pkasting9cf9b942014-10-01 22:18:43677 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59678}
679
[email protected]d8617a62009-10-09 23:52:20680#if defined(OS_WIN)
681// This has already been defined in the header, but defining it again as DWORD
682// ensures that the type used in the header is equivalent to DWORD. If not,
683// the redefinition is a compile error.
684typedef DWORD SystemErrorCode;
685#endif
686
687SystemErrorCode GetLastSystemErrorCode() {
688#if defined(OS_WIN)
689 return ::GetLastError();
690#elif defined(OS_POSIX)
691 return errno;
692#else
693#error Not implemented
694#endif
695}
696
697#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01698BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27699 const int kErrorMessageBufferSize = 256;
700 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01701 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52702 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
703 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01704 if (len) {
705 // Messages returned by system end with line breaks.
706 return base::CollapseWhitespaceASCII(msgbuf, true) +
707 base::StringPrintf(" (0x%X)", error_code);
708 }
709 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
710 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20711}
[email protected]c914d8a2014-04-23 01:11:01712#elif defined(OS_POSIX)
713BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
brettw6ee6fd62015-06-09 18:05:24714 return base::safe_strerror(error_code);
[email protected]c914d8a2014-04-23 01:11:01715}
716#else
717#error Not implemented
thestig3e4787d2015-05-19 19:31:52718#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20719
[email protected]c914d8a2014-04-23 01:11:01720
721#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20722Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
723 int line,
724 LogSeverity severity,
725 SystemErrorCode err)
726 : err_(err),
[email protected]d8617a62009-10-09 23:52:20727 log_message_(file, line, severity) {
728}
729
730Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01731 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06732 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
733 // field) and use Alias in hopes that it makes it into crash dumps.
734 DWORD last_error = err_;
735 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20736}
737#elif defined(OS_POSIX)
738ErrnoLogMessage::ErrnoLogMessage(const char* file,
739 int line,
740 LogSeverity severity,
741 SystemErrorCode err)
742 : err_(err),
743 log_message_(file, line, severity) {
744}
745
746ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01747 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20748}
thestig3e4787d2015-05-19 19:31:52749#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20750
initial.commitd7cae122008-07-26 21:49:38751void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09752#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55753 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09754#endif
[email protected]17dcf752013-07-15 21:47:09755 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38756}
757
[email protected]e36ddc82009-12-08 04:22:50758void RawLog(int level, const char* message) {
thestig3e4787d2015-05-19 19:31:52759 if (level >= g_min_log_level) {
[email protected]e36ddc82009-12-08 04:22:50760 size_t bytes_written = 0;
761 const size_t message_len = strlen(message);
762 int rv;
763 while (bytes_written < message_len) {
764 rv = HANDLE_EINTR(
765 write(STDERR_FILENO, message + bytes_written,
766 message_len - bytes_written));
767 if (rv < 0) {
768 // Give up, nothing we can do now.
769 break;
770 }
771 bytes_written += rv;
772 }
773
774 if (message_len > 0 && message[message_len - 1] != '\n') {
775 do {
776 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
777 if (rv < 0) {
778 // Give up, nothing we can do now.
779 break;
780 }
781 } while (rv != 1);
782 }
783 }
784
785 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50786 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50787}
788
[email protected]34a907732012-01-20 06:33:27789// This was defined at the beginning of this file.
790#undef write
791
[email protected]f01b88a2013-02-27 22:04:00792#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09793bool IsLoggingToFileEnabled() {
794 return g_logging_destination & LOG_TO_FILE;
795}
796
[email protected]f01b88a2013-02-27 22:04:00797std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52798 if (g_log_file_name)
799 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00800 return std::wstring();
801}
802#endif
803
tnagel80388e682015-05-26 13:27:56804BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14805 LogMessage(file, line, LOG_ERROR).stream()
806 << "NOTREACHED() hit.";
807}
808
[email protected]96fd0032009-04-24 00:13:08809} // namespace logging
initial.commitd7cae122008-07-26 21:49:38810
[email protected]81411c62014-07-08 23:03:06811std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
thestig75f87352014-12-03 21:42:27812 return out << base::WideToUTF8(wstr);
initial.commitd7cae122008-07-26 21:49:38813}